php-lsp 0.13.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
/// Code action: "Implement missing methods"
///
/// When a class `implements` an interface or `extends` an abstract class,
/// this action generates stub methods for any abstract/interface methods
/// that are not yet implemented in the class body.
use std::collections::{HashMap, HashSet};
use std::sync::Arc;

use php_ast::{ClassMemberKind, NamespaceBody, Stmt, StmtKind, Visibility};
use tower_lsp::lsp_types::{
    CodeAction, CodeActionKind, CodeActionOrCommand, Range, TextEdit, Url, WorkspaceEdit,
};

use crate::document::ast::{ParsedDoc, SourceView, format_type_hint};
use crate::hover::format_params_str;
use crate::text::fqn_short_name;

struct MethodStub {
    name: String,
    visibility: &'static str,
    is_static: bool,
    params: String,
    return_type: Option<String>,
}

pub fn implement_missing_actions(
    _source: &str,
    doc: &ParsedDoc,
    all_docs: &[(Url, Arc<ParsedDoc>)],
    range: Range,
    uri: &Url,
    file_imports: &HashMap<String, String>,
) -> Vec<CodeActionOrCommand> {
    let sv = doc.view();
    let mut actions = Vec::new();
    collect_actions(
        &doc.program().stmts,
        sv,
        all_docs,
        file_imports,
        range,
        uri,
        &mut actions,
    );
    actions
}

fn collect_actions(
    stmts: &[Stmt<'_, '_>],
    sv: SourceView<'_>,
    all_docs: &[(Url, Arc<ParsedDoc>)],
    file_imports: &HashMap<String, String>,
    range: Range,
    uri: &Url,
    out: &mut Vec<CodeActionOrCommand>,
) {
    for stmt in stmts {
        match &stmt.kind {
            StmtKind::Class(c) => {
                let class_start = sv.position_of(stmt.span.start).line;
                let class_end = sv.position_of(stmt.span.end).line;
                if class_start > range.end.line || class_end < range.start.line {
                    continue;
                }

                let existing: HashSet<String> = c
                    .body
                    .members
                    .iter()
                    .filter_map(|m| {
                        if let ClassMemberKind::Method(method) = &m.kind {
                            Some(method.name.to_string())
                        } else {
                            None
                        }
                    })
                    .collect();

                let mut missing: Vec<MethodStub> = Vec::new();

                for iface in c.implements.iter() {
                    let iface_name = iface.to_string_repr().into_owned();
                    let short = fqn_short_name(&iface_name).to_string();
                    // Try to resolve through `use` imports first; fall back to short-name scan.
                    let fqn = file_imports.get(&short).cloned();
                    for stub in abstract_methods_of(&short, fqn.as_deref(), all_docs) {
                        if !existing.contains(&stub.name) {
                            missing.push(stub);
                        }
                    }
                }

                if let Some(parent) = &c.extends {
                    let parent_name = parent.to_string_repr().into_owned();
                    let short = fqn_short_name(&parent_name).to_string();
                    let fqn = file_imports.get(&short).cloned();
                    for stub in abstract_methods_of(&short, fqn.as_deref(), all_docs) {
                        if !existing.contains(&stub.name) {
                            missing.push(stub);
                        }
                    }
                }

                // Deduplicate by method name (multiple interfaces may declare the same method).
                {
                    let mut seen = HashSet::new();
                    missing.retain(|s| seen.insert(s.name.clone()));
                }

                if missing.is_empty() {
                    continue;
                }

                let mut stub_text = generate_stub_text(&missing);
                let closing_pos = sv.position_of(stmt.span.end.saturating_sub(1));
                let insert_pos = closing_pos;
                // For single-line classes `class Foo {}` the `}` is not at column 0,
                // so we need a leading newline to avoid the stub running onto the
                // opening brace of the class.
                if closing_pos.character > 0 {
                    stub_text = format!("\n{stub_text}");
                }
                let edit = TextEdit {
                    range: Range {
                        start: insert_pos,
                        end: insert_pos,
                    },
                    new_text: stub_text,
                };
                let mut changes = HashMap::new();
                changes.insert(uri.clone(), vec![edit]);

                let n = missing.len();
                let title = if n == 1 {
                    "Implement missing method".to_string()
                } else {
                    format!("Implement {n} missing methods")
                };
                out.push(CodeActionOrCommand::CodeAction(CodeAction {
                    title,
                    kind: Some(CodeActionKind::QUICKFIX),
                    edit: Some(WorkspaceEdit {
                        changes: Some(changes),
                        ..Default::default()
                    }),
                    ..Default::default()
                }));
            }
            StmtKind::Namespace(ns) => {
                if let NamespaceBody::Braced(inner) = &ns.body {
                    collect_actions(&inner.stmts, sv, all_docs, file_imports, range, uri, out);
                }
            }
            _ => {}
        }
    }
}

