Skip to main content

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                            // A generic alias name (`ListOf<T> = array<int, T>`)
443                            // kept the `<T>` suffix verbatim, so even a BARE
444                            // (non-parameterized) use site's lookup by the
445                            // plain name (`ListOf`) never matched — the alias
446                            // was silently 100% dead. Strip the suffix so at
447                            // least bare usage resolves; substituting T at a
448                            // parameterized use site (`ListOf<int>`) stays a
449                            // separate, not-yet-modeled problem (the template
450                            // parameter list itself is discarded here, same
451                            // as before).
452                            let raw_name = name.trim();
453                            let name = raw_name
454                                .split('<')
455                                .next()
456                                .unwrap_or(raw_name)
457                                .trim()
458                                .to_string();
459                            result.type_aliases.push(DocTypeAlias {
460                                name,
461                                type_expr: type_expr.trim().to_string(),
462                            });
463                        }
464                    }
465                }
466                "psalm-import-type" | "phpstan-import-type" => {
467                    if let Some(body_str) = body_text(&tag.body) {
468                        if let Some(import) = parse_import_type(&body_str) {
469                            result.import_types.push(import);
470                        }
471                    }
472                }
473                "since" if result.since.is_none() => {
474                    if let Some(body_str) = body_text(&tag.body) {
475                        let v = body_str.split_whitespace().next().unwrap_or("");
476                        if !v.is_empty() {
477                            result.since = Some(v.to_string());
478                        }
479                    }
480                }
481                "removed" if result.removed.is_none() => {
482                    if let Some(body_str) = body_text(&tag.body) {
483                        let v = body_str.split_whitespace().next().unwrap_or("");
484                        if !v.is_empty() {
485                            result.removed = Some(v.to_string());
486                        }
487                    }
488                }
489                "internal" | "psalm-internal" => result.is_internal = true,
490                "pure" | "psalm-pure" | "phpstan-pure" => result.is_pure = true,
491                "seal-properties" | "psalm-seal-properties" => result.seal_properties = true,
492                "no-named-arguments" => result.no_named_arguments = true,
493                "mutation-free" | "psalm-mutation-free" | "phpstan-mutation-free" => {
494                    result.is_mutation_free = true
495                }
496                "external-mutation-free"
497                | "psalm-external-mutation-free"
498                | "phpstan-external-mutation-free" => result.is_external_mutation_free = true,
499                "immutable" | "psalm-immutable" | "phpstan-immutable" => result.is_immutable = true,
500                "readonly" | "psalm-readonly" | "phpstan-readonly" => result.is_readonly = true,
501                "final" => result.is_final = true,
502                "inheritDoc" | "inheritdoc" => result.is_inherit_doc = true,
503                "api" | "psalm-api" => result.is_api = true,
504                "assert-if-true" | "psalm-assert-if-true" | "phpstan-assert-if-true" => {
505                    if let Some(body_str) = body_text(&tag.body) {
506                        if let Some((ty_str, name)) = parse_param_line(&body_str) {
507                            let (ty, negated) = parse_assertion_type(&ty_str);
508                            let (name, key) = split_array_key_suffix(&name);
509                            result.assertions_if_true.push((name, key, ty, negated));
510                        }
511                    }
512                }
513                "assert-if-false" | "psalm-assert-if-false" | "phpstan-assert-if-false" => {
514                    if let Some(body_str) = body_text(&tag.body) {
515                        if let Some((ty_str, name)) = parse_param_line(&body_str) {
516                            let (ty, negated) = parse_assertion_type(&ty_str);
517                            let (name, key) = split_array_key_suffix(&name);
518                            result.assertions_if_false.push((name, key, ty, negated));
519                        }
520                    }
521                }
522                "psalm-property" => {
523                    if let Some(body_str) = body_text(&tag.body) {
524                        if let Some((ty_str, name)) = parse_param_line(&body_str) {
525                            result.properties.push(DocProperty {
526                                type_hint: ty_str,
527                                name,
528                                read_only: false,
529                                write_only: false,
530                            });
531                        }
532                    }
533                }
534                "psalm-property-read" => {
535                    if let Some(body_str) = body_text(&tag.body) {
536                        if let Some((ty_str, name)) = parse_param_line(&body_str) {
537                            result.properties.push(DocProperty {
538                                type_hint: ty_str,
539                                name,
540                                read_only: true,
541                                write_only: false,
542                            });
543                        }
544                    }
545                }
546                "psalm-property-write" => {
547                    if let Some(body_str) = body_text(&tag.body) {
548                        if let Some((ty_str, name)) = parse_param_line(&body_str) {
549                            result.properties.push(DocProperty {
550                                type_hint: ty_str,
551                                name,
552                                read_only: false,
553                                write_only: true,
554                            });
555                        }
556                    }
557                }
558                "psalm-require-extends" | "phpstan-require-extends" => {
559                    if let Some(body_str) = body_text(&tag.body) {
560                        let cls = body_str
561                            .split_whitespace()
562                            .next()
563                            .unwrap_or("")
564                            .trim()
565                            .to_string();
566                        if !cls.is_empty() {
567                            result.require_extends.push(cls);
568                        }
569                    }
570                }
571                "psalm-require-implements" | "phpstan-require-implements" => {
572                    if let Some(body_str) = body_text(&tag.body) {
573                        let cls = body_str
574                            .split_whitespace()
575                            .next()
576                            .unwrap_or("")
577                            .trim()
578                            .to_string();
579                        if !cls.is_empty() {
580                            result.require_implements.push(cls);
581                        }
582                    }
583                }
584                "mir-check" => {
585                    if let Some(body_str) = body_text(&tag.body) {
586                        if let Some((expr_part, type_part)) = body_str.split_once(" is ") {
587                            // Kept verbatim (including any leading `$`) — the
588                            // consumer parses this as a real PHP expression,
589                            // not just a bare variable name.
590                            let expr_text = expr_part.trim().to_string();
591                            let type_string = type_part.trim().to_string();
592                            if !expr_text.is_empty() && !type_string.is_empty() {
593                                result.mir_checks.push((expr_text, type_string));
594                            }
595                        }
596                    }
597                }
598                "dataProvider" => {
599                    if let Some(body_str) = body_text(&tag.body) {
600                        let name = body_str
601                            .trim()
602                            .trim_end_matches("()")
603                            .rsplit("::")
604                            .next()
605                            .unwrap_or("")
606                            .trim();
607                        if !name.is_empty() {
608                            result.data_providers.push(name.to_string());
609                        }
610                    }
611                }
612                "trace" => {
613                    if let Some(body_str) = body_text(&tag.body) {
614                        // Support both comma-separated and space-separated variable names
615                        for part in body_str.split([',', ' ']) {
616                            let var_name = part.trim().trim_start_matches('$').to_string();
617                            if !var_name.is_empty() {
618                                result.trace_vars.push(var_name);
619                            }
620                        }
621                    }
622                }
623                "taint-sink" => {
624                    if let Some(body_str) = body_text(&tag.body) {
625                        // Format: `kind $param` or `kind $param1 $param2`
626                        let mut tokens = body_str.split_whitespace();
627                        if let Some(kind) = tokens.next() {
628                            let kind = kind.to_string();
629                            for param_token in tokens {
630                                let param = param_token.trim_start_matches('$').to_string();
631                                if !param.is_empty() {
632                                    result.taint_sinks.push((param, kind.clone()));
633                                }
634                            }
635                        }
636                    }
637                }
638                "taint-source" => result.is_taint_source = true,
639                _ => {}
640            }
641        }
642
643        if text.to_ascii_lowercase().contains("{@inheritdoc}") {
644            result.is_inherit_doc = true;
645        }
646
647        result
648    }
649}
650
651/// Record the backslash-qualified non-class (`\int`) members of a docblock
652/// type spelling in `result` — the collector turns each into an
653/// `InvalidDocblockType` warning anchored at the token's own source line.
654fn record_backslash_keyword_types(
655    result: &mut ParsedDocblock,
656    tag_name: &str,
657    ty: &str,
658    tag_start: u32,
659    text: &str,
660) {
661    for token in backslash_keyword_members(ty) {
662        let (line, col) = token_line_col(text, tag_start, ty, &token);
663        result.backslash_keyword_types.push(BackslashKeywordType {
664            tag: tag_name.to_string(),
665            token,
666            line,
667            col,
668        });
669    }
670}
671
672/// 0-based `(line, col)` of `token` within the docblock `text`. `token` is a
673/// verbatim member of `ty`, which sits in the tag body that follows `@tag`;
674/// it is located relative to `tag_start` (the tag's offset in the text).
675/// Falls back to the tag start when the token cannot be found.
676fn token_line_col(text: &str, tag_start: u32, ty: &str, token: &str) -> (u32, u32) {
677    let start = (tag_start as usize).min(text.len());
678    let mut abs = start;
679    if let Some(rest) = text.get(abs..) {
680        if let Some(ty_off) = rest.find(ty) {
681            if let Some(ty_text) = text.get(abs + ty_off..) {
682                if let Some(tok_off) = ty_text.find(token) {
683                    abs = (abs + ty_off + tok_off).min(text.len());
684                }
685            }
686        }
687    }
688    let mut line = 0u32;
689    let mut line_start = 0usize;
690    for (i, b) in text.bytes().enumerate() {
691        if i >= abs {
692            break;
693        }
694        if b == b'\n' {
695            line += 1;
696            line_start = i + 1;
697        }
698    }
699    (line, (abs - line_start) as u32)
700}
701
702/// `self<T>`/`static<T>`/`parent<T>`/`$this<T>` written in a self-out
703/// annotation (`@psalm-self-out`, `@phpstan-self-out`, `@psalm-this-out`)
704/// needs its `<T>` kept intact for method-level template substitution (e.g.
705/// `@psalm-self-out self<U>` on a method with its own `@template U`) —
706/// unlike an ordinary `@return self<T>`, where the shared type parser
707/// deliberately drops the args and reattaches the receiver's own params
708/// instead (see `parse_generic`'s `self`/`static`/`parent` arms). Parsed
709/// here as a `TNamedObject` sentinel whose `fqcn` is the literal keyword
710/// (never a real PHP class name), which `substitute_static_atom` recognizes
711/// and resolves to the actual receiver class at call time while keeping
712/// `type_params` intact for the caller's later template substitution.
713fn parse_self_out_type(trimmed: &str) -> Type {
714    for keyword in ["self", "static", "parent", "$this"] {
715        let Some(rest) = strip_ascii_ci_prefix(trimmed, keyword) else {
716            continue;
717        };
718        let rest = rest.trim_start();
719        if let Some(inner) = rest.strip_prefix('<').and_then(|s| s.strip_suffix('>')) {
720            let params: Vec<Type> = split_generics(inner)
721                .iter()
722                .map(|p| parse_type_string(p.trim()))
723                .collect();
724            return Type::single(Atomic::TNamedObject {
725                fqcn: mir_types::Name::from(keyword),
726                type_params: mir_types::union::vec_to_type_params(params),
727            });
728        }
729    }
730    parse_type_string(trimmed)
731}
732
733// ---------------------------------------------------------------------------
734// ParsedDocblock support types
735// ---------------------------------------------------------------------------
736
737#[derive(Debug, Default, Clone)]
738pub struct DocProperty {
739    pub type_hint: String,
740    pub name: String,     // without leading $
741    pub read_only: bool,  // true for @property-read
742    pub write_only: bool, // true for @property-write
743}
744
745#[derive(Debug, Default, Clone)]
746pub struct DocMethod {
747    pub return_type: String,
748    pub name: String,
749    pub is_static: bool,
750    pub params: Vec<DocMethodParam>,
751}
752
753#[derive(Debug, Default, Clone)]
754pub struct DocMethodParam {
755    pub name: String,
756    pub type_hint: String,
757    pub is_variadic: bool,
758    pub is_byref: bool,
759    pub is_optional: bool,
760}
761
762#[derive(Debug, Default, Clone)]
763pub struct DocTypeAlias {
764    pub name: String,
765    pub type_expr: String,
766}
767
768/// A docblock type token written with a leading `\` (the fully-qualified
769/// class qualifier) on a non-class type keyword (`\int`, `?\string`, …).
770/// `line`/`col` are 0-based positions within the docblock text, so the
771/// collector can anchor the warning at the token's own source line.
772#[derive(Debug, Clone)]
773pub struct BackslashKeywordType {
774    /// The annotation tag carrying the type (`param`, `return`, `var`, …).
775    pub tag: String,
776    /// The offending type token, verbatim with its leading backslash.
777    pub token: String,
778    /// Line of the token within the docblock text.
779    pub line: u32,
780    /// Column of the token within its docblock-text line.
781    pub col: u32,
782}
783
784#[derive(Debug, Default, Clone)]
785pub struct DocImportType {
786    /// The name exported by the source class (the original alias name).
787    pub original: String,
788    /// The local name to use in this class (`as LocalAlias`); defaults to `original`.
789    pub local: String,
790    /// The FQCN of the class to import the type from.
791    pub from_class: String,
792}
793
794// ---------------------------------------------------------------------------
795// ParsedDocblock
796// ---------------------------------------------------------------------------
797
798#[derive(Debug, Default, Clone)]
799pub struct ParsedDocblock {
800    /// `@param Type $name`
801    pub params: Vec<(String, Type)>,
802    /// Raw `@param` type spellings keyed by parameter name. Kept so later
803    /// analysis can distinguish ambiguous pseudo-type aliases like
804    /// `integer`/`boolean` from a same-named class that should take
805    /// precedence once the full symbol table is available.
806    pub param_type_strings: Vec<(String, String)>,
807    /// `@param-out Type $name` / `@psalm-param-out Type $name` — the type written
808    /// back to the caller's by-ref argument after the call.
809    pub out_params: Vec<(String, Type)>,
810    /// `@return Type`
811    pub return_type: Option<Type>,
812    /// `@var Type` or `@var Type $name` — type and optional variable name
813    pub var_type: Option<Type>,
814    /// Optional variable name from `@var Type $name`
815    pub var_name: Option<String>,
816    /// `@template T` / `@template T of Bound` / `@template-covariant T` / `@template-contravariant T`
817    /// The last element is the optional `@template T = Default` default type.
818    pub templates: Vec<(String, Option<Type>, Variance, Option<Type>)>,
819    /// `@extends ClassName<T>` — a class has at most one entry (its single
820    /// parent); an interface may have several, one per base interface named
821    /// in its native `extends A, B` clause.
822    pub extends: Vec<Type>,
823    /// `@implements InterfaceName<T>`
824    pub implements: Vec<Type>,
825    /// `@use TraitName<T>` — explicit type argument(s) for a `use`d trait's
826    /// own `@template`, mirroring `@implements` for interfaces.
827    pub uses: Vec<Type>,
828    /// `@throws ClassName`
829    pub throws: Vec<String>,
830    /// `@psalm-assert Type $var` — the `bool` is true for the `!Type` negated
831    /// form; the key path is non-empty when the target is a specific
832    /// (possibly nested) array key of `$var` (`@psalm-assert Type
833    /// $var['a']['b']`) rather than the whole variable.
834    pub assertions: Vec<(String, Vec<ArrayKey>, Type, bool)>,
835    /// `@psalm-assert-if-true Type $var`
836    pub assertions_if_true: Vec<(String, Vec<ArrayKey>, Type, bool)>,
837    /// `@psalm-assert-if-false Type $var`
838    pub assertions_if_false: Vec<(String, Vec<ArrayKey>, Type, bool)>,
839    /// `@psalm-suppress IssueName`
840    pub suppressed_issues: Vec<String>,
841    pub is_deprecated: bool,
842    pub is_internal: bool,
843    pub is_pure: 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 [`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;