php-lsp 0.1.54

A PHP Language Server Protocol implementation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
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
use std::sync::Arc;

use php_ast::{ClassMemberKind, EnumMemberKind, ExprKind, NamespaceBody, Param, Stmt, StmtKind};
use tower_lsp::lsp_types::{Hover, HoverContents, MarkupContent, MarkupKind, Position};

use crate::ast::{ParsedDoc, format_type_hint};
use crate::docblock::{Docblock, docblock_before, find_docblock, parse_docblock};
use crate::type_map::TypeMap;
use crate::util::{is_php_builtin, php_doc_url, word_at};

pub fn hover_info(
    source: &str,
    doc: &ParsedDoc,
    position: Position,
    other_docs: &[(tower_lsp::lsp_types::Url, Arc<ParsedDoc>)],
) -> Option<Hover> {
    hover_at(source, doc, other_docs, position)
}

/// Full hover implementation.
pub fn hover_at(
    source: &str,
    doc: &ParsedDoc,
    other_docs: &[(tower_lsp::lsp_types::Url, Arc<ParsedDoc>)],
    position: Position,
) -> Option<Hover> {
    // Feature 6: hover on use statement shows full FQN
    // Check this before word_at since cursor may be past the last word boundary
    if let Some(line_text) = source.lines().nth(position.line as usize) {
        let trimmed = line_text.trim();
        if trimmed.starts_with("use ") && !trimmed.starts_with("use function ") {
            let fqn = trimmed
                .strip_prefix("use ")
                .unwrap_or("")
                .trim_end_matches(';')
                .trim();
            if !fqn.is_empty() {
                // Find the word at position (may be None if at end of line)
                let maybe_word = word_at(source, position);
                let alias = fqn.rsplit('\\').next().unwrap_or(fqn);
                let matches = match &maybe_word {
                    Some(w) => w == alias || fqn.contains(w.as_str()),
                    None => true, // hovering past end of line on a use statement
                };
                if matches {
                    return Some(Hover {
                        contents: HoverContents::Markup(MarkupContent {
                            kind: MarkupKind::Markdown,
                            value: format!("`use {};`", fqn),
                        }),
                        range: None,
                    });
                }
            }
        }
    }

    let word = word_at(source, position)?;

    // Feature 2: hover on $variable shows its type
    if word.starts_with('$') {
        let arc_docs: Vec<Arc<ParsedDoc>> = other_docs.iter().map(|(_, d)| d.clone()).collect();
        let type_map = TypeMap::from_docs_with_meta(doc, &arc_docs, None);
        if let Some(class_name) = type_map.get(&word) {
            return Some(Hover {
                contents: HoverContents::Markup(MarkupContent {
                    kind: MarkupKind::Markdown,
                    value: format!("`{}` `{}`", word, class_name),
                }),
                range: None,
            });
        }
    }

    // Search current document first, then cross-file.
    let found = scan_statements(&doc.program().stmts, &word).map(|sig| (sig, source, doc));
    let found = found.or_else(|| {
        for (_, other) in other_docs {
            if let Some(sig) = scan_statements(&other.program().stmts, &word) {
                return Some((sig, other.source(), other.as_ref()));
            }
        }
        None
    });

    if let Some((sig, sig_source, sig_doc)) = found {
        let mut value = wrap_php(&sig);
        if let Some(db) = find_docblock(sig_source, &sig_doc.program().stmts, &word) {
            let md = db.to_markdown();
            if !md.is_empty() {
                value.push_str("\n\n---\n\n");
                value.push_str(&md);
            }
        }
        if is_php_builtin(&word) {
            value.push_str(&format!(
                "\n\n[php.net documentation]({})",
                php_doc_url(&word)
            ));
        }
        return Some(Hover {
            contents: HoverContents::Markup(MarkupContent {
                kind: MarkupKind::Markdown,
                value,
            }),
            range: None,
        });
    }

    // Fallback: built-in function with no user-defined counterpart.
    if is_php_builtin(&word) {
        let value = format!(
            "```php\nfunction {}()\n```\n\n[php.net documentation]({})",
            word,
            php_doc_url(&word)
        );
        return Some(Hover {
            contents: HoverContents::Markup(MarkupContent {
                kind: MarkupKind::Markdown,
                value,
            }),
            range: None,
        });
    }

    // Feature 4: hover on a property name in `$obj->propName` or `$this->propName`
    if !word.starts_with('$')
        && let Some(line_text) = source.lines().nth(position.line as usize)
    {
        // Check if the word appears after `->` or `?->` on this line
        let arrow_word = format!("->{}", word);
        let nullsafe_arrow_word = format!("?->{}", word);
        if line_text.contains(&arrow_word) || line_text.contains(&nullsafe_arrow_word) {
            // Find the position of `->word` in the line and extract the receiver var
            // before it.
            let arrow_pos = line_text
                .find(&nullsafe_arrow_word)
                .or_else(|| line_text.find(&arrow_word));
            if let Some(apos) = arrow_pos {
                let before_arrow = &line_text[..apos];
                let receiver_var = extract_receiver_var_from_end(before_arrow);
                if let Some(var_name) = receiver_var {
                    let arc_docs: Vec<Arc<ParsedDoc>> =
                        other_docs.iter().map(|(_, d)| d.clone()).collect();
                    let type_map = TypeMap::from_docs_with_meta(doc, &arc_docs, None);
                    let class_name = if var_name == "$this" {
                        crate::type_map::enclosing_class_at(source, doc, position)
                            .or_else(|| type_map.get("$this").map(|s| s.to_string()))
                    } else {
                        type_map.get(&var_name).map(|s| s.to_string())
                    };
                    if let Some(cls) = class_name {
                        // Search current doc + other docs for the property type
                        let all_docs_search: Vec<&ParsedDoc> = std::iter::once(doc)
                            .chain(other_docs.iter().map(|(_, d)| d.as_ref()))
                            .collect();
                        for d in &all_docs_search {
                            if let Some((type_str, db)) = find_property_info(d, &cls, &word) {
                                let sig = format!(
                                    "(property) {}::${}{}",
                                    cls,
                                    word,
                                    if type_str.is_empty() {
                                        String::new()
                                    } else {
                                        format!(": {}", type_str)
                                    }
                                );
                                let mut value = wrap_php(&sig);
                                if let Some(doc) = db {
                                    let md = doc.to_markdown();
                                    if !md.is_empty() {
                                        value.push_str("\n\n---\n\n");
                                        value.push_str(&md);
                                    }
                                }
                                return Some(Hover {
                                    contents: HoverContents::Markup(MarkupContent {
                                        kind: MarkupKind::Markdown,
                                        value,
                                    }),
                                    range: None,
                                });
                            }
                        }
                    }
                }
            }
        }
    }

    // Feature 3: hover on a built-in class name shows stub info
    if let Some(stub) = crate::stubs::builtin_class_members(&word) {
        let method_names: Vec<&str> = stub
            .methods
            .iter()
            .filter(|(_, is_static)| !is_static)
            .map(|(n, _)| n.as_str())
            .take(8)
            .collect();
        let static_names: Vec<&str> = stub
            .methods
            .iter()
            .filter(|(_, is_static)| *is_static)
            .map(|(n, _)| n.as_str())
            .take(4)
            .collect();
        let mut lines = vec![format!("**{}** — built-in class", word)];
        if !method_names.is_empty() {
            lines.push(format!(
                "Methods: {}",
                method_names
                    .iter()
                    .map(|n| format!("`{n}`"))
                    .collect::<Vec<_>>()
                    .join(", ")
            ));
        }
        if !static_names.is_empty() {
            lines.push(format!(
                "Static: {}",
                static_names
                    .iter()
                    .map(|n| format!("`{n}`"))
                    .collect::<Vec<_>>()
                    .join(", ")
            ));
        }
        if let Some(parent) = &stub.parent {
            lines.push(format!("Extends: `{parent}`"));
        }
        return Some(Hover {
            contents: HoverContents::Markup(MarkupContent {
                kind: MarkupKind::Markdown,
                value: lines.join("\n\n"),
            }),
            range: None,
        });
    }

    None
}

