Skip to main content

mir_analyzer/session/
queries.rs

1use std::sync::Arc;
2
3use super::*;
4
5impl AnalysisSession {
6    /// Open-file diagnostics entrypoint for issue-only consumers.
7    ///
8    /// Updates the session's current text for `file`, reuses the tracked parse
9    /// and definition queries for syntax/collector diagnostics, then runs the
10    /// targeted open-file body-analysis path without retaining whole-file
11    /// `ResolvedSymbol` payloads.
12    pub fn analyze_file_diagnostics(&mut self, file: &str, source: &str) -> crate::FileAnalysis {
13        let file: Arc<str> = Arc::from(file);
14        self.ingest_file(file.clone(), Arc::from(source));
15
16        // Body analysis can load classes, a write that would wait forever on
17        // a db handle still alive here.
18        let (mut issues, parsed) = {
19            let view = self.db_view();
20            let db = view.db();
21            let Some(sf) = db.lookup_source_file(file.as_ref()) else {
22                return crate::FileAnalysis {
23                    issues: Vec::new(),
24                    symbols: Vec::new(),
25                };
26            };
27            let defs = crate::db::collect_file_definitions(db, sf);
28            let prepared = crate::db::prepare_analysis_file(db, sf);
29            let parsed = (!prepared.has_hard_parse_errors)
30                .then(|| (prepared.text.clone(), prepared.parsed.0.clone()));
31            (Arc::unwrap_or_clone(defs.issues.clone()), parsed)
32        };
33
34        if let Some((text, parsed)) = parsed {
35            let analysis = crate::FileAnalyzer::new(self).analyze_diagnostics_only(
36                file.clone(),
37                text.as_ref(),
38                &parsed.program,
39                &parsed.source_map,
40            );
41            issues.extend(analysis.issues);
42        }
43
44        self.apply_suppressions_and_emit_unused(&mut issues, std::slice::from_ref(&file));
45        crate::FileAnalysis {
46            issues,
47            symbols: Vec::new(),
48        }
49    }
50
51    /// Resolve the codebase-level symbol name at `byte_offset` in `file`.
52    ///
53    /// The identity half of [`Self::symbol_at`], for consumers that only need
54    /// a [`crate::Name`] to feed [`Self::definition_of`] or
55    /// [`Self::indexed_references_to`].
56    pub fn name_at(&mut self, file: &str, byte_offset: u32) -> Option<crate::Name> {
57        crate::FileAnalyzer::new(self).name_at(Arc::from(file), byte_offset)
58    }
59
60    /// Resolve the symbol at `byte_offset` in `file`'s current ingested text.
61    ///
62    /// Answers the same as [`crate::FileAnalysis::symbol_at`] without the
63    /// caller retaining a whole-file symbol list: the containing scope is
64    /// re-analyzed on demand and only its symbol payload is searched.
65    ///
66    /// **Side effects:** may fault in direct dependencies of `file` by running
67    /// the open-file warm-up path (`prepare_file_for_analysis`).
68    pub fn symbol_at(&mut self, file: &str, byte_offset: u32) -> Option<crate::ResolvedSymbol> {
69        crate::FileAnalyzer::new(self).symbol_at(Arc::from(file), byte_offset)
70    }
71
72    /// Resolve a top-level symbol (class or function) to its declaration
73    /// location. Powers go-to-definition.
74    ///
75    /// **Side effects:** ingests the file defining the symbol's class if the
76    /// symbol index lacks it. [`Self::definition_of_cached`] answers the same
77    /// without writing inputs.
78    ///
79    /// Returns:
80    /// - `Ok(Location)` — symbol found with a source location
81    /// - `Err(NotFound)` — no such symbol in the codebase
82    /// - `Err(NoSourceLocation)` — symbol exists but has no recorded span
83    ///   (e.g. some stub-only declarations)
84    pub fn definition_of(
85        &mut self,
86        symbol: &crate::Name,
87    ) -> Result<mir_types::Location, crate::SymbolLookupError> {
88        self.load_symbol_owner(symbol);
89        self.definition_of_cached(symbol)
90    }
91
92    /// Ingest the file defining the class (or function) `symbol` is rooted
93    /// in, so the symbol index holds it. No-op when indexed.
94    fn load_symbol_owner(&mut self, symbol: &crate::Name) {
95        match symbol {
96            crate::Name::Class(fqn) | crate::Name::Function(fqn) => {
97                let _ = self.load_class(fqn.as_ref());
98            }
99            crate::Name::Method { class, .. }
100            | crate::Name::Property { class, .. }
101            | crate::Name::ClassConstant { class, .. } => {
102                let _ = self.load_class(class.as_ref());
103            }
104            crate::Name::GlobalConstant(_) => {}
105        }
106    }
107
108    /// Pure variant of [`Self::definition_of`]: never writes salsa inputs.
109    /// Symbols the index lacks load on demand through the resolver and
110    /// [`crate::SourceProvider`] as pure reads.
111    pub fn definition_of_cached(
112        &self,
113        symbol: &crate::Name,
114    ) -> Result<mir_types::Location, crate::SymbolLookupError> {
115        self.query_snapshot(|snap| snap.definition_of_cached(symbol))
116    }
117
118    /// Raw reference locations indexed by string symbol key, kept for tests
119    /// that use the string-keyed API. Prefer [`Self::indexed_references_to`]
120    /// with a typed [`crate::Name`].
121    #[doc(hidden)]
122    pub fn reference_locations(&self, symbol: &str) -> Vec<(Arc<str>, u32, u16, u16)> {
123        use crate::db::MirDatabase;
124        let db = self.snapshot_db();
125        db.reference_locations(symbol)
126    }
127
128    /// Files declaring transitive subclasses of `class_fqn`, backed by the
129    /// maintained subtype index (see [`Self::indexed_subtype_classes`]).
130    /// Excludes `class_fqn`'s own declaring file — the caller adds it.
131    ///
132    /// Lets a reference-search caller scope a `protected` member to its class
133    /// hierarchy without reconstructing that hierarchy from declaration text:
134    /// subclasses are matched by resolved FQCN, so `extends \Ns\Base` and
135    /// aliased `use` forms are all found. Read-only from the caller's
136    /// perspective; may trigger an on-demand commit of stale/uncommitted
137    /// candidates' class edges (same self-heal `indexed_subtype_classes` uses).
138    pub fn subtype_files(&mut self, class_fqn: &str) -> Vec<Arc<str>> {
139        self.prepare_for_query(None);
140        self.query_snapshot(|snap| snap.subtype_files(class_fqn))
141    }
142
143    /// Compatibility wrapper for callers that only want `use` import items.
144    /// Delegates to [`Self::indexed_references_to`] so import references share
145    /// the same freshness/self-heal path, scope filtering, and memoization
146    /// boundary as every other reference query.
147    pub fn indexed_use_import_locations(
148        &mut self,
149        symbol: &crate::Name,
150        files: &[Arc<str>],
151    ) -> Vec<(Arc<str>, crate::Range)> {
152        self.indexed_references_to(
153            symbol,
154            files,
155            false,
156            crate::ReferenceIncludes::UseImports,
157            &|| false,
158        )
159        .unwrap_or_default()
160    }
161
162    /// See [`AnalysisSnapshot::indexed_references_to`]. Unlike the snapshot
163    /// form, this runs the owner-side warm-up for stale candidates first, so
164    /// every one of them is analyzed with its referenced classes loaded.
165    ///
166    /// `should_cancel` is polled at phase boundaries and between stale
167    /// candidates; `true` aborts with `None`, as does an index settle that
168    /// snapshot readers keep feeding past its round cap.
169    pub fn indexed_references_to(
170        &mut self,
171        symbol: &crate::Name,
172        files: &[Arc<str>],
173        include_declaration: bool,
174        includes: crate::ReferenceIncludes,
175        should_cancel: &(dyn Fn() -> bool + Sync),
176    ) -> Option<Vec<(Arc<str>, crate::Range)>> {
177        // Settling can move the generation, which turns commits with
178        // unresolved names stale, so it runs before both the memo probe and
179        // the stale set.
180        if self.db.salsa.needs_index_settle()
181            && !self.settle_workspace_index_cancellable(should_cancel)
182        {
183            return None;
184        }
185        // No `should_cancel()` check before the memo probe: a hit does no
186        // analysis work, and some callers count probe invocations to prove
187        // a warm query needed no re-analysis.
188        let key = {
189            let snap = self.db_view();
190            let key = snap.reference_query_key(symbol, files, include_declaration, includes);
191            if let Some(hit) = self.index.ref_queries.get(&key) {
192                return Some(hit);
193            }
194            key
195        };
196        if should_cancel() {
197            return None;
198        }
199        let stale = self.db_view().stale_reference_candidates(symbol, files);
200
201        if !stale.is_empty() {
202            // The bump scope closes before the commit view captures its
203            // generation.
204            {
205                let mut session = self.defer_revision_bumps();
206                for path in &stale {
207                    if !session.prepare_file_for_analysis_cancellable(path, should_cancel) {
208                        return None;
209                    }
210                }
211            }
212            if should_cancel() {
213                return None;
214            }
215            self.query_snapshot(|snap| snap.commit_reference_candidates(&stale));
216        }
217
218        if include_declaration {
219            self.load_symbol_owner(symbol);
220        }
221        let snap = self.db_view();
222        let out = snap.read_references(symbol, files, include_declaration, includes);
223        snap.memoize_references(key, &out);
224        Some(out)
225    }
226
227    /// The symbol's declaration site, narrowed from the collector's
228    /// whole-declaration span to the declared name's own token (matching the
229    /// span shape of recorded references).
230    pub fn declaration_name_range(
231        &mut self,
232        symbol: &crate::Name,
233    ) -> Option<(Arc<str>, crate::Range)> {
234        self.load_symbol_owner(symbol);
235        self.db_view().declaration_name_range(symbol)
236    }
237
238    /// See [`AnalysisSnapshot::indexed_subtype_classes`].
239    pub fn indexed_subtype_classes(
240        &mut self,
241        class_fqn: &str,
242        files: &[Arc<str>],
243        include_trait_users: bool,
244    ) -> Vec<SubtypeClassSite> {
245        self.prepare_for_query(None);
246        self.query_snapshot(|snap| {
247            snap.indexed_subtype_classes(class_fqn, files, include_trait_users)
248        })
249    }
250
251    /// See [`AnalysisSnapshot::indexed_method_implementations`].
252    pub fn indexed_method_implementations(
253        &mut self,
254        class_fqn: &str,
255        method: &str,
256        files: &[Arc<str>],
257    ) -> Vec<(Arc<str>, Arc<str>, crate::Range)> {
258        self.prepare_for_query(None);
259        self.query_snapshot(|snap| snap.indexed_method_implementations(class_fqn, method, files))
260    }
261
262    /// See [`AnalysisSnapshot::class_issues`]. Call this after ingesting or
263    /// re-analyzing a file and its dependents to get the full diagnostic
264    /// picture.
265    pub fn class_issues(&mut self, files: &[Arc<str>]) -> Vec<crate::Issue> {
266        self.prepare_for_query(None);
267        self.query_snapshot(|snap| snap.class_issues(files))
268    }
269
270    /// See [`AnalysisSnapshot::collector_issues`]. Correct regardless of
271    /// which path put the file's text into the db (`ingest_file`,
272    /// `set_file_text`, lazy vendor load) or how many times.
273    pub fn collector_issues(&self, files: &[Arc<str>]) -> Vec<crate::Issue> {
274        self.query_snapshot(|snap| snap.collector_issues(files))
275    }
276
277    /// All declarations defined in `file` as a **hierarchical tree**.
278    ///
279    /// Classes/interfaces/traits/enums are returned with their methods,
280    /// properties, and constants nested in `children`. Top-level functions
281    /// and constants are returned with empty `children`.
282    pub fn document_symbols(&self, file: &str) -> Vec<crate::symbol::DocumentSymbol> {
283        use crate::symbol::{DeclarationKind, DocumentSymbol};
284
285        let db = self.snapshot_db();
286        let Some(sf) = db.lookup_source_file(file) else {
287            return Vec::new();
288        };
289        let defs = crate::db::collect_file_definitions(&db, sf);
290        let mut out: Vec<DocumentSymbol> = Vec::new();
291
292        let class_children = |methods: &mir_codebase::definitions::MemberMap<
293            Arc<mir_codebase::definitions::MethodDef>,
294        >,
295                              props: Option<
296            &mir_codebase::definitions::MemberMap<mir_codebase::definitions::PropertyDef>,
297        >,
298                              consts: &mir_codebase::definitions::MemberMap<
299            mir_codebase::definitions::ConstantDef,
300        >,
301                              is_enum: bool|
302         -> Vec<DocumentSymbol> {
303            let mut out: Vec<DocumentSymbol> = Vec::new();
304            for (_, m) in methods.iter() {
305                out.push(DocumentSymbol {
306                    name: m.name.clone(),
307                    kind: DeclarationKind::Method,
308                    location: m.location.clone(),
309                    children: Vec::new(),
310                });
311            }
312            if let Some(props) = props {
313                for (_, p) in props.iter() {
314                    out.push(DocumentSymbol {
315                        name: p.name.clone(),
316                        kind: DeclarationKind::Property,
317                        location: p.location.clone(),
318                        children: Vec::new(),
319                    });
320                }
321            }
322            let const_kind = if is_enum {
323                DeclarationKind::EnumCase
324            } else {
325                DeclarationKind::Constant
326            };
327            for (_, c) in consts.iter() {
328                out.push(DocumentSymbol {
329                    name: c.name.clone(),
330                    kind: const_kind,
331                    location: c.location.clone(),
332                    children: Vec::new(),
333                });
334            }
335            out
336        };
337
338        for c in defs.slice.classes.iter() {
339            out.push(DocumentSymbol {
340                name: c.fqcn.clone(),
341                kind: DeclarationKind::Class,
342                location: c.location.clone(),
343                children: class_children(
344                    &c.own_methods,
345                    Some(&c.own_properties),
346                    &c.own_constants,
347                    false,
348                ),
349            });
350        }
351        for i in defs.slice.interfaces.iter() {
352            out.push(DocumentSymbol {
353                name: i.fqcn.clone(),
354                kind: DeclarationKind::Interface,
355                location: i.location.clone(),
356                children: class_children(&i.own_methods, None, &i.own_constants, false),
357            });
358        }
359        for t in defs.slice.traits.iter() {
360            out.push(DocumentSymbol {
361                name: t.fqcn.clone(),
362                kind: DeclarationKind::Trait,
363                location: t.location.clone(),
364                children: class_children(
365                    &t.own_methods,
366                    Some(&t.own_properties),
367                    &t.own_constants,
368                    false,
369                ),
370            });
371        }
372        for e in defs.slice.enums.iter() {
373            let mut children = class_children(&e.own_methods, None, &e.own_constants, true);
374            for (_, case) in e.cases.iter() {
375                children.push(DocumentSymbol {
376                    name: case.name.clone(),
377                    kind: DeclarationKind::EnumCase,
378                    location: case.location.clone(),
379                    children: Vec::new(),
380                });
381            }
382            out.push(DocumentSymbol {
383                name: e.fqcn.clone(),
384                kind: DeclarationKind::Enum,
385                location: e.location.clone(),
386                children,
387            });
388        }
389        for f in defs.slice.functions.iter() {
390            out.push(DocumentSymbol {
391                name: f.fqn.clone(),
392                kind: DeclarationKind::Function,
393                location: f.location.clone(),
394                children: Vec::new(),
395            });
396        }
397        for (name, _) in defs.slice.constants.iter() {
398            out.push(DocumentSymbol {
399                name: name.clone(),
400                kind: DeclarationKind::Constant,
401                location: None,
402                children: Vec::new(),
403            });
404        }
405        out
406    }
407}
408
409/// A transitive subtype hit with its declaration name span, as returned by
410/// [`AnalysisSession::indexed_subtype_classes`].
411#[derive(Debug, Clone)]
412pub struct SubtypeClassSite {
413    /// Display-form FQCN (no leading `\`).
414    pub fqcn: Arc<str>,
415    pub kind: crate::db::ClassLikeKind,
416    pub is_abstract: bool,
417    pub file: Arc<str>,
418    /// The declared name's own token (1-based line, 0-based char columns).
419    pub range: crate::Range,
420}
421
422/// Build a [`crate::Range`] on one line from mir's native coordinates
423/// (1-based line, 0-based columns).
424pub(super) fn span_range(line: u32, col_start: u32, col_end: u32) -> crate::Range {
425    crate::Range {
426        start: crate::Position {
427            line,
428            column: col_start,
429        },
430        end: crate::Position {
431            line,
432            column: col_end,
433        },
434    }
435}
436
437/// Char column of the first word-boundary occurrence of `needle` in `line`
438/// at or after char column `min_col`. Columns are code points, matching the
439/// collector's `Location` convention.
440pub(super) fn identifier_char_col(
441    line: &str,
442    needle: &str,
443    min_col: usize,
444    case_insensitive: bool,
445) -> Option<u32> {
446    if needle.is_empty() {
447        return None;
448    }
449    let is_ident = |c: char| c.is_ascii_alphanumeric() || c == '_';
450    let chars: Vec<char> = line.chars().collect();
451    let needle_chars: Vec<char> = needle.chars().collect();
452    let n = needle_chars.len();
453    if chars.len() < n {
454        return None;
455    }
456    for start in min_col..=chars.len().saturating_sub(n) {
457        let matches = chars[start..start + n]
458            .iter()
459            .zip(needle_chars.iter())
460            .all(|(a, b)| {
461                if case_insensitive {
462                    a.eq_ignore_ascii_case(b)
463                } else {
464                    a == b
465                }
466            });
467        if !matches {
468            continue;
469        }
470        let before_ok = start == 0 || !is_ident(chars[start - 1]);
471        let after = start + n;
472        let after_ok = after >= chars.len() || !is_ident(chars[after]);
473        if before_ok && after_ok {
474            return Some(start as u32);
475        }
476    }
477    None
478}
479
480/// Whether `hay` mentions `needle` as a whole identifier (ASCII word
481/// boundaries; conservative near multibyte text). ASCII-case-insensitive:
482/// PHP class, function, and method names are case-insensitive, so `new
483/// COLOR()` must count as mentioning `Color`; for the case-sensitive kinds
484/// (constants, properties) folding only widens the candidate superset.
485///
486/// Test-only semantic oracle: the production gates (references freshness,
487/// subtype-BFS defs commit) answer this predicate through the persistent
488/// `ClassMentionIndex`; the parity test below pins the scanner to these
489/// exact boundary and case semantics.
490#[cfg(test)]
491fn mentions_identifier(hay: &str, needle: &str) -> bool {
492    let hay = hay.as_bytes();
493    let needle = needle.as_bytes();
494    let n = needle.len();
495    if n == 0 || hay.len() < n {
496        return false;
497    }
498    let is_ident = |b: u8| b.is_ascii_alphanumeric() || b == b'_';
499    let first = needle[0].to_ascii_lowercase();
500    for i in 0..=(hay.len() - n) {
501        if hay[i].to_ascii_lowercase() != first || !hay[i..i + n].eq_ignore_ascii_case(needle) {
502            continue;
503        }
504        if (i == 0 || !is_ident(hay[i - 1])) && (i + n == hay.len() || !is_ident(hay[i + n])) {
505            return true;
506        }
507    }
508    false
509}
510
511fn short(fqn: &str) -> &str {
512    fqn.rsplit('\\').next().unwrap_or(fqn)
513}
514
515/// A candidate-file admission predicate for `indexed_references_to`'s
516/// freshness pass, chosen by [`ReferenceGate::for_symbol`]. A file is
517/// admitted when its text mentions any of `idents` as a whole identifier
518/// (word-bounded, ASCII-case-insensitive) OR contains any of `raw` as a
519/// plain substring (ASCII-case-insensitive, no word bounds — used for
520/// call-shaped tokens like `->__construct`). A file matching neither can
521/// hold no posting for the symbol.
522pub(super) struct ReferenceGate {
523    pub(super) idents: Vec<String>,
524    pub(super) raw: Vec<String>,
525}
526
527impl ReferenceGate {
528    /// Choose the candidate-admission gate for `symbol`.
529    ///
530    /// For any known non-constructor/non-`__invoke` method, the member name
531    /// alone is the sound gate. Every posting-producing reference spells that
532    /// token: `$obj->m()`, `Owner::m()`, inherited `Sub::m()`,
533    /// `self::`/`static::`/`parent::m()`, callable strings/arrays, and trait
534    /// aliases (`orig as alias` records `orig`, alias calls record `alias`
535    /// plus the origin key). Dropping the owner short name matters on common
536    /// owner names (`User`, `Model`, `Widget`): otherwise a cold reference
537    /// query analyzes files that only type-hint the owner and cannot contain a
538    /// reference to the queried method. Dynamic member names (`$obj->$m()`)
539    /// produce no posting, so nothing is lost there.
540    ///
541    /// For `__construct` with a known owner, the identifier needle is the
542    /// owner's short name (`new Cls(` sites never spell the member name and
543    /// the bare word `__construct` would admit every file *declaring* a
544    /// constructor), complemented by the raw call tokens `->__construct` /
545    /// `::__construct`: an explicit re-init `$obj->__construct()` is a real
546    /// recorded reference whose file may never name the class.
547    ///
548    /// `__invoke` keeps the general owner/name gate because `$obj()` call sites
549    /// do not spell `__invoke`.
550    ///
551    /// Everything else uses the general OR needles
552    /// ([`reference_gate_needles`]).
553    pub(super) fn for_symbol(db: &MirDbStorage, symbol: &crate::Name) -> Self {
554        if let crate::Name::Method { class, name } = symbol {
555            if name.as_ref() == "__construct" && !class.is_empty() {
556                return Self {
557                    idents: reference_gate_needles(symbol),
558                    raw: vec!["->__construct".to_string(), "::__construct".to_string()],
559                };
560            }
561            if name.as_ref() != "__construct" && name.as_ref() != "__invoke" && !class.is_empty() {
562                let here = crate::db::Fqcn::from_str(db, class.as_ref());
563                let is_static = crate::db::find_method_in_chain(db, here, name)
564                    .map(|(_, m)| m.is_static)
565                    .unwrap_or(false);
566                if is_static || crate::db::class_exists(db, class.as_ref()) {
567                    return Self {
568                        idents: vec![name.to_string()],
569                        raw: Vec::new(),
570                    };
571                }
572            }
573        }
574        Self {
575            idents: reference_gate_needles(symbol),
576            raw: Vec::new(),
577        }
578    }
579}
580
581/// Identifier words whose whole-word presence in a file's text is necessary
582/// for the file to hold any posting [`AnalysisSession::indexed_references_to`]
583/// can return for `symbol`. Member symbols include the owner class's short
584/// name alongside the member name: `__construct` postings are recorded at
585/// `new Cls(` sites, which never spell the member name.
586fn reference_gate_needles(symbol: &crate::Name) -> Vec<String> {
587    let mut needles = match symbol {
588        crate::Name::Class(f) | crate::Name::Function(f) | crate::Name::GlobalConstant(f) => {
589            vec![short(f).to_string()]
590        }
591        // `__construct` is invoked only as `new Cls(...)`, `parent::__construct()`,
592        // or `self::__construct()`/`static::__construct()` from inside a
593        // subclass — every real call site textually names the class itself
594        // (directly, or via the enclosing subclass's own `extends`/`use`),
595        // never the bare word `__construct`. Gating on the class's short name
596        // alone is exact (no lost call sites) and, unlike the general member
597        // case, dropping the method-name needle here doesn't reintroduce a
598        // false negative. This matters: `__construct` is one of the most
599        // common tokens in any real codebase, so OR-ing it in as a needle
600        // admits nearly every file as a "must re-analyze" candidate on a
601        // cold query, defeating the gate's entire purpose for constructors.
602        crate::Name::Method { class, name } if name.as_ref() == "__construct" => {
603            if class.is_empty() {
604                // No class to scope to (owner unknown) — fall back to gating
605                // on the bare name, same as the general member case below.
606                vec![name.to_string()]
607            } else {
608                vec![short(class).to_string()]
609            }
610        }
611        crate::Name::Method { class, name }
612        | crate::Name::Property { class, name }
613        | crate::Name::ClassConstant { class, name } => {
614            let mut v = vec![name.to_string()];
615            if !class.is_empty() {
616                v.push(short(class).to_string());
617            }
618            v
619        }
620    };
621    // An empty needle can never match; dropping it keeps the "empty needle
622    // set disables the gate" contract at the call site conservative.
623    needles.retain(|n| !n.is_empty());
624    needles
625}
626
627#[cfg(test)]
628mod tests {
629    use super::*;
630
631    #[test]
632    fn mentions_identifier_is_case_insensitive_and_word_bounded() {
633        assert!(mentions_identifier("$this->save();", "save"));
634        assert!(mentions_identifier("new COLOR()", "Color"));
635        assert!(mentions_identifier("use App\\Color as Paint;", "color"));
636        assert!(!mentions_identifier("$this->saveAll();", "save"));
637        assert!(!mentions_identifier("return $unsaved;", "save"));
638        assert!(!mentions_identifier("no occurrence", "save"));
639        assert!(!mentions_identifier("anything", ""));
640        // Multibyte neighbors are conservatively treated as boundaries, and
641        // substring scans must not split codepoints.
642        assert!(!mentions_identifier("function xÉclairFoo() {}", "Éclair"));
643        assert!(mentions_identifier("implements Éclair {}", "Éclair"));
644    }
645
646    #[test]
647    fn mention_scanner_membership_equals_per_needle_scans() {
648        // The mention index is the sole implementation of the gates' textual
649        // predicate, so scanner membership must equal the reference
650        // per-needle predicate for every (hay, needle) pair — same boundary
651        // and case semantics.
652        use crate::db::MentionScanner;
653        use std::sync::Arc;
654        let universe = ["Color", "save", "ColorPicker", "Éclair", "C1", "_Wrap"];
655        let names: Vec<(mir_types::Name, bool)> = universe
656            .iter()
657            .map(|s| (mir_types::Name::new(s).ascii_lowercase(), false))
658            .collect();
659        let scanner = Arc::new(MentionScanner::build(1, names).unwrap());
660        let hays = [
661            "$this->save();",
662            "new COLOR()",
663            "use App\\Color as Paint;",
664            "$this->saveAll();",
665            "return $unsaved;",
666            "new ColorPicker(); Color::save();",
667            "function xÉclairFoo() {}",
668            "implements Éclair {}",
669            "colorsave savecolor color_save",
670            "class C1 extends _Wrap {}",
671            "",
672        ];
673        for hay in hays {
674            let scanned = scanner.scan(hay);
675            for needle in universe {
676                let expected = mentions_identifier(hay, needle);
677                let name = mir_types::Name::new(needle).ascii_lowercase();
678                assert_eq!(
679                    scanned.binary_search(&name).is_ok(),
680                    expected,
681                    "needle {needle:?} on {hay:?}"
682                );
683            }
684        }
685    }
686
687    #[test]
688    fn gate_needles_cover_member_and_owner_class() {
689        // A regular member (non-constructor) gates on both the member name
690        // and the owner's short name — a call site may name only one.
691        let n = reference_gate_needles(&crate::Name::method("App\\Job", "run"));
692        assert!(n.contains(&"run".to_string()) && n.contains(&"Job".to_string()));
693        let n = reference_gate_needles(&crate::Name::class("App\\Ui\\Color"));
694        assert_eq!(n, vec!["Color".to_string()]);
695        // Unknown-owner member symbols still gate on the member name alone.
696        let n = reference_gate_needles(&crate::Name::method("", "run"));
697        assert_eq!(n, vec!["run".to_string()]);
698    }
699
700    #[test]
701    fn gate_needles_for_constructor_scope_to_owner_class_only() {
702        // `__construct` is only ever spelled at `new Cls(`/`parent::__construct()`
703        // sites, which always name the class — the bare method-name needle is
704        // dropped so a cold constructor query doesn't admit nearly every file
705        // in the workspace (every class defines *some* `__construct`).
706        let n = reference_gate_needles(&crate::Name::method("App\\Job", "__construct"));
707        assert_eq!(n, vec!["Job".to_string()]);
708        // Unknown owner: nothing to scope to, fall back to the bare name.
709        let n = reference_gate_needles(&crate::Name::method("", "__construct"));
710        assert_eq!(n, vec!["__construct".to_string()]);
711    }
712
713    fn session_with(files: &[(&str, &str)]) -> crate::AnalysisSession {
714        let mut session = crate::AnalysisSession::new(crate::PhpVersion::LATEST);
715        for (path, text) in files {
716            session.set_file_text(Arc::from(*path), Arc::from(*text));
717        }
718        session
719    }
720
721    #[test]
722    fn gate_static_method_is_member_name_only() {
723        // Regardless of subtypes: the member token alone is the sound gate
724        // (an instance receiver `$obj::m()` never names the owner), and it
725        // is also the selective part — the owner short name would only
726        // widen the admitted set.
727        let session = session_with(&[
728            (
729                "owner.php",
730                "<?php\nclass Owner { public static function m(): void {} }\n",
731            ),
732            ("sub.php", "<?php\nclass Sub extends Owner {}\n"),
733        ]);
734        let gate = session
735            .snapshot()
736            .reference_gate(&crate::Name::method("Owner", "m"));
737        assert_eq!(gate.idents, vec!["m".to_string()]);
738        assert!(gate.raw.is_empty());
739    }
740
741    #[test]
742    fn gate_instance_method_is_member_name_only() {
743        let session = session_with(&[(
744            "owner.php",
745            "<?php\nclass Owner { public function m(): void {} }\n",
746        )]);
747        let gate = session
748            .snapshot()
749            .reference_gate(&crate::Name::method("Owner", "m"));
750        assert_eq!(gate.idents, vec!["m".to_string()]);
751        assert!(gate.raw.is_empty());
752    }
753
754    #[test]
755    fn gate_invoke_keeps_owner_needle() {
756        let session = session_with(&[(
757            "owner.php",
758            "<?php\nclass Owner { public function __invoke(): void {} }\n",
759        )]);
760        let gate = session
761            .snapshot()
762            .reference_gate(&crate::Name::method("Owner", "__invoke"));
763        assert_eq!(
764            gate.idents,
765            reference_gate_needles(&crate::Name::method("Owner", "__invoke"))
766        );
767        assert!(gate.raw.is_empty());
768    }
769
770    #[test]
771    fn gate_constructor_adds_raw_call_tokens() {
772        // Owner short name for `new Cls(` sites, plus the raw call tokens
773        // for explicit re-init (`$obj->__construct()`) whose file may never
774        // name the class. The bare identifier `__construct` must NOT be a
775        // needle — it would admit every file declaring a constructor.
776        let session = session_with(&[(
777            "owner.php",
778            "<?php\nclass Owner { public function __construct() {} }\n",
779        )]);
780        let gate = session
781            .snapshot()
782            .reference_gate(&crate::Name::method("Owner", "__construct"));
783        assert_eq!(
784            gate.idents,
785            reference_gate_needles(&crate::Name::method("Owner", "__construct"))
786        );
787        assert_eq!(
788            gate.raw,
789            vec!["->__construct".to_string(), "::__construct".to_string()]
790        );
791    }
792
793    #[test]
794    fn gate_unresolvable_owner_falls_back_to_general_needles() {
795        let session = session_with(&[(
796            "owner.php",
797            "<?php\nclass Owner { public static function m(): void {} }\n",
798        )]);
799        let gate = session
800            .snapshot()
801            .reference_gate(&crate::Name::method("Nonexistent\\Missing", "m"));
802        assert_eq!(
803            gate.idents,
804            reference_gate_needles(&crate::Name::method("Nonexistent\\Missing", "m"))
805        );
806        assert!(gate.raw.is_empty());
807    }
808}