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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
//! "Remove @throws" code action for PHPStan `throws.unusedType` and
//! `throws.notThrowable`.
//!
//! When PHPStan reports that a `@throws` tag references a type that is
//! either not thrown (`throws.unusedType`) or not a subtype of
//! `Throwable` (`throws.notThrowable`), this code action offers to
//! remove the offending `@throws` line from the docblock.
//!
//! After applying the edit the triggering diagnostic is eagerly removed
//! from the PHPStan cache so the user gets instant visual feedback
//! without waiting for the next PHPStan run.
//!
//! **Trigger:** A PHPStan diagnostic with identifier
//! `throws.unusedType` or `throws.notThrowable` overlaps the cursor.
//!
//! **Code action kind:** `quickfix`.

use std::collections::HashMap;

use tower_lsp::lsp_types::*;

use crate::Backend;
use crate::code_actions::CodeActionData;
use crate::code_actions::make_code_action_data;
use crate::php_type::PhpType;
use crate::util::{offset_to_position, ranges_overlap, short_name};

/// PHPStan identifiers we match on.
const UNUSED_TYPE_ID: &str = "throws.unusedType";
const NOT_THROWABLE_ID: &str = "throws.notThrowable";

impl Backend {
    /// Collect "Remove @throws" code actions for PHPStan
    /// `throws.unusedType` and `throws.notThrowable` diagnostics.
    pub(crate) fn collect_remove_throws_actions(
        &self,
        uri: &str,
        content: &str,
        params: &CodeActionParams,
        out: &mut Vec<CodeActionOrCommand>,
    ) {
        let phpstan_diags: Vec<Diagnostic> = {
            let cache = self.phpstan_last_diags.lock();
            cache.get(uri).cloned().unwrap_or_default()
        };

        for diag in &phpstan_diags {
            if !ranges_overlap(&diag.range, &params.range) {
                continue;
            }

            let identifier = match &diag.code {
                Some(NumberOrString::String(s)) => s.as_str(),
                _ => continue,
            };

            if identifier != UNUSED_TYPE_ID && identifier != NOT_THROWABLE_ID {
                continue;
            }

            // Extract the type name from the message (validation only).
            let type_name = match extract_throws_type(&diag.message, identifier) {
                Some(t) => t,
                None => continue,
            };

            let type_name_str = type_name.to_string();
            let short_name = short_name(&type_name_str);

            // Find the docblock above the diagnostic line (validation only).
            let diag_line = diag.range.start.line as usize;
            let docblock = match find_docblock_above_line(content, diag_line) {
                Some(db) => db,
                None => continue,
            };

            // Validate that the @throws line can be removed (validation only).
            if build_remove_throws_edit(content, &docblock, &type_name_str).is_none() {
                continue;
            }

            let title = format!("Remove @throws {}", short_name);

            let extra = serde_json::json!({
                "diagnostic_message": diag.message,
                "diagnostic_line": diag_line,
                "diagnostic_code": identifier,
            });

            out.push(CodeActionOrCommand::CodeAction(CodeAction {
                title,
                kind: Some(CodeActionKind::QUICKFIX),
                diagnostics: Some(vec![diag.clone()]),
                edit: None,
                command: None,
                is_preferred: Some(true),
                disabled: None,
                data: Some(make_code_action_data(
                    "phpstan.removeThrows",
                    uri,
                    &params.range,
                    extra,
                )),
            }));
        }
    }

    /// Resolve a "Remove @throws" code action by recomputing the
    /// workspace edit from the stored data.
    pub(crate) fn resolve_remove_throws(
        &self,
        data: &CodeActionData,
        content: &str,
    ) -> Option<WorkspaceEdit> {
        let extra = &data.extra;
        let message = extra.get("diagnostic_message")?.as_str()?;
        let line = extra.get("diagnostic_line")?.as_u64()? as usize;
        let code = extra.get("diagnostic_code")?.as_str()?;

        let type_name = extract_throws_type(message, code)?;
        let type_name_str = type_name.to_string();

        let docblock = find_docblock_above_line(content, line)?;
        let throws_edit = build_remove_throws_edit(content, &docblock, &type_name_str)?;

        let doc_uri: Url = data.uri.parse().ok()?;
        let mut changes = HashMap::new();
        changes.insert(doc_uri, vec![throws_edit]);

        Some(WorkspaceEdit {
            changes: Some(changes),
            document_changes: None,
            change_annotations: None,
        })
    }
}

// ── Helpers ─────────────────────────────────────────────────────────────────

