php-lsp 0.11.0

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
//! Per-file memoized symbol table.
//!
//! [`SymbolMap`] is a pre-computed `HashMap<name, Vec<SymbolEntry>>` built from
//! a parsed PHP file in one AST pass. Each entry stores the precise LSP `Range`
//! of the identifier, the declaration kind, whether it is abstract, a
//! pre-rendered hover signature, and a pre-extracted docblock (as markdown).
//!
//! Because building the map is O(AST_size) but lookup is O(1), the payoff is
//! on the cross-file / `other_docs` path: a stable file (one that hasn't changed
//! since the last keystroke) has its map served from the salsa cache rather than
//! re-walking its AST on every request. See [`crate::db::symbol_map`] for the
//! salsa query that drives this.

use std::collections::HashMap;

use php_ast::{ClassMemberKind, EnumMemberKind, NamespaceBody, Stmt, StmtKind};
use tower_lsp::lsp_types::Range;

use crate::document::ast::ParsedDoc;
use crate::hover::formatting::declaration_signature;
use crate::types::resolve::{Container, Declaration};

/// Which kind of PHP declaration this entry represents. Mirrors the variants of
/// [`Declaration`] so callers can reconstruct any accept predicate without an
/// AST walk.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SymbolEntryKind {
    Function,
    Class,
    Interface,
    Trait,
    Enum,
    Method { container: Container },
    ClassConst { container: Container },
    Property { container: Container },
    PromotedParam,
    EnumCase,
}

/// A single resolved declaration stored in the pre-computed symbol map.
#[derive(Debug, Clone)]
pub struct SymbolEntry {
    /// Precise LSP range of the identifier (not the full declaration span).
    pub name_range: Range,
    pub kind: SymbolEntryKind,
    /// Whether the declaration is abstract (interface members, abstract methods).
    /// Used to reconstruct `goto_declaration`'s two-pass abstract-first logic.
    pub is_abstract: bool,
    /// Pre-rendered hover signature (e.g. `function foo(int $x): void`).
    /// `None` for properties and promoted parameters, which use the mir path.
    pub signature: Option<String>,
    /// Pre-extracted docblock rendered as markdown. `None` when no docblock
    /// precedes the declaration.
    pub doc_markdown: Option<String>,
}

/// Pre-computed symbol table for a single PHP file.
///
/// Built by [`SymbolMap::build`] in one AST pass; looked up in O(1) via
/// [`SymbolMap::lookup`]. The `Vec` per key preserves source order so that
/// predicates applied by [`lookup`] (e.g. "abstract first") stay correct.
#[derive(Clone, Default)]
pub struct SymbolMap {
    entries: HashMap<String, Vec<SymbolEntry>>,
}

impl SymbolMap {
    /// Walk `doc`'s AST once and build the complete symbol map.
    pub fn build(doc: &ParsedDoc) -> Self {
        let sv = doc.view();
        let mut entries: HashMap<String, Vec<SymbolEntry>> = HashMap::new();
        collect_stmts(&doc.program().stmts, sv, &mut entries);
        SymbolMap { entries }
    }

    /// Find the first entry with key `name` that `accept` approves, in source
    /// order — matching [`resolve_declaration`]'s first-match semantics.
    pub fn lookup(
        &self,
        name: &str,
        accept: impl Fn(&SymbolEntry) -> bool,
    ) -> Option<&SymbolEntry> {
        self.entries.get(name)?.iter().find(|e| accept(e))
    }