fn scan_statements(stmts: &[Stmt<'_, '_>], word: &str) -> Option<String> {
    for stmt in stmts {
        match &stmt.kind {
            StmtKind::Function(f) if f.name == word => {
                let params = format_params(&f.params);
                let ret = f
                    .return_type
                    .as_ref()
                    .map(|r| format!(": {}", format_type_hint(r)))
                    .unwrap_or_default();
                return Some(format!("function {}({}){}", word, params, ret));
            }
            StmtKind::Class(c) if c.name == Some(word) => {
                let mut sig = format!("class {}", word);
                if let Some(ext) = &c.extends {
                    sig.push_str(&format!(" extends {}", ext.to_string_repr()));
                }
                if !c.implements.is_empty() {
                    let ifaces: Vec<String> = c
                        .implements
                        .iter()
                        .map(|i| i.to_string_repr().into_owned())
                        .collect();
                    sig.push_str(&format!(" implements {}", ifaces.join(", ")));
                }
                return Some(sig);
            }
            StmtKind::Interface(i) if i.name == word => {
                return Some(format!("interface {}", word));
            }
            StmtKind::Interface(i) => {
                for member in i.members.iter() {
                    match &member.kind {
                        ClassMemberKind::Method(m) if m.name == word => {
                            let params = format_params(&m.params);
                            let ret = m
                                .return_type
                                .as_ref()
                                .map(|r| format!(": {}", format_type_hint(r)))
                                .unwrap_or_default();
                            return Some(format!("function {}({}){}", word, params, ret));
                        }
                        ClassMemberKind::ClassConst(k) if k.name == word => {
                            return Some(format_class_const(k));
                        }
                        _ => {}
                    }
                }
            }
            StmtKind::Trait(t) if t.name == word => {
                return Some(format!("trait {}", word));
            }
            StmtKind::Enum(e) if e.name == word => {
                let mut sig = format!("enum {}", word);
                if !e.implements.is_empty() {
                    let ifaces: Vec<String> = e
                        .implements
                        .iter()
                        .map(|i| i.to_string_repr().into_owned())
                        .collect();
                    sig.push_str(&format!(" implements {}", ifaces.join(", ")));
                }
                return Some(sig);
            }
            StmtKind::Enum(e) => {
                for member in e.members.iter() {
                    match &member.kind {
                        EnumMemberKind::Method(m) if m.name == word => {
                            let params = format_params(&m.params);
                            let ret = m
                                .return_type
                                .as_ref()
                                .map(|r| format!(": {}", format_type_hint(r)))
                                .unwrap_or_default();
                            return Some(format!("function {}({}){}", word, params, ret));
                        }
                        EnumMemberKind::Case(c) if c.name == word => {
                            let value_str = c
                                .value
                                .as_ref()
                                .and_then(format_expr_literal)
                                .map(|v| format!(" = {v}"))
                                .unwrap_or_default();
                            return Some(format!("case {}::{}{}", e.name, c.name, value_str));
                        }
                        EnumMemberKind::ClassConst(k) if k.name == word => {
                            return Some(format_class_const(k));
                        }
                        _ => {}
                    }
                }
            }
            StmtKind::Class(c) => {
                for member in c.members.iter() {
                    match &member.kind {
                        ClassMemberKind::Method(m) if m.name == word => {
                            let params = format_params(&m.params);
                            let ret = m
                                .return_type
                                .as_ref()
                                .map(|r| format!(": {}", format_type_hint(r)))
                                .unwrap_or_default();
                            return Some(format!("function {}({}){}", word, params, ret));
                        }
                        ClassMemberKind::ClassConst(k) if k.name == word => {
                            return Some(format_class_const(k));
                        }
                        _ => {}
                    }
                }
            }
            StmtKind::Trait(t) => {
                for member in t.members.iter() {
                    match &member.kind {
                        ClassMemberKind::Method(m) if m.name == word => {
                            let params = format_params(&m.params);
                            let ret = m
                                .return_type
                                .as_ref()
                                .map(|r| format!(": {}", format_type_hint(r)))
                                .unwrap_or_default();
                            return Some(format!("function {}({}){}", word, params, ret));
                        }
                        ClassMemberKind::ClassConst(k) if k.name == word => {
                            return Some(format_class_const(k));
                        }
                        _ => {}
                    }
                }
            }
            StmtKind::Namespace(ns) => {
                if let NamespaceBody::Braced(inner) = &ns.body
                    && let Some(sig) = scan_statements(inner, word)
                {
                    return Some(sig);
                }
            }
            _ => {}
        }
    }
    None
}

