1use mir_types::{ArrayKey, Atomic, Type, Variance};
2use std::sync::Arc;
5
6use indexmap::IndexMap;
7use phpdoc_parser::{body_text, parse as parse_phpdoc};
8
9pub 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" | "psalm-param" | "phpstan-param" => {
26 if let Some(body_str) = body_text(&tag.body) {
27 if let Some((ty_s, name)) = parse_param_line(&body_str) {
28 if is_inside_generics(&ty_s) {
30 if let Some(msg) = validate_type_str(&body_str, "param") {
32 result.invalid_annotations.push(msg);
33 }
34 } else if let Some(msg) = validate_type_str(&ty_s, "param") {
35 result.invalid_annotations.push(msg);
37 } else {
38 result.params.push((
39 name.trim_start_matches('$').to_string(),
40 parse_type_string(&ty_s),
41 ));
42 }
43 } else if let Some(msg) = validate_type_str(&body_str, "param") {
44 result.invalid_annotations.push(msg);
46 }
47 }
48 }
49 "return" | "psalm-return" | "phpstan-return" => {
50 if let Some(body_str) = body_text(&tag.body) {
51 let ty_s = extract_return_type(&body_str);
52 if let Some(msg) = validate_type_str(&ty_s, "return") {
53 result.invalid_annotations.push(msg);
54 }
55 result.return_type = Some(parse_type_string(&ty_s));
56 }
57 }
58 "var" => {
59 if let Some(body_str) = body_text(&tag.body) {
60 if let Some((ty_s, name)) = parse_param_line(&body_str) {
61 if let Some(msg) = validate_type_str(&ty_s, "var") {
62 result.invalid_annotations.push(msg);
63 }
64 result.var_type = Some(parse_type_string(&ty_s));
65 result.var_name = Some(name.trim_start_matches('$').to_string());
66 } else {
67 let ty_s = extract_type_prefix(body_str.trim());
71 if let Some(msg) = validate_type_str(ty_s, "var") {
72 result.invalid_annotations.push(msg);
73 }
74 result.var_type = Some(parse_type_string(ty_s));
75 }
76 }
77 }
78 "throws" => {
79 if let Some(body_str) = body_text(&tag.body) {
80 let class = body_str.split_whitespace().next().unwrap_or("").to_string();
81 if !class.is_empty() {
82 result.throws.push(class);
83 }
84 }
85 }
86 "deprecated" => {
87 result.is_deprecated = true;
88 result.deprecated = Some(body_text(&tag.body).unwrap_or_default().to_string());
89 }
90 "template" => {
91 if let Some((name, bound)) =
92 parse_template_line(tag.name.as_str(), body_text(&tag.body))
93 {
94 if let Some(b) = &bound {
95 if let Some(msg) = validate_type_str(b, "template") {
96 result.invalid_annotations.push(msg);
97 }
98 }
99 result.templates.push((
100 name,
101 bound.map(|b| parse_type_string(&b)),
102 Variance::Invariant,
103 ));
104 }
105 }
106 "template-covariant" => {
107 if let Some((name, bound)) =
108 parse_template_line(tag.name.as_str(), body_text(&tag.body))
109 {
110 if let Some(b) = &bound {
111 if let Some(msg) = validate_type_str(b, "template-covariant") {
112 result.invalid_annotations.push(msg);
113 }
114 }
115 result.templates.push((
116 name,
117 bound.map(|b| parse_type_string(&b)),
118 Variance::Covariant,
119 ));
120 }
121 }
122 "template-contravariant" => {
123 if let Some((name, bound)) =
124 parse_template_line(tag.name.as_str(), body_text(&tag.body))
125 {
126 if let Some(b) = &bound {
127 if let Some(msg) = validate_type_str(b, "template-contravariant") {
128 result.invalid_annotations.push(msg);
129 }
130 }
131 result.templates.push((
132 name,
133 bound.map(|b| parse_type_string(&b)),
134 Variance::Contravariant,
135 ));
136 }
137 }
138 "extends" => {
139 if let Some(body_str) = body_text(&tag.body) {
140 result.extends = Some(parse_type_string(body_str.trim()));
141 }
142 }
143 "implements" => {
144 if let Some(body_str) = body_text(&tag.body) {
145 result.implements.push(parse_type_string(body_str.trim()));
146 }
147 }
148 "assert" | "psalm-assert" | "phpstan-assert" => {
149 if let Some(body_str) = body_text(&tag.body) {
150 if let Some((ty_str, name)) = parse_param_line(&body_str) {
151 result.assertions.push((name, parse_type_string(&ty_str)));
152 }
153 }
154 }
155 "suppress" | "psalm-suppress" => {
156 if let Some(body_str) = body_text(&tag.body) {
157 for rule in body_str.split([',', ' ']) {
158 let rule = rule.trim().to_string();
159 if !rule.is_empty() {
160 result.suppressed_issues.push(rule);
161 }
162 }
163 }
164 }
165 "see" => {
166 if let Some(body_str) = body_text(&tag.body) {
167 result.see.push(body_str.to_string());
168 }
169 }
170 "link" => {
171 if let Some(body_str) = body_text(&tag.body) {
172 result.see.push(body_str.to_string());
173 }
174 }
175 "mixin" => {
176 if let Some(body_str) = body_text(&tag.body) {
177 let base_class =
178 body_str.split('<').next().unwrap_or(&body_str).to_string();
179 result.mixins.push(base_class);
180 }
181 }
182 "property" => {
183 if let Some(body_str) = body_text(&tag.body) {
184 if let Some((ty_str, name)) = parse_param_line(&body_str) {
185 result.properties.push(DocProperty {
186 type_hint: ty_str,
187 name: name.trim_start_matches('$').to_string(),
188 read_only: false,
189 write_only: false,
190 });
191 }
192 }
193 }
194 "property-read" => {
195 if let Some(body_str) = body_text(&tag.body) {
196 if let Some((ty_str, name)) = parse_param_line(&body_str) {
197 result.properties.push(DocProperty {
198 type_hint: ty_str,
199 name: name.trim_start_matches('$').to_string(),
200 read_only: true,
201 write_only: false,
202 });
203 }
204 }
205 }
206 "property-write" => {
207 if let Some(body_str) = body_text(&tag.body) {
208 if let Some((ty_str, name)) = parse_param_line(&body_str) {
209 result.properties.push(DocProperty {
210 type_hint: ty_str,
211 name: name.trim_start_matches('$').to_string(),
212 read_only: false,
213 write_only: true,
214 });
215 }
216 }
217 }
218 "method" | "psalm-method" => {
219 if let Some(body_str) = body_text(&tag.body) {
220 if let Some(m) = parse_method_line(&body_str) {
221 result.methods.push(m);
222 }
223 }
224 }
225 "psalm-type" | "phpstan-type" => {
226 if let Some(body_str) = body_text(&tag.body) {
227 if let Some((name, type_expr)) = body_str.split_once('=') {
228 result.type_aliases.push(DocTypeAlias {
229 name: name.trim().to_string(),
230 type_expr: type_expr.trim().to_string(),
231 });
232 }
233 }
234 }
235 "psalm-import-type" | "phpstan-import-type" => {
236 if let Some(body_str) = body_text(&tag.body) {
237 if let Some(import) = parse_import_type(&body_str) {
238 result.import_types.push(import);
239 }
240 }
241 }
242 "since" if result.since.is_none() => {
243 if let Some(body_str) = body_text(&tag.body) {
244 let v = body_str.split_whitespace().next().unwrap_or("");
245 if !v.is_empty() {
246 result.since = Some(v.to_string());
247 }
248 }
249 }
250 "removed" if result.removed.is_none() => {
251 if let Some(body_str) = body_text(&tag.body) {
252 let v = body_str.split_whitespace().next().unwrap_or("");
253 if !v.is_empty() {
254 result.removed = Some(v.to_string());
255 }
256 }
257 }
258 "internal" => result.is_internal = true,
259 "pure" => result.is_pure = true,
260 "immutable" => result.is_immutable = true,
261 "readonly" => result.is_readonly = true,
262 "inheritDoc" | "inheritdoc" => result.is_inherit_doc = true,
263 "api" | "psalm-api" => result.is_api = true,
264 "psalm-assert-if-true" | "phpstan-assert-if-true" => {
265 if let Some(body_str) = body_text(&tag.body) {
266 if let Some((ty_str, name)) = parse_param_line(&body_str) {
267 result
268 .assertions_if_true
269 .push((name, parse_type_string(&ty_str)));
270 }
271 }
272 }
273 "psalm-assert-if-false" | "phpstan-assert-if-false" => {
274 if let Some(body_str) = body_text(&tag.body) {
275 if let Some((ty_str, name)) = parse_param_line(&body_str) {
276 result
277 .assertions_if_false
278 .push((name, parse_type_string(&ty_str)));
279 }
280 }
281 }
282 "psalm-property" => {
283 if let Some(body_str) = body_text(&tag.body) {
284 if let Some((ty_str, name)) = parse_param_line(&body_str) {
285 result.properties.push(DocProperty {
286 type_hint: ty_str,
287 name,
288 read_only: false,
289 write_only: false,
290 });
291 }
292 }
293 }
294 "psalm-property-read" => {
295 if let Some(body_str) = body_text(&tag.body) {
296 if let Some((ty_str, name)) = parse_param_line(&body_str) {
297 result.properties.push(DocProperty {
298 type_hint: ty_str,
299 name,
300 read_only: true,
301 write_only: false,
302 });
303 }
304 }
305 }
306 "psalm-property-write" => {
307 if let Some(body_str) = body_text(&tag.body) {
308 if let Some((ty_str, name)) = parse_param_line(&body_str) {
309 result.properties.push(DocProperty {
310 type_hint: ty_str,
311 name,
312 read_only: false,
313 write_only: true,
314 });
315 }
316 }
317 }
318 "psalm-require-extends" | "phpstan-require-extends" => {
319 if let Some(body_str) = body_text(&tag.body) {
320 let cls = body_str
321 .split_whitespace()
322 .next()
323 .unwrap_or("")
324 .trim()
325 .to_string();
326 if !cls.is_empty() {
327 result.require_extends.push(cls);
328 }
329 }
330 }
331 "psalm-require-implements" | "phpstan-require-implements" => {
332 if let Some(body_str) = body_text(&tag.body) {
333 let cls = body_str
334 .split_whitespace()
335 .next()
336 .unwrap_or("")
337 .trim()
338 .to_string();
339 if !cls.is_empty() {
340 result.require_implements.push(cls);
341 }
342 }
343 }
344 "mir-check" => {
345 if let Some(body_str) = body_text(&tag.body) {
346 if let Some((var_part, type_part)) = body_str.split_once(" is ") {
347 let var_name = var_part.trim().trim_start_matches('$').to_string();
348 let type_string = type_part.trim().to_string();
349 if !var_name.is_empty() && !type_string.is_empty() {
350 result.mir_checks.push((var_name, type_string));
351 }
352 }
353 }
354 }
355 _ => {}
356 }
357 }
358
359 if text.to_ascii_lowercase().contains("{@inheritdoc}") {
360 result.is_inherit_doc = true;
361 }
362
363 result
364 }
365}
366
367#[derive(Debug, Default, Clone)]
372pub struct DocProperty {
373 pub type_hint: String,
374 pub name: String, pub read_only: bool, pub write_only: bool, }
378
379#[derive(Debug, Default, Clone)]
380pub struct DocMethod {
381 pub return_type: String,
382 pub name: String,
383 pub is_static: bool,
384 pub params: Vec<DocMethodParam>,
385}
386
387#[derive(Debug, Default, Clone)]
388pub struct DocMethodParam {
389 pub name: String,
390 pub type_hint: String,
391 pub is_variadic: bool,
392 pub is_byref: bool,
393 pub is_optional: bool,
394}
395
396#[derive(Debug, Default, Clone)]
397pub struct DocTypeAlias {
398 pub name: String,
399 pub type_expr: String,
400}
401
402#[derive(Debug, Default, Clone)]
403pub struct DocImportType {
404 pub original: String,
406 pub local: String,
408 pub from_class: String,
410}
411
412#[derive(Debug, Default, Clone)]
417pub struct ParsedDocblock {
418 pub params: Vec<(String, Type)>,
420 pub return_type: Option<Type>,
422 pub var_type: Option<Type>,
424 pub var_name: Option<String>,
426 pub templates: Vec<(String, Option<Type>, Variance)>,
428 pub extends: Option<Type>,
430 pub implements: Vec<Type>,
432 pub throws: Vec<String>,
434 pub assertions: Vec<(String, Type)>,
436 pub assertions_if_true: Vec<(String, Type)>,
438 pub assertions_if_false: Vec<(String, Type)>,
440 pub suppressed_issues: Vec<String>,
442 pub is_deprecated: bool,
443 pub is_internal: bool,
444 pub is_pure: bool,
445 pub is_immutable: bool,
446 pub is_readonly: bool,
447 pub is_api: bool,
448 pub is_inherit_doc: bool,
451 pub description: String,
453 pub deprecated: Option<String>,
455 pub see: Vec<String>,
457 pub mixins: Vec<String>,
459 pub properties: Vec<DocProperty>,
461 pub methods: Vec<DocMethod>,
463 pub type_aliases: Vec<DocTypeAlias>,
465 pub import_types: Vec<DocImportType>,
467 pub require_extends: Vec<String>,
469 pub require_implements: Vec<String>,
471 pub since: Option<String>,
473 pub removed: Option<String>,
475 pub invalid_annotations: Vec<String>,
477 pub mir_checks: Vec<(String, String)>,
479}
480
481impl ParsedDocblock {
482 pub fn get_param_type(&self, name: &str) -> Option<&Type> {
488 let name = name.trim_start_matches('$');
489 self.params
490 .iter()
491 .rfind(|(n, _)| n.trim_start_matches('$') == name)
492 .map(|(_, ty)| ty)
493 }
494}
495
496pub fn parse_type_string(s: &str) -> Type {
504 let s = s.trim();
505
506 if let Some(inner) = s.strip_prefix('?') {
508 let inner_ty = parse_type_string(inner);
509 let mut u = inner_ty;
510 u.add_type(Atomic::TNull);
511 return u;
512 }
513
514 if s.starts_with('(') && s.ends_with(')') {
517 let inner = s[1..s.len() - 1].trim();
518 if let Some(conditional) = parse_conditional_type(inner) {
519 return conditional;
520 }
521 if is_balanced_parens(s) {
523 return parse_type_string(inner);
524 }
525 }
526
527 if s.contains('|') && !is_inside_generics(s) {
529 let parts = split_union(s);
530 if parts.len() > 1 {
531 let mut u = Type::empty();
532 for part in parts {
533 for atomic in parse_type_string(&part).types {
534 u.add_type(atomic);
535 }
536 }
537 return u;
538 }
539 }
540
541 if s.contains('&') && !is_inside_generics(s) {
544 let parts = split_intersection(s);
545 if parts.len() > 1 {
546 let parts: Vec<Type> = parts.iter().map(|p| parse_type_string(p.trim())).collect();
547 return Type::single(Atomic::TIntersection {
548 parts: mir_types::union::vec_to_type_params(parts),
549 });
550 }
551 }
552
553 if let Some(value_str) = s.strip_suffix("[]") {
555 let value = parse_type_string(value_str);
556 return Type::single(Atomic::TArray {
557 key: Box::new(Type::single(Atomic::TInt)),
558 value: Box::new(value),
559 });
560 }
561
562 if let Some(call_ty) = parse_callable_syntax(s) {
564 return call_ty;
565 }
566
567 if s.ends_with('}') {
569 if let Some(open) = s.find('{') {
570 let prefix = s[..open].to_lowercase();
571 let inner = &s[open + 1..s.len() - 1];
572 if prefix == "array" {
573 return parse_keyed_array(inner, false);
574 } else if prefix == "list" {
575 return parse_keyed_array(inner, true);
576 }
577 }
578 }
579
580 if let Some(open) = s.find('<') {
582 if s.ends_with('>') {
583 let name = &s[..open];
584 let inner = &s[open + 1..s.len() - 1];
585 return parse_generic(name, inner);
586 }
587 }
588
589 match s.to_lowercase().as_str() {
591 "string" => Type::single(Atomic::TString),
592 "non-empty-string" => Type::single(Atomic::TNonEmptyString),
593 "numeric-string" => Type::single(Atomic::TNumericString),
594 "class-string" => Type::single(Atomic::TClassString(None)),
595 "int" | "integer" => Type::single(Atomic::TInt),
596 "positive-int" => Type::single(Atomic::TPositiveInt),
597 "negative-int" => Type::single(Atomic::TNegativeInt),
598 "non-negative-int" => Type::single(Atomic::TNonNegativeInt),
599 "float" | "double" => Type::single(Atomic::TFloat),
600 "bool" | "boolean" => Type::single(Atomic::TBool),
601 "true" => Type::single(Atomic::TTrue),
602 "false" => Type::single(Atomic::TFalse),
603 "null" => Type::single(Atomic::TNull),
604 "void" => Type::single(Atomic::TVoid),
605 "never" | "never-return" | "no-return" | "never-returns" => Type::single(Atomic::TNever),
606 "mixed" => Type::single(Atomic::TMixed),
607 "object" => Type::single(Atomic::TObject),
608 "array" => Type::single(Atomic::TArray {
609 key: Box::new(Type::single(Atomic::TMixed)),
610 value: Box::new(Type::mixed()),
611 }),
612 "list" => Type::single(Atomic::TList {
613 value: Box::new(Type::mixed()),
614 }),
615 "callable" => Type::single(Atomic::TCallable {
616 params: None,
617 return_type: None,
618 }),
619 "callable-string" => Type::single(Atomic::TCallableString),
620 "iterable" => Type::single(Atomic::TArray {
621 key: Box::new(Type::single(Atomic::TMixed)),
622 value: Box::new(Type::mixed()),
623 }),
624 "scalar" => Type::single(Atomic::TScalar),
625 "numeric" => Type::single(Atomic::TNumeric),
626 "array-key" => {
627 let mut u = Type::single(Atomic::TInt);
628 u.add_type(Atomic::TString);
629 u
630 }
631 "resource" => Type::mixed(), "static" => Type::single(Atomic::TStaticObject {
634 fqcn: mir_types::Name::from(""),
635 }),
636 "self" | "$this" => Type::single(Atomic::TSelf {
637 fqcn: mir_types::Name::from(""),
638 }),
639 "parent" => Type::single(Atomic::TParent {
640 fqcn: mir_types::Name::from(""),
641 }),
642
643 _ if !s.is_empty()
645 && s.chars()
646 .next()
647 .map(|c| c.is_alphanumeric() || c == '\\' || c == '_')
648 .unwrap_or(false) =>
649 {
650 if let Ok(n) = s.parse::<i64>() {
652 return Type::single(Atomic::TLiteralInt(n));
653 }
654 Type::single(Atomic::TNamedObject {
655 fqcn: normalize_fqcn(s).into(),
656 type_params: mir_types::union::empty_type_params(),
657 })
658 }
659
660 _ if s.starts_with('-') && s.len() > 1 && s[1..].chars().all(|c| c.is_ascii_digit()) => {
662 if let Ok(n) = s.parse::<i64>() {
663 Type::single(Atomic::TLiteralInt(n))
664 } else {
665 Type::mixed()
666 }
667 }
668
669 _ if (s.starts_with('\'') && s.ends_with('\''))
671 || (s.starts_with('"') && s.ends_with('"')) =>
672 {
673 let inner = &s[1..s.len() - 1];
674 Type::single(Atomic::TLiteralString(Arc::from(inner)))
675 }
676
677 _ => Type::mixed(),
678 }
679}
680
681fn parse_generic(name: &str, inner: &str) -> Type {
682 match name.to_lowercase().as_str() {
683 "array" => {
684 let params = split_generics(inner);
685 let array_key = || {
686 let mut k = Type::single(Atomic::TInt);
687 k.add_type(Atomic::TString);
688 k
689 };
690 let (key, value) = match params.len() {
691 n if n >= 2 => (
692 parse_type_string(params[0].trim()),
693 parse_type_string(params[1].trim()),
694 ),
695 1 => (array_key(), parse_type_string(params[0].trim())),
696 _ => (array_key(), Type::mixed()),
697 };
698 Type::single(Atomic::TArray {
699 key: Box::new(key),
700 value: Box::new(value),
701 })
702 }
703 "list" | "non-empty-list" => {
704 let value = parse_type_string(inner.trim());
705 if name.to_lowercase().starts_with("non-empty") {
706 Type::single(Atomic::TNonEmptyList {
707 value: Box::new(value),
708 })
709 } else {
710 Type::single(Atomic::TList {
711 value: Box::new(value),
712 })
713 }
714 }
715 "non-empty-array" => {
716 let params = split_generics(inner);
717 let array_key = || {
718 let mut k = Type::single(Atomic::TInt);
719 k.add_type(Atomic::TString);
720 k
721 };
722 let (key, value) = match params.len() {
723 n if n >= 2 => (
724 parse_type_string(params[0].trim()),
725 parse_type_string(params[1].trim()),
726 ),
727 1 => (array_key(), parse_type_string(params[0].trim())),
728 _ => (array_key(), Type::mixed()),
729 };
730 Type::single(Atomic::TNonEmptyArray {
731 key: Box::new(key),
732 value: Box::new(value),
733 })
734 }
735 "iterable" => {
736 let params = split_generics(inner);
737 let value = match params.len() {
738 n if n >= 2 => parse_type_string(params[1].trim()),
739 1 => parse_type_string(params[0].trim()),
740 _ => Type::mixed(),
741 };
742 Type::single(Atomic::TArray {
743 key: Box::new(Type::single(Atomic::TMixed)),
744 value: Box::new(value),
745 })
746 }
747 "class-string" => Type::single(Atomic::TClassString(Some(
748 normalize_fqcn(inner.trim()).into(),
749 ))),
750 "int" => {
751 Type::single(Atomic::TIntRange {
753 min: None,
754 max: None,
755 })
756 }
757 _ => {
759 let params: Vec<Type> = split_generics(inner)
760 .iter()
761 .map(|p| parse_type_string(p.trim()))
762 .collect();
763 Type::single(Atomic::TNamedObject {
764 fqcn: normalize_fqcn(name).into(),
765 type_params: mir_types::union::vec_to_type_params(params),
766 })
767 }
768 }
769}
770
771fn strip_quotes(s: &str) -> &str {
772 if (s.starts_with('\'') && s.ends_with('\'')) || (s.starts_with('"') && s.ends_with('"')) {
773 &s[1..s.len() - 1]
774 } else {
775 s
776 }
777}
778
779fn parse_keyed_array(inner: &str, is_list: bool) -> Type {
780 use mir_types::atomic::KeyedProperty;
781 let mut properties: IndexMap<ArrayKey, KeyedProperty> = IndexMap::new();
782 let mut is_open = false;
783 let mut auto_index = 0i64;
784
785 for item in split_generics(inner) {
786 let item = item.trim();
787 if item.is_empty() {
788 continue;
789 }
790 if item == "..." {
791 is_open = true;
792 continue;
793 }
794 let colon_pos = {
796 let mut depth = 0i32;
797 let mut found = None;
798 for (i, ch) in item.char_indices() {
799 match ch {
800 '<' | '(' | '{' => depth += 1,
801 '>' | ')' | '}' => depth -= 1,
802 ':' if depth == 0 => {
803 found = Some(i);
804 break;
805 }
806 _ => {}
807 }
808 }
809 found
810 };
811 if let Some(colon) = colon_pos {
812 let key_part = item[..colon].trim();
813 let ty_part = item[colon + 1..].trim();
814 let optional = key_part.ends_with('?');
815 let key_str = key_part.trim_end_matches('?').trim();
816 let key_str = strip_quotes(key_str);
817 let key = if let Ok(n) = key_str.parse::<i64>() {
818 ArrayKey::Int(n)
819 } else {
820 ArrayKey::String(Arc::from(key_str))
821 };
822 properties.insert(
823 key,
824 KeyedProperty {
825 ty: parse_type_string(ty_part),
826 optional,
827 },
828 );
829 } else {
830 properties.insert(
831 ArrayKey::Int(auto_index),
832 KeyedProperty {
833 ty: parse_type_string(item),
834 optional: false,
835 },
836 );
837 auto_index += 1;
838 }
839 }
840
841 Type::single(Atomic::TKeyedArray {
842 properties,
843 is_open,
844 is_list,
845 })
846}
847
848fn parse_callable_syntax(s: &str) -> Option<Type> {
849 let s = s.trim_start_matches('\\');
850 let lower = s.to_lowercase();
851 let is_closure = lower.starts_with("closure");
852 let is_callable = lower.starts_with("callable");
853 if !is_closure && !is_callable {
854 return None;
855 }
856 let prefix_len = if is_closure {
857 "closure".len()
858 } else {
859 "callable".len()
860 };
861 let rest = s[prefix_len..].trim_start();
862 if !rest.starts_with('(') {
863 return None;
864 }
865 let close = find_matching_paren(rest)?;
866 let params_str = &rest[1..close];
867 let after = rest[close + 1..].trim();
868 let return_type = after
869 .strip_prefix(':')
870 .map(|ret_str| Box::new(parse_type_string(ret_str.trim())));
871 let params: Vec<mir_types::atomic::FnParam> = split_generics(params_str)
872 .into_iter()
873 .enumerate()
874 .filter(|(_, p)| !p.trim().is_empty())
875 .map(|(i, p)| {
876 let p = p.trim();
877 let (ty_str, name) = if let Some(dollar) = p.rfind('$') {
878 (p[..dollar].trim(), p[dollar + 1..].to_string())
879 } else {
880 (p, format!("arg{i}"))
881 };
882 mir_types::atomic::FnParam {
883 name: name.into(),
884 ty: Some(mir_types::SimpleType::from_union(parse_type_string(ty_str))),
885 default: None,
886 is_variadic: false,
887 is_byref: false,
888 is_optional: false,
889 }
890 })
891 .collect();
892 if is_closure {
893 Some(Type::single(Atomic::TClosure {
894 params,
895 return_type: return_type.unwrap_or_else(|| Box::new(Type::single(Atomic::TVoid))),
896 this_type: None,
897 }))
898 } else {
899 Some(Type::single(Atomic::TCallable {
900 params: Some(params),
901 return_type,
902 }))
903 }
904}
905
906fn find_matching_paren(s: &str) -> Option<usize> {
907 if !s.starts_with('(') {
908 return None;
909 }
910 let mut depth = 0i32;
911 for (i, ch) in s.char_indices() {
912 match ch {
913 '(' | '<' | '{' => depth += 1,
914 ')' | '>' | '}' => {
915 depth -= 1;
916 if depth == 0 {
917 return Some(i);
918 }
919 }
920 _ => {}
921 }
922 }
923 None
924}
925
926fn parse_template_line(_tag_name: &str, body: Option<String>) -> Option<(String, Option<String>)> {
932 let body = body?;
933 if let Some((name, bound)) = body.split_once(" of ").or_else(|| body.split_once(" as ")) {
934 Some((name.trim().to_string(), Some(bound.trim().to_string())))
935 } else {
936 Some((body.trim().to_string(), None))
937 }
938}
939
940fn extract_description(text: &str) -> String {
942 let mut desc_lines: Vec<&str> = Vec::new();
943 for line in text.lines() {
944 let l = line.trim();
945 let l = l.trim_start_matches("/**").trim();
946 let l = l.trim_end_matches("*/").trim();
947 let l = l.trim_start_matches("*/").trim();
948 let l = l.strip_prefix("* ").unwrap_or(l.trim_start_matches('*'));
949 let l = l.trim();
950 if l.starts_with('@') {
951 break;
952 }
953 if !l.is_empty() {
954 desc_lines.push(l);
955 }
956 }
957 desc_lines.join(" ")
958}
959
960fn parse_import_type(body: &str) -> Option<DocImportType> {
966 let (before_from, from_class_raw) = body.split_once(" from ")?;
968 let from_class = from_class_raw.trim().trim_start_matches('\\').to_string();
969 if from_class.is_empty() {
970 return None;
971 }
972 let (original, local) = if let Some((orig, loc)) = before_from.split_once(" as ") {
974 (orig.trim().to_string(), loc.trim().to_string())
975 } else {
976 let name = before_from.trim().to_string();
977 (name.clone(), name)
978 };
979 if original.is_empty() || local.is_empty() {
980 return None;
981 }
982 Some(DocImportType {
983 original,
984 local,
985 from_class,
986 })
987}
988
989fn parse_param_line(s: &str) -> Option<(String, String)> {
990 let first_line = s.lines().next().unwrap_or(s);
996
997 let mut best_split: Option<(String, String)> = None;
1000
1001 for (i, ch) in first_line.char_indices() {
1002 if ch.is_whitespace() {
1003 let after = first_line[i..].trim_start();
1004 let after_stripped = after.strip_prefix('&').unwrap_or(after);
1006 if after_stripped.starts_with('$') {
1007 let mut var_parts = after_stripped.split(char::is_whitespace);
1008 if let Some(name_with_dollar) = var_parts.next() {
1009 let name = name_with_dollar.trim_start_matches('$').to_string();
1010 if !name.is_empty() {
1011 let type_part = first_line[..i].trim().to_string();
1012 if !type_part.is_empty() {
1013 best_split = Some((type_part, name));
1014 }
1015 }
1016 }
1017 }
1018 }
1019 }
1020
1021 best_split
1022}
1023
1024fn extract_return_type(s: &str) -> String {
1025 let mut depth: i32 = 0;
1034 let mut current_token = String::new();
1035
1036 for ch in s.chars() {
1037 match ch {
1038 '<' | '(' | '{' => {
1039 depth += 1;
1040 current_token.push(ch);
1041 }
1042 '>' | ')' | '}' => {
1043 depth = (depth - 1).max(0);
1044 current_token.push(ch);
1045 }
1046 _ if ch.is_whitespace() && depth == 0 => {
1047 break;
1048 }
1049 _ => {
1050 current_token.push(ch);
1051 }
1052 }
1053 }
1054
1055 if current_token.ends_with(':') {
1059 let offset = current_token.len();
1060 let rest = s[offset..].trim_start();
1061 if !rest.is_empty() {
1062 let ret_type = extract_return_type(rest);
1063 current_token.push_str(&ret_type);
1064 }
1065 }
1066
1067 current_token.trim().to_string()
1068}
1069
1070fn split_union(s: &str) -> Vec<String> {
1071 let mut parts = Vec::new();
1072 let mut depth = 0;
1073 let mut current = String::new();
1074 for ch in s.chars() {
1075 match ch {
1076 '<' | '(' | '{' => {
1077 depth += 1;
1078 current.push(ch);
1079 }
1080 '>' | ')' | '}' => {
1081 depth -= 1;
1082 current.push(ch);
1083 }
1084 '|' if depth == 0 => {
1085 parts.push(current.trim().to_string());
1086 current = String::new();
1087 }
1088 _ => current.push(ch),
1089 }
1090 }
1091 if !current.trim().is_empty() {
1092 parts.push(current.trim().to_string());
1093 }
1094 parts
1095}
1096
1097fn split_intersection(s: &str) -> Vec<String> {
1099 let mut parts = Vec::new();
1100 let mut depth = 0i32;
1101 let mut current = String::new();
1102 for ch in s.chars() {
1103 match ch {
1104 '<' | '(' | '{' => {
1105 depth += 1;
1106 current.push(ch);
1107 }
1108 '>' | ')' | '}' => {
1109 depth -= 1;
1110 current.push(ch);
1111 }
1112 '&' if depth == 0 => {
1113 parts.push(current.trim().to_string());
1114 current = String::new();
1115 }
1116 _ => current.push(ch),
1117 }
1118 }
1119 if !current.trim().is_empty() {
1120 parts.push(current.trim().to_string());
1121 }
1122 parts
1123}
1124
1125fn is_balanced_parens(s: &str) -> bool {
1129 if !s.starts_with('(') || !s.ends_with(')') {
1130 return false;
1131 }
1132 let mut depth = 0i32;
1133 let chars: Vec<char> = s.chars().collect();
1134 let last = chars.len() - 1;
1135 for (i, ch) in chars.iter().enumerate() {
1136 match ch {
1137 '(' => depth += 1,
1138 ')' => {
1139 depth -= 1;
1140 if depth == 0 && i < last {
1143 return false;
1144 }
1145 }
1146 _ => {}
1147 }
1148 }
1149 depth == 0
1150}
1151
1152fn split_generics(s: &str) -> Vec<String> {
1153 let mut parts = Vec::new();
1154 let mut depth = 0;
1155 let mut current = String::new();
1156 for ch in s.chars() {
1157 match ch {
1158 '<' | '(' | '{' => {
1159 depth += 1;
1160 current.push(ch);
1161 }
1162 '>' | ')' | '}' => {
1163 depth -= 1;
1164 current.push(ch);
1165 }
1166 ',' if depth == 0 => {
1167 parts.push(current.trim().to_string());
1168 current = String::new();
1169 }
1170 _ => current.push(ch),
1171 }
1172 }
1173 if !current.trim().is_empty() {
1174 parts.push(current.trim().to_string());
1175 }
1176 parts
1177}
1178
1179fn extract_type_prefix(s: &str) -> &str {
1182 let mut depth = 0i32;
1183 let mut end = s.len();
1184 for (i, ch) in s.char_indices() {
1185 match ch {
1186 '<' | '(' | '{' => depth += 1,
1187 '>' | ')' | '}' => depth -= 1,
1188 _ if ch.is_whitespace() && depth == 0 => {
1189 end = i;
1190 break;
1191 }
1192 _ => {}
1193 }
1194 }
1195 &s[..end]
1196}
1197
1198fn is_inside_generics(s: &str) -> bool {
1199 let mut depth = 0i32;
1200 for ch in s.chars() {
1201 match ch {
1202 '<' | '(' | '{' => depth += 1,
1203 '>' | ')' | '}' => depth -= 1,
1204 _ => {}
1205 }
1206 }
1207 depth != 0
1208}
1209
1210fn parse_conditional_type(s: &str) -> Option<Type> {
1213 let is_pos = s.find(" is ")?;
1214 let param_raw = s[..is_pos].trim();
1215
1216 let param_name_str: &str = if let Some(name) = param_raw.strip_prefix('$') {
1218 if name.is_empty() {
1219 return None;
1220 }
1221 name
1222 } else {
1223 if param_raw.is_empty()
1226 || !param_raw.starts_with(|c: char| c.is_alphabetic() || c == '_')
1227 || !param_raw.chars().all(|c| c.is_alphanumeric() || c == '_')
1228 || !s.contains('?')
1229 {
1230 return None;
1231 }
1232 param_raw
1233 };
1234 let param_name = Some(mir_types::Name::new(param_name_str));
1235 let after_is = s[is_pos + 4..].trim();
1236 let q_pos = find_char_at_depth(after_is, '?')?;
1237 let subject_str = after_is[..q_pos].trim();
1238 let rest = after_is[q_pos + 1..].trim();
1239 let colon_pos = find_char_at_depth(rest, ':')?;
1240 let true_str = rest[..colon_pos].trim();
1241 let false_str = rest[colon_pos + 1..].trim();
1242 Some(Type::single(Atomic::TConditional {
1243 param_name,
1244 subject: Box::new(parse_type_string(subject_str)),
1245 if_true: Box::new(parse_type_string(true_str)),
1246 if_false: Box::new(parse_type_string(false_str)),
1247 }))
1248}
1249
1250fn find_char_at_depth(s: &str, target: char) -> Option<usize> {
1252 let mut depth = 0i32;
1253 for (i, ch) in s.char_indices() {
1254 match ch {
1255 '<' | '(' | '{' => depth += 1,
1256 '>' | ')' | '}' => depth -= 1,
1257 _ if ch == target && depth == 0 => return Some(i),
1258 _ => {}
1259 }
1260 }
1261 None
1262}
1263
1264fn normalize_fqcn(s: &str) -> String {
1265 s.trim_start_matches('\\').to_string()
1267}
1268
1269fn validate_type_str(s: &str, tag: &str) -> Option<String> {
1275 let s = s.trim();
1276 if s.is_empty() {
1277 return None;
1278 }
1279 if is_inside_generics(s) {
1280 return Some(format!("@{tag} has unclosed generic type `{s}`"));
1281 }
1282 let is_callable_type = s.to_lowercase().contains("callable") || s.contains("Closure");
1284 if !is_callable_type && has_empty_generics(s) {
1285 return Some(format!("@{tag} has empty generic type parameter in `{s}`"));
1286 }
1287 for part in split_union(s) {
1288 let p = part.trim();
1289 if p.starts_with('$') && p != "$this" {
1290 return Some(format!("@{tag} contains variable `{p}` in type position"));
1291 }
1292 }
1293 None
1294}
1295
1296fn has_empty_generics(s: &str) -> bool {
1297 let mut depth = 0;
1298 let mut prev_open = false;
1299 for ch in s.chars() {
1300 match ch {
1301 '<' | '(' | '{' => {
1302 if prev_open && depth == 0 {
1303 return true;
1304 }
1305 prev_open = true;
1306 depth += 1;
1307 }
1308 '>' | ')' | '}' => {
1309 depth -= 1;
1310 if depth == 0 {
1311 if prev_open {
1312 return true;
1313 }
1314 prev_open = false;
1315 }
1316 }
1317 c if !c.is_whitespace() => {
1318 prev_open = false;
1319 }
1320 _ => {}
1321 }
1322 }
1323 false
1324}
1325
1326fn parse_method_line(s: &str) -> Option<DocMethod> {
1328 let mut rest = s.trim();
1329 if rest.is_empty() {
1330 return None;
1331 }
1332 let is_static = rest
1333 .split_whitespace()
1334 .next()
1335 .map(|w| w.eq_ignore_ascii_case("static"))
1336 .unwrap_or(false);
1337 if is_static {
1338 rest = rest["static".len()..].trim_start();
1339 }
1340
1341 let open = rest.find('(').unwrap_or(rest.len());
1342 let prefix = rest[..open].trim();
1343 let mut parts: Vec<&str> = prefix.split_whitespace().collect();
1344 let name = parts.pop()?.to_string();
1345 if name.is_empty() {
1346 return None;
1347 }
1348 let return_type = parts.join(" ");
1349 Some(DocMethod {
1350 return_type,
1351 name,
1352 is_static,
1353 params: parse_method_params(rest),
1354 })
1355}
1356
1357fn parse_method_params(name_part: &str) -> Vec<DocMethodParam> {
1358 let Some(open) = name_part.find('(') else {
1359 return vec![];
1360 };
1361 let Some(close) = name_part.rfind(')') else {
1362 return vec![];
1363 };
1364 let inner = name_part[open + 1..close].trim();
1365 if inner.is_empty() {
1366 return vec![];
1367 }
1368
1369 split_generics(inner)
1370 .into_iter()
1371 .filter_map(|param| parse_method_param(¶m))
1372 .collect()
1373}
1374
1375fn parse_method_param(param: &str) -> Option<DocMethodParam> {
1376 let before_default = param.split('=').next()?.trim();
1377 let is_optional = param.contains('=');
1378 let mut tokens: Vec<&str> = before_default.split_whitespace().collect();
1379 let raw_name = tokens.pop()?;
1380 let is_variadic = raw_name.contains("...");
1381 let is_byref = raw_name.contains('&');
1382 let name = raw_name
1383 .trim_start_matches('&')
1384 .trim_start_matches("...")
1385 .trim_start_matches('&')
1386 .trim_start_matches('$')
1387 .to_string();
1388 if name.is_empty() {
1389 return None;
1390 }
1391 Some(DocMethodParam {
1392 name,
1393 type_hint: tokens.join(" "),
1394 is_variadic,
1395 is_byref,
1396 is_optional: is_optional || is_variadic,
1397 })
1398}
1399
1400#[cfg(test)]
1405mod tests {
1406 use super::*;
1407 use mir_types::Atomic;
1408
1409 #[test]
1410 fn parse_string() {
1411 let u = parse_type_string("string");
1412 assert_eq!(u.types.len(), 1);
1413 assert!(matches!(u.types[0], Atomic::TString));
1414 }
1415
1416 #[test]
1417 fn parse_nullable_string() {
1418 let u = parse_type_string("?string");
1419 assert!(u.is_nullable());
1420 assert!(u.contains(|t| matches!(t, Atomic::TString)));
1421 }
1422
1423 #[test]
1424 fn parse_union() {
1425 let u = parse_type_string("string|int|null");
1426 assert!(u.contains(|t| matches!(t, Atomic::TString)));
1427 assert!(u.contains(|t| matches!(t, Atomic::TInt)));
1428 assert!(u.is_nullable());
1429 }
1430
1431 #[test]
1432 fn parse_array_of_string() {
1433 let u = parse_type_string("array<string>");
1434 assert!(u.contains(|t| matches!(t, Atomic::TArray { .. })));
1435 }
1436
1437 #[test]
1438 fn parse_list_of_int() {
1439 let u = parse_type_string("list<int>");
1440 assert!(u.contains(|t| matches!(t, Atomic::TList { .. })));
1441 }
1442
1443 #[test]
1444 fn parse_named_class() {
1445 let u = parse_type_string("Foo\\Bar");
1446 assert!(u.contains(
1447 |t| matches!(t, Atomic::TNamedObject { fqcn, .. } if fqcn.as_ref() == "Foo\\Bar")
1448 ));
1449 }
1450
1451 #[test]
1452 fn parse_docblock_param_return() {
1453 let doc = r#"/**
1454 * @param string $name
1455 * @param int $age
1456 * @return bool
1457 */"#;
1458 let parsed = DocblockParser::parse(doc);
1459 assert_eq!(parsed.params.len(), 2);
1460 assert!(parsed.return_type.is_some());
1461 let ret = parsed.return_type.unwrap();
1462 assert!(ret.contains(|t| matches!(t, Atomic::TBool)));
1463 }
1464
1465 #[test]
1466 fn parse_template() {
1467 let doc = "/** @template T of object */";
1468 let parsed = DocblockParser::parse(doc);
1469 assert_eq!(parsed.templates.len(), 1);
1470 assert_eq!(parsed.templates[0].0, "T");
1471 assert!(parsed.templates[0].1.is_some());
1472 assert_eq!(parsed.templates[0].2, Variance::Invariant);
1473 }
1474
1475 #[test]
1476 fn parse_template_covariant() {
1477 let doc = "/** @template-covariant T */";
1478 let parsed = DocblockParser::parse(doc);
1479 assert_eq!(parsed.templates.len(), 1);
1480 assert_eq!(parsed.templates[0].0, "T");
1481 assert_eq!(parsed.templates[0].2, Variance::Covariant);
1482 }
1483
1484 #[test]
1485 fn parse_template_contravariant() {
1486 let doc = "/** @template-contravariant T */";
1487 let parsed = DocblockParser::parse(doc);
1488 assert_eq!(parsed.templates.len(), 1);
1489 assert_eq!(parsed.templates[0].0, "T");
1490 assert_eq!(parsed.templates[0].2, Variance::Contravariant);
1491 }
1492
1493 #[test]
1494 fn parse_deprecated() {
1495 let doc = "/** @deprecated use newMethod() instead */";
1496 let parsed = DocblockParser::parse(doc);
1497 assert!(parsed.is_deprecated);
1498 assert_eq!(
1499 parsed.deprecated.as_deref(),
1500 Some("use newMethod() instead")
1501 );
1502 }
1503
1504 #[test]
1505 fn parse_since_plain() {
1506 let parsed = DocblockParser::parse("/** @since 8.0 */");
1507 assert_eq!(parsed.since.as_deref(), Some("8.0"));
1508 assert_eq!(parsed.removed, None);
1509 }
1510
1511 #[test]
1512 fn parse_since_strips_trailing_description() {
1513 let parsed = DocblockParser::parse("/** @since 1.4.0 added \\$options argument */");
1516 assert_eq!(parsed.since.as_deref(), Some("1.4.0"));
1517 }
1518
1519 #[test]
1520 fn parse_removed_tag() {
1521 let parsed = DocblockParser::parse("/** @removed 8.0 use mb_convert_encoding */");
1522 assert_eq!(parsed.removed.as_deref(), Some("8.0"));
1523 }
1524
1525 #[test]
1526 fn parse_since_empty_body_is_none() {
1527 let parsed = DocblockParser::parse("/** @since */");
1528 assert_eq!(parsed.since, None);
1529 }
1530
1531 #[test]
1532 fn parse_description() {
1533 let doc = r#"/**
1534 * This is a description.
1535 * Spans two lines.
1536 * @param string $x
1537 */"#;
1538 let parsed = DocblockParser::parse(doc);
1539 assert!(parsed.description.contains("This is a description"));
1540 assert!(parsed.description.contains("Spans two lines"));
1541 }
1542
1543 #[test]
1544 fn parse_see_and_link() {
1545 let doc = "/** @see SomeClass\n * @link https://example.com */";
1546 let parsed = DocblockParser::parse(doc);
1547 assert_eq!(parsed.see.len(), 2);
1548 assert!(parsed.see.contains(&"SomeClass".to_string()));
1549 assert!(parsed.see.contains(&"https://example.com".to_string()));
1550 }
1551
1552 #[test]
1553 fn parse_mixin() {
1554 let doc = "/** @mixin SomeTrait */";
1555 let parsed = DocblockParser::parse(doc);
1556 assert_eq!(parsed.mixins, vec!["SomeTrait".to_string()]);
1557 }
1558
1559 #[test]
1560 fn parse_property_tags() {
1561 let doc = r#"/**
1562 * @property string $name
1563 * @property-read int $id
1564 * @property-write bool $active
1565 */"#;
1566 let parsed = DocblockParser::parse(doc);
1567 assert_eq!(parsed.properties.len(), 3);
1568 let name_prop = parsed.properties.iter().find(|p| p.name == "name").unwrap();
1569 assert_eq!(name_prop.type_hint, "string");
1570 assert!(!name_prop.read_only);
1571 assert!(!name_prop.write_only);
1572 let id_prop = parsed.properties.iter().find(|p| p.name == "id").unwrap();
1573 assert!(id_prop.read_only);
1574 let active_prop = parsed
1575 .properties
1576 .iter()
1577 .find(|p| p.name == "active")
1578 .unwrap();
1579 assert!(active_prop.write_only);
1580 }
1581
1582 #[test]
1583 fn parse_method_tag() {
1584 let doc = r#"/**
1585 * @method string getName()
1586 * @method static int create()
1587 */"#;
1588 let parsed = DocblockParser::parse(doc);
1589 assert_eq!(parsed.methods.len(), 2);
1590 let get_name = parsed.methods.iter().find(|m| m.name == "getName").unwrap();
1591 assert_eq!(get_name.return_type, "string");
1592 assert!(!get_name.is_static);
1593 let create = parsed.methods.iter().find(|m| m.name == "create").unwrap();
1594 assert!(create.is_static);
1595 }
1596
1597 #[test]
1598 fn parse_type_alias_tag() {
1599 let doc = "/** @psalm-type MyAlias = string|int */";
1600 let parsed = DocblockParser::parse(doc);
1601 assert_eq!(parsed.type_aliases.len(), 1);
1602 assert_eq!(parsed.type_aliases[0].name, "MyAlias");
1603 assert_eq!(parsed.type_aliases[0].type_expr, "string|int");
1604 }
1605
1606 #[test]
1607 fn parse_import_type_no_as() {
1608 let doc = "/** @psalm-import-type UserId from UserRepository */";
1609 let parsed = DocblockParser::parse(doc);
1610 assert_eq!(parsed.import_types.len(), 1);
1611 assert_eq!(parsed.import_types[0].original, "UserId");
1612 assert_eq!(parsed.import_types[0].local, "UserId");
1613 assert_eq!(parsed.import_types[0].from_class, "UserRepository");
1614 }
1615
1616 #[test]
1617 fn parse_import_type_with_as() {
1618 let doc = "/** @psalm-import-type UserId as LocalId from UserRepository */";
1619 let parsed = DocblockParser::parse(doc);
1620 assert_eq!(parsed.import_types.len(), 1);
1621 assert_eq!(parsed.import_types[0].original, "UserId");
1622 assert_eq!(parsed.import_types[0].local, "LocalId");
1623 assert_eq!(parsed.import_types[0].from_class, "UserRepository");
1624 }
1625
1626 #[test]
1627 fn parse_require_extends() {
1628 let doc = "/** @psalm-require-extends Model */";
1629 let parsed = DocblockParser::parse(doc);
1630 assert_eq!(parsed.require_extends, vec!["Model".to_string()]);
1631 }
1632
1633 #[test]
1634 fn parse_require_implements() {
1635 let doc = "/** @psalm-require-implements Countable */";
1636 let parsed = DocblockParser::parse(doc);
1637 assert_eq!(parsed.require_implements, vec!["Countable".to_string()]);
1638 }
1639
1640 #[test]
1641 fn parse_intersection_two_parts() {
1642 let u = parse_type_string("Iterator&Countable");
1643 assert_eq!(u.types.len(), 1);
1644 assert!(matches!(u.types[0], Atomic::TIntersection { ref parts } if parts.len() == 2));
1645 if let Atomic::TIntersection { parts } = &u.types[0] {
1646 assert!(parts[0].contains(
1647 |t| matches!(t, Atomic::TNamedObject { fqcn, .. } if fqcn.as_ref() == "Iterator")
1648 ));
1649 assert!(parts[1].contains(
1650 |t| matches!(t, Atomic::TNamedObject { fqcn, .. } if fqcn.as_ref() == "Countable")
1651 ));
1652 }
1653 }
1654
1655 #[test]
1656 fn parse_intersection_three_parts() {
1657 let u = parse_type_string("Iterator&Countable&Stringable");
1658 assert_eq!(u.types.len(), 1);
1659 let Atomic::TIntersection { parts } = &u.types[0] else {
1660 panic!("expected TIntersection");
1661 };
1662 assert_eq!(parts.len(), 3);
1663 assert!(parts[0].contains(
1664 |t| matches!(t, Atomic::TNamedObject { fqcn, .. } if fqcn.as_ref() == "Iterator")
1665 ));
1666 assert!(parts[1].contains(
1667 |t| matches!(t, Atomic::TNamedObject { fqcn, .. } if fqcn.as_ref() == "Countable")
1668 ));
1669 assert!(parts[2].contains(
1670 |t| matches!(t, Atomic::TNamedObject { fqcn, .. } if fqcn.as_ref() == "Stringable")
1671 ));
1672 }
1673
1674 #[test]
1675 fn parse_intersection_in_union_with_null() {
1676 let u = parse_type_string("Iterator&Countable|null");
1677 assert!(u.is_nullable());
1678 let intersection = u
1679 .types
1680 .iter()
1681 .find_map(|t| {
1682 if let Atomic::TIntersection { parts } = t {
1683 Some(parts)
1684 } else {
1685 None
1686 }
1687 })
1688 .expect("expected TIntersection");
1689 assert_eq!(intersection.len(), 2);
1690 assert!(intersection[0].contains(
1691 |t| matches!(t, Atomic::TNamedObject { fqcn, .. } if fqcn.as_ref() == "Iterator")
1692 ));
1693 assert!(intersection[1].contains(
1694 |t| matches!(t, Atomic::TNamedObject { fqcn, .. } if fqcn.as_ref() == "Countable")
1695 ));
1696 }
1697
1698 #[test]
1699 fn parse_intersection_in_union_with_scalar() {
1700 let u = parse_type_string("Iterator&Countable|string");
1701 assert!(u.contains(|t| matches!(t, Atomic::TString)));
1702 let intersection = u
1703 .types
1704 .iter()
1705 .find_map(|t| {
1706 if let Atomic::TIntersection { parts } = t {
1707 Some(parts)
1708 } else {
1709 None
1710 }
1711 })
1712 .expect("expected TIntersection");
1713 assert!(intersection[0].contains(
1714 |t| matches!(t, Atomic::TNamedObject { fqcn, .. } if fqcn.as_ref() == "Iterator")
1715 ));
1716 assert!(intersection[1].contains(
1717 |t| matches!(t, Atomic::TNamedObject { fqcn, .. } if fqcn.as_ref() == "Countable")
1718 ));
1719 }
1720
1721 #[test]
1722 fn validate_unclosed_generic_return() {
1723 let parsed = DocblockParser::parse("/** @return array< */");
1724 assert_eq!(parsed.invalid_annotations.len(), 1);
1725 assert!(
1726 parsed.invalid_annotations[0].contains("unclosed generic"),
1727 "got: {}",
1728 parsed.invalid_annotations[0]
1729 );
1730 }
1731
1732 #[test]
1733 fn parse_empty_generic_array_graceful() {
1734 let u = parse_type_string("array<>");
1735 assert!(u.contains(|t| matches!(t, Atomic::TArray { .. })));
1736 }
1737
1738 #[test]
1739 fn parse_empty_generic_iterable_graceful() {
1740 let u = parse_type_string("iterable<>");
1741 assert!(u.contains(|t| matches!(t, Atomic::TArray { .. })));
1742 }
1743
1744 #[test]
1745 fn parse_empty_generic_non_empty_array_graceful() {
1746 let u = parse_type_string("non-empty-array<>");
1747 assert!(u.contains(|t| matches!(t, Atomic::TNonEmptyArray { .. })));
1748 }
1749
1750 #[test]
1751 fn validate_variable_in_type_position_param() {
1752 let parsed = DocblockParser::parse("/** @param Foo|$invalid $x */");
1753 assert_eq!(parsed.invalid_annotations.len(), 1);
1754 assert!(
1755 parsed.invalid_annotations[0].contains("$invalid"),
1756 "got: {}",
1757 parsed.invalid_annotations[0]
1758 );
1759 }
1760
1761 #[test]
1762 fn validate_this_is_valid_in_type_position() {
1763 let parsed = DocblockParser::parse("/** @return $this */");
1764 assert!(
1765 parsed.invalid_annotations.is_empty(),
1766 "unexpected error: {:?}",
1767 parsed.invalid_annotations
1768 );
1769 }
1770
1771 #[test]
1772 fn validate_unclosed_generic_var() {
1773 let parsed = DocblockParser::parse("/** @var array<string */");
1774 assert_eq!(parsed.invalid_annotations.len(), 1);
1775 assert!(parsed.invalid_annotations[0].contains("@var"));
1776 }
1777
1778 #[test]
1779 fn validate_variable_in_template_bound() {
1780 let parsed = DocblockParser::parse("/** @template T of $invalid */");
1781 assert_eq!(parsed.invalid_annotations.len(), 1);
1782 assert!(parsed.invalid_annotations[0].contains("$invalid"));
1783 }
1784}