mir-analyzer 0.88.0

Analysis engine for the mir PHP static analyzer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
use super::*;

impl AnalysisSession {
    /// Retrieve the source text the session has registered for `file`, if
    /// any. Returns `None` when the file has never been ingested. Used by
    /// the parallel re-analysis path to re-feed dependents to body analysis without
    /// the caller having to track sources independently.
    pub fn source_of(&self, file: &str) -> Option<Arc<str>> {
        let db = self.snapshot_db();
        let sf = db.lookup_source_file(file)?;
        Some(sf.text(&db).clone())
    }

    /// Re-analyze every transitive dependent of `file`.
    ///
    /// When the user saves a file that other files depend on (e.g. editing
    /// a base class, an interface, or a trait), those dependents may have
    /// new diagnostics. Returns the per-file analysis results so the LSP
    /// server can publish updated diagnostics in one batch.
    ///
    /// Source text for dependents is retrieved from the session's salsa
    /// inputs (set by previous `ingest_file` calls) — the caller doesn't
    /// need to track or re-read files. Files for which the session has no
    /// source are silently skipped (returns the analyzable subset).
    ///
    /// Cross-file inferred return types are resolved on demand via salsa.
    pub fn reanalyze_dependents(&mut self, file: &str) -> Vec<(Arc<str>, crate::FileAnalysis)> {
        self.reanalyze_dependents_cancellable(file, &crate::IndexCancel::new())
    }

    /// Cancellable variant of [`Self::reanalyze_dependents`].
    ///
    /// The consumer flips `cancel` (typically because a newer edit arrived) to
    /// abandon the re-analysis; the flag is checked at each file boundary. Salsa
    /// cannot unwind the plain-Rust body-analysis walk mid-flight, so a file
    /// already in progress finishes, but no further files are started. Files
    /// skipped due to cancellation are simply absent from the returned vec —
    /// the consumer should drop a stale flag and start fresh work on each edit.
    pub fn reanalyze_dependents_cancellable(
        &mut self,
        file: &str,
        cancel: &crate::IndexCancel,
    ) -> Vec<(Arc<str>, crate::FileAnalysis)> {
        if cancel.is_cancelled() {
            return Vec::new();
        }

        // Phase 1: compute dependents outside the analysis loop.
        let dependents = self.dependency_graph().transitive_dependents(file);
        if dependents.is_empty() {
            return Vec::new();
        }
        let dependents: Vec<Arc<str>> = dependents
            .into_iter()
            .map(|path| Arc::from(path.as_str()))
            .collect();
        self.reanalyze_file_set(dependents, cancel)
    }

    /// Re-analyze an explicit file set — typically the editor's currently
    /// open files — after an edit elsewhere in the workspace.
    ///
    /// The caller passes the files it publishes diagnostics for instead of
    /// computing the edited file's transitive dependents; salsa memoization
    /// makes unaffected files ~free. Per-edit cost is O(open files).
    ///
    /// Files the session has no source for are silently skipped. Cancellation
    /// semantics match [`Self::reanalyze_dependents_cancellable`].
    pub fn reanalyze_files_cancellable(
        &mut self,
        files: &[Arc<str>],
        cancel: &crate::IndexCancel,
    ) -> Vec<(Arc<str>, crate::FileAnalysis)> {
        if cancel.is_cancelled() || files.is_empty() {
            return Vec::new();
        }
        if !self.settle_workspace_index_cancellable(&|| cancel.is_cancelled()) {
            return Vec::new();
        }
        self.reanalyze_file_set(files.to_vec(), cancel)
    }

