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
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
//! Update Docblock to Match Signature code action.
//!
//! When a function or method signature changes (parameters added, removed,
//! reordered, or type hints updated), the docblock often falls out of sync.
//! This code action patches the `@param` and `@return` tags to match the
//! current signature while preserving descriptions and other tags.
//!
//! **Trigger:** Cursor is inside the docblock of a function/method whose
//! `@param` tags don't match the signature's parameters (by name, count,
//! or order), whose `@return` tag contradicts the return type hint, or
//! whose `@return` tag can be enriched with body-based type inference.
//!
//! **Code action kind:** `quickfix`.

use std::collections::HashMap;
use std::sync::Arc;

use bumpalo::Bump;
use mago_docblock::document::TagKind;
use mago_span::HasSpan;
use mago_syntax::ast::class_like::member::ClassLikeMember;
use mago_syntax::ast::*;
use tower_lsp::lsp_types::*;

use super::cursor_context::{CursorContext, MemberContext, find_cursor_context};
use crate::Backend;
use crate::code_actions::phpstan::fix_return_type::enrichment_return_type;
use crate::completion::phpdoc::generation::{enrichment_plain, enrichment_plain_typed};
use crate::completion::source::throws_analysis::{self, ThrowsContext};
use crate::docblock::is_compatible_refinement_typed;
use crate::docblock::parser::{DocblockInfo, parse_docblock_for_tags};
use crate::docblock::type_strings::split_type_token;
use crate::parser::extract_hint_type;
use crate::php_type::PhpType;
use crate::types::{ClassInfo, FunctionLoader};
use crate::util::{offset_to_position, short_name};

// ── Data types ──────────────────────────────────────────────────────────────

/// A parameter extracted from the function/method signature.
#[derive(Debug, Clone)]
struct SigParam {
    /// Parameter name including `$` prefix.
    name: String,
    /// Native type hint as a structured type, if present.
    type_hint: Option<PhpType>,
    /// Whether the parameter is variadic (`...$args`).
    is_variadic: bool,
}

/// A `@param` tag parsed from an existing docblock.
#[derive(Debug, Clone)]
struct DocParam {
    /// The original type string from the tag, preserved for docblock output.
    type_str_raw: String,
    /// The parsed type, constructed once from `type_str_raw`.
    type_parsed: PhpType,
    /// Parameter name including `$` prefix (and optional `...` prefix for variadic).
    name: String,
    /// Description text after the `$name`.
    description: String,
}

/// A `@return` tag parsed from an existing docblock.
#[derive(Debug, Clone)]
struct DocReturn {
    /// The parsed type, constructed once from the raw tag string.
    type_parsed: PhpType,
    /// Description text after the type.
    description: String,
}

/// Information about the function/method under the cursor, including its
/// docblock position and parsed tags.
struct FunctionWithDocblock {
    /// Byte range of the docblock comment (from `/**` to `*/` inclusive).
    docblock_start: usize,
    docblock_end: usize,
    /// The raw docblock text.
    docblock_text: String,
    /// Parameters from the signature.
    sig_params: Vec<SigParam>,
    /// Return type from the signature (if any).
    sig_return: Option<PhpType>,
    /// `@param` tags from the docblock.
    doc_params: Vec<DocParam>,
    /// `@return` tag from the docblock (if any).
    doc_return: Option<DocReturn>,
    /// `@throws` exception type names from the docblock.
    doc_throws: Vec<String>,
    /// Indentation of the docblock lines (whitespace before ` * `).
    indent: String,
    /// LSP position of the docblock start (for throws analysis).
    docblock_position: Position,
}

impl Backend {
    /// Collect "Update docblock" code actions for the function/method
    /// under the cursor.
    pub(crate) fn collect_update_docblock_actions(
        &self,
        uri: &str,
        content: &str,
        params: &CodeActionParams,
        out: &mut Vec<CodeActionOrCommand>,
    ) {
        let doc_uri: Url = match uri.parse() {
            Ok(u) => u,
            Err(_) => return,
        };

        let cursor_offset = crate::util::position_to_offset(content, params.range.start);

        let arena = Bump::new();
        let file_id = mago_database::file::FileId::new("input.php");
        let program = mago_syntax::parser::parse_file_content(&arena, file_id, content);

        let ctx = find_cursor_context(&program.statements, cursor_offset);
        let trivia = program.trivia.as_slice();

        let info = match find_function_with_docblock_from_context(
            &ctx,
            &program.statements,
            trivia,
            content,
            cursor_offset,
        ) {
            Some(info) => info,
            None => return,
        };

        // Build a class loader and function loader for type enrichment.
        let ctx = self.file_context(uri);
        let class_loader = self.class_loader(&ctx);
        let function_loader = self.function_loader(&ctx);

        // Determine if anything needs updating.
        let needs_update = check_needs_update(
            &info,
            content,
            &ctx.classes,
            &class_loader,
            Some(&function_loader),
        );
        if !needs_update {
            return;
        }

        // Build the replacement docblock.
        let new_docblock = build_updated_docblock(
            &info,
            content,
            &ctx.classes,
            &class_loader,
            Some(&function_loader),
        );
        if new_docblock == info.docblock_text {
            return;
        }

        let start_pos = offset_to_position(content, info.docblock_start);
        let end_pos = offset_to_position(content, info.docblock_end);

        let mut changes = HashMap::new();
        changes.insert(
            doc_uri,
            vec![TextEdit {
                range: Range {
                    start: start_pos,
                    end: end_pos,
                },
                new_text: new_docblock,
            }],
        );

        out.push(CodeActionOrCommand::CodeAction(CodeAction {
            title: "Update docblock to match signature".to_string(),
            kind: Some(CodeActionKind::QUICKFIX),
            diagnostics: None,
            edit: Some(WorkspaceEdit {
                changes: Some(changes),
                document_changes: None,
                change_annotations: None,
            }),
            command: None,
            is_preferred: Some(true),
            disabled: None,
            data: None,
        }));
    }
}

// ── AST walk ────────────────────────────────────────────────────────────────

/// Use the shared `CursorContext` to find the function/method at the cursor
/// position, then check for an existing docblock.
fn find_function_with_docblock_from_context<'a>(
    ctx: &CursorContext<'a>,
    statements: &'a Sequence<'a, Statement<'a>>,
    trivia: &[Trivia<'a>],
    content: &str,
    cursor: u32,
) -> Option<FunctionWithDocblock> {
    match ctx {
        CursorContext::InClassLike {
            member,
            all_members,
            ..
        } => {
            if let MemberContext::Method(method, _in_body) = member
                && cursor_on_docblock(cursor, method, trivia, content)
            {
                return build_info_for_function_like(
                    method.span().start.offset,
                    &method.parameter_list,
                    method.return_type_hint.as_ref(),
                    trivia,
                    content,
                );
            }
            // The cursor may be inside the docblock trivia that precedes
            // a method.  Docblocks live outside the method's AST span, so
            // `find_cursor_context` reports `MemberContext::None`.  Scan
            // all members to find a method whose preceding docblock
            // contains the cursor.
            if matches!(member, MemberContext::None) {
                for m in all_members.iter() {
                    if let ClassLikeMember::Method(method) = m
                        && cursor_on_docblock(cursor, method, trivia, content)
                    {
                        return build_info_for_function_like(
                            method.span().start.offset,
                            &method.parameter_list,
                            method.return_type_hint.as_ref(),
                            trivia,
                            content,
                        );
                    }
                }
            }
            None
        }
        CursorContext::InFunction(func, _in_body) => {
            if cursor_on_docblock(cursor, func, trivia, content) {
                return build_info_for_function_like(
                    func.span().start.offset,
                    &func.parameter_list,
                    func.return_type_hint.as_ref(),
                    trivia,
                    content,
                );
            }
            None
        }
        CursorContext::None => {
            // The cursor may be inside a docblock that precedes a
            // top-level (or namespace-level) standalone function.
            // Docblocks are trivia, so `find_cursor_context` returns
            // `None` when the cursor sits before the function's AST
            // span.  Scan all top-level statements to find a match.
            find_standalone_function_by_docblock(statements, trivia, content, cursor)
        }
    }
}