/// Extract the type from a PHPStan `throws.unusedType` or
/// `throws.notThrowable` message as a [`PhpType`].
///
/// `throws.unusedType` formats:
/// - `"Method Ns\Cls::method() has Ns\Ex in PHPDoc @throws tag but it's not thrown."`
/// - `"Function foo() has Ns\Ex in PHPDoc @throws tag but it's not thrown."`
/// - `"Get hook for property Ns\Cls::$prop has Ns\Ex in PHPDoc @throws tag but it's not thrown."`
///
/// `throws.notThrowable` format:
/// - `"PHPDoc tag @throws with type Ns\Ex is not subtype of Throwable"`
fn extract_throws_type(message: &str, identifier: &str) -> Option<PhpType> {
    let raw = if identifier == UNUSED_TYPE_ID {
        // Pattern: "has <type> in PHPDoc @throws tag"
        let marker = " has ";
        let start = message.find(marker)? + marker.len();
        let rest = &message[start..];
        let end = rest.find(" in PHPDoc @throws tag")?;
        rest[..end].trim()
    } else {
        // Pattern: "@throws with type <type> is not subtype of Throwable"
        let marker = "@throws with type ";
        let start = message.find(marker)? + marker.len();
        let rest = &message[start..];
        let end = rest.find(" is not subtype")?;
        rest[..end].trim()
    };

    if raw.is_empty() {
        return None;
    }

    Some(PhpType::parse(raw))
}

/// Information about a docblock found above a given line.
struct DocblockAbove {
    /// Byte offset of the `/**`.
    start: usize,
    /// Byte offset just past the `*/`.
    end: usize,
    /// The raw docblock text.
    text: String,
}

/// Find the docblock immediately above the given line.
///
/// The diagnostic line is the method/function signature.  The docblock
/// (if any) sits directly above it, possibly separated by blank lines
/// or attribute lines.
fn find_docblock_above_line(content: &str, line: usize) -> Option<DocblockAbove> {
    let lines: Vec<&str> = content.lines().collect();
    if line == 0 || line > lines.len() {
        return None;
    }

    // Walk backward from the line before the diagnostic to find `*/`.
    let mut doc_end_line = None;
    for i in (0..line).rev() {
        let trimmed = lines[i].trim();
        if trimmed.is_empty() {
            continue;
        }
        if trimmed.ends_with("*/") {
            doc_end_line = Some(i);
            break;
        }
        // Attributes (#[...]) can appear between docblock and function.
        if trimmed.starts_with("#[") {
            continue;
        }
        // Anything else means no docblock.
        break;
    }

    let end_line = doc_end_line?;

    // Walk backward from end_line to find `/**`.
    let mut doc_start_line = None;
    for i in (0..=end_line).rev() {
        let trimmed = lines[i].trim();
        if trimmed.contains("/**") {
            doc_start_line = Some(i);
            break;
        }
        // Should be a `*`-prefixed line.
        if !trimmed.starts_with('*') && !trimmed.ends_with("*/") {
            break;
        }
    }

    let start_line = doc_start_line?;

    // Convert line numbers to byte offsets.
    let mut byte_offset = 0;
    let mut start_byte = 0;
    let mut end_byte = 0;
    for (i, line_text) in lines.iter().enumerate() {
        if i == start_line {
            start_byte = byte_offset;
        }
        byte_offset += line_text.len() + 1; // +1 for newline
        if i == end_line {
            end_byte = byte_offset; // include trailing newline
        }
    }

    // Trim to just the docblock including its indentation.
    let text = content
        .get(start_byte..end_byte.min(content.len()))
        .unwrap_or("")
        .to_string();

    Some(DocblockAbove {
        start: start_byte,
        end: end_byte.min(content.len()),
        text,
    })
}