    /// Shared body of [`Self::reanalyze_dependents_cancellable`] and
    /// [`Self::reanalyze_files_cancellable`]: warm up, analyze in parallel,
    /// commit reference locations.
    fn reanalyze_file_set(
        &mut self,
        files: Vec<Arc<str>>,
        cancel: &crate::IndexCancel,
    ) -> Vec<(Arc<str>, crate::FileAnalysis)> {
        let dependents = files;

        // Phase 2a: index each dependent's direct class references the
        // background indexer hasn't reached yet, as `FileAnalyzer` does.
        // Loading writes salsa inputs, and a write waits for every live db
        // handle, so this runs serially before the pass takes its snapshot.
        //
        // Files already prepared against their current text skip the parse +
        // AST walk entirely — hosts on the `ingest_file_prepared` write path
        // pre-pay this per edit, making the whole loop a map-lookup sweep.
        {
            // Closed before the pass view is taken, so commits carry the
            // post-load generation.
            let mut session = self.defer_revision_bumps();
            for file in &dependents {
                if cancel.is_cancelled() {
                    return Vec::new();
                }
                if !session.prepare_file_for_analysis_cancellable(file, &|| cancel.is_cancelled()) {
                    return Vec::new();
                }
            }
        }

        // Phase 2b: drive each dependent through the `analyze_file` tracked
        // query. Salsa's memo validation does the real work here: after a
        // body-only edit, a dependent whose tracked inputs are structurally
        // unchanged (`FileDefinitions` backdating) returns its cached output
        // without re-running body analysis — re-analysis cost scales with
        // what actually changed, not with dependent count.
        //
        // The pass runs serially on the owner's thread, checking `cancel`
        // between files.
        //
        // Dependents' `FileAnalysis::symbols` are empty on this path:
        // per-expression symbols are intentionally not memoized (a typical
        // file resolves thousands; caching them balloons memory), and
        // diagnostics consumers don't read them. Cursor navigation resolves
        // the open file on demand via `symbol_at`/`name_at`.
        self.query_snapshot(|snap| snap.reanalyze_files(&dependents, cancel))
            .unwrap_or_default()
    }

    /// Return the `use`-import alias map for a file: a list of `(alias, fqcn)`
    /// pairs where `alias` is the local name (e.g. `"Str"`) and `fqcn` is the
    /// fully-qualified name (e.g. `"Illuminate\\Support\\Str"`).
    ///
    /// Completion handlers can use this to expand a short class name written
    /// before `::` into its FQN before looking up static members, mirroring the
    /// same alias expansion that go-to-definition already performs via
    /// `symbol_at` + `definition_of`.
    ///
    /// Returns an empty Vec if the file has not been ingested or has no use
    /// imports.
    pub fn class_imports(&self, file: &str) -> Vec<(Arc<str>, Arc<str>)> {
        let db = self.snapshot_db();
        let imports = db.file_class_imports(file);
        imports
            .iter()
            .map(|(alias, fqcn)| (Arc::from(alias.as_str()), Arc::from(fqcn.as_str())))
            .collect()
    }

    /// FQCNs that `file` imports via `use` statements but that aren't yet
    /// in the session's symbol index.
    ///
    /// Designed as the input to background prefetching: after the LSP server
    /// ingests an open buffer, it can call this and lazy-load the returned
    /// FQCNs on a worker thread so the user's first Cmd+Click into vendor
    /// code doesn't pay the file-read+parse cost.
    ///
    /// Returns an empty Vec if the file hasn't been ingested or has no
    /// unresolved imports.
    pub fn pending_lazy_loads(&self, file: &str) -> Vec<Arc<str>> {
        use rustc_hash::FxHashSet;

        let db = self.snapshot_db();
        let imports = db.file_imports(file);
        if imports.is_empty() {
            return Vec::new();
        }
        let mut out = Vec::new();
        let mut seen: FxHashSet<Arc<str>> = FxHashSet::default();
        for fqcn in imports.values() {
            let here = crate::db::Fqcn::interned(&db, *fqcn);
            if crate::db::class_like_indexed(&db, here) {
                continue;
            }
            if let Some(resolver) = &self.resolver {
                let fqcn_arc: Arc<str> = Arc::from(fqcn.as_str());
                if !seen.insert(fqcn_arc.clone()) {
                    continue;
                }
                if resolver.resolve(fqcn.as_str()).is_some() {
                    out.push(fqcn_arc);
                }
            }
        }
        out
    }

