//! The analysis database: the one place where source texts, packages and //! the checking pipeline meet. Both `louise check` and the language server //! use it, so they always report the same diagnostics. //! //! v0 granularity (docs/adr/0006-incremental-model.md): parses are cached //! per file and re-done only when that file changes; resolution and type //! checking re-run over the whole package, and over the std modules it //! reaches (docs/adr/0074-std-closure.md). That is well within budget at //! v0 scale; finer caching keyed by stable item ids can replace the //! internals of [`Db::analyze`] without changing its callers. //! //! A package's files are parsed on a few threads at once, and std's once //! per process, shared by every `Db` (issue #122). mod comptime; mod fip; pub mod ide; mod reach; pub use comptime::{ ComptimeDiagnosticsError, comptime_diagnostics, comptime_diagnostics_with, evaluate_comptime, semantic_diagnostics, semantic_diagnostics_with, }; pub use fip::{FIP_ERROR, fip_diagnostics, fip_diagnostics_of}; use std::collections::BTreeSet; use std::path::{Path, PathBuf}; use std::time::{Duration, Instant}; use louise_diag::Diagnostic; use louise_hir::{Hir, SourceModule}; use louise_package::{self as package, MANIFEST, manifest}; use louise_span::{FileId, SourceDb, SourceFile, Span, TextRange, TextSize}; use louise_syntax::Parse; use louise_types::TypeckOutput; use louise_span::timings::Timings; /// The standard library, compiled into the toolchain. pub const STD: &[(&str, &str)] = &[ ("std/prelude", include_str!("../../../std/prelude.lse")), ("std/io", include_str!("../../../std/io.lse")), ("std/ref", include_str!("../../../std/ref.lse")), ("std/list", include_str!("../../../std/list.lse")), ("std/iter", include_str!("../../../std/iter.lse")), ("std/option", include_str!("../../../std/option.lse")), ("std/result", include_str!("../../../std/result.lse")), ("std/string", include_str!("../../../std/string.lse")), ("std/bytes", include_str!("../../../std/bytes.lse")), ("std/array", include_str!("../../../std/array.lse")), ("std/html", include_str!("../../../std/html.lse")), ("std/template", include_str!("../../../std/template.lse")), ("std/process", include_str!("../../../std/process.lse")), ("std/actor", include_str!("../../../std/actor.lse")), ( "std/supervisor", include_str!("../../../std/supervisor.lse"), ), ("std/test", include_str!("../../../std/test.lse")), ("std/random", include_str!("../../../std/random.lse")), ("std/ffi", include_str!("../../../std/ffi.lse")), ("std/dict", include_str!("../../../std/dict.lse")), ("std/net", include_str!("../../../std/net.lse")), ("std/http", include_str!("../../../std/http.lse")), ( "std/http/cookie", include_str!("../../../std/http/cookie.lse"), ), ("std/http/sse", include_str!("../../../std/http/sse.lse")), ( "std/collection", include_str!("../../../std/collection.lse"), ), ("std/os", include_str!("../../../std/os.lse")), ("std/file", include_str!("../../../std/file.lse")), ("std/crypto", include_str!("../../../std/crypto.lse")), ("std/base64", include_str!("../../../std/base64.lse")), ("std/int", include_str!("../../../std/int.lse")), ("std/msgpack", include_str!("../../../std/msgpack.lse")), ("std/float", include_str!("../../../std/float.lse")), ("std/u64", include_str!("../../../std/u64.lse")), ("std/dec", include_str!("../../../std/dec.lse")), ("std/table", include_str!("../../../std/table.lse")), ("std/prng", include_str!("../../../std/prng.lse")), ("std/time", include_str!("../../../std/time.lse")), ("std/tls", include_str!("../../../std/tls.lse")), ("std/runtime", include_str!("../../../std/runtime.lse")), ("std/wire", include_str!("../../../std/wire.lse")), ("std/dist", include_str!("../../../std/dist.lse")), ( "std/dist/remote", include_str!("../../../std/dist/remote.lse"), ), ]; /// The code of a package that cannot be loaded: an invalid manifest, or /// dependencies that cannot be resolved (see [`Db::load_package`]). pub const PACKAGE_ERROR: &str = "E0801"; /// The module whose public items are visible everywhere. pub const PRELUDE: &str = "std/prelude"; struct Module { path: String, file: FileId, parse: Parse, } /// The immutable build settings and source ownership of one root package /// resolution. Dependency sources belong to it too: their `[cluster]` is not /// used, so `std/wire.cluster_policy` has the root's value for their code. /// Source identity is the stored file, not a spelling of its path: another /// resolution can reach an already-loaded dependency through `..` or a link. /// A new editor source joins only by its stored [`FileId`] after its package /// root has been identified; a source with no loaded root stays standalone. struct PackageSettings { root: PathBuf, sources: BTreeSet, lower: louise_core::lower::Settings, } pub struct Db { sources: SourceDb, modules: Vec, /// Dependencies already loaded (by name). loaded_deps: Vec, /// Root-package settings retained for source-only whole-program checks. packages: Vec, /// Why packages could not be loaded ([`Db::load_package`]). load_errors: Vec, /// Time spent parsing, for `--timings`. parse_time: Duration, /// Whether `@test` functions and `@test import`s are analysed (ADR /// 0064). On by default; a program build turns it off with /// [`Db::without_tests`]. tests: bool, /// Whether every std module is analysed, reached or not (ADR 0074): /// [`Db::with_all_std`]. all_std: bool, } /// The result of checking everything in a [`Db`]. pub struct Analysis { pub hir: Hir, pub typeck: TypeckOutput, /// All diagnostics, sorted by file and position. pub diagnostics: Vec, } impl Default for Db { fn default() -> Self { Self::new() } } impl Db { /// A database containing the standard library. pub fn new() -> Db { let mut db = Db { sources: SourceDb::default(), modules: Vec::new(), loaded_deps: Vec::new(), packages: Vec::new(), load_errors: Vec::new(), parse_time: Duration::ZERO, tests: true, all_std: false, }; let start = Instant::now(); let parses = std_parses(); db.parse_time += start.elapsed(); for ((path, text), parse) in STD.iter().zip(parses) { db.add_parsed( path, &format!("<{path}.lse>"), (*text).to_owned(), parse.clone(), ); } db } /// A database that analyses all of std, not only what its modules /// reach (ADR 0074): what checks std itself. pub fn with_all_std() -> Db { Db { all_std: true, ..Db::new() } } pub fn sources(&self) -> &SourceDb { &self.sources } /// `file` belongs to a dependency or to std, not to the root /// package: the CLI prints only the root's warnings unless /// `--deps-warnings` asks for the rest (issue #301). A file no /// module owns (a manifest, say) is the root's. pub fn file_is_dependency(&self, file: FileId) -> bool { let Some(m) = self.modules.iter().find(|m| m.file == file) else { return false; }; let (first, _) = m.path.split_once('/').unwrap_or((&m.path, "")); first == "std" || self .loaded_deps .iter() .any(|d| m.path == *d || m.path.starts_with(&format!("{d}/"))) } /// Add a module; `display_path` is what diagnostics show (and, for the /// language server, the file's path on disk). pub fn add_module(&mut self, module_path: &str, display_path: &str, text: String) -> FileId { let start = Instant::now(); let parse = louise_syntax::parse(&text); self.parse_time += start.elapsed(); self.add_parsed(module_path, display_path, text, parse) } /// Add an editor module to the loaded resolution rooted at `root`. /// /// `root` is the package root identified by the caller (the language /// server's [`louise_package::Target`]), never inferred from the source's /// display path. The new source keeps its default settings if that root /// has no recorded package. Only root directories are canonicalized: an /// unsaved source need not exist on disk. pub fn add_module_in_package( &mut self, module_path: &str, display_path: &str, text: String, root: &Path, ) -> FileId { let file = self.add_module(module_path, display_path, text); if let Some(package) = self.packages.iter_mut().find(|package| { package.root == root || root.canonicalize().is_ok_and(|root| { package .root .canonicalize() .is_ok_and(|package| package == root) }) }) { package.sources.insert(file); } file } /// [`Db::add_module`] for a text already parsed. fn add_parsed( &mut self, module_path: &str, display_path: &str, text: String, parse: Parse, ) -> FileId { let file = self.sources.add(SourceFile::new(display_path, text)); self.modules.push(Module { path: module_path.to_owned(), file, parse, }); file } /// Replace a module's text (an editor change) and re-parse it. pub fn set_text(&mut self, file: FileId, text: String) { if let Some(m) = self.modules.iter_mut().find(|m| m.file == file) { m.parse = louise_syntax::parse(&text); self.sources.set_text(file, text); } } /// Paths of the modules added outside the standard library. pub fn user_modules(&self) -> Vec { self.modules .iter() .filter(|m| !m.path.starts_with("std/")) .map(|m| m.path.clone()) .collect() } pub fn file_by_display_path(&self, path: &str) -> Option { self.modules .iter() .find(|m| self.sources.get(m.file).path() == path) .map(|m| m.file) } /// The stored file loaded from `file` on disk, if one was. Canonical /// paths make an already-loaded dependency reachable under another /// spelling still owned through its first stored identity. fn file_id_of_path(&self, file: &Path) -> Option { let file = file.canonicalize().ok()?; self.modules .iter() .find(|m| { Path::new(self.sources.get(m.file).path()) .canonicalize() .ok() == Some(file.clone()) }) .map(|m| m.file) } /// The path of the module loaded from `file` on disk, if one was. Paths /// are compared once canonicalized, since modules are loaded under the /// path they are shown with. pub fn module_of_file(&self, file: &Path) -> Option { let file = self.file_id_of_path(file)?; self.modules .iter() .find(|m| m.file == file) .map(|m| m.path.clone()) } pub fn parse(&self, file: FileId) -> Option<&Parse> { self.modules .iter() .find(|m| m.file == file) .map(|m| &m.parse) } /// Time spent parsing the modules added so far. pub fn parse_time(&self) -> Duration { self.parse_time } /// Check every module outside std, and the std modules they reach /// (ADR 0074; all of them with [`Db::with_all_std`]). What is /// reached is found anew each time, since an edit can add an import. pub fn analyze(&self) -> Analysis { self.analyze_timed(&mut Timings::default()) } /// Leave out every `@test` function and `@test import` (ADR 0064): /// what a program build compiles, where tests are not entries and /// what only they use need not resolve. pub fn without_tests(&mut self) { self.tests = false; } /// [`Db::analyze`], recording the time of name resolution (with /// finding the std modules reached, and lowering to HIR) and of type /// checking. pub fn analyze_timed(&self, timings: &mut Timings) -> Analysis { let mut diagnostics: Vec = self .modules .iter() .flat_map(|m| m.parse.diagnostics(m.file)) .collect(); let (hir, lower_diags) = timings.time("resolve", || { let reached = if self.all_std { vec![true; self.modules.len()] } else { reach::reached(&self.modules, self.tests) }; let sources: Vec = (self.modules.iter().zip(reached)) .filter(|(_, reached)| *reached) .map(|(m, _)| SourceModule { path: m.path.clone(), file: m.file, parse: &m.parse, }) .collect(); louise_hir::lower_package_for(&sources, Some(PRELUDE), self.tests) }); diagnostics.extend(lower_diags); let typeck = timings.time("typecheck", || louise_types::check(&hir)); diagnostics.extend(typeck.diagnostics.iter().cloned()); diagnostics.extend(self.load_errors.iter().cloned()); diagnostics.sort_by_key(|d| (d.primary.span.file, d.primary.span.range.start())); Analysis { hir, typeck, diagnostics, } } /// Load the package rooted at `root`, its tests and its dependencies, /// from what is on disk: the lockfile and the git cache, without /// fetching. This is the language server's view; the CLI resolves /// first, with its own options, then calls [`Db::load_resolved`]. /// /// What goes wrong is reported, not returned: a diagnostic /// ([`PACKAGE_ERROR`]) in the manifest at fault, which [`Db::analyze`] /// returns with the others. If the package cannot be resolved, its own /// modules and tests are still loaded, so only the imports of its /// dependencies fail. pub fn load_package(&mut self, root: &Path) { let loaded = match package::resolve( root, &package::Options::cached(), package::Version::current(), ) { Ok(resolution) => self.load_resolved(&resolution).map(drop), Err(e) => { self.report_load_error(root, &e); match manifest::load(root) { Ok(m) => { let loaded = self.load_root(&m.root, &m.name); if let Ok(ids) = &loaded { self.record_package(&m, ids.iter().copied().collect()); } loaded.map(drop) } Err(_) => self.load_dir(&root.join("src"), None).map(drop), } } }; if let Err(e) = loaded.and_then(|()| self.load_tests(root).map(drop)) { let message = format!("cannot load package {}: {e}", root.display()); self.report_load_error(root, &package::Error::Other(message)); } } /// A diagnostic for `error`, in the manifest it is about: the faulty one /// for an invalid manifest, else the root's (at its start). fn report_load_error(&mut self, root: &Path, error: &package::Error) { let (file, span, message) = match error { package::Error::Manifest(e) => (e.file.clone(), e.span.clone(), e.message.clone()), package::Error::Other(message) => (root.join(MANIFEST), None, message.clone()), }; let text = std::fs::read_to_string(&file).unwrap_or_default(); let span = span.unwrap_or(0..0); let range = TextRange::new( TextSize::new(span.start.min(text.len()) as u32), TextSize::new(span.end.min(text.len()) as u32), ); let file = self .sources .add(SourceFile::new(file.display().to_string(), text)); self.load_errors.push(Diagnostic::error( PACKAGE_ERROR, message, Span { file, range }, )); } /// Retain a root package's immutable lowering inputs and the stored /// source files its resolution compiles. A later load of the same root /// replaces the settings rather than appending another owner. fn record_package(&mut self, root: &manifest::Manifest, sources: BTreeSet) { let settings = louise_core::lower::Settings { cluster_policy: root .cluster .as_ref() .map_or_else(String::new, manifest::cluster_policy), }; if let Some(package) = self .packages .iter_mut() .find(|package| package.root == root.root) { package.sources = sources; package.lower = settings; } else { self.packages.push(PackageSettings { root: root.root.clone(), sources, lower: settings, }); } } /// Load a resolved package and its dependencies: every `.lse` file /// under each package's `src/`, named by its path relative to `src/` /// (`src/app/main.lse` is `app/main`), and prefixed with the name of /// a dependency. pub fn load_resolved( &mut self, resolution: &package::Resolution, ) -> std::io::Result> { let root = resolution.root(); let mut ids = self.load_root(&root.manifest.root, &root.name)?; let mut sources: BTreeSet = ids.iter().copied().collect(); for dep in &resolution.packages[1..] { let src = dep.manifest.root.join("src"); if self.loaded_deps.contains(&dep.name) { // The later resolution still owns this dependency. Find the // first stored FileIds by physical file identity; its lexical // path need not have anything in common with this spelling. sources.extend(self.stored_source_ids(&src)?); continue; } self.loaded_deps.push(dep.name.clone()); let loaded = self.load_dir(&src, Some(&dep.name))?; sources.extend(loaded.iter().copied()); ids.extend(loaded); } self.record_package(&root.manifest, sources); Ok(ids) } /// A package's own modules. Its `src/lib.lse` is named after the /// package, for its own tests as for its dependents (see `manifest`). fn load_root(&mut self, root: &Path, name: &str) -> std::io::Result> { let ids = self.load_dir(&root.join("src"), None)?; if let Some(m) = self.modules.iter_mut().find(|m| m.path == "lib") { m.path = name.to_owned(); } Ok(ids) } /// Identify the files of an already-loaded source directory without /// reading their text or adding replacement modules. fn stored_source_ids(&self, src: &Path) -> std::io::Result> { let mut files = Vec::new(); collect_til_files(src, &mut files)?; Ok(files .iter() .filter_map(|path| self.file_id_of_path(path)) .collect()) } /// Load a package's tests: `.lse` files under `test/`, named relative /// to it. Returns their module paths. Tests loaded after the source /// packet join that root's resolution, rather than becoming standalone. pub fn load_tests(&mut self, root: &Path) -> std::io::Result> { let ids = self.load_dir(&root.join("test"), None)?; if let Some(package) = self .packages .iter_mut() .find(|package| package.root == root) { package.sources.extend(ids.iter().copied()); } Ok(ids .iter() .filter_map(|id| { self.modules .iter() .find(|m| m.file == *id) .map(|m| m.path.clone()) }) .collect()) } /// Load the `.lse` files under `src`; with `prefix`, as a dependency's /// modules (`lib` is the prefix itself). fn load_dir(&mut self, src: &Path, prefix: Option<&str>) -> std::io::Result> { let mut files = Vec::new(); collect_til_files(src, &mut files)?; files.sort(); let texts = files .iter() .map(std::fs::read_to_string) .collect::>>()?; let start = Instant::now(); let parses = parse_all(&texts.iter().map(String::as_str).collect::>()); self.parse_time += start.elapsed(); let mut ids = Vec::new(); for ((path, text), parse) in files.iter().zip(texts).zip(parses) { let module = match (prefix, module_path(src, path)) { (Some(p), m) if m == "lib" => p.to_owned(), (Some(p), m) => format!("{p}/{m}"), (None, m) => m, }; ids.push(self.add_parsed(&module, &path.display().to_string(), text, parse)); } Ok(ids) } } /// The standard library's modules, parsed once per process: every [`Db`] /// clones them, which only copies reference counts (a syntax tree is /// shared and immutable). Tests and the language server make many. fn std_parses() -> &'static [Parse] { static PARSES: std::sync::OnceLock> = std::sync::OnceLock::new(); PARSES.get_or_init(|| parse_all(&STD.iter().map(|(_, text)| *text).collect::>())) } /// Parse `texts`, a few at a time (issue #122); the results are in the /// same order. Modules are parsed independently: imports are resolved /// afterwards, on all of them. The largest texts go first, so that the /// prelude (a third of std) does not finish last; more than [`PARSERS`] /// threads cost more CPU to start than they saved. fn parse_all(texts: &[&str]) -> Vec { let threads = std::thread::available_parallelism() .map_or(1, |n| n.get()) .min(PARSERS) .min(texts.len()); if threads <= 1 { return texts.iter().map(|t| louise_syntax::parse(t)).collect(); } let mut order: Vec = (0..texts.len()).collect(); order.sort_by_key(|i| std::cmp::Reverse(texts[*i].len())); let next = std::sync::atomic::AtomicUsize::new(0); let mut parsed: Vec<(usize, Parse)> = std::thread::scope(|scope| { let workers: Vec<_> = (0..threads) .map(|_| { std::thread::Builder::new() // The parser recurses up to its depth limit. .stack_size(8 << 20) .spawn_scoped(scope, || { let mut done = Vec::new(); loop { let k = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed); let Some(&i) = order.get(k) else { break done }; done.push((i, louise_syntax::parse(texts[i]))); } }) .expect("louise: cannot start a parser thread") }) .collect(); workers .into_iter() .flat_map(|w| w.join().unwrap_or_else(|p| std::panic::resume_unwind(p))) .collect() }); parsed.sort_by_key(|(i, _)| *i); parsed.into_iter().map(|(_, parse)| parse).collect() } /// The most threads [`parse_all`] starts. const PARSERS: usize = 3; fn collect_til_files(dir: &Path, out: &mut Vec) -> std::io::Result<()> { if !dir.is_dir() { return Ok(()); } for entry in std::fs::read_dir(dir)? { let path = entry?.path(); if path.is_dir() { collect_til_files(&path, out)?; } else if path.extension().is_some_and(|e| e == "lse") { out.push(path); } } Ok(()) } /// `src/app/main.lse` relative to `src` is module `app/main`. pub fn module_path(src: &Path, file: &Path) -> String { let rel = file.strip_prefix(src).unwrap_or(file).with_extension(""); rel.components() .map(|c| c.as_os_str().to_string_lossy().into_owned()) .collect::>() .join("/") } #[cfg(test)] mod tests { use super::*; #[test] fn std_checks_cleanly() { let analysis = Db::with_all_std().analyze(); assert_eq!(analysis.hir.modules.len(), STD.len()); assert!( analysis.diagnostics.is_empty(), "{:#?}", analysis.diagnostics ); } /// The std modules analysed with `db`'s. fn std_reached(db: &Db) -> Vec { let analysis = db.analyze(); (analysis.hir.modules.iter()) .map(|(_, m)| m.path.clone()) .filter(|p| p.starts_with("std/")) .collect() } /// The std modules analysed with a module `main` of `text`. fn std_reached_by(text: &str) -> Vec { let mut db = Db::new(); db.add_module("main", "main.lse", text.into()); std_reached(&db) } #[test] fn only_the_std_modules_a_program_reaches_are_analysed() { let reached = std_reached_by( "import std/io\npub fn main :: -> () / {\n io.println \"hi\"\n}\n", ); // The prelude always; what `std/io` imports, transitively. for m in ["std/prelude", "std/io", "std/ffi"] { assert!(reached.iter().any(|r| r == m), "{m}: {reached:?}"); } for m in ["std/dist", "std/wire", "std/html", "std/http"] { assert!(!reached.iter().any(|r| r == m), "{m}: {reached:?}"); } // Everything std imports is in, so what is reached checks. let dist = std_reached_by("import std/dist\n"); for m in ["std/dist", "std/wire", "std/dist/remote", "std/net"] { assert!(dist.iter().any(|r| r == m), "{m}: {dist:?}"); } } #[test] fn syntax_that_names_a_std_module_reaches_it() { for (body, module) in [ ("let _ =