/// Build a `TextEdit` that removes the `@throws` line matching the
/// given type from the docblock.
///
/// If the docblock would become "empty" (only summary or nothing) after
/// removal, this still preserves the docblock shell — removing the
/// whole docblock could lose `@param` / `@return` / summary text.
fn build_remove_throws_edit(
    content: &str,
    docblock: &DocblockAbove,
    type_name: &str,
) -> Option<TextEdit> {
    let short = short_name(type_name);

    // Find the @throws line(s) to remove.
    let doc_lines: Vec<&str> = docblock.text.lines().collect();

    // Identify which line indices to remove.
    let mut lines_to_remove: Vec<usize> = Vec::new();
    for (i, line) in doc_lines.iter().enumerate() {
        let mut trimmed = line.trim();
        // Strip docblock delimiters so single-line `/** @throws ... */`
        // and multi-line `* @throws ...` are both handled.
        if let Some(inner) = trimmed.strip_prefix("/**") {
            trimmed = inner.trim_start();
        }
        if let Some(inner) = trimmed.strip_suffix("*/") {
            trimmed = inner.trim_end();
        }
        trimmed = trimmed.trim_start_matches('*').trim();
        if let Some(rest) = trimmed.strip_prefix("@throws") {
            let rest = rest.trim_start();
            let tag_type = rest.split_whitespace().next().unwrap_or("");
            let tag_short = short_name(tag_type);

            // Match by short name (case-insensitive) — the docblock
            // might use the short name, the FQN, or a leading-backslash
            // variant.  The message from PHPStan can also be FQN.
            if tag_short.eq_ignore_ascii_case(short)
                || crate::util::strip_fqn_prefix(tag_type)
                    .eq_ignore_ascii_case(crate::util::strip_fqn_prefix(type_name))
            {
                lines_to_remove.push(i);
            }
        }
    }

    if lines_to_remove.is_empty() {
        return None;
    }

    // Also remove blank `*` separator lines that would be orphaned.
    // If the line before a removed line is a blank `*`, and the line
    // after the removed block is `*/` or another blank `*`, remove
    // the blank line too.
    let mut extra_removals: Vec<usize> = Vec::new();
    for &idx in &lines_to_remove {
        // Check the line before.
        if idx > 0 && !lines_to_remove.contains(&(idx - 1)) {
            let prev = doc_lines[idx - 1].trim().trim_start_matches('*').trim();
            if prev.is_empty() {
                // Check what follows the removed block.
                let next_idx = lines_to_remove
                    .iter()
                    .filter(|&&j| j > idx)
                    .max()
                    .copied()
                    .unwrap_or(idx)
                    + 1;
                if next_idx < doc_lines.len() {
                    let next = doc_lines[next_idx].trim();
                    if next == "*/" || next.trim_start_matches('*').trim().is_empty() {
                        extra_removals.push(idx - 1);
                    }
                } else {
                    extra_removals.push(idx - 1);
                }
            }
        }
    }
    lines_to_remove.extend(extra_removals);
    lines_to_remove.sort();
    lines_to_remove.dedup();

    // Build the new docblock text by excluding the removed lines.
    let new_lines: Vec<&str> = doc_lines
        .iter()
        .enumerate()
        .filter(|(i, _)| !lines_to_remove.contains(i))
        .map(|(_, l)| *l)
        .collect();

    // If the docblock is now essentially empty (just `/**` and `*/`
    // with maybe blank `*` lines), keep it minimal.
    let has_content = new_lines.iter().any(|l| {
        let mut t = l.trim();
        if let Some(inner) = t.strip_prefix("/**") {
            t = inner.trim_start();
        }
        if let Some(inner) = t.strip_suffix("*/") {
            t = inner.trim_end();
        }
        t = t.trim_start_matches('*').trim();
        !t.is_empty()
    });

    let new_text = if !has_content && new_lines.len() <= 3 {
        // The docblock is essentially empty after removal — remove it
        // entirely (including its trailing newline).
        String::new()
    } else {
        let mut text = new_lines.join("\n");
        // Preserve trailing newline if original had one.
        if docblock.text.ends_with('\n') && !text.ends_with('\n') {
            text.push('\n');
        }
        text
    };

    let start = offset_to_position(content, docblock.start);
    let end = offset_to_position(content, docblock.end);

    Some(TextEdit {
        range: Range { start, end },
        new_text,
    })
}