    /// Convenience: synchronously lazy-load every import of `file` that
    /// isn't already in the symbol index. Returns the number successfully loaded.
    ///
    /// Loads only the imported files themselves; their ancestors and
    /// signature types resolve through the symbol index or on demand.
    pub fn prefetch_imports(&mut self, file: &str) -> usize {
        let pending = self.pending_lazy_loads(file);
        if pending.is_empty() {
            return 0;
        }
        let mut session = self.defer_revision_bumps();
        let mut loaded = 0;
        for fqcn in &pending {
            if session.load_class(fqcn.as_ref()).is_loaded() {
                loaded += 1;
            }
        }
        loaded
    }

    /// All class / interface / trait / enum FQCNs currently known to the
    /// session, each paired with the file that defines them when available.
    ///
    /// Use this to build workspace-wide views (outline, fuzzy search, etc.).
    /// Consumers implement their own search/match logic on top — the analyzer
    /// only exposes the iterator.
    pub fn all_classes(&self) -> Vec<(Arc<str>, Option<mir_types::Location>)> {
        let db = self.snapshot_db();
        crate::db::workspace_classes(&db)
            .iter()
            .filter_map(|fqcn| {
                let here = crate::db::Fqcn::from_str(&db, fqcn.as_str());
                crate::db::find_class_like(&db, here)
                    .map(|class| (Arc::<str>::from(fqcn.as_str()), class.location().cloned()))
            })
            .collect()
    }

    /// All global function FQNs currently known to the session, each paired
    /// with their declaration location when available.
    pub fn all_functions(&self) -> Vec<(Arc<str>, Option<mir_types::Location>)> {
        let db = self.snapshot_db();
        crate::db::workspace_functions(&db)
            .iter()
            .filter_map(|fqn| {
                let here = crate::db::Fqcn::from_str(&db, fqn.as_str());
                crate::db::find_function(&db, here)
                    .map(|f| (Arc::<str>::from(fqn.as_str()), f.location.clone()))
            })
            .collect()
    }

    /// Every ancestor of `fqcn` — extended class, implemented interfaces,
    /// used traits, transitively — most-derived first. Does not include
    /// `fqcn` itself. Memoized per FQCN (shares `class_ancestors_by_fqcn`'s
    /// tracked cache with member-resolution paths).
    pub fn ancestors_of(&self, fqcn: &str) -> Vec<Arc<str>> {
        let db = self.snapshot_db();
        let here = crate::db::Fqcn::from_str(&db, fqcn.trim_start_matches('\\'));
        crate::db::class_ancestors_by_fqcn(&db, here)
            .iter()
            .skip(1)
            .cloned()
            .collect()
    }

    /// Full signature for a global function, resolved by FQN.
    pub fn function_signature(&self, fqn: &str) -> Option<Arc<crate::FunctionDef>> {
        let db = self.snapshot_db();
        let here = crate::db::Fqcn::from_str(&db, fqn);
        crate::db::find_function(&db, here)
    }

    /// Persist `file`'s outgoing dependency edges to the disk cache's
    /// reverse-dep graph, if one is attached.
    pub(super) fn update_reverse_deps_for(&self, file: &str) {
        if let Some(cache) = self.cache.as_deref() {
            let db = self.snapshot_db();
            let targets = file_outgoing_dependencies(&db, file, true);
            cache.update_reverse_deps_for_file(file, &targets);
        }
    }