/// Scan top-level (and namespace-level) statements for a standalone
/// function whose preceding docblock contains the cursor.
fn find_standalone_function_by_docblock<'a>(
    statements: &'a Sequence<'a, Statement<'a>>,
    trivia: &[Trivia<'a>],
    content: &str,
    cursor: u32,
) -> Option<FunctionWithDocblock> {
    for stmt in statements.iter() {
        match stmt {
            Statement::Function(func) => {
                if cursor_on_docblock(cursor, func, trivia, content) {
                    return build_info_for_function_like(
                        func.span().start.offset,
                        &func.parameter_list,
                        func.return_type_hint.as_ref(),
                        trivia,
                        content,
                    );
                }
            }
            Statement::Namespace(ns) => {
                for s in ns.statements().iter() {
                    if let Statement::Function(func) = s
                        && cursor_on_docblock(cursor, func, trivia, content)
                    {
                        return build_info_for_function_like(
                            func.span().start.offset,
                            &func.parameter_list,
                            func.return_type_hint.as_ref(),
                            trivia,
                            content,
                        );
                    }
                }
            }
            _ => {}
        }
    }
    None
}

/// Check whether the cursor is inside the docblock trivia that immediately
/// precedes the given AST node.
fn cursor_on_docblock(
    cursor: u32,
    node: &impl HasSpan,
    trivia: &[Trivia<'_>],
    content: &str,
) -> bool {
    let node_start = node.span().start.offset;
    // Check if the cursor is inside the docblock that belongs to this node.
    // Uses the canonical trivia-based locator from symbol_map::docblock.
    if let Some((_text, db_start)) =
        crate::symbol_map::docblock::get_docblock_text_with_offset(trivia, content, node)
        && cursor >= db_start
        && cursor < node_start
    {
        return true;
    }
    false
}

/// Build a `FunctionWithDocblock` from a function-like AST node.
fn build_info_for_function_like<'a>(
    node_start: u32,
    param_list: &function_like::parameter::FunctionLikeParameterList<'a>,
    return_type_hint: Option<&function_like::r#return::FunctionLikeReturnTypeHint<'a>>,
    trivia: &[Trivia<'a>],
    content: &str,
) -> Option<FunctionWithDocblock> {
    // Find the docblock trivia immediately before this node.
    let candidate_idx = trivia.partition_point(|t| t.span.start.offset < node_start);
    if candidate_idx == 0 {
        return None;
    }

    let content_bytes = content.as_bytes();
    let mut covered_from = node_start;

    let mut docblock_trivia = None;
    for i in (0..candidate_idx).rev() {
        let t = &trivia[i];
        let t_end = t.span.end.offset;

        let gap = content_bytes
            .get(t_end as usize..covered_from as usize)
            .unwrap_or(&[]);
        if !gap.iter().all(u8::is_ascii_whitespace) {
            break;
        }

        match t.kind {
            TriviaKind::DocBlockComment => {
                docblock_trivia = Some(t);
                break;
            }
            TriviaKind::WhiteSpace
            | TriviaKind::SingleLineComment
            | TriviaKind::MultiLineComment
            | TriviaKind::HashComment => {
                covered_from = t.span.start.offset;
            }
        }
    }

    let trivia_node = docblock_trivia?;
    let docblock_start = trivia_node.span.start.offset as usize;
    let docblock_end = trivia_node.span.end.offset as usize;
    let docblock_text = content.get(docblock_start..docblock_end)?.to_string();

    // Extract signature parameters.
    let sig_params: Vec<SigParam> = param_list
        .parameters
        .iter()
        .map(|p| {
            let name = p.variable.name.to_string();
            let type_hint = p.hint.as_ref().map(|h| extract_hint_type(h));
            let is_variadic = p.ellipsis.is_some();
            SigParam {
                name,
                type_hint,
                is_variadic,
            }
        })
        .collect();

    // Extract return type.
    let sig_return = return_type_hint.map(|rth| extract_hint_type(&rth.hint));

    // Parse existing docblock tags with a single parse pass.
    let docblock_info = parse_docblock_for_tags(&docblock_text);
    let doc_params = docblock_info
        .as_ref()
        .map(parse_doc_params_from_info)
        .unwrap_or_default();
    let doc_return = docblock_info.as_ref().and_then(parse_doc_return_from_info);
    let doc_throws = docblock_info
        .as_ref()
        .map(parse_doc_throws_from_info)
        .unwrap_or_default();

    // Detect indentation.
    let indent = detect_indent(content, docblock_start);

    // Compute LSP position for throws analysis.
    let docblock_position = offset_to_position(content, docblock_start);

    Some(FunctionWithDocblock {
        docblock_start,
        docblock_end,
        docblock_text,
        sig_params,
        sig_return,
        doc_params,
        doc_return,
        doc_throws,
        indent,
        docblock_position,
    })
}

// ── Docblock parsing ────────────────────────────────────────────────────────

/// Parse all `@param` tags from a pre-parsed [`DocblockInfo`].
fn parse_doc_params_from_info(info: &DocblockInfo) -> Vec<DocParam> {
    let mut results = Vec::new();

    for tag in info.tags_by_kind(TagKind::Param) {
        let rest = tag.description.trim();
        if rest.is_empty() {
            continue;
        }

        // When the first token starts with `$` (or `...$` for variadic),
        // there is no type — the token is the parameter name directly.
        let first_token = rest.split_whitespace().next().unwrap_or("");
        let is_name_first = first_token.starts_with('$') || first_token.starts_with("...$");

        let (type_str, name_token, after_params) = if is_name_first {
            ("", first_token, &rest[first_token.len()..])
        } else {
            // Extract type token.
            let (type_str, remainder) = split_type_token(rest);
            let remainder = remainder.trim_start();

            // Extract parameter name.
            let name_token = remainder.split_whitespace().next().unwrap_or("");
            let after_params = remainder.get(name_token.len()..).unwrap_or("");
            (type_str, name_token, after_params)
        };

        if name_token.is_empty() || (!name_token.contains('$')) {
            continue;
        }

        let name = name_token.to_string();

        // mago-docblock joins continuation lines with \n; collapse to spaces
        // for the description to match the old behaviour.
        let description = after_params
            .trim()
            .lines()
            .map(str::trim)
            .collect::<Vec<_>>()
            .join(" ");

        results.push(DocParam {
            type_parsed: PhpType::parse(type_str),
            type_str_raw: type_str.to_string(),
            name,
            description,
        });
    }

    results
}

/// Parse the `@return` tag from a pre-parsed [`DocblockInfo`].
fn parse_doc_return_from_info(info: &DocblockInfo) -> Option<DocReturn> {
    for tag in info.tags_by_kind(TagKind::Return) {
        let rest = tag.description.trim();
        if rest.is_empty() {
            continue;
        }

        // Skip conditional return types.
        if rest.starts_with('(') {
            continue;
        }

        let (type_str, remainder) = split_type_token(rest);
        let description = remainder.trim().to_string();

        return Some(DocReturn {
            type_parsed: PhpType::parse(type_str),
            description,
        });
    }

    None
}

/// Parse `@throws` tags from a pre-parsed [`DocblockInfo`], returning
/// the exception type names.
fn parse_doc_throws_from_info(info: &DocblockInfo) -> Vec<String> {
    let mut results = Vec::new();
    for tag in info.tags_by_kind(TagKind::Throws) {
        let rest = tag.description.trim();
        if let Some(type_name) = rest.split_whitespace().next()
            && !type_name.is_empty()
        {
            results.push(type_name.to_string());
        }
    }
    results
}

/// Detect the indentation prefix from the source at the docblock position.
fn detect_indent(content: &str, docblock_start: usize) -> String {
    // Walk backward from docblock_start to find the line start.
    let before = &content[..docblock_start];
    let line_start = before.rfind('\n').map(|p| p + 1).unwrap_or(0);
    let prefix = &content[line_start..docblock_start];
    // The indent is just whitespace.
    prefix.chars().take_while(|c| c.is_whitespace()).collect()
}

// ── Diff and update logic ───────────────────────────────────────────────────

/// Check whether the docblock needs updating.
fn check_needs_update(
    info: &FunctionWithDocblock,
    content: &str,
    local_classes: &[Arc<ClassInfo>],
    class_loader: &dyn Fn(&str) -> Option<Arc<ClassInfo>>,
    function_loader: FunctionLoader<'_>,
) -> bool {
    // Build a map of existing doc param names.
    let doc_param_names: Vec<&str> = info
        .doc_params
        .iter()
        .map(|p| {
            let n = p.name.as_str();
            n.strip_prefix("...").unwrap_or(n)
        })
        .collect();

    let sig_param_names: Vec<String> = info.sig_params.iter().map(|p| p.name.clone()).collect();

    // When the docblock already has at least one @param tag the user has
    // opted-in to documenting parameters, so every signature param is
    // relevant.  When the docblock has *zero* @param tags we only consider
    // params that need enrichment (matching generate-docblock behaviour).
    let has_any_doc_params = !doc_param_names.is_empty();

    if has_any_doc_params {
        // Check for missing, extra, or reordered params.
        if doc_param_names.len() != sig_param_names.len() {
            return true;
        }
        for (doc_name, sig_name) in doc_param_names.iter().zip(sig_param_names.iter()) {
            if *doc_name != sig_name.as_str() {
                return true;
            }
        }
    } else {
        // No @param tags at all — only flag if a param needs enrichment.
        let needs_enrichment = info
            .sig_params
            .iter()
            .any(|sp| enrichment_plain(sp.type_hint.as_ref(), class_loader).is_some());
        if needs_enrichment {
            return true;
        }
    }

    // Check for type contradictions in @param tags.
    for sig_param in &info.sig_params {
        if let Some(native_type) = &sig_param.type_hint
            && let Some(doc_param) = info.doc_params.iter().find(|dp| {
                let n = dp.name.as_str();
                let n = n.strip_prefix("...").unwrap_or(n);
                n == sig_param.name
            })
            && is_type_contradiction(&doc_param.type_parsed, native_type)
        {
            return true;
        }
    }

    // Check whether any existing @param type needs enrichment (e.g. a bare
    // `Closure` that should become `(Closure(): mixed)`, or a class with templates).
    // Skip when the doc type is already more specific (contains `<` or `(`).
    for sig_param in &info.sig_params {
        if let Some(doc_param) = info.doc_params.iter().find(|dp| {
            let n = dp.name.as_str();
            let n = n.strip_prefix("...").unwrap_or(n);
            n == sig_param.name
        }) {
            // If the doc type already carries generic params or a callable
            // signature, it is already enriched — no update needed.
            if doc_param.type_parsed.has_type_structure() {
                continue;
            }
            if let Some(enriched) =
                enrichment_plain_typed(sig_param.type_hint.as_ref(), class_loader)
                && !enriched.equivalent(&doc_param.type_parsed)
            {
                return true;
            }
        }
    }

    // Check @return tag.
    if let Some(sig_ret) = &info.sig_return
        && let Some(doc_ret) = &info.doc_return
    {
        // Remove `@return void` if the signature also has `: void`.
        if sig_ret.is_void() && doc_ret.type_parsed.is_void() {
            return true;
        }
        if is_type_contradiction(&doc_ret.type_parsed, sig_ret) {
            return true;
        }
    }

    // Check if the @return tag needs body-based enrichment.
    if let Some(sig_ret) = &info.sig_return
        && !sig_ret.is_void()
    {
        let doc_already_rich = info
            .doc_return
            .as_ref()
            .is_some_and(|dr| dr.type_parsed.has_type_structure());
        if !doc_already_rich
            && let Some(enriched) = enrichment_return_type(
                content,
                info.docblock_position,
                local_classes,
                class_loader,
                function_loader,
            )
            && !enriched.is_void()
            && !enriched.is_mixed()
            && !enriched.equivalent(sig_ret)
        {
            let differs_from_doc = info
                .doc_return
                .as_ref()
                .is_none_or(|dr| !dr.type_parsed.equivalent(&enriched));
            if differs_from_doc {
                return true;
            }
        }
    }

    // Check for missing @throws tags.
    let uncaught = throws_analysis::find_uncaught_throw_types_with_context(
        content,
        info.docblock_position,
        Some(&ThrowsContext {
            class_loader,
            function_loader,
        }),
    );
    let existing_lower: Vec<String> = info
        .doc_throws
        .iter()
        .map(|t| short_name(t).to_lowercase())
        .collect();
    for exc in &uncaught {
        let short = short_name(exc);
        if !existing_lower.contains(&short.to_lowercase()) {
            return true;
        }
    }

    false
}

/// Check if a docblock type contradicts a native type hint.
///
/// A contradiction means the docblock type is NOT a refinement of the native
/// type. For example, docblock says `string` but native says `int` is a
/// contradiction. But docblock says `non-empty-string` while native says
/// `string` is a refinement (not a contradiction).
fn is_type_contradiction(doc_type: &PhpType, native_type: &PhpType) -> bool {
    // `PhpType::equivalent` handles `?T` ↔ `T|null`, order-independent
    // unions, and FQN shortening.  It does not do case-insensitive
    // comparison, but PHP class names in practice come from the same
    // source so casing matches.
    if doc_type.equivalent(native_type) {
        return false;
    }

    // Check whether the docblock type is a compatible refinement of the
    // native type (e.g. `class-string<Foo>` refines `string`,
    // `list<User>` refines `array`, `positive-int` refines `int`).
    // This uses the shared refinement checker that also guards
    // `resolve_effective_type`.
    let native_core = native_type
        .non_null_type()
        .unwrap_or_else(|| native_type.clone());
    let doc_core = doc_type.non_null_type().unwrap_or_else(|| doc_type.clone());
    if is_compatible_refinement_typed(&doc_core, &native_core) {
        return false;
    }

    // For single-member types, compare base names directly.  If they
    // differ and neither is a refinement of the other, it is a
    // contradiction.
    let doc_bases = doc_type.union_members();
    let native_bases = native_type.union_members();

    if doc_bases.len() == 1
        && native_bases.len() == 1
        && !doc_bases[0].equivalent(native_bases[0])
        && !is_compatible_refinement_typed(doc_bases[0], native_bases[0])
    {
        return true;
    }

    false
}

/// Build the updated docblock text.
fn build_updated_docblock(
    info: &FunctionWithDocblock,
    content: &str,
    local_classes: &[Arc<ClassInfo>],
    class_loader: &dyn Fn(&str) -> Option<Arc<ClassInfo>>,
    function_loader: FunctionLoader<'_>,
) -> String {
    let indent = &info.indent;

    // Parse the existing docblock into lines, categorizing each line.
    let mut lines = parse_docblock_lines(&info.docblock_text);

    // Remove existing @param lines.
    lines.retain(|l| !matches!(l, DocLine::Param(_)));

    // Clean up orphaned empty lines left after removing @param lines.
    // Remove Empty lines that directly follow Open (no summary text).
    while lines.len() >= 2
        && matches!(lines[0], DocLine::Open)
        && matches!(lines[1], DocLine::Empty)
        && lines.get(2).is_some_and(|l| !matches!(l, DocLine::Text(_)))
    {
        lines.remove(1);
    }

    // Remove @return if it's redundant (void) or contradicted.
    let should_remove_return = should_remove_return(info);
    let should_update_return = should_update_return(info);
    if should_remove_return {
        lines.retain(|l| !matches!(l, DocLine::Return(_)));
    }

    // Find where to insert new @param lines.
    // Prefer inserting before the first @return or @throws, or at the end
    // before the closing `*/`.
    let insert_pos = find_param_insert_position(&lines);

    // Build new @param entries: (type_str, name_with_prefix, description).
    let param_entries: Vec<(String, String, String)> = info
        .sig_params
        .iter()
        .filter_map(|sig| {
            // Try to preserve the existing description for this param.
            let existing = info.doc_params.iter().find(|dp| {
                let n = dp.name.as_str();
                let n = n.strip_prefix("...").unwrap_or(n);
                n == sig.name
            });

            let has_any_doc_params = !info.doc_params.is_empty();

            let type_str = if let Some(existing) = existing {
                // If the existing type is a refinement, keep it.
                if let Some(native) = &sig.type_hint {
                    let native_str = native.to_string();
                    if is_type_contradiction(&existing.type_parsed, native) {
                        // Type is contradicted — try enrichment first, fall
                        // back to the raw native hint.
                        {
                            enrichment_plain(sig.type_hint.as_ref(), class_loader)
                                .unwrap_or(native_str)
                        }
                    } else if existing.type_parsed.has_type_structure() {
                        // Doc already has generics / callable / shape — keep it.
                        existing.type_str_raw.clone()
                    } else {
                        // Check if enrichment would upgrade the type (e.g.
                        // bare `Closure` → `(Closure(): mixed)`).
                        if let Some(enriched) =
                            enrichment_plain_typed(sig.type_hint.as_ref(), class_loader)
                        {
                            if !enriched.equivalent(&existing.type_parsed) {
                                enrichment_plain(sig.type_hint.as_ref(), class_loader)
                                    .unwrap_or_else(|| existing.type_str_raw.clone())
                            } else {
                                existing.type_str_raw.clone()
                            }
                        } else {
                            existing.type_str_raw.clone()
                        }
                    }
                } else {
                    existing.type_str_raw.clone()
                }
            } else if has_any_doc_params {
                // The docblock already documents some params, so add this
                // missing one — use enrichment or fall back to raw hint / mixed.
                {
                    enrichment_plain(sig.type_hint.as_ref(), class_loader).unwrap_or_else(|| {
                        sig.type_hint
                            .as_ref()
                            .map(|t| t.to_string())
                            .unwrap_or_else(|| PhpType::mixed().to_string())
                    })
                }
            } else {
                // No @param tags at all — only add a tag when the native
                // type needs enrichment, matching generate-docblock behaviour.
                enrichment_plain(sig.type_hint.as_ref(), class_loader)?
            };

            let description = existing.map(|e| e.description.clone()).unwrap_or_default();

            let name_prefix = if sig.is_variadic { "..." } else { "" };
            let full_name = format!("{}{}", name_prefix, sig.name);

            Some((type_str, full_name, description))
        })
        .collect();

    // Compute max type width for column alignment.
    let max_type_len = param_entries
        .iter()
        .map(|(t, _, _)| t.len())
        .max()
        .unwrap_or(0);

    // Build aligned @param DocLines.
    let new_params: Vec<DocLine> = param_entries
        .iter()
        .map(|(type_str, name, description)| {
            let padding = " ".repeat(max_type_len - type_str.len());
            let line_text = if description.is_empty() {
                format!("@param {}{} {}", type_str, padding, name)
            } else {
                format!("@param {}{} {} {}", type_str, padding, name, description)
            };
            DocLine::Param(line_text)
        })
        .collect();

    // Insert new param lines.
    for (i, param_line) in new_params.into_iter().enumerate() {
        lines.insert(insert_pos + i, param_line);
    }

    // Add missing @throws tags.
    let uncaught = throws_analysis::find_uncaught_throw_types_with_context(
        content,
        info.docblock_position,
        Some(&ThrowsContext {
            class_loader,
            function_loader,
        }),
    );
    let existing_throws_lower: Vec<String> = info
        .doc_throws
        .iter()
        .map(|t| short_name(t).to_lowercase())
        .collect();

    let mut new_throws: Vec<String> = Vec::new();
    for exc in &uncaught {
        let short = short_name(exc);
        if !existing_throws_lower.contains(&short.to_lowercase()) {
            new_throws.push(short.to_string());
        }
    }

    if !new_throws.is_empty() {
        // Find the position to insert @throws — after the last existing
        // @throws tag, or after @param block, or before @return.
        let throws_insert_pos = find_throws_insert_position(&lines);
        for (i, exc) in new_throws.iter().enumerate() {
            lines.insert(
                throws_insert_pos + i,
                DocLine::OtherTag(format!("@throws {}", exc)),
            );
        }
    }

    // Update @return type if needed.
    if should_update_return
        && let Some(sig_ret) = &info.sig_return
        && let Some(doc_ret) = &info.doc_return
    {
        let sig_ret_str = sig_ret.to_string();
        // Find and update the return line.
        for line in &mut lines {
            if let DocLine::Return(text) = line {
                let description = &doc_ret.description;
                if description.is_empty() {
                    *text = format!("@return {}", sig_ret_str);
                } else {
                    *text = format!("@return {} {}", sig_ret_str, description);
                }
                break;
            }
        }
    }

    // Body-based @return enrichment.
    if let Some(sig_ret) = &info.sig_return
        && !sig_ret.is_void()
    {
        let has_rich_return = info
            .doc_return
            .as_ref()
            .is_some_and(|dr| dr.type_parsed.has_type_structure());
        if !has_rich_return
            && let Some(enriched) = enrichment_return_type(
                content,
                info.docblock_position,
                local_classes,
                class_loader,
                function_loader,
            )
            && !enriched.is_void()
            && !enriched.is_mixed()
            && !enriched.equivalent(sig_ret)
        {
            let differs_from_doc = info
                .doc_return
                .as_ref()
                .is_none_or(|dr| !dr.type_parsed.equivalent(&enriched));
            if differs_from_doc {
                // Update existing @return line or insert a new one.
                let mut updated_existing = false;
                for line in &mut lines {
                    if let DocLine::Return(text) = line {
                        // Preserve any description text after the type.
                        let desc = info
                            .doc_return
                            .as_ref()
                            .map(|dr| dr.description.as_str())
                            .unwrap_or("");
                        if desc.is_empty() {
                            *text = format!("@return {}", enriched);
                        } else {
                            *text = format!("@return {} {}", enriched, desc);
                        }
                        updated_existing = true;
                        break;
                    }
                }
                if !updated_existing {
                    // Insert before the closing `*/`.
                    let close_pos = lines
                        .iter()
                        .position(|l| matches!(l, DocLine::Close))
                        .unwrap_or(lines.len());
                    lines.insert(close_pos, DocLine::Return(format!("@return {}", enriched)));
                }
            }
        }
    }

    // Rebuild the docblock text.
    rebuild_docblock(&lines, indent)
}

/// Categorized docblock line.
#[derive(Debug, Clone)]
enum DocLine {
    /// Opening `/**`.
    Open,
    /// Closing `*/`.
    Close,
    /// A summary or description line (not a tag).
    Text(String),
    /// A `@param` tag line.
    Param(String),
    /// A `@return` tag line.
    Return(String),
    /// Any other tag line (`@throws`, `@template`, `@deprecated`, etc.).
    OtherTag(String),
    /// An empty line (just ` * `).
    Empty,
}

/// Parse a docblock into categorized lines.
fn parse_docblock_lines(docblock: &str) -> Vec<DocLine> {
    let mut result = Vec::new();
    let lines: Vec<&str> = docblock.lines().collect();

    for (i, line) in lines.iter().enumerate() {
        let trimmed = line.trim();

        if i == 0 && trimmed.starts_with("/**") {
            // Single-line docblock: `/** @return void */`
            if trimmed.ends_with("*/") && trimmed.len() > 5 {
                let inner = trimmed
                    .strip_prefix("/**")
                    .unwrap_or("")
                    .strip_suffix("*/")
                    .unwrap_or("")
                    .trim();
                result.push(DocLine::Open);
                if !inner.is_empty() {
                    categorize_tag_line(inner, &mut result);
                }
                result.push(DocLine::Close);
                continue;
            }
            result.push(DocLine::Open);
            // Check if there's content after `/**` on the same line.
            let after_open = trimmed.strip_prefix("/**").unwrap_or("").trim();
            if !after_open.is_empty() {
                categorize_tag_line(after_open, &mut result);
            }
            continue;
        }

        if trimmed == "*/" || trimmed.ends_with("*/") {
            // Check if there's content before `*/`.
            let before_close = trimmed.strip_suffix("*/").unwrap_or("").trim();
            let before_close = before_close
                .strip_prefix('*')
                .unwrap_or(before_close)
                .trim();
            if !before_close.is_empty() {
                categorize_tag_line(before_close, &mut result);
            }
            result.push(DocLine::Close);
            continue;
        }

        // Regular docblock line: ` * content`
        let content = trimmed.strip_prefix('*').unwrap_or(trimmed).trim();

        // Check if this is a continuation line (no `@` prefix, preceded by
        // a tag line). If so, merge it into the previous tag line.
        if !content.is_empty()
            && !content.starts_with('@')
            && !result.is_empty()
            && matches!(
                result.last(),
                Some(DocLine::Param(_)) | Some(DocLine::Return(_)) | Some(DocLine::OtherTag(_))
            )
        {
            match result.last_mut() {
                Some(DocLine::Param(text))
                | Some(DocLine::Return(text))
                | Some(DocLine::OtherTag(text)) => {
                    text.push(' ');
                    text.push_str(content);
                }
                _ => {}
            }
            continue;
        }

        if content.is_empty() {
            result.push(DocLine::Empty);
        } else {
            categorize_tag_line(content, &mut result);
        }
    }

    result
}

/// Categorize a single content line (without the `*` prefix).
fn categorize_tag_line(content: &str, result: &mut Vec<DocLine>) {
    if content.starts_with("@param") {
        result.push(DocLine::Param(content.to_string()));
    } else if content.starts_with("@return") {
        result.push(DocLine::Return(content.to_string()));
    } else if content.starts_with('@') {
        result.push(DocLine::OtherTag(content.to_string()));
    } else {
        result.push(DocLine::Text(content.to_string()));
    }
}

/// Find the position to insert new `@param` lines.
fn find_param_insert_position(lines: &[DocLine]) -> usize {
    // Insert before the first @return, @throws, or other tag that comes
    // after any text/summary.
    let mut last_text_or_empty = None;
    let mut first_return_or_throws = None;

    for (i, line) in lines.iter().enumerate() {
        match line {
            DocLine::Text(_) | DocLine::Empty => {
                last_text_or_empty = Some(i);
            }
            DocLine::Return(_) => {
                if first_return_or_throws.is_none() {
                    first_return_or_throws = Some(i);
                }
            }
            DocLine::OtherTag(text) => {
                if (text.starts_with("@throws") || text.starts_with("@return"))
                    && first_return_or_throws.is_none()
                {
                    first_return_or_throws = Some(i);
                }
            }
            _ => {}
        }
    }

    // Prefer inserting before @return/@throws.
    if let Some(pos) = first_return_or_throws {
        return pos;
    }

    // Otherwise insert after the last text/empty line.
    if let Some(pos) = last_text_or_empty {
        return pos + 1;
    }

    // Fallback: insert before Close.
    for (i, line) in lines.iter().enumerate() {
        if matches!(line, DocLine::Close) {
            return i;
        }
    }

    lines.len()
}

/// Find the position to insert new `@throws` lines.
fn find_throws_insert_position(lines: &[DocLine]) -> usize {
    // Insert after the last existing @throws tag.
    let mut last_throws = None;
    let mut first_return = None;

    for (i, line) in lines.iter().enumerate() {
        match line {
            DocLine::OtherTag(text) if text.starts_with("@throws") => {
                last_throws = Some(i);
            }
            DocLine::Return(_) => {
                if first_return.is_none() {
                    first_return = Some(i);
                }
            }
            _ => {}
        }
    }

    // After the last existing @throws.
    if let Some(pos) = last_throws {
        return pos + 1;
    }

    // Before @return (but after any blank separator preceding it).
    if let Some(pos) = first_return {
        // If the line before @return is Empty, insert before that too.
        if pos > 0 && matches!(lines.get(pos - 1), Some(DocLine::Empty)) {
            return pos - 1;
        }
        return pos;
    }

    // After the last @param.
    let mut last_param = None;
    for (i, line) in lines.iter().enumerate() {
        if matches!(line, DocLine::Param(_)) {
            last_param = Some(i);
        }
    }
    if let Some(pos) = last_param {
        return pos + 1;
    }

    // Fallback: before Close.
    for (i, line) in lines.iter().enumerate() {
        if matches!(line, DocLine::Close) {
            return i;
        }
    }

    lines.len()
}

/// Check if the `@return` tag should be removed.
fn should_remove_return(info: &FunctionWithDocblock) -> bool {
    if let Some(sig_ret) = &info.sig_return
        && let Some(doc_ret) = &info.doc_return
        && sig_ret.is_void()
        && doc_ret.type_parsed.is_void()
        && doc_ret.description.is_empty()
    {
        return true;
    }
    false
}

/// Check if the `@return` tag needs its type updated.
fn should_update_return(info: &FunctionWithDocblock) -> bool {
    if let Some(sig_ret) = &info.sig_return
        && let Some(doc_ret) = &info.doc_return
        && is_type_contradiction(&doc_ret.type_parsed, sig_ret)
    {
        return true;
    }
    false
}

/// Rebuild a docblock string from categorized lines.
fn rebuild_docblock(lines: &[DocLine], indent: &str) -> String {
    let mut result = String::new();
    let mut prev_was_param = false;
    let mut prev_was_text_or_empty = false;

    for (i, line) in lines.iter().enumerate() {
        match line {
            DocLine::Open => {
                result.push_str("/**");
                result.push('\n');
                prev_was_param = false;
                prev_was_text_or_empty = false;
            }
            DocLine::Close => {
                result.push_str(indent);
                result.push_str(" */");
                prev_was_param = false;
                prev_was_text_or_empty = false;
            }
            DocLine::Text(text) => {
                // Add blank separator before text if preceded by tags.
                if prev_was_param {
                    result.push_str(indent);
                    result.push_str(" *\n");
                }
                result.push_str(indent);
                result.push_str(" * ");
                result.push_str(text);
                result.push('\n');
                prev_was_param = false;
                prev_was_text_or_empty = true;
            }
            DocLine::Empty => {
                result.push_str(indent);
                result.push_str(" *\n");
                prev_was_param = false;
                prev_was_text_or_empty = true;
            }
            DocLine::Param(text) => {
                // Add blank separator before first @param if preceded by text.
                if !prev_was_param && prev_was_text_or_empty {
                    // Check if the previous line was already empty.
                    let prev_empty = i > 0 && matches!(lines.get(i - 1), Some(DocLine::Empty));
                    if !prev_empty {
                        result.push_str(indent);
                        result.push_str(" *\n");
                    }
                }
                result.push_str(indent);
                result.push_str(" * ");
                result.push_str(text);
                result.push('\n');
                prev_was_param = true;
                prev_was_text_or_empty = false;
            }
            DocLine::Return(text) => {
                // Add blank separator before @return if preceded by @param.
                if prev_was_param {
                    result.push_str(indent);
                    result.push_str(" *\n");
                }
                // Add blank separator if preceded by text without a blank line.
                if prev_was_text_or_empty && !prev_was_param {
                    let prev_empty = i > 0 && matches!(lines.get(i - 1), Some(DocLine::Empty));
                    if !prev_empty {
                        result.push_str(indent);
                        result.push_str(" *\n");
                    }
                }
                result.push_str(indent);
                result.push_str(" * ");
                result.push_str(text);
                result.push('\n');
                prev_was_param = false;
                prev_was_text_or_empty = false;
            }
            DocLine::OtherTag(text) => {
                if prev_was_param {
                    result.push_str(indent);
                    result.push_str(" *\n");
                }
                result.push_str(indent);
                result.push_str(" * ");
                result.push_str(text);
                result.push('\n');
                prev_was_param = false;
                prev_was_text_or_empty = false;
            }
        }
    }

    result
}

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

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

    /// Helper: parse PHP and check if an update is needed at the given offset.
    fn find_info(php: &str, offset: u32) -> Option<FunctionWithDocblock> {
        let arena = Bump::new();
        let file_id = mago_database::file::FileId::new("input.php");
        let program = mago_syntax::parser::parse_file_content(&arena, file_id, php);
        let ctx = find_cursor_context(&program.statements, offset);
        find_function_with_docblock_from_context(
            &ctx,
            &program.statements,
            program.trivia.as_slice(),
            php,
            offset,
        )
    }

    /// Stub class loader that never resolves anything (for unit tests).
    fn no_class_loader() -> impl Fn(&str) -> Option<Arc<ClassInfo>> {
        |_| None
    }

    /// No function loader (for unit tests).
    fn no_function_loader() -> FunctionLoader<'static> {
        None
    }

    #[test]
    fn detects_missing_param() {
        let php = r#"<?php
class Foo {
    /**
     * Does something.
     *
     * @param string $a The first param
     */
    public function bar(string $a, int $b): void {}
}
"#;
        let pos = php.find("@param string").unwrap() as u32;
        let info = find_info(php, pos).unwrap();
        let cl = no_class_loader();
        assert!(check_needs_update(
            &info,
            php,
            &[],
            &cl,
            no_function_loader()
        ));
    }

    #[test]
    fn detects_extra_param() {
        let php = r#"<?php
class Foo {
    /**
     * @param string $a
     * @param int $b
     */
    public function bar(string $a): void {}
}
"#;
        let pos = php.find("@param string").unwrap() as u32;
        let info = find_info(php, pos).unwrap();
        let cl = no_class_loader();
        assert!(check_needs_update(
            &info,
            php,
            &[],
            &cl,
            no_function_loader()
        ));
    }

    #[test]
    fn detects_reordered_params() {
        let php = r#"<?php
class Foo {
    /**
     * @param int $b
     * @param string $a
     */
    public function bar(string $a, int $b): void {}
}
"#;
        let pos = php.find("@param int").unwrap() as u32;
        let info = find_info(php, pos).unwrap();
        let cl = no_class_loader();
        assert!(check_needs_update(
            &info,
            php,
            &[],
            &cl,
            no_function_loader()
        ));
    }

    #[test]
    fn no_update_when_params_match() {
        let php = r#"<?php
class Foo {
    /**
     * @param string $a
     * @param int $b
     */
    public function bar(string $a, int $b): void {}
}
"#;
        let pos = php.find("@param string").unwrap() as u32;
        let info = find_info(php, pos).unwrap();
        let cl = no_class_loader();
        assert!(!check_needs_update(
            &info,
            php,
            &[],
            &cl,
            no_function_loader()
        ));
    }

    #[test]
    fn detects_type_contradiction_in_param() {
        let php = r#"<?php
class Foo {
    /**
     * @param string $a
     */
    public function bar(int $a): void {}
}
"#;
        let pos = php.find("@param string").unwrap() as u32;
        let info = find_info(php, pos).unwrap();
        let cl = no_class_loader();
        assert!(check_needs_update(
            &info,
            php,
            &[],
            &cl,
            no_function_loader()
        ));
    }

    #[test]
    fn preserves_refinement_type() {
        let php = r#"<?php
class Foo {
    /**
     * @param non-empty-string $a
     */
    public function bar(string $a): void {}
}
"#;
        let pos = php.find("@param non-empty-string").unwrap() as u32;
        let info = find_info(php, pos).unwrap();
        let cl = no_class_loader();
        assert!(!check_needs_update(
            &info,
            php,
            &[],
            &cl,
            no_function_loader()
        ));
    }

    #[test]
    fn detects_void_return_redundancy() {
        let php = r#"<?php
class Foo {
    /**
     * @return void
     */
    public function bar(): void {}
}
"#;
        let pos = php.find("@return void").unwrap() as u32;
        let info = find_info(php, pos).unwrap();
        let cl = no_class_loader();
        assert!(check_needs_update(
            &info,
            php,
            &[],
            &cl,
            no_function_loader()
        ));
    }

    #[test]
    fn detects_return_type_contradiction() {
        let php = r#"<?php
class Foo {
    /**
     * @return string
     */
    public function bar(): int {}
}
"#;
        let pos = php.find("@return string").unwrap() as u32;
        let info = find_info(php, pos).unwrap();
        let cl = no_class_loader();
        assert!(check_needs_update(
            &info,
            php,
            &[],
            &cl,
            no_function_loader()
        ));
    }

    #[test]
    fn no_action_without_docblock() {
        let php = r#"<?php
class Foo {
    public function bar(string $a): void {}
}
"#;
        // No docblock at all — cursor on signature should return None.
        let pos = php.find("function bar").unwrap() as u32;
        let info = find_info(php, pos);
        assert!(info.is_none());
    }

    #[test]
    fn works_with_standalone_function() {
        let php = r#"<?php
/**
 * @param string $a
 * @param int $b
 */
function bar(string $a, int $b, bool $c): void {}
"#;
        let pos = php.find("@param string").unwrap() as u32;
        let info = find_info(php, pos).unwrap();
        let cl = no_class_loader();
        assert!(check_needs_update(
            &info,
            php,
            &[],
            &cl,
            no_function_loader()
        ));
    }

    #[test]
    fn preserves_descriptions() {
        let php = r#"<?php
class Foo {
    /**
     * Summary line.
     *
     * @param string $a The first param
     */
    public function bar(string $a, int $b): void {}
}
"#;
        let pos = php.find("@param string").unwrap() as u32;
        let info = find_info(php, pos).unwrap();
        let cl = no_class_loader();
        let updated = build_updated_docblock(&info, php, &[], &cl, no_function_loader());
        assert!(
            updated.contains("The first param"),
            "Should preserve description: {}",
            updated
        );
        assert!(
            updated.contains("$b"),
            "Should add missing param: {}",
            updated
        );
        assert!(
            updated.contains("Summary line"),
            "Should preserve summary: {}",
            updated
        );
    }

    #[test]
    fn removes_extra_param_and_adds_missing() {
        let php = r#"<?php
class Foo {
    /**
     * @param string $old
     * @param int $b
     */
    public function bar(int $b, bool $c): void {}
}
"#;
        let pos = php.find("@param string").unwrap() as u32;
        let info = find_info(php, pos).unwrap();
        let cl = no_class_loader();
        let updated = build_updated_docblock(&info, php, &[], &cl, no_function_loader());
        assert!(
            !updated.contains("$old"),
            "Should remove old param: {}",
            updated
        );
        assert!(updated.contains("$b"), "Should keep $b: {}", updated);
        assert!(updated.contains("$c"), "Should add $c: {}", updated);
    }

    #[test]
    fn updates_contradicted_return_type() {
        let php = r#"<?php
class Foo {
    /**
     * @return string Some description
     */
    public function bar(): int {}
}
"#;
        let pos = php.find("@return string").unwrap() as u32;
        let info = find_info(php, pos).unwrap();
        let cl = no_class_loader();
        let updated = build_updated_docblock(&info, php, &[], &cl, no_function_loader());
        assert!(
            updated.contains("@return int Some description"),
            "Should update return type: {}",
            updated
        );
    }

    #[test]
    fn removes_void_return() {
        let php = r#"<?php
class Foo {
    /**
     * Does something.
     *
     * @return void
     */
    public function bar(): void {}
}
"#;
        let pos = php.find("@return void").unwrap() as u32;
        let info = find_info(php, pos).unwrap();
        let cl = no_class_loader();
        let updated = build_updated_docblock(&info, php, &[], &cl, no_function_loader());
        assert!(
            !updated.contains("@return"),
            "Should remove @return void: {}",
            updated
        );
    }

    #[test]
    fn handles_variadic_param() {
        let php = r#"<?php
class Foo {
    /**
     * @param string ...$args
     */
    public function bar(string ...$args): void {}
}
"#;
        let pos = php.find("@param string").unwrap() as u32;
        let info = find_info(php, pos).unwrap();
        let cl = no_class_loader();
        // Variadic params should match — no update needed.
        assert!(!check_needs_update(
            &info,
            php,
            &[],
            &cl,
            no_function_loader()
        ));
    }

    #[test]
    fn preserves_generic_refinement() {
        let php = r#"<?php
class Foo {
    /**
     * @param array<int, string> $items
     */
    public function bar(array $items): void {}
}
"#;
        let pos = php.find("@param array").unwrap() as u32;
        let info = find_info(php, pos).unwrap();
        let cl = no_class_loader();
        // array<int, string> refines array — no contradiction.
        assert!(!check_needs_update(
            &info,
            php,
            &[],
            &cl,
            no_function_loader()
        ));
    }

    #[test]
    fn preserves_other_tags() {
        let php = r#"<?php
class Foo {
    /**
     * Summary.
     *
     * @template T
     * @param string $a
     * @throws \RuntimeException
     */
    public function bar(string $a, int $b): void {}
}
"#;
        let pos = php.find("@template T").unwrap() as u32;
        let info = find_info(php, pos).unwrap();
        let cl = no_class_loader();
        let updated = build_updated_docblock(&info, php, &[], &cl, no_function_loader());
        assert!(
            updated.contains("@template T"),
            "Should preserve @template: {}",
            updated
        );
        assert!(
            updated.contains("@throws"),
            "Should preserve @throws: {}",
            updated
        );
        assert!(
            updated.contains("$b"),
            "Should add missing param: {}",
            updated
        );
    }

    #[test]
    fn is_contradiction_basic() {
        assert!(is_type_contradiction(
            &PhpType::parse("string"),
            &PhpType::parse("int")
        ));
        assert!(!is_type_contradiction(
            &PhpType::parse("string"),
            &PhpType::parse("string")
        ));
        assert!(!is_type_contradiction(
            &PhpType::parse("non-empty-string"),
            &PhpType::parse("string")
        ));
        assert!(!is_type_contradiction(
            &PhpType::parse("array<int, string>"),
            &PhpType::parse("array")
        ));
    }

    #[test]
    fn is_contradiction_nullable() {
        // ?string and string|null are equivalent.
        assert!(!is_type_contradiction(
            &PhpType::parse("?string"),
            &PhpType::parse("?string")
        ));
        assert!(!is_type_contradiction(
            &PhpType::parse("string|null"),
            &PhpType::parse("?string")
        ));
    }

    #[test]
    fn works_in_namespace() {
        let php = r#"<?php
namespace App;
class Foo {
    /**
     * @param string $a
     */
    public function bar(int $a): void {}
}
"#;
        let pos = php.find("@param string").unwrap() as u32;
        let info = find_info(php, pos).unwrap();
        let cl = no_class_loader();
        assert!(check_needs_update(
            &info,
            php,
            &[],
            &cl,
            no_function_loader()
        ));
    }

    #[test]
    fn aligns_param_columns() {
        let php = r#"<?php
class Foo {
    /**
     * @param string $a
     */
    public function bar(string $a, int $b, array $items): void {}
}
"#;
        let pos = php.find("@param string").unwrap() as u32;
        let info = find_info(php, pos).unwrap();
        let cl = no_class_loader();
        let updated = build_updated_docblock(&info, php, &[], &cl, no_function_loader());
        // All $names should be aligned at the same column.
        assert!(
            updated.contains("@param string       $a"),
            "Should have string padded: {}",
            updated
        );
        assert!(
            updated.contains("@param int          $b"),
            "Should have int padded: {}",
            updated
        );
        assert!(
            updated.contains("@param array<mixed> $items"),
            "Should have array<mixed> padded: {}",
            updated
        );
    }

    #[test]
    fn no_spurious_blank_line_after_open() {
        let php = r#"<?php
class Foo {
    /**
     * @param string $a
     * @param int $b
     *
     * @return string
     */
    public function bar(string $a, int $b, bool $c): string {}
}
"#;
        let pos = php.find("@param string").unwrap() as u32;
        let info = find_info(php, pos).unwrap();
        let cl = no_class_loader();
        let updated = build_updated_docblock(&info, php, &[], &cl, no_function_loader());
        // Should NOT have a blank line between /** and the first @param.
        let lines: Vec<&str> = updated.lines().collect();
        assert_eq!(
            lines[0].trim(),
            "/**",
            "First line should be opening: {}",
            updated
        );
        assert!(
            lines[1].trim().starts_with("* @param"),
            "Second line should be @param, not blank: {}",
            updated
        );
    }

    #[test]
    fn enriches_callable_types() {
        let php = r#"<?php
class Foo {
    /**
     * @param string $a
     */
    public function bar(string $a, Closure $handler, callable $fallback): void {}
}
"#;
        let pos = php.find("@param string").unwrap() as u32;
        let info = find_info(php, pos).unwrap();
        let cl = no_class_loader();
        let updated = build_updated_docblock(&info, php, &[], &cl, no_function_loader());
        assert!(
            updated.contains("(Closure(): mixed)"),
            "Should enrich Closure: {}",
            updated
        );
        assert!(
            updated.contains("(callable(): mixed)"),
            "Should enrich callable: {}",
            updated
        );
    }

    #[test]
    fn adds_missing_throws() {
        let php = r#"<?php
class Foo {
    /**
     * @param string $a
     *
     * @return string
     */
    public function bar(string $a): string {
        throw new \RuntimeException('oops');
    }
}
"#;
        let pos = php.find("@param string").unwrap() as u32;
        let info = find_info(php, pos).unwrap();
        let cl = no_class_loader();
        let updated = build_updated_docblock(&info, php, &[], &cl, no_function_loader());
        assert!(
            updated.contains("@throws RuntimeException"),
            "Should add missing @throws: {}",
            updated
        );
    }

    #[test]
    fn does_not_duplicate_existing_throws() {
        let php = r#"<?php
class Foo {
    /**
     * @param string $a
     *
     * @throws RuntimeException
     *
     * @return string
     */
    public function bar(string $a): string {
        throw new \RuntimeException('oops');
    }
}
"#;
        let pos = php.find("@param string").unwrap() as u32;
        let info = find_info(php, pos).unwrap();
        let cl = no_class_loader();
        assert!(
            !check_needs_update(&info, php, &[], &cl, no_function_loader()),
            "Should not need update when throws already documented"
        );
    }

    #[test]
    fn triggers_when_cursor_inside_docblock() {
        let php = r#"<?php
class Foo {
    /**
     * @param string $a
     */
    public function bar(string $a, int $b): void {}
}
"#;
        // Place the cursor on the @param line inside the docblock.
        let pos = php.find("@param string").unwrap() as u32;
        let info = find_info(php, pos);
        assert!(
            info.is_some(),
            "Should find function info when cursor is inside the docblock"
        );
        let cl = no_class_loader();
        assert!(check_needs_update(
            &info.unwrap(),
            php,
            &[],
            &cl,
            no_function_loader()
        ));
    }

    #[test]
    fn triggers_when_cursor_on_docblock_summary() {
        let php = r#"<?php
class Foo {
    /**
     * Does something.
     *
     * @param string $a
     */
    public function bar(string $a, int $b): void {}
}
"#;
        // Place the cursor on the summary line.
        let pos = php.find("Does something").unwrap() as u32;
        let info = find_info(php, pos);
        assert!(
            info.is_some(),
            "Should find function info when cursor is on docblock summary"
        );
    }

    #[test]
    fn triggers_when_cursor_on_opening_docblock() {
        let php = r#"<?php
class Foo {
    /**
     * @param string $a
     */
    public function bar(string $a, int $b): void {}
}
"#;
        // Place the cursor on the /** line.
        let pos = php.find("/**").unwrap() as u32;
        let info = find_info(php, pos);
        assert!(
            info.is_some(),
            "Should find function info when cursor is on opening /**"
        );
    }

    // ── @param with no type ─────────────────────────────────────────

    /// Helper: parse a docblock string into params via `_from_info`.
    fn test_parse_params(docblock: &str) -> Vec<DocParam> {
        match parse_docblock_for_tags(docblock) {
            Some(info) => parse_doc_params_from_info(&info),
            None => Vec::new(),
        }
    }

    #[test]
    fn parse_param_no_type_recognised() {
        let docblock = r#"/**
     * @param $name The user name
     */"#;
        let params = test_parse_params(docblock);
        assert_eq!(params.len(), 1, "should parse one param: {:?}", params);
        assert_eq!(params[0].name, "$name");
        assert_eq!(params[0].type_str_raw, "");
        assert_eq!(params[0].description, "The user name");
    }

    #[test]
    fn parse_param_no_type_variadic() {
        let docblock = r#"/**
     * @param ...$args The arguments
     */"#;
        let params = test_parse_params(docblock);
        assert_eq!(params.len(), 1, "should parse one param: {:?}", params);
        assert_eq!(params[0].name, "...$args");
        assert_eq!(params[0].type_str_raw, "");
        assert_eq!(params[0].description, "The arguments");
    }

    #[test]
    fn parse_param_no_type_no_description() {
        let docblock = r#"/**
     * @param $name
     */"#;
        let params = test_parse_params(docblock);
        assert_eq!(params.len(), 1, "should parse one param: {:?}", params);
        assert_eq!(params[0].name, "$name");
        assert_eq!(params[0].type_str_raw, "");
    }

    #[test]
    fn parse_param_no_type_mixed_with_typed() {
        let docblock = r#"/**
     * @param string $a First
     * @param $b Second
     * @param int $c Third
     */"#;
        let params = test_parse_params(docblock);
        assert_eq!(params.len(), 3, "should parse three params: {:?}", params);
        assert_eq!(params[0].name, "$a");
        assert_eq!(params[0].type_str_raw, "string");
        assert_eq!(params[1].name, "$b");
        assert_eq!(params[1].type_str_raw, "");
        assert_eq!(params[1].description, "Second");
        assert_eq!(params[2].name, "$c");
        assert_eq!(params[2].type_str_raw, "int");
    }

    #[test]
    fn update_needed_when_untyped_param_matches_untyped_sig() {
        // Even when both the docblock and signature omit the type, the
        // update action should fire to add `mixed` as the explicit type.
        let php = r#"<?php
class Foo {
    /**
     * @param $name The user name
     */
    public function bar($name): void {}
}
"#;
        let pos = php.find("@param $name").unwrap() as u32;
        let info = find_info(php, pos).unwrap();
        let cl = no_class_loader();
        assert!(
            check_needs_update(&info, php, &[], &cl, no_function_loader()),
            "should need update to add `mixed` type to @param $name"
        );
        // The param must still be recognised (not duplicated).
        assert_eq!(info.doc_params.len(), 1);
        assert_eq!(info.doc_params[0].name, "$name");
        assert_eq!(info.doc_params[0].type_str_raw, "");
        assert_eq!(info.doc_params[0].description, "The user name");
    }

    #[test]
    fn detects_missing_param_when_existing_has_no_type() {
        let php = r#"<?php
class Foo {
    /**
     * @param $a First param
     */
    public function bar(string $a, int $b): void {}
}
"#;
        let pos = php.find("@param $a").unwrap() as u32;
        let info = find_info(php, pos).unwrap();
        let cl = no_class_loader();
        assert!(
            check_needs_update(&info, php, &[], &cl, no_function_loader()),
            "should need update because $b is missing"
        );
        assert_eq!(info.doc_params.len(), 1);
        assert_eq!(info.doc_params[0].name, "$a");
        assert_eq!(info.doc_params[0].description, "First param");
    }

    #[test]
    fn no_update_for_empty_docblock_with_fully_typed_params() {
        // When generate-docblock produces `/** */` (no @param tags) because
        // the native types are sufficient, update-docblock should NOT offer
        // to add redundant @param tags.
        let php = r#"<?php
class Foo {
    /**
     *
     */
    public function stepIntro(CustomerRequest $request): View {}
}
"#;
        let pos = php.find("/**").unwrap() as u32;
        let info = find_info(php, pos).unwrap();
        let cl = no_class_loader();
        assert!(
            !check_needs_update(&info, php, &[], &cl, no_function_loader()),
            "should not suggest adding @param for a fully-typed non-templated class param"
        );
    }

    #[test]
    fn no_update_for_empty_docblock_with_scalar_params() {
        let php = r#"<?php
class Foo {
    /**
     *
     */
    public function bar(string $a, int $b, bool $c): void {}
}
"#;
        let pos = php.find("/**").unwrap() as u32;
        let info = find_info(php, pos).unwrap();
        let cl = no_class_loader();
        assert!(
            !check_needs_update(&info, php, &[], &cl, no_function_loader()),
            "should not suggest adding @param for scalar-typed params"
        );
    }

    #[test]
    fn update_for_empty_docblock_with_untyped_param() {
        // When a param has no native type, enrichment produces `mixed`,
        // so the update should be offered.
        let php = r#"<?php
class Foo {
    /**
     *
     */
    public function bar($untyped): void {}
}
"#;
        let pos = php.find("/**").unwrap() as u32;
        let info = find_info(php, pos).unwrap();
        let cl = no_class_loader();
        assert!(
            check_needs_update(&info, php, &[], &cl, no_function_loader()),
            "should suggest adding @param for an untyped param"
        );
    }

    #[test]
    fn update_for_empty_docblock_with_array_param() {
        // `array` is enrichable (stays `array` but signals it needs a shape
        // or value-type annotation), so the update should be offered.
        let php = r#"<?php
class Foo {
    /**
     *
     */
    public function bar(array $items): void {}
}
"#;
        let pos = php.find("/**").unwrap() as u32;
        let info = find_info(php, pos).unwrap();
        let cl = no_class_loader();
        assert!(
            check_needs_update(&info, php, &[], &cl, no_function_loader()),
            "should suggest adding @param for an array param"
        );
    }

    #[test]
    fn no_info_inside_method_body() {
        let php = r#"<?php
class Foo {
    /**
     * @param string $a
     */
    public function bar(string $a, int $b): void {
        $x = 1;
    }
}
"#;
        // Place cursor on `$x = 1;` inside the method body.
        let pos = php.find("$x = 1").unwrap() as u32;
        let info = find_info(php, pos);
        assert!(
            info.is_none(),
            "should not offer update docblock inside method body"
        );
    }

    #[test]
    fn no_info_on_method_opening_brace() {
        let php = r#"<?php
class Foo {
    /**
     * @param string $a
     */
    public function bar(string $a, int $b): void {
        $x = 1;
    }
}
"#;
        // Place cursor on the opening brace of the method body.
        let pos = php.find("{\n        $x").unwrap() as u32;
        let info = find_info(php, pos);
        assert!(
            info.is_none(),
            "should not offer update docblock on method body brace"
        );
    }

    #[test]
    fn no_info_on_method_name() {
        let php = r#"<?php
class Foo {
    /**
     * @param string $a
     */
    public function bar(string $a, int $b): void {
        $x = 1;
    }
}
"#;
        let pos = php.find("bar").unwrap() as u32;
        let info = find_info(php, pos);
        assert!(
            info.is_none(),
            "should not offer update docblock when cursor is on method name"
        );
    }

    #[test]
    fn no_info_on_method_return_type() {
        let php = r#"<?php
class Foo {
    /**
     * @param string $a
     */
    public function bar(string $a, int $b): void {
        $x = 1;
    }
}
"#;
        let pos = php.find("void").unwrap() as u32;
        let info = find_info(php, pos);
        assert!(
            info.is_none(),
            "should not offer update docblock when cursor is on return type hint"
        );
    }

    #[test]
    fn no_info_inside_standalone_function_body() {
        let php = r#"<?php
/**
 * @param string $a
 */
function foo(string $a, int $b): void {
    $x = 1;
}
"#;
        let pos = php.find("$x = 1").unwrap() as u32;
        let info = find_info(php, pos);
        assert!(
            info.is_none(),
            "should not offer update docblock inside standalone function body"
        );
    }

    #[test]
    fn no_info_on_standalone_function_signature() {
        let php = r#"<?php
/**
 * @param string $a
 */
function foo(string $a, int $b): void {
    $x = 1;
}
"#;
        let pos = php.find("function foo").unwrap() as u32;
        let info = find_info(php, pos);
        assert!(
            info.is_none(),
            "should not offer update docblock when cursor is on standalone function signature"
        );
    }
}