// ── Tests ───────────────────────────────────────────────────────────────────

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

    // ── extract_throws_type ─────────────────────────────────────────

    #[test]
    fn extracts_unused_type_from_method_message() {
        let msg = "Method App\\Controllers\\Foo::bar() has Luxplus\\Decimal\\Decimal in PHPDoc @throws tag but it's not thrown.";
        let t = extract_throws_type(msg, UNUSED_TYPE_ID).unwrap();
        assert_eq!(t.to_string(), "Luxplus\\Decimal\\Decimal");
    }

    #[test]
    fn extracts_unused_type_from_function_message() {
        let msg = "Function doStuff() has App\\Exceptions\\FooException in PHPDoc @throws tag but it's not thrown.";
        let t = extract_throws_type(msg, UNUSED_TYPE_ID).unwrap();
        assert_eq!(t.to_string(), "App\\Exceptions\\FooException");
    }

    #[test]
    fn extracts_unused_type_from_property_hook_message() {
        let msg = "Get hook for property App\\Foo::$bar has App\\Exceptions\\PropException in PHPDoc @throws tag but it's not thrown.";
        let t = extract_throws_type(msg, UNUSED_TYPE_ID).unwrap();
        assert_eq!(t.to_string(), "App\\Exceptions\\PropException");
    }

    #[test]
    fn extracts_not_throwable_type() {
        let msg =
            "PHPDoc tag @throws with type App\\Http\\Controllers\\not is not subtype of Throwable";
        let t = extract_throws_type(msg, NOT_THROWABLE_ID).unwrap();
        assert_eq!(t.to_string(), "App\\Http\\Controllers\\not");
    }

    #[test]
    fn extracts_not_throwable_fqn_type() {
        let msg = "PHPDoc tag @throws with type \\TheSeer\\Tokenizer\\Exception is not subtype of Throwable";
        let t = extract_throws_type(msg, NOT_THROWABLE_ID).unwrap();
        assert_eq!(t.to_string(), "\\TheSeer\\Tokenizer\\Exception");
    }

    #[test]
    fn returns_none_for_unrelated_message() {
        assert!(extract_throws_type("Some other error.", UNUSED_TYPE_ID).is_none());
        assert!(extract_throws_type("Some other error.", NOT_THROWABLE_ID).is_none());
    }

    // ── short_name_from_type ────────────────────────────────────────

    #[test]
    fn short_name_simple() {
        assert_eq!(short_name("RuntimeException"), "RuntimeException");
    }

    #[test]
    fn short_name_namespaced() {
        assert_eq!(short_name("App\\Exceptions\\FooException"), "FooException");
    }

    #[test]
    fn short_name_leading_backslash() {
        assert_eq!(short_name("\\TheSeer\\Tokenizer\\Exception"), "Exception");
    }

    #[test]
    fn short_name_non_class() {
        // "not even correct" — the short name is the whole thing
        // since there are no backslashes.
        assert_eq!(short_name("not"), "not");
    }

    // ── find_docblock_above_line ────────────────────────────────────

    #[test]
    fn finds_docblock_directly_above() {
        let php = "\
<?php
class Foo {
    /**
     * @throws Decimal
     */
    public function bar(): void {}
}
";
        // Line 5 is `    public function bar(): void {}`
        let db = find_docblock_above_line(php, 5).unwrap();
        assert!(db.text.contains("@throws Decimal"), "got: {}", db.text);
    }

    #[test]
    fn finds_docblock_with_blank_line_between() {
        // Some code styles leave a blank line between docblock and
        // attributes/function.  We skip blank lines.
        let php = "\
<?php
class Foo {
    /**
     * @throws Decimal
     */

    public function bar(): void {}
}
";
        let db = find_docblock_above_line(php, 6).unwrap();
        assert!(db.text.contains("@throws Decimal"), "got: {}", db.text);
    }

    #[test]
    fn finds_docblock_with_attribute_between() {
        let php = "\
<?php
class Foo {
    /**
     * @throws Decimal
     */
    #[SomeAttribute]
    public function bar(): void {}
}
";
        let db = find_docblock_above_line(php, 6).unwrap();
        assert!(db.text.contains("@throws Decimal"), "got: {}", db.text);
    }

    #[test]
    fn no_docblock_found() {
        let php = "\
<?php
class Foo {
    public function bar(): void {}
}
";
        assert!(find_docblock_above_line(php, 2).is_none());
    }

    // ── build_remove_throws_edit ────────────────────────────────────

    #[test]
    fn removes_throws_line_from_docblock() {
        let php = "\
<?php
class Foo {
    /**
     * Summary.
     *
     * @throws Decimal
     */
    public function bar(): void {}
}
";
        let db = find_docblock_above_line(php, 7).unwrap();
        let edit = build_remove_throws_edit(php, &db, "Luxplus\\Decimal\\Decimal").unwrap();
        assert!(
            !edit.new_text.contains("@throws"),
            "should remove @throws: {:?}",
            edit.new_text
        );
        assert!(
            edit.new_text.contains("Summary."),
            "should preserve summary: {:?}",
            edit.new_text
        );
    }

    #[test]
    fn removes_fqn_throws_line() {
        let php = "\
<?php
class Foo {
    /**
     * @throws \\TheSeer\\Tokenizer\\Exception
     */
    public function bar(): void {}
}
";
        let db = find_docblock_above_line(php, 5).unwrap();
        let edit = build_remove_throws_edit(php, &db, "\\TheSeer\\Tokenizer\\Exception").unwrap();
        // The docblock only had the @throws line, so the entire
        // docblock should be removed.
        assert_eq!(
            edit.new_text, "",
            "empty docblock should be removed entirely"
        );
    }

    #[test]
    fn removes_short_name_throws_matching_fqn() {
        let php = "\
<?php
class Foo {
    /**
     * @throws Exception
     */
    public function bar(): void {}
}
";
        let db = find_docblock_above_line(php, 5).unwrap();
        let edit = build_remove_throws_edit(php, &db, "TheSeer\\Tokenizer\\Exception").unwrap();
        assert_eq!(edit.new_text, "");
    }

    #[test]
    fn preserves_other_throws_tags() {
        let php = "\
<?php
class Foo {
    /**
     * @throws FooException
     * @throws BarException
     */
    public function bar(): void {}
}
";
        let db = find_docblock_above_line(php, 6).unwrap();
        let edit = build_remove_throws_edit(php, &db, "FooException").unwrap();
        assert!(
            !edit.new_text.contains("FooException"),
            "should remove FooException: {:?}",
            edit.new_text
        );
        assert!(
            edit.new_text.contains("@throws BarException"),
            "should keep BarException: {:?}",
            edit.new_text
        );
    }

    #[test]
    fn removes_throws_with_non_class_text() {
        // "not even correct" — PHPStan reports the parsed type which
        // is just "not".
        let php = "\
<?php
class Foo {
    /**
     * @throws not even correct
     */
    public function bar(): void {}
}
";
        let db = find_docblock_above_line(php, 5).unwrap();
        // PHPStan reports the type as "App\Http\Controllers\not"
        // because it resolves relative to the namespace.
        let edit = build_remove_throws_edit(php, &db, "App\\Http\\Controllers\\not").unwrap();
        assert_eq!(edit.new_text, "");
    }

    #[test]
    fn removes_entire_empty_docblock() {
        let php = "\
<?php
class Foo {
    /**
     * @throws Decimal
     */
    public function bar(): void {}
}
";
        let db = find_docblock_above_line(php, 5).unwrap();
        let edit = build_remove_throws_edit(php, &db, "Decimal").unwrap();
        assert_eq!(
            edit.new_text, "",
            "docblock with only @throws should be removed"
        );
    }

    #[test]
    fn keeps_docblock_with_other_content() {
        let php = "\
<?php
class Foo {
    /**
     * Summary.
     *
     * @param string $a
     * @throws Decimal
     *
     * @return string
     */
    public function bar(string $a): string {}
}
";
        let db = find_docblock_above_line(php, 10).unwrap();
        let edit = build_remove_throws_edit(php, &db, "Decimal").unwrap();
        assert!(
            edit.new_text.contains("Summary."),
            "should keep summary: {:?}",
            edit.new_text
        );
        assert!(
            edit.new_text.contains("@param"),
            "should keep @param: {:?}",
            edit.new_text
        );
        assert!(
            edit.new_text.contains("@return"),
            "should keep @return: {:?}",
            edit.new_text
        );
        assert!(
            !edit.new_text.contains("@throws"),
            "should remove @throws: {:?}",
            edit.new_text
        );
    }

    #[test]
    fn no_match_returns_none() {
        let php = "\
<?php
class Foo {
    /**
     * @throws FooException
     */
    public function bar(): void {}
}
";
        let db = find_docblock_above_line(php, 5).unwrap();
        assert!(build_remove_throws_edit(php, &db, "BarException").is_none());
    }

    #[test]
    fn removes_orphaned_blank_separator() {
        let php = "\
<?php
class Foo {
    /**
     * @param string $a
     *
     * @throws Decimal
     */
    public function bar(string $a): void {}
}
";
        let db = find_docblock_above_line(php, 7).unwrap();
        let edit = build_remove_throws_edit(php, &db, "Decimal").unwrap();
        // The blank `*` line between @param and @throws should also
        // be removed so we don't get a trailing blank line before `*/`.
        let trailing_blank = edit.new_text.contains(" *\n     */");
        assert!(
            !trailing_blank,
            "should not leave orphaned blank line: {:?}",
            edit.new_text
        );
    }

    // ── Single-line docblock ────────────────────────────────────────

    #[test]
    fn removes_single_line_docblock_with_throws() {
        let php = "<?php\nclass Foo {\n    /** @throws Decimal */\n    public function bar(): void {}\n}\n";
        // Line 3 is `    public function bar(): void {}`
        let db = find_docblock_above_line(php, 3)
            .expect("should find single-line docblock above line 3");
        let edit = build_remove_throws_edit(php, &db, "Decimal").unwrap();
        assert_eq!(
            edit.new_text, "",
            "single-line docblock with only @throws should be removed"
        );
    }
}