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