phpantom_lsp 0.7.0

Fast PHP language server with deep type intelligence. Generics, Laravel, PHPStan annotations. Ready in an instant.
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
//! Workspace Symbols (`workspace/symbol`).
//!
//! Returns a flat list of symbols across the entire workspace so that
//! editors can display a "Go to Symbol in Workspace" picker (typically
//! triggered via Ctrl+T / Cmd+T).
//!
//! The handler builds the list from five data sources:
//!
//! 1. **`ast_map`** — provides `ClassInfo` records for every class,
//!    interface, trait, and enum across all indexed files.  Class members
//!    (methods, properties, constants) are also emitted with
//!    `container_name` set to the owning class FQN.
//!
//! 2. **`global_functions`** — provides `FunctionInfo` records keyed by
//!    name with associated file URIs.
//!
//! 3. **`global_defines`** — provides `DefineInfo` records for
//!    `define()` / top-level `const` declarations.
//!
//! 4. **`class_index`** — maps fully-qualified class names to file URIs
//!    for classes discovered during parsing but not necessarily open.
//!    Paired with `fqn_index` for rich metadata when available.
//!
//! 5. **`classmap`** — maps fully-qualified class names to file paths
//!    from Composer's `autoload_classmap.php`, covering vendor classes.

use std::collections::HashSet;

use tower_lsp::lsp_types::*;

use crate::Backend;
use crate::types::{ClassLikeKind, DefineInfo, FunctionInfo};
use crate::util::offset_to_position;

/// Maximum number of symbols returned for a single workspace/symbol request.
///
/// When the query is empty (or very short) the result set can be enormous.
/// We cap it to keep the response snappy and avoid overwhelming the client.
const MAX_RESULTS: usize = 500;

/// Relevance tier for sorting workspace symbol results.
///
/// Lower numeric values sort first (higher relevance).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum MatchTier {
    /// The symbol name exactly equals the query (case-insensitive).
    Exact = 0,
    /// The symbol name starts with the query (case-insensitive).
    Prefix = 1,
    /// The symbol name contains the query as a substring.
    Substring = 2,
}

/// A workspace symbol paired with its relevance tier for sorting.
struct RankedSymbol {
    symbol: SymbolInformation,
    tier: MatchTier,
}

/// Determine the match tier of `name` against `query_lower`.
///
/// `query_lower` must already be lowercased.  Returns `None` when
/// there is no match at all.
fn match_tier(name: &str, query_lower: &str) -> Option<MatchTier> {
    if query_lower.is_empty() {
        // Empty query matches everything at the lowest tier so that
        // alphabetical ordering is the only tiebreaker.
        return Some(MatchTier::Substring);
    }
    let name_lower = name.to_lowercase();
    if name_lower == query_lower {
        Some(MatchTier::Exact)
    } else if name_lower.starts_with(query_lower) {
        Some(MatchTier::Prefix)
    } else if name_lower.contains(query_lower) {
        Some(MatchTier::Substring)
    } else {
        None
    }
}

/// Extract the short name from a symbol name for relevance ranking.
///
/// For namespaced names like `"App\\Models\\User"`, returns `"User"`.
/// For member-qualified names like `"App\\Models\\User::findByEmail"`,
/// returns `"findByEmail"`.  For unqualified names, returns the input
/// as-is.
fn short_name(full_name: &str) -> &str {
    // Check for `::` first (class member notation).
    if let Some(idx) = full_name.rfind("::") {
        return &full_name[idx + 2..];
    }
    // Then check for `\` (namespace separator).
    if let Some(idx) = full_name.rfind('\\') {
        return &full_name[idx + 1..];
    }
    full_name
}