/// Collect abstract/interface methods declared by `name` across all documents.
///
/// When `fqn` is provided (resolved from a `use` statement), the search uses
/// FQN-aware matching only — it looks for a document whose namespace + class
/// name matches the FQN exactly.  This avoids picking up a different class that
/// happens to share the same short name in another namespace.
///
/// When `fqn` is `None` (no `use` import found), falls back to a plain
/// short-name scan across all documents, preserving the original behaviour.
fn abstract_methods_of(
    name: &str,
    fqn: Option<&str>,
    all_docs: &[(Url, Arc<ParsedDoc>)],
) -> Vec<MethodStub> {
    if let Some(fqn) = fqn {
        // FQN-aware pass: only return stubs when the exact namespace matches.
        // Do NOT fall back to short-name scan to avoid picking the wrong class.
        for (_, doc) in all_docs {
            if let Some(stubs) = collect_abstract_methods_fqn(&doc.program().stmts, fqn, "") {
                return stubs;
            }
        }
        return vec![];
    }

    // Short-name fallback (no `use` import): scan all docs as before.
    for (_, doc) in all_docs {
        if let Some(stubs) = collect_abstract_methods(&doc.program().stmts, name) {
            return stubs;
        }
    }
    vec![]
}

/// Like `collect_abstract_methods` but matches the fully-qualified name
/// `namespace\ClassName` by tracking the current namespace prefix while
/// recursing into `StmtKind::Namespace` blocks (both braced and unbraced).
fn collect_abstract_methods_fqn(
    stmts: &[Stmt<'_, '_>],
    fqn: &str,
    current_ns: &str,
) -> Option<Vec<MethodStub>> {
    // The expected short name is the last segment of the FQN.
    let short = fqn_short_name(fqn);
    // For unbraced namespaces (`namespace Foo;`) the active namespace changes
    // mid-statement-list; track it mutably as we iterate.
    let mut active_ns = current_ns.to_string();

    for stmt in stmts {
        match &stmt.kind {
            StmtKind::Interface(i) if i.name == short => {
                // Verify the namespace matches.
                let declared_fqn = if active_ns.is_empty() {
                    i.name.to_string()
                } else {
                    format!("{}\\{}", active_ns, &i.name.to_string())
                };
                if fqn_eq(fqn, &declared_fqn) {
                    let stubs = i
                        .body
                        .members
                        .iter()
                        .filter_map(|m| {
                            if let ClassMemberKind::Method(method) = &m.kind {
                                Some(MethodStub {
                                    name: method.name.to_string(),
                                    visibility: "public",
                                    is_static: method.is_static,
                                    params: format_params_str(&method.params),
                                    return_type: method
                                        .return_type
                                        .as_ref()
                                        .map(|t| format_type_hint(t)),
                                })
                            } else {
                                None
                            }
                        })
                        .collect();
                    return Some(stubs);
                }
            }
            StmtKind::Class(c)
                if c.name.as_ref().map(|n| n.to_string()) == Some(short.to_string())
                    && c.modifiers.is_abstract =>
            {
                let declared_fqn = if active_ns.is_empty() {
                    short.to_string()
                } else {
                    format!("{}\\{}", active_ns, short)
                };
                if fqn_eq(fqn, &declared_fqn) {
                    let stubs = c
                        .body
                        .members
                        .iter()
                        .filter_map(|m| {
                            if let ClassMemberKind::Method(method) = &m.kind {
                                if method.is_abstract {
                                    Some(MethodStub {
                                        name: method.name.to_string(),
                                        visibility: visibility_str(method.visibility.as_ref()),
                                        is_static: method.is_static,
                                        params: format_params_str(&method.params),
                                        return_type: method
                                            .return_type
                                            .as_ref()
                                            .map(|t| format_type_hint(t)),
                                    })
                                } else {
                                    None
                                }
                            } else {
                                None
                            }
                        })
                        .collect();
                    return Some(stubs);
                }
            }
            StmtKind::Namespace(ns) => {
                let ns_name = ns.name.as_ref().map(|n| n.to_string_repr().into_owned());
                match &ns.body {
                    NamespaceBody::Braced(inner) => {
                        let child_ns = match &ns_name {
                            Some(n) if !active_ns.is_empty() => {
                                format!("{}\\{}", active_ns, n)
                            }
                            Some(n) => n.clone(),
                            None => active_ns.clone(),
                        };
                        if let Some(stubs) =
                            collect_abstract_methods_fqn(&inner.stmts, fqn, &child_ns)
                        {
                            return Some(stubs);
                        }
                    }
                    NamespaceBody::Simple => {
                        // Unbraced form: all subsequent statements are in this namespace.
                        active_ns = ns_name.unwrap_or_default();
                    }
                }
            }
            _ => {}
        }
    }
    None
}

