php-lsp 0.25.3

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

#[allow(unused_imports)]
use self::helpers::*;

use arc_swap::ArcSwap;

/// Sent to the client once Phase 3 (reference index build) finishes.
/// Allows tests and tooling to wait for the codebase fast path to be active.
enum IndexReadyNotification {}
impl tower_lsp_server::ls_types::notification::Notification for IndexReadyNotification {
    type Params = ();
    const METHOD: &'static str = "$/php-lsp/indexReady";
}

/// A `$/progress` partial-result batch for `textDocument/references`.
///
/// `lsp_types::ProgressParamsValue` only has a `WorkDone` variant (it can't
/// carry an arbitrary partial-result payload), so partial results use this
/// hand-rolled notification instead — same `$/progress` method, but `value`
/// is the request's own result type unwrapped, per the LSP spec's
/// partial-result shape.
enum ReferencesPartialResult {}
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct ReferencesPartialResultParams {
    token: tower_lsp_server::ls_types::NumberOrString,
    value: Vec<tower_lsp_server::ls_types::Location>,
}
impl tower_lsp_server::ls_types::notification::Notification for ReferencesPartialResult {
    type Params = ReferencesPartialResultParams;
    const METHOD: &'static str = "$/progress";
}

/// Stream a batch of reference locations to the client as a `$/progress`
/// partial result. Best-effort: the final response is always sent
/// separately and is unaffected if the client ignores this.
pub(crate) async fn send_references_partial_result(
    client: &Client,
    token: tower_lsp_server::ls_types::NumberOrString,
    locations: Vec<tower_lsp_server::ls_types::Location>,
) {
    client
        .send_notification::<ReferencesPartialResult>(ReferencesPartialResultParams {
            token,
            value: locations,
        })
        .await;
}

use tower_lsp_server::Client;
use tower_lsp_server::ls_types::*;

/// Response for the `$/php-lsp/debugStats` custom request.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct DebugStats {
    /// Cumulative count of real `ParsedDoc` parses (cache misses).
    pub parses: u64,
    /// Times mir's reference index was locked. Reads are per-key posting
    /// lookups and edits commit one file's postings, so this grows by a
    /// small bounded amount per operation — never per candidate file.
    pub ref_index_locks: u64,
    /// Analysis warm sweeps run to completion (not cancelled). Lets benches
    /// and tests wait for the post-index sweep before baselining.
    pub warm_sweeps_completed: u64,
    /// Whether mir's workspace symbol index singleton is populated (seeded
    /// from the disk cache at warm start, or built by the first sweep).
    pub workspace_symbol_index_ready: bool,
    /// Executions of mir's tracked O(all-files) symbol-index walk. A
    /// cache-warm session must keep this at zero — the regression tests
    /// assert it.
    pub workspace_index_walks: u64,
    /// Workspace-wide FQN/text-needle scan passes for reference-scope
    /// narrowing (`DocumentStore::resolve_reachability_queries`). A request
    /// with many narrowing-requiring declarations (e.g. code lens on a file
    /// with several classes/public-static-methods) must pay one pass per
    /// request, not one per declaration — the regression tests assert the
    /// delta across such a request.
    pub reachability_scan_passes: u64,
    /// Real `FileAnalyzer::analyze` runs (never a cache hit). Concurrent
    /// callers racing for the same uncached file's analysis (e.g. `did_open`
    /// diagnostics vs. a fast-following hover) must serialize onto one run,
    /// not one per caller — the regression test asserts the delta.
    pub analysis_compute_count: u64,
    /// `DocumentStore::warm_start_indexes` calls that replayed at least one
    /// file. A runtime-added workspace folder runs this in the same spawned
    /// task as its scan, before the refresh-request notifications go out —
    /// tests await a count bump here instead of guessing a fixed delay.
    pub warm_start_replays_completed: u64,
    /// Files handed to a background reanalysis because their replayed
    /// reference postings were flagged untrusted by mir's `warm_start_files`.
    /// See `DocumentStore::warm_start_untrusted_reanalyzed`.
    pub warm_start_untrusted_reanalyzed: u64,
    /// Throttled vendor warm-analysis sweeps run to completion. Always 0
    /// today — the sweep doesn't exist yet (ROADMAP 0c step 2). See
    /// `DocumentStore::vendor_warm_sweeps_completed`.
    pub vendor_warm_sweeps_completed: u64,
    /// Section currently parked at the debug gate (see `debug_gate.rs`), if
    /// any. The responsiveness tests poll this to prove a handler's blocking
    /// work is both off the serve future and genuinely in flight.
    pub debug_gate_held: Option<String>,
    /// Files mirrored into the salsa workspace. Denominator for the per-file
    /// cache sizes below.
    pub workspace_file_count: u64,
    /// Entries in the semantic-tokens delta cache.
    pub token_cache_len: u64,
    /// Entries in the mirrored-source-text cache. Expected to track
    /// `workspace_file_count`.
    pub text_cache_len: u64,
    /// Entries in the read-through `ParsedDoc` cache (LRU-capped).
    pub parsed_cache_len: u64,
    /// Entries in the per-file `FileAnalysis` cache (LRU-capped).
    pub analysis_cache_len: u64,
    /// Entries in the owned-`Program` cache (LRU-capped).
    pub owned_program_cache_len: u64,
    /// Entries in the declaration-fingerprint cache. Expected to track
    /// `workspace_file_count`.
    pub decl_fingerprints_len: u64,
    /// Entries in the lazily-loaded vendor `FileIndex` cache. Not
    /// LRU-capped today — the one cache size here worth watching on a
    /// long-running session with heavy vendor navigation.
    pub vendor_index_cache_len: u64,
    /// Hits served from mir's `indexed_references_to` memoization cache
    /// (see `mir_analyzer::AnalysisSession::ref_query_cache_hits`).
    pub mir_ref_query_cache_hits: u64,
    /// Hits served from mir's `indexed_subtype_classes` memoization cache
    /// (see `mir_analyzer::AnalysisSession::subtype_query_cache_hits`).
    pub mir_subtype_query_cache_hits: u64,
    /// Per-file text scans recorded in mir's own `ClassMentionIndex` — the
    /// single shared backend every `resolve_reachability_queries` needle is
    /// answered by. The ratio against `reachability_scan_passes` is the
    /// per-file mention cache's hit rate — a warm, unedited repeat query
    /// should not move this at all.
    pub mir_mention_scans_recorded: u64,
}