    /// Number of distinct symbol names (for size estimation / tests).
    #[cfg(test)]
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Whether the map holds no symbols.
    #[cfg(test)]
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

/// Parse a doc-comment already attached by the parser and render it as markdown.
/// Returns `None` when the docblock has no visible content.
fn doc_to_markdown(c: &php_ast::Comment<'_>) -> Option<String> {
    let md = crate::lang::docblock::parse_docblock(c.text).to_markdown();
    if md.is_empty() { None } else { Some(md) }
}

fn collect_stmts<'a>(
    stmts: &'a [Stmt<'a, 'a>],
    sv: crate::document::ast::SourceView<'_>,
    out: &mut HashMap<String, Vec<SymbolEntry>>,
) {
    for stmt in stmts {
        match &stmt.kind {
            StmtKind::Function(f) => {
                let Some(name) = f.name.as_str() else {
                    continue;
                };
                let decl = Declaration::Function {
                    decl: f,
                    stmt_span: stmt.span,
                };
                let sig = declaration_signature(&decl, name);
                let doc_markdown = f.doc_comment.as_ref().and_then(doc_to_markdown);
                push(
                    out,
                    name.to_owned(),
                    SymbolEntry {
                        name_range: sv.name_range_in_span(name, stmt.span),
                        kind: SymbolEntryKind::Function,
                        is_abstract: false,
                        signature: sig,
                        doc_markdown,
                    },
                );
            }

            StmtKind::Class(c) => {
                // Class name entry.
                if let Some(name_ident) = c.name {
                    let name = name_ident.or_error();
                    let decl = Declaration::Class {
                        decl: c,
                        name: name_ident,
                        stmt_span: stmt.span,
                    };
                    let sig = declaration_signature(&decl, name);
                    let doc_markdown = c.doc_comment.as_ref().and_then(doc_to_markdown);
                    push(
                        out,
                        name.to_owned(),
                        SymbolEntry {
                            name_range: sv.name_range_in_span(name, stmt.span),
                            kind: SymbolEntryKind::Class,
                            is_abstract: c.modifiers.is_abstract,
                            signature: sig,
                            doc_markdown,
                        },
                    );
                }
                collect_members(c.body.members.iter(), sv, Container::Class, out);
            }

            StmtKind::Interface(i) => {
                let name = i.name.or_error();
                let decl = Declaration::Interface {
                    decl: i,
                    stmt_span: stmt.span,
                };
                let sig = declaration_signature(&decl, name);
                let doc_markdown = i.doc_comment.as_ref().and_then(doc_to_markdown);
                push(
                    out,
                    name.to_owned(),
                    SymbolEntry {
                        name_range: sv.name_range_in_span(name, stmt.span),
                        kind: SymbolEntryKind::Interface,
                        is_abstract: true,
                        signature: sig,
                        doc_markdown,
                    },
                );
                collect_members(i.body.members.iter(), sv, Container::Interface, out);
            }

            StmtKind::Trait(t) => {
                let name = t.name.or_error();
                let decl = Declaration::Trait {
                    decl: t,
                    stmt_span: stmt.span,
                };
                let sig = declaration_signature(&decl, name);
                let doc_markdown = t.doc_comment.as_ref().and_then(doc_to_markdown);
                push(
                    out,
                    name.to_owned(),
                    SymbolEntry {
                        name_range: sv.name_range_in_span(name, stmt.span),
                        kind: SymbolEntryKind::Trait,
                        is_abstract: false,
                        signature: sig,
                        doc_markdown,
                    },
                );
                collect_members(t.body.members.iter(), sv, Container::Trait, out);
            }

            StmtKind::Enum(e) => {
                let name = e.name.or_error();
                let decl = Declaration::Enum {
                    decl: e,
                    stmt_span: stmt.span,
                };
                let sig = declaration_signature(&decl, name);
                let doc_markdown = e.doc_comment.as_ref().and_then(doc_to_markdown);
                push(
                    out,
                    name.to_owned(),
                    SymbolEntry {
                        name_range: sv.name_range_in_span(name, stmt.span),
                        kind: SymbolEntryKind::Enum,
                        is_abstract: false,
                        signature: sig,
                        doc_markdown,
                    },
                );

                for member in e.body.members.iter() {
                    match &member.kind {
                        EnumMemberKind::Case(c) => {
                            let case_name = c.name.or_error();
                            let case_decl = Declaration::EnumCase {
                                case: c,
                                enum_name: e.name,
                                member_span: member.span,
                            };
                            let sig = declaration_signature(&case_decl, case_name);
                            let doc_markdown = c.doc_comment.as_ref().and_then(doc_to_markdown);
                            push(
                                out,
                                case_name.to_owned(),
                                SymbolEntry {
                                    name_range: sv.name_range_in_span(case_name, member.span),
                                    kind: SymbolEntryKind::EnumCase,
                                    is_abstract: false,
                                    signature: sig,
                                    doc_markdown,
                                },
                            );
                        }
                        EnumMemberKind::Method(m) => {
                            let mname = m.name.or_error();
                            let m_decl = Declaration::Method {
                                method: m,
                                container: Container::Enum,
                                member_span: member.span,
                            };
                            let sig = declaration_signature(&m_decl, mname);
                            let doc_markdown = m.doc_comment.as_ref().and_then(doc_to_markdown);
                            push(
                                out,
                                mname.to_owned(),
                                SymbolEntry {
                                    name_range: sv.name_range_in_span(mname, member.span),
                                    kind: SymbolEntryKind::Method {
                                        container: Container::Enum,
                                    },
                                    is_abstract: false,
                                    signature: sig,
                                    doc_markdown,
                                },
                            );
                        }
                        EnumMemberKind::ClassConst(cc) => {
                            let cc_name = cc.name.or_error();
                            let cc_decl = Declaration::ClassConst {
                                konst: cc,
                                container: Container::Enum,
                                member_span: member.span,
                            };
                            let sig = declaration_signature(&cc_decl, cc_name);
                            let doc_markdown = cc.doc_comment.as_ref().and_then(doc_to_markdown);
                            push(
                                out,
                                cc_name.to_owned(),
                                SymbolEntry {
                                    name_range: sv.name_range_in_span(cc_name, member.span),
                                    kind: SymbolEntryKind::ClassConst {
                                        container: Container::Enum,
                                    },
                                    is_abstract: false,
                                    signature: sig,
                                    doc_markdown,
                                },
                            );
                        }
                        _ => {}
                    }
                }
            }

            StmtKind::Namespace(ns) => {
                if let NamespaceBody::Braced(inner) = &ns.body {
                    collect_stmts(&inner.stmts, sv, out);
                }
            }

            _ => {}
        }
    }
}

