Skip to main content

php_lsp/backend/
mod.rs

1use std::path::PathBuf;
2use std::sync::Arc;
3
4#[allow(unused_imports)]
5use self::helpers::*;
6
7use arc_swap::ArcSwap;
8
9/// Sent to the client once Phase 3 (reference index build) finishes.
10/// Allows tests and tooling to wait for the codebase fast path to be active.
11enum IndexReadyNotification {}
12impl tower_lsp::lsp_types::notification::Notification for IndexReadyNotification {
13    type Params = ();
14    const METHOD: &'static str = "$/php-lsp/indexReady";
15}
16use tower_lsp::Client;
17use tower_lsp::lsp_types::*;
18
19/// Response for the `$/php-lsp/debugStats` custom request.
20#[derive(Debug, serde::Serialize, serde::Deserialize)]
21pub struct DebugStats {
22    /// Cumulative count of real `ParsedDoc` parses (cache misses).
23    pub parses: u64,
24}
25
26use crate::document::ast::ParsedDoc;
27use crate::document::document_store::DocumentStore;
28use crate::document::open_files::OpenFiles;
29use crate::lang::autoload::Psr4Map;
30use crate::lang::config::LspConfig;
31use crate::lang::phpstorm_meta::PhpStormMeta;
32use crate::text::fqn_short_name;
33
34use crate::navigation::references::find_constructor_references;
35
36use crate::analysis::diagnostics::merge_file_diagnostics;
37use crate::document::open_files::compute_open_file_diagnostics;
38
39pub struct Backend {
40    client: Client,
41    docs: Arc<DocumentStore>,
42    /// Open-file state: text, version token, parse diagnostics.
43    /// Files that are only background-indexed (never opened in the editor)
44    /// do not appear here; they live only in `DocumentStore`'s salsa layer.
45    open_files: OpenFiles,
46    root_paths: Arc<ArcSwap<Vec<PathBuf>>>,
47    psr4: Arc<ArcSwap<Psr4Map>>,
48    meta: Arc<ArcSwap<PhpStormMeta>>,
49    config: Arc<ArcSwap<LspConfig>>,
50}
51
52impl Backend {
53    pub fn new(client: Client) -> Self {
54        // No imperative Codebase field anymore — analysis reads the
55        // salsa-memoized `codebase` query, which composes bundled stubs + every
56        // file's StubSlice and returns a fresh `Arc<Codebase>` (or the memoized
57        // one when inputs are unchanged).
58        let docs = Arc::new(DocumentStore::new());
59        let psr4 = docs.psr4_arc();
60        Backend {
61            client,
62            docs,
63            open_files: OpenFiles::new(),
64            root_paths: Arc::new(ArcSwap::from_pointee(Vec::new())),
65            psr4,
66            meta: Arc::new(ArcSwap::from_pointee(PhpStormMeta::default())),
67            config: Arc::new(ArcSwap::from_pointee(LspConfig::default())),
68        }
69    }
70
71    /// `$/php-lsp/debugStats` — internal observability counters. Currently just
72    /// the cumulative real-parse count, used by the references stress tests to
73    /// assert the read path doesn't parse the whole workspace.
74    pub async fn debug_stats(&self) -> tower_lsp::jsonrpc::Result<DebugStats> {
75        Ok(DebugStats {
76            parses: self.docs.parse_count(),
77        })
78    }
79
80    fn set_open_text(&self, uri: Url, text: String) -> u64 {
81        self.open_files.set_open_text(&self.docs, uri, text)
82    }
83
84    fn close_open_file(&self, uri: &Url) {
85        self.open_files.close(&self.docs, uri);
86    }
87
88    /// Background-index a file from disk, but only if it isn't currently
89    /// open in the editor — the editor's buffer is authoritative while a
90    /// file is open, and we must not overwrite it with disk contents.
91    fn ingest_if_not_open(&self, uri: Url, text: &str) {
92        if !self.open_files.contains(&uri) {
93            self.docs.ingest(uri, text);
94        }
95    }
96
97    /// Variant of [`ingest_if_not_open`] that reuses an already-parsed doc.
98    fn ingest_from_doc_if_not_open(&self, uri: Url, doc: &ParsedDoc) {
99        if !self.open_files.contains(&uri) {
100            self.docs.ingest_from_doc(uri, doc);
101        }
102    }
103
104    fn get_open_text(&self, uri: &Url) -> Option<String> {
105        self.open_files.text(uri)
106    }
107
108    fn set_parse_diagnostics(&self, uri: &Url, diagnostics: Vec<Diagnostic>) {
109        self.open_files.set_parse_diagnostics(uri, diagnostics);
110    }
111
112    fn get_parse_diagnostics(&self, uri: &Url) -> Option<Vec<Diagnostic>> {
113        self.open_files.parse_diagnostics(uri)
114    }
115
116    fn all_open_files_with_diagnostics(&self) -> Vec<(Url, Vec<Diagnostic>, Option<i64>)> {
117        self.open_files.all_with_diagnostics()
118    }
119
120    fn open_urls(&self) -> Vec<Url> {
121        self.open_files.urls()
122    }
123
124    fn get_doc(&self, uri: &Url) -> Option<Arc<ParsedDoc>> {
125        self.open_files.get_doc(&self.docs, uri)
126    }
127
128    /// `use Foo as Bar;` map for a single file, read directly from the AST.
129    fn file_imports(&self, uri: &Url) -> std::collections::HashMap<String, String> {
130        self.docs
131            .get_doc_salsa(uri)
132            .map(|doc| crate::references::collect_file_imports(&doc))
133            .unwrap_or_default()
134    }
135
136    /// Reference call sites for a class's `__construct`.
137    ///
138    /// The constructor's call sites are `new OwningClass(...)`, not
139    /// `->__construct()`, so name-only matching would return every class's
140    /// constructor declaration. We search for `new` expressions only, scoped to
141    /// the owning class.
142    ///
143    /// `class_name` is the FQN when the constructor is inside a namespace
144    /// (e.g. `"Shop\\Order"`). The AST walker searches for the *short* name
145    /// (`"Order"`) since that's what appears at call sites, while the FQN is
146    /// used only to scope the search and prevent collisions between two classes
147    /// with the same short name in different namespaces.
148    fn construct_references(
149        &self,
150        uri: &Url,
151        source: &str,
152        position: Position,
153        class_name: &str,
154        include_declaration: bool,
155    ) -> Vec<Location> {
156        let short_name = fqn_short_name(class_name).to_owned();
157        let class_fqn = class_name.contains('\\').then_some(class_name);
158        // Prefilter to files mentioning the short class name before parsing.
159        let candidate_docs = self.docs.candidate_docs_for(&short_name);
160        // `find_constructor_references` walks `new` expressions directly —
161        // bypasses the codebase/salsa index whose `ClassReference` key is too
162        // broad (covers type hints, `instanceof`, `extends`, `implements`).
163        let mut locations = find_constructor_references(&short_name, &candidate_docs, class_fqn);
164        // The cursor is already on the `__construct` name, so derive the span
165        // from the identifier under the cursor rather than re-searching via
166        // str_offset (which finds the first occurrence in the file and would
167        // point at the wrong constructor in files with more than one class).
168        if include_declaration && let Some(range) = crate::text::word_range_at(source, position) {
169            locations.push(Location {
170                uri: uri.clone(),
171                range,
172            });
173        }
174        locations
175    }
176
177    /// Resolve the FQN of the symbol at the cursor so reference lookups can match
178    /// by exact FQN instead of short name (fixes cross-namespace overmatch for
179    /// Function/Class and unrelated-class overmatch for Method via the owning
180    /// FQCN). Returns `None` when the kind doesn't carry an FQN or it can't be
181    /// resolved. For class constants, returns the owning class short name.
182    fn resolve_reference_target_fqn(
183        &self,
184        uri: &Url,
185        doc_opt: Option<&Arc<ParsedDoc>>,
186        word: &str,
187        kind: Option<crate::navigation::references::SymbolKind>,
188        position: Position,
189        constant_owner: Option<String>,
190    ) -> Option<String> {
191        use crate::navigation::references::SymbolKind;
192        let doc = doc_opt?;
193        let imports = self.file_imports(uri);
194        match kind {
195            Some(SymbolKind::Function) | Some(SymbolKind::Class) => {
196                let resolved = crate::navigation::moniker::resolve_fqn(doc, word, &imports);
197                resolved.contains('\\').then_some(resolved)
198            }
199            Some(SymbolKind::Method) => {
200                // Owning FQCN: the class/interface/trait/enum that contains the cursor.
201                let short_owner =
202                    crate::types::type_map::enclosing_class_at(doc.source(), doc, position)?;
203                // `resolve_fqn` walks the doc and applies the namespace prefix if any.
204                Some(crate::navigation::moniker::resolve_fqn(
205                    doc,
206                    &short_owner,
207                    &imports,
208                ))
209            }
210            Some(SymbolKind::Property) => {
211                // Only resolve the owning class when the cursor is on a property
212                // declaration — for access sites (`$obj->prop`) enclosing_class_at
213                // returns the accessing class, not the declaring class, so the session
214                // would be queried with the wrong key. Access sites fall back to the
215                // AST walker which finds all `->prop` occurrences.
216                let stmts = &doc.program().stmts;
217                crate::backend::helpers::cursor_is_on_property_decl(doc.source(), stmts, position)?;
218                let short_owner =
219                    crate::types::type_map::enclosing_class_at(doc.source(), doc, position)?;
220                Some(crate::navigation::moniker::resolve_fqn(
221                    doc,
222                    &short_owner,
223                    &imports,
224                ))
225            }
226            Some(SymbolKind::Constant) => {
227                if constant_owner.is_some() {
228                    // Class constant: the owning class short name as-is.
229                    constant_owner
230                } else {
231                    // Global/namespace constant: compute FQN so cross-namespace
232                    // references like `\Config\DB_HOST` can be found.
233                    let fqn = crate::navigation::moniker::resolve_fqn(doc, word, &imports);
234                    fqn.contains('\\').then_some(fqn)
235                }
236            }
237            _ => None,
238        }
239    }
240
241    /// Resolve the PHP version to use. See `autoload::resolve_php_version_from_roots`
242    /// for the full priority order.
243    fn resolve_php_version(&self, explicit: Option<&str>) -> (String, &'static str) {
244        let roots = self.root_paths.load();
245        crate::lang::autoload::resolve_php_version_from_roots(&roots, explicit)
246    }
247}
248
249/// Refine the cursor's `(word, kind)` for a references request using
250/// declaration-aware heuristics, returning the (possibly rewritten) word, its
251/// symbol kind, and — for class constants — the owning class short name.
252///
253/// Checks, in order: promoted constructor property params (so `$name` in
254/// `__construct(public string $name)` resolves to the `->name` property, not
255/// `$name` variable occurrences), then method / property / constant
256/// declarations, falling back to the character-based `symbol_kind_at` heuristic.
257fn resolve_reference_symbol(
258    doc_opt: Option<&Arc<ParsedDoc>>,
259    source: &str,
260    position: Position,
261    word: String,
262) -> (
263    String,
264    Option<crate::navigation::references::SymbolKind>,
265    Option<String>,
266) {
267    use crate::navigation::references::SymbolKind;
268    let mut constant_owner: Option<String> = None;
269    let (word, kind) = if let Some(doc) = doc_opt
270        && let Some(prop_name) =
271            promoted_property_at_cursor(doc.source(), &doc.program().stmts, position)
272    {
273        (prop_name, Some(SymbolKind::Property))
274    } else if let Some(doc) = doc_opt {
275        let stmts = &doc.program().stmts;
276        if cursor_is_on_method_decl(doc.source(), stmts, position) {
277            (word, Some(SymbolKind::Method))
278        } else if let Some(prop_name) = cursor_is_on_property_decl(doc.source(), stmts, position) {
279            (prop_name, Some(SymbolKind::Property))
280        } else if let Some((const_name, owner)) =
281            cursor_is_on_constant_decl(doc.source(), stmts, position)
282        {
283            constant_owner = owner;
284            (const_name, Some(SymbolKind::Constant))
285        } else {
286            let k = symbol_kind_at(source, position, &word);
287            // For constant access sites (`ClassName::CONST`, `self::CONST`),
288            // extract the owning class so the constant walker is scoped to
289            // the right class rather than falling back to the global-constant
290            // path (which would look for a top-level constant named `CONST`).
291            if matches!(k, Some(SymbolKind::Constant))
292                && let Some(raw) = class_before_double_colon(source, position)
293            {
294                constant_owner = Some(match raw.as_str() {
295                    "self" | "static" => {
296                        crate::types::type_map::enclosing_class_at(doc.source(), doc, position)
297                            .unwrap_or(raw)
298                    }
299                    _ => raw,
300                });
301            }
302            (word, k)
303        }
304    } else {
305        let k = symbol_kind_at(source, position, &word);
306        (word, k)
307    };
308    (word, kind, constant_owner)
309}
310
311/// Extract the class name (or pseudo-keyword) immediately to the left of `::` at
312/// the cursor position. Returns `None` when the cursor is not on an identifier
313/// preceded by `::`.
314///
315/// Used to populate `constant_owner` for constant access sites so that
316/// `Status::ACTIVE` (cursor on `ACTIVE`) scopes the constant walker to `Status`
317/// rather than treating `ACTIVE` as a global constant.
318fn class_before_double_colon(source: &str, position: Position) -> Option<String> {
319    let line = source.lines().nth(position.line as usize)?;
320    let chars: Vec<char> = line.chars().collect();
321    let col = position.character as usize;
322
323    let mut utf16_col = 0usize;
324    let mut char_idx = 0usize;
325    for ch in &chars {
326        if utf16_col >= col {
327            break;
328        }
329        utf16_col += ch.len_utf16();
330        char_idx += 1;
331    }
332
333    let is_word = |c: char| c.is_alphanumeric() || c == '_';
334    while char_idx > 0 && is_word(chars[char_idx - 1]) {
335        char_idx -= 1;
336    }
337
338    if char_idx < 2 || chars[char_idx - 1] != ':' || chars[char_idx - 2] != ':' {
339        return None;
340    }
341
342    let class_end = char_idx - 2;
343    let mut class_start = class_end;
344    while class_start > 0 && (is_word(chars[class_start - 1]) || chars[class_start - 1] == '\\') {
345        class_start -= 1;
346    }
347
348    let name: String = chars[class_start..class_end].iter().collect();
349    if name.is_empty() { None } else { Some(name) }
350}
351
352/// Off-`self` variant of `Backend::compute_dependent_publishes`. Needed
353/// because did_change's blocking republish runs inside a detached
354/// `tokio::spawn` that captures `Arc<Backend>` indirectly via clones of
355/// `docs` / `open_files` rather than `&self`.
356async fn compute_dependent_publishes_owned(
357    docs: Arc<DocumentStore>,
358    open_files: OpenFiles,
359    changed_uri: Url,
360    diag_cfg: crate::lang::config::DiagnosticsConfig,
361) -> Vec<(Url, Vec<Diagnostic>)> {
362    tokio::task::spawn_blocking(move || {
363        // Ask mir which files actually depend on `changed_uri` and let it
364        // re-run Pass 2 for them in parallel. mir 0.25's dependency graph
365        // covers every reference kind that can produce a cross-file
366        // diagnostic (imports, class hierarchy, type hints, instanceof,
367        // catch, ::class, ::CONST, `new`, static and instance calls) and
368        // tracks symbols-deleted-from-a-file so renames / deletions still
369        // surface the orphaned dependents.
370        let php_version = docs.workspace_php_version();
371        let session = docs.analysis_session(php_version);
372        let analyses = session.reanalyze_dependents(changed_uri.as_str());
373        if analyses.is_empty() {
374            return Vec::new();
375        }
376
377        // We only publish for files the editor has open. Filter the
378        // session-wide dependent set down to open URLs.
379        let open_urls: std::collections::HashSet<Url> = open_files
380            .urls()
381            .into_iter()
382            .filter(|u| u != &changed_uri)
383            .collect();
384        let dependents: Vec<(Url, mir_analyzer::FileAnalysis)> = analyses
385            .into_iter()
386            .filter_map(|(file, analysis)| {
387                let url = Url::parse(file.as_ref()).ok()?;
388                open_urls.contains(&url).then_some((url, analysis))
389            })
390            .collect();
391        if dependents.is_empty() {
392            return Vec::new();
393        }
394
395        // Workspace-level class issues (circular inheritance, override
396        // violations, abstract-method gaps) aren't in `FileAnalysis` —
397        // pull them in one batched call covering every affected file.
398        let dep_files: Vec<Arc<str>> = dependents
399            .iter()
400            .map(|(u, _)| Arc::from(u.as_str()))
401            .collect();
402        let class_issues = session.class_issues(&dep_files);
403        let mut class_issues_by_file: std::collections::HashMap<Arc<str>, Vec<mir_issues::Issue>> =
404            std::collections::HashMap::new();
405        for issue in class_issues {
406            if issue.suppressed {
407                continue;
408            }
409            let file = issue.location.file.clone();
410            class_issues_by_file.entry(file).or_default().push(issue);
411        }
412
413        let mut out: Vec<(Url, Vec<Diagnostic>)> = Vec::with_capacity(dependents.len());
414        for (url, analysis) in dependents {
415            let parse = open_files.parse_diagnostics(&url).unwrap_or_default();
416            let mut issues: Vec<mir_issues::Issue> = analysis
417                .issues
418                .into_iter()
419                .filter(|i| !i.suppressed)
420                .collect();
421            if let Some(extra) = class_issues_by_file.remove(&Arc::<str>::from(url.as_str())) {
422                issues.extend(extra);
423            }
424            let semantic =
425                crate::semantic_diagnostics::issues_to_diagnostics(&issues, &url, &diag_cfg);
426            out.push((url, merge_file_diagnostics(parse, semantic)));
427        }
428        out
429    })
430    .await
431    .unwrap_or_default()
432}
433
434/// Compute and publish diagnostics for `uri`, then republish any open files
435/// that depend on it. Requires `open_files.set_parse_diagnostics` to be up to
436/// date for `uri` before this is called.
437pub(super) async fn publish_with_dependents(
438    client: Client,
439    docs: Arc<DocumentStore>,
440    open_files: OpenFiles,
441    uri: Url,
442    diag_cfg: crate::lang::config::DiagnosticsConfig,
443) {
444    let docs_ref = Arc::clone(&docs);
445    let open_files_ref = open_files.clone();
446    let uri_ref = uri.clone();
447    let diag_cfg_ref = diag_cfg.clone();
448    let all_diags = tokio::task::spawn_blocking(move || {
449        compute_open_file_diagnostics(&docs_ref, &open_files_ref, &uri_ref, &diag_cfg_ref)
450    })
451    .await
452    .unwrap_or_default();
453    client
454        .publish_diagnostics(uri.clone(), all_diags, None)
455        .await;
456    let dependents = compute_dependent_publishes_owned(docs, open_files, uri, diag_cfg).await;
457    for (dep_uri, dep_diags) in dependents {
458        client.publish_diagnostics(dep_uri, dep_diags, None).await;
459    }
460}
461
462/// Generate a stable result_id for diagnostics. Uses the count and position of diagnostics
463/// to create a stable identifier. Same diagnostics = same result_id.
464fn compute_diagnostic_result_id(diagnostics: &[Diagnostic], uri: &str) -> String {
465    use std::collections::hash_map::DefaultHasher;
466    use std::hash::{Hash, Hasher};
467
468    let mut hasher = DefaultHasher::new();
469    uri.hash(&mut hasher);
470    diagnostics.len().hash(&mut hasher);
471
472    for diag in diagnostics {
473        diag.range.start.line.hash(&mut hasher);
474        diag.range.start.character.hash(&mut hasher);
475        diag.range.end.line.hash(&mut hasher);
476        diag.range.end.character.hash(&mut hasher);
477        diag.message.hash(&mut hasher);
478        let severity_val = match diag.severity {
479            Some(tower_lsp::lsp_types::DiagnosticSeverity::ERROR) => 1,
480            Some(tower_lsp::lsp_types::DiagnosticSeverity::WARNING) => 2,
481            Some(tower_lsp::lsp_types::DiagnosticSeverity::INFORMATION) => 3,
482            Some(tower_lsp::lsp_types::DiagnosticSeverity::HINT) => 4,
483            None => 0,
484            _ => 5, // Unknown variants
485        };
486        severity_val.hash(&mut hasher);
487        if let Some(code) = &diag.code {
488            format!("{:?}", code).hash(&mut hasher);
489        }
490        if let Some(source) = &diag.source {
491            source.hash(&mut hasher);
492        }
493        if let Some(tags) = &diag.tags {
494            for tag in tags {
495                let tag_val = match *tag {
496                    tower_lsp::lsp_types::DiagnosticTag::UNNECESSARY => 1,
497                    tower_lsp::lsp_types::DiagnosticTag::DEPRECATED => 2,
498                    _ => 3,
499                };
500                tag_val.hash(&mut hasher);
501            }
502        }
503    }
504
505    format!("v1:{:x}", hasher.finish())
506}
507
508mod handlers;
509mod helpers;
510pub mod panic_guard;
511mod server;
512#[cfg(test)]
513mod tests;