/// Params for the `$/php-lsp/debugHoldGate` custom request.
#[cfg(feature = "test-hooks")]
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct DebugHoldGateParams {
    /// One of the `GATE_*` constants in `debug_gate`.
    pub section: String,
}

/// The one place custom methods are registered — `main` and the test harness
/// both build the service here so their method tables can never drift. The
/// gate methods exist only under `test-hooks` (test targets); a production
/// build answers them with MethodNotFound like any unknown method.
pub fn build_lsp_service() -> (
    tower_lsp_server::LspService<Backend>,
    tower_lsp_server::ClientSocket,
) {
    let builder = tower_lsp_server::LspService::build(Backend::new)
        .custom_method("$/php-lsp/debugStats", Backend::debug_stats);
    #[cfg(feature = "test-hooks")]
    let builder = builder
        .custom_method("$/php-lsp/debugHoldGate", Backend::debug_hold_gate)
        .custom_method("$/php-lsp/debugReleaseGate", Backend::debug_release_gate);
    builder.finish()
}

use crate::document::ast::ParsedDoc;
use crate::document::document_store::DocumentStore;
use crate::document::open_files::OpenFiles;
use crate::lang::autoload::Psr4Map;
use crate::lang::config::LspConfig;
use crate::laravel::LaravelIndex;

use crate::analysis::diagnostics::merge_file_diagnostics;
use crate::document::open_files::compute_open_file_diagnostics;

pub struct Backend {
    client: Client,
    docs: Arc<DocumentStore>,
    /// Open-file state: text, version token, parse diagnostics.
    /// Files that are only background-indexed (never opened in the editor)
    /// do not appear here; they live only in `DocumentStore`'s salsa layer.
    open_files: OpenFiles,
    root_paths: Arc<ArcSwap<Vec<PathBuf>>>,
    psr4: Arc<ArcSwap<Psr4Map>>,
    laravel: Arc<ArcSwap<LaravelIndex>>,
    config: Arc<ArcSwap<LspConfig>>,
    /// Capabilities the client declared in `initialize`. Consulted in
    /// `initialized` to decide which capabilities are safe to register
    /// dynamically (e.g. a client that didn't declare
    /// `typeHierarchy.dynamicRegistration` won't understand a
    /// `client/registerCapability` call for it).
    client_capabilities: Arc<ArcSwap<ClientCapabilities>>,
    /// Test-only hold points for the responsiveness regression tests.
    debug_gate: Arc<debug_gate::DebugGate>,
}

