Skip to main content

gdscript_db/
lib.rs

1//! `gdscript-db` — the input layer for the analyzer.
2//!
3//! > **Internal layer (not a stable API).** Depend on [`gdscript-ide`](https://docs.rs/gdscript-ide) (the public surface); the items here
4//! > may change between releases.
5//!
6//! Holds the virtual file system (`FileId` → text, always injected — never `std::fs`), the
7//! project model, and (from Phase 3) the **salsa** query graph: `#[salsa::input]`s set via
8//! `apply_change`, `#[salsa::tracked]` derived queries, durability tiers. The Phase-0/1/2
9//! plain VFS map + reparse-on-change is being replaced here, localized behind the unchanged
10//! `gdscript-ide` public API (Playbook §3.M0).
11//!
12//! Crate boundary: `gdscript-db` is the *base* of the salsa stack — it owns the [`Db`] trait,
13//! the inputs, and the [`parse`] query (it may depend on `gdscript-syntax`, never on
14//! `gdscript-hir`). The higher queries (`item_tree`, `analyze_file`) live in `gdscript-hir`,
15//! which depends on this crate for `&dyn Db`. This one-way layering is what avoids a
16//! `db ↔ hir` dependency cycle.
17//!
18//! `FileId` is deliberately **not** a salsa input. The `FileId → FileText` mapping is a side
19//! table ([`Files`]) the database owns, mirroring rust-analyzer's `base-db`: `FileId`s are
20//! assigned by the client/loader and stay opaque ids, while the salsa input is the *text*.
21//!
22//! Must build for `wasm32` (single-threaded; salsa with `default-features = false`).
23#![cfg_attr(docsrs, feature(doc_cfg))]
24
25use std::sync::Arc;
26
27use dashmap::DashMap;
28use dashmap::mapref::entry::Entry;
29use gdscript_api::EngineApi;
30use gdscript_base::FileId;
31use gdscript_syntax::Parse;
32use rustc_hash::FxBuildHasher;
33use salsa::{Durability, Setter};
34
35/// The database trait `gdscript-hir` / `gdscript-ide` depend on. `#[salsa::db]` on the *trait*
36/// makes it a salsa supertrait, so any `&dyn Db` upcasts to `&dyn salsa::Database` and every
37/// `#[salsa::tracked]` free function downstream can take `db: &dyn Db`.
38/// A host/CLI-level override of the warning-strictness baseline `type_diagnostics` resolves against
39/// (regardless of `project.godot` presence). A plain (non-salsa) per-session policy knob: it is read
40/// **only** inside the non-tracked `type_diagnostics`, so it never enters the salsa query graph and
41/// cannot break the W1 firewall (a warning-level change must never re-run inference).
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
43pub enum WarningOverride {
44    /// Auto-select by project presence (the default): standalone ⇒ strict, project ⇒ engine defaults.
45    #[default]
46    None,
47    /// Force the strict baseline (the opt-in group promoted to WARN) even with a `project.godot`.
48    Strict,
49    /// Force Godot's engine defaults (the opt-in group stays IGNORE) even in standalone mode.
50    EngineDefaults,
51}
52
53#[salsa::db]
54pub trait Db: salsa::Database {
55    /// The text input for `file`, or `None` if no text has been set for it.
56    fn file_text(&self, file: FileId) -> Option<FileText>;
57    /// The bundled engine model, or `None` on `wasm32` (no embedded blob — the host wires the
58    /// fetched blob in via `EngineApi::from_bytes` in Phase 5).
59    fn engine(&self) -> Option<&'static EngineApi>;
60    /// The project's file set, or `None` before any file has been applied. Project-wide queries
61    /// (the global `class_name` registry) take this as their salsa-tracked input.
62    fn source_root(&self) -> Option<SourceRoot>;
63    /// The project's `project.godot` config, or `None` in single-file mode. The autoload registry
64    /// (M4) takes this as its salsa-tracked input.
65    fn project_config(&self) -> Option<ProjectConfig>;
66    /// The host-level warning-strictness override (default [`WarningOverride::None`]). A plain
67    /// field, NOT a salsa input — read only by the downstream gate, so it never re-runs inference.
68    fn warning_override(&self) -> WarningOverride;
69}
70
71/// The VFS leaf: one file's UTF-8 text, as a salsa input, plus its [`FileId`] (so a query
72/// holding only a `FileText` can recover the id for cross-file resolution) and its `res://`
73/// path (so `preload`/`extends "res://…"` resolve to the declaring file — M3).
74///
75/// `res_path` is a **separate salsa input field** from `text`: salsa tracks input fields
76/// individually (per-field `revisions`/`durabilities` — verified against salsa 0.27.1
77/// `input.rs`), so a query reading only `res_path` (the `res_path_registry`) *backdates* across
78/// a `text` keystroke — exactly the firewall that protects `file_class_name`. It is held at
79/// `MEDIUM` durability (set on file add, stable across edits); `text` stays `LOW`.
80#[salsa::input(debug)]
81pub struct FileText {
82    /// The file's full text (interned `Arc<str>`; the getter returns `&Arc<str>`).
83    #[returns(ref)]
84    pub text: Arc<str>,
85    /// The opaque file id this text belongs to.
86    pub file_id: FileId,
87    /// The file's project-relative `res://` path, if the loader supplied one (`None` in
88    /// single-file mode / tests — then `preload`/`extends "res://…"` resolve to the seam).
89    pub res_path: Option<smol_str::SmolStr>,
90}
91
92/// The project's file set — a salsa input so project-wide queries (the global `class_name`
93/// registry, M1) iterate the files incrementally. It changes only when a file is **added or
94/// removed**, never on a body edit, and is held at MEDIUM durability — so a keystroke (a `LOW`
95/// change) never invalidates project-wide derived data.
96#[salsa::input]
97pub struct SourceRoot {
98    /// Every file currently in the project, ordered by `FileId` for determinism.
99    #[returns(ref)]
100    pub files: Vec<FileText>,
101}
102
103/// The project's `project.godot`, injected as raw text — the wasm-clean core never reads the
104/// filesystem, so the loader pushes the bytes exactly like a `.gd` file. The autoload index is a
105/// tracked query that parses this text (M4). Held at `MEDIUM` durability (project structure,
106/// stable across `.gd` keystrokes), so a body edit (LOW) never invalidates the autoload registry.
107#[salsa::input]
108pub struct ProjectConfig {
109    /// The full `project.godot` text.
110    #[returns(ref)]
111    pub project_godot_text: Arc<str>,
112}
113
114/// A generation counter that makes the otherwise-untracked runtime engine model **invalidate**
115/// correctly. The engine model is a leaked `&'static` side handle (not a salsa input), so a query
116/// memoized while it was still absent (`engine() == None`, on `wasm32` before `set_engine_api`)
117/// would otherwise return that stale empty result forever. Every `engine()` read records a
118/// dependency on this input; `set_engine_api` bumps it, recomputing those queries. The *value* is
119/// irrelevant — only that setting it advances the revision. Used on `wasm32` only (native has the
120/// bundled model from the start, so it never changes — no generation tracking, no overhead).
121#[salsa::input]
122pub struct EngineGeneration {
123    /// An opaque counter (only its revision matters).
124    pub generation: u32,
125}
126
127/// The `FileId → FileText` side table. `Arc`-backed so a cheap clone shares the same map —
128/// needed to mutate an input (`&mut dyn Db`) without simultaneously borrowing `self.files`.
129#[derive(Debug, Default, Clone)]
130pub struct Files {
131    inner: Arc<DashMap<FileId, FileText, FxBuildHasher>>,
132}
133
134impl Files {
135    /// The input for `file`, if set.
136    #[must_use]
137    pub fn file_text(&self, file: FileId) -> Option<FileText> {
138        self.inner.get(&file).map(|r| *r)
139    }
140
141    /// Create or update `file`'s text input at `durability`. Creating uses `&db`; updating an
142    /// existing input bumps the revision (`&mut db`), which is what cancels live read handles.
143    pub fn set_file_text(&self, db: &mut dyn Db, file: FileId, text: &str, durability: Durability) {
144        match self.inner.entry(file) {
145            Entry::Occupied(occ) => {
146                occ.get()
147                    .set_text(db)
148                    .with_durability(durability)
149                    .to(Arc::from(text));
150            }
151            Entry::Vacant(vac) => {
152                let ft = FileText::builder(Arc::from(text), file, None)
153                    .durability(durability)
154                    .new(db);
155                vac.insert(ft);
156            }
157        }
158    }
159
160    /// Set `file`'s `res://` path at `MEDIUM` durability (stable project structure, like the
161    /// source root). No-op if the file is unknown or the path is unchanged: salsa does **not**
162    /// value-backdate an input setter (it bumps the field revision on *every* call, even for an
163    /// identical value — verified against salsa 0.27.1 `input.rs:set_field`), so a redundant set
164    /// would needlessly invalidate the `res_path_registry`. The guard keeps a re-`apply_change`
165    /// of an already-known path free.
166    pub fn set_file_path(&self, db: &mut dyn Db, file: FileId, path: &str) {
167        let Some(ft) = self.inner.get(&file).map(|r| *r) else {
168            return;
169        };
170        if ft.res_path(&*db).as_deref() == Some(path) {
171            return;
172        }
173        ft.set_res_path(db)
174            .with_durability(Durability::MEDIUM)
175            .to(Some(smol_str::SmolStr::new(path)));
176    }
177
178    /// Drop `file` from the side table (its salsa input lingers, unreferenced, until GC).
179    pub fn remove(&self, file: FileId) {
180        self.inner.remove(&file);
181    }
182
183    /// Every file, ordered by `FileId` — the deterministic input to project-wide queries.
184    fn all(&self) -> Vec<FileText> {
185        let mut v: Vec<(FileId, FileText)> =
186            self.inner.iter().map(|r| (*r.key(), *r.value())).collect();
187        v.sort_by_key(|(id, _)| *id);
188        v.into_iter().map(|(_, ft)| ft).collect()
189    }
190}
191
192/// Parse a file to its lossless CST. Memoized; re-parses only when the file text changes.
193#[salsa::tracked]
194pub fn parse(db: &dyn Db, file: FileText) -> Parse {
195    gdscript_syntax::parse(file.text(db))
196}
197
198/// The concrete analyzer database — a salsa `Storage` plus the [`Files`] side table.
199#[salsa::db]
200#[derive(Clone, Default)]
201pub struct RootDatabase {
202    storage: salsa::Storage<Self>,
203    files: Files,
204    /// The project file-set input (lazily created on the first file change). Held outside salsa
205    /// as a handle so `apply_change` can update it.
206    root: Option<SourceRoot>,
207    /// The `project.godot` config input (lazily created on the first config push). Held outside
208    /// salsa as a handle so `apply_change` can update it (M4 autoloads).
209    config: Option<ProjectConfig>,
210    /// A runtime-injected engine model. `None` falls back to the bundled blob on native and to "no
211    /// engine model" on `wasm32` (where nothing is embedded). The wasm binding fetches the blob and
212    /// installs it here via [`RootDatabase::set_engine_api`] (Playbook §4.4). Held outside salsa (a
213    /// process-lifetime `&'static`, leaked once).
214    engine: Option<&'static EngineApi>,
215    /// The host-level warning-strictness override (CLI `--strict`/`--engine-defaults`). A plain
216    /// field — read only by the non-tracked `type_diagnostics`, never a salsa input.
217    warning_override: WarningOverride,
218    /// `wasm32`-only: the [`EngineGeneration`] input that makes a *later* `set_engine_api` invalidate
219    /// queries memoized while the model was still absent (so the order "query, then load the engine"
220    /// is correct, not just "load, then query"). Lazily created on the first structural change.
221    #[cfg(target_arch = "wasm32")]
222    engine_gen: Option<EngineGeneration>,
223}
224
225// `salsa::Storage` is not `Debug`, but the public `AnalysisHost`/`Analysis` that will own a
226// `RootDatabase` must stay `Debug` (frozen API); hand-impl an opaque one.
227impl std::fmt::Debug for RootDatabase {
228    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
229        f.debug_struct("RootDatabase").finish_non_exhaustive()
230    }
231}
232
233impl RootDatabase {
234    /// Create/update `file`'s text input (the single input-mutation primitive `apply_change`
235    /// drives). Clones the `Arc`-backed [`Files`] handle first so `self` is free to pass as the
236    /// `&mut dyn Db` the salsa setter needs.
237    pub fn set_file_text(&mut self, file: FileId, text: &str, durability: Durability) {
238        let files = self.files.clone();
239        files.set_file_text(self, file, text, durability);
240    }
241
242    /// Set `file`'s `res://` path (the loader supplies it on add; M3 `preload`/`extends` resolve
243    /// through it). Guarded against no-op re-sets — see [`Files::set_file_path`].
244    pub fn set_file_path(&mut self, file: FileId, path: &str) {
245        let files = self.files.clone();
246        files.set_file_path(self, file, path);
247    }
248
249    /// Remove `file`'s entry from the side table.
250    pub fn remove_file(&mut self, file: FileId) {
251        self.files.remove(file);
252    }
253
254    /// Set the host-level warning-strictness override (a CLI `--strict`/`--engine-defaults`
255    /// policy). A plain field — changing it does not touch salsa, so it never re-runs inference;
256    /// `type_diagnostics` re-reads it on the next snapshot.
257    pub fn set_warning_override(&mut self, ov: WarningOverride) {
258        self.warning_override = ov;
259    }
260
261    /// Set the project's `project.godot` text (the loader supplies it on project open / when it
262    /// changes — M4 autoloads). No-op if unchanged: salsa bumps an input field's revision on
263    /// every set even for an identical value, so a redundant push would needlessly invalidate the
264    /// autoload registry. Held at `MEDIUM` durability, so a `.gd` keystroke never touches it.
265    pub fn set_project_config(&mut self, text: &str) {
266        if let Some(cfg) = self.config {
267            if cfg.project_godot_text(self).as_ref() == text {
268                return;
269            }
270            cfg.set_project_godot_text(self)
271                .with_durability(Durability::MEDIUM)
272                .to(Arc::from(text));
273        } else {
274            self.config = Some(
275                ProjectConfig::builder(Arc::from(text))
276                    .durability(Durability::MEDIUM)
277                    .new(self),
278            );
279        }
280    }
281
282    /// Install a runtime-loaded engine model (the wasm path: a `fetch`ed `extension_api` blob
283    /// decoded via [`EngineApi::from_bytes`]). Leaked to `&'static` (one per session, process
284    /// lifetime). **Load-once before any query** — the engine model is not a salsa input, so a later
285    /// set would not invalidate cached reads; first-wins (a redundant install is ignored, so the
286    /// leak happens at most once). Native builds normally never call this (they fall back to the
287    /// bundled blob); it is the seam the wasm/wasip1 binding uses.
288    pub fn set_engine_api(&mut self, api: EngineApi) {
289        if self.engine.is_none() {
290            self.engine = Some(Box::leak(Box::new(api)));
291            // wasm: advance the generation so any query memoized while the model was absent (the
292            // "query before load" order) recomputes. Native never reaches here through the bindings,
293            // and its bundled model is present from the start, so it needs no generation tracking.
294            #[cfg(target_arch = "wasm32")]
295            self.bump_engine_generation();
296        }
297    }
298
299    /// wasm-only: create-or-advance the [`EngineGeneration`] input (see its docs). Creating it the
300    /// first time is harmless; advancing it invalidates every query that read `engine()`.
301    #[cfg(target_arch = "wasm32")]
302    fn bump_engine_generation(&mut self) {
303        if let Some(eg) = self.engine_gen {
304            let next = eg.generation(self).wrapping_add(1);
305            eg.set_generation(self)
306                .with_durability(Durability::MEDIUM)
307                .to(next);
308        } else {
309            self.engine_gen = Some(
310                EngineGeneration::builder(0)
311                    .durability(Durability::MEDIUM)
312                    .new(self),
313            );
314        }
315    }
316
317    /// Rebuild the project file-set input from the current side table. Call this from
318    /// `apply_change` **only when a file was added or removed** — never on a body edit — so the
319    /// MEDIUM-durability project input (and everything derived from it) stays stable across
320    /// keystrokes.
321    pub fn sync_source_root(&mut self) {
322        // wasm: ensure the engine generation exists before the first query runs, so every query's
323        // `engine()` read records a dependency on it — otherwise a `set_engine_api` afterwards could
324        // not invalidate a query that ran before the input existed. (The first structural change
325        // always precedes the first query, since the Session early-returns for unknown URIs.)
326        #[cfg(target_arch = "wasm32")]
327        if self.engine_gen.is_none() {
328            self.engine_gen = Some(
329                EngineGeneration::builder(0)
330                    .durability(Durability::MEDIUM)
331                    .new(self),
332            );
333        }
334        let files = self.files.all();
335        if let Some(root) = self.root {
336            root.set_files(self)
337                .with_durability(Durability::MEDIUM)
338                .to(files);
339        } else {
340            let root = SourceRoot::builder(files)
341                .durability(Durability::MEDIUM)
342                .new(self);
343            self.root = Some(root);
344        }
345    }
346}
347
348#[salsa::db]
349impl salsa::Database for RootDatabase {}
350
351#[salsa::db]
352impl Db for RootDatabase {
353    fn file_text(&self, file: FileId) -> Option<FileText> {
354        self.files.file_text(file)
355    }
356
357    // A runtime-injected model wins; else native falls back to the bundled blob and wasm32 to
358    // `None` (until the binding installs a fetched blob). clippy sees one target per build.
359    #[allow(clippy::unnecessary_wraps)]
360    fn engine(&self) -> Option<&'static EngineApi> {
361        // wasm: record a dependency on the generation so a later `set_engine_api` invalidates this
362        // read. (Native skips this entirely — the bundled model is constant, so zero overhead.)
363        #[cfg(target_arch = "wasm32")]
364        if let Some(eg) = self.engine_gen {
365            let _ = eg.generation(self);
366        }
367        if let Some(api) = self.engine {
368            return Some(api);
369        }
370        #[cfg(not(target_arch = "wasm32"))]
371        {
372            Some(gdscript_api::bundled())
373        }
374        #[cfg(target_arch = "wasm32")]
375        {
376            None
377        }
378    }
379
380    fn source_root(&self) -> Option<SourceRoot> {
381        self.root
382    }
383
384    fn project_config(&self) -> Option<ProjectConfig> {
385        self.config
386    }
387
388    fn warning_override(&self) -> WarningOverride {
389        self.warning_override
390    }
391}
392
393#[cfg(test)]
394mod tests {
395    use super::*;
396
397    #[test]
398    fn parse_query_returns_a_cst() {
399        let mut db = RootDatabase::default();
400        db.set_file_text(FileId(0), "func f():\n\tpass\n", Durability::LOW);
401        let ft = db.file_text(FileId(0)).unwrap();
402        let p = parse(&db, ft);
403        assert!(p.errors().is_empty());
404        // Re-querying the same input returns the memoized value (no re-parse).
405        assert_eq!(parse(&db, ft).debug_tree(), p.debug_tree());
406    }
407
408    #[test]
409    fn set_get_remove_round_trips() {
410        let mut db = RootDatabase::default();
411        let id = FileId(7);
412        db.set_file_text(id, "var x = 1\n", Durability::LOW);
413        assert_eq!(db.file_text(id).unwrap().text(&db).as_ref(), "var x = 1\n");
414        // Update in place.
415        db.set_file_text(id, "var y = 2\n", Durability::LOW);
416        assert_eq!(db.file_text(id).unwrap().text(&db).as_ref(), "var y = 2\n");
417        // Remove.
418        db.remove_file(id);
419        assert!(db.file_text(id).is_none());
420    }
421
422    #[test]
423    fn res_path_round_trips_and_guards_no_op_sets() {
424        let mut db = RootDatabase::default();
425        let id = FileId(3);
426        // No path until the loader sets one.
427        db.set_file_text(id, "class_name A\n", Durability::LOW);
428        assert_eq!(db.file_text(id).unwrap().res_path(&db), None);
429        // Set, then read back.
430        db.set_file_path(id, "res://a.gd");
431        assert_eq!(
432            db.file_text(id).unwrap().res_path(&db).as_deref(),
433            Some("res://a.gd")
434        );
435        // A re-set of the SAME path is a guarded no-op (does not panic / regress); a real rename
436        // updates it.
437        db.set_file_path(id, "res://a.gd");
438        db.set_file_path(id, "res://b.gd");
439        assert_eq!(
440            db.file_text(id).unwrap().res_path(&db).as_deref(),
441            Some("res://b.gd")
442        );
443        // Setting a path for an unknown file is a no-op (no panic).
444        db.set_file_path(FileId(999), "res://ghost.gd");
445        assert!(db.file_text(FileId(999)).is_none());
446    }
447}