    /// File dependency graph: which files depend on which other files.
    /// Used for incremental invalidation in LSP servers and build systems.
    ///
    /// O(E) in the (file, symbol) edges from the reference index and
    /// `file_structural_symbols`, each resolved to its defining
    /// file by index lookup. Cached until the file set or an edge changes.
    pub fn dependency_graph(&self) -> crate::DependencyGraph {
        let stamp = self.index.dependency_graph_stamp(&self.db.salsa);
        if let Some(graph) = self.index.cached_dependency_graph(stamp) {
            return graph;
        }
        let db = self.snapshot_db();

        fn push_edge(
            dependencies: &mut [Vec<u32>],
            dependents: &mut [Vec<u32>],
            from: u32,
            to: u32,
        ) {
            if from == to {
                return;
            }
            dependents[to as usize].push(from);
            dependencies[from as usize].push(to);
        }

        fn sort_and_dedup(adjacency: &mut [Vec<u32>]) {
            for deps in adjacency {
                deps.sort();
                deps.dedup();
            }
        }

        // Every file a symbol resolves to joins the graph, including ones
        // loaded on demand while resolving, so their own edges are walked too.
        let mut known: HashSet<Arc<str>> = db.known_file_paths().into_iter().collect();
        let mut pending: Vec<Arc<str>> = known.iter().cloned().collect();
        let mut outgoing: Vec<(Arc<str>, HashSet<Arc<str>>)> = Vec::with_capacity(pending.len());
        while let Some(file) = pending.pop() {
            let mut targets: HashSet<Arc<str>> = HashSet::default();
            let mut resolve = |symbol_key: &str| {
                let lookup = crate::defining_file_lookup_key(symbol_key);
                if let Some(defining_file) = db.symbol_defining_file(lookup) {
                    targets.insert(defining_file);
                }
            };
            // O(degree(file)) — forward reference-index lookup, no full-table scan.
            for symbol_key in db.file_referenced_symbols(file.as_ref()) {
                resolve(&symbol_key);
            }
            // Declaration-level symbol edges from Salsa. These cover imports,
            // class hierarchy edges, and type-hint-only references that never
            // appear in file_referenced_symbols.
            if let Some(sf) = db.lookup_source_file(file.as_ref()) {
                for symbol in crate::db::file_structural_symbols(&db, sf).iter() {
                    resolve(symbol);
                }
            }
            for target in &targets {
                if known.insert(target.clone()) {
                    pending.push(target.clone());
                }
            }
            outgoing.push((file, targets));
        }

        let mut all_files: Vec<Arc<str>> = known.into_iter().collect();
        all_files.sort();
        assert!(
            u32::try_from(all_files.len()).is_ok(),
            "dependency graph file ids require at most u32::MAX files"
        );
        let file_ids: HashMap<Arc<str>, u32> = all_files
            .iter()
            .enumerate()
            .map(|(id, file)| (file.clone(), id as u32))
            .collect();

        let mut dependencies = vec![Vec::new(); all_files.len()];
        let mut dependents = vec![Vec::new(); all_files.len()];
        for (file, targets) in outgoing {
            let file_id = file_ids[&file];
            for target in targets {
                push_edge(
                    &mut dependencies,
                    &mut dependents,
                    file_id,
                    file_ids[&target],
                );
            }
        }

        sort_and_dedup(&mut dependents);
        sort_and_dedup(&mut dependencies);

        // Augment with stale dependents: files referencing symbols that were
        // deleted from their defining file. These edges disappear from the
        // symbol_defining_file lookup but the referencing file still needs
        // re-analysis to surface the now-broken reference.
        {
            let stale = &self.stale_defined_symbols;
            if !stale.is_empty() {
                for (file, deleted_syms) in stale.iter() {
                    let Some(&file_id) = file_ids.get(file.as_str()) else {
                        continue;
                    };
                    for sym in deleted_syms {
                        let lookup = crate::defining_file_lookup_key(sym);
                        // `defined_symbols()` only yields top-level FQ names
                        // (classes/interfaces/traits/enums, functions, global
                        // constants) — never knows here which kind `sym` was,
                        // so probe every prefix the reference index actually
                        // uses (see `Name::codebase_key`) rather than guessing
                        // one and silently missing referencers of the others.
                        for prefix in ["cls:", "fn:", "gcnst:"] {
                            for referencing_file in
                                db.symbol_referencers_of(&format!("{prefix}{lookup}"))
                            {
                                if let Some(&ref_id) = file_ids.get(referencing_file.as_ref()) {
                                    push_edge(&mut dependencies, &mut dependents, ref_id, file_id);
                                }
                            }
                        }
                    }
                }
                // Re-sort and dedup since we may have added entries.
                sort_and_dedup(&mut dependents);
                sort_and_dedup(&mut dependencies);
            }
        }

        let graph = crate::DependencyGraph::from_compact_parts(
            all_files,
            file_ids,
            dependencies,
            dependents,
        );
        self.index.store_dependency_graph(stamp, graph.clone());
        graph
    }
}