impl Backend {
    pub fn new(client: Client) -> Self {
        // No imperative Codebase field anymore — analysis reads the
        // salsa-memoized `codebase` query, which composes bundled stubs + every
        // file's StubSlice and returns a fresh `Arc<Codebase>` (or the memoized
        // one when inputs are unchanged).
        let docs = Arc::new(DocumentStore::new());
        let psr4 = docs.psr4_arc();
        Backend {
            client,
            docs,
            open_files: OpenFiles::new(),
            root_paths: Arc::new(ArcSwap::from_pointee(Vec::new())),
            psr4,
            laravel: Arc::new(ArcSwap::from_pointee(LaravelIndex::default())),
            config: Arc::new(ArcSwap::from_pointee(LspConfig::default())),
            client_capabilities: Arc::new(ArcSwap::from_pointee(ClientCapabilities::default())),
            debug_gate: Arc::new(debug_gate::DebugGate::new()),
        }
    }

    /// `$/php-lsp/debugStats` — internal observability counters, used by the
    /// stress tests to assert the read path doesn't parse the whole workspace
    /// and that reference-index lock traffic stays bounded per operation.
    pub async fn debug_stats(&self) -> tower_lsp_server::jsonrpc::Result<DebugStats> {
        Ok(DebugStats {
            parses: self.docs.parse_count(),
            ref_index_locks: self.docs.ref_index_lock_count(),
            warm_sweeps_completed: self.docs.warm_sweeps_completed(),
            workspace_symbol_index_ready: self.docs.workspace_symbol_index_ready(),
            workspace_index_walks: self.docs.workspace_index_walks(),
            reachability_scan_passes: self.docs.reachability_scan_passes(),
            analysis_compute_count: self.docs.analysis_compute_count(),
            warm_start_replays_completed: self.docs.warm_start_replays_completed(),
            warm_start_untrusted_reanalyzed: self.docs.warm_start_untrusted_reanalyzed(),
            vendor_warm_sweeps_completed: self.docs.vendor_warm_sweeps_completed(),
            debug_gate_held: self.debug_gate.held_section(),
            workspace_file_count: self.docs.workspace_file_count(),
            token_cache_len: self.docs.token_cache_len(),
            text_cache_len: self.docs.text_cache_len(),
            parsed_cache_len: self.docs.parsed_cache_len(),
            analysis_cache_len: self.docs.analysis_cache_len(),
            owned_program_cache_len: self.docs.owned_program_cache_len(),
            decl_fingerprints_len: self.docs.decl_fingerprints_len(),
            vendor_index_cache_len: self.docs.vendor_index_cache_len(),
            mir_ref_query_cache_hits: self.docs.mir_ref_query_cache_hits(),
            mir_subtype_query_cache_hits: self.docs.mir_subtype_query_cache_hits(),
            mir_mention_scans_recorded: self.docs.mir_mention_scans_recorded(),
        })
    }

    /// `$/php-lsp/debugHoldGate` — test-only: park the next blocking-pool
    /// passage through the named section until `debugReleaseGate`.
    #[cfg(feature = "test-hooks")]
    pub async fn debug_hold_gate(
        &self,
        params: DebugHoldGateParams,
    ) -> tower_lsp_server::jsonrpc::Result<()> {
        self.debug_gate.arm(&params.section);
        Ok(())
    }

    /// `$/php-lsp/debugReleaseGate` — release a passage parked by
    /// `debugHoldGate` (and disarm the gate).
    #[cfg(feature = "test-hooks")]
    pub async fn debug_release_gate(&self) -> tower_lsp_server::jsonrpc::Result<()> {
        self.debug_gate.release();
        Ok(())
    }

    fn set_open_text(&self, uri: Uri, text: String) -> u64 {
        self.open_files.set_open_text(&self.docs, uri, text)
    }

    fn close_open_file(&self, uri: &Uri) {
        self.open_files.close(&self.docs, uri);
    }

