tobogganSe connecter

louise

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

822 lignes · 31392 octetsBrut · Historique
1//! The analysis database: the one place where source texts, packages and
2//! the checking pipeline meet. Both `louise check` and the language server
3//! use it, so they always report the same diagnostics.
4//!
5//! v0 granularity (docs/adr/0006-incremental-model.md): parses are cached
6//! per file and re-done only when that file changes; resolution and type
7//! checking re-run over the whole package, and over the std modules it
8//! reaches (docs/adr/0074-std-closure.md). That is well within budget at
9//! v0 scale; finer caching keyed by stable item ids can replace the
10//! internals of [`Db::analyze`] without changing its callers.
11//!
12//! A package's files are parsed on a few threads at once, and std's once
13//! per process, shared by every `Db` (issue #122).
14
15mod comptime;
16mod fip;
17pub mod ide;
18mod reach;
19
20pub use comptime::{
21 ComptimeDiagnosticsError, comptime_diagnostics, comptime_diagnostics_with, evaluate_comptime,
22 semantic_diagnostics, semantic_diagnostics_with,
23};
24pub use fip::{FIP_ERROR, fip_diagnostics, fip_diagnostics_of};
25
26use std::collections::BTreeSet;
27use std::path::{Path, PathBuf};
28use std::time::{Duration, Instant};
29
30use louise_diag::Diagnostic;
31use louise_hir::{Hir, SourceModule};
32use louise_package::{self as package, MANIFEST, manifest};
33use louise_span::{FileId, SourceDb, SourceFile, Span, TextRange, TextSize};
34use louise_syntax::Parse;
35use louise_types::TypeckOutput;
36
37use louise_span::timings::Timings;
38
39/// The standard library, compiled into the toolchain.
40pub const STD: &[(&str, &str)] = &[
41 ("std/prelude", include_str!("../../../std/prelude.lse")),
42 ("std/io", include_str!("../../../std/io.lse")),
43 ("std/ref", include_str!("../../../std/ref.lse")),
44 ("std/list", include_str!("../../../std/list.lse")),
45 ("std/iter", include_str!("../../../std/iter.lse")),
46 ("std/option", include_str!("../../../std/option.lse")),
47 ("std/result", include_str!("../../../std/result.lse")),
48 ("std/string", include_str!("../../../std/string.lse")),
49 ("std/bytes", include_str!("../../../std/bytes.lse")),
50 ("std/array", include_str!("../../../std/array.lse")),
51 ("std/html", include_str!("../../../std/html.lse")),
52 ("std/template", include_str!("../../../std/template.lse")),
53 ("std/process", include_str!("../../../std/process.lse")),
54 ("std/actor", include_str!("../../../std/actor.lse")),
55 (
56 "std/supervisor",
57 include_str!("../../../std/supervisor.lse"),
58 ),
59 ("std/test", include_str!("../../../std/test.lse")),
60 ("std/random", include_str!("../../../std/random.lse")),
61 ("std/ffi", include_str!("../../../std/ffi.lse")),
62 ("std/dict", include_str!("../../../std/dict.lse")),
63 ("std/net", include_str!("../../../std/net.lse")),
64 ("std/http", include_str!("../../../std/http.lse")),
65 (
66 "std/http/cookie",
67 include_str!("../../../std/http/cookie.lse"),
68 ),
69 ("std/http/sse", include_str!("../../../std/http/sse.lse")),
70 (
71 "std/collection",
72 include_str!("../../../std/collection.lse"),
73 ),
74 ("std/os", include_str!("../../../std/os.lse")),
75 ("std/file", include_str!("../../../std/file.lse")),
76 ("std/crypto", include_str!("../../../std/crypto.lse")),
77 ("std/base64", include_str!("../../../std/base64.lse")),
78 ("std/int", include_str!("../../../std/int.lse")),
79 ("std/msgpack", include_str!("../../../std/msgpack.lse")),
80 ("std/float", include_str!("../../../std/float.lse")),
81 ("std/u64", include_str!("../../../std/u64.lse")),
82 ("std/dec", include_str!("../../../std/dec.lse")),
83 ("std/table", include_str!("../../../std/table.lse")),
84 ("std/prng", include_str!("../../../std/prng.lse")),
85 ("std/time", include_str!("../../../std/time.lse")),
86 ("std/tls", include_str!("../../../std/tls.lse")),
87 ("std/runtime", include_str!("../../../std/runtime.lse")),
88 ("std/wire", include_str!("../../../std/wire.lse")),
89 ("std/dist", include_str!("../../../std/dist.lse")),
90 (
91 "std/dist/remote",
92 include_str!("../../../std/dist/remote.lse"),
93 ),
94];
95
96/// The code of a package that cannot be loaded: an invalid manifest, or
97/// dependencies that cannot be resolved (see [`Db::load_package`]).
98pub const PACKAGE_ERROR: &str = "E0801";
99
100/// The module whose public items are visible everywhere.
101pub const PRELUDE: &str = "std/prelude";
102
103struct Module {
104 path: String,
105 file: FileId,
106 parse: Parse,
107}
108
109/// The immutable build settings and source ownership of one root package
110/// resolution. Dependency sources belong to it too: their `[cluster]` is not
111/// used, so `std/wire.cluster_policy` has the root's value for their code.
112/// Source identity is the stored file, not a spelling of its path: another
113/// resolution can reach an already-loaded dependency through `..` or a link.
114/// A new editor source joins only by its stored [`FileId`] after its package
115/// root has been identified; a source with no loaded root stays standalone.
116struct PackageSettings {
117 root: PathBuf,
118 sources: BTreeSet<FileId>,
119 lower: louise_core::lower::Settings,
120}
121
122pub struct Db {
123 sources: SourceDb,
124 modules: Vec<Module>,
125 /// Dependencies already loaded (by name).
126 loaded_deps: Vec<String>,
127 /// Root-package settings retained for source-only whole-program checks.
128 packages: Vec<PackageSettings>,
129 /// Why packages could not be loaded ([`Db::load_package`]).
130 load_errors: Vec<Diagnostic>,
131 /// Time spent parsing, for `--timings`.
132 parse_time: Duration,
133 /// Whether `@test` functions and `@test import`s are analysed (ADR
134 /// 0064). On by default; a program build turns it off with
135 /// [`Db::without_tests`].
136 tests: bool,
137 /// Whether every std module is analysed, reached or not (ADR 0074):
138 /// [`Db::with_all_std`].
139 all_std: bool,
140}
141
142/// The result of checking everything in a [`Db`].
143pub struct Analysis {
144 pub hir: Hir,
145 pub typeck: TypeckOutput,
146 /// All diagnostics, sorted by file and position.
147 pub diagnostics: Vec<Diagnostic>,
148}
149
150impl Default for Db {
151 fn default() -> Self {
152 Self::new()
153 }
154}
155
156impl Db {
157 /// A database containing the standard library.
158 pub fn new() -> Db {
159 let mut db = Db {
160 sources: SourceDb::default(),
161 modules: Vec::new(),
162 loaded_deps: Vec::new(),
163 packages: Vec::new(),
164 load_errors: Vec::new(),
165 parse_time: Duration::ZERO,
166 tests: true,
167 all_std: false,
168 };
169 let start = Instant::now();
170 let parses = std_parses();
171 db.parse_time += start.elapsed();
172 for ((path, text), parse) in STD.iter().zip(parses) {
173 db.add_parsed(
174 path,
175 &format!("<{path}.lse>"),
176 (*text).to_owned(),
177 parse.clone(),
178 );
179 }
180 db
181 }
182
183 /// A database that analyses all of std, not only what its modules
184 /// reach (ADR 0074): what checks std itself.
185 pub fn with_all_std() -> Db {
186 Db {
187 all_std: true,
188 ..Db::new()
189 }
190 }
191
192 pub fn sources(&self) -> &SourceDb {
193 &self.sources
194 }
195
196 /// `file` belongs to a dependency or to std, not to the root
197 /// package: the CLI prints only the root's warnings unless
198 /// `--deps-warnings` asks for the rest (issue #301). A file no
199 /// module owns (a manifest, say) is the root's.
200 pub fn file_is_dependency(&self, file: FileId) -> bool {
201 let Some(m) = self.modules.iter().find(|m| m.file == file) else {
202 return false;
203 };
204 let (first, _) = m.path.split_once('/').unwrap_or((&m.path, ""));
205 first == "std"
206 || self
207 .loaded_deps
208 .iter()
209 .any(|d| m.path == *d || m.path.starts_with(&format!("{d}/")))
210 }
211
212 /// Add a module; `display_path` is what diagnostics show (and, for the
213 /// language server, the file's path on disk).
214 pub fn add_module(&mut self, module_path: &str, display_path: &str, text: String) -> FileId {
215 let start = Instant::now();
216 let parse = louise_syntax::parse(&text);
217 self.parse_time += start.elapsed();
218 self.add_parsed(module_path, display_path, text, parse)
219 }
220
221 /// Add an editor module to the loaded resolution rooted at `root`.
222 ///
223 /// `root` is the package root identified by the caller (the language
224 /// server's [`louise_package::Target`]), never inferred from the source's
225 /// display path. The new source keeps its default settings if that root
226 /// has no recorded package. Only root directories are canonicalized: an
227 /// unsaved source need not exist on disk.
228 pub fn add_module_in_package(
229 &mut self,
230 module_path: &str,
231 display_path: &str,
232 text: String,
233 root: &Path,
234 ) -> FileId {
235 let file = self.add_module(module_path, display_path, text);
236 if let Some(package) = self.packages.iter_mut().find(|package| {
237 package.root == root
238 || root.canonicalize().is_ok_and(|root| {
239 package
240 .root
241 .canonicalize()
242 .is_ok_and(|package| package == root)
243 })
244 }) {
245 package.sources.insert(file);
246 }
247 file
248 }
249
250 /// [`Db::add_module`] for a text already parsed.
251 fn add_parsed(
252 &mut self,
253 module_path: &str,
254 display_path: &str,
255 text: String,
256 parse: Parse,
257 ) -> FileId {
258 let file = self.sources.add(SourceFile::new(display_path, text));
259 self.modules.push(Module {
260 path: module_path.to_owned(),
261 file,
262 parse,
263 });
264 file
265 }
266
267 /// Replace a module's text (an editor change) and re-parse it.
268 pub fn set_text(&mut self, file: FileId, text: String) {
269 if let Some(m) = self.modules.iter_mut().find(|m| m.file == file) {
270 m.parse = louise_syntax::parse(&text);
271 self.sources.set_text(file, text);
272 }
273 }
274
275 /// Paths of the modules added outside the standard library.
276 pub fn user_modules(&self) -> Vec<String> {
277 self.modules
278 .iter()
279 .filter(|m| !m.path.starts_with("std/"))
280 .map(|m| m.path.clone())
281 .collect()
282 }
283
284 pub fn file_by_display_path(&self, path: &str) -> Option<FileId> {
285 self.modules
286 .iter()
287 .find(|m| self.sources.get(m.file).path() == path)
288 .map(|m| m.file)
289 }
290
291 /// The stored file loaded from `file` on disk, if one was. Canonical
292 /// paths make an already-loaded dependency reachable under another
293 /// spelling still owned through its first stored identity.
294 fn file_id_of_path(&self, file: &Path) -> Option<FileId> {
295 let file = file.canonicalize().ok()?;
296 self.modules
297 .iter()
298 .find(|m| {
299 Path::new(self.sources.get(m.file).path())
300 .canonicalize()
301 .ok()
302 == Some(file.clone())
303 })
304 .map(|m| m.file)
305 }
306
307 /// The path of the module loaded from `file` on disk, if one was. Paths
308 /// are compared once canonicalized, since modules are loaded under the
309 /// path they are shown with.
310 pub fn module_of_file(&self, file: &Path) -> Option<String> {
311 let file = self.file_id_of_path(file)?;
312 self.modules
313 .iter()
314 .find(|m| m.file == file)
315 .map(|m| m.path.clone())
316 }
317
318 pub fn parse(&self, file: FileId) -> Option<&Parse> {
319 self.modules
320 .iter()
321 .find(|m| m.file == file)
322 .map(|m| &m.parse)
323 }
324
325 /// Time spent parsing the modules added so far.
326 pub fn parse_time(&self) -> Duration {
327 self.parse_time
328 }
329
330 /// Check every module outside std, and the std modules they reach
331 /// (ADR 0074; all of them with [`Db::with_all_std`]). What is
332 /// reached is found anew each time, since an edit can add an import.
333 pub fn analyze(&self) -> Analysis {
334 self.analyze_timed(&mut Timings::default())
335 }
336
337 /// Leave out every `@test` function and `@test import` (ADR 0064):
338 /// what a program build compiles, where tests are not entries and
339 /// what only they use need not resolve.
340 pub fn without_tests(&mut self) {
341 self.tests = false;
342 }
343
344 /// [`Db::analyze`], recording the time of name resolution (with
345 /// finding the std modules reached, and lowering to HIR) and of type
346 /// checking.
347 pub fn analyze_timed(&self, timings: &mut Timings) -> Analysis {
348 let mut diagnostics: Vec<Diagnostic> = self
349 .modules
350 .iter()
351 .flat_map(|m| m.parse.diagnostics(m.file))
352 .collect();
353 let (hir, lower_diags) = timings.time("resolve", || {
354 let reached = if self.all_std {
355 vec![true; self.modules.len()]
356 } else {
357 reach::reached(&self.modules, self.tests)
358 };
359 let sources: Vec<SourceModule> = (self.modules.iter().zip(reached))
360 .filter(|(_, reached)| *reached)
361 .map(|(m, _)| SourceModule {
362 path: m.path.clone(),
363 file: m.file,
364 parse: &m.parse,
365 })
366 .collect();
367 louise_hir::lower_package_for(&sources, Some(PRELUDE), self.tests)
368 });
369 diagnostics.extend(lower_diags);
370 let typeck = timings.time("typecheck", || louise_types::check(&hir));
371 diagnostics.extend(typeck.diagnostics.iter().cloned());
372 diagnostics.extend(self.load_errors.iter().cloned());
373 diagnostics.sort_by_key(|d| (d.primary.span.file, d.primary.span.range.start()));
374 Analysis {
375 hir,
376 typeck,
377 diagnostics,
378 }
379 }
380
381 /// Load the package rooted at `root`, its tests and its dependencies,
382 /// from what is on disk: the lockfile and the git cache, without
383 /// fetching. This is the language server's view; the CLI resolves
384 /// first, with its own options, then calls [`Db::load_resolved`].
385 ///
386 /// What goes wrong is reported, not returned: a diagnostic
387 /// ([`PACKAGE_ERROR`]) in the manifest at fault, which [`Db::analyze`]
388 /// returns with the others. If the package cannot be resolved, its own
389 /// modules and tests are still loaded, so only the imports of its
390 /// dependencies fail.
391 pub fn load_package(&mut self, root: &Path) {
392 let loaded = match package::resolve(
393 root,
394 &package::Options::cached(),
395 package::Version::current(),
396 ) {
397 Ok(resolution) => self.load_resolved(&resolution).map(drop),
398 Err(e) => {
399 self.report_load_error(root, &e);
400 match manifest::load(root) {
401 Ok(m) => {
402 let loaded = self.load_root(&m.root, &m.name);
403 if let Ok(ids) = &loaded {
404 self.record_package(&m, ids.iter().copied().collect());
405 }
406 loaded.map(drop)
407 }
408 Err(_) => self.load_dir(&root.join("src"), None).map(drop),
409 }
410 }
411 };
412 if let Err(e) = loaded.and_then(|()| self.load_tests(root).map(drop)) {
413 let message = format!("cannot load package {}: {e}", root.display());
414 self.report_load_error(root, &package::Error::Other(message));
415 }
416 }
417
418 /// A diagnostic for `error`, in the manifest it is about: the faulty one
419 /// for an invalid manifest, else the root's (at its start).
420 fn report_load_error(&mut self, root: &Path, error: &package::Error) {
421 let (file, span, message) = match error {
422 package::Error::Manifest(e) => (e.file.clone(), e.span.clone(), e.message.clone()),
423 package::Error::Other(message) => (root.join(MANIFEST), None, message.clone()),
424 };
425 let text = std::fs::read_to_string(&file).unwrap_or_default();
426 let span = span.unwrap_or(0..0);
427 let range = TextRange::new(
428 TextSize::new(span.start.min(text.len()) as u32),
429 TextSize::new(span.end.min(text.len()) as u32),
430 );
431 let file = self
432 .sources
433 .add(SourceFile::new(file.display().to_string(), text));
434 self.load_errors.push(Diagnostic::error(
435 PACKAGE_ERROR,
436 message,
437 Span { file, range },
438 ));
439 }
440
441 /// Retain a root package's immutable lowering inputs and the stored
442 /// source files its resolution compiles. A later load of the same root
443 /// replaces the settings rather than appending another owner.
444 fn record_package(&mut self, root: &manifest::Manifest, sources: BTreeSet<FileId>) {
445 let settings = louise_core::lower::Settings {
446 cluster_policy: root
447 .cluster
448 .as_ref()
449 .map_or_else(String::new, manifest::cluster_policy),
450 };
451 if let Some(package) = self
452 .packages
453 .iter_mut()
454 .find(|package| package.root == root.root)
455 {
456 package.sources = sources;
457 package.lower = settings;
458 } else {
459 self.packages.push(PackageSettings {
460 root: root.root.clone(),
461 sources,
462 lower: settings,
463 });
464 }
465 }
466
467 /// Load a resolved package and its dependencies: every `.lse` file
468 /// under each package's `src/`, named by its path relative to `src/`
469 /// (`src/app/main.lse` is `app/main`), and prefixed with the name of
470 /// a dependency.
471 pub fn load_resolved(
472 &mut self,
473 resolution: &package::Resolution,
474 ) -> std::io::Result<Vec<FileId>> {
475 let root = resolution.root();
476 let mut ids = self.load_root(&root.manifest.root, &root.name)?;
477 let mut sources: BTreeSet<FileId> = ids.iter().copied().collect();
478 for dep in &resolution.packages[1..] {
479 let src = dep.manifest.root.join("src");
480 if self.loaded_deps.contains(&dep.name) {
481 // The later resolution still owns this dependency. Find the
482 // first stored FileIds by physical file identity; its lexical
483 // path need not have anything in common with this spelling.
484 sources.extend(self.stored_source_ids(&src)?);
485 continue;
486 }
487 self.loaded_deps.push(dep.name.clone());
488 let loaded = self.load_dir(&src, Some(&dep.name))?;
489 sources.extend(loaded.iter().copied());
490 ids.extend(loaded);
491 }
492 self.record_package(&root.manifest, sources);
493 Ok(ids)
494 }
495
496 /// A package's own modules. Its `src/lib.lse` is named after the
497 /// package, for its own tests as for its dependents (see `manifest`).
498 fn load_root(&mut self, root: &Path, name: &str) -> std::io::Result<Vec<FileId>> {
499 let ids = self.load_dir(&root.join("src"), None)?;
500 if let Some(m) = self.modules.iter_mut().find(|m| m.path == "lib") {
501 m.path = name.to_owned();
502 }
503 Ok(ids)
504 }
505
506 /// Identify the files of an already-loaded source directory without
507 /// reading their text or adding replacement modules.
508 fn stored_source_ids(&self, src: &Path) -> std::io::Result<BTreeSet<FileId>> {
509 let mut files = Vec::new();
510 collect_til_files(src, &mut files)?;
511 Ok(files
512 .iter()
513 .filter_map(|path| self.file_id_of_path(path))
514 .collect())
515 }
516
517 /// Load a package's tests: `.lse` files under `test/`, named relative
518 /// to it. Returns their module paths. Tests loaded after the source
519 /// packet join that root's resolution, rather than becoming standalone.
520 pub fn load_tests(&mut self, root: &Path) -> std::io::Result<Vec<String>> {
521 let ids = self.load_dir(&root.join("test"), None)?;
522 if let Some(package) = self
523 .packages
524 .iter_mut()
525 .find(|package| package.root == root)
526 {
527 package.sources.extend(ids.iter().copied());
528 }
529 Ok(ids
530 .iter()
531 .filter_map(|id| {
532 self.modules
533 .iter()
534 .find(|m| m.file == *id)
535 .map(|m| m.path.clone())
536 })
537 .collect())
538 }
539
540 /// Load the `.lse` files under `src`; with `prefix`, as a dependency's
541 /// modules (`lib` is the prefix itself).
542 fn load_dir(&mut self, src: &Path, prefix: Option<&str>) -> std::io::Result<Vec<FileId>> {
543 let mut files = Vec::new();
544 collect_til_files(src, &mut files)?;
545 files.sort();
546 let texts = files
547 .iter()
548 .map(std::fs::read_to_string)
549 .collect::<std::io::Result<Vec<_>>>()?;
550 let start = Instant::now();
551 let parses = parse_all(&texts.iter().map(String::as_str).collect::<Vec<_>>());
552 self.parse_time += start.elapsed();
553 let mut ids = Vec::new();
554 for ((path, text), parse) in files.iter().zip(texts).zip(parses) {
555 let module = match (prefix, module_path(src, path)) {
556 (Some(p), m) if m == "lib" => p.to_owned(),
557 (Some(p), m) => format!("{p}/{m}"),
558 (None, m) => m,
559 };
560 ids.push(self.add_parsed(&module, &path.display().to_string(), text, parse));
561 }
562 Ok(ids)
563 }
564}
565
566/// The standard library's modules, parsed once per process: every [`Db`]
567/// clones them, which only copies reference counts (a syntax tree is
568/// shared and immutable). Tests and the language server make many.
569fn std_parses() -> &'static [Parse] {
570 static PARSES: std::sync::OnceLock<Vec<Parse>> = std::sync::OnceLock::new();
571 PARSES.get_or_init(|| parse_all(&STD.iter().map(|(_, text)| *text).collect::<Vec<_>>()))
572}
573
574/// Parse `texts`, a few at a time (issue #122); the results are in the
575/// same order. Modules are parsed independently: imports are resolved
576/// afterwards, on all of them. The largest texts go first, so that the
577/// prelude (a third of std) does not finish last; more than [`PARSERS`]
578/// threads cost more CPU to start than they saved.
579fn parse_all(texts: &[&str]) -> Vec<Parse> {
580 let threads = std::thread::available_parallelism()
581 .map_or(1, |n| n.get())
582 .min(PARSERS)
583 .min(texts.len());
584 if threads <= 1 {
585 return texts.iter().map(|t| louise_syntax::parse(t)).collect();
586 }
587 let mut order: Vec<usize> = (0..texts.len()).collect();
588 order.sort_by_key(|i| std::cmp::Reverse(texts[*i].len()));
589 let next = std::sync::atomic::AtomicUsize::new(0);
590 let mut parsed: Vec<(usize, Parse)> = std::thread::scope(|scope| {
591 let workers: Vec<_> = (0..threads)
592 .map(|_| {
593 std::thread::Builder::new()
594 // The parser recurses up to its depth limit.
595 .stack_size(8 << 20)
596 .spawn_scoped(scope, || {
597 let mut done = Vec::new();
598 loop {
599 let k = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
600 let Some(&i) = order.get(k) else { break done };
601 done.push((i, louise_syntax::parse(texts[i])));
602 }
603 })
604 .expect("louise: cannot start a parser thread")
605 })
606 .collect();
607 workers
608 .into_iter()
609 .flat_map(|w| w.join().unwrap_or_else(|p| std::panic::resume_unwind(p)))
610 .collect()
611 });
612 parsed.sort_by_key(|(i, _)| *i);
613 parsed.into_iter().map(|(_, parse)| parse).collect()
614}
615
616/// The most threads [`parse_all`] starts.
617const PARSERS: usize = 3;
618
619fn collect_til_files(dir: &Path, out: &mut Vec<PathBuf>) -> std::io::Result<()> {
620 if !dir.is_dir() {
621 return Ok(());
622 }
623 for entry in std::fs::read_dir(dir)? {
624 let path = entry?.path();
625 if path.is_dir() {
626 collect_til_files(&path, out)?;
627 } else if path.extension().is_some_and(|e| e == "lse") {
628 out.push(path);
629 }
630 }
631 Ok(())
632}
633
634/// `src/app/main.lse` relative to `src` is module `app/main`.
635pub fn module_path(src: &Path, file: &Path) -> String {
636 let rel = file.strip_prefix(src).unwrap_or(file).with_extension("");
637 rel.components()
638 .map(|c| c.as_os_str().to_string_lossy().into_owned())
639 .collect::<Vec<_>>()
640 .join("/")
641}
642
643#[cfg(test)]
644mod tests {
645 use super::*;
646
647 #[test]
648 fn std_checks_cleanly() {
649 let analysis = Db::with_all_std().analyze();
650 assert_eq!(analysis.hir.modules.len(), STD.len());
651 assert!(
652 analysis.diagnostics.is_empty(),
653 "{:#?}",
654 analysis.diagnostics
655 );
656 }
657
658 /// The std modules analysed with `db`'s.
659 fn std_reached(db: &Db) -> Vec<String> {
660 let analysis = db.analyze();
661 (analysis.hir.modules.iter())
662 .map(|(_, m)| m.path.clone())
663 .filter(|p| p.starts_with("std/"))
664 .collect()
665 }
666
667 /// The std modules analysed with a module `main` of `text`.
668 fn std_reached_by(text: &str) -> Vec<String> {
669 let mut db = Db::new();
670 db.add_module("main", "main.lse", text.into());
671 std_reached(&db)
672 }
673
674 #[test]
675 fn only_the_std_modules_a_program_reaches_are_analysed() {
676 let reached = std_reached_by(
677 "import std/io\npub fn main :: -> () / <io> {\n io.println \"hi\"\n}\n",
678 );
679 // The prelude always; what `std/io` imports, transitively.
680 for m in ["std/prelude", "std/io", "std/ffi"] {
681 assert!(reached.iter().any(|r| r == m), "{m}: {reached:?}");
682 }
683 for m in ["std/dist", "std/wire", "std/html", "std/http"] {
684 assert!(!reached.iter().any(|r| r == m), "{m}: {reached:?}");
685 }
686 // Everything std imports is in, so what is reached checks.
687 let dist = std_reached_by("import std/dist\n");
688 for m in ["std/dist", "std/wire", "std/dist/remote", "std/net"] {
689 assert!(dist.iter().any(|r| r == m), "{m}: {dist:?}");
690 }
691 }
692
693 #[test]
694 fn syntax_that_names_a_std_module_reaches_it() {
695 for (body, module) in [
696 ("let _ = <p>hi</p>\n ()", "std/html"),
697 ("let _ = tag`hi`\n ()", "std/template"),
698 ("region\n {\n ()\n }", "std/ref"),
699 ] {
700 let text = format!("pub fn f :: -> ()\n{{\n {body}\n}}\n");
701 assert!(
702 std_reached_by(&text).iter().any(|r| r == module),
703 "{module} for {text}"
704 );
705 assert!(
706 !std_reached_by("pub fn f :: -> () {\n ()\n}\n")
707 .iter()
708 .any(|r| r == module),
709 "{module} without the syntax"
710 );
711 }
712 let remote = std_reached_by("@remote\nfn worker :: n: Int -> () {\n ()\n}\n");
713 assert!(remote.iter().any(|r| r == "std/dist/remote"), "{remote:?}");
714 }
715
716 #[test]
717 fn an_edit_that_adds_an_import_reaches_its_module() {
718 let mut db = Db::new();
719 let file = db.add_module("main", "main.lse", "pub fn f :: -> () {\n ()\n}\n".into());
720 assert!(!std_reached(&db).iter().any(|r| r == "std/dict"));
721 db.set_text(
722 file,
723 "import std/dict\npub fn f :: -> Int {\n dict.size (dict.empty ())\n}\n".into(),
724 );
725 assert!(std_reached(&db).iter().any(|r| r == "std/dict"));
726 assert!(db.analyze().diagnostics.is_empty());
727 }
728
729 #[test]
730 fn a_test_import_reaches_its_module_only_with_tests() {
731 let text = "@test import std/dict\npub fn f :: -> () {\n ()\n}\n";
732 let mut db = Db::new();
733 db.add_module("main", "main.lse", text.into());
734 assert!(std_reached(&db).iter().any(|r| r == "std/dict"));
735 db.without_tests();
736 assert!(!std_reached(&db).iter().any(|r| r == "std/dict"));
737 }
738
739 #[test]
740 fn a_missing_std_module_is_still_unresolved() {
741 let mut db = Db::new();
742 db.add_module("main", "main.lse", "import std/nope\n".into());
743 let codes: Vec<&str> = (db.analyze().diagnostics.iter()).map(|d| d.code).collect();
744 assert_eq!(codes, ["E0103"]);
745 }
746
747 #[test]
748 fn parallel_parses_come_back_in_order() {
749 let texts: Vec<String> = (0..40)
750 .map(|i| format!("pub fn f{i}() -> Int {{ {} }}", "1 + ".repeat(i % 7) + "1"))
751 .collect();
752 let refs: Vec<&str> = texts.iter().map(String::as_str).collect();
753 let parallel = parse_all(&refs);
754 assert_eq!(parallel.len(), texts.len());
755 for (text, parse) in texts.iter().zip(&parallel) {
756 assert_eq!(
757 parse.syntax().to_string(),
758 *text,
759 "a parse is in another's place"
760 );
761 }
762 }
763
764 #[test]
765 fn a_package_loads_the_same_way_twice() {
766 let dir = std::env::temp_dir().join(format!("louise-db-order-{}", std::process::id()));
767 let src = dir.join("src");
768 std::fs::create_dir_all(src.join("app")).unwrap();
769 for (file, text) in [
770 (
771 "main.lse",
772 "import app/b\npub fn main :: -> Int {\n b.two ()\n}\n",
773 ),
774 ("app/a.lse", "pub fn one :: -> Int {\n 1\n}\n"),
775 (
776 "app/b.lse",
777 "import app/a\npub fn two :: -> Int {\n a.one () + true\n}\n",
778 ),
779 ] {
780 std::fs::write(src.join(file), text).unwrap();
781 }
782 let load = || {
783 let mut db = Db::new();
784 db.load_dir(&src, None).unwrap();
785 let messages: Vec<String> = db
786 .analyze()
787 .diagnostics
788 .iter()
789 .map(|d| d.message.clone())
790 .collect();
791 (db.user_modules(), messages)
792 };
793 let (modules, diagnostics) = load();
794 assert_eq!(modules, ["app/a", "app/b", "main"]);
795 assert!(!diagnostics.is_empty(), "the type error in app/b");
796 assert_eq!(load(), (modules, diagnostics));
797 let _ = std::fs::remove_dir_all(&dir);
798 }
799
800 #[test]
801 fn edits_are_reanalyzed() {
802 let mut db = Db::new();
803 let file = db.add_module(
804 "main",
805 "main.lse",
806 "pub fn f :: -> Int {\n \"no\"\n}\n".into(),
807 );
808 assert_eq!(db.analyze().diagnostics.len(), 1);
809 db.set_text(file, "pub fn f :: -> Int {\n 1\n}\n".into());
810 assert!(db.analyze().diagnostics.is_empty());
811 }
812
813 #[test]
814 fn module_paths_are_relative_to_src() {
815 let src = Path::new("/p/src");
816 assert_eq!(
817 module_path(src, Path::new("/p/src/app/main.lse")),
818 "app/main"
819 );
820 assert_eq!(module_path(src, Path::new("/p/src/lib.lse")), "lib");
821 }
822}