/// Format a literal expression value for hover display (int, float, bool, or string literals).
fn format_expr_literal(expr: &php_ast::Expr<'_, '_>) -> Option<String> {
    match &expr.kind {
        ExprKind::Int(n) => Some(n.to_string()),
        ExprKind::Float(f) => Some(f.to_string()),
        ExprKind::Bool(b) => Some(if *b { "true" } else { "false" }.to_string()),
        ExprKind::String(s) => Some(format!("'{}'", s)),
        _ => None,
    }
}

/// Format a class/interface/enum constant declaration for hover display.
fn format_class_const(c: &php_ast::ClassConstDecl<'_, '_>) -> String {
    let type_str = c
        .type_hint
        .as_ref()
        .map(|t| format!("{} ", format_type_hint(t)))
        .or_else(|| match &c.value.kind {
            ExprKind::Int(_) => Some("int ".to_string()),
            ExprKind::String(_) => Some("string ".to_string()),
            ExprKind::Float(_) => Some("float ".to_string()),
            ExprKind::Bool(_) => Some("bool ".to_string()),
            _ => None,
        })
        .unwrap_or_default();
    let value_str = format_expr_literal(&c.value)
        .map(|v| format!(" = {v}"))
        .unwrap_or_default();
    format!("const {}{}{}", type_str, c.name, value_str)
}

/// Look up markdown documentation for a symbol by name across all indexed documents.
/// Returns a markdown string with a code fence signature and optional PHPDoc annotations,
/// or `None` if the symbol is not found.
pub fn docs_for_symbol(
    name: &str,
    all_docs: &[(tower_lsp::lsp_types::Url, Arc<ParsedDoc>)],
) -> Option<String> {
    for (_, doc) in all_docs {
        if let Some(sig) = scan_statements(&doc.program().stmts, name) {
            let mut value = wrap_php(&sig);
            if let Some(db) = find_docblock(doc.source(), &doc.program().stmts, name) {
                let md = db.to_markdown();
                if !md.is_empty() {
                    value.push_str("\n\n---\n\n");
                    value.push_str(&md);
                }
            }
            if is_php_builtin(name) {
                value.push_str(&format!(
                    "\n\n[php.net documentation]({})",
                    php_doc_url(name)
                ));
            }
            return Some(value);
        }
    }
    // Fallback: built-in with no user-defined counterpart.
    if is_php_builtin(name) {
        return Some(format!(
            "```php\nfunction {}()\n```\n\n[php.net documentation]({})",
            name,
            php_doc_url(name)
        ));
    }
    None
}

pub(crate) fn format_params_str(params: &[Param<'_, '_>]) -> String {
    format_params(params)
}

/// Return the plain-text signature for a symbol (function or method) found in
/// any of the supplied documents, or `None` if not found.
///
/// Examples of returned strings:
///   `"function foo(string $bar, int $baz): bool"`
///   `"function __construct(Foo $x)"`
pub fn signature_for_symbol(
    name: &str,
    all_docs: &[(tower_lsp::lsp_types::Url, Arc<ParsedDoc>)],
) -> Option<String> {
    for (_, doc) in all_docs {
        if let Some(sig) = scan_statements(&doc.program().stmts, name) {
            return Some(sig);
        }
    }
    None
}

fn format_params(params: &[Param<'_, '_>]) -> String {
    params
        .iter()
        .map(|p| {
            let mut s = String::new();
            if p.by_ref {
                s.push('&');
            }
            if p.variadic {
                s.push_str("...");
            }
            if let Some(t) = &p.type_hint {
                s.push_str(&format!("{} ", format_type_hint(t)));
            }
            s.push_str(&format!("${}", p.name));
            if let Some(default) = &p.default {
                s.push_str(&format!(" = {}", format_default_value(default)));
            }
            s
        })
        .collect::<Vec<_>>()
        .join(", ")
}

/// Format a default parameter value for display in signatures.
fn format_default_value(expr: &php_ast::Expr<'_, '_>) -> String {
    match &expr.kind {
        ExprKind::Int(n) => n.to_string(),
        ExprKind::Float(f) => f.to_string(),
        ExprKind::String(s) => format!("'{}'", s),
        ExprKind::Bool(b) => {
            if *b {
                "true".to_string()
            } else {
                "false".to_string()
            }
        }
        ExprKind::Null => "null".to_string(),
        ExprKind::Array(items) => {
            if items.is_empty() {
                "[]".to_string()
            } else {
                "[...]".to_string()
            }
        }
        _ => "...".to_string(),
    }
}

