| @@ -0,0 +1,220 @@ |
| 1 | +//! The analysis database: the one place where source texts, packages and |
| 2 | +//! the checking pipeline meet. Both `tilc 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. That is well within budget at |
| 8 | +//! v0 scale; finer caching keyed by stable item ids can replace the |
| 9 | +//! internals of [`Db::analyze`] without changing its callers. |
| 10 | + |
| 11 | +use std::path::{Path, PathBuf}; |
| 12 | + |
| 13 | +use tilc_diag::Diagnostic; |
| 14 | +use tilc_hir::{Hir, SourceModule}; |
| 15 | +use tilc_span::{FileId, SourceDb, SourceFile}; |
| 16 | +use tilc_syntax::Parse; |
| 17 | +use tilc_types::TypeckOutput; |
| 18 | + |
| 19 | +/// The standard library, compiled into the toolchain. |
| 20 | +pub const STD: &[(&str, &str)] = &[("std/prelude", include_str!("../../../std/prelude.til"))]; |
| 21 | + |
| 22 | +/// The module whose public items are visible everywhere. |
| 23 | +pub const PRELUDE: &str = "std/prelude"; |
| 24 | + |
| 25 | +/// Marks a package root. |
| 26 | +pub const MANIFEST: &str = "tilcayo.toml"; |
| 27 | + |
| 28 | +struct Module { |
| 29 | + path: String, |
| 30 | + file: FileId, |
| 31 | + parse: Parse, |
| 32 | +} |
| 33 | + |
| 34 | +pub struct Db { |
| 35 | + sources: SourceDb, |
| 36 | + modules: Vec<Module>, |
| 37 | +} |
| 38 | + |
| 39 | +/// The result of checking everything in a [`Db`]. |
| 40 | +pub struct Analysis { |
| 41 | + pub hir: Hir, |
| 42 | + pub typeck: TypeckOutput, |
| 43 | + /// All diagnostics, sorted by file and position. |
| 44 | + pub diagnostics: Vec<Diagnostic>, |
| 45 | +} |
| 46 | + |
| 47 | +impl Default for Db { |
| 48 | + fn default() -> Self { |
| 49 | + Self::new() |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +impl Db { |
| 54 | + /// A database containing the standard library. |
| 55 | + pub fn new() -> Db { |
| 56 | + let mut db = Db { |
| 57 | + sources: SourceDb::default(), |
| 58 | + modules: Vec::new(), |
| 59 | + }; |
| 60 | + for (path, text) in STD { |
| 61 | + db.add_module(path, &format!("<{path}.til>"), (*text).to_owned()); |
| 62 | + } |
| 63 | + db |
| 64 | + } |
| 65 | + |
| 66 | + pub fn sources(&self) -> &SourceDb { |
| 67 | + &self.sources |
| 68 | + } |
| 69 | + |
| 70 | + /// Add a module; `display_path` is what diagnostics show (and, for the |
| 71 | + /// language server, the file's path on disk). |
| 72 | + pub fn add_module(&mut self, module_path: &str, display_path: &str, text: String) -> FileId { |
| 73 | + let parse = tilc_syntax::parse(&text); |
| 74 | + let file = self.sources.add(SourceFile::new(display_path, text)); |
| 75 | + self.modules.push(Module { |
| 76 | + path: module_path.to_owned(), |
| 77 | + file, |
| 78 | + parse, |
| 79 | + }); |
| 80 | + file |
| 81 | + } |
| 82 | + |
| 83 | + /// Replace a module's text (an editor change) and re-parse it. |
| 84 | + pub fn set_text(&mut self, file: FileId, text: String) { |
| 85 | + if let Some(m) = self.modules.iter_mut().find(|m| m.file == file) { |
| 86 | + m.parse = tilc_syntax::parse(&text); |
| 87 | + self.sources.set_text(file, text); |
| 88 | + } |
| 89 | + } |
| 90 | + |
| 91 | + pub fn file_by_display_path(&self, path: &str) -> Option<FileId> { |
| 92 | + self.modules |
| 93 | + .iter() |
| 94 | + .find(|m| self.sources.get(m.file).path() == path) |
| 95 | + .map(|m| m.file) |
| 96 | + } |
| 97 | + |
| 98 | + pub fn parse(&self, file: FileId) -> Option<&Parse> { |
| 99 | + self.modules |
| 100 | + .iter() |
| 101 | + .find(|m| m.file == file) |
| 102 | + .map(|m| &m.parse) |
| 103 | + } |
| 104 | + |
| 105 | + /// Check every module. |
| 106 | + pub fn analyze(&self) -> Analysis { |
| 107 | + let sources: Vec<SourceModule> = self |
| 108 | + .modules |
| 109 | + .iter() |
| 110 | + .map(|m| SourceModule { |
| 111 | + path: m.path.clone(), |
| 112 | + file: m.file, |
| 113 | + parse: &m.parse, |
| 114 | + }) |
| 115 | + .collect(); |
| 116 | + let mut diagnostics: Vec<Diagnostic> = self |
| 117 | + .modules |
| 118 | + .iter() |
| 119 | + .flat_map(|m| m.parse.diagnostics(m.file)) |
| 120 | + .collect(); |
| 121 | + let (hir, lower_diags) = tilc_hir::lower_package(&sources, Some(PRELUDE)); |
| 122 | + diagnostics.extend(lower_diags); |
| 123 | + let typeck = tilc_types::check(&hir); |
| 124 | + diagnostics.extend(typeck.diagnostics.iter().cloned()); |
| 125 | + diagnostics.sort_by_key(|d| (d.primary.span.file, d.primary.span.range.start())); |
| 126 | + Analysis { |
| 127 | + hir, |
| 128 | + typeck, |
| 129 | + diagnostics, |
| 130 | + } |
| 131 | + } |
| 132 | + |
| 133 | + /// Load the package rooted at `root`: every `.til` file under `src/`, |
| 134 | + /// named by its path relative to `src/` (`src/app/main.til` is |
| 135 | + /// `app/main`). |
| 136 | + pub fn load_package(&mut self, root: &Path) -> std::io::Result<Vec<FileId>> { |
| 137 | + let src = root.join("src"); |
| 138 | + let mut files = Vec::new(); |
| 139 | + collect_til_files(&src, &mut files)?; |
| 140 | + files.sort(); |
| 141 | + let mut ids = Vec::new(); |
| 142 | + for path in files { |
| 143 | + let text = std::fs::read_to_string(&path)?; |
| 144 | + let module = module_path(&src, &path); |
| 145 | + ids.push(self.add_module(&module, &path.display().to_string(), text)); |
| 146 | + } |
| 147 | + Ok(ids) |
| 148 | + } |
| 149 | +} |
| 150 | + |
| 151 | +fn collect_til_files(dir: &Path, out: &mut Vec<PathBuf>) -> std::io::Result<()> { |
| 152 | + if !dir.is_dir() { |
| 153 | + return Ok(()); |
| 154 | + } |
| 155 | + for entry in std::fs::read_dir(dir)? { |
| 156 | + let path = entry?.path(); |
| 157 | + if path.is_dir() { |
| 158 | + collect_til_files(&path, out)?; |
| 159 | + } else if path.extension().is_some_and(|e| e == "til") { |
| 160 | + out.push(path); |
| 161 | + } |
| 162 | + } |
| 163 | + Ok(()) |
| 164 | +} |
| 165 | + |
| 166 | +/// `src/app/main.til` relative to `src` is module `app/main`. |
| 167 | +pub fn module_path(src: &Path, file: &Path) -> String { |
| 168 | + let rel = file.strip_prefix(src).unwrap_or(file).with_extension(""); |
| 169 | + rel.components() |
| 170 | + .map(|c| c.as_os_str().to_string_lossy().into_owned()) |
| 171 | + .collect::<Vec<_>>() |
| 172 | + .join("/") |
| 173 | +} |
| 174 | + |
| 175 | +/// The nearest ancestor of `start` (inclusive) containing `tilcayo.toml`. |
| 176 | +pub fn find_package_root(start: &Path) -> Option<PathBuf> { |
| 177 | + let start = if start.is_file() { |
| 178 | + start.parent()? |
| 179 | + } else { |
| 180 | + start |
| 181 | + }; |
| 182 | + start |
| 183 | + .ancestors() |
| 184 | + .find(|dir| dir.join(MANIFEST).is_file()) |
| 185 | + .map(Path::to_path_buf) |
| 186 | +} |
| 187 | + |
| 188 | +#[cfg(test)] |
| 189 | +mod tests { |
| 190 | + use super::*; |
| 191 | + |
| 192 | + #[test] |
| 193 | + fn std_checks_cleanly() { |
| 194 | + let analysis = Db::new().analyze(); |
| 195 | + assert!( |
| 196 | + analysis.diagnostics.is_empty(), |
| 197 | + "{:#?}", |
| 198 | + analysis.diagnostics |
| 199 | + ); |
| 200 | + } |
| 201 | + |
| 202 | + #[test] |
| 203 | + fn edits_are_reanalyzed() { |
| 204 | + let mut db = Db::new(); |
| 205 | + let file = db.add_module("main", "main.til", "pub fn f() -> Int { \"no\" }".into()); |
| 206 | + assert_eq!(db.analyze().diagnostics.len(), 1); |
| 207 | + db.set_text(file, "pub fn f() -> Int { 1 }".into()); |
| 208 | + assert!(db.analyze().diagnostics.is_empty()); |
| 209 | + } |
| 210 | + |
| 211 | + #[test] |
| 212 | + fn module_paths_are_relative_to_src() { |
| 213 | + let src = Path::new("/p/src"); |
| 214 | + assert_eq!( |
| 215 | + module_path(src, Path::new("/p/src/app/main.til")), |
| 216 | + "app/main" |
| 217 | + ); |
| 218 | + assert_eq!(module_path(src, Path::new("/p/src/lib.til")), "lib"); |
| 219 | + } |
| 220 | +} |