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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
use std::sync::Arc;
use super::*;
impl AnalysisSession {
/// Open-file diagnostics entrypoint for issue-only consumers.
///
/// Updates the session's current text for `file`, reuses the tracked parse
/// and definition queries for syntax/collector diagnostics, then runs the
/// targeted open-file body-analysis path without retaining whole-file
/// `ResolvedSymbol` payloads.
pub fn analyze_file_diagnostics(&mut self, file: &str, source: &str) -> crate::FileAnalysis {
let file: Arc<str> = Arc::from(file);
self.ingest_file(file.clone(), Arc::from(source));
// Body analysis can load classes, a write that would wait forever on
// a db handle still alive here.
let (mut issues, parsed) = {
let view = self.db_view();
let db = view.db();
let Some(sf) = db.lookup_source_file(file.as_ref()) else {
return crate::FileAnalysis {
issues: Vec::new(),
symbols: Vec::new(),
};
};
let defs = crate::db::collect_file_definitions(db, sf);
let prepared = crate::db::prepare_analysis_file(db, sf);
let parsed = (!prepared.has_hard_parse_errors)
.then(|| (prepared.text.clone(), prepared.parsed.0.clone()));
(Arc::unwrap_or_clone(defs.issues.clone()), parsed)
};
if let Some((text, parsed)) = parsed {
let analysis = crate::FileAnalyzer::new(self).analyze_diagnostics_only(
file.clone(),
text.as_ref(),
&parsed.program,
&parsed.source_map,
);
issues.extend(analysis.issues);
}
self.apply_suppressions_and_emit_unused(&mut issues, std::slice::from_ref(&file));
crate::FileAnalysis {
issues,
symbols: Vec::new(),
}
}
/// Resolve the codebase-level symbol name at `byte_offset` in `file`.
///
/// The identity half of [`Self::symbol_at`], for consumers that only need
/// a [`crate::Name`] to feed [`Self::definition_of`] or
/// [`Self::indexed_references_to`].
pub fn name_at(&mut self, file: &str, byte_offset: u32) -> Option<crate::Name> {
crate::FileAnalyzer::new(self).name_at(Arc::from(file), byte_offset)
}
/// Calls inside the function or method whose declaration contains
/// `byte_offset` in `file`, as `(callee, call-site name range)` in source
/// order. Callees are resolved [`crate::Name`]s — a trait alias reports
/// the original method, `parent::`/`self::` the declaring class — so the
/// result feeds [`Self::definition_of`] and [`Self::indexed_references_to`]
/// directly. Calls in nested closures belong to the enclosing function.
/// `new Foo` is a class reference, not reported. Empty when the offset is
/// outside a function or method body.
pub fn outgoing_calls(
&mut self,
file: &str,
byte_offset: u32,
) -> Vec<(crate::Name, crate::Range)> {
crate::FileAnalyzer::new(self).outgoing_calls(Arc::from(file), byte_offset)
}
/// Every occurrence of the local variable or parameter under
/// `byte_offset` in `file`, in source order, as name ranges including the
/// `$`. An occurrence belongs to the variable when it binds to the same
/// declaration: nested functions and closures start a new scope, except
/// where a closure captures the variable with `use`; arrow functions share
/// the enclosing scope except for their own parameters. Empty when the
/// offset is not on a variable. Powers document highlight and local
/// rename.
pub fn variable_references(&mut self, file: &str, byte_offset: u32) -> Vec<crate::Range> {
crate::FileAnalyzer::new(self).variable_references(Arc::from(file), byte_offset)
}
/// Resolve the symbol at `byte_offset` in `file`'s current ingested text.
///
/// Answers the same as [`crate::FileAnalysis::symbol_at`] without the
/// caller retaining a whole-file symbol list: the containing scope is
/// re-analyzed on demand and only its symbol payload is searched.
///
/// **Side effects:** may fault in direct dependencies of `file` by running
/// the open-file warm-up path (`prepare_file_for_analysis`).
pub fn symbol_at(&mut self, file: &str, byte_offset: u32) -> Option<crate::ResolvedSymbol> {
crate::FileAnalyzer::new(self).symbol_at(Arc::from(file), byte_offset)
}
/// Resolve a top-level symbol (class or function) to its declaration
/// location. Powers go-to-definition.
///
/// **Side effects:** ingests the file defining the symbol's class if the
/// symbol index lacks it. [`Self::definition_of_cached`] answers the same
/// without writing inputs.
///
/// Returns:
/// - `Ok(Location)` — symbol found with a source location
/// - `Err(NotFound)` — no such symbol in the codebase
/// - `Err(NoSourceLocation)` — symbol exists but has no recorded span
/// (e.g. some stub-only declarations)
pub fn definition_of(
&mut self,
symbol: &crate::Name,
) -> Result<mir_types::Location, crate::SymbolLookupError> {
self.load_symbol_owner(symbol);
self.definition_of_cached(symbol)
}
/// Ingest the file defining the class (or function) `symbol` is rooted
/// in, so the symbol index holds it. No-op when indexed.
fn load_symbol_owner(&mut self, symbol: &crate::Name) {
match symbol {
crate::Name::Class(fqn) | crate::Name::Function(fqn) => {
let _ = self.load_class(fqn.as_ref());
}
crate::Name::Method { class, .. }
| crate::Name::Property { class, .. }
| crate::Name::ClassConstant { class, .. } => {
let _ = self.load_class(class.as_ref());
}
crate::Name::GlobalConstant(_) => {}
}
}
/// Pure variant of [`Self::definition_of`]: never writes salsa inputs.
/// Symbols the index lacks load on demand through the resolver and
/// [`crate::SourceProvider`] as pure reads.
pub fn definition_of_cached(
&self,
symbol: &crate::Name,
) -> Result<mir_types::Location, crate::SymbolLookupError> {
self.query_snapshot(|snap| snap.definition_of_cached(symbol))
}
/// See [`AnalysisSnapshot::implemented_method`].
pub fn implemented_method(&self, method: &crate::Name) -> Option<crate::Name> {
self.query_snapshot(|snap| snap.implemented_method(method))
}
/// Raw reference locations indexed by string symbol key, kept for tests
/// that use the string-keyed API. Prefer [`Self::indexed_references_to`]
/// with a typed [`crate::Name`].
#[doc(hidden)]
pub fn reference_locations(&self, symbol: &str) -> Vec<(Arc<str>, u32, u16, u16)> {
use crate::db::MirDatabase;
let db = self.snapshot_db();
db.reference_locations(symbol)
}
/// Files declaring transitive subclasses of `class_fqn`, backed by the
/// maintained subtype index (see [`Self::indexed_subtype_classes`]).
/// Excludes `class_fqn`'s own declaring file — the caller adds it.
///
/// Lets a reference-search caller scope a `protected` member to its class
/// hierarchy without reconstructing that hierarchy from declaration text:
/// subclasses are matched by resolved FQCN, so `extends \Ns\Base` and
/// aliased `use` forms are all found. Read-only from the caller's
/// perspective; may trigger an on-demand commit of stale/uncommitted
/// candidates' class edges (same self-heal `indexed_subtype_classes` uses).
/// `include_trait_users` also counts classes that `use` the trait.
pub fn subtype_files(&mut self, class_fqn: &str, include_trait_users: bool) -> Vec<Arc<str>> {
self.prepare_for_query(None);
self.query_snapshot(|snap| snap.subtype_files(class_fqn, include_trait_users))
}
/// Compatibility wrapper for callers that only want `use` import items.
/// Delegates to [`Self::indexed_references_to`] so import references share
/// the same freshness/self-heal path, scope filtering, and memoization
/// boundary as every other reference query.
pub fn indexed_use_import_locations(
&mut self,
symbol: &crate::Name,
files: &[Arc<str>],
) -> Vec<(Arc<str>, crate::Range)> {
self.indexed_references_to(
symbol,
files,
false,
crate::ReferenceIncludes::UseImports,
&|| false,
)
.unwrap_or_default()
}
/// See [`AnalysisSnapshot::indexed_references_to`]. Unlike the snapshot
/// form, this runs the owner-side warm-up for stale candidates first, so
/// every one of them is analyzed with its referenced classes loaded.
///
/// `should_cancel` is polled at phase boundaries and between stale
/// candidates; `true` aborts with `None`, as does an index settle that
/// snapshot readers keep feeding past its round cap.
pub fn indexed_references_to(
&mut self,
symbol: &crate::Name,
files: &[Arc<str>],
include_declaration: bool,
includes: crate::ReferenceIncludes,
should_cancel: &(dyn Fn() -> bool + Sync),
) -> Option<Vec<(Arc<str>, crate::Range)>> {
// Settling can move the generation, which turns commits with
// unresolved names stale, so it runs before both the memo probe and
// the stale set.
if self.db.salsa.needs_index_settle()
&& !self.settle_workspace_index_cancellable(should_cancel)
{
return None;
}
// No `should_cancel()` check before the memo probe: a hit does no
// analysis work, and some callers count probe invocations to prove
// a warm query needed no re-analysis.
let key = {
let snap = self.db_view();
let key = snap.reference_query_key(symbol, files, include_declaration, includes);
if let Some(hit) = self.index.ref_queries.get(&key) {
return Some(hit);
}
key
};
if should_cancel() {
return None;
}
let stale = self
.db_view()
.stale_reference_candidates_unguarded(symbol, files);
if !stale.is_empty() {
if !self.prepare_stale_candidates(&stale, should_cancel) {
return None;
}
self.query_snapshot(|snap| snap.commit_reference_candidates(&stale));
}
if include_declaration {
self.load_symbol_owner(symbol);
}
let snap = self.db_view();
let out = snap.read_references(symbol, files, include_declaration, includes);
snap.memoize_references(key, &out);
Some(out)
}
/// Owner-side prelude for [`AnalysisSnapshot::indexed_references_to`]:
/// the warm-up [`Self::indexed_references_to`] runs before reading, so a
/// snapshot taken afterwards analyzes every stale candidate with its
/// dependencies loaded.
///
/// `stale` is [`AnalysisSnapshot::stale_reference_candidates`], computed
/// on a snapshot *before* the host takes its lock to call this: that scan
/// is O(candidates) and, on a cold workspace, scans file text, so it must
/// not run under the lock. Only the stale files are prepared (not every
/// candidate), the workspace index is settled when it has pending work,
/// and with `include_declaration` the file declaring `symbol` is loaded.
/// With nothing stale and nothing pending this is a no-op. A file that
/// went stale after `stale` was computed is analyzed without the warm-up,
/// as it would be without this call. `false` when `should_cancel` stopped
/// it first.
pub fn prepare_references_query(
&mut self,
symbol: &crate::Name,
stale: &[Arc<str>],
include_declaration: bool,
should_cancel: &(dyn Fn() -> bool + Sync),
) -> bool {
if self.db.salsa.needs_index_settle()
&& !self.settle_workspace_index_cancellable(should_cancel)
{
return false;
}
if !self.prepare_stale_candidates(stale, should_cancel) {
return false;
}
if include_declaration {
self.load_symbol_owner(symbol);
}
true
}
/// Class-load warm-up for `stale`, with revision bumps coalesced. The
/// bump scope closes before the caller's commit view captures its
/// generation.
fn prepare_stale_candidates(
&mut self,
stale: &[Arc<str>],
should_cancel: &(dyn Fn() -> bool + Sync),
) -> bool {
{
let mut session = self.defer_revision_bumps();
for path in stale {
if !session.prepare_file_for_analysis_cancellable(path, should_cancel) {
return false;
}
}
}
!should_cancel()
}
/// The symbol's declaration site, narrowed from the collector's
/// whole-declaration span to the declared name's own token (matching the
/// span shape of recorded references).
pub fn declaration_name_range(
&mut self,
symbol: &crate::Name,
) -> Option<(Arc<str>, crate::Range)> {
self.load_symbol_owner(symbol);
self.db_view().declaration_name_range(symbol)
}
/// See [`AnalysisSnapshot::indexed_subtype_classes`].
pub fn indexed_subtype_classes(
&mut self,
class_fqn: &str,
files: &[Arc<str>],
include_trait_users: bool,
) -> Vec<SubtypeClassSite> {
self.prepare_for_query(None);
self.query_snapshot(|snap| {
snap.indexed_subtype_classes(class_fqn, files, include_trait_users)
})
}
/// See [`AnalysisSnapshot::indexed_direct_subtype_classes`].
pub fn indexed_direct_subtype_classes(
&mut self,
class_fqn: &str,
files: &[Arc<str>],
include_trait_users: bool,
) -> Vec<SubtypeClassSite> {
self.prepare_for_query(None);
self.query_snapshot(|snap| {
snap.indexed_direct_subtype_classes(class_fqn, files, include_trait_users)
})
}
/// See [`AnalysisSnapshot::indexed_method_implementations`].
pub fn indexed_method_implementations(
&mut self,
class_fqn: &str,
method: &str,
files: &[Arc<str>],
) -> Vec<(Arc<str>, Arc<str>, crate::Range)> {
self.prepare_for_query(None);
self.query_snapshot(|snap| snap.indexed_method_implementations(class_fqn, method, files))
}
/// See [`AnalysisSnapshot::class_issues`]. Call this after ingesting or
/// re-analyzing a file and its dependents to get the full diagnostic
/// picture.
pub fn class_issues(&mut self, files: &[Arc<str>]) -> Vec<crate::Issue> {
self.prepare_for_query(None);
self.query_snapshot(|snap| snap.class_issues(files))
}
/// See [`AnalysisSnapshot::collector_issues`]. Correct regardless of
/// which path put the file's text into the db (`ingest_file`,
/// `set_file_text`, lazy vendor load) or how many times.
pub fn collector_issues(&self, files: &[Arc<str>]) -> Vec<crate::Issue> {
self.query_snapshot(|snap| snap.collector_issues(files))
}
/// All declarations defined in `file` as a **hierarchical tree**.
///
/// Classes/interfaces/traits/enums are returned with their methods,
/// properties, and constants nested in `children`. Top-level functions
/// and constants are returned with empty `children`.
pub fn document_symbols(&self, file: &str) -> Vec<crate::symbol::DocumentSymbol> {
use crate::symbol::{DeclarationKind, DocumentSymbol};
let db = self.snapshot_db();
let Some(sf) = db.lookup_source_file(file) else {
return Vec::new();
};
let defs = crate::db::collect_file_definitions(&db, sf);
let mut out: Vec<DocumentSymbol> = Vec::new();
let class_children = |methods: &mir_codebase::definitions::MemberMap<
Arc<mir_codebase::definitions::MethodDef>,
>,
props: Option<
&mir_codebase::definitions::MemberMap<mir_codebase::definitions::PropertyDef>,
>,
consts: &mir_codebase::definitions::MemberMap<
mir_codebase::definitions::ConstantDef,
>,
is_enum: bool|
-> Vec<DocumentSymbol> {
let mut out: Vec<DocumentSymbol> = Vec::new();
for (_, m) in methods.iter() {
out.push(DocumentSymbol {
name: m.name.clone(),
kind: DeclarationKind::Method,
location: m.location.clone(),
children: Vec::new(),
});
}
if let Some(props) = props {
for (_, p) in props.iter() {
out.push(DocumentSymbol {
name: p.name.clone(),
kind: DeclarationKind::Property,
location: p.location.clone(),
children: Vec::new(),
});
}
}
let const_kind = if is_enum {
DeclarationKind::EnumCase
} else {
DeclarationKind::Constant
};
for (_, c) in consts.iter() {
out.push(DocumentSymbol {
name: c.name.clone(),
kind: const_kind,
location: c.location.clone(),
children: Vec::new(),
});
}
out
};
for c in defs.slice.classes.iter() {
out.push(DocumentSymbol {
name: c.fqcn.clone(),
kind: DeclarationKind::Class,
location: c.location.clone(),
children: class_children(
&c.own_methods,
Some(&c.own_properties),
&c.own_constants,
false,
),
});
}
for i in defs.slice.interfaces.iter() {
out.push(DocumentSymbol {
name: i.fqcn.clone(),
kind: DeclarationKind::Interface,
location: i.location.clone(),
children: class_children(&i.own_methods, None, &i.own_constants, false),
});
}
for t in defs.slice.traits.iter() {
out.push(DocumentSymbol {
name: t.fqcn.clone(),
kind: DeclarationKind::Trait,
location: t.location.clone(),
children: class_children(
&t.own_methods,
Some(&t.own_properties),
&t.own_constants,
false,
),
});
}
for e in defs.slice.enums.iter() {
let mut children = class_children(&e.own_methods, None, &e.own_constants, true);
for (_, case) in e.cases.iter() {
children.push(DocumentSymbol {
name: case.name.clone(),
kind: DeclarationKind::EnumCase,
location: case.location.clone(),
children: Vec::new(),
});
}
out.push(DocumentSymbol {
name: e.fqcn.clone(),
kind: DeclarationKind::Enum,
location: e.location.clone(),
children,
});
}
for f in defs.slice.functions.iter() {
out.push(DocumentSymbol {
name: f.fqn.clone(),
kind: DeclarationKind::Function,
location: f.location.clone(),
children: Vec::new(),
});
}
for (name, _) in defs.slice.constants.iter() {
out.push(DocumentSymbol {
name: name.clone(),
kind: DeclarationKind::Constant,
location: None,
children: Vec::new(),
});
}
out
}
}
/// A transitive subtype hit with its declaration name span, as returned by
/// [`AnalysisSession::indexed_subtype_classes`].
#[derive(Debug, Clone)]
pub struct SubtypeClassSite {
/// Display-form FQCN (no leading `\`).
pub fqcn: Arc<str>,
pub kind: crate::db::ClassLikeKind,
pub is_abstract: bool,
pub file: Arc<str>,
/// The declared name's own token (1-based line, 0-based char columns).
pub range: crate::Range,
}
/// Build a [`crate::Range`] on one line from mir's native coordinates
/// (1-based line, 0-based columns).
pub(super) fn span_range(line: u32, col_start: u32, col_end: u32) -> crate::Range {
crate::Range {
start: crate::Position {
line,
column: col_start,
},
end: crate::Position {
line,
column: col_end,
},
}
}
/// Char column of the first word-boundary occurrence of `needle` in `line`
/// at or after char column `min_col`. Columns are code points, matching the
/// collector's `Location` convention.
pub(super) fn identifier_char_col(
line: &str,
needle: &str,
min_col: usize,
case_insensitive: bool,
) -> Option<u32> {
if needle.is_empty() {
return None;
}
let is_ident = |c: char| c.is_ascii_alphanumeric() || c == '_';
let chars: Vec<char> = line.chars().collect();
let needle_chars: Vec<char> = needle.chars().collect();
let n = needle_chars.len();
if chars.len() < n {
return None;
}
for start in min_col..=chars.len().saturating_sub(n) {
let matches = chars[start..start + n]
.iter()
.zip(needle_chars.iter())
.all(|(a, b)| {
if case_insensitive {
a.eq_ignore_ascii_case(b)
} else {
a == b
}
});
if !matches {
continue;
}
let before_ok = start == 0 || !is_ident(chars[start - 1]);
let after = start + n;
let after_ok = after >= chars.len() || !is_ident(chars[after]);
if before_ok && after_ok {
return Some(start as u32);
}
}
None
}
/// Whether `hay` mentions `needle` as a whole identifier (ASCII word
/// boundaries; conservative near multibyte text). ASCII-case-insensitive:
/// PHP class, function, and method names are case-insensitive, so `new
/// COLOR()` must count as mentioning `Color`; for the case-sensitive kinds
/// (constants, properties) folding only widens the candidate superset.
///
/// Test-only semantic oracle: the production gates (references freshness,
/// subtype-BFS defs commit) answer this predicate through the persistent
/// `ClassMentionIndex`; the parity test below pins the scanner to these
/// exact boundary and case semantics.
#[cfg(test)]
fn mentions_identifier(hay: &str, needle: &str) -> bool {
let hay = hay.as_bytes();
let needle = needle.as_bytes();
let n = needle.len();
if n == 0 || hay.len() < n {
return false;
}
let is_ident = |b: u8| b.is_ascii_alphanumeric() || b == b'_';
let first = needle[0].to_ascii_lowercase();
for i in 0..=(hay.len() - n) {
if hay[i].to_ascii_lowercase() != first || !hay[i..i + n].eq_ignore_ascii_case(needle) {
continue;
}
if (i == 0 || !is_ident(hay[i - 1])) && (i + n == hay.len() || !is_ident(hay[i + n])) {
return true;
}
}
false
}
fn short(fqn: &str) -> &str {
fqn.rsplit('\\').next().unwrap_or(fqn)
}
/// A candidate-file admission predicate for `indexed_references_to`'s
/// freshness pass, chosen by [`ReferenceGate::for_symbol`]. A file is
/// admitted when its text mentions any of `idents` as a whole identifier
/// (word-bounded, ASCII-case-insensitive) OR contains any of `raw` as a
/// plain substring (ASCII-case-insensitive, no word bounds — used for
/// call-shaped tokens like `->__construct`). A file matching neither can
/// hold no posting for the symbol.
pub(super) struct ReferenceGate {
pub(super) idents: Vec<String>,
pub(super) raw: Vec<String>,
}
impl ReferenceGate {
/// Choose the candidate-admission gate for `symbol`.
///
/// For any known non-constructor/non-`__invoke` method, the member name
/// alone is the sound gate. Every posting-producing reference spells that
/// token: `$obj->m()`, `Owner::m()`, inherited `Sub::m()`,
/// `self::`/`static::`/`parent::m()`, callable strings/arrays, and trait
/// aliases (`orig as alias` records `orig`, alias calls record `alias`
/// plus the origin key). Dropping the owner short name matters on common
/// owner names (`User`, `Model`, `Widget`): otherwise a cold reference
/// query analyzes files that only type-hint the owner and cannot contain a
/// reference to the queried method. Dynamic member names (`$obj->$m()`)
/// produce no posting, so nothing is lost there.
///
/// For `__construct` with a known owner, the identifier needle is the
/// owner's short name (`new Cls(` sites never spell the member name and
/// the bare word `__construct` would admit every file *declaring* a
/// constructor), complemented by the raw call tokens `->__construct` /
/// `::__construct`: an explicit re-init `$obj->__construct()` is a real
/// recorded reference whose file may never name the class.
///
/// `__invoke` keeps the general owner/name gate because `$obj()` call sites
/// do not spell `__invoke`.
///
/// Everything else uses the general OR needles
/// ([`reference_gate_needles`]).
pub(super) fn for_symbol(db: &MirDbStorage, symbol: &crate::Name) -> Self {
if let crate::Name::Method { class, name } = symbol {
if name.as_ref() == "__construct" && !class.is_empty() {
return Self {
idents: reference_gate_needles(symbol),
raw: vec!["->__construct".to_string(), "::__construct".to_string()],
};
}
if name.as_ref() != "__construct" && name.as_ref() != "__invoke" && !class.is_empty() {
let here = crate::db::Fqcn::from_str(db, class.as_ref());
let is_static = crate::db::find_method_in_chain(db, here, name)
.map(|(_, m)| m.is_static)
.unwrap_or(false);
if is_static || crate::db::class_exists(db, class.as_ref()) {
return Self {
idents: vec![name.to_string()],
raw: Vec::new(),
};
}
}
}
Self {
idents: reference_gate_needles(symbol),
raw: Vec::new(),
}
}
}
/// Identifier words whose whole-word presence in a file's text is necessary
/// for the file to hold any posting [`AnalysisSession::indexed_references_to`]
/// can return for `symbol`. Member symbols include the owner class's short
/// name alongside the member name: `__construct` postings are recorded at
/// `new Cls(` sites, which never spell the member name.
fn reference_gate_needles(symbol: &crate::Name) -> Vec<String> {
let mut needles = match symbol {
crate::Name::Class(f) | crate::Name::Function(f) | crate::Name::GlobalConstant(f) => {
vec![short(f).to_string()]
}
// `__construct` is invoked only as `new Cls(...)`, `parent::__construct()`,
// or `self::__construct()`/`static::__construct()` from inside a
// subclass — every real call site textually names the class itself
// (directly, or via the enclosing subclass's own `extends`/`use`),
// never the bare word `__construct`. Gating on the class's short name
// alone is exact (no lost call sites) and, unlike the general member
// case, dropping the method-name needle here doesn't reintroduce a
// false negative. This matters: `__construct` is one of the most
// common tokens in any real codebase, so OR-ing it in as a needle
// admits nearly every file as a "must re-analyze" candidate on a
// cold query, defeating the gate's entire purpose for constructors.
crate::Name::Method { class, name } if name.as_ref() == "__construct" => {
if class.is_empty() {
// No class to scope to (owner unknown) — fall back to gating
// on the bare name, same as the general member case below.
vec![name.to_string()]
} else {
vec![short(class).to_string()]
}
}
crate::Name::Method { class, name }
| crate::Name::Property { class, name }
| crate::Name::ClassConstant { class, name } => {
let mut v = vec![name.to_string()];
if !class.is_empty() {
v.push(short(class).to_string());
}
v
}
};
// An empty needle can never match; dropping it keeps the "empty needle
// set disables the gate" contract at the call site conservative.
needles.retain(|n| !n.is_empty());
needles
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn mentions_identifier_is_case_insensitive_and_word_bounded() {
assert!(mentions_identifier("$this->save();", "save"));
assert!(mentions_identifier("new COLOR()", "Color"));
assert!(mentions_identifier("use App\\Color as Paint;", "color"));
assert!(!mentions_identifier("$this->saveAll();", "save"));
assert!(!mentions_identifier("return $unsaved;", "save"));
assert!(!mentions_identifier("no occurrence", "save"));
assert!(!mentions_identifier("anything", ""));
// Multibyte neighbors are conservatively treated as boundaries, and
// substring scans must not split codepoints.
assert!(!mentions_identifier("function xÉclairFoo() {}", "Éclair"));
assert!(mentions_identifier("implements Éclair {}", "Éclair"));
}
#[test]
fn mention_scanner_membership_equals_per_needle_scans() {
// The mention index is the sole implementation of the gates' textual
// predicate, so scanner membership must equal the reference
// per-needle predicate for every (hay, needle) pair — same boundary
// and case semantics.
use crate::db::MentionScanner;
use std::sync::Arc;
let universe = ["Color", "save", "ColorPicker", "Éclair", "C1", "_Wrap"];
let names: Vec<(mir_types::Name, bool)> = universe
.iter()
.map(|s| (mir_types::Name::new(s).ascii_lowercase(), false))
.collect();
let scanner = Arc::new(MentionScanner::build(1, names).unwrap());
let hays = [
"$this->save();",
"new COLOR()",
"use App\\Color as Paint;",
"$this->saveAll();",
"return $unsaved;",
"new ColorPicker(); Color::save();",
"function xÉclairFoo() {}",
"implements Éclair {}",
"colorsave savecolor color_save",
"class C1 extends _Wrap {}",
"",
];
for hay in hays {
let scanned = scanner.scan(hay);
for needle in universe {
let expected = mentions_identifier(hay, needle);
let name = mir_types::Name::new(needle).ascii_lowercase();
assert_eq!(
scanned.binary_search(&name).is_ok(),
expected,
"needle {needle:?} on {hay:?}"
);
}
}
}
#[test]
fn gate_needles_cover_member_and_owner_class() {
// A regular member (non-constructor) gates on both the member name
// and the owner's short name — a call site may name only one.
let n = reference_gate_needles(&crate::Name::method("App\\Job", "run"));
assert!(n.contains(&"run".to_string()) && n.contains(&"Job".to_string()));
let n = reference_gate_needles(&crate::Name::class("App\\Ui\\Color"));
assert_eq!(n, vec!["Color".to_string()]);
// Unknown-owner member symbols still gate on the member name alone.
let n = reference_gate_needles(&crate::Name::method("", "run"));
assert_eq!(n, vec!["run".to_string()]);
}
#[test]
fn gate_needles_for_constructor_scope_to_owner_class_only() {
// `__construct` is only ever spelled at `new Cls(`/`parent::__construct()`
// sites, which always name the class — the bare method-name needle is
// dropped so a cold constructor query doesn't admit nearly every file
// in the workspace (every class defines *some* `__construct`).
let n = reference_gate_needles(&crate::Name::method("App\\Job", "__construct"));
assert_eq!(n, vec!["Job".to_string()]);
// Unknown owner: nothing to scope to, fall back to the bare name.
let n = reference_gate_needles(&crate::Name::method("", "__construct"));
assert_eq!(n, vec!["__construct".to_string()]);
}
fn session_with(files: &[(&str, &str)]) -> crate::AnalysisSession {
let mut session = crate::AnalysisSession::new(crate::PhpVersion::LATEST);
for (path, text) in files {
session.set_file_text(Arc::from(*path), Arc::from(*text));
}
session
}
#[test]
fn gate_static_method_is_member_name_only() {
// Regardless of subtypes: the member token alone is the sound gate
// (an instance receiver `$obj::m()` never names the owner), and it
// is also the selective part — the owner short name would only
// widen the admitted set.
let session = session_with(&[
(
"owner.php",
"<?php\nclass Owner { public static function m(): void {} }\n",
),
("sub.php", "<?php\nclass Sub extends Owner {}\n"),
]);
let gate = session
.snapshot()
.reference_gate(&crate::Name::method("Owner", "m"));
assert_eq!(gate.idents, vec!["m".to_string()]);
assert!(gate.raw.is_empty());
}
#[test]
fn gate_instance_method_is_member_name_only() {
let session = session_with(&[(
"owner.php",
"<?php\nclass Owner { public function m(): void {} }\n",
)]);
let gate = session
.snapshot()
.reference_gate(&crate::Name::method("Owner", "m"));
assert_eq!(gate.idents, vec!["m".to_string()]);
assert!(gate.raw.is_empty());
}
#[test]
fn gate_invoke_keeps_owner_needle() {
let session = session_with(&[(
"owner.php",
"<?php\nclass Owner { public function __invoke(): void {} }\n",
)]);
let gate = session
.snapshot()
.reference_gate(&crate::Name::method("Owner", "__invoke"));
assert_eq!(
gate.idents,
reference_gate_needles(&crate::Name::method("Owner", "__invoke"))
);
assert!(gate.raw.is_empty());
}
#[test]
fn gate_constructor_adds_raw_call_tokens() {
// Owner short name for `new Cls(` sites, plus the raw call tokens
// for explicit re-init (`$obj->__construct()`) whose file may never
// name the class. The bare identifier `__construct` must NOT be a
// needle — it would admit every file declaring a constructor.
let session = session_with(&[(
"owner.php",
"<?php\nclass Owner { public function __construct() {} }\n",
)]);
let gate = session
.snapshot()
.reference_gate(&crate::Name::method("Owner", "__construct"));
assert_eq!(
gate.idents,
reference_gate_needles(&crate::Name::method("Owner", "__construct"))
);
assert_eq!(
gate.raw,
vec!["->__construct".to_string(), "::__construct".to_string()]
);
}
#[test]
fn gate_unresolvable_owner_falls_back_to_general_needles() {
let session = session_with(&[(
"owner.php",
"<?php\nclass Owner { public static function m(): void {} }\n",
)]);
let gate = session
.snapshot()
.reference_gate(&crate::Name::method("Nonexistent\\Missing", "m"));
assert_eq!(
gate.idents,
reference_gate_needles(&crate::Name::method("Nonexistent\\Missing", "m"))
);
assert!(gate.raw.is_empty());
}
}