fn wrap_php(sig: &str) -> String {
    format!("```php\n{}\n```", sig)
}

/// Extract the receiver variable name (with `$`) from the end of text that appears
/// immediately before `->` or `?->`.
fn extract_receiver_var_from_end(before_arrow: &str) -> Option<String> {
    // The text ends with the variable name (and possibly whitespace)
    let trimmed = before_arrow.trim_end();
    let var_name: String = trimmed
        .chars()
        .rev()
        .take_while(|&c| c.is_alphanumeric() || c == '_' || c == '$')
        .collect::<String>()
        .chars()
        .rev()
        .collect();
    if var_name.starts_with('$') && var_name.len() > 1 {
        Some(var_name)
    } else if !var_name.is_empty() && !var_name.starts_with('$') {
        Some(format!("${}", var_name))
    } else {
        None
    }
}

/// Find the type hint and docblock for a property named `prop_name` in class `class_name`
/// within `doc`. Returns `Some((type_str, docblock))` if found, where `type_str` may be empty
/// if no type hint is present and `docblock` is `None` if there is no preceding `/** */` comment.
fn find_property_info(
    doc: &ParsedDoc,
    class_name: &str,
    prop_name: &str,
) -> Option<(String, Option<Docblock>)> {
    find_property_info_in_stmts(doc.source(), &doc.program().stmts, class_name, prop_name)
}