hi

\n ()", "std/html"), ("let _ = tag`hi`\n ()", "std/template"), ("region\n {\n ()\n }", "std/ref"), ] { let text = format!("pub fn f :: -> ()\n{{\n {body}\n}}\n"); assert!( std_reached_by(&text).iter().any(|r| r == module), "{module} for {text}" ); assert!( !std_reached_by("pub fn f :: -> () {\n ()\n}\n") .iter() .any(|r| r == module), "{module} without the syntax" ); } let remote = std_reached_by("@remote\nfn worker :: n: Int -> () {\n ()\n}\n"); assert!(remote.iter().any(|r| r == "std/dist/remote"), "{remote:?}"); } #[test] fn an_edit_that_adds_an_import_reaches_its_module() { let mut db = Db::new(); let file = db.add_module("main", "main.lse", "pub fn f :: -> () {\n ()\n}\n".into()); assert!(!std_reached(&db).iter().any(|r| r == "std/dict")); db.set_text( file, "import std/dict\npub fn f :: -> Int {\n dict.size (dict.empty ())\n}\n".into(), ); assert!(std_reached(&db).iter().any(|r| r == "std/dict")); assert!(db.analyze().diagnostics.is_empty()); } #[test] fn a_test_import_reaches_its_module_only_with_tests() { let text = "@test import std/dict\npub fn f :: -> () {\n ()\n}\n"; let mut db = Db::new(); db.add_module("main", "main.lse", text.into()); assert!(std_reached(&db).iter().any(|r| r == "std/dict")); db.without_tests(); assert!(!std_reached(&db).iter().any(|r| r == "std/dict")); } #[test] fn a_missing_std_module_is_still_unresolved() { let mut db = Db::new(); db.add_module("main", "main.lse", "import std/nope\n".into()); let codes: Vec<&str> = (db.analyze().diagnostics.iter()).map(|d| d.code).collect(); assert_eq!(codes, ["E0103"]); } #[test] fn parallel_parses_come_back_in_order() { let texts: Vec = (0..40) .map(|i| format!("pub fn f{i}() -> Int {{ {} }}", "1 + ".repeat(i % 7) + "1")) .collect(); let refs: Vec<&str> = texts.iter().map(String::as_str).collect(); let parallel = parse_all(&refs); assert_eq!(parallel.len(), texts.len()); for (text, parse) in texts.iter().zip(¶llel) { assert_eq!( parse.syntax().to_string(), *text, "a parse is in another's place" ); } } #[test] fn a_package_loads_the_same_way_twice() { let dir = std::env::temp_dir().join(format!("louise-db-order-{}", std::process::id())); let src = dir.join("src"); std::fs::create_dir_all(src.join("app")).unwrap(); for (file, text) in [ ( "main.lse", "import app/b\npub fn main :: -> Int {\n b.two ()\n}\n", ), ("app/a.lse", "pub fn one :: -> Int {\n 1\n}\n"), ( "app/b.lse", "import app/a\npub fn two :: -> Int {\n a.one () + true\n}\n", ), ] { std::fs::write(src.join(file), text).unwrap(); } let load = || { let mut db = Db::new(); db.load_dir(&src, None).unwrap(); let messages: Vec = db .analyze() .diagnostics .iter() .map(|d| d.message.clone()) .collect(); (db.user_modules(), messages) }; let (modules, diagnostics) = load(); assert_eq!(modules, ["app/a", "app/b", "main"]); assert!(!diagnostics.is_empty(), "the type error in app/b"); assert_eq!(load(), (modules, diagnostics)); let _ = std::fs::remove_dir_all(&dir); } #[test] fn edits_are_reanalyzed() { let mut db = Db::new(); let file = db.add_module( "main", "main.lse", "pub fn f :: -> Int {\n \"no\"\n}\n".into(), ); assert_eq!(db.analyze().diagnostics.len(), 1); db.set_text(file, "pub fn f :: -> Int {\n 1\n}\n".into()); assert!(db.analyze().diagnostics.is_empty()); } #[test] fn module_paths_are_relative_to_src() { let src = Path::new("/p/src"); assert_eq!( module_path(src, Path::new("/p/src/app/main.lse")), "app/main" ); assert_eq!(module_path(src, Path::new("/p/src/lib.lse")), "lib"); } }