mir_analyzer/parser/docblock/mod.rs
1use mir_types::{ArrayKey, Atomic, Type, Variance};
2/// Docblock parser — delegates to `phpdoc_parser` for tag extraction,
3/// then converts tags into mir's `ParsedDocblock` with resolved types.
4use std::sync::Arc;
5
6use indexmap::IndexMap;
7use phpdoc_parser::{body_text, parse as parse_phpdoc};
8
9// ---------------------------------------------------------------------------
10// DocblockParser
11// ---------------------------------------------------------------------------
12
13pub struct DocblockParser;
14
15impl DocblockParser {
16 pub fn parse(text: &str) -> ParsedDocblock {
17 let doc = parse_phpdoc(text);
18 let mut result = ParsedDocblock {
19 description: extract_description(text),
20 ..Default::default()
21 };
22
23 for tag in &doc.tags {
24 match tag.name.as_str() {
25 "param-out" | "psalm-param-out" | "phpstan-param-out" => {
26 if let Some(body_str) = body_text(&tag.body) {
27 if let Some((ty_s, name)) = parse_param_line(&body_str) {
28 record_backslash_keyword_types(
29 &mut result,
30 "param-out",
31 &ty_s,
32 tag.span.start,
33 text,
34 );
35 if let Some(msg) = validate_type_str(&ty_s, "param-out") {
36 result.invalid_annotations.push(msg);
37 } else {
38 result.out_params.push((
39 name.trim_start_matches('$').to_string(),
40 parse_type_string(&ty_s),
41 ));
42 }
43 }
44 }
45 }
46 "param" | "psalm-param" | "phpstan-param" | "phan-param" => {
47 if let Some(body_str) = body_text(&tag.body) {
48 if let Some((ty_s, name)) = parse_param_line(&body_str) {
49 record_backslash_keyword_types(
50 &mut result,
51 "param",
52 &ty_s,
53 tag.span.start,
54 text,
55 );
56 // Check if the parsed type is valid
57 if is_inside_generics(&ty_s) {
58 // For unclosed generics, report the full body for context
59 if let Some(msg) = validate_type_str(&body_str, "param") {
60 result.invalid_annotations.push(msg);
61 }
62 } else if let Some(msg) = validate_type_str(&ty_s, "param") {
63 // For other errors, report the parsed type
64 result.invalid_annotations.push(msg);
65 } else {
66 result
67 .param_type_strings
68 .push((name.trim_start_matches('$').to_string(), ty_s.clone()));
69 result.params.push((
70 name.trim_start_matches('$').to_string(),
71 parse_type_string(&ty_s),
72 ));
73 }
74 } else if let Some(msg) = validate_type_str(&body_str, "param") {
75 // If parsing failed, validate the full body to provide better error context
76 result.invalid_annotations.push(msg);
77 record_backslash_keyword_types(
78 &mut result,
79 "param",
80 &body_str,
81 tag.span.start,
82 text,
83 );
84 }
85 }
86 }
87 "return" | "psalm-return" | "phpstan-return" => {
88 if let Some(body_str) = body_text(&tag.body) {
89 let ty_s = extract_return_type(&body_str);
90 record_backslash_keyword_types(
91 &mut result,
92 "return",
93 &ty_s,
94 tag.span.start,
95 text,
96 );
97 if let Some(msg) = validate_type_str(&ty_s, "return") {
98 result.invalid_annotations.push(msg);
99 }
100 result.return_type = Some(parse_type_string(&ty_s));
101 }
102 }
103 "var" | "psalm-var" | "phpstan-var" => {
104 if let Some(body_str) = body_text(&tag.body) {
105 if let Some((ty_s, name)) = parse_var_line(&body_str) {
106 record_backslash_keyword_types(
107 &mut result,
108 "var",
109 &ty_s,
110 tag.span.start,
111 text,
112 );
113 if let Some(msg) = validate_type_str(&ty_s, "var") {
114 result.invalid_annotations.push(msg);
115 }
116 result.var_type = Some(parse_type_string(&ty_s));
117 result.var_name = Some(name.trim_start_matches('$').to_string());
118 } else {
119 // Spaces inside PHP types only appear within <…> generics.
120 // Stop at top-level whitespace to exclude description text that
121 // follows the type in multi-line @var bodies.
122 let ty_s = extract_type_prefix(body_str.trim());
123 record_backslash_keyword_types(
124 &mut result,
125 "var",
126 ty_s,
127 tag.span.start,
128 text,
129 );
130 if let Some(msg) = validate_type_str(ty_s, "var") {
131 result.invalid_annotations.push(msg);
132 }
133 result.var_type = Some(parse_type_string(ty_s));
134 }
135 }
136 }
137 "throws" => {
138 if let Some(body_str) = body_text(&tag.body) {
139 let first_word = body_str.split_whitespace().next().unwrap_or("");
140 for class in first_word.split('|') {
141 if !class.is_empty() {
142 record_backslash_keyword_types(
143 &mut result,
144 "throws",
145 class,
146 tag.span.start,
147 text,
148 );
149 result.throws.push(class.to_string());
150 }
151 }
152 }
153 }
154 "deprecated" => {
155 result.is_deprecated = true;
156 result.deprecated = Some(body_text(&tag.body).unwrap_or_default().to_string());
157 }
158 "template" | "psalm-template" | "phpstan-template" => {
159 if let Some((name, bound, default)) =
160 parse_template_line(tag.name.as_str(), body_text(&tag.body))
161 {
162 if let Some(msg) = validate_type_str(&name, "template") {
163 result.invalid_annotations.push(msg);
164 }
165 if let Some(b) = &bound {
166 record_backslash_keyword_types(
167 &mut result,
168 "template",
169 b,
170 tag.span.start,
171 text,
172 );
173 if let Some(msg) = validate_type_str(b, "template") {
174 result.invalid_annotations.push(msg);
175 }
176 }
177 result.templates.push((
178 name,
179 bound.map(|b| parse_type_string(&b)),
180 Variance::Invariant,
181 default.map(|d| parse_type_string(&d)),
182 ));
183 }
184 }
185 "template-covariant"
186 | "psalm-template-covariant"
187 | "phpstan-template-covariant" => {
188 if let Some((name, bound, default)) =
189 parse_template_line(tag.name.as_str(), body_text(&tag.body))
190 {
191 if let Some(msg) = validate_type_str(&name, "template-covariant") {
192 result.invalid_annotations.push(msg);
193 }
194 if let Some(b) = &bound {
195 record_backslash_keyword_types(
196 &mut result,
197 "template-covariant",
198 b,
199 tag.span.start,
200 text,
201 );
202 if let Some(msg) = validate_type_str(b, "template-covariant") {
203 result.invalid_annotations.push(msg);
204 }
205 }
206 result.templates.push((
207 name,
208 bound.map(|b| parse_type_string(&b)),
209 Variance::Covariant,
210 default.map(|d| parse_type_string(&d)),
211 ));
212 }
213 }
214 "template-contravariant"
215 | "psalm-template-contravariant"
216 | "phpstan-template-contravariant" => {
217 if let Some((name, bound, default)) =
218 parse_template_line(tag.name.as_str(), body_text(&tag.body))
219 {
220 if let Some(msg) = validate_type_str(&name, "template-contravariant") {
221 result.invalid_annotations.push(msg);
222 }
223 if let Some(b) = &bound {
224 record_backslash_keyword_types(
225 &mut result,
226 "template-contravariant",
227 b,
228 tag.span.start,
229 text,
230 );
231 if let Some(msg) = validate_type_str(b, "template-contravariant") {
232 result.invalid_annotations.push(msg);
233 }
234 }
235 result.templates.push((
236 name,
237 bound.map(|b| parse_type_string(&b)),
238 Variance::Contravariant,
239 default.map(|d| parse_type_string(&d)),
240 ));
241 }
242 }
243 "extends" | "template-extends" | "psalm-extends" | "phpstan-extends" => {
244 if let Some(body_str) = body_text(&tag.body) {
245 let trimmed = body_str.trim();
246 record_backslash_keyword_types(
247 &mut result,
248 "extends",
249 trimmed,
250 tag.span.start,
251 text,
252 );
253 if let Some(msg) = validate_type_str(trimmed, "extends") {
254 result.invalid_annotations.push(msg);
255 }
256 result.extends.push(parse_type_string(trimmed));
257 }
258 }
259 "implements"
260 | "template-implements"
261 | "psalm-implements"
262 | "phpstan-implements" => {
263 if let Some(body_str) = body_text(&tag.body) {
264 let trimmed = body_str.trim();
265 record_backslash_keyword_types(
266 &mut result,
267 "implements",
268 trimmed,
269 tag.span.start,
270 text,
271 );
272 if let Some(msg) = validate_type_str(trimmed, "implements") {
273 result.invalid_annotations.push(msg);
274 }
275 result.implements.push(parse_type_string(trimmed));
276 }
277 }
278 "use" | "template-use" | "psalm-use" | "phpstan-use" => {
279 if let Some(body_str) = body_text(&tag.body) {
280 let trimmed = body_str.trim();
281 record_backslash_keyword_types(
282 &mut result,
283 "use",
284 trimmed,
285 tag.span.start,
286 text,
287 );
288 if let Some(msg) = validate_type_str(trimmed, "use") {
289 result.invalid_annotations.push(msg);
290 }
291 result.uses.push(parse_type_string(trimmed));
292 }
293 }
294 "assert" | "psalm-assert" | "phpstan-assert" => {
295 if let Some(body_str) = body_text(&tag.body) {
296 if let Some((ty_str, name)) = parse_param_line(&body_str) {
297 let (ty, negated) = parse_assertion_type(&ty_str);
298 let (name, key) = split_array_key_suffix(&name);
299 result.assertions.push((name, key, ty, negated));
300 }
301 }
302 }
303 "if-this-is" | "psalm-if-this-is" | "phpstan-if-this-is" => {
304 if let Some(body_str) = body_text(&tag.body) {
305 let trimmed = body_str.trim();
306 if !trimmed.is_empty() {
307 result.if_this_is = Some(parse_type_string(trimmed));
308 }
309 }
310 }
311 "self-out" | "psalm-self-out" | "phpstan-self-out" | "this-out"
312 | "psalm-this-out" | "phpstan-this-out" => {
313 if let Some(body_str) = body_text(&tag.body) {
314 let trimmed = body_str.trim();
315 if !trimmed.is_empty() {
316 result.self_out = Some(parse_self_out_type(trimmed));
317 }
318 }
319 }
320 "suppress" | "psalm-suppress" => {
321 if let Some(body_str) = body_text(&tag.body) {
322 for rule in body_str.split([',', ' ']) {
323 let rule = rule.trim().to_string();
324 if !rule.is_empty() {
325 result.suppressed_issues.push(rule);
326 }
327 }
328 }
329 }
330 "see" => {
331 if let Some(body_str) = body_text(&tag.body) {
332 result.see.push(body_str.to_string());
333 }
334 }
335 "link" => {
336 if let Some(body_str) = body_text(&tag.body) {
337 result.see.push(body_str.to_string());
338 }
339 }
340 "mixin" => {
341 if let Some(body_str) = body_text(&tag.body) {
342 let base_class =
343 body_str.split('<').next().unwrap_or(&body_str).to_string();
344 result.mixins.push(base_class);
345 }
346 }
347 "property" => {
348 if let Some(body_str) = body_text(&tag.body) {
349 if let Some((ty_str, name)) = parse_param_line(&body_str) {
350 record_backslash_keyword_types(
351 &mut result,
352 "property",
353 &ty_str,
354 tag.span.start,
355 text,
356 );
357 result.properties.push(DocProperty {
358 type_hint: ty_str,
359 name: name.trim_start_matches('$').to_string(),
360 read_only: false,
361 write_only: false,
362 });
363 }
364 }
365 }
366 "property-read" => {
367 if let Some(body_str) = body_text(&tag.body) {
368 if let Some((ty_str, name)) = parse_param_line(&body_str) {
369 record_backslash_keyword_types(
370 &mut result,
371 "property-read",
372 &ty_str,
373 tag.span.start,
374 text,
375 );
376 result.properties.push(DocProperty {
377 type_hint: ty_str,
378 name: name.trim_start_matches('$').to_string(),
379 read_only: true,
380 write_only: false,
381 });
382 }
383 }
384 }
385 "property-write" => {
386 if let Some(body_str) = body_text(&tag.body) {
387 if let Some((ty_str, name)) = parse_param_line(&body_str) {
388 record_backslash_keyword_types(
389 &mut result,
390 "property-write",
391 &ty_str,
392 tag.span.start,
393 text,
394 );
395 result.properties.push(DocProperty {
396 type_hint: ty_str,
397 name: name.trim_start_matches('$').to_string(),
398 read_only: false,
399 write_only: true,
400 });
401 }
402 }
403 }
404 "method" | "psalm-method" => {
405 let body_str = body_text(&tag.body).unwrap_or_default().trim().to_string();
406 if let Some(err) = validate_method_body(&body_str) {
407 result.invalid_annotations.push(err);
408 } else if let Some(m) = parse_method_line(&body_str) {
409 for p in &m.params {
410 record_backslash_keyword_types(
411 &mut result,
412 "method",
413 &p.type_hint,
414 tag.span.start,
415 text,
416 );
417 }
418 record_backslash_keyword_types(
419 &mut result,
420 "method",
421 &m.return_type,
422 tag.span.start,
423 text,
424 );
425 result.methods.push(m);
426 }
427 }
428 "psalm-type" | "phpstan-type" => {
429 if let Some(body_str) = body_text(&tag.body) {
430 // Real Psalm's `@psalm-type Name = Expr` requires the `=`;
431 // real PHPStan's `@phpstan-type Name Expr` doesn't — split
432 // on the first whitespace instead when there's no `=` and
433 // this is the PHPStan spelling. A `phpstan-type` written
434 // WITH `=` (some codebases mix conventions) still works via
435 // the primary split.
436 let split = body_str.split_once('=').or_else(|| {
437 (tag.name == "phpstan-type")
438 .then(|| body_str.split_once(char::is_whitespace))
439 .flatten()
440 });
441 if let Some((name, type_expr)) = split {
442 // Strip a generic alias name's `<T>` suffix
443 // (`ListOf<T> = array<int, T>`) so bare use sites
444 // (`ListOf`) resolve. Substituting T at a
445 // parameterized use site (`ListOf<int>`) isn't
446 // modeled: the template parameter list is
447 // discarded here.
448 let raw_name = name.trim();
449 let name = raw_name
450 .split('<')
451 .next()
452 .unwrap_or(raw_name)
453 .trim()
454 .to_string();
455 result.type_aliases.push(DocTypeAlias {
456 name,
457 type_expr: type_expr.trim().to_string(),
458 });
459 }
460 }
461 }
462 "psalm-import-type" | "phpstan-import-type" => {
463 if let Some(body_str) = body_text(&tag.body) {
464 if let Some(import) = parse_import_type(&body_str) {
465 result.import_types.push(import);
466 }
467 }
468 }
469 "since" if result.since.is_none() => {
470 if let Some(body_str) = body_text(&tag.body) {
471 let v = body_str.split_whitespace().next().unwrap_or("");
472 if !v.is_empty() {
473 result.since = Some(v.to_string());
474 }
475 }
476 }
477 "removed" if result.removed.is_none() => {
478 if let Some(body_str) = body_text(&tag.body) {
479 let v = body_str.split_whitespace().next().unwrap_or("");
480 if !v.is_empty() {
481 result.removed = Some(v.to_string());
482 }
483 }
484 }
485 "internal" | "psalm-internal" => result.is_internal = true,
486 "pure" | "psalm-pure" | "phpstan-pure" => result.is_pure = true,
487 "impure" | "psalm-impure" | "phpstan-impure" => result.is_impure = true,
488 "seal-properties" | "psalm-seal-properties" => result.seal_properties = true,
489 "no-named-arguments" => result.no_named_arguments = true,
490 "mutation-free" | "psalm-mutation-free" | "phpstan-mutation-free" => {
491 result.is_mutation_free = true
492 }
493 "external-mutation-free"
494 | "psalm-external-mutation-free"
495 | "phpstan-external-mutation-free" => result.is_external_mutation_free = true,
496 "immutable" | "psalm-immutable" | "phpstan-immutable" => result.is_immutable = true,
497 "readonly" | "psalm-readonly" | "phpstan-readonly" => result.is_readonly = true,
498 "final" => result.is_final = true,
499 "inheritDoc" | "inheritdoc" => result.is_inherit_doc = true,
500 "api" | "psalm-api" => result.is_api = true,
501 "assert-if-true" | "psalm-assert-if-true" | "phpstan-assert-if-true" => {
502 if let Some(body_str) = body_text(&tag.body) {
503 if let Some((ty_str, name)) = parse_param_line(&body_str) {
504 let (ty, negated) = parse_assertion_type(&ty_str);
505 let (name, key) = split_array_key_suffix(&name);
506 result.assertions_if_true.push((name, key, ty, negated));
507 }
508 }
509 }
510 "assert-if-false" | "psalm-assert-if-false" | "phpstan-assert-if-false" => {
511 if let Some(body_str) = body_text(&tag.body) {
512 if let Some((ty_str, name)) = parse_param_line(&body_str) {
513 let (ty, negated) = parse_assertion_type(&ty_str);
514 let (name, key) = split_array_key_suffix(&name);
515 result.assertions_if_false.push((name, key, ty, negated));
516 }
517 }
518 }
519 "psalm-property" => {
520 if let Some(body_str) = body_text(&tag.body) {
521 if let Some((ty_str, name)) = parse_param_line(&body_str) {
522 result.properties.push(DocProperty {
523 type_hint: ty_str,
524 name,
525 read_only: false,
526 write_only: false,
527 });
528 }
529 }
530 }
531 "psalm-property-read" => {
532 if let Some(body_str) = body_text(&tag.body) {
533 if let Some((ty_str, name)) = parse_param_line(&body_str) {
534 result.properties.push(DocProperty {
535 type_hint: ty_str,
536 name,
537 read_only: true,
538 write_only: false,
539 });
540 }
541 }
542 }
543 "psalm-property-write" => {
544 if let Some(body_str) = body_text(&tag.body) {
545 if let Some((ty_str, name)) = parse_param_line(&body_str) {
546 result.properties.push(DocProperty {
547 type_hint: ty_str,
548 name,
549 read_only: false,
550 write_only: true,
551 });
552 }
553 }
554 }
555 "psalm-require-extends" | "phpstan-require-extends" => {
556 if let Some(body_str) = body_text(&tag.body) {
557 let cls = body_str
558 .split_whitespace()
559 .next()
560 .unwrap_or("")
561 .trim()
562 .to_string();
563 if !cls.is_empty() {
564 result.require_extends.push(cls);
565 }
566 }
567 }
568 "psalm-require-implements" | "phpstan-require-implements" => {
569 if let Some(body_str) = body_text(&tag.body) {
570 let cls = body_str
571 .split_whitespace()
572 .next()
573 .unwrap_or("")
574 .trim()
575 .to_string();
576 if !cls.is_empty() {
577 result.require_implements.push(cls);
578 }
579 }
580 }
581 "mir-check" => {
582 if let Some(body_str) = body_text(&tag.body) {
583 if let Some((expr_part, type_part)) = body_str.split_once(" is ") {
584 // Kept verbatim (including any leading `$`) — the
585 // consumer parses this as a real PHP expression,
586 // not just a bare variable name.
587 let expr_text = expr_part.trim().to_string();
588 let type_string = type_part.trim().to_string();
589 if !expr_text.is_empty() && !type_string.is_empty() {
590 result.mir_checks.push((expr_text, type_string));
591 }
592 }
593 }
594 }
595 "dataProvider" => {
596 if let Some(body_str) = body_text(&tag.body) {
597 let name = body_str
598 .trim()
599 .trim_end_matches("()")
600 .rsplit("::")
601 .next()
602 .unwrap_or("")
603 .trim();
604 if !name.is_empty() {
605 result.data_providers.push(name.to_string());
606 }
607 }
608 }
609 "trace" => {
610 if let Some(body_str) = body_text(&tag.body) {
611 // Support both comma-separated and space-separated variable names
612 for part in body_str.split([',', ' ']) {
613 let var_name = part.trim().trim_start_matches('$').to_string();
614 if !var_name.is_empty() {
615 result.trace_vars.push(var_name);
616 }
617 }
618 }
619 }
620 "taint-sink" => {
621 if let Some(body_str) = body_text(&tag.body) {
622 // Format: `kind $param` or `kind $param1 $param2`
623 let mut tokens = body_str.split_whitespace();
624 if let Some(kind) = tokens.next() {
625 let kind = kind.to_string();
626 for param_token in tokens {
627 let param = param_token.trim_start_matches('$').to_string();
628 if !param.is_empty() {
629 result.taint_sinks.push((param, kind.clone()));
630 }
631 }
632 }
633 }
634 }
635 "taint-source" => result.is_taint_source = true,
636 _ => {}
637 }
638 }
639
640 if text.to_ascii_lowercase().contains("{@inheritdoc}") {
641 result.is_inherit_doc = true;
642 }
643
644 result
645 }
646}
647
648/// Record the backslash-qualified non-class (`\int`) members of a docblock
649/// type spelling in `result` — the collector turns each into an
650/// `InvalidDocblockType` warning anchored at the token's own source line.
651fn record_backslash_keyword_types(
652 result: &mut ParsedDocblock,
653 tag_name: &str,
654 ty: &str,
655 tag_start: u32,
656 text: &str,
657) {
658 for token in backslash_keyword_members(ty) {
659 let (line, col) = token_line_col(text, tag_start, ty, &token);
660 result.backslash_keyword_types.push(BackslashKeywordType {
661 tag: tag_name.to_string(),
662 token,
663 line,
664 col,
665 });
666 }
667}
668
669/// 0-based `(line, col)` of `token` within the docblock `text`. `token` is a
670/// verbatim member of `ty`, which sits in the tag body that follows `@tag`;
671/// it is located relative to `tag_start` (the tag's offset in the text).
672/// Falls back to the tag start when the token cannot be found.
673fn token_line_col(text: &str, tag_start: u32, ty: &str, token: &str) -> (u32, u32) {
674 let start = (tag_start as usize).min(text.len());
675 let mut abs = start;
676 if let Some(rest) = text.get(abs..) {
677 if let Some(ty_off) = rest.find(ty) {
678 if let Some(ty_text) = text.get(abs + ty_off..) {
679 if let Some(tok_off) = ty_text.find(token) {
680 abs = (abs + ty_off + tok_off).min(text.len());
681 }
682 }
683 }
684 }
685 let mut line = 0u32;
686 let mut line_start = 0usize;
687 for (i, b) in text.bytes().enumerate() {
688 if i >= abs {
689 break;
690 }
691 if b == b'\n' {
692 line += 1;
693 line_start = i + 1;
694 }
695 }
696 (line, (abs - line_start) as u32)
697}
698
699/// `self<T>`/`static<T>`/`parent<T>`/`$this<T>` written in a self-out
700/// annotation (`@psalm-self-out`, `@phpstan-self-out`, `@psalm-this-out`)
701/// needs its `<T>` kept intact for method-level template substitution (e.g.
702/// `@psalm-self-out self<U>` on a method with its own `@template U`) —
703/// unlike an ordinary `@return self<T>`, where the shared type parser
704/// deliberately drops the args and reattaches the receiver's own params
705/// instead (see `parse_generic`'s `self`/`static`/`parent` arms). Parsed
706/// here as a `TNamedObject` sentinel whose `fqcn` is the literal keyword
707/// (never a real PHP class name), which `substitute_static_atom` recognizes
708/// and resolves to the actual receiver class at call time while keeping
709/// `type_params` intact for the caller's later template substitution.
710fn parse_self_out_type(trimmed: &str) -> Type {
711 for keyword in ["self", "static", "parent", "$this"] {
712 let Some(rest) = strip_ascii_ci_prefix(trimmed, keyword) else {
713 continue;
714 };
715 let rest = rest.trim_start();
716 if let Some(inner) = rest.strip_prefix('<').and_then(|s| s.strip_suffix('>')) {
717 let params: Vec<Type> = split_generics(inner)
718 .iter()
719 .map(|p| parse_type_string(p.trim()))
720 .collect();
721 return Type::single(Atomic::TNamedObject {
722 fqcn: mir_types::Name::from(keyword),
723 type_params: mir_types::union::vec_to_type_params(params),
724 });
725 }
726 }
727 parse_type_string(trimmed)
728}
729
730// ---------------------------------------------------------------------------
731// ParsedDocblock support types
732// ---------------------------------------------------------------------------
733
734#[derive(Debug, Default, Clone)]
735pub struct DocProperty {
736 pub type_hint: String,
737 pub name: String, // without leading $
738 pub read_only: bool, // true for @property-read
739 pub write_only: bool, // true for @property-write
740}
741
742#[derive(Debug, Default, Clone)]
743pub struct DocMethod {
744 pub return_type: String,
745 pub name: String,
746 pub is_static: bool,
747 pub params: Vec<DocMethodParam>,
748}
749
750#[derive(Debug, Default, Clone)]
751pub struct DocMethodParam {
752 pub name: String,
753 pub type_hint: String,
754 pub is_variadic: bool,
755 pub is_byref: bool,
756 pub is_optional: bool,
757}
758
759#[derive(Debug, Default, Clone)]
760pub struct DocTypeAlias {
761 pub name: String,
762 pub type_expr: String,
763}
764
765/// A docblock type token written with a leading `\` (the fully-qualified
766/// class qualifier) on a non-class type keyword (`\int`, `?\string`, …).
767/// `line`/`col` are 0-based positions within the docblock text, so the
768/// collector can anchor the warning at the token's own source line.
769#[derive(Debug, Clone)]
770pub struct BackslashKeywordType {
771 /// The annotation tag carrying the type (`param`, `return`, `var`, …).
772 pub tag: String,
773 /// The offending type token, verbatim with its leading backslash.
774 pub token: String,
775 /// Line of the token within the docblock text.
776 pub line: u32,
777 /// Column of the token within its docblock-text line.
778 pub col: u32,
779}
780
781#[derive(Debug, Default, Clone)]
782pub struct DocImportType {
783 /// The name exported by the source class (the original alias name).
784 pub original: String,
785 /// The local name to use in this class (`as LocalAlias`); defaults to `original`.
786 pub local: String,
787 /// The FQCN of the class to import the type from.
788 pub from_class: String,
789}
790
791// ---------------------------------------------------------------------------
792// ParsedDocblock
793// ---------------------------------------------------------------------------
794
795#[derive(Debug, Default, Clone)]
796pub struct ParsedDocblock {
797 /// `@param Type $name`
798 pub params: Vec<(String, Type)>,
799 /// Raw `@param` type spellings keyed by parameter name. Kept so later
800 /// analysis can distinguish ambiguous pseudo-type aliases like
801 /// `integer`/`boolean` from a same-named class that should take
802 /// precedence once the full symbol table is available.
803 pub param_type_strings: Vec<(String, String)>,
804 /// `@param-out Type $name` / `@psalm-param-out Type $name` — the type written
805 /// back to the caller's by-ref argument after the call.
806 pub out_params: Vec<(String, Type)>,
807 /// `@return Type`
808 pub return_type: Option<Type>,
809 /// `@var Type` or `@var Type $name` — type and optional variable name
810 pub var_type: Option<Type>,
811 /// Optional variable name from `@var Type $name`
812 pub var_name: Option<String>,
813 /// `@template T` / `@template T of Bound` / `@template-covariant T` / `@template-contravariant T`
814 /// The last element is the optional `@template T = Default` default type.
815 pub templates: Vec<(String, Option<Type>, Variance, Option<Type>)>,
816 /// `@extends ClassName<T>` — a class has at most one entry (its single
817 /// parent); an interface may have several, one per base interface named
818 /// in its native `extends A, B` clause.
819 pub extends: Vec<Type>,
820 /// `@implements InterfaceName<T>`
821 pub implements: Vec<Type>,
822 /// `@use TraitName<T>` — explicit type argument(s) for a `use`d trait's
823 /// own `@template`, mirroring `@implements` for interfaces.
824 pub uses: Vec<Type>,
825 /// `@throws ClassName`
826 pub throws: Vec<String>,
827 /// `@psalm-assert Type $var` — the `bool` is true for the `!Type` negated
828 /// form; the key path is non-empty when the target is a specific
829 /// (possibly nested) array key of `$var` (`@psalm-assert Type
830 /// $var['a']['b']`) rather than the whole variable.
831 pub assertions: Vec<(String, Vec<ArrayKey>, Type, bool)>,
832 /// `@psalm-assert-if-true Type $var`
833 pub assertions_if_true: Vec<(String, Vec<ArrayKey>, Type, bool)>,
834 /// `@psalm-assert-if-false Type $var`
835 pub assertions_if_false: Vec<(String, Vec<ArrayKey>, Type, bool)>,
836 /// `@psalm-suppress IssueName`
837 pub suppressed_issues: Vec<String>,
838 pub is_deprecated: bool,
839 pub is_internal: bool,
840 pub is_pure: bool,
841 /// An explicit `@impure`/`@psalm-impure`/`@phpstan-impure` declaration.
842 /// This opts an implementation out of an inherited purity contract.
843 pub is_impure: bool,
844 pub is_mutation_free: bool,
845 pub is_external_mutation_free: bool,
846 pub no_named_arguments: bool,
847 pub is_immutable: bool,
848 pub is_readonly: bool,
849 pub is_api: bool,
850 /// `@final` — class should be treated as final even without the PHP `final` keyword.
851 pub is_final: bool,
852 /// `@inheritDoc` or `{@inheritDoc}` was present — documentation should be
853 /// inherited from the nearest ancestor that has a real docblock.
854 pub is_inherit_doc: bool,
855 /// Free text before first `@` tag — used for hover display
856 pub description: String,
857 /// `@deprecated message` — Some(message) or Some("") if no message
858 pub deprecated: Option<String>,
859 /// `@see ClassName` / `@link URL`
860 pub see: Vec<String>,
861 /// `@mixin ClassName`
862 pub mixins: Vec<String>,
863 /// `@property`, `@property-read`, `@property-write`
864 pub properties: Vec<DocProperty>,
865 /// `@method [static] ReturnType name([params])`
866 pub methods: Vec<DocMethod>,
867 /// `@psalm-type Alias = TypeExpr` / `@phpstan-type Alias = TypeExpr`
868 pub type_aliases: Vec<DocTypeAlias>,
869 /// `@psalm-import-type Alias from SourceClass` / `@phpstan-import-type ...`
870 pub import_types: Vec<DocImportType>,
871 /// `@psalm-require-extends ClassName` / `@phpstan-require-extends ClassName`
872 pub require_extends: Vec<String>,
873 /// `@psalm-require-implements InterfaceName` / `@phpstan-require-implements InterfaceName`
874 pub require_implements: Vec<String>,
875 /// `@since X.Y` — first PHP version this symbol exists in.
876 pub since: Option<String>,
877 /// `@removed X.Y` — first PHP version this symbol no longer exists in.
878 pub removed: Option<String>,
879 /// Malformed type annotations detected during parsing.
880 pub invalid_annotations: Vec<String>,
881 /// Docblock type spellings that use a leading `\` (the fully-qualified
882 /// class qualifier) on a non-class type keyword (`\int`, `?\string`, …);
883 /// the collector emits an `InvalidDocblockType` warning for each, anchored
884 /// at the token's own line.
885 pub backslash_keyword_types: Vec<BackslashKeywordType>,
886 /// `@mir-check EXPR is TYPE` — (expr_text, type_string). `expr_text` is
887 /// kept verbatim (e.g. `$h->status`, `self::$prop`, `$arr['key']`) and
888 /// parsed as a real PHP expression by the consumer, not just a bare
889 /// variable name.
890 pub mir_checks: Vec<(String, String)>,
891 /// `@trace $var1, $var2` or `@trace $var1 $var2` — variable names to trace
892 pub trace_vars: Vec<String>,
893 /// `@taint-sink <kind> $param` — (param_name_without_dollar, sink_kind_string)
894 pub taint_sinks: Vec<(String, String)>,
895 /// `@taint-source` — this function/method's return value is tainted.
896 pub is_taint_source: bool,
897 /// `@seal-properties` / `@psalm-seal-properties` — disallows undeclared property access.
898 pub seal_properties: bool,
899 /// `@if-this-is Type` / `@psalm-if-this-is Type` — the method may only be
900 /// called when `$this` satisfies this type. Stored as the raw parsed type;
901 /// class names are resolved later by the collector.
902 pub if_this_is: Option<Type>,
903 /// `@psalm-self-out Type` / `@phpstan-self-out Type` — the receiver's type
904 /// after this call returns. Stored as the raw parsed type; class names
905 /// (and `self`/`static`) are resolved later by the collector.
906 pub self_out: Option<Type>,
907 /// `@dataProvider methodName` (PHPUnit) — name of the method that supplies
908 /// this test's data, invoked by PHPUnit via reflection rather than a call.
909 pub data_providers: Vec<String>,
910}
911
912impl ParsedDocblock {
913 /// Returns the type for a given parameter name (strips leading `$`).
914 ///
915 /// Uses the **last** match so that `@psalm-param` / `@phpstan-param` (which
916 /// php-rs-parser maps to the same `Param` variant as `@param`) overrides a
917 /// preceding plain `@param` annotation.
918 pub fn get_param_type(&self, name: &str) -> Option<&Type> {
919 let name = name.trim_start_matches('$');
920 self.params
921 .iter()
922 .rfind(|(n, _)| n.trim_start_matches('$') == name)
923 .map(|(_, ty)| ty)
924 }
925
926 /// Returns the raw `@param` type spelling for a given parameter name.
927 /// Uses the **last** match, mirroring [`Self::get_param_type`].
928 pub fn get_param_type_string(&self, name: &str) -> Option<&str> {
929 let name = name.trim_start_matches('$');
930 self.param_type_strings
931 .iter()
932 .rfind(|(n, _)| n.trim_start_matches('$') == name)
933 .map(|(_, ty)| ty.as_str())
934 }
935
936 /// Returns the `@param-out` / `@psalm-param-out` type for a given parameter
937 /// name, if declared. Uses the **last** match.
938 pub fn get_out_param_type(&self, name: &str) -> Option<&Type> {
939 let name = name.trim_start_matches('$');
940 self.out_params
941 .iter()
942 .rfind(|(n, _)| n.trim_start_matches('$') == name)
943 .map(|(_, ty)| ty)
944 }
945}
946
947// ---------------------------------------------------------------------------
948// Type string parser
949// ---------------------------------------------------------------------------
950
951#[cfg(test)]
952mod tests;
953/// Parse a PHPDoc type expression string into a `Type`.
954/// Handles: `string`, `int|null`, `array<string>`, `list<int>`,
955/// `ClassName`, `?string` (nullable), `string[]` (array shorthand).
956mod types;
957mod validate;
958
959pub(crate) use types::SelfIntConstantsGuard;
960use types::*;
961use validate::*;
962
963pub(crate) use types::is_docblock_type_keyword;
964pub(crate) use types::parse_type_string;