fn find_property_info_in_stmts<'a>(
    source: &str,
    stmts: &[Stmt<'a, 'a>],
    class_name: &str,
    prop_name: &str,
) -> Option<(String, Option<Docblock>)> {
    for stmt in stmts {
        match &stmt.kind {
            StmtKind::Class(c) if c.name == Some(class_name) => {
                for member in c.members.iter() {
                    match &member.kind {
                        ClassMemberKind::Property(p) if p.name == prop_name => {
                            let type_str = p
                                .type_hint
                                .as_ref()
                                .map(|t| crate::ast::format_type_hint(t))
                                .unwrap_or_default();
                            let db = docblock_before(source, member.span.start)
                                .map(|raw| parse_docblock(&raw));
                            return Some((type_str, db));
                        }
                        ClassMemberKind::Method(m) if m.name == "__construct" => {
                            // Check promoted constructor parameters
                            for p in m.params.iter() {
                                if p.name == prop_name && p.visibility.is_some() {
                                    let type_str = p
                                        .type_hint
                                        .as_ref()
                                        .map(|t| crate::ast::format_type_hint(t))
                                        .unwrap_or_default();
                                    // Promoted params don't have their own docblock;
                                    // filter the constructor's docblock to the @param for this
                                    // property only — exclude description, @return, @throws, etc.
                                    // Returns None (not Some(empty)) when no matching @param
                                    // exists, preserving the contract of this function.
                                    let db = docblock_before(source, member.span.start).and_then(
                                        |raw| {
                                            let full = parse_docblock(&raw);
                                            let matching: Vec<_> = full
                                                .params
                                                .into_iter()
                                                .filter(|dp| {
                                                    dp.name.strip_prefix('$') == Some(prop_name)
                                                })
                                                .collect();
                                            if matching.is_empty() {
                                                None
                                            } else {
                                                Some(crate::docblock::Docblock {
                                                    params: matching,
                                                    ..Default::default()
                                                })
                                            }
                                        },
                                    );
                                    return Some((type_str, db));
                                }
                            }
                        }
                        _ => {}
                    }
                }
                // Property not found in this class
                return None;
            }
            StmtKind::Namespace(ns) => {
                if let NamespaceBody::Braced(inner) = &ns.body
                    && let Some(t) =
                        find_property_info_in_stmts(source, inner, class_name, prop_name)
                {
                    return Some(t);
                }
            }
            _ => {}
        }
    }
    None
}

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

    fn pos(line: u32, character: u32) -> Position {
        Position { line, character }
    }

    #[test]
    fn hover_on_function_name_returns_signature() {
        let (src, p) = cursor("<?php\nfunction g$0reet(string $name): string {}");
        let doc = ParsedDoc::parse(src.clone());
        let result = hover_info(&src, &doc, p, &[]);
        assert!(result.is_some(), "expected hover result");
        if let Some(Hover {
            contents: HoverContents::Markup(mc),
            ..
        }) = result
        {
            assert!(
                mc.value.contains("function greet("),
                "expected function signature, got: {}",
                mc.value
            );
        }
    }

    #[test]
    fn hover_on_class_name_returns_class_sig() {
        let (src, p) = cursor("<?php\nclass My$0Service {}");
        let doc = ParsedDoc::parse(src.clone());
        let result = hover_info(&src, &doc, p, &[]);
        assert!(result.is_some(), "expected hover result");
        if let Some(Hover {
            contents: HoverContents::Markup(mc),
            ..
        }) = result
        {
            assert!(
                mc.value.contains("class MyService"),
                "expected class sig, got: {}",
                mc.value
            );
        }
    }

    #[test]
    fn hover_on_unknown_word_returns_none() {
        let src = "<?php\n$unknown = 42;";
        let doc = ParsedDoc::parse(src.to_string());
        let result = hover_info(src, &doc, pos(1, 2), &[]);
        assert!(result.is_none(), "expected None for unknown word");
    }

    #[test]
    fn hover_at_column_beyond_line_length_returns_none() {
        let src = "<?php\nfunction hi() {}";
        let doc = ParsedDoc::parse(src.to_string());
        let result = hover_info(src, &doc, pos(1, 999), &[]);
        assert!(result.is_none());
    }

    #[test]
    fn word_at_extracts_from_middle_of_identifier() {
        let (src, p) = cursor("<?php\nfunction greet$0User() {}");
        let word = word_at(&src, p);
        assert_eq!(word.as_deref(), Some("greetUser"));
    }

    #[test]
    fn hover_on_class_with_extends_shows_parent() {
        let src = "<?php\nclass Dog extends Animal {}";
        let doc = ParsedDoc::parse(src.to_string());
        let result = hover_info(src, &doc, pos(1, 8), &[]);
        assert!(result.is_some());
        if let Some(Hover {
            contents: HoverContents::Markup(mc),
            ..
        }) = result
        {
            assert!(
                mc.value.contains("extends Animal"),
                "expected 'extends Animal', got: {}",
                mc.value
            );
        }
    }

    #[test]
    fn hover_on_class_with_implements_shows_interfaces() {
        let src = "<?php\nclass Repo implements Countable, Serializable {}";
        let doc = ParsedDoc::parse(src.to_string());
        let result = hover_info(src, &doc, pos(1, 8), &[]);
        assert!(result.is_some());
        if let Some(Hover {
            contents: HoverContents::Markup(mc),
            ..
        }) = result
        {
            assert!(
                mc.value.contains("implements Countable, Serializable"),
                "expected implements list, got: {}",
                mc.value
            );
        }
    }

    #[test]
    fn hover_on_trait_returns_trait_sig() {
        let src = "<?php\ntrait Loggable {}";
        let doc = ParsedDoc::parse(src.to_string());
        let result = hover_info(src, &doc, pos(1, 8), &[]);
        assert!(result.is_some());
        if let Some(Hover {
            contents: HoverContents::Markup(mc),
            ..
        }) = result
        {
            assert!(
                mc.value.contains("trait Loggable"),
                "expected 'trait Loggable', got: {}",
                mc.value
            );
        }
    }

    #[test]
    fn hover_on_interface_returns_interface_sig() {
        let src = "<?php\ninterface Serializable {}";
        let doc = ParsedDoc::parse(src.to_string());
        let result = hover_info(src, &doc, pos(1, 12), &[]);
        assert!(result.is_some(), "expected hover result");
        if let Some(Hover {
            contents: HoverContents::Markup(mc),
            ..
        }) = result
        {
            assert!(
                mc.value.contains("interface Serializable"),
                "expected interface sig, got: {}",
                mc.value
            );
        }
    }

    #[test]
    fn function_with_no_params_no_return_shows_no_colon() {
        let src = "<?php\nfunction init() {}";
        let doc = ParsedDoc::parse(src.to_string());
        let result = hover_info(src, &doc, pos(1, 10), &[]);
        assert!(result.is_some());
        if let Some(Hover {
            contents: HoverContents::Markup(mc),
            ..
        }) = result
        {
            assert!(
                mc.value.contains("function init()"),
                "expected 'function init()', got: {}",
                mc.value
            );
            assert!(
                !mc.value.contains(':'),
                "should not contain ':' when no return type, got: {}",
                mc.value
            );
        }
    }

    #[test]
    fn hover_on_enum_returns_enum_sig() {
        let src = "<?php\nenum Suit {}";
        let doc = ParsedDoc::parse(src.to_string());
        let result = hover_info(src, &doc, pos(1, 6), &[]);
        assert!(result.is_some());
        if let Some(Hover {
            contents: HoverContents::Markup(mc),
            ..
        }) = result
        {
            assert!(
                mc.value.contains("enum Suit"),
                "expected 'enum Suit', got: {}",
                mc.value
            );
        }
    }

    #[test]
    fn hover_on_enum_with_implements_shows_interface() {
        let src = "<?php\nenum Status: string implements Stringable {}";
        let doc = ParsedDoc::parse(src.to_string());
        let result = hover_info(src, &doc, pos(1, 6), &[]);
        assert!(result.is_some());
        if let Some(Hover {
            contents: HoverContents::Markup(mc),
            ..
        }) = result
        {
            assert!(
                mc.value.contains("implements Stringable"),
                "expected implements clause, got: {}",
                mc.value
            );
        }
    }

    #[test]
    fn hover_on_enum_case_shows_case_sig() {
        let src = "<?php\nenum Status { case Active; case Inactive; }";
        let doc = ParsedDoc::parse(src.to_string());
        // "Active" starts at col 19: "enum Status { case Active;"
        let result = hover_info(src, &doc, pos(1, 21), &[]);
        assert!(result.is_some(), "expected hover on enum case");
        if let Some(Hover {
            contents: HoverContents::Markup(mc),
            ..
        }) = result
        {
            assert!(
                mc.value.contains("Status::Active"),
                "expected 'Status::Active', got: {}",
                mc.value
            );
        }
    }

    #[test]
    fn snapshot_hover_backed_enum_case_shows_value() {
        check_hover(
            "<?php\nenum Color: string { case Red = 'red'; }",
            pos(1, 27),
            expect![[r#"
                ```php
                case Color::Red = 'red'
                ```"#]],
        );
    }

    #[test]
    fn snapshot_hover_enum_class_const() {
        check_hover(
            "<?php\nenum Suit { const int MAX = 4; }",
            pos(1, 22),
            expect![[r#"
                ```php
                const int MAX = 4
                ```"#]],
        );
    }

    #[test]
    fn hover_on_trait_method_returns_signature() {
        let src = "<?php\ntrait Loggable { public function log(string $msg): void {} }";
        let doc = ParsedDoc::parse(src.to_string());
        // "log" at "trait Loggable { public function log(" — col 33
        let result = hover_info(src, &doc, pos(1, 34), &[]);
        assert!(result.is_some(), "expected hover on trait method");
        if let Some(Hover {
            contents: HoverContents::Markup(mc),
            ..
        }) = result
        {
            assert!(
                mc.value.contains("function log("),
                "expected function sig, got: {}",
                mc.value
            );
        }
    }

    #[test]
    fn cross_file_hover_finds_class_in_other_doc() {
        use std::sync::Arc;
        let src = "<?php\n$x = new PaymentService();";
        let other_src = "<?php\nclass PaymentService { public function charge() {} }";
        let doc = ParsedDoc::parse(src.to_string());
        let other_doc = Arc::new(ParsedDoc::parse(other_src.to_string()));
        let uri = tower_lsp::lsp_types::Url::parse("file:///other.php").unwrap();
        let other_docs = vec![(uri, other_doc)];
        // Hover on "PaymentService" in line 1
        let result = hover_info(src, &doc, pos(1, 12), &other_docs);
        assert!(result.is_some(), "expected cross-file hover result");
        if let Some(Hover {
            contents: HoverContents::Markup(mc),
            ..
        }) = result
        {
            assert!(
                mc.value.contains("PaymentService"),
                "expected 'PaymentService', got: {}",
                mc.value
            );
        }
    }

    #[test]
    fn hover_on_variable_shows_type() {
        let src = "<?php\n$obj = new Mailer();\n$obj";
        let doc = ParsedDoc::parse(src.to_string());
        let h = hover_at(src, &doc, &[], pos(2, 2));
        assert!(h.is_some());
        let text = match h.unwrap().contents {
            HoverContents::Markup(m) => m.value,
            _ => String::new(),
        };
        assert!(text.contains("Mailer"), "hover on $obj should show Mailer");
    }

    #[test]
    fn hover_on_builtin_class_shows_stub_info() {
        let src = "<?php\n$pdo = new PDO('sqlite::memory:');\n$pdo->query('SELECT 1');";
        let doc = ParsedDoc::parse(src.to_string());
        let h = hover_at(src, &doc, &[], pos(1, 12));
        assert!(h.is_some(), "should hover on PDO");
        let text = match h.unwrap().contents {
            HoverContents::Markup(m) => m.value,
            _ => String::new(),
        };
        assert!(text.contains("PDO"), "hover should mention PDO");
    }

    #[test]
    fn hover_on_property_shows_type() {
        let src = "<?php\nclass User { public string $name; public int $age; }\n$u = new User();\n$u->name";
        let doc = ParsedDoc::parse(src.to_string());
        // "name" in "$u->name" — col 4 in "$u->name"
        let h = hover_at(src, &doc, &[], pos(3, 5));
        assert!(h.is_some(), "expected hover on property");
        let text = match h.unwrap().contents {
            HoverContents::Markup(m) => m.value,
            _ => String::new(),
        };
        assert!(text.contains("User"), "should mention class name");
        assert!(text.contains("name"), "should mention property name");
        assert!(text.contains("string"), "should show type hint");
    }

    #[test]
    fn hover_on_promoted_property_shows_type() {
        let src = "<?php\nclass Point {\n    public function __construct(\n        public float $x,\n        public float $y,\n    ) {}\n}\n$p = new Point(1.0, 2.0);\n$p->x";
        let doc = ParsedDoc::parse(src.to_string());
        // "x" at the end of "$p->x"
        let h = hover_at(src, &doc, &[], pos(8, 4));
        assert!(h.is_some(), "expected hover on promoted property");
        let text = match h.unwrap().contents {
            HoverContents::Markup(m) => m.value,
            _ => String::new(),
        };
        assert!(text.contains("Point"), "should mention class name");
        assert!(text.contains("x"), "should mention property name");
        assert!(
            text.contains("float"),
            "should show type hint for promoted property"
        );
    }

    #[test]
    fn hover_on_promoted_property_shows_only_its_param_docblock() {
        // Issue #26: hovering a promoted property should show only the @param for
        // that property, not the full constructor docblock (no @return, @throws,
        // or @param entries for other parameters).
        let src = "<?php\nclass User {\n    /**\n     * Create a user.\n     * @param string $name The user's display name\n     * @param int $age The user's age\n     * @return void\n     * @throws \\InvalidArgumentException\n     */\n    public function __construct(\n        public string $name,\n        public int $age,\n    ) {}\n}\n$u = new User('Alice', 30);\n$u->name";
        let doc = ParsedDoc::parse(src.to_string());
        // hover on "$u->name" — cursor on 'name' (line 15, char 4 after "$u->")
        let h = hover_at(src, &doc, &[], pos(15, 4));
        assert!(h.is_some(), "expected hover on promoted property");
        let text = match h.unwrap().contents {
            HoverContents::Markup(m) => m.value,
            _ => String::new(),
        };
        assert!(
            text.contains("@param") && text.contains("$name"),
            "should show @param for $name"
        );
        assert!(
            !text.contains("$age"),
            "should NOT show @param for other parameters"
        );
        assert!(
            !text.contains("@return"),
            "should NOT show @return from constructor docblock"
        );
        assert!(
            !text.contains("@throws"),
            "should NOT show @throws from constructor docblock"
        );
        assert!(
            !text.contains("Create a user"),
            "should NOT show constructor description"
        );
    }

    #[test]
    fn hover_on_promoted_property_with_no_param_docblock_shows_type_only() {
        // When the constructor has a docblock but no @param for this promoted property,
        // hover should still work (showing type) without appending any docblock section.
        let src = "<?php\nclass User {\n    /**\n     * Create a user.\n     * @return void\n     */\n    public function __construct(\n        public string $name,\n    ) {}\n}\n$u = new User('Alice');\n$u->name";
        let doc = ParsedDoc::parse(src.to_string());
        let h = hover_at(src, &doc, &[], pos(11, 4));
        assert!(h.is_some(), "expected hover on promoted property");
        let text = match h.unwrap().contents {
            HoverContents::Markup(m) => m.value,
            _ => String::new(),
        };
        assert!(text.contains("string"), "should show type hint");
        assert!(
            !text.contains("---"),
            "should not append a docblock section"
        );
    }

    #[test]
    fn hover_on_use_alias_shows_fqn() {
        let src = "<?php\nuse App\\Mail\\Mailer;\n$m = new Mailer();";
        let doc = ParsedDoc::parse(src.to_string());
        let h = hover_at(
            src,
            &doc,
            &[],
            Position {
                line: 1,
                character: 20,
            },
        );
        assert!(h.is_some());
        let text = match h.unwrap().contents {
            HoverContents::Markup(m) => m.value,
            _ => String::new(),
        };
        assert!(text.contains("App\\Mail\\Mailer"), "should show full FQN");
    }

    #[test]
    fn hover_unknown_symbol_returns_none() {
        // `unknownFunc` is not defined anywhere — hover should return None.
        let src = "<?php\nunknownFunc();";
        let doc = ParsedDoc::parse(src.to_string());
        let result = hover_info(src, &doc, pos(1, 3), &[]);
        assert!(
            result.is_none(),
            "hover on undefined symbol should return None"
        );
    }

    #[test]
    fn hover_on_builtin_function_returns_signature() {
        // `strlen` is a built-in function; hovering should return a non-empty
        // string that contains "strlen".
        let src = "<?php\nstrlen('hello');";
        let doc = ParsedDoc::parse(src.to_string());
        let result = hover_info(src, &doc, pos(1, 3), &[]);
        let h = result.expect("expected hover result for built-in 'strlen'");
        let text = match h.contents {
            HoverContents::Markup(mc) => mc.value,
            _ => String::new(),
        };
        assert!(
            !text.is_empty(),
            "hover on strlen should return non-empty content"
        );
        assert!(
            text.contains("strlen"),
            "hover content should contain 'strlen', got: {text}"
        );
    }

    #[test]
    fn hover_on_property_shows_docblock() {
        let src = "<?php\nclass User {\n    /** The user's display name. */\n    public string $name;\n}\n$u = new User();\n$u->name";
        let doc = ParsedDoc::parse(src.to_string());
        // "name" in "$u->name" at the last line
        let h = hover_at(src, &doc, &[], pos(6, 5));
        assert!(h.is_some(), "expected hover on property with docblock");
        let text = match h.unwrap().contents {
            HoverContents::Markup(m) => m.value,
            _ => String::new(),
        };
        assert!(text.contains("User"), "should mention class name");
        assert!(text.contains("name"), "should mention property name");
        assert!(text.contains("string"), "should show type hint");
        assert!(
            text.contains("display name"),
            "should include docblock description, got: {}",
            text
        );
    }

    #[test]
    fn hover_on_property_with_var_tag_shows_type_annotation() {
        // A property with only `@var TypeHint` (no free-text description) must still
        // surface the @var annotation in the hover — it was previously swallowed because
        // to_markdown() never rendered var_type.
        let src = "<?php\nclass User {\n    /** @var string */\n    public $name;\n}\n$u = new User();\n$u->name";
        let doc = ParsedDoc::parse(src.to_string());
        let h = hover_at(src, &doc, &[], pos(6, 5));
        assert!(h.is_some(), "expected hover on @var-only property");
        let text = match h.unwrap().contents {
            HoverContents::Markup(m) => m.value,
            _ => String::new(),
        };
        assert!(
            text.contains("@var"),
            "should show @var annotation, got: {}",
            text
        );
        assert!(
            text.contains("string"),
            "should show var type, got: {}",
            text
        );
    }

    #[test]
    fn hover_on_property_with_var_tag_and_description() {
        let src = "<?php\nclass User {\n    /** @var string The display name. */\n    public $name;\n}\n$u = new User();\n$u->name";
        let doc = ParsedDoc::parse(src.to_string());
        let h = hover_at(src, &doc, &[], pos(6, 5));
        assert!(
            h.is_some(),
            "expected hover on property with @var description"
        );
        let text = match h.unwrap().contents {
            HoverContents::Markup(m) => m.value,
            _ => String::new(),
        };
        assert!(
            text.contains("@var"),
            "should show @var annotation, got: {}",
            text
        );
        assert!(
            text.contains("The display name"),
            "should show @var description, got: {}",
            text
        );
    }

    #[test]
    fn hover_on_this_property_shows_type() {
        let src = "<?php\nclass Counter {\n    public int $count = 0;\n    public function increment(): void {\n        $this->count;\n    }\n}";
        let doc = ParsedDoc::parse(src.to_string());
        // "$this->count" — "count" starts at col 15 in "        $this->count;"
        let h = hover_at(src, &doc, &[], pos(4, 16));
        assert!(h.is_some(), "expected hover on $this->property");
        let text = match h.unwrap().contents {
            HoverContents::Markup(m) => m.value,
            _ => String::new(),
        };
        assert!(text.contains("Counter"), "should mention enclosing class");
        assert!(text.contains("count"), "should mention property name");
        assert!(text.contains("int"), "should show type hint");
    }

    #[test]
    fn hover_on_nullsafe_property_shows_type() {
        let src = "<?php\nclass Profile { public string $bio; }\n$p = new Profile();\n$p?->bio";
        let doc = ParsedDoc::parse(src.to_string());
        // "bio" in "$p?->bio" at line 3, col 5
        let h = hover_at(src, &doc, &[], pos(3, 5));
        assert!(h.is_some(), "expected hover on nullsafe property access");
        let text = match h.unwrap().contents {
            HoverContents::Markup(m) => m.value,
            _ => String::new(),
        };
        assert!(text.contains("Profile"), "should mention class name");
        assert!(text.contains("bio"), "should mention property name");
        assert!(text.contains("string"), "should show type hint");
    }

    // ── Snapshot tests ───────────────────────────────────────────────────────

    use expect_test::{Expect, expect};

    fn check_hover(src: &str, position: Position, expect: Expect) {
        let doc = ParsedDoc::parse(src.to_string());
        let result = hover_info(src, &doc, position, &[]);
        let actual = match result {
            Some(Hover {
                contents: HoverContents::Markup(mc),
                ..
            }) => mc.value,
            Some(_) => "(non-markup hover)".to_string(),
            None => "(no hover)".to_string(),
        };
        expect.assert_eq(&actual);
    }

    #[test]
    fn snapshot_hover_simple_function() {
        check_hover(
            "<?php\nfunction init() {}",
            pos(1, 10),
            expect![[r#"
                ```php
                function init()
                ```"#]],
        );
    }

    #[test]
    fn snapshot_hover_function_with_return_type() {
        check_hover(
            "<?php\nfunction greet(string $name): string {}",
            pos(1, 10),
            expect![[r#"
                ```php
                function greet(string $name): string
                ```"#]],
        );
    }

    #[test]
    fn snapshot_hover_class() {
        check_hover(
            "<?php\nclass MyService {}",
            pos(1, 8),
            expect![[r#"
                ```php
                class MyService
                ```"#]],
        );
    }

    #[test]
    fn snapshot_hover_class_with_extends() {
        check_hover(
            "<?php\nclass Dog extends Animal {}",
            pos(1, 8),
            expect![[r#"
                ```php
                class Dog extends Animal
                ```"#]],
        );
    }

    #[test]
    fn snapshot_hover_method() {
        check_hover(
            "<?php\nclass Calc { public function add(int $a, int $b): int {} }",
            pos(1, 32),
            expect![[r#"
                ```php
                function add(int $a, int $b): int
                ```"#]],
        );
    }

    #[test]
    fn snapshot_hover_trait() {
        check_hover(
            "<?php\ntrait Loggable {}",
            pos(1, 8),
            expect![[r#"
                ```php
                trait Loggable
                ```"#]],
        );
    }

    #[test]
    fn snapshot_hover_interface() {
        check_hover(
            "<?php\ninterface Serializable {}",
            pos(1, 12),
            expect![[r#"
                ```php
                interface Serializable
                ```"#]],
        );
    }

    #[test]
    fn snapshot_hover_class_const_with_type_hint() {
        check_hover(
            "<?php\nclass Config { const string VERSION = '1.0.0'; }",
            pos(1, 28),
            expect![[r#"
                ```php
                const string VERSION = '1.0.0'
                ```"#]],
        );
    }

    #[test]
    fn snapshot_hover_class_const_float_value() {
        check_hover(
            "<?php\nclass Math { const float PI = 3.14; }",
            pos(1, 27),
            expect![[r#"
                ```php
                const float PI = 3.14
                ```"#]],
        );
    }

    #[test]
    fn snapshot_hover_class_const_infers_type_from_value() {
        let (src, p) = cursor("<?php\nclass Config { const VERSION$0 = '1.0.0'; }");
        check_hover(
            &src,
            p,
            expect![[r#"
                ```php
                const string VERSION = '1.0.0'
                ```"#]],
        );
    }

    #[test]
    fn snapshot_hover_interface_const_shows_type_and_value() {
        let (src, p) = cursor("<?php\ninterface Limits { const int MA$0X = 100; }");
        check_hover(
            &src,
            p,
            expect![[r#"
                ```php
                const int MAX = 100
                ```"#]],
        );
    }

    #[test]
    fn snapshot_hover_trait_const_shows_type_and_value() {
        let (src, p) = cursor("<?php\ntrait HasVersion { const string TAG$0 = 'v1'; }");
        check_hover(
            &src,
            p,
            expect![[r#"
                ```php
                const string TAG = 'v1'
                ```"#]],
        );
    }

    #[test]
    fn hover_on_catch_variable_shows_exception_class() {
        let (src, p) = cursor("<?php\ntry { } catch (RuntimeException $e$0) { }");
        let doc = ParsedDoc::parse(src.clone());
        let result = hover_info(&src, &doc, p, &[]);
        assert!(result.is_some(), "expected hover result for catch variable");
        if let Some(Hover {
            contents: HoverContents::Markup(mc),
            ..
        }) = result
        {
            assert!(
                mc.value.contains("RuntimeException"),
                "expected RuntimeException in hover, got: {}",
                mc.value
            );
        }
    }

    #[test]
    fn hover_on_static_var_with_array_default_shows_array() {
        let (src, p) = cursor("<?php\nfunction counter() { static $cach$0e = []; }");
        let doc = ParsedDoc::parse(src.clone());
        let result = hover_info(&src, &doc, p, &[]);
        assert!(
            result.is_some(),
            "expected hover result for static variable"
        );
        if let Some(Hover {
            contents: HoverContents::Markup(mc),
            ..
        }) = result
        {
            assert!(
                mc.value.contains("array"),
                "expected array type in hover, got: {}",
                mc.value
            );
        }
    }

    #[test]
    fn hover_on_static_var_with_new_shows_class() {
        let (src, p) = cursor("<?php\nfunction make() { static $inst$0ance = new MyService(); }");
        let doc = ParsedDoc::parse(src.clone());
        let result = hover_info(&src, &doc, p, &[]);
        assert!(
            result.is_some(),
            "expected hover result for static variable"
        );
        if let Some(Hover {
            contents: HoverContents::Markup(mc),
            ..
        }) = result
        {
            assert!(
                mc.value.contains("MyService"),
                "expected MyService in hover, got: {}",
                mc.value
            );
        }
    }
}