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                "impure" | "psalm-impure" | "phpstan-impure" => result.is_impure = true,
492                "seal-properties" | "psalm-seal-properties" => result.seal_properties = true,
493                "no-named-arguments" => result.no_named_arguments = true,
494                "mutation-free" | "psalm-mutation-free" | "phpstan-mutation-free" => {
495                    result.is_mutation_free = true
496                }
497                "external-mutation-free"
498                | "psalm-external-mutation-free"
499                | "phpstan-external-mutation-free" => result.is_external_mutation_free = true,
500                "immutable" | "psalm-immutable" | "phpstan-immutable" => result.is_immutable = true,
501                "readonly" | "psalm-readonly" | "phpstan-readonly" => result.is_readonly = true,
502                "final" => result.is_final = true,
503                "inheritDoc" | "inheritdoc" => result.is_inherit_doc = true,
504                "api" | "psalm-api" => result.is_api = true,
505                "assert-if-true" | "psalm-assert-if-true" | "phpstan-assert-if-true" => {
506                    if let Some(body_str) = body_text(&tag.body) {
507                        if let Some((ty_str, name)) = parse_param_line(&body_str) {
508                            let (ty, negated) = parse_assertion_type(&ty_str);
509                            let (name, key) = split_array_key_suffix(&name);
510                            result.assertions_if_true.push((name, key, ty, negated));
511                        }
512                    }
513                }
514                "assert-if-false" | "psalm-assert-if-false" | "phpstan-assert-if-false" => {
515                    if let Some(body_str) = body_text(&tag.body) {
516                        if let Some((ty_str, name)) = parse_param_line(&body_str) {
517                            let (ty, negated) = parse_assertion_type(&ty_str);
518                            let (name, key) = split_array_key_suffix(&name);
519                            result.assertions_if_false.push((name, key, ty, negated));
520                        }
521                    }
522                }
523                "psalm-property" => {
524                    if let Some(body_str) = body_text(&tag.body) {
525                        if let Some((ty_str, name)) = parse_param_line(&body_str) {
526                            result.properties.push(DocProperty {
527                                type_hint: ty_str,
528                                name,
529                                read_only: false,
530                                write_only: false,
531                            });
532                        }
533                    }
534                }
535                "psalm-property-read" => {
536                    if let Some(body_str) = body_text(&tag.body) {
537                        if let Some((ty_str, name)) = parse_param_line(&body_str) {
538                            result.properties.push(DocProperty {
539                                type_hint: ty_str,
540                                name,
541                                read_only: true,
542                                write_only: false,
543                            });
544                        }
545                    }
546                }
547                "psalm-property-write" => {
548                    if let Some(body_str) = body_text(&tag.body) {
549                        if let Some((ty_str, name)) = parse_param_line(&body_str) {
550                            result.properties.push(DocProperty {
551                                type_hint: ty_str,
552                                name,
553                                read_only: false,
554                                write_only: true,
555                            });
556                        }
557                    }
558                }
559                "psalm-require-extends" | "phpstan-require-extends" => {
560                    if let Some(body_str) = body_text(&tag.body) {
561                        let cls = body_str
562                            .split_whitespace()
563                            .next()
564                            .unwrap_or("")
565                            .trim()
566                            .to_string();
567                        if !cls.is_empty() {
568                            result.require_extends.push(cls);
569                        }
570                    }
571                }
572                "psalm-require-implements" | "phpstan-require-implements" => {
573                    if let Some(body_str) = body_text(&tag.body) {
574                        let cls = body_str
575                            .split_whitespace()
576                            .next()
577                            .unwrap_or("")
578                            .trim()
579                            .to_string();
580                        if !cls.is_empty() {
581                            result.require_implements.push(cls);
582                        }
583                    }
584                }
585                "mir-check" => {
586                    if let Some(body_str) = body_text(&tag.body) {
587                        if let Some((expr_part, type_part)) = body_str.split_once(" is ") {
588                            // Kept verbatim (including any leading `$`) — the
589                            // consumer parses this as a real PHP expression,
590                            // not just a bare variable name.
591                            let expr_text = expr_part.trim().to_string();
592                            let type_string = type_part.trim().to_string();
593                            if !expr_text.is_empty() && !type_string.is_empty() {
594                                result.mir_checks.push((expr_text, type_string));
595                            }
596                        }
597                    }
598                }
599                "dataProvider" => {
600                    if let Some(body_str) = body_text(&tag.body) {
601                        let name = body_str
602                            .trim()
603                            .trim_end_matches("()")
604                            .rsplit("::")
605                            .next()
606                            .unwrap_or("")
607                            .trim();
608                        if !name.is_empty() {
609                            result.data_providers.push(name.to_string());
610                        }
611                    }
612                }
613                "trace" => {
614                    if let Some(body_str) = body_text(&tag.body) {
615                        // Support both comma-separated and space-separated variable names
616                        for part in body_str.split([',', ' ']) {
617                            let var_name = part.trim().trim_start_matches('$').to_string();
618                            if !var_name.is_empty() {
619                                result.trace_vars.push(var_name);
620                            }
621                        }
622                    }
623                }
624                "taint-sink" => {
625                    if let Some(body_str) = body_text(&tag.body) {
626                        // Format: `kind $param` or `kind $param1 $param2`
627                        let mut tokens = body_str.split_whitespace();
628                        if let Some(kind) = tokens.next() {
629                            let kind = kind.to_string();
630                            for param_token in tokens {
631                                let param = param_token.trim_start_matches('$').to_string();
632                                if !param.is_empty() {
633                                    result.taint_sinks.push((param, kind.clone()));
634                                }
635                            }
636                        }
637                    }
638                }
639                "taint-source" => result.is_taint_source = true,
640                _ => {}
641            }
642        }
643
644        if text.to_ascii_lowercase().contains("{@inheritdoc}") {
645            result.is_inherit_doc = true;
646        }
647
648        result
649    }
650}
651
652/// Record the backslash-qualified non-class (`\int`) members of a docblock
653/// type spelling in `result` — the collector turns each into an
654/// `InvalidDocblockType` warning anchored at the token's own source line.
655fn record_backslash_keyword_types(
656    result: &mut ParsedDocblock,
657    tag_name: &str,
658    ty: &str,
659    tag_start: u32,
660    text: &str,
661) {
662    for token in backslash_keyword_members(ty) {
663        let (line, col) = token_line_col(text, tag_start, ty, &token);
664        result.backslash_keyword_types.push(BackslashKeywordType {
665            tag: tag_name.to_string(),
666            token,
667            line,
668            col,
669        });
670    }
671}
672
673/// 0-based `(line, col)` of `token` within the docblock `text`. `token` is a
674/// verbatim member of `ty`, which sits in the tag body that follows `@tag`;
675/// it is located relative to `tag_start` (the tag's offset in the text).
676/// Falls back to the tag start when the token cannot be found.
677fn token_line_col(text: &str, tag_start: u32, ty: &str, token: &str) -> (u32, u32) {
678    let start = (tag_start as usize).min(text.len());
679    let mut abs = start;
680    if let Some(rest) = text.get(abs..) {
681        if let Some(ty_off) = rest.find(ty) {
682            if let Some(ty_text) = text.get(abs + ty_off..) {
683                if let Some(tok_off) = ty_text.find(token) {
684                    abs = (abs + ty_off + tok_off).min(text.len());
685                }
686            }
687        }
688    }
689    let mut line = 0u32;
690    let mut line_start = 0usize;
691    for (i, b) in text.bytes().enumerate() {
692        if i >= abs {
693            break;
694        }
695        if b == b'\n' {
696            line += 1;
697            line_start = i + 1;
698        }
699    }
700    (line, (abs - line_start) as u32)
701}
702
703/// `self<T>`/`static<T>`/`parent<T>`/`$this<T>` written in a self-out
704/// annotation (`@psalm-self-out`, `@phpstan-self-out`, `@psalm-this-out`)
705/// needs its `<T>` kept intact for method-level template substitution (e.g.
706/// `@psalm-self-out self<U>` on a method with its own `@template U`) —
707/// unlike an ordinary `@return self<T>`, where the shared type parser
708/// deliberately drops the args and reattaches the receiver's own params
709/// instead (see `parse_generic`'s `self`/`static`/`parent` arms). Parsed
710/// here as a `TNamedObject` sentinel whose `fqcn` is the literal keyword
711/// (never a real PHP class name), which `substitute_static_atom` recognizes
712/// and resolves to the actual receiver class at call time while keeping
713/// `type_params` intact for the caller's later template substitution.
714fn parse_self_out_type(trimmed: &str) -> Type {
715    for keyword in ["self", "static", "parent", "$this"] {
716        let Some(rest) = strip_ascii_ci_prefix(trimmed, keyword) else {
717            continue;
718        };
719        let rest = rest.trim_start();
720        if let Some(inner) = rest.strip_prefix('<').and_then(|s| s.strip_suffix('>')) {
721            let params: Vec<Type> = split_generics(inner)
722                .iter()
723                .map(|p| parse_type_string(p.trim()))
724                .collect();
725            return Type::single(Atomic::TNamedObject {
726                fqcn: mir_types::Name::from(keyword),
727                type_params: mir_types::union::vec_to_type_params(params),
728            });
729        }
730    }
731    parse_type_string(trimmed)
732}
733
734// ---------------------------------------------------------------------------
735// ParsedDocblock support types
736// ---------------------------------------------------------------------------
737
738#[derive(Debug, Default, Clone)]
739pub struct DocProperty {
740    pub type_hint: String,
741    pub name: String,     // without leading $
742    pub read_only: bool,  // true for @property-read
743    pub write_only: bool, // true for @property-write
744}
745
746#[derive(Debug, Default, Clone)]
747pub struct DocMethod {
748    pub return_type: String,
749    pub name: String,
750    pub is_static: bool,
751    pub params: Vec<DocMethodParam>,
752}
753
754#[derive(Debug, Default, Clone)]
755pub struct DocMethodParam {
756    pub name: String,
757    pub type_hint: String,
758    pub is_variadic: bool,
759    pub is_byref: bool,
760    pub is_optional: bool,
761}
762
763#[derive(Debug, Default, Clone)]
764pub struct DocTypeAlias {
765    pub name: String,
766    pub type_expr: String,
767}
768
769/// A docblock type token written with a leading `\` (the fully-qualified
770/// class qualifier) on a non-class type keyword (`\int`, `?\string`, …).
771/// `line`/`col` are 0-based positions within the docblock text, so the
772/// collector can anchor the warning at the token's own source line.
773#[derive(Debug, Clone)]
774pub struct BackslashKeywordType {
775    /// The annotation tag carrying the type (`param`, `return`, `var`, …).
776    pub tag: String,
777    /// The offending type token, verbatim with its leading backslash.
778    pub token: String,
779    /// Line of the token within the docblock text.
780    pub line: u32,
781    /// Column of the token within its docblock-text line.
782    pub col: u32,
783}
784
785#[derive(Debug, Default, Clone)]
786pub struct DocImportType {
787    /// The name exported by the source class (the original alias name).
788    pub original: String,
789    /// The local name to use in this class (`as LocalAlias`); defaults to `original`.
790    pub local: String,
791    /// The FQCN of the class to import the type from.
792    pub from_class: String,
793}
794
795// ---------------------------------------------------------------------------
796// ParsedDocblock
797// ---------------------------------------------------------------------------
798
799#[derive(Debug, Default, Clone)]
800pub struct ParsedDocblock {
801    /// `@param Type $name`
802    pub params: Vec<(String, Type)>,
803    /// Raw `@param` type spellings keyed by parameter name. Kept so later
804    /// analysis can distinguish ambiguous pseudo-type aliases like
805    /// `integer`/`boolean` from a same-named class that should take
806    /// precedence once the full symbol table is available.
807    pub param_type_strings: Vec<(String, String)>,
808    /// `@param-out Type $name` / `@psalm-param-out Type $name` — the type written
809    /// back to the caller's by-ref argument after the call.
810    pub out_params: Vec<(String, Type)>,
811    /// `@return Type`
812    pub return_type: Option<Type>,
813    /// `@var Type` or `@var Type $name` — type and optional variable name
814    pub var_type: Option<Type>,
815    /// Optional variable name from `@var Type $name`
816    pub var_name: Option<String>,
817    /// `@template T` / `@template T of Bound` / `@template-covariant T` / `@template-contravariant T`
818    /// The last element is the optional `@template T = Default` default type.
819    pub templates: Vec<(String, Option<Type>, Variance, Option<Type>)>,
820    /// `@extends ClassName<T>` — a class has at most one entry (its single
821    /// parent); an interface may have several, one per base interface named
822    /// in its native `extends A, B` clause.
823    pub extends: Vec<Type>,
824    /// `@implements InterfaceName<T>`
825    pub implements: Vec<Type>,
826    /// `@use TraitName<T>` — explicit type argument(s) for a `use`d trait's
827    /// own `@template`, mirroring `@implements` for interfaces.
828    pub uses: Vec<Type>,
829    /// `@throws ClassName`
830    pub throws: Vec<String>,
831    /// `@psalm-assert Type $var` — the `bool` is true for the `!Type` negated
832    /// form; the key path is non-empty when the target is a specific
833    /// (possibly nested) array key of `$var` (`@psalm-assert Type
834    /// $var['a']['b']`) rather than the whole variable.
835    pub assertions: Vec<(String, Vec<ArrayKey>, Type, bool)>,
836    /// `@psalm-assert-if-true Type $var`
837    pub assertions_if_true: Vec<(String, Vec<ArrayKey>, Type, bool)>,
838    /// `@psalm-assert-if-false Type $var`
839    pub assertions_if_false: Vec<(String, Vec<ArrayKey>, Type, bool)>,
840    /// `@psalm-suppress IssueName`
841    pub suppressed_issues: Vec<String>,
842    pub is_deprecated: bool,
843    pub is_internal: bool,
844    pub is_pure: bool,
845    /// An explicit `@impure`/`@psalm-impure`/`@phpstan-impure` declaration.
846    /// This opts an implementation out of an inherited purity contract.
847    pub is_impure: bool,
848    pub is_mutation_free: bool,
849    pub is_external_mutation_free: bool,
850    pub no_named_arguments: bool,
851    pub is_immutable: bool,
852    pub is_readonly: bool,
853    pub is_api: bool,
854    /// `@final` — class should be treated as final even without the PHP `final` keyword.
855    pub is_final: bool,
856    /// `@inheritDoc` or `{@inheritDoc}` was present — documentation should be
857    /// inherited from the nearest ancestor that has a real docblock.
858    pub is_inherit_doc: bool,
859    /// Free text before first `@` tag — used for hover display
860    pub description: String,
861    /// `@deprecated message` — Some(message) or Some("") if no message
862    pub deprecated: Option<String>,
863    /// `@see ClassName` / `@link URL`
864    pub see: Vec<String>,
865    /// `@mixin ClassName`
866    pub mixins: Vec<String>,
867    /// `@property`, `@property-read`, `@property-write`
868    pub properties: Vec<DocProperty>,
869    /// `@method [static] ReturnType name([params])`
870    pub methods: Vec<DocMethod>,
871    /// `@psalm-type Alias = TypeExpr` / `@phpstan-type Alias = TypeExpr`
872    pub type_aliases: Vec<DocTypeAlias>,
873    /// `@psalm-import-type Alias from SourceClass` / `@phpstan-import-type ...`
874    pub import_types: Vec<DocImportType>,
875    /// `@psalm-require-extends ClassName` / `@phpstan-require-extends ClassName`
876    pub require_extends: Vec<String>,
877    /// `@psalm-require-implements InterfaceName` / `@phpstan-require-implements InterfaceName`
878    pub require_implements: Vec<String>,
879    /// `@since X.Y` — first PHP version this symbol exists in.
880    pub since: Option<String>,
881    /// `@removed X.Y` — first PHP version this symbol no longer exists in.
882    pub removed: Option<String>,
883    /// Malformed type annotations detected during parsing.
884    pub invalid_annotations: Vec<String>,
885    /// Docblock type spellings that use a leading `\` (the fully-qualified
886    /// class qualifier) on a non-class type keyword (`\int`, `?\string`, …);
887    /// the collector emits an `InvalidDocblockType` warning for each, anchored
888    /// at the token's own line.
889    pub backslash_keyword_types: Vec<BackslashKeywordType>,
890    /// `@mir-check EXPR is TYPE` — (expr_text, type_string). `expr_text` is
891    /// kept verbatim (e.g. `$h->status`, `self::$prop`, `$arr['key']`) and
892    /// parsed as a real PHP expression by the consumer, not just a bare
893    /// variable name.
894    pub mir_checks: Vec<(String, String)>,
895    /// `@trace $var1, $var2` or `@trace $var1 $var2` — variable names to trace
896    pub trace_vars: Vec<String>,
897    /// `@taint-sink <kind> $param` — (param_name_without_dollar, sink_kind_string)
898    pub taint_sinks: Vec<(String, String)>,
899    /// `@taint-source` — this function/method's return value is tainted.
900    pub is_taint_source: bool,
901    /// `@seal-properties` / `@psalm-seal-properties` — disallows undeclared property access.
902    pub seal_properties: bool,
903    /// `@if-this-is Type` / `@psalm-if-this-is Type` — the method may only be
904    /// called when `$this` satisfies this type. Stored as the raw parsed type;
905    /// class names are resolved later by the collector.
906    pub if_this_is: Option<Type>,
907    /// `@psalm-self-out Type` / `@phpstan-self-out Type` — the receiver's type
908    /// after this call returns. Stored as the raw parsed type; class names
909    /// (and `self`/`static`) are resolved later by the collector.
910    pub self_out: Option<Type>,
911    /// `@dataProvider methodName` (PHPUnit) — name of the method that supplies
912    /// this test's data, invoked by PHPUnit via reflection rather than a call.
913    pub data_providers: Vec<String>,
914}
915
916impl ParsedDocblock {
917    /// Returns the type for a given parameter name (strips leading `$`).
918    ///
919    /// Uses the **last** match so that `@psalm-param` / `@phpstan-param` (which
920    /// php-rs-parser maps to the same `Param` variant as `@param`) overrides a
921    /// preceding plain `@param` annotation.
922    pub fn get_param_type(&self, name: &str) -> Option<&Type> {
923        let name = name.trim_start_matches('$');
924        self.params
925            .iter()
926            .rfind(|(n, _)| n.trim_start_matches('$') == name)
927            .map(|(_, ty)| ty)
928    }
929
930    /// Returns the raw `@param` type spelling for a given parameter name.
931    /// Uses the **last** match, mirroring [`get_param_type`].
932    pub fn get_param_type_string(&self, name: &str) -> Option<&str> {
933        let name = name.trim_start_matches('$');
934        self.param_type_strings
935            .iter()
936            .rfind(|(n, _)| n.trim_start_matches('$') == name)
937            .map(|(_, ty)| ty.as_str())
938    }
939
940    /// Returns the `@param-out` / `@psalm-param-out` type for a given parameter
941    /// name, if declared. Uses the **last** match.
942    pub fn get_out_param_type(&self, name: &str) -> Option<&Type> {
943        let name = name.trim_start_matches('$');
944        self.out_params
945            .iter()
946            .rfind(|(n, _)| n.trim_start_matches('$') == name)
947            .map(|(_, ty)| ty)
948    }
949}
950
951// ---------------------------------------------------------------------------
952// Type string parser
953// ---------------------------------------------------------------------------
954
955#[cfg(test)]
956mod tests;
957/// Parse a PHPDoc type expression string into a `Type`.
958/// Handles: `string`, `int|null`, `array<string>`, `list<int>`,
959/// `ClassName`, `?string` (nullable), `string[]` (array shorthand).
960mod types;
961mod validate;
962
963pub(crate) use types::SelfIntConstantsGuard;
964use types::*;
965use validate::*;
966
967pub(crate) use types::is_docblock_type_keyword;
968pub(crate) use types::parse_type_string;