impl Backend {
    /// Handle a `workspace/symbol` request.
    ///
    /// Searches classes, interfaces, traits, enums, their members
    /// (methods, properties, class constants), standalone functions,
    /// and global constants across all indexed files plus vendor classes
    /// from the Composer classmap and class index.  The `query` string
    /// is matched as a case-insensitive substring against symbol names.
    /// An empty query returns symbols from parsed files only (not the
    /// full classmap/class_index) to avoid flooding the picker.
    ///
    /// Results are sorted by relevance: exact matches first, then prefix
    /// matches, then substring matches. Within each tier, symbols are
    /// sorted alphabetically by name.
    #[allow(deprecated)] // SymbolInformation::deprecated is deprecated in the LSP types crate
    pub fn handle_workspace_symbol(&self, query: &str) -> Option<Vec<SymbolInformation>> {
        let query_lower = query.to_lowercase();
        let mut ranked: Vec<RankedSymbol> = Vec::new();

        // Track FQNs already emitted so that class_index and classmap
        // don't produce duplicates for classes already in the ast_map.
        let mut seen_fqns: HashSet<String> = HashSet::new();

        // ── Classes, interfaces, traits, enums (from ast_map) ───────
        // Also emits methods, properties, and class constants.
        {
            let ast_map = self.ast_map.read();
            for (file_uri, classes) in ast_map.iter() {
                for class in classes {
                    // Skip anonymous classes (empty name or name starting with
                    // "anonymous@" which the parser uses for anonymous classes).
                    if class.name.is_empty() || class.name.starts_with("anonymous@") {
                        continue;
                    }

                    let fqn = class.fqn();

                    let content = match self.get_file_content_arc(file_uri) {
                        Some(c) => c,
                        None => continue,
                    };

                    // ── The class itself ─────────────────────────────
                    // Match against both the FQN and the short class name.
                    let class_tier = match_tier(&fqn, &query_lower)
                        .or_else(|| match_tier(&class.name, &query_lower));

                    if let Some(tier) = class_tier
                        && class.keyword_offset != 0
                    {
                        let pos = offset_to_position(&content, class.keyword_offset as usize);
                        let kind = match class.kind {
                            ClassLikeKind::Class => SymbolKind::CLASS,
                            ClassLikeKind::Interface => SymbolKind::INTERFACE,
                            ClassLikeKind::Trait => SymbolKind::CLASS,
                            ClassLikeKind::Enum => SymbolKind::ENUM,
                        };

                        let tags = class
                            .deprecation_message
                            .as_ref()
                            .map(|_| vec![SymbolTag::DEPRECATED]);

                        seen_fqns.insert(fqn.clone());

                        ranked.push(RankedSymbol {
                            symbol: SymbolInformation {
                                name: fqn.clone(),
                                kind,
                                tags,
                                deprecated: None,
                                location: Location {
                                    uri: Url::parse(file_uri)
                                        .unwrap_or_else(|_| Url::parse("file:///unknown").unwrap()),
                                    range: Range::new(pos, pos),
                                },
                                container_name: class.file_namespace.clone(),
                            },
                            tier,
                        });
                    }

                    // ── Methods ──────────────────────────────────────
                    for method in &class.methods {
                        // Skip virtual methods — they have no real source position.
                        if method.is_virtual {
                            continue;
                        }
                        if method.name_offset == 0 {
                            continue;
                        }

                        let tier = match match_tier(&method.name, &query_lower) {
                            Some(t) => t,
                            None => continue,
                        };

                        let pos = offset_to_position(&content, method.name_offset as usize);

                        let tags = method
                            .deprecation_message
                            .as_ref()
                            .map(|_| vec![SymbolTag::DEPRECATED]);

                        ranked.push(RankedSymbol {
                            symbol: SymbolInformation {
                                name: format!("{}::{}", fqn, method.name),
                                kind: SymbolKind::METHOD,
                                tags,
                                deprecated: None,
                                location: Location {
                                    uri: Url::parse(file_uri)
                                        .unwrap_or_else(|_| Url::parse("file:///unknown").unwrap()),
                                    range: Range::new(pos, pos),
                                },
                                container_name: Some(fqn.clone()),
                            },
                            tier,
                        });
                    }

                    // ── Properties ───────────────────────────────────
                    for prop in &class.properties {
                        if prop.is_virtual {
                            continue;
                        }
                        if prop.name_offset == 0 {
                            continue;
                        }

                        // Match against the property name (without $).
                        let match_name = format!("${}", prop.name);
                        let tier = match_tier(&prop.name, &query_lower)
                            .or_else(|| match_tier(&match_name, &query_lower));
                        let tier = match tier {
                            Some(t) => t,
                            None => continue,
                        };

                        let pos = offset_to_position(&content, prop.name_offset as usize);

                        let tags = prop
                            .deprecation_message
                            .as_ref()
                            .map(|_| vec![SymbolTag::DEPRECATED]);

                        ranked.push(RankedSymbol {
                            symbol: SymbolInformation {
                                name: format!("{}::${}", fqn, prop.name),
                                kind: SymbolKind::PROPERTY,
                                tags,
                                deprecated: None,
                                location: Location {
                                    uri: Url::parse(file_uri)
                                        .unwrap_or_else(|_| Url::parse("file:///unknown").unwrap()),
                                    range: Range::new(pos, pos),
                                },
                                container_name: Some(fqn.clone()),
                            },
                            tier,
                        });
                    }

                    // ── Class constants ──────────────────────────────
                    for constant in &class.constants {
                        if constant.is_virtual {
                            continue;
                        }
                        if constant.name_offset == 0 {
                            continue;
                        }

                        let tier = match match_tier(&constant.name, &query_lower) {
                            Some(t) => t,
                            None => continue,
                        };

                        let pos = offset_to_position(&content, constant.name_offset as usize);

                        let tags = constant
                            .deprecation_message
                            .as_ref()
                            .map(|_| vec![SymbolTag::DEPRECATED]);

                        // Use ENUM_MEMBER for enum cases, CONSTANT for class constants.
                        let kind = if constant.is_enum_case {
                            SymbolKind::ENUM_MEMBER
                        } else {
                            SymbolKind::CONSTANT
                        };

                        ranked.push(RankedSymbol {
                            symbol: SymbolInformation {
                                name: format!("{}::{}", fqn, constant.name),
                                kind,
                                tags,
                                deprecated: None,
                                location: Location {
                                    uri: Url::parse(file_uri)
                                        .unwrap_or_else(|_| Url::parse("file:///unknown").unwrap()),
                                    range: Range::new(pos, pos),
                                },
                                container_name: Some(fqn.clone()),
                            },
                            tier,
                        });
                    }
                }
            }
        }

        // ── Standalone functions ────────────────────────────────────
        {
            let fmap = self.global_functions.read();
            for (_name, (file_uri, func)) in fmap.iter() {
                let display_name = function_display_name(func);

                let func_short = short_name(&display_name);
                let tier = match match_tier(&display_name, &query_lower)
                    .or_else(|| match_tier(func_short, &query_lower))
                {
                    Some(t) => t,
                    None => continue,
                };

                // Skip functions with no usable offset.
                if func.name_offset == 0 {
                    continue;
                }

                let content = match self.get_file_content_arc(file_uri) {
                    Some(c) => c,
                    None => continue,
                };

                let pos = offset_to_position(&content, func.name_offset as usize);

                let tags = func
                    .deprecation_message
                    .as_ref()
                    .map(|_| vec![SymbolTag::DEPRECATED]);

                ranked.push(RankedSymbol {
                    symbol: SymbolInformation {
                        name: display_name,
                        kind: SymbolKind::FUNCTION,
                        tags,
                        deprecated: None,
                        location: Location {
                            uri: Url::parse(file_uri)
                                .unwrap_or_else(|_| Url::parse("file:///unknown").unwrap()),
                            range: Range::new(pos, pos),
                        },
                        container_name: func.namespace.clone(),
                    },
                    tier,
                });
            }
        }

        // ── Global defines / constants ──────────────────────────────
        {
            let dmap = self.global_defines.read();
            for (name, info) in dmap.iter() {
                let tier = match match_tier(name, &query_lower) {
                    Some(t) => t,
                    None => continue,
                };

                // Skip constants with no usable offset.
                if info.name_offset == 0 {
                    continue;
                }

                let content = match self.get_file_content_arc(&info.file_uri) {
                    Some(c) => c,
                    None => continue,
                };

                let pos = offset_to_position(&content, info.name_offset as usize);

                ranked.push(RankedSymbol {
                    symbol: make_constant_symbol(name, info, pos),
                    tier,
                });
            }
        }

        // ── class_index (discovered classes not yet in ast_map) ─────
        // Only searched when the user has typed a query — an empty query
        // would dump thousands of vendor classes into the picker.
        if !query_lower.is_empty() {
            // Grab the fqn_index for rich metadata (kind, deprecation).
            let fqn_idx = self.fqn_index.read();
            let idx = self.class_index.read();
            for (fqn, file_uri) in idx.iter() {
                if seen_fqns.contains(fqn) {
                    continue;
                }

                let fqn_short = short_name(fqn);
                let tier = match match_tier(fqn, &query_lower)
                    .or_else(|| match_tier(fqn_short, &query_lower))
                {
                    Some(t) => t,
                    None => continue,
                };

                let (kind, tags, container_name) =
                    if let Some(class_info) = fqn_idx.get(fqn.as_str()) {
                        let k = match class_info.kind {
                            ClassLikeKind::Class => SymbolKind::CLASS,
                            ClassLikeKind::Interface => SymbolKind::INTERFACE,
                            ClassLikeKind::Trait => SymbolKind::CLASS,
                            ClassLikeKind::Enum => SymbolKind::ENUM,
                        };
                        let t = class_info
                            .deprecation_message
                            .as_ref()
                            .map(|_| vec![SymbolTag::DEPRECATED]);
                        (k, t, class_info.file_namespace.clone())
                    } else {
                        (SymbolKind::CLASS, None, namespace_from_fqn(fqn))
                    };

                // Try to compute a precise position from file content.
                let pos = if let Some(class_info) = fqn_idx.get(fqn.as_str()) {
                    if class_info.keyword_offset > 0 {
                        if let Some(content) = self.get_file_content_arc(file_uri) {
                            offset_to_position(&content, class_info.keyword_offset as usize)
                        } else {
                            Position::new(0, 0)
                        }
                    } else {
                        Position::new(0, 0)
                    }
                } else {
                    Position::new(0, 0)
                };

                seen_fqns.insert(fqn.clone());

                ranked.push(RankedSymbol {
                    symbol: SymbolInformation {
                        name: fqn.clone(),
                        kind,
                        tags,
                        deprecated: None,
                        location: Location {
                            uri: Url::parse(file_uri)
                                .unwrap_or_else(|_| Url::parse("file:///unknown").unwrap()),
                            range: Range::new(pos, pos),
                        },
                        container_name,
                    },
                    tier,
                });
            }
        }

        // ── classmap (Composer vendor classes) ──────────────────────
        // Only searched when the user has typed a query, same rationale
        // as above.
        if !query_lower.is_empty() {
            let cmap = self.classmap.read();
            for (fqn, file_path) in cmap.iter() {
                if seen_fqns.contains(fqn) {
                    continue;
                }

                let fqn_short = short_name(fqn);
                let tier = match match_tier(fqn, &query_lower)
                    .or_else(|| match_tier(fqn_short, &query_lower))
                {
                    Some(t) => t,
                    None => continue,
                };

                let uri = match Url::from_file_path(file_path) {
                    Ok(u) => u,
                    Err(()) => continue,
                };

                seen_fqns.insert(fqn.clone());

                ranked.push(RankedSymbol {
                    symbol: SymbolInformation {
                        name: fqn.clone(),
                        kind: SymbolKind::CLASS,
                        tags: None,
                        deprecated: None,
                        location: Location {
                            uri,
                            range: Range::new(Position::new(0, 0), Position::new(0, 0)),
                        },
                        container_name: namespace_from_fqn(fqn),
                    },
                    tier,
                });
            }
        }

        // ── Sort by relevance then alphabetically ───────────────────
        ranked.sort_by(|a, b| {
            a.tier
                .cmp(&b.tier)
                .then_with(|| a.symbol.name.cmp(&b.symbol.name))
        });

        // ── Cap at MAX_RESULTS ──────────────────────────────────────
        ranked.truncate(MAX_RESULTS);

        let symbols: Vec<SymbolInformation> = ranked.into_iter().map(|r| r.symbol).collect();

        if symbols.is_empty() {
            None
        } else {
            Some(symbols)
        }
    }
}