fn collect_members<'a>(
    members: impl Iterator<Item = &'a php_ast::ClassMember<'a, 'a>>,
    sv: crate::document::ast::SourceView<'_>,
    container: Container,
    out: &mut HashMap<String, Vec<SymbolEntry>>,
) {
    for member in members {
        match &member.kind {
            ClassMemberKind::Method(m) => {
                let mname = m.name.or_error();
                let m_decl = Declaration::Method {
                    method: m,
                    container,
                    member_span: member.span,
                };
                let sig = declaration_signature(&m_decl, mname);
                let doc_markdown = m.doc_comment.as_ref().and_then(doc_to_markdown);
                let name_range = sv.name_range_in_span(mname, member.span);
                let is_abstract = match container {
                    Container::Interface => true,
                    Container::Class | Container::Trait => m.is_abstract,
                    Container::Enum => false,
                };
                push(
                    out,
                    mname.to_owned(),
                    SymbolEntry {
                        name_range,
                        kind: SymbolEntryKind::Method { container },
                        is_abstract,
                        signature: sig,
                        doc_markdown,
                    },
                );

                // Constructor-promoted parameters (only for Container::Class).
                if container == Container::Class && m.name == "__construct" {
                    for p in m.params.iter() {
                        if p.visibility.is_some() {
                            let pname = p.name.or_error();
                            let bare = pname.trim_start_matches('$');
                            push(
                                out,
                                bare.to_owned(),
                                SymbolEntry {
                                    name_range: sv.name_range_in_span(pname, p.span),
                                    kind: SymbolEntryKind::PromotedParam,
                                    is_abstract: false,
                                    signature: None,
                                    doc_markdown: None,
                                },
                            );
                        }
                    }
                }
            }

            ClassMemberKind::ClassConst(cc) => {
                let cc_name = cc.name.or_error();
                let cc_decl = Declaration::ClassConst {
                    konst: cc,
                    container,
                    member_span: member.span,
                };
                let sig = declaration_signature(&cc_decl, cc_name);
                let doc_markdown = cc.doc_comment.as_ref().and_then(doc_to_markdown);
                let name_range = sv.name_range_in_span(cc_name, member.span);
                push(
                    out,
                    cc_name.to_owned(),
                    SymbolEntry {
                        name_range,
                        kind: SymbolEntryKind::ClassConst { container },
                        is_abstract: false,
                        signature: sig,
                        doc_markdown,
                    },
                );
            }

            ClassMemberKind::Property(p) => {
                let pname = p.name.or_error();
                let bare = pname.trim_start_matches('$');
                // Properties: signature rendered via mir, not here.
                let name_range = sv.name_range_in_span(pname, member.span);
                push(
                    out,
                    bare.to_owned(),
                    SymbolEntry {
                        name_range,
                        kind: SymbolEntryKind::Property { container },
                        is_abstract: false,
                        signature: None,
                        doc_markdown: None,
                    },
                );
            }

            _ => {}
        }
    }
}

fn push(out: &mut HashMap<String, Vec<SymbolEntry>>, key: String, entry: SymbolEntry) {
    out.entry(key).or_default().push(entry);
}

/// Reconstruct the `is_hoverable` predicate from a stored [`SymbolEntryKind`].
pub fn is_hoverable_kind(kind: SymbolEntryKind) -> bool {
    !matches!(
        kind,
        SymbolEntryKind::Property { .. } | SymbolEntryKind::PromotedParam
    )
}