    /// Background-index a file from disk, but only if it isn't currently
    /// open in the editor — the editor's buffer is authoritative while a
    /// file is open, and we must not overwrite it with disk contents.
    fn ingest_if_not_open(&self, uri: Uri, text: &str) {
        if !self.open_files.contains(&uri) {
            self.docs.ingest(uri, text);
        }
    }

    fn get_open_text(&self, uri: &Uri) -> Option<Arc<str>> {
        self.open_files.text(uri)
    }

    /// See [`offload::run`]. The sanctioned way for a handler to leave the
    /// async runtime worker for CPU-bound work with no debug-gated test.
    async fn blocking<F, R>(&self, label: &'static str, f: F) -> Option<R>
    where
        F: FnOnce() -> R + Send + 'static,
        R: Send + 'static,
    {
        offload::run(label, f).await
    }

    /// See [`offload::run_gated`]. Use when a responsiveness regression
    /// test needs to pin this closure in flight via a `GATE_*` section.
    async fn blocking_gated<F, R>(&self, section: &'static str, f: F) -> Option<R>
    where
        F: FnOnce() -> R + Send + 'static,
        R: Send + 'static,
    {
        offload::run_gated(&self.debug_gate, section, f).await
    }

    fn set_parse_diagnostics(&self, uri: &Uri, diagnostics: Vec<Diagnostic>) {
        self.open_files.set_parse_diagnostics(uri, diagnostics);
    }

    fn get_parse_diagnostics(&self, uri: &Uri) -> Option<Vec<Diagnostic>> {
        self.open_files.parse_diagnostics(uri)
    }

    fn all_open_files_with_diagnostics(&self) -> Vec<(Uri, Vec<Diagnostic>, Option<i64>)> {
        self.open_files.all_with_diagnostics()
    }

    fn open_urls(&self) -> Vec<Uri> {
        self.open_files.urls()
    }

    fn get_doc(&self, uri: &Uri) -> Option<Arc<ParsedDoc>> {
        self.open_files.get_doc(&self.docs, uri)
    }

    fn get_doc_stale(&self, uri: &Uri) -> Option<Arc<ParsedDoc>> {
        self.open_files.get_doc_stale(&self.docs, uri)
    }

    /// Re-mirror every open buffer's live text into `self.docs`.
    ///
    /// Needed after anything that rebuilds the analysis session's salsa db
    /// (`DocumentStore::set_session_cache_dir` / `set_php_version`, when
    /// they report a drop): the workspace scan that normally repopulates
    /// `lsp_ws_files` explicitly skips files already open, so an open file
    /// whose entry was cleared by the drop would otherwise stay unresolvable
    /// (`get_doc` returning `None`) until the next edit.
    pub(crate) fn remirror_open_files(&self) {
        for uri in self.open_files.urls() {
            if let Some(text) = self.open_files.text(&uri) {
                self.docs.mirror_text_arc(&uri, text);
            }
        }
    }

    /// `use Foo as Bar;` map for a single file, read directly from the AST.
    /// Memoized per `ParsedDoc` (see `ParsedDoc::file_imports`) — cheap to
    /// call repeatedly within or across requests against the same revision.
    fn file_imports(&self, uri: &Uri) -> Arc<std::collections::HashMap<String, String>> {
        self.docs
            .get_doc_salsa(uri)
            .map(|doc| doc.file_imports())
            .unwrap_or_default()
    }

    /// Resolve the FQN of the symbol at the cursor so reference lookups can match
    /// by exact FQN instead of short name (fixes cross-namespace overmatch for
    /// Function/Class and unrelated-class overmatch for Method via the owning
    /// FQCN). Returns `None` when the kind doesn't carry an FQN or it can't be
    /// resolved. For class constants, returns the owning class short name.
    fn resolve_reference_target_fqn(
        &self,
        uri: &Uri,
        doc_opt: Option<&Arc<ParsedDoc>>,
        word: &str,
        kind: Option<crate::navigation::references::SymbolKind>,
        position: Position,
        constant_owner: Option<String>,
    ) -> Option<String> {
        use crate::navigation::references::SymbolKind;
        let doc = doc_opt?;
        let imports = self.file_imports(uri);
        match kind {
            Some(SymbolKind::Function) | Some(SymbolKind::Class) => {
                let resolved = crate::navigation::moniker::resolve_fqn(doc, word, &imports);
                resolved.contains('\\').then_some(resolved)
            }
            Some(SymbolKind::Method) => {
                // Owning FQCN: the class/interface/trait/enum that contains the cursor.
                let short_owner =
                    crate::types::type_map::enclosing_class_at(doc.source(), doc, position)?;
                // `resolve_fqn` walks the doc and applies the namespace prefix if any.
                Some(crate::navigation::moniker::resolve_fqn(
                    doc,
                    &short_owner,
                    &imports,
                ))
            }
            Some(SymbolKind::Property) => {
                // Resolve the owning class when the cursor is on a property
                // declaration (including promoted constructor parameters) —
                // for access sites (`$obj->prop`) the resolved usage symbol
                // from `FileAnalysis::symbol_at` carries the owner instead.
                let stmts = &doc.program().stmts;
                if crate::backend::helpers::cursor_is_on_property_decl(
                    doc.source(),
                    stmts,
                    position,
                )
                .is_none()
                    && promoted_property_at_cursor(doc.source(), stmts, position).is_none()
                {
                    return None;
                }
                let short_owner =
                    crate::types::type_map::enclosing_class_at(doc.source(), doc, position)?;
                Some(crate::navigation::moniker::resolve_fqn(
                    doc,
                    &short_owner,
                    &imports,
                ))
            }
            Some(SymbolKind::Constant) => {
                if let Some(owner) = constant_owner {
                    // Class constant: resolve the owning class to its FQCN —
                    // mir's index keys are `cnst:{fqcn}::{NAME}`.
                    if owner.contains('\\') {
                        Some(owner.trim_start_matches('\\').to_string())
                    } else {
                        Some(crate::navigation::moniker::resolve_fqn(
                            doc, &owner, &imports,
                        ))
                    }
                } else {
                    // Global/namespace constant: compute FQN so cross-namespace
                    // references like `\Config\DB_HOST` can be found.
                    let fqn = crate::navigation::moniker::resolve_fqn(doc, word, &imports);
                    fqn.contains('\\').then_some(fqn)
                }
            }
            _ => None,
        }
    }

    /// Resolve the PHP version to use. See `autoload::resolve_php_version_from_roots`
    /// for the full priority order.
    fn resolve_php_version(&self, explicit: Option<&str>) -> (String, &'static str) {
        let roots = self.root_paths.load();
        crate::lang::autoload::resolve_php_version_from_roots(&roots, explicit)
    }
}

/// Refine the cursor's `(word, kind)` for a references request using
/// declaration-aware heuristics, returning the (possibly rewritten) word, its
/// symbol kind, and — for class constants — the owning class short name.
///
/// Checks, in order: promoted constructor property params (so `$name` in
/// `__construct(public string $name)` resolves to the `->name` property, not
/// `$name` variable occurrences), then method / property / constant
/// declarations, falling back to the character-based `symbol_kind_at` heuristic.
fn resolve_reference_symbol(
    doc_opt: Option<&Arc<ParsedDoc>>,
    source: &str,
    position: Position,
    word: String,
) -> (
    String,
    Option<crate::navigation::references::SymbolKind>,
    Option<String>,
) {
    use crate::navigation::references::SymbolKind;
    let mut constant_owner: Option<String> = None;
    let (word, kind) = if let Some(doc) = doc_opt
        && let Some(prop_name) =
            promoted_property_at_cursor(doc.source(), &doc.program().stmts, position)
    {
        (prop_name, Some(SymbolKind::Property))
    } else if let Some(doc) = doc_opt {
        let stmts = &doc.program().stmts;
        if cursor_is_on_method_decl(doc.source(), stmts, position) {
            (word, Some(SymbolKind::Method))
        } else if let Some(prop_name) = cursor_is_on_property_decl(doc.source(), stmts, position) {
            (prop_name, Some(SymbolKind::Property))
        } else if let Some((const_name, owner)) =
            cursor_is_on_constant_decl(doc.source(), stmts, position)
        {
            constant_owner = owner;
            (const_name, Some(SymbolKind::Constant))
        } else {
            let k = symbol_kind_at(source, position, &word);
            // For constant access sites (`ClassName::CONST`, `self::CONST`),
            // extract the owning class so the constant walker is scoped to
            // the right class rather than falling back to the global-constant
            // path (which would look for a top-level constant named `CONST`).
            if matches!(k, Some(SymbolKind::Constant))
                && let Some(raw) = class_before_double_colon(source, position)
            {
                constant_owner = Some(match raw.as_str() {
                    "self" | "static" => {
                        crate::types::type_map::enclosing_class_at(doc.source(), doc, position)
                            .unwrap_or(raw)
                    }
                    // `parent::CONST` is compile-time resolved to the literal
                    // `extends` class, never subject to late static binding —
                    // same semantics `resolve_parent_construct_class` and
                    // `type_definition.rs::param_decl_type` already apply.
                    // Without this, the owner stayed the literal string
                    // `"parent"`, which can never match a real class.
                    "parent" => {
                        crate::types::type_map::enclosing_class_at(doc.source(), doc, position)
                            .and_then(|child| {
                                crate::types::type_map::parent_class_name(doc, &child)
                            })
                            .unwrap_or(raw)
                    }
                    _ => raw,
                });
            }
            (word, k)
        }
    } else {
        let k = symbol_kind_at(source, position, &word);
        (word, k)
    };
    (word, kind, constant_owner)
}

/// Extract the class name (or pseudo-keyword) immediately to the left of `::` at
/// the cursor position. Returns `None` when the cursor is not on an identifier
/// preceded by `::`.
///
/// Used to populate `constant_owner` for constant access sites so that
/// `Status::ACTIVE` (cursor on `ACTIVE`) scopes the constant walker to `Status`
/// rather than treating `ACTIVE` as a global constant.
fn class_before_double_colon(source: &str, position: Position) -> Option<String> {
    let line = source.lines().nth(position.line as usize)?;
    let chars: Vec<char> = line.chars().collect();
    let col = position.character as usize;

    let mut utf16_col = 0usize;
    let mut char_idx = 0usize;
    for ch in &chars {
        if utf16_col >= col {
            break;
        }
        utf16_col += ch.len_utf16();
        char_idx += 1;
    }

    let is_word = |c: char| c.is_alphanumeric() || c == '_';
    while char_idx > 0 && is_word(chars[char_idx - 1]) {
        char_idx -= 1;
    }

    if char_idx < 2 || chars[char_idx - 1] != ':' || chars[char_idx - 2] != ':' {
        return None;
    }

    let class_end = char_idx - 2;
    let mut class_start = class_end;
    while class_start > 0 && (is_word(chars[class_start - 1]) || chars[class_start - 1] == '\\') {
        class_start -= 1;
    }

    let name: String = chars[class_start..class_end].iter().collect();
    if name.is_empty() { None } else { Some(name) }
}

/// Takes `docs`/`open_files` by owned clone rather than `&Backend` because
/// did_change's blocking republish runs inside a detached `tokio::spawn`,
/// which requires a `'static` future — a borrow of `self` wouldn't live
/// long enough.
async fn compute_dependent_publishes_owned(
    docs: Arc<DocumentStore>,
    open_files: OpenFiles,
    changed_uri: Uri,
    diag_cfg: crate::lang::config::DiagnosticsConfig,
    is_laravel: bool,
) -> Vec<(Uri, Vec<Diagnostic>)> {
    tokio::task::spawn_blocking(move || {
        // A dependent sweep started during the initial scan can deadlock the
        // shared rayon pool: reanalysis retains salsa snapshots while a scan
        // writer waits for them to drop. Defer the sweep until readiness;
        // post-scan republishing covers every open file.
        if !docs.is_index_ready() {
            return Vec::new();
        }

        // rust-analyzer model: we only ever publish for files the editor has
        // open, so re-analyze exactly that set and let salsa memoization make
        // the unaffected ones ~free. No dependent set is computed at all —
        // the old path rebuilt mir's dependency_graph() on every keystroke,
        // an O(all-ingested-files) walk whose cost grew with session age.
        let open_set: Vec<std::sync::Arc<str>> = open_files
            .urls()
            .into_iter()
            .filter(|u| u != &changed_uri)
            .map(|u| std::sync::Arc::from(u.as_str()))
            .collect();
        if open_set.is_empty() {
            return Vec::new();
        }

        let session = docs.current_analysis_session();
        // The user is typing: pause the background scan's write storm so this
        // sweep's snapshots aren't repeatedly cancelled while indexing runs.
        let _interactive = docs.interactive_read_guard();
        // Cancel any older in-flight sweep and take a fresh token: when the
        // next edit starts its own sweep, this one stops at its next file
        // boundary instead of blocking typing behind the previous sweep.
        let cancel = docs.begin_reanalyze();
        let analyses = session.reanalyze_files_cancellable(&open_set, &cancel);
        // A newer edit that flipped `cancel` mid-sweep is now authoritative and
        // will republish; drop this sweep's partial results so they can't land
        // out of order and leave stale diagnostics as the final state.
        if cancel.is_cancelled() || analyses.is_empty() {
            return Vec::new();
        }

        let dependents: Vec<(Uri, mir_analyzer::FileAnalysis)> = analyses
            .into_iter()
            .filter_map(|(file, analysis)| {
                let url = (file.as_ref()).parse::<Uri>().ok()?;
                Some((url, analysis))
            })
            .collect();
        if dependents.is_empty() {
            return Vec::new();
        }

        // Workspace-level class issues (circular inheritance, override
        // violations, abstract-method gaps) aren't in `FileAnalysis` —
        // pull them in one batched call covering every affected file.
        let dep_files: Vec<Arc<str>> = dependents
            .iter()
            .map(|(u, _)| Arc::from(u.as_str()))
            .collect();
        let class_issues = session.class_issues(&dep_files);
        let mut class_issues_by_file: std::collections::HashMap<Arc<str>, Vec<mir_issues::Issue>> =
            std::collections::HashMap::new();
        for issue in class_issues {
            if issue.suppressed {
                continue;
            }
            let file = issue.location.file.clone();
            class_issues_by_file.entry(file).or_default().push(issue);
        }

        let mut out: Vec<(Uri, Vec<Diagnostic>)> = Vec::with_capacity(dependents.len());
        for (url, analysis) in dependents {
            let parse = open_files.parse_diagnostics(&url).unwrap_or_default();
            let mut issues: Vec<mir_issues::Issue> = analysis
                .issues
                .into_iter()
                .filter(|i| !i.suppressed)
                .collect();
            if let Some(extra) = class_issues_by_file.remove(&Arc::<str>::from(url.as_str())) {
                issues.extend(extra);
            }
            let semantic =
                crate::semantic_diagnostics::issues_to_diagnostics(&issues, &url, &diag_cfg);
            let mut diags = merge_file_diagnostics(parse, semantic);
            diags.extend(crate::laravel::unguarded_model_diagnostics(
                &docs, &url, is_laravel,
            ));
            diags.extend(open_files.external_diagnostics(&url));
            out.push((url, diags));
        }
        out
    })
    .await
    .unwrap_or_default()
}

/// Republish diagnostics for every currently open file once the initial
/// workspace index finishes.
///
/// `compute_open_file_diagnostics` holds back workspace-symbol-dependent
/// issues (`UndefinedClass` and friends, see `issue_needs_workspace_index`)
/// until `docs.is_index_ready()`, so a file opened during the scan may be
/// first published missing some of those. Push-diagnostics clients (the
/// common case) have no other trigger to re-request them — pull clients get
/// `send_refresh_requests`'s `WorkspaceDiagnosticRefresh`, but push clients
/// would otherwise carry a stale view until the user's next edit. Skips
/// files whose recomputed diagnostics are identical to what was already
/// published.
pub(super) async fn republish_after_index_ready(
    client: Client,
    docs: Arc<DocumentStore>,
    open_files: OpenFiles,
    diag_cfg: crate::lang::config::DiagnosticsConfig,
    is_laravel: bool,
) {
    let uris = open_files.urls();
    if uris.is_empty() {
        return;
    }
    let docs_ref = Arc::clone(&docs);
    let open_files_ref = open_files.clone();
    let all: Vec<(Uri, Vec<Diagnostic>)> = tokio::task::spawn_blocking(move || {
        uris.into_iter()
            .map(|uri| {
                let diags = compute_open_file_diagnostics(
                    &docs_ref,
                    &open_files_ref,
                    &uri,
                    &diag_cfg,
                    is_laravel,
                );
                (uri, diags)
            })
            .collect()
    })
    .await
    .unwrap_or_default();
    for (uri, diags) in all {
        let hash = diagnostics_content_hash(&diags);
        if open_files.published_hash(&uri) == Some(hash) {
            continue;
        }
        open_files.note_published(&uri, hash);
        client.publish_diagnostics(uri, diags, None).await;
    }
}

/// Content hash of a diagnostics set, for skipping republishes the client
/// already displays. In-process only — never persisted.
pub(super) fn diagnostics_content_hash(diagnostics: &[Diagnostic]) -> u64 {
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};
    let mut hasher = DefaultHasher::new();
    serde_json::to_string(diagnostics)
        .unwrap_or_default()
        .hash(&mut hasher);
    hasher.finish()
}

/// Compute and publish diagnostics for `uri`, then republish any open files
/// that depend on it. Requires `open_files.set_parse_diagnostics` to be up to
/// date for `uri` before this is called.
///
/// The edited file always publishes (editors rely on one publish per change).
/// Dependents publish only when their content differs from the last publish —
/// the sweep re-analyzes every open file on every edit, and unchanged results
/// would otherwise flood the client with no-op notifications.
pub(super) async fn publish_with_dependents(
    client: Client,
    docs: Arc<DocumentStore>,
    open_files: OpenFiles,
    uri: Uri,
    diag_cfg: crate::lang::config::DiagnosticsConfig,
    is_laravel: bool,
) {
    let docs_ref = Arc::clone(&docs);
    let open_files_ref = open_files.clone();
    let uri_ref = uri.clone();
    let diag_cfg_ref = diag_cfg.clone();
    let all_diags = tokio::task::spawn_blocking(move || {
        compute_open_file_diagnostics(
            &docs_ref,
            &open_files_ref,
            &uri_ref,
            &diag_cfg_ref,
            is_laravel,
        )
    })
    .await
    .unwrap_or_default();
    open_files.note_published(&uri, diagnostics_content_hash(&all_diags));
    client
        .publish_diagnostics(uri.clone(), all_diags, None)
        .await;
    let dependents =
        compute_dependent_publishes_owned(docs, open_files.clone(), uri, diag_cfg, is_laravel)
            .await;
    for (dep_uri, dep_diags) in dependents {
        let hash = diagnostics_content_hash(&dep_diags);
        if open_files.published_hash(&dep_uri) == Some(hash) {
            continue;
        }
        open_files.note_published(&dep_uri, hash);
        client.publish_diagnostics(dep_uri, dep_diags, None).await;
    }
}

/// Generate a stable result_id for diagnostics. Uses the count and position of diagnostics
/// to create a stable identifier. Same diagnostics = same result_id.
fn compute_diagnostic_result_id(diagnostics: &[Diagnostic], uri: &str) -> String {
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};

