tobogganSe connecter

louise

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

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