tobogganSe connecter

louise

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

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