    let mut hasher = DefaultHasher::new();
    uri.hash(&mut hasher);
    diagnostics.len().hash(&mut hasher);

    for diag in diagnostics {
        diag.range.start.line.hash(&mut hasher);
        diag.range.start.character.hash(&mut hasher);
        diag.range.end.line.hash(&mut hasher);
        diag.range.end.character.hash(&mut hasher);
        diag.message.hash(&mut hasher);
        let severity_val = match diag.severity {
            Some(tower_lsp_server::ls_types::DiagnosticSeverity::ERROR) => 1,
            Some(tower_lsp_server::ls_types::DiagnosticSeverity::WARNING) => 2,
            Some(tower_lsp_server::ls_types::DiagnosticSeverity::INFORMATION) => 3,
            Some(tower_lsp_server::ls_types::DiagnosticSeverity::HINT) => 4,
            None => 0,
            _ => 5, // Unknown variants
        };
        severity_val.hash(&mut hasher);
        if let Some(code) = &diag.code {
            format!("{:?}", code).hash(&mut hasher);
        }
        if let Some(source) = &diag.source {
            source.hash(&mut hasher);
        }
        if let Some(tags) = &diag.tags {
            for tag in tags {
                let tag_val = match *tag {
                    tower_lsp_server::ls_types::DiagnosticTag::UNNECESSARY => 1,
                    tower_lsp_server::ls_types::DiagnosticTag::DEPRECATED => 2,
                    _ => 3,
                };
                tag_val.hash(&mut hasher);
            }
        }
    }

    format!("v1:{:x}", hasher.finish())
}

pub mod debug_gate;
mod handlers;
mod helpers;
pub mod offload;
pub mod panic_guard;
mod server;
#[cfg(test)]
mod tests;