/// `goto_declaration` pass 1: abstract/interface declarations.
pub fn is_abstract_entry(e: &SymbolEntry) -> bool {
    match e.kind {
        SymbolEntryKind::Interface => true,
        SymbolEntryKind::Method {
            container: Container::Interface,
        } => true,
        SymbolEntryKind::Method {
            container: Container::Class | Container::Trait,
        } => e.is_abstract,
        _ => false,
    }
}

/// `goto_declaration` pass 2: any declaration except promoted params.
pub fn is_any_entry(e: &SymbolEntry) -> bool {
    !matches!(e.kind, SymbolEntryKind::PromotedParam)
}

/// `goto_definition`: skip enum constants (matching original walker).
pub fn is_definition_entry(e: &SymbolEntry) -> bool {
    !matches!(
        e.kind,
        SymbolEntryKind::ClassConst {
            container: Container::Enum
        }
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    fn build(src: &str) -> SymbolMap {
        let doc = ParsedDoc::parse(src.to_owned());
        SymbolMap::build(&doc)
    }

    #[test]
    fn top_level_function() {
        let m = build("<?php\nfunction greet(string $name): string { return $name; }");
        let e = m.lookup("greet", |_| true).unwrap();
        assert_eq!(e.kind, SymbolEntryKind::Function);
        assert!(!e.is_abstract);
        assert_eq!(
            e.signature.as_deref(),
            Some("function greet(string $name): string")
        );
    }

    #[test]
    fn class_with_abstract_method() {
        let m = build("<?php\nabstract class Foo {\n    abstract public function bar(): void;\n}");
        let cls = m.lookup("Foo", |_| true).unwrap();
        assert_eq!(cls.kind, SymbolEntryKind::Class);
        assert!(cls.is_abstract);

        let method = m
            .lookup("bar", |e| {
                matches!(
                    e.kind,
                    SymbolEntryKind::Method {
                        container: Container::Class
                    }
                )
            })
            .unwrap();
        assert!(method.is_abstract);
    }

    #[test]
    fn interface_member_is_abstract() {
        let m = build("<?php\ninterface Shape {\n    public function area(): float;\n}");
        let method = m.lookup("area", |_| true).unwrap();
        assert!(method.is_abstract);
        assert_eq!(
            method.kind,
            SymbolEntryKind::Method {
                container: Container::Interface
            }
        );
    }

    #[test]
    fn enum_entries() {
        let m = build("<?php\nenum Color {\n    case Red;\n    case Blue;\n}");
        assert!(m.lookup("Color", |_| true).is_some());
        assert!(m.lookup("Red", |_| true).is_some());
        assert!(m.lookup("Blue", |_| true).is_some());
    }

    #[test]
    fn promoted_param_keyed_without_dollar() {
        let m = build(
            "<?php\nclass Point {\n    public function __construct(\n        public float $x,\n        public float $y,\n    ) {}\n}",
        );
        assert!(
            m.lookup("x", |e| matches!(e.kind, SymbolEntryKind::PromotedParam))
                .is_some()
        );
        assert!(
            m.lookup("y", |e| matches!(e.kind, SymbolEntryKind::PromotedParam))
                .is_some()
        );
    }

    #[test]
    fn source_order_preserved() {
        // Both `render` in Interface and Trait: interface entry must come before
        // trait entry so the abstract-first lookup finds the right one.
        let m = build(
            "<?php\ninterface I {\n    public function render(): void;\n}\ntrait T {\n    abstract public function render(): void;\n}",
        );
        let entries = m.entries.get("render").unwrap();
        assert_eq!(
            entries[0].kind,
            SymbolEntryKind::Method {
                container: Container::Interface
            }
        );
        assert_eq!(
            entries[1].kind,
            SymbolEntryKind::Method {
                container: Container::Trait
            }
        );
    }

    #[test]
    fn docblock_extracted() {
        let m = build("<?php\n/** Greets the user. */\nfunction greet(): void {}");
        let e = m.lookup("greet", |_| true).unwrap();
        assert!(
            e.doc_markdown.is_some(),
            "expected docblock to be extracted"
        );
    }

    #[test]
    fn no_docblock_when_absent() {
        let m = build("<?php\nfunction greet(): void {}");
        let e = m.lookup("greet", |_| true).unwrap();
        assert!(e.doc_markdown.is_none());
    }
}