/// Compare two FQNs ignoring a leading backslash.
fn fqn_eq(a: &str, b: &str) -> bool {
    a.trim_start_matches('\\') == b.trim_start_matches('\\')
}

fn collect_abstract_methods(stmts: &[Stmt<'_, '_>], name: &str) -> Option<Vec<MethodStub>> {
    for stmt in stmts {
        match &stmt.kind {
            StmtKind::Interface(i) if i.name == name => {
                let stubs = i
                    .body
                    .members
                    .iter()
                    .filter_map(|m| {
                        if let ClassMemberKind::Method(method) = &m.kind {
                            Some(MethodStub {
                                name: method.name.to_string(),
                                visibility: "public",
                                is_static: method.is_static,
                                params: format_params_str(&method.params),
                                return_type: method
                                    .return_type
                                    .as_ref()
                                    .map(|t| format_type_hint(t)),
                            })
                        } else {
                            None
                        }
                    })
                    .collect();
                return Some(stubs);
            }
            StmtKind::Class(c)
                if c.name.as_ref().map(|n| n.to_string()) == Some(name.to_string())
                    && c.modifiers.is_abstract =>
            {
                let stubs = c
                    .body
                    .members
                    .iter()
                    .filter_map(|m| {
                        if let ClassMemberKind::Method(method) = &m.kind {
                            if method.is_abstract {
                                Some(MethodStub {
                                    name: method.name.to_string(),
                                    visibility: visibility_str(method.visibility.as_ref()),
                                    is_static: method.is_static,
                                    params: format_params_str(&method.params),
                                    return_type: method
                                        .return_type
                                        .as_ref()
                                        .map(|t| format_type_hint(t)),
                                })
                            } else {
                                None
                            }
                        } else {
                            None
                        }
                    })
                    .collect();
                return Some(stubs);
            }
            StmtKind::Namespace(ns) => {
                if let NamespaceBody::Braced(inner) = &ns.body
                    && let Some(stubs) = collect_abstract_methods(&inner.stmts, name)
                {
                    return Some(stubs);
                }
            }
            _ => {}
        }
    }
    None
}

fn visibility_str(v: Option<&Visibility>) -> &'static str {
    match v {
        Some(Visibility::Protected) => "protected",
        Some(Visibility::Private) => "private",
        _ => "public",
    }
}

fn generate_stub_text(stubs: &[MethodStub]) -> String {
    let mut text = String::new();
    for stub in stubs {
        let static_kw = if stub.is_static { "static " } else { "" };
        let ret = match &stub.return_type {
            Some(t) => format!(": {t}"),
            None => String::new(),
        };
        text.push_str(&format!(
            "    {} {}function {}({}){ret}\n    {{\n        throw new \\RuntimeException('Not implemented');\n    }}\n\n",
            stub.visibility, static_kw, stub.name, stub.params
        ));
    }
    text
}