-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathdocblock.rs
More file actions
1539 lines (1392 loc) · 60.6 KB
/
Copy pathdocblock.rs
File metadata and controls
1539 lines (1392 loc) · 60.6 KB
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
//! Docblock symbol extraction helpers for the symbol map.
//!
//! This module contains functions that scan PHPDoc comment blocks for
//! type references in supported tags (`@param`, `@return`, `@var`,
//! `@template`, `@method`, etc.) and emit [`SymbolSpan`] entries with
//! correct file-level byte offsets.
//!
//! Tag detection and iteration uses the structured [`DocblockInfo`] /
//! [`TagInfo`] infrastructure from [`crate::docblock::parser`], which
//! delegates to `mago-docblock` for parsing. Type *string* decomposition
//! (unions, intersections, generics, callables, conditionals) remains
//! structured via [`emit_type_spans`] which uses `mago-type-syntax` to
//! parse types and walk the AST with accurate span information.
use bumpalo::Bump;
use mago_database::file::FileId;
use mago_docblock::document::TagKind;
use mago_span::{HasSpan, Position, Span};
use mago_syntax::ast::*;
use mago_type_syntax::ast as type_ast;
use crate::docblock::parser::parse_docblock;
use crate::docblock::types::split_type_token;
use crate::php_type::PhpType;
use crate::types::TemplateVariance;
use super::{ClassRefContext, SelfStaticParentKind, SymbolKind, SymbolSpan};
use crate::util::strip_fqn_prefix;
// ─── Navigability filter ────────────────────────────────────────────────────
/// Returns `true` when a type name refers to a class/interface that the
/// user should be able to navigate to.
///
/// Uses simple string splitting instead of `PhpType::parse()` + `base_name()`
/// because this is called for every type span during symbol-map extraction
/// and must stay allocation-free.
pub(crate) fn is_navigable_type(name: &str) -> bool {
let base = name.split('<').next().unwrap_or(name);
let base = base.split('{').next().unwrap_or(base);
let base = base.trim();
if base.is_empty() {
return false;
}
!crate::php_type::is_keyword_type(base)
}
// ─── Span construction helpers ──────────────────────────────────────────────
/// Construct a `ClassReference` `SymbolSpan` from a raw identifier string.
///
/// Detects whether the name is fully-qualified (leading `\`) and sets
/// `is_fqn` accordingly. The leading `\` is stripped from the stored
/// `name` in all cases.
pub(super) fn class_ref_span(start: u32, end: u32, raw_name: &str) -> SymbolSpan {
let is_fqn = raw_name.starts_with('\\');
let name = strip_fqn_prefix(raw_name).to_string();
SymbolSpan {
start,
end,
kind: SymbolKind::ClassReference {
name,
is_fqn,
context: ClassRefContext::Other,
},
}
}
/// Like [`class_ref_span`] but with an explicit [`ClassRefContext`].
pub(super) fn class_ref_span_ctx(
start: u32,
end: u32,
raw_name: &str,
ctx: ClassRefContext,
) -> SymbolSpan {
let is_fqn = raw_name.starts_with('\\');
let name = strip_fqn_prefix(raw_name).to_string();
SymbolSpan {
start,
end,
kind: SymbolKind::ClassReference {
name,
is_fqn,
context: ctx,
},
}
}
// ─── Docblock text retrieval ────────────────────────────────────────────────
/// Like [`crate::docblock::get_docblock_text_for_node`] but also returns
/// the byte offset of the `/**` opening within the file.
pub fn get_docblock_text_with_offset<'a>(
trivia: &'a [Trivia<'a>],
content: &str,
node: &impl HasSpan,
) -> Option<(&'a str, u32)> {
use crate::atom::bytes_to_str;
let node_start = node.span().start.offset;
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;
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) {
return None;
}
match t.kind {
TriviaKind::DocBlockComment => {
return Some((bytes_to_str(t.value), t.span.start.offset));
}
TriviaKind::WhiteSpace
| TriviaKind::SingleLineComment
| TriviaKind::MultiLineComment
| TriviaKind::HashComment => {
covered_from = t.span.start.offset;
}
}
}
None
}
// ─── Tag classification ─────────────────────────────────────────────────────
/// `TagKind` values whose description starts with a type expression.
const TYPE_FIRST_KINDS: &[TagKind] = &[
TagKind::Param,
TagKind::Return,
TagKind::Throws,
TagKind::Var,
TagKind::Property,
TagKind::PropertyRead,
TagKind::PropertyWrite,
TagKind::Mixin,
TagKind::Extends,
TagKind::Implements,
TagKind::Use,
TagKind::TemplateExtends,
TagKind::TemplateImplements,
TagKind::PhpstanReturn,
TagKind::PhpstanParam,
TagKind::PhpstanVar,
TagKind::PhpstanRequireExtends,
TagKind::PhpstanRequireImplements,
TagKind::PsalmReturn,
TagKind::PsalmParam,
TagKind::PsalmVar,
TagKind::PhpstanAssert,
TagKind::PhpstanAssertIfTrue,
TagKind::PhpstanAssertIfFalse,
TagKind::PsalmAssert,
TagKind::PsalmAssertIfTrue,
TagKind::PsalmAssertIfFalse,
];
/// Tag names (for `TagKind::Other`) whose description starts with a type.
///
/// Note: `@psalm-return`, `@psalm-param`, and `@psalm-var` are no longer
/// listed here because `mago-docblock` now maps them to dedicated
/// `TagKind::PsalmReturn` / `PsalmParam` / `PsalmVar` variants (handled
/// in `TYPE_FIRST_KINDS` above).
const TYPE_FIRST_OTHER_NAMES: &[&str] = &["phpstan-sealed"];
use crate::docblock::templates::{TEMPLATE_KINDS, variance_for};
/// Determine the template variance for a tag, if it is a template tag.
fn template_variance_for_tag(tag: &TagKind) -> Option<TemplateVariance> {
if TEMPLATE_KINDS.contains(tag) {
Some(variance_for(*tag))
} else {
None
}
}
/// Returns `true` when the tag's description starts with a type expression.
fn is_type_first_tag(kind: &TagKind, name: &str) -> bool {
TYPE_FIRST_KINDS.contains(kind)
|| (*kind == TagKind::Other && TYPE_FIRST_OTHER_NAMES.contains(&name))
}
// ─── Docblock tag scanning ──────────────────────────────────────────────────
/// Scan a docblock for type references in supported tags and emit
/// `SymbolSpan` entries with file-level byte offsets.
///
/// Returns a list of `@template` parameter definitions found in the
/// docblock, each as `(name, byte_offset, optional_bound, variance)`.
pub(super) fn extract_docblock_symbols(
docblock: &str,
base_offset: u32,
spans: &mut Vec<SymbolSpan>,
) -> Vec<(String, u32, Option<PhpType>, TemplateVariance)> {
// ── Inline `{@see ...}` references ──────────────────────────────
// These appear in free-text, not as top-level tags, so we scan the
// raw docblock text for them.
extract_inline_see_symbols(docblock, base_offset, spans);
// ── Parse structured tags ───────────────────────────────────────
let base_span = Span::new(
FileId::zero(),
Position::new(base_offset),
Position::new(base_offset + docblock.len() as u32),
);
let Some(info) = parse_docblock(docblock, base_span) else {
return Vec::new();
};
let mut template_params: Vec<(String, u32, Option<PhpType>, TemplateVariance)> = Vec::new();
for tag in &info.tags {
let desc_file_offset = tag.description_span.start.offset;
let desc_start_in_docblock = (desc_file_offset - base_offset) as usize;
// ── @see ────────────────────────────────────────────────────
if tag.kind == TagKind::See {
extract_see_tag_symbol(tag, spans);
continue;
}
// ── @method ─────────────────────────────────────────────────
if tag.kind == TagKind::Method || tag.kind == TagKind::PsalmMethod {
extract_method_tag_symbols(docblock, desc_start_in_docblock, base_offset, spans);
continue;
}
// ── @property variants ───────────────────────────────────────
if matches!(
tag.kind,
TagKind::Property
| TagKind::PropertyRead
| TagKind::PropertyWrite
| TagKind::PsalmProperty
| TagKind::PsalmPropertyRead
| TagKind::PsalmPropertyWrite
) {
extract_property_tag_symbols(docblock, desc_start_in_docblock, base_offset, spans);
continue;
}
// ── @template variants ──────────────────────────────────────
if let Some(variance) = template_variance_for_tag(&tag.kind) {
if let Some((name, offset, bound)) =
extract_template_tag_symbols(docblock, desc_start_in_docblock, base_offset, spans)
{
template_params.push((name, offset, bound, variance));
}
continue;
}
// ── Type-first tags ─────────────────────────────────────────
if is_type_first_tag(&tag.kind, &tag.name) {
emit_type_first_tag(docblock, desc_start_in_docblock, base_offset, spans);
}
}
template_params
}
/// Emit type spans for a tag whose description starts with a type
/// expression (e.g. `@param string $name`, `@return Collection<int>`).
///
/// Uses [`join_multiline_type`] to handle types that span continuation
/// lines and [`emit_type_spans`] to produce navigable symbol spans.
fn emit_type_first_tag(
docblock: &str,
desc_start_in_docblock: usize,
base_offset: u32,
spans: &mut Vec<SymbolSpan>,
) {
if desc_start_in_docblock >= docblock.len() {
return;
}
// The description may start with whitespace (e.g. double-space after
// the tag name: `@param Type`). Trim it and adjust the offset so
// that `join_multiline_type` begins at the first non-whitespace byte
// on the same line.
let raw = &docblock[desc_start_in_docblock..];
let first_nl = raw.find('\n').unwrap_or(raw.len());
let first_line = &raw[..first_nl];
let trimmed = first_line.trim_start();
if trimmed.is_empty() {
return;
}
let leading_ws = first_line.len() - trimmed.len();
let adjusted_start = desc_start_in_docblock + leading_ws;
let (joined, offset_map) = join_multiline_type(docblock, adjusted_start);
let (type_token, _remainder) = split_type_token(&joined);
if !type_token.is_empty() {
let mut local_spans: Vec<SymbolSpan> = Vec::new();
emit_type_spans(type_token, 0, &mut local_spans);
for mut sp in local_spans {
sp.start = base_offset
+ offset_map
.get(sp.start as usize)
.copied()
.unwrap_or(sp.start as usize) as u32;
sp.end = base_offset
+ offset_map
.get(sp.end as usize)
.copied()
.unwrap_or(sp.end as usize) as u32;
spans.push(sp);
}
}
}
/// Scan a docblock for `@param $varName` tokens and return
/// `(name_without_dollar, file_byte_offset_of_dollar)` pairs.
///
/// These are used by the symbol-map extraction to emit
/// [`SymbolKind::Variable`] spans so that rename and find-references
/// cover parameter names mentioned in docblocks.
pub(super) fn extract_param_var_spans(docblock: &str, base_offset: u32) -> Vec<(String, u32)> {
let base_span = Span::new(
FileId::zero(),
Position::new(base_offset),
Position::new(base_offset + docblock.len() as u32),
);
let Some(info) = parse_docblock(docblock, base_span) else {
return Vec::new();
};
let mut results = Vec::new();
for tag in &info.tags {
let is_param = matches!(
tag.kind,
TagKind::Param | TagKind::PhpstanParam | TagKind::PsalmParam
);
if !is_param {
continue;
}
// The description is `TypeHint $varName desc` or just `$varName`.
// Find the `$` in the raw source covered by description_span so
// the file offset is accurate.
let desc_file_start = tag.description_span.start.offset;
let desc_in_doc_start = (desc_file_start - base_offset) as usize;
let desc_in_doc_end =
((tag.description_span.end.offset - base_offset) as usize).min(docblock.len());
let raw_desc = &docblock[desc_in_doc_start..desc_in_doc_end];
if let Some(dollar_pos) = raw_desc.find('$') {
let rest = &raw_desc[dollar_pos..];
let name_end = rest[1..]
.find(|c: char| !c.is_alphanumeric() && c != '_')
.map(|i| i + 1)
.unwrap_or(rest.len());
if name_end > 1 {
let name = rest[1..name_end].to_string();
let file_offset = desc_file_start + dollar_pos as u32;
results.push((name, file_offset));
}
}
}
results
}
/// Scan a docblock for `@var Type $varName` tokens and return
/// `(name_without_dollar, file_byte_offset_of_dollar)` pairs.
///
/// These are used by the symbol-map extraction to emit
/// [`VarDefSite`](super::VarDefSite) entries for inline `@var`
/// docblocks so the forward walker treats them as variable definitions.
pub(super) fn extract_var_docblock_var_spans(
docblock: &str,
base_offset: u32,
) -> Vec<(String, u32)> {
let base_span = Span::new(
FileId::zero(),
Position::new(base_offset),
Position::new(base_offset + docblock.len() as u32),
);
let Some(info) = parse_docblock(docblock, base_span) else {
return Vec::new();
};
let mut results = Vec::new();
for tag in &info.tags {
let is_var = matches!(
tag.kind,
TagKind::Var | TagKind::PhpstanVar | TagKind::PsalmVar
);
if !is_var {
continue;
}
// The description is `TypeHint $varName desc` or just `$varName`.
// Find the `$` in the raw source covered by description_span so
// the file offset is accurate.
let desc_file_start = tag.description_span.start.offset;
let desc_in_doc_start = (desc_file_start - base_offset) as usize;
let desc_in_doc_end =
((tag.description_span.end.offset - base_offset) as usize).min(docblock.len());
let raw_desc = &docblock[desc_in_doc_start..desc_in_doc_end];
if let Some(dollar_pos) = raw_desc.find('$') {
let rest = &raw_desc[dollar_pos..];
let name_end = rest[1..]
.find(|c: char| !c.is_alphanumeric() && c != '_')
.map(|i| i + 1)
.unwrap_or(rest.len());
if name_end > 1 {
let name = rest[1..name_end].to_string();
let file_offset = desc_file_start + dollar_pos as u32;
results.push((name, file_offset));
}
}
}
results
}
// ─── Type span emission ─────────────────────────────────────────────────────
/// Emit `SymbolSpan` entries for a type token, splitting unions and
/// intersections and skipping scalars.
/// Build a contiguous type string from a potentially multiline docblock
/// region, starting at `start_in_docblock` (byte offset within the
/// docblock text).
///
/// Returns `(joined_text, offset_map)` where `offset_map[i]` is the byte
/// offset in the original `docblock` that corresponds to byte `i` in
/// `joined_text`. Continuation-line prefixes (`* `) are stripped so that
/// `split_type_token` / `emit_type_spans` see a clean type string.
fn join_multiline_type(docblock: &str, start_in_docblock: usize) -> (String, Vec<usize>) {
let mut joined = String::new();
// offset_map[i] = byte offset in `docblock` for byte `i` in `joined`.
// We only add the one-past-end sentinel at the very end so that
// continuation chunks don't shift indices.
let mut offset_map: Vec<usize> = Vec::new();
let first_line_rest = &docblock[start_in_docblock..];
// Take text up to (but not including) the newline on the first line.
let first_nl = first_line_rest.find('\n').unwrap_or(first_line_rest.len());
let first_chunk = &first_line_rest[..first_nl];
for (i, _) in first_chunk.char_indices() {
offset_map.push(start_in_docblock + i);
}
joined.push_str(first_chunk);
// Check whether the first chunk has unclosed `<`, `(`, or `{`.
if !crate::util::has_unclosed_delimiters(&joined) {
// Push one-past-end sentinel.
offset_map.push(start_in_docblock + first_chunk.len());
return (joined, offset_map);
}
// Consume continuation lines.
let mut pos = start_in_docblock + first_nl;
while pos < docblock.len() {
// Skip the `\n`.
if docblock.as_bytes().get(pos) == Some(&b'\n') {
pos += 1;
}
if pos >= docblock.len() {
break;
}
let line_end = docblock[pos..]
.find('\n')
.map_or(docblock.len(), |p| pos + p);
let raw_line = &docblock[pos..line_end];
// Strip the leading `* ` (with optional whitespace before `*`).
let stripped = raw_line.trim_start();
if stripped.starts_with("*/") {
// End of docblock.
break;
}
let content_after_star = if let Some(rest) = stripped.strip_prefix('*') {
// Skip one optional space after `*`.
rest.strip_prefix(' ').unwrap_or(rest)
} else {
stripped
};
// If the continuation line starts with `@`, it's a new tag — stop.
if content_after_star.trim_start().starts_with('@') {
break;
}
let content_start_in_docblock = pos + (raw_line.len() - content_after_star.len());
// Append a space to represent the line break in the joined string,
// mapped to the newline position.
offset_map.push(pos.saturating_sub(1));
joined.push(' ');
for (i, _) in content_after_star.char_indices() {
offset_map.push(content_start_in_docblock + i);
}
joined.push_str(content_after_star);
pos = line_end;
if !crate::util::has_unclosed_delimiters(&joined) {
break;
}
}
// One-past-end sentinel so that `sp.end` lookups work.
let last_mapped = offset_map.last().copied().unwrap_or(start_in_docblock);
offset_map.push(last_mapped + 1);
(joined, offset_map)
}
pub(super) fn emit_type_spans(
type_token: &str,
token_file_offset: u32,
spans: &mut Vec<SymbolSpan>,
) {
if type_token.is_empty() {
return;
}
// ── Strip PHPStan variance annotations ──────────────────────────
// Generic type arguments may carry a variance prefix, e.g.
// `Collection<int, covariant array{customer: Customer}>`.
// `mago-type-syntax` does not recognise these, so we strip them
// before parsing and build an offset map so that spans emitted
// from the cleaned string can be translated back to the original.
let (cleaned, variance_offset_map) = strip_variance_annotations(type_token);
// ── Replace PHPStan `*` wildcards in generic positions ──────────
// PHPStan supports `*` as a bivariant wildcard in generic args,
// e.g. `Relation<TRelatedModel, *, *>`. `mago-type-syntax` does
// not recognise this. Replace with `mixed` and build an offset
// map that accounts for the 1→5 character expansion.
let (effective_cleaned, wildcard_offset_map) = replace_star_wildcards_with_offset_map(&cleaned);
let effective_token: &str = &effective_cleaned;
// Parse the type string using mago-type-syntax. The span we
// provide starts at 0 so that all AST node offsets are relative
// to `effective_token`.
let parse_span = Span::new(
FileId::zero(),
Position::new(0),
Position::new(effective_token.len() as u32),
);
let arena = Bump::new();
let effective_token = arena.alloc_slice_copy(effective_token.as_bytes());
match mago_type_syntax::parse_str(&arena, parse_span, effective_token) {
Ok(ty) => {
let mut local_spans: Vec<SymbolSpan> = Vec::new();
emit_type_spans_from_ast(&ty, 0, &mut local_spans);
// Map cleaned-string offsets back to original-string
// offsets, then shift by token_file_offset.
//
// Two offset maps may be active:
// 1. wildcard_offset_map: effective_token → cleaned (after
// variance stripping but before wildcard replacement)
// 2. variance_offset_map: cleaned → original type_token
for mut sp in local_spans {
if let Some(ref map) = wildcard_offset_map {
sp.start = map
.get(sp.start as usize)
.copied()
.unwrap_or(sp.start as usize) as u32;
sp.end = map.get(sp.end as usize).copied().unwrap_or(sp.end as usize) as u32;
}
if let Some(ref map) = variance_offset_map {
sp.start = map
.get(sp.start as usize)
.copied()
.unwrap_or(sp.start as usize) as u32;
sp.end = map.get(sp.end as usize).copied().unwrap_or(sp.end as usize) as u32;
}
sp.start += token_file_offset;
sp.end += token_file_offset;
spans.push(sp);
}
}
Err(_) => {
// Parse failed — fall back to emitting a single span for
// the whole token if it looks like a navigable class name.
let trimmed = type_token.trim();
let base = strip_fqn_prefix(trimmed)
.split('<')
.next()
.unwrap_or(trimmed);
if is_navigable_type(base) {
let is_fqn = trimmed.starts_with('\\');
let name = strip_fqn_prefix(trimmed).to_string();
spans.push(SymbolSpan {
start: token_file_offset,
end: token_file_offset + trimmed.len() as u32,
kind: SymbolKind::ClassReference {
name,
is_fqn,
context: ClassRefContext::Other,
},
});
}
}
}
}
/// Strip `covariant ` and `contravariant ` prefixes from generic type
/// arguments so that `mago-type-syntax` can parse the type.
///
/// Returns `(cleaned_string, offset_map)`. When no variance annotations
/// are found, `offset_map` is `None` and `cleaned_string` is the original
/// input (no allocation). When annotations *are* stripped,
/// `offset_map[i]` gives the byte offset in the original string that
/// corresponds to byte `i` in the cleaned string, plus a one-past-end
/// sentinel.
/// Replace PHPStan `*` wildcards in generic type argument positions with
/// `mixed`, returning the cleaned string and an offset map.
///
/// The offset map translates positions in the cleaned string back to
/// positions in the input string. When `*` (1 byte) is replaced with
/// `mixed` (5 bytes), all 5 positions in the output map back to the
/// single `*` position in the input.
///
/// Returns `(cleaned, None)` when no wildcards are found (no allocation
/// for the offset map).
fn replace_star_wildcards_with_offset_map(s: &str) -> (String, Option<Vec<usize>>) {
use crate::php_type::is_generic_wildcard;
if !s.contains('*') {
return (s.to_owned(), None);
}
let bytes = s.as_bytes();
let has_generic_wildcard =
(0..bytes.len()).any(|i| bytes[i] == b'*' && is_generic_wildcard(bytes, i));
if !has_generic_wildcard {
return (s.to_owned(), None);
}
let mut cleaned = String::with_capacity(s.len() + 16);
let mut offset_map: Vec<usize> = Vec::with_capacity(s.len() + 32);
let mut i = 0usize;
while i < bytes.len() {
if bytes[i] == b'*' && is_generic_wildcard(bytes, i) {
// Replace `*` with `mixed` — all 5 output positions map
// back to the original `*` position.
for _ in 0.."mixed".len() {
offset_map.push(i);
}
cleaned.push_str("mixed");
i += 1;
} else {
offset_map.push(i);
cleaned.push(bytes[i] as char);
i += 1;
}
}
// One-past-end sentinel.
offset_map.push(i);
(cleaned, Some(offset_map))
}
fn strip_variance_annotations(s: &str) -> (String, Option<Vec<usize>>) {
// Fast path: no variance annotations at all.
if !s.contains("covariant ") && !s.contains("contravariant ") {
return (s.to_owned(), None);
}
let mut cleaned = String::with_capacity(s.len());
let mut offset_map: Vec<usize> = Vec::with_capacity(s.len() + 1);
let bytes = s.as_bytes();
let mut i = 0usize;
while i < bytes.len() {
// Only strip variance keywords that appear after `<` or `,`
// at some nesting depth (i.e. inside generic parameters).
// We look for the pattern and check whether the preceding
// non-whitespace character is `<` or `,`.
let try_strip = |prefix: &str, pos: usize, src: &[u8]| -> bool {
if pos + prefix.len() > src.len() {
return false;
}
if &src[pos..pos + prefix.len()] != prefix.as_bytes() {
return false;
}
// Check that the preceding non-whitespace is `<` or `,`.
let mut j = pos;
while j > 0 {
j -= 1;
if !src[j].is_ascii_whitespace() {
return src[j] == b'<' || src[j] == b',';
}
}
false
};
if try_strip("covariant ", i, bytes) {
i += "covariant ".len();
} else if try_strip("contravariant ", i, bytes) {
i += "contravariant ".len();
} else {
offset_map.push(i);
cleaned.push(bytes[i] as char);
i += 1;
}
}
// One-past-end sentinel.
offset_map.push(i);
(cleaned, Some(offset_map))
}
/// Walk a `mago_type_syntax` AST node and emit [`SymbolSpan`] entries
/// for every navigable type reference (class names, `self`, `static`,
/// `parent`, `$this`).
///
/// `base_offset` is added to every AST-local offset to produce
/// file-level byte positions.
fn emit_type_spans_from_ast(
ty: &type_ast::Type<'_>,
base_offset: u32,
spans: &mut Vec<SymbolSpan>,
) {
use crate::atom::bytes_to_str;
match ty {
// ── Composite types ─────────────────────────────────────────
type_ast::Type::Union(u) => {
emit_type_spans_from_ast(u.left, base_offset, spans);
emit_type_spans_from_ast(u.right, base_offset, spans);
}
type_ast::Type::Intersection(i) => {
emit_type_spans_from_ast(i.left, base_offset, spans);
emit_type_spans_from_ast(i.right, base_offset, spans);
}
type_ast::Type::Nullable(n) => {
emit_type_spans_from_ast(n.inner, base_offset, spans);
}
type_ast::Type::Parenthesized(p) => {
emit_type_spans_from_ast(p.inner, base_offset, spans);
}
// ── Named / Reference types ─────────────────────────────────
type_ast::Type::Reference(r) => {
let name = bytes_to_str(r.identifier.value);
let id_start = base_offset + r.identifier.span.start.offset;
let id_end = base_offset + r.identifier.span.end.offset;
// Emit a span for the identifier itself.
emit_identifier_span(name, id_start, id_end, spans);
// Recurse into generic parameters if present.
if let Some(params) = &r.parameters {
emit_generic_params(params, base_offset, spans);
}
}
// ── Array-like types with optional generic parameters ───────
type_ast::Type::Array(a) => {
if let Some(params) = &a.parameters {
emit_generic_params(params, base_offset, spans);
}
}
type_ast::Type::NonEmptyArray(a) => {
if let Some(params) = &a.parameters {
emit_generic_params(params, base_offset, spans);
}
}
type_ast::Type::AssociativeArray(a) => {
if let Some(params) = &a.parameters {
emit_generic_params(params, base_offset, spans);
}
}
type_ast::Type::List(l) => {
if let Some(params) = &l.parameters {
emit_generic_params(params, base_offset, spans);
}
}
type_ast::Type::NonEmptyList(l) => {
if let Some(params) = &l.parameters {
emit_generic_params(params, base_offset, spans);
}
}
type_ast::Type::Iterable(i) => {
if let Some(params) = &i.parameters {
emit_generic_params(params, base_offset, spans);
}
}
// ── Slice: T[] ──────────────────────────────────────────────
type_ast::Type::Slice(s) => {
emit_type_spans_from_ast(s.inner, base_offset, spans);
}
// ── Shape types ─────────────────────────────────────────────
type_ast::Type::Shape(s) => {
for field in &s.fields {
emit_type_spans_from_ast(field.value, base_offset, spans);
}
}
// ── Object type (with optional shape) ───────────────────────
type_ast::Type::Object(o) => {
if let Some(props) = &o.properties {
for field in &props.fields {
emit_type_spans_from_ast(field.value, base_offset, spans);
}
}
}
// ── Callable types ──────────────────────────────────────────
type_ast::Type::Callable(c) => {
// Emit span for the callable keyword if it's navigable
// (e.g. `Closure` is a class, `callable` is not).
let kw_name = bytes_to_str(c.keyword.value);
let kw_start = base_offset + c.keyword.span.start.offset;
let kw_end = base_offset + c.keyword.span.end.offset;
emit_identifier_span(kw_name, kw_start, kw_end, spans);
// Recurse into parameter types and return type.
if let Some(spec) = &c.specification {
for param in &spec.parameters.entries {
if let Some(param_type) = ¶m.parameter_type {
emit_type_spans_from_ast(param_type, base_offset, spans);
}
}
if let Some(ret) = &spec.return_type {
emit_type_spans_from_ast(ret.return_type, base_offset, spans);
}
}
}
// ── Conditional types ───────────────────────────────────────
type_ast::Type::Conditional(c) => {
// The subject is a variable ($param) — skip it.
// Recurse into the condition, then, and otherwise types.
emit_type_spans_from_ast(c.target, base_offset, spans);
emit_type_spans_from_ast(c.then, base_offset, spans);
emit_type_spans_from_ast(c.otherwise, base_offset, spans);
}
// ── class-string / interface-string / enum-string / trait-string ─
type_ast::Type::ClassString(c) => {
if let Some(param) = &c.parameter {
emit_type_spans_from_ast(¶m.entry.inner, base_offset, spans);
}
}
type_ast::Type::InterfaceString(i) => {
if let Some(param) = &i.parameter {
emit_type_spans_from_ast(¶m.entry.inner, base_offset, spans);
}
}
type_ast::Type::EnumString(e) => {
if let Some(param) = &e.parameter {
emit_type_spans_from_ast(¶m.entry.inner, base_offset, spans);
}
}
type_ast::Type::TraitString(t) => {
if let Some(param) = &t.parameter {
emit_type_spans_from_ast(¶m.entry.inner, base_offset, spans);
}
}
// ── key-of / value-of ───────────────────────────────────────
type_ast::Type::KeyOf(k) => {
emit_type_spans_from_ast(&k.parameter.entry.inner, base_offset, spans);
}
type_ast::Type::ValueOf(v) => {
emit_type_spans_from_ast(&v.parameter.entry.inner, base_offset, spans);
}
// ── Index access: T[K] ─────────────────────────────────────
type_ast::Type::IndexAccess(i) => {
emit_type_spans_from_ast(i.target, base_offset, spans);
emit_type_spans_from_ast(i.index, base_offset, spans);
}
// ── int-mask / int-mask-of ──────────────────────────────────
type_ast::Type::IntMask(m) => {
for entry in &m.parameters.entries {
emit_type_spans_from_ast(&entry.inner, base_offset, spans);
}
}
type_ast::Type::IntMaskOf(m) => {
emit_type_spans_from_ast(&m.parameter.entry.inner, base_offset, spans);
}
// ── properties-of ───────────────────────────────────────────
type_ast::Type::PropertiesOf(p) => {
emit_type_spans_from_ast(&p.parameter.entry.inner, base_offset, spans);
}
// ── Negated / Posited literals ──────────────────────────────
type_ast::Type::Negated(_) | type_ast::Type::Posited(_) => {
// Numeric literals — not navigable.
}
// ── Variable ($this) ────────────────────────────────────────
type_ast::Type::Variable(v) if v.value == b"$this" => {
let start = base_offset + v.span.start.offset;
let end = base_offset + v.span.end.offset;
spans.push(SymbolSpan {
start,
end,
kind: SymbolKind::SelfStaticParent(SelfStaticParentKind::This),
});
}
// Other variables (parameter names leaked from @param) are skipped.
type_ast::Type::Variable(_) => {}
// ── Member / Alias references ───────────────────────────────
type_ast::Type::MemberReference(_) | type_ast::Type::AliasReference(_) => {
// These are rare PHPStan types — not navigable in our system.
}
// ── Keyword types (int, string, bool, void, etc.) ───────────
// All keyword types are non-navigable *except* `static`, `self`,
// and `parent` which should produce SelfStaticParent spans.
type_ast::Type::Mixed(k)
| type_ast::Type::NonEmptyMixed(k)
| type_ast::Type::Null(k)
| type_ast::Type::Void(k)
| type_ast::Type::Never(k)
| type_ast::Type::Resource(k)
| type_ast::Type::ClosedResource(k)
| type_ast::Type::OpenResource(k)
| type_ast::Type::True(k)
| type_ast::Type::False(k)
| type_ast::Type::Bool(k)
| type_ast::Type::Float(k)
| type_ast::Type::Int(k)
| type_ast::Type::PositiveInt(k)
| type_ast::Type::NegativeInt(k)
| type_ast::Type::NonPositiveInt(k)
| type_ast::Type::NonNegativeInt(k)
| type_ast::Type::String(k)
| type_ast::Type::StringableObject(k)
| type_ast::Type::ArrayKey(k)
| type_ast::Type::Numeric(k)
| type_ast::Type::Scalar(k)
| type_ast::Type::NumericString(k)
| type_ast::Type::NonEmptyString(k)
| type_ast::Type::NonEmptyLowercaseString(k)
| type_ast::Type::LowercaseString(k)
| type_ast::Type::NonEmptyUppercaseString(k)
| type_ast::Type::UppercaseString(k)
| type_ast::Type::TruthyString(k)
| type_ast::Type::NonFalsyString(k)
| type_ast::Type::UnspecifiedLiteralInt(k)
| type_ast::Type::UnspecifiedLiteralString(k)
| type_ast::Type::UnspecifiedLiteralFloat(k)
| type_ast::Type::NonEmptyUnspecifiedLiteralString(k) => {
// `static`, `self`, and `parent` are parsed as keywords by
// mago but should still produce SelfStaticParent spans.
let name = bytes_to_str(k.value);
if name == "static" || name == "self" || name == "parent" {
let start = base_offset + k.span.start.offset;
let end = base_offset + k.span.end.offset;
let ssp_kind = match name {
"self" => SelfStaticParentKind::Self_,
"static" => SelfStaticParentKind::Static,
"parent" => SelfStaticParentKind::Parent,
_ => unreachable!(),
};
spans.push(SymbolSpan {
start,
end,
kind: SymbolKind::SelfStaticParent(ssp_kind),
});
}
// All other keywords (int, string, void, etc.) are non-navigable.
}
// ── Literal types ───────────────────────────────────────────
type_ast::Type::LiteralInt(_)
| type_ast::Type::LiteralFloat(_)
| type_ast::Type::LiteralString(_) => {
// Literals are not navigable.
}
// ── int range ───────────────────────────────────────────────
type_ast::Type::IntRange(_) => {
// int<min, max> — not navigable.
}
// ── Catch-all (non_exhaustive) ──────────────────────────────
_ => {}