/// Build the display name for a function, including its namespace prefix
/// when present (e.g. `"Amp\\delay"`).
fn function_display_name(func: &FunctionInfo) -> String {
    match &func.namespace {
        Some(ns) if !ns.is_empty() => format!("{}\\{}", ns, func.name),
        _ => func.name.clone(),
    }
}

/// Extract the namespace portion from a fully-qualified class name.
///
/// Returns `Some("App\\Models")` for `"App\\Models\\User"`, or `None`
/// for a class with no namespace (e.g. `"stdClass"`).
fn namespace_from_fqn(fqn: &str) -> Option<String> {
    fqn.rfind('\\').map(|i| fqn[..i].to_string())
}

/// Build a `SymbolInformation` for a global constant.
#[allow(deprecated)] // SymbolInformation::deprecated is deprecated in the LSP types crate
fn make_constant_symbol(name: &str, info: &DefineInfo, pos: Position) -> SymbolInformation {
    SymbolInformation {
        name: name.to_string(),
        kind: SymbolKind::CONSTANT,
        tags: None,
        deprecated: None,
        location: Location {
            uri: Url::parse(&info.file_uri)
                .unwrap_or_else(|_| Url::parse("file:///unknown").unwrap()),
            range: Range::new(pos, pos),
        },
        container_name: None,
    }
}

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

    #[test]
    fn short_name_no_separator() {
        assert_eq!(short_name("Foo"), "Foo");
    }

    #[test]
    fn short_name_with_namespace() {
        assert_eq!(short_name("App\\Models\\User"), "User");
    }

    #[test]
    fn short_name_with_member() {
        assert_eq!(short_name("App\\Models\\User::findByEmail"), "findByEmail");
    }

    #[test]
    fn short_name_member_takes_precedence() {
        assert_eq!(short_name("Ns\\Cls::method"), "method");
    }

    #[test]
    fn match_tier_exact() {
        assert_eq!(match_tier("Foo", "foo"), Some(MatchTier::Exact));
    }

    #[test]
    fn match_tier_prefix() {
        assert_eq!(match_tier("FooBar", "foo"), Some(MatchTier::Prefix));
    }

    #[test]
    fn match_tier_substring() {
        assert_eq!(match_tier("MyFooBar", "foo"), Some(MatchTier::Substring));
    }

    #[test]
    fn match_tier_no_match() {
        assert_eq!(match_tier("Bar", "foo"), None);
    }

    #[test]
    fn match_tier_empty_query() {
        assert_eq!(match_tier("Anything", ""), Some(MatchTier::Substring));
    }

    #[test]
    fn tier_ordering() {
        assert!(MatchTier::Exact < MatchTier::Prefix);
        assert!(MatchTier::Prefix < MatchTier::Substring);
    }
}