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
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use arc_swap::ArcSwap;
use dashmap::{DashMap, DashSet};
use salsa::Setter;
use tower_lsp::lsp_types::{SemanticToken, Url};
use crate::ast::ParsedDoc;
use crate::autoload::Psr4Map;
use crate::db::analysis::AnalysisHost;
use crate::db::input::{FileText, Workspace, find_source_file};
use crate::file_index::FileIndex;
/// Upper bound on `parsed_cache` entries. Matched to the `lru = 2048` on
/// `parsed_doc` in `src/db/parse.rs` so the secondary Arc retention can't
/// pin more ASTs alive than salsa's memo already bounds. Exceeding this
/// triggers probabilistic eviction (see [`DocumentStore::insert_parsed_cache`]).
const PARSED_CACHE_CAP: usize = 2048;
pub struct DocumentStore {
/// Cached semantic tokens per document: (result_id, tokens).
/// Used to compute incremental deltas for `textDocument/semanticTokens/full/delta`.
/// Tokens are stored in an `Arc` so the delta-path lookup can hand the
/// previous snapshot back without cloning the inner Vec.
token_cache: DashMap<Url, (String, Arc<Vec<SemanticToken>>)>,
// ── Salsa-input storage ────────────────────────────────────────────────
// Phase E4: `DocumentStore` is now a pure salsa-input wrapper. Open-file
// state (live text, version token, parse-diagnostics cache) lives on
// `Backend` in its `open_files` map; the set of files tracked by salsa
// is exactly `source_files.keys()`.
/// Mutex — held briefly to clone the database for reads and to mutate
/// it for writes. Per-thread salsa state (`zalsa_local`) is `!Sync`,
/// which rules out `RwLock<AnalysisHost>`. Readers instead snapshot the
/// db (cheap — storage is `Arc<Zalsa>`) and run queries on the clone
/// with the lock released, giving real read/read parallelism. Writers
/// during an in-flight read bump the shared revision; the reader raises
/// `salsa::Cancelled` on its next query call and `snapshot_query` below
/// retries with a fresh snapshot.
host: Mutex<AnalysisHost>,
/// `Url -> FileText` lookup. One immortal `FileText` salsa input per unique
/// URI ever seen. Text edits mutate the existing handle; delete/reopen cycles
/// reuse it rather than allocating a new input each time.
file_texts: DashMap<Url, FileText>,
/// URIs that have been removed. Re-opening a deleted URI un-deletes it here
/// and reuses the existing `FileText` handle.
deleted_uris: DashSet<Url>,
/// G2: lock-free mirror of each `SourceFile`'s last-set text. Lets
/// `mirror_text` dedup repeated no-op updates (common during workspace
/// scan and `did_open` for already-indexed files) without taking
/// `host.lock()`. Updated inside the mutex whenever the salsa input is
/// set, so it is always consistent with the salsa revision for the
/// purposes of byte-equality comparison.
text_cache: DashMap<Url, Arc<str>>,
/// G3: cross-revision read-through cache for `parsed_doc`. Keyed on
/// `Url`, stored value is `(text_arc, Arc<ParsedDoc>)` — the text Arc
/// captured at parse time. On read, compare against `text_cache[uri]`
/// via `Arc::ptr_eq`; a match guarantees the cached ParsedDoc matches
/// the current salsa revision's text input, so the query can return
/// without snapshotting the db or invoking salsa at all. A miss
/// (different pointer, stale or absent entry) falls through to
/// `snapshot_query`. Self-evicts on text change — no writer-side
/// invalidation is required, which avoids the TOCTOU window where a
/// concurrent reader could re-insert a stale entry after a writer's
/// eviction.
///
/// Size-bounded at [`PARSED_CACHE_CAP`] — see `insert_parsed_cache`.
/// Without this bound, every workspace file read-through would pin
/// its bumpalo arena alive regardless of salsa's `lru = 2048` on the
/// `parsed_doc` memo.
parsed_cache: DashMap<Url, (Arc<str>, Arc<ParsedDoc>)>,
/// Cross-request read-through cache for a file's mir body analysis. Keyed
/// on `Url`, stored value is `(source_arc, Arc<FileAnalysis>)` — the source
/// Arc captured at analysis time. On read, compare against the current
/// `doc.source_arc()` via `Arc::ptr_eq`; a match means the cached analysis
/// matches the live content. A miss recomputes and overwrites, so the cache
/// self-evicts on edit (same discipline as `parsed_cache`).
///
/// `FileAnalysis` carries BOTH the issues consumed by diagnostics and the
/// per-expression `ResolvedSymbol`s consumed by position features (hover,
/// type-definition, completion, inlay hints). Retaining it means mir's
/// `FileAnalyzer::analyze` runs once per content revision instead of being
/// re-run (for diagnostics) and then re-derived in a weaker form (for
/// position queries). Bounded by the set of analyzed files (open files plus
/// their open dependents); explicitly evicted in [`DocumentStore::remove`].
analysis_cache: DashMap<Url, (Arc<str>, Arc<mir_analyzer::FileAnalysis>)>,
/// Cross-request cache for the whole-doc completion [`crate::type_map::TypeMap`]
/// (`TypeMap::from_doc_with_meta`). Unlike `analysis_cache`, validity is
/// purely per-file (the map reads only this doc plus PHPStorm meta), so the
/// entry needs no cross-file invalidation: it is fresh when its captured
/// source `Arc` is pointer-equal to the doc's current `source_arc()` and
/// the meta pointer is unchanged, self-evicting on any content/meta edit.
type_map_cache: DashMap<Url, (Arc<str>, usize, Arc<crate::type_map::TypeMap>)>,
/// Set to `true` when the set of tracked files changes (add or remove).
/// `sync_workspace_files` skips the collect/sort/compare path when this
/// is `false`, avoiding a mutex acquisition on every LSP request.
workspace_files_dirty: AtomicBool,
/// Workspace salsa input. Tracks the full set of `SourceFile`s that
/// participate in whole-program queries (`codebase`, `file_refs`).
/// Re-synced from `source_files` on demand by `sync_workspace_files`.
workspace: Workspace,
/// Shared PSR-4 namespace-to-path map. Shared with `Backend` via `Arc`
/// so updates from `initialized` (when composer.json is loaded) are
/// visible here without any additional wiring. `ArcSwap` makes reads
/// lock-free — a poisoned guard can no longer crash a request handler.
psr4: Arc<ArcSwap<Psr4Map>>,
/// mir-analyzer's `AnalysisSession` — owns the workspace MirDb, runs
/// Pass-2 analysis, and lazy-loads dependencies via PSR-4. Built lazily
/// on first use; rebuilt when PHP version changes.
analysis_session: Mutex<Option<(mir_analyzer::PhpVersion, Arc<mir_analyzer::AnalysisSession>)>>,
/// Cache directory shared with the workspace file-index cache. When set,
/// new `AnalysisSession`s are built with `with_cache_dir` so that stub
/// parsing results survive server restarts.
session_cache_dir: OnceLock<std::path::PathBuf>,
}
impl Default for DocumentStore {
fn default() -> Self {
Self::new()
}
}
impl DocumentStore {
pub fn new() -> Self {
let host = AnalysisHost::new();
let workspace = Workspace::new(
host.db(),
Arc::<[(Arc<str>, FileText)]>::from(Vec::new()),
mir_analyzer::PhpVersion::LATEST,
);
DocumentStore {
token_cache: DashMap::new(),
host: Mutex::new(host),
file_texts: DashMap::new(),
deleted_uris: DashSet::new(),
text_cache: DashMap::new(),
parsed_cache: DashMap::new(),
analysis_cache: DashMap::new(),
type_map_cache: DashMap::new(),
workspace_files_dirty: AtomicBool::new(true),
workspace,
psr4: Arc::new(ArcSwap::from_pointee(Psr4Map::empty())),
analysis_session: Mutex::new(None),
session_cache_dir: OnceLock::new(),
}
}
/// Set the directory used to persist stub-parse and analysis results across
/// server restarts. Must be called before the first `analysis_session` use;
/// subsequent calls are silently ignored (`OnceLock` semantics).
pub fn set_session_cache_dir(&self, dir: std::path::PathBuf) {
let _ = self.session_cache_dir.set(dir);
}
/// Get or build the `AnalysisSession` for the given PHP version. Rebuilds
/// when the version changes (e.g. user flipped config). The session owns
/// its own salsa db and AnalysisCache; lazy-loads vendor files via the
/// shared PSR-4 map.
pub fn analysis_session(
&self,
php_version: mir_analyzer::PhpVersion,
) -> Arc<mir_analyzer::AnalysisSession> {
let mut guard = self.analysis_session.lock().unwrap();
if let Some((cached_ver, session)) = guard.as_ref()
&& *cached_ver == php_version
{
return Arc::clone(session);
}
// Build a fresh session. Hand it the shared PSR-4 map so it can
// lazy-resolve `UndefinedClass` candidates without us having to mirror
// every vendor file upfront.
let resolver: Arc<dyn mir_analyzer::ClassResolver> = self.psr4.load_full();
let mut builder =
mir_analyzer::AnalysisSession::new(php_version).with_class_resolver(resolver);
if let Some(dir) = self.session_cache_dir.get() {
builder = builder.with_cache_dir(dir);
}
let session = Arc::new(builder);
session.ensure_all_stubs();
*guard = Some((php_version, Arc::clone(&session)));
session
}
/// Current PHP version tracked by the workspace input.
pub fn workspace_php_version(&self) -> mir_analyzer::PhpVersion {
self.with_host(|h| self.workspace.php_version(h.db()))
}
/// Return the `Arc<ArcSwap<Psr4Map>>` so callers can share it.
/// `Backend` clones this arc at construction time so writes
/// (e.g. loading composer.json on `initialized`) are immediately visible
/// to `lazy_load_psr4_imports` without extra plumbing.
pub fn psr4_arc(&self) -> Arc<ArcSwap<Psr4Map>> {
Arc::clone(&self.psr4)
}
/// Mirror a file's current text into the salsa layer. Creates the
/// `FileText` input on first sight, otherwise updates `text` on the
/// existing input (bumping the salsa revision so downstream queries
/// invalidate).
pub fn mirror_text(&self, uri: &Url, text: &str) {
// G2 fast path: compare against the lock-free text cache. When the
// new text byte-matches what we already mirrored, skip the host
// mutex entirely. Common during workspace scan + `did_open` for
// unchanged files, where most threads would otherwise serialise on
// `host.lock()` just to confirm a no-op.
if let Some(cached) = self.text_cache.get(uri)
&& **cached == *text
&& !self.deleted_uris.contains(uri)
&& self.file_texts.contains_key(uri)
{
return;
}
self.mirror_text_arc(uri, Arc::from(text))
}
/// Like [`mirror_text`] but takes an already-allocated `Arc<str>`.
///
/// Callers that already hold an `Arc<str>` (e.g. `index_from_doc` reusing
/// `ParsedDoc::source_arc()`) use this to avoid a second allocation and to
/// ensure `text_cache` and `parsed_cache` hold the same Arc pointer —
/// enabling `Arc::ptr_eq` validation in `get_parsed_cached`.
pub fn mirror_text_arc(&self, uri: &Url, text_arc: Arc<str>) {
if let Some(ft) = self.file_texts.get(uri).map(|e| *e) {
self.deleted_uris.remove(uri);
// Slow path: re-check inside the mutex. Salsa's `set_text`
// unconditionally bumps the revision, so every spurious setter
// invalidates every downstream query.
let mut host = self.host.lock().unwrap();
let current: Arc<str> = ft.text(host.db());
if *current == *text_arc {
drop(host);
self.text_cache.insert(uri.clone(), current);
return;
}
ft.set_text(host.db_mut()).to(text_arc.clone());
// Phase K2: any text change invalidates a previously-seeded
// cached index. Only bump the revision when a cached index is
// actually present — an unconditional set would cause two
// revision bumps per edit (one for text, one for cached_index),
// which needlessly cancels in-flight `file_index` queries on
// every keystroke.
if ft.cached_index(host.db()).is_some() {
ft.set_cached_index(host.db_mut()).to(None);
}
drop(host);
self.text_cache.insert(uri.clone(), text_arc);
// A content change to ANY file can invalidate cross-file analysis
// (mir resolves types/issues against other files). `cached_analysis`
// is validated only on a file's own `source_arc`, so a dependency
// edit wouldn't otherwise refresh an unchanged dependent's cached
// entry — drop the whole cache. Bounded by open files; recompute is
// ~6ms warm. Matches the salsa revision bump `set_text` just made.
self.analysis_cache.clear();
} else {
let is_vendor = uri.as_str().contains("/vendor/");
let ft = {
let mut host = self.host.lock().unwrap();
let ft = FileText::new(host.db(), text_arc.clone(), None);
if is_vendor {
// Vendor files never change in a session — mark their text
// as HIGH durability so salsa skips re-validating
// parsed_doc/file_index for them on every user edit.
ft.set_text(host.db_mut())
.with_durability(salsa::Durability::HIGH)
.to(Arc::clone(&text_arc));
}
ft
};
self.file_texts.insert(uri.clone(), ft);
self.text_cache.insert(uri.clone(), text_arc);
self.workspace_files_dirty.store(true, Ordering::Release);
// A newly-ingested file may resolve references that were previously
// unresolved in already-analyzed files; invalidate cross-file caches.
self.analysis_cache.clear();
}
}
/// Return the `FileText` handle for a URL, if active (not deleted).
#[cfg(test)]
pub fn source_file(&self, uri: &Url) -> Option<FileText> {
if self.deleted_uris.contains(uri) {
return None;
}
self.file_texts.get(uri).map(|e| *e)
}
/// Phase K2: pre-seed a `FileIndex` loaded from the on-disk cache onto
/// the `FileText` input for `uri`. The next `file_index` call for that
/// file returns the cached index directly, skipping parse + extract.
///
/// Must be called **before** any `file_index(db, sf)` call for this file —
/// otherwise salsa has already memoized the fresh-parse result and setting
/// `cached_index` now would only bump the revision without using the cache.
/// In practice the workspace-scan path seeds immediately after `mirror_text`
/// and before any query runs.
///
/// Returns `false` when `uri` was not mirrored (caller should mirror
/// first); returns `true` on success.
pub fn seed_cached_index(&self, uri: &Url, index: Arc<FileIndex>) -> bool {
let Some(ft) = self.file_texts.get(uri).map(|e| *e) else {
return false;
};
let mut host = self.host.lock().unwrap();
ft.set_cached_index(host.db_mut()).to(Some(index));
true
}
/// Run `f` with a borrow of the `AnalysisHost`. Used by tests and by the
/// upcoming `*_salsa` accessors to query the salsa layer.
pub fn with_host<R>(&self, f: impl FnOnce(&AnalysisHost) -> R) -> R {
let host = self.host.lock().unwrap();
f(&host)
}
/// Phase E1: take a brief lock, clone the salsa database, release the
/// lock. Queries then run on the cloned `RootDatabase` without blocking
/// writers or other readers. Salsa's `Storage<Self>` is reference-counted
/// (`Arc<Zalsa>`), so the clone is cheap — it shares memoized data and
/// the cancellation flag with the host's db.
fn snapshot_db(&self) -> crate::db::analysis::RootDatabase {
let host = self.host.lock().unwrap();
host.db().clone()
}
/// Run a query on a fresh snapshot, catching `salsa::Cancelled` (raised
/// when a concurrent writer advances the revision) and retrying with a
/// new snapshot. Writers hold the mutex only long enough to bump input
/// values, so a handful of retries is more than enough in practice; we
/// cap at 8 to avoid pathological livelock under sustained write pressure.
fn snapshot_query<R>(&self, f: impl Fn(&crate::db::analysis::RootDatabase) -> R + Clone) -> R {
use std::panic::AssertUnwindSafe;
for _ in 0..8 {
let db = self.snapshot_db();
let f = f.clone();
match salsa::Cancelled::catch(AssertUnwindSafe(move || f(&db))) {
Ok(r) => return r,
Err(_) => continue,
}
}
// Last-resort attempt: take the mutex for the whole query so no
// writer can race us. Much slower, but guaranteed to make progress.
let host = self.host.lock().unwrap();
f(host.db())
}
/// Evict the semantic-tokens cache for `uri`. Called by Backend when a
/// file is closed; diff-based tokens computed against the old revision
/// are no longer meaningful.
pub fn evict_token_cache(&self, uri: &Url) {
self.token_cache.remove(uri);
}
/// Return the `FileIndex` for `uri` by running `file_index` on a salsa
/// snapshot. Returns `None` when `uri` has not been mirrored.
///
/// Test-only — production code uses the salsa query directly via
/// `snapshot_query`.
#[cfg(test)]
pub fn source_files_len(&self) -> usize {
self.file_texts.len()
}
#[cfg(test)]
pub fn snapshot_query_file_index(&self, uri: &Url) -> Option<crate::file_index::FileIndex> {
if self.deleted_uris.contains(uri) {
return None;
}
if !self.file_texts.contains_key(uri) {
return None;
}
self.sync_workspace_files();
let uri_str: Arc<str> = Arc::from(uri.as_str());
let ws = self.workspace;
self.snapshot_query(move |db| {
let sf = find_source_file(db, ws, &uri_str)?;
Some(crate::db::index::file_index(db, sf).get().clone())
})
}
/// Register a file in the salsa layer without marking it open.
///
/// Salsa's `parsed_doc` query parses lazily on first read; diagnostics
/// are populated by `did_open` when the editor actually opens the file.
pub fn index(&self, uri: Url, text: &str) {
self.mirror_text(&uri, text);
}
/// Index a file using an already-parsed `ParsedDoc`, avoiding a second parse.
///
/// Prefer this over [`index`] when the caller already has a `ParsedDoc` (e.g.
/// after running `DefinitionCollector` during workspace scan). Reuses the
/// `Arc<str>` already owned by `doc` so that `text_cache` and `SourceFile::text`
/// share the same pointer — enabling the `Arc::ptr_eq` fast path in
/// `get_parsed_cached` on the first subsequent salsa query, without an extra
/// `Arc::from(source)` allocation.
pub fn index_from_doc(&self, uri: Url, doc: &ParsedDoc) {
self.mirror_text_arc(&uri, doc.source_arc());
}
pub fn remove(&self, uri: &Url) {
self.token_cache.remove(uri);
// Mark the URI as deleted but keep the `source_files` entry so the
// salsa `SourceFile` handle remains alive. Re-opening the file reuses
// the same handle instead of calling `SourceFile::new()` again, which
// would create a new orphaned salsa input on every delete-reopen cycle.
self.deleted_uris.insert(uri.clone());
self.workspace_files_dirty.store(true, Ordering::Release);
// Sync workspace files so the deleted file is removed from the salsa
// `Workspace::files` list and won't appear in workspace symbols etc.
self.sync_workspace_files();
self.text_cache.remove(uri);
self.parsed_cache.remove(uri);
self.analysis_cache.remove(uri);
self.type_map_cache.remove(uri);
// Also evict the file from the `AnalysisSession`'s internal state so
// workspace symbol queries don't keep returning the deleted file's
// declarations. Cheap when the session hasn't ingested this file.
let guard = self.analysis_session.lock().unwrap();
if let Some((_, session)) = guard.as_ref() {
session.invalidate_file(uri.as_str());
}
}
// ── Salsa-backed accessors ─────────────────────────────────────────────
//
// Reads run the memoized `parsed_doc` / `file_index` queries, parsing
// only on first access per revision. These are the production accessors
// used by every handler.
/// Salsa-backed parsed document.
///
/// Salsa-backed parsed document for any mirrored file (open or
/// background-indexed). Returns `None` only when the file is not known
/// to the store. Callers that want "only if open" should gate on
/// `Backend::open_files` at the call site (see `Backend::get_doc`).
pub fn get_doc_salsa(&self, uri: &Url) -> Option<Arc<ParsedDoc>> {
self.get_parsed_cached(uri)
}
/// Salsa-backed compact symbol index.
pub fn get_index_salsa(&self, uri: &Url) -> Option<Arc<FileIndex>> {
if self.deleted_uris.contains(uri) {
return None;
}
if !self.file_texts.contains_key(uri) {
return None;
}
self.sync_workspace_files();
let uri_str: Arc<str> = Arc::from(uri.as_str());
let ws = self.workspace;
self.snapshot_query(move |db| {
let sf = find_source_file(db, ws, &uri_str)?;
Some(crate::db::index::file_index(db, sf).0.clone())
})
}
/// Salsa-backed pre-computed symbol map (name → Vec<SymbolEntry>).
/// Memoized per revision: stable files serve from cache in O(1).
pub fn get_symbol_map_salsa(&self, uri: &Url) -> Option<Arc<crate::symbol_map::SymbolMap>> {
if self.deleted_uris.contains(uri) {
return None;
}
if !self.file_texts.contains_key(uri) {
return None;
}
self.sync_workspace_files();
let uri_str: Arc<str> = Arc::from(uri.as_str());
let ws = self.workspace;
self.snapshot_query(move |db| {
let sf = find_source_file(db, ws, &uri_str)?;
Some(crate::db::symbol_map::symbol_map(db, sf).0.clone())
})
}
/// Pre-computed symbol maps for every entry in `open_urls` except `uri`.
pub fn other_symbol_maps(
&self,
uri: &Url,
open_urls: &[Url],
) -> Vec<(Url, Arc<crate::symbol_map::SymbolMap>)> {
open_urls
.iter()
.filter(|u| *u != uri)
.filter_map(|u| self.get_symbol_map_salsa(u).map(|m| (u.clone(), m)))
.collect()
}
/// G3: shared implementation for `get_doc_salsa`.
/// Tries the `parsed_cache` (lock-free) first; validates via
/// `Arc::ptr_eq` against the G2 `text_cache` so a concurrent writer
/// that has already committed a new text input cannot be masked by a
/// stale cache entry. On miss, captures the text Arc and ParsedDoc
/// together inside a single `snapshot_query`, then publishes both.
fn get_parsed_cached(&self, uri: &Url) -> Option<Arc<ParsedDoc>> {
if let Some(current_text) = self.text_cache.get(uri)
&& let Some(entry) = self.parsed_cache.get(uri)
&& Arc::ptr_eq(&*current_text, &entry.0)
{
return Some(entry.1.clone());
}
if self.deleted_uris.contains(uri) {
return None;
}
if !self.file_texts.contains_key(uri) {
return None;
}
self.sync_workspace_files();
let uri_str: Arc<str> = Arc::from(uri.as_str());
let ws = self.workspace;
let (text, doc) = self.snapshot_query(move |db| {
let sf = find_source_file(db, ws, &uri_str)?;
let text = sf.text_input(db).text(db);
let doc = crate::db::parse::parsed_doc(db, sf).0.clone();
Some((text, doc))
})?;
self.insert_parsed_cache(uri.clone(), text, doc.clone());
Some(doc)
}
/// Publish a fresh `ParsedDoc` into `parsed_cache`, shedding roughly
/// half of the cache first if it has grown past [`PARSED_CACHE_CAP`].
///
/// Eviction is probabilistic (DashMap iteration order is arbitrary),
/// not LRU. That's fine — salsa's own `parsed_doc` memo uses
/// `lru = 2048` on hotness-aware storage, so a cache-miss here is
/// cheap: the next read goes through `snapshot_query` and
/// `parsed_doc`, which still short-circuits on the salsa memo.
/// What we're bounding here is the *secondary* Arc retention that
/// would otherwise pin every workspace file's bumpalo arena alive
/// regardless of salsa's eviction decisions.
fn insert_parsed_cache(&self, uri: Url, text: Arc<str>, doc: Arc<ParsedDoc>) {
if self.parsed_cache.len() >= PARSED_CACHE_CAP {
let drop_target = self.parsed_cache.len() / 2;
let mut dropped = 0usize;
self.parsed_cache.retain(|_, _| {
if dropped < drop_target {
dropped += 1;
false
} else {
true
}
});
}
self.parsed_cache.insert(uri, (text, doc));
}
/// Refresh `workspace.files` to mirror the current active file set.
///
/// Skips all work when `workspace_files_dirty` is `false` (the common
/// case after the workspace scan completes — file-set changes are rare).
pub fn sync_workspace_files(&self) {
// Atomically clear the flag. If it was already false the file set
// hasn't changed since the last sync; nothing to do.
if !self.workspace_files_dirty.swap(false, Ordering::AcqRel) {
return;
}
// Collect active (non-deleted) files without holding the host lock.
let mut files: Vec<(Arc<str>, FileText)> = self
.file_texts
.iter()
.filter(|e| !self.deleted_uris.contains(e.key()))
.map(|e| (Arc::<str>::from(e.key().as_str()), *e.value()))
.collect();
// Sort by URI string for stable ordering.
files.sort_unstable_by(|(a, _), (b, _)| a.cmp(b));
let mut host = self.host.lock().unwrap();
let current = self.workspace.files(host.db());
if current.len() == files.len()
&& current
.iter()
.zip(files.iter())
.all(|(a, b)| a.0 == b.0 && a.1 == b.1)
{
return;
}
self.workspace.set_files(host.db_mut()).to(Arc::from(files));
}
/// Mark the workspace file set as dirty so the next `sync_workspace_files`
/// call re-runs the collect/sort/compare path. Exposed for benchmarks that
/// need to measure the dirty-path cost in isolation.
pub fn mark_workspace_files_dirty(&self) {
self.workspace_files_dirty.store(true, Ordering::Release);
}
/// Update the PHP version tracked by the workspace. Salsa will invalidate
/// all `semantic_issues` queries so diagnostics are re-evaluated.
/// Skips the setter when the version hasn't changed to avoid spurious
/// query invalidation.
pub fn set_php_version(&self, version: mir_analyzer::PhpVersion) {
let mut host = self.host.lock().unwrap();
if self.workspace.php_version(host.db()) == version {
return;
}
self.workspace.set_php_version(host.db_mut()).to(version);
// The analysis_cache validates against source content only, so stale
// FileAnalysis results from the old PHP version would survive unchanged
// files. Clear it so the next request re-runs with the new version.
drop(host);
self.analysis_cache.clear();
}
/// Session-backed workspace reference lookup. Returns `(file, line, col)`
/// locations for every occurrence of `symbol` in the files that the
/// `AnalysisSession` has ingested so far. The session's reference index
/// is built incrementally during `ingest_file`, so refs for files the
/// session hasn't seen yet (background-indexed but never opened) won't
/// appear here — those are covered by the AST-walker fallback in the
/// references handler.
///
/// Returns LSP-style 0-based line/column.
pub fn session_references_to(
&self,
symbol: &mir_analyzer::Name,
) -> Vec<(Arc<str>, u32, u32, u32)> {
let php_version = self.workspace_php_version();
let session = self.analysis_session(php_version);
session
.references_to(symbol)
.into_iter()
.map(|(file, range)| {
// mir 0.30+ uses 1-based lines and 1-based columns; LSP uses 0-based.
let line = range.start.line.saturating_sub(1);
let col_start = range.start.column.saturating_sub(1);
let col_end = range.end.column.saturating_sub(1);
(file, line, col_start, col_end)
})
.collect()
}
/// Phase J: salsa-memoized aggregate workspace index.
///
/// Returns the shared `Arc<WorkspaceIndexData>` with flat
/// `(Url, Arc<FileIndex>)` list plus pre-built `classes_by_name` and
/// `subtypes_of` reverse maps. Used by workspace_symbols,
/// prepare_type_hierarchy, supertypes_of, subtypes_of, and
/// find_implementations so they don't each rebuild the aggregate per
/// request. Invalidates automatically when any file's `file_index`
/// changes.
pub fn get_workspace_index_salsa(&self) -> Arc<crate::db::workspace_index::WorkspaceIndexData> {
self.sync_workspace_files();
let ws = self.workspace;
self.snapshot_query(move |db| {
crate::db::workspace_index::workspace_index(db, ws)
.0
.clone()
})
}
/// No-op after mir 0.22 migration. The session manages its own warm-up
/// via `ingest_file` / `analyze_dependents_of`; there's nothing for us
/// to pre-warm here.
pub fn warm_reference_index(&self) {}
/// Return the raw source text for `uri` if it has been mirrored into the
/// salsa workspace. Used by the references handler to pre-filter session
/// results by checking whether a file mentions the owning class name.
pub fn source_text(&self, uri: &Url) -> Option<Arc<str>> {
self.text_cache.get(uri).map(|e| Arc::clone(&e))
}
/// Run Pass 1 + Pass 2 analysis on every mirrored workspace file so that
/// type-aware queries (e.g. `session.references_to`) see the full workspace.
///
/// Reference locations are only recorded during Pass 2 (`FileAnalyzer::analyze`).
/// `ingest_file` alone (Pass 1) is not sufficient. Only needed for cross-file
/// queries like `textDocument/references` that rely on the reference index.
/// The session's internal cache makes re-analysis of unchanged files cheap.
pub fn ensure_all_files_ingested(&self) {
let php_version = self.workspace_php_version();
let session = self.analysis_session(php_version);
let urls: Vec<Url> = self
.file_texts
.iter()
.filter(|e| !self.deleted_uris.contains(e.key()))
.map(|e| e.key().clone())
.collect();
for uri in &urls {
let Some(doc) = self.get_doc_salsa(uri) else {
continue;
};
let file: Arc<str> = Arc::from(uri.as_str());
session.ingest_file(file.clone(), doc.source_arc());
let source_map = php_rs_parser::source_map::SourceMap::new(doc.source());
let owned_program = php_ast::owned::to_owned_program(doc.program());
let analyzer = mir_analyzer::FileAnalyzer::new(&session);
analyzer.analyze(file, doc.source(), &owned_program, &source_map);
}
}
/// Cache the semantic tokens computed for a delta response.
/// `result_id` is an opaque string (a hash of the token data) returned to the client.
pub fn store_token_cache(&self, uri: &Url, result_id: String, tokens: Arc<Vec<SemanticToken>>) {
self.token_cache.insert(uri.clone(), (result_id, tokens));
}
/// Return the cached tokens if `result_id` matches the stored one.
pub fn get_token_cache(&self, uri: &Url, result_id: &str) -> Option<Arc<Vec<SemanticToken>>> {
self.token_cache
.get(uri)
.filter(|e| e.0.as_str() == result_id)
.map(|e| Arc::clone(&e.1))
}
/// Before running semantic analysis for `uri`, resolve every `use`-imported
/// class through the PSR-4 map and mirror any that are not yet registered.
/// This prevents spurious `UndefinedClass` diagnostics when the background
/// workspace scan has not yet reached a dependency file.
fn lazy_load_psr4_imports(&self, uri: &Url) {
let doc = match self.get_doc_salsa(uri) {
Some(d) => d,
None => return,
};
let fqns = crate::references::collect_referenced_class_fqns(&doc);
if fqns.is_empty() {
return;
}
let psr4 = self.psr4.load();
let paths: Vec<std::path::PathBuf> =
fqns.iter().filter_map(|fqcn| psr4.resolve(fqcn)).collect();
drop(psr4);
for path in paths {
let Ok(dep_url) = Url::from_file_path(&path) else {
continue;
};
if self.file_texts.contains_key(&dep_url) && !self.deleted_uris.contains(&dep_url) {
continue;
}
if let Ok(text) = std::fs::read_to_string(&path) {
self.mirror_text(&dep_url, &text);
}
}
}
/// Raw semantic issues for a file, computed via mir's session-based
/// `FileAnalyzer`. The session lazy-loads dependencies via PSR-4 so the
/// LSP no longer needs to mirror vendor up-front. Callers apply their
/// own `DiagnosticsConfig` filter via
/// [`crate::semantic_diagnostics::issues_to_diagnostics`].
#[tracing::instrument(skip_all)]
pub fn get_semantic_issues_salsa(&self, uri: &Url) -> Option<Arc<[mir_issues::Issue]>> {
let analysis = self.cached_analysis(uri)?;
let file: Arc<str> = Arc::from(uri.as_str());
// Workspace-level class issues for this file (circular inheritance,
// override violations, abstract-method gaps). These are session-wide
// (a dependency edit changes them without changing this file's bytes),
// so they are recomputed live rather than cached alongside the
// per-file body analysis.
let class_issues = {
let _s = tracing::debug_span!("session.class_issues_for").entered();
self.analysis_session(self.workspace_php_version())
.class_issues(std::slice::from_ref(&file))
};
let combined: Vec<mir_issues::Issue> = analysis
.issues
.iter()
.cloned()
.chain(class_issues)
.filter(|i| !i.suppressed)
.collect();
Some(Arc::from(combined))
}
/// Run (or reuse) mir's per-file body analysis, retaining the full
/// [`mir_analyzer::FileAnalysis`] — issues **and** resolved symbols — across
/// requests. Diagnostics read `.issues`; position features call
/// `.symbol_at(offset)` for the resolved type at a cursor.
///
/// Cache hit when the entry's captured source `Arc` is pointer-equal to the
/// file's current `doc.source_arc()`. A miss recomputes and overwrites, so
/// the entry self-evicts on any content edit.
/// Build (or reuse) the whole-doc completion [`crate::type_map::TypeMap`]
/// for `uri`. Cache hit when the entry's captured source `Arc` is
/// pointer-equal to `doc.source_arc()` and the PHPStorm-meta pointer is
/// unchanged (meta lives behind `ArcSwap`, so its address is stable until
/// `.phpstorm.meta.php` is reloaded). A miss rebuilds and overwrites, so
/// the entry self-evicts on any content edit.
pub fn cached_type_map(
&self,
uri: &Url,
doc: &crate::ast::ParsedDoc,
meta: Option<&crate::phpstorm_meta::PhpStormMeta>,
) -> Arc<crate::type_map::TypeMap> {
let source = doc.source_arc();
let meta_key = meta.map_or(0usize, |m| std::ptr::from_ref(m) as usize);
if let Some(entry) = self.type_map_cache.get(uri)
&& Arc::ptr_eq(&entry.0, &source)
&& entry.1 == meta_key
{
return Arc::clone(&entry.2);
}
let map = Arc::new(crate::type_map::TypeMap::from_doc_with_meta(doc, meta));
self.type_map_cache
.insert(uri.clone(), (source, meta_key, Arc::clone(&map)));
map
}
/// Cache-hit-only variant of [`Self::cached_analysis`]: returns the cached
/// analysis when the entry is current for the file's text, never computes.
/// Lets async handlers take the warm path synchronously and reserve
/// `spawn_blocking` for the cold path (mir Pass 1 + Pass 2 can take
/// hundreds of ms on large files).
pub fn cached_analysis_if_fresh(&self, uri: &Url) -> Option<Arc<mir_analyzer::FileAnalysis>> {
let doc = self.get_doc_salsa(uri)?;
let source = doc.source_arc();
let entry = self.analysis_cache.get(uri)?;
Arc::ptr_eq(&entry.0, &source).then(|| Arc::clone(&entry.1))
}
#[tracing::instrument(skip_all)]
pub fn cached_analysis(&self, uri: &Url) -> Option<Arc<mir_analyzer::FileAnalysis>> {
// Need the parsed doc both for the analyzer and as the cache key.
let doc = self.get_doc_salsa(uri)?;
let source = doc.source_arc();
if let Some(entry) = self.analysis_cache.get(uri)
&& Arc::ptr_eq(&entry.0, &source)
{
return Some(Arc::clone(&entry.1));
}
let php_version = self.with_host(|h| self.workspace.php_version(h.db()));
let session = self.analysis_session(php_version);
let file: Arc<str> = Arc::from(uri.as_str());
{
let _s = tracing::debug_span!("session.ingest_file").entered();
session.ingest_file(file.clone(), source.clone());
}
// Pre-load every imported class via PSR-4 so Pass-2 doesn't emit
// spurious `UndefinedClass` for classes that ARE on disk but haven't
// been ingested yet. The session's resolver was supplied at
// construction time.
{
let _s = tracing::debug_span!("session.lazy_load_imports").entered();
// Pre-load every class-typed reference resolved via the file's
// namespace + `use` imports. This covers `use` imports, FQN refs
// (`new \App\Foo`), and bare same-namespace refs (`new Foo` from
// inside `namespace App;`) in a single sweep — mir won't auto-
// resolve via the ClassResolver, so anything not lazy-loaded here
// produces a spurious `UndefinedClass`.
let fqns = crate::references::collect_referenced_class_fqns(&doc);
for fqcn in &fqns {
let _ = session.load_class(fqcn);
}
}
let source_map = php_rs_parser::source_map::SourceMap::new(doc.source());
let owned_program = php_ast::owned::to_owned_program(doc.program());
let analysis = {
let _s = tracing::debug_span!("FileAnalyzer::analyze").entered();
let analyzer = mir_analyzer::FileAnalyzer::new(&session);
Arc::new(analyzer.analyze(file.clone(), doc.source(), &owned_program, &source_map))
};
self.analysis_cache
.insert(uri.clone(), (source, Arc::clone(&analysis)));
Some(analysis)
}
/// Returns `(uri, doc)` for files currently open in the editor.
///
/// Resolve `open_urls` (from `Backend::open_urls()`) to parsed docs.
/// Files not mirrored in the salsa layer are filtered out silently.
pub fn docs_for(&self, open_urls: &[Url]) -> Vec<(Url, Arc<ParsedDoc>)> {
open_urls
.iter()
.filter_map(|u| self.get_doc_salsa(u).map(|d| (u.clone(), d)))
.collect()
}
/// `(primary, doc)` first, then every other open file's parsed doc.
/// The `open_urls` slice should include `uri` — this helper filters it out.
pub fn doc_with_others(
&self,
uri: &Url,
doc: Arc<ParsedDoc>,
open_urls: &[Url],
) -> Vec<(Url, Arc<ParsedDoc>)> {
let mut result = vec![(uri.clone(), doc)];
result.extend(self.other_docs(uri, open_urls));
result
}
/// Parsed docs for every entry in `open_urls` except `uri`.
pub fn other_docs(&self, uri: &Url, open_urls: &[Url]) -> Vec<(Url, Arc<ParsedDoc>)> {
open_urls
.iter()
.filter(|u| *u != uri)
.filter_map(|u| self.get_doc_salsa(u).map(|d| (u.clone(), d)))
.collect()
}
/// Compact symbol index for every mirrored file.
pub fn all_indexes(&self) -> Vec<(Url, Arc<FileIndex>)> {
self.get_workspace_index_salsa().files.clone()
}
/// Same as `all_indexes` but excludes `uri`.
pub fn other_indexes(&self, uri: &Url) -> Vec<(Url, Arc<FileIndex>)> {
self.get_workspace_index_salsa()
.files
.iter()
.filter(|(u, _)| u != uri)
.cloned()
.collect()
}
/// Parsed documents for every mirrored file (open or background-indexed).
/// Suitable for full-scan operations: find-references, rename,
/// call_hierarchy, code_lens.
pub fn all_docs_for_scan(&self) -> Vec<(Url, Arc<ParsedDoc>)> {
let urls: Vec<Url> = self
.file_texts
.iter()
.filter(|e| !self.deleted_uris.contains(e.key()))
.map(|e| e.key().clone())
.collect();
urls.into_iter()
.filter_map(|u| self.get_doc_salsa(&u).map(|d| (u, d)))
.collect()
}
}
/// Run `file_refs` for every workspace file in parallel.
///
/// `db` clones are cheap (they share the same `Arc<Zalsa>` memo store), so
/// results computed on any clone are immediately visible to all others at the
/// same revision. After this returns, the sequential loop inside `symbol_refs`
/// only does cheap memo lookups instead of running `StatementsAnalyzer` on
/// every file one-by-one.
///
/// Per-task `salsa::Cancelled` is caught and swallowed. If the revision was
/// bumped, the main thread's next salsa call inside `symbol_refs` will raise
/// `Cancelled` too and `snapshot_query` retries the whole operation from
/// scratch. If the revision was not bumped, any file whose task was cancelled
/// before completion simply has no memo entry and `symbol_refs`'s sequential
/// loop recomputes it.
// `warm_file_refs_parallel` removed: the analyzer-side reference index is
// now owned by `AnalysisSession` and warmed by `ingest_file`. This salsa-side
// helper has no counterpart in the new architecture.
#[cfg(test)]
mod tests {
use super::*;
fn uri(path: &str) -> Url {
Url::parse(&format!("file://{path}")).unwrap()
}
/// Phase E4: open-file state lives on `Backend`, not `DocumentStore`.
/// Tests that need to simulate "file is open" just mirror the text into
/// the salsa input — the open/closed distinction is enforced by the
/// caller (Backend) in production.
fn open(store: &DocumentStore, u: Url, text: String) {
store.mirror_text(&u, &text);
}
// Removed `salsa_codebase_aggregates_all_files`: the salsa-side codebase
// aggregation was deleted with the mir 0.22 migration. Equivalent
// behaviour is now covered by mir-analyzer's own session tests.
#[test]
fn index_registers_file_in_salsa() {
let store = DocumentStore::new();
store.index(uri("/lib.php"), "<?php\nfunction lib_fn() {}");
let idx = store.get_index_salsa(&uri("/lib.php")).unwrap();
assert_eq!(idx.functions.len(), 1);
assert_eq!(idx.functions[0].name, "lib_fn".into());
}
#[test]
fn remove_hides_file_from_index() {
let store = DocumentStore::new();
let u = uri("/lib.php");
store.index(u.clone(), "<?php");
store.remove(&u);
assert!(store.get_index_salsa(&u).is_none());
}
#[test]
fn remove_and_reopen_reuses_source_file_handle() {
let store = DocumentStore::new();
let u = uri("/lib.php");
store.index(u.clone(), "<?php");
let ft_before = store.source_file(&u).unwrap();
store.remove(&u);
assert!(
store.source_file(&u).is_none(),
"deleted file should be hidden"
);
store.mirror_text(&u, "<?php");
let ft_after = store.source_file(&u).unwrap();
assert!(
ft_before == ft_after,
"reopen must reuse the same FileText handle"
);
}
#[test]
fn delete_reopen_churn_does_not_amplify_salsa_inputs() {
let store = DocumentStore::new();
let uris: Vec<Url> = (0..20).map(|i| uri(&format!("/churn/f{i}.php"))).collect();
for u in &uris {
store.index(u.clone(), "<?php class A {}");
}
let count_before = store.source_files_len();
for _ in 0..10 {
for u in &uris {
store.remove(u);
}
for u in &uris {
store.index(u.clone(), "<?php class A {}");
}
}
assert_eq!(
store.source_files_len(),
count_before,
"delete-reopen cycles must not create new salsa inputs (L1-B regression guard)"
);
}
#[test]
fn all_indexes_includes_every_mirrored_file() {
let store = DocumentStore::new();
open(&store, uri("/a.php"), "<?php\nfunction a() {}".to_string());
store.index(uri("/b.php"), "<?php\nfunction b() {}");
assert_eq!(store.all_indexes().len(), 2);
}
#[test]
fn other_indexes_excludes_current_uri() {
let store = DocumentStore::new();
open(&store, uri("/a.php"), "<?php\nfunction a() {}".to_string());
open(&store, uri("/b.php"), "<?php\nfunction b() {}".to_string());
assert_eq!(store.other_indexes(&uri("/a.php")).len(), 1);
}
#[test]
fn other_docs_excludes_current_uri() {
let store = DocumentStore::new();
let ua = uri("/a.php");
let ub = uri("/b.php");
open(&store, ua.clone(), "<?php\nfunction a() {}".to_string());
open(&store, ub.clone(), "<?php\nfunction b() {}".to_string());
let open_urls = vec![ua.clone(), ub];
assert_eq!(store.other_docs(&ua, &open_urls).len(), 1);
}
#[test]
fn evict_token_cache_removes_entry() {
let store = DocumentStore::new();
let u = uri("/a.php");
open(&store, u.clone(), "<?php".to_string());
store.store_token_cache(&u, "id1".to_string(), Arc::new(vec![]));
assert!(store.get_token_cache(&u, "id1").is_some());
store.evict_token_cache(&u);
assert!(store.get_token_cache(&u, "id1").is_none());
}
#[test]
fn index_populates_file_index_with_symbols() {
let store = DocumentStore::new();
store.index(uri("/a.php"), "<?php\nfunction hello() {}");
let idx = store.get_index_salsa(&uri("/a.php")).unwrap();
assert_eq!(idx.functions.len(), 1);
assert_eq!(idx.functions[0].name, "hello".into());
}
#[test]
fn open_populates_file_index_with_symbols() {
let store = DocumentStore::new();
open(&store, uri("/a.php"), "<?php\nclass Foo {}".to_string());
let idx = store.get_index_salsa(&uri("/a.php")).unwrap();
assert_eq!(idx.classes.len(), 1);
assert_eq!(idx.classes[0].name, "Foo".into());
}
// ── Mirror invariants ────────────────────────────────────────────────
//
// Every mutation path that changes file text must keep the salsa layer
// consistent. These tests walk a set-edit-reopen cycle and assert that
// the salsa-derived `FileIndex` reflects the latest text at each step.
fn names_of(idx: &FileIndex) -> Vec<String> {
let mut out: Vec<String> = idx.classes.iter().map(|c| c.name.to_string()).collect();
out.extend(idx.functions.iter().map(|f| f.name.to_string()));
out.sort();
out
}
fn salsa_index_names(store: &DocumentStore, url: &Url) -> Vec<String> {
store
.snapshot_query_file_index(url)
.map(|idx| names_of(&idx))
.unwrap_or_default()
}
#[test]
fn mirror_tracks_repeated_edits() {
let store = DocumentStore::new();
let u = uri("/mirror.php");
open(&store, u.clone(), "<?php\nclass A {}".to_string());
assert_eq!(salsa_index_names(&store, &u), vec!["A".to_string()]);
open(
&store,
u.clone(),
"<?php\nclass A {}\nclass B {}".to_string(),
);
assert_eq!(
salsa_index_names(&store, &u),
vec!["A".to_string(), "B".to_string()]
);
open(&store, u.clone(), "<?php\nfunction greet() {}".to_string());
assert_eq!(salsa_index_names(&store, &u), vec!["greet".to_string()]);
}
#[test]
fn mirror_tracks_index_and_index_from_doc() {
let store = DocumentStore::new();
// Background `index(url, text)` path.
let u1 = uri("/bg1.php");
store.index(u1.clone(), "<?php\nclass Bg1 {}");
assert_eq!(salsa_index_names(&store, &u1), vec!["Bg1".to_string()]);
// `index_from_doc(url, &doc)` path (workspace-scan Phase 2).
let u2 = uri("/bg2.php");
let doc = crate::analysis::diagnostics::parse_document_no_diags(
"<?php\nclass Bg2 {}\nfunction f() {}",
);
store.index_from_doc(u2.clone(), &doc);
assert_eq!(
salsa_index_names(&store, &u2),
vec!["Bg2".to_string(), "f".to_string()]
);
}
/// G3: confirms the `parsed_cache` actually hits — two consecutive
/// `get_doc_salsa` calls on unchanged text return the same `Arc`
/// (pointer equality), and an edit forces a miss that produces a
/// different `Arc`.
/// parsed_cache must stay bounded — inserting more than
/// `PARSED_CACHE_CAP` unique URLs must not cause unbounded growth.
/// Eviction is probabilistic, so we only assert the bound, not which
/// Seeding a cached index for a URL that was never mirrored is a no-op
/// (returns `false`) — avoids silently allocating SourceFiles outside
/// `mirror_text`'s control.
#[test]
fn seed_cached_index_noops_for_unknown_uri() {
let store = DocumentStore::new();
let u = uri("/never_mirrored.php");
let index = Arc::new(crate::file_index::FileIndex::default());
assert!(!store.seed_cached_index(&u, index));
}
/// entries survive.
#[test]
fn parsed_cache_stays_bounded_under_many_inserts() {
let store = DocumentStore::new();
let overflow = PARSED_CACHE_CAP + 100;
for i in 0..overflow {
let u = uri(&format!("/cap/file{i}.php"));
store.index(u.clone(), "<?php\nclass A {}");
// Force a parsed_cache insert via get_doc_salsa.
let _ = store.get_doc_salsa(&u);
}
assert!(
store.parsed_cache.len() <= PARSED_CACHE_CAP,
"parsed_cache grew to {} entries (cap {})",
store.parsed_cache.len(),
PARSED_CACHE_CAP
);
}
#[test]
fn get_doc_salsa_cache_hits_across_calls() {
let store = DocumentStore::new();
let u = uri("/g3_cache.php");
open(&store, u.clone(), "<?php\nclass G3 {}".to_string());
let a = store.get_doc_salsa(&u).unwrap();
let b = store.get_doc_salsa(&u).unwrap();
assert!(
Arc::ptr_eq(&a, &b),
"parsed_cache hit should yield the same Arc across calls"
);
open(&store, u.clone(), "<?php\nclass G3b {}".to_string());
let c = store.get_doc_salsa(&u).unwrap();
assert!(
!Arc::ptr_eq(&a, &c),
"edit should invalidate the parsed_cache entry"
);
}
#[test]
fn get_doc_salsa_returns_some_for_mirrored_files() {
// Phase E4: `get_doc_salsa` no longer gates on open-state. The
// open/closed distinction now lives on `Backend::get_doc`.
let store = DocumentStore::new();
let u = uri("/e4_doc.php");
store.index(u.clone(), "<?php\nclass P {}");
assert!(store.get_doc_salsa(&u).is_some());
}
#[test]
fn get_salsa_accessors_return_none_for_unknown_uri() {
let store = DocumentStore::new();
let u = uri("/never-seen.php");
assert!(store.get_doc_salsa(&u).is_none());
assert!(store.get_index_salsa(&u).is_none());
}
/// Phase E1: concurrent readers and writers must not deadlock, panic, or
/// return stale data. Writers briefly bump inputs while readers are
/// running on cloned snapshots; any `salsa::Cancelled` raised on the
/// reader side must be caught and retried by `snapshot_query`.
///
/// The salsa surface (`get_doc_salsa`, `get_index_salsa`) is protected by
/// `snapshot_query`'s last-resort host-lock fallback.
#[test]
fn concurrent_reads_and_writes_do_not_panic() {
use std::sync::Arc;
use std::thread;
use std::time::{Duration, Instant};
let store = Arc::new(DocumentStore::new());
let urls: Vec<Url> = (0..8).map(|i| uri(&format!("/f{i}.php"))).collect();
for (i, u) in urls.iter().enumerate() {
open(&store, u.clone(), format!("<?php\nclass C{i} {{}}"));
}
let deadline = Instant::now() + Duration::from_millis(400);
let mut handles = Vec::new();
// Writer thread: keep bumping every file's text.
{
let store = Arc::clone(&store);
let urls = urls.clone();
handles.push(thread::spawn(move || {
let mut rev = 0u32;
while Instant::now() < deadline {
for u in &urls {
let text = format!("<?php\nclass C{{}}\n// rev {rev}");
store.mirror_text(u, &text);
}
rev += 1;
}
}));
}
// Reader threads: hammer the salsa accessors.
for _ in 0..4 {
let store = Arc::clone(&store);
let urls = urls.clone();
handles.push(thread::spawn(move || {
while Instant::now() < deadline {
for u in &urls {
let _ = store.get_doc_salsa(u);
let _ = store.get_index_salsa(u);
}
// Post mir 0.22: codebase + refs live in the session,
// not salsa. Concurrent-read smoke is limited to the
// remaining salsa surface (parsed_doc, file_index).
}
}));
}
for h in handles {
h.join().expect("no panic under concurrent read/write");
}
}
/// PSR-4 lazy-loading: `get_semantic_issues_salsa` must not emit
/// `UndefinedClass` for a class that is PSR-4-resolvable on disk, even
/// when the dependency file is not yet in `source_files`.
#[test]
fn psr4_lazy_load_suppresses_undefined_class() {
let tmp = tempfile::tempdir().unwrap();
// Write Entity.php to disk (not mirrored into the store).
std::fs::create_dir_all(tmp.path().join("src/Model")).unwrap();
std::fs::write(
tmp.path().join("src/Model/Entity.php"),
"<?php\nnamespace App\\Model;\nclass Entity {}\n",
)
.unwrap();
// Write composer.json so Psr4Map::load can build the map.
std::fs::write(
tmp.path().join("composer.json"),
r#"{"autoload":{"psr-4":{"App\\":"src/"}}}"#,
)
.unwrap();
let store = DocumentStore::new();
// Inject a PSR-4 map pointing at the tmp dir.
store
.psr4
.store(Arc::new(crate::autoload::Psr4Map::load(tmp.path())));
// Mirror the consuming file (Entity not yet in source_files).
// Uses Entity as a parameter type hint — the analyzer resolves these
// through use statements, so this exercises the full PSR-4 lazy-load path.
let handler_url = Url::from_file_path(tmp.path().join("src/Service/Handler.php")).unwrap();
store.mirror_text(
&handler_url,
"<?php\nnamespace App\\Service;\nuse App\\Model\\Entity;\nfunction handle(Entity $e): Entity { return $e; }\n",
);
let issues = store.get_semantic_issues_salsa(&handler_url).unwrap();
let undef: Vec<_> = issues
.iter()
.filter(|i| matches!(i.kind, mir_issues::IssueKind::UndefinedClass { .. }))
.collect();
assert!(
undef.is_empty(),
"PSR-4 lazy-loading must prevent UndefinedClass for App\\Model\\Entity; got: {undef:?}"
);
}
/// Issue #191 regression: workspace-wide scans (find-references, rename,
/// call-hierarchy) must not re-parse closed/indexed files on repeated
/// invocations. Once a file's `ParsedDoc` has been produced, subsequent
/// `all_docs_for_scan()` calls must hit the cache and return the same
/// `Arc<ParsedDoc>` (pointer equality), proving no re-parse occurred.
///
/// The cache layers protecting this are:
/// 1. `parsed_cache` (cap [`PARSED_CACHE_CAP`]) — read-through, validated
/// via `Arc::ptr_eq` on the text Arc.
/// 2. salsa `parsed_doc` memo (`lru = 2048`) — second line of defense
/// when `parsed_cache` evicts.
///
/// Together they keep every workspace-scan op O(N) memo lookups, never
/// O(N) parses, for any workspace whose file count fits the cap.
#[test]
fn all_docs_for_scan_does_not_reparse_indexed_files() {
let store = DocumentStore::new();
const N: usize = 50;
for i in 0..N {
let u = uri(&format!("/scan/file{i}.php"));
store.index(u, &format!("<?php\nclass C{i} {{}}\nfunction f{i}() {{}}"));
}
let first: Vec<_> = store.all_docs_for_scan();
let second: Vec<_> = store.all_docs_for_scan();
assert_eq!(first.len(), N);
assert_eq!(second.len(), N);
let by_url_first: std::collections::HashMap<Url, Arc<ParsedDoc>> =
first.into_iter().collect();
for (u, doc2) in second {
let doc1 = by_url_first
.get(&u)
.expect("second scan returned a URL the first didn't");
assert!(
Arc::ptr_eq(doc1, &doc2),
"{u} re-parsed across all_docs_for_scan calls — \
cache (parsed_cache + salsa parsed_doc memo) failed to hit"
);
}
// Editing one file's text must invalidate just that file's entry,
// not the rest. This locks in self-eviction via Arc::ptr_eq on text.
let edited_url = uri("/scan/file0.php");
let pre_edit = store.get_doc_salsa(&edited_url).unwrap();
store.index(edited_url.clone(), "<?php\nclass C0Edited {}");
let post_edit = store.get_doc_salsa(&edited_url).unwrap();
assert!(
!Arc::ptr_eq(&pre_edit, &post_edit),
"edited file must produce a fresh ParsedDoc"
);
for i in 1..N {
let u = uri(&format!("/scan/file{i}.php"));
let original = by_url_first.get(&u).unwrap();
let after = store.get_doc_salsa(&u).unwrap();
assert!(
Arc::ptr_eq(original, &after),
"{u} should not have re-parsed because of an unrelated edit"
);
}
}
}