Skip to main content

php_lsp/analysis/
semantic_diagnostics.rs

1/// Semantic diagnostics bridge.
2///
3/// Delegates all analysis to the `mir-analyzer` crate and converts its `Issue`
4/// type into the `tower-lsp` `Diagnostic` type expected by the LSP backend.
5use tower_lsp_server::ls_types::{
6    Diagnostic, DiagnosticSeverity, NumberOrString, Position, Range, Uri,
7};
8
9use crate::analysis::diagnostics::PHP_LSP_SOURCE;
10use crate::document::ast::ParsedDoc;
11use crate::lang::config::DiagnosticsConfig;
12
13/// Run semantic checks on `doc` against the supplied `AnalysisSession`.
14/// Ingests the current file through mir's diagnostics-only path and returns
15/// LSP diagnostics filtered by `DiagnosticsConfig`.
16///
17/// Used only by `benches/semantic.rs` to measure raw analyzer cost. It is
18/// not on the production request path and skips `DocumentStore`'s salsa
19/// caching, PSR-4 lazy-loading, and `collector_issues` diagnostics — for
20/// that, see `DocumentStore::get_semantic_issues_salsa` and
21/// `compute_open_file_diagnostics`.
22pub fn semantic_diagnostics(
23    uri: &Uri,
24    doc: &ParsedDoc,
25    session: &mir_analyzer::AnalysisSession,
26    cfg: &DiagnosticsConfig,
27) -> Vec<Diagnostic> {
28    if !cfg.enabled {
29        return vec![];
30    }
31    let file: std::sync::Arc<str> = std::sync::Arc::from(uri.as_str());
32    let analysis = session.analyze_file_diagnostics(uri.as_str(), doc.source());
33    let class_issues = session.class_issues(std::slice::from_ref(&file));
34    analysis
35        .issues
36        .into_iter()
37        .chain(class_issues)
38        .filter(|i| !i.suppressed)
39        .filter(|i| issue_passes_filter(i, cfg))
40        .map(to_lsp_diagnostic)
41        .collect()
42}
43
44/// Convert pre-computed raw issues (from `db::semantic::semantic_issues`) into
45/// LSP diagnostics, applying the user's `DiagnosticsConfig` filter. Keeping
46/// filter + conversion outside the salsa query preserves memoization across
47/// config toggles (the user flipping a category must not rerun the analyzer).
48///
49/// `ParseError` issues are always excluded here, regardless of which mir API
50/// produced `issues`: php-lsp already surfaces raw parse errors as
51/// `SyntaxError` diagnostics from its own parser pass (see
52/// `crate::analysis::diagnostics::diagnostics_from_doc`), so this is the one
53/// place every issue source funnels through before becoming a `Diagnostic`.
54pub fn issues_to_diagnostics(
55    issues: &[mir_issues::Issue],
56    _uri: &Uri,
57    cfg: &DiagnosticsConfig,
58) -> Vec<Diagnostic> {
59    if !cfg.enabled {
60        return vec![];
61    }
62    issues
63        .iter()
64        .filter(|i| !matches!(i.kind, mir_issues::IssueKind::ParseError { .. }))
65        .filter(|i| issue_passes_filter(i, cfg))
66        .cloned()
67        .map(to_lsp_diagnostic)
68        .collect()
69}
70
71/// Like [`issues_to_diagnostics`], but additionally holds back
72/// workspace-symbol-dependent issues (see [`issue_needs_workspace_index`])
73/// while `index_ready` is `false`. Skips the extra filter/clone pass
74/// entirely once ready — the common case, well past server startup — so
75/// this costs nothing in steady state.
76pub fn issues_to_diagnostics_gated(
77    issues: &[mir_issues::Issue],
78    uri: &Uri,
79    cfg: &DiagnosticsConfig,
80    index_ready: bool,
81) -> Vec<Diagnostic> {
82    if index_ready {
83        return issues_to_diagnostics(issues, uri, cfg);
84    }
85    let filtered: Vec<mir_issues::Issue> = issues
86        .iter()
87        .filter(|i| !issue_needs_workspace_index(&i.kind))
88        .cloned()
89        .collect();
90    issues_to_diagnostics(&filtered, uri, cfg)
91}
92
93/// Whether resolving this issue required looking up a symbol (class,
94/// function, method, or trait) by name against the workspace-wide symbol
95/// table, as opposed to something derivable from the file's own contents.
96///
97/// Before the initial workspace scan finishes, that table only reflects the
98/// subset of files indexed so far, so these specific kinds can misreport a
99/// symbol declared in a not-yet-scanned file as undefined — see issue #242.
100/// Everything else (return-type mismatches, unreachable code, duplicate
101/// declarations within a file, etc.) is safe to report immediately: it's
102/// checked against the file's own text and can't be invalidated by more of
103/// the workspace becoming known.
104pub fn issue_needs_workspace_index(kind: &mir_issues::IssueKind) -> bool {
105    use mir_issues::IssueKind;
106    matches!(
107        kind,
108        IssueKind::UndefinedFunction { .. }
109            | IssueKind::UndefinedMethod { .. }
110            | IssueKind::UndefinedClass { .. }
111            | IssueKind::UndefinedTrait { .. }
112    )
113}
114
115/// Returns `true` if the mir-analyzer issue is allowed through by the config.
116fn issue_passes_filter(issue: &mir_issues::Issue, cfg: &DiagnosticsConfig) -> bool {
117    use mir_issues::IssueKind;
118    match &issue.kind {
119        IssueKind::UndefinedVariable { .. } | IssueKind::PossiblyUndefinedVariable { .. } => {
120            cfg.undefined_variables
121        }
122        IssueKind::UndefinedFunction { .. } | IssueKind::UndefinedMethod { .. } => {
123            cfg.undefined_functions
124        }
125        IssueKind::UndefinedClass { .. } | IssueKind::UndefinedTrait { .. } => {
126            cfg.undefined_classes
127        }
128        IssueKind::InvalidTraitUse { .. } => cfg.type_errors,
129        IssueKind::TooFewArguments { .. }
130        | IssueKind::TooManyArguments { .. }
131        | IssueKind::InvalidPassByReference { .. }
132        | IssueKind::InvalidNamedArgument { .. } => cfg.arity_errors,
133        // InvalidArgument covers both arity errors and type mismatches in mir-analyzer;
134        // show it if either toggle is on.
135        IssueKind::InvalidArgument { .. } | IssueKind::PossiblyInvalidArgument { .. } => {
136            cfg.arity_errors || cfg.type_errors
137        }
138        IssueKind::InvalidReturnType { .. }
139        | IssueKind::NullMethodCall { .. }
140        | IssueKind::NullPropertyFetch { .. }
141        | IssueKind::NullArrayAccess
142        | IssueKind::NullArgument { .. }
143        | IssueKind::PossiblyNullMethodCall { .. }
144        | IssueKind::PossiblyNullPropertyFetch { .. }
145        | IssueKind::PossiblyNullArrayAccess
146        | IssueKind::PossiblyNullArgument { .. }
147        | IssueKind::NullableReturnStatement { .. }
148        | IssueKind::InvalidPropertyAssignment { .. }
149        | IssueKind::InvalidOperand { .. }
150        | IssueKind::InvalidCast { .. }
151        | IssueKind::AbstractInstantiation { .. }
152        | IssueKind::MixedClone
153        | IssueKind::ReadonlyPropertyAssignment { .. }
154        | IssueKind::ArgumentTypeCoercion { .. } => cfg.type_errors,
155        IssueKind::DeprecatedCall { .. }
156        | IssueKind::DeprecatedMethodCall { .. }
157        | IssueKind::DeprecatedMethod { .. }
158        | IssueKind::DeprecatedClass { .. } => cfg.deprecated_calls,
159        IssueKind::CircularInheritance { .. } => cfg.type_errors,
160        IssueKind::DuplicateClass { .. }
161        | IssueKind::DuplicateInterface { .. }
162        | IssueKind::DuplicateTrait { .. }
163        | IssueKind::DuplicateEnum { .. }
164        | IssueKind::DuplicateFunction { .. } => cfg.duplicate_declarations,
165        IssueKind::UnusedVariable { .. }
166        | IssueKind::UnusedParam { .. }
167        | IssueKind::UnusedMethod { .. }
168        | IssueKind::UnusedProperty { .. }
169        | IssueKind::UnusedFunction { .. } => cfg.unused_symbols,
170        IssueKind::MissingReturnType { .. }
171        | IssueKind::MissingParamType { .. }
172        | IssueKind::MissingPropertyType { .. } => cfg.missing_types,
173        IssueKind::MixedArgument { .. }
174        | IssueKind::MixedAssignment { .. }
175        | IssueKind::MixedMethodCall { .. }
176        | IssueKind::MixedPropertyFetch { .. }
177        | IssueKind::MixedPropertyAssignment { .. }
178        | IssueKind::MixedArrayAccess
179        | IssueKind::MixedArrayOffset
180        | IssueKind::MixedReturnStatement { .. } => cfg.mixed_usage,
181        IssueKind::DocblockTypeContradiction { .. }
182        | IssueKind::UnevaluatedCode { .. }
183        | IssueKind::IfThisIsMismatch { .. } => true,
184        _ => true,
185    }
186}
187
188fn to_lsp_diagnostic(issue: mir_issues::Issue) -> Diagnostic {
189    // mir uses 1-based lines; LSP uses 0-based. Columns are 0-based on both sides.
190    let line = issue.location.line.saturating_sub(1);
191    let col_start = issue.location.col_start as u32;
192    let col_end = issue.location.col_end as u32;
193    Diagnostic {
194        range: Range {
195            start: Position {
196                line,
197                character: col_start,
198            },
199            end: Position {
200                line,
201                character: col_end.max(col_start + 1),
202            },
203        },
204        severity: Some(match issue.severity {
205            mir_issues::Severity::Error => DiagnosticSeverity::ERROR,
206            mir_issues::Severity::Warning => DiagnosticSeverity::WARNING,
207            mir_issues::Severity::Info => DiagnosticSeverity::INFORMATION,
208        }),
209        code: Some(NumberOrString::String(issue.kind.name().to_string())),
210        source: Some(PHP_LSP_SOURCE.to_string()),
211        message: issue.kind.message(),
212        ..Default::default()
213    }
214}
215
216#[cfg(test)]
217mod tests {
218    use super::*;
219
220    #[test]
221    fn to_lsp_diagnostic_sets_code_to_issue_kind_name() {
222        use mir_issues::{Issue, IssueKind, Location};
223        use std::sync::Arc;
224        use tower_lsp_server::ls_types::NumberOrString;
225
226        let location = Location {
227            file: Arc::from("file:///test.php"),
228            line: 1,
229            line_end: 1,
230            col_start: 0,
231            col_end: 3,
232        };
233        let issue = Issue::new(
234            IssueKind::UndefinedClass {
235                name: "Foo".to_string(),
236            },
237            location,
238        );
239        let diag = to_lsp_diagnostic(issue);
240        assert_eq!(
241            diag.code,
242            Some(NumberOrString::String("UndefinedClass".to_string())),
243            "diagnostic code must be the IssueKind name so code actions can match by type"
244        );
245        assert!(
246            diag.message.contains("Foo"),
247            "diagnostic message should mention the class name"
248        );
249    }
250}