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 (key, value) = match params.len() {
686 n if n >= 2 => (
687 parse_type_string(params[0].trim()),
688 parse_type_string(params[1].trim()),
689 ),
690 1 => (
691 Type::single(Atomic::TInt),
692 parse_type_string(params[0].trim()),
693 ),
694 _ => (Type::single(Atomic::TInt), Type::mixed()),
695 };
696 Type::single(Atomic::TArray {
697 key: Box::new(key),
698 value: Box::new(value),
699 })
700 }
701 "list" | "non-empty-list" => {
702 let value = parse_type_string(inner.trim());
703 if name.to_lowercase().starts_with("non-empty") {
704 Type::single(Atomic::TNonEmptyList {
705 value: Box::new(value),
706 })
707 } else {
708 Type::single(Atomic::TList {
709 value: Box::new(value),
710 })
711 }
712 }
713 "non-empty-array" => {
714 let params = split_generics(inner);
715 let (key, value) = match params.len() {
716 n if n >= 2 => (
717 parse_type_string(params[0].trim()),
718 parse_type_string(params[1].trim()),
719 ),
720 1 => (
721 Type::single(Atomic::TInt),
722 parse_type_string(params[0].trim()),
723 ),
724 _ => (Type::single(Atomic::TInt), Type::mixed()),
725 };
726 Type::single(Atomic::TNonEmptyArray {
727 key: Box::new(key),
728 value: Box::new(value),
729 })
730 }
731 "iterable" => {
732 let params = split_generics(inner);
733 let value = match params.len() {
734 n if n >= 2 => parse_type_string(params[1].trim()),
735 1 => parse_type_string(params[0].trim()),
736 _ => Type::mixed(),
737 };
738 Type::single(Atomic::TArray {
739 key: Box::new(Type::single(Atomic::TMixed)),
740 value: Box::new(value),
741 })
742 }
743 "class-string" => Type::single(Atomic::TClassString(Some(
744 normalize_fqcn(inner.trim()).into(),
745 ))),
746 "int" => {
747 Type::single(Atomic::TIntRange {
749 min: None,
750 max: None,
751 })
752 }
753 _ => {
755 let params: Vec<Type> = split_generics(inner)
756 .iter()
757 .map(|p| parse_type_string(p.trim()))
758 .collect();
759 Type::single(Atomic::TNamedObject {
760 fqcn: normalize_fqcn(name).into(),
761 type_params: mir_types::union::vec_to_type_params(params),
762 })
763 }
764 }
765}
766
767fn parse_keyed_array(inner: &str, is_list: bool) -> Type {
768 use mir_types::atomic::KeyedProperty;
769 let mut properties: IndexMap<ArrayKey, KeyedProperty> = IndexMap::new();
770 let mut is_open = false;
771 let mut auto_index = 0i64;
772
773 for item in split_generics(inner) {
774 let item = item.trim();
775 if item.is_empty() {
776 continue;
777 }
778 if item == "..." {
779 is_open = true;
780 continue;
781 }
782 let colon_pos = {
784 let mut depth = 0i32;
785 let mut found = None;
786 for (i, ch) in item.char_indices() {
787 match ch {
788 '<' | '(' | '{' => depth += 1,
789 '>' | ')' | '}' => depth -= 1,
790 ':' if depth == 0 => {
791 found = Some(i);
792 break;
793 }
794 _ => {}
795 }
796 }
797 found
798 };
799 if let Some(colon) = colon_pos {
800 let key_part = item[..colon].trim();
801 let ty_part = item[colon + 1..].trim();
802 let optional = key_part.ends_with('?');
803 let key_str = key_part.trim_end_matches('?').trim();
804 let key = if let Ok(n) = key_str.parse::<i64>() {
805 ArrayKey::Int(n)
806 } else {
807 ArrayKey::String(Arc::from(key_str))
808 };
809 properties.insert(
810 key,
811 KeyedProperty {
812 ty: parse_type_string(ty_part),
813 optional,
814 },
815 );
816 } else {
817 properties.insert(
818 ArrayKey::Int(auto_index),
819 KeyedProperty {
820 ty: parse_type_string(item),
821 optional: false,
822 },
823 );
824 auto_index += 1;
825 }
826 }
827
828 Type::single(Atomic::TKeyedArray {
829 properties,
830 is_open,
831 is_list,
832 })
833}
834
835fn parse_callable_syntax(s: &str) -> Option<Type> {
836 let s = s.trim_start_matches('\\');
837 let lower = s.to_lowercase();
838 let is_closure = lower.starts_with("closure");
839 let is_callable = lower.starts_with("callable");
840 if !is_closure && !is_callable {
841 return None;
842 }
843 let prefix_len = if is_closure {
844 "closure".len()
845 } else {
846 "callable".len()
847 };
848 let rest = s[prefix_len..].trim_start();
849 if !rest.starts_with('(') {
850 return None;
851 }
852 let close = find_matching_paren(rest)?;
853 let params_str = &rest[1..close];
854 let after = rest[close + 1..].trim();
855 let return_type = after
856 .strip_prefix(':')
857 .map(|ret_str| Box::new(parse_type_string(ret_str.trim())));
858 let params: Vec<mir_types::atomic::FnParam> = split_generics(params_str)
859 .into_iter()
860 .enumerate()
861 .filter(|(_, p)| !p.trim().is_empty())
862 .map(|(i, p)| {
863 let p = p.trim();
864 let (ty_str, name) = if let Some(dollar) = p.rfind('$') {
865 (p[..dollar].trim(), p[dollar + 1..].to_string())
866 } else {
867 (p, format!("arg{i}"))
868 };
869 mir_types::atomic::FnParam {
870 name: name.into(),
871 ty: Some(mir_types::SimpleType::from_union(parse_type_string(ty_str))),
872 default: None,
873 is_variadic: false,
874 is_byref: false,
875 is_optional: false,
876 }
877 })
878 .collect();
879 if is_closure {
880 Some(Type::single(Atomic::TClosure {
881 params,
882 return_type: return_type.unwrap_or_else(|| Box::new(Type::single(Atomic::TVoid))),
883 this_type: None,
884 }))
885 } else {
886 Some(Type::single(Atomic::TCallable {
887 params: Some(params),
888 return_type,
889 }))
890 }
891}
892
893fn find_matching_paren(s: &str) -> Option<usize> {
894 if !s.starts_with('(') {
895 return None;
896 }
897 let mut depth = 0i32;
898 for (i, ch) in s.char_indices() {
899 match ch {
900 '(' | '<' | '{' => depth += 1,
901 ')' | '>' | '}' => {
902 depth -= 1;
903 if depth == 0 {
904 return Some(i);
905 }
906 }
907 _ => {}
908 }
909 }
910 None
911}
912
913fn parse_template_line(_tag_name: &str, body: Option<String>) -> Option<(String, Option<String>)> {
919 let body = body?;
920 if let Some((name, bound)) = body.split_once(" of ").or_else(|| body.split_once(" as ")) {
921 Some((name.trim().to_string(), Some(bound.trim().to_string())))
922 } else {
923 Some((body.trim().to_string(), None))
924 }
925}
926
927fn extract_description(text: &str) -> String {
929 let mut desc_lines: Vec<&str> = Vec::new();
930 for line in text.lines() {
931 let l = line.trim();
932 let l = l.trim_start_matches("/**").trim();
933 let l = l.trim_end_matches("*/").trim();
934 let l = l.trim_start_matches("*/").trim();
935 let l = l.strip_prefix("* ").unwrap_or(l.trim_start_matches('*'));
936 let l = l.trim();
937 if l.starts_with('@') {
938 break;
939 }
940 if !l.is_empty() {
941 desc_lines.push(l);
942 }
943 }
944 desc_lines.join(" ")
945}
946
947fn parse_import_type(body: &str) -> Option<DocImportType> {
953 let (before_from, from_class_raw) = body.split_once(" from ")?;
955 let from_class = from_class_raw.trim().trim_start_matches('\\').to_string();
956 if from_class.is_empty() {
957 return None;
958 }
959 let (original, local) = if let Some((orig, loc)) = before_from.split_once(" as ") {
961 (orig.trim().to_string(), loc.trim().to_string())
962 } else {
963 let name = before_from.trim().to_string();
964 (name.clone(), name)
965 };
966 if original.is_empty() || local.is_empty() {
967 return None;
968 }
969 Some(DocImportType {
970 original,
971 local,
972 from_class,
973 })
974}
975
976fn parse_param_line(s: &str) -> Option<(String, String)> {
977 let mut best_split: Option<(String, String)> = None;
984
985 for (i, ch) in s.char_indices() {
986 if ch.is_whitespace() {
987 let after = &s[i..].trim_start();
989 if after.starts_with('$') {
990 let mut var_parts = after.split(char::is_whitespace);
992 if let Some(name_with_dollar) = var_parts.next() {
993 let name = name_with_dollar.trim_start_matches('$').to_string();
994 if !name.is_empty() {
995 let type_part = s[..i].trim().to_string();
996 if !type_part.is_empty() {
997 best_split = Some((type_part, name));
999 }
1000 }
1001 }
1002 }
1003 }
1004 }
1005
1006 best_split
1007}
1008
1009fn extract_return_type(s: &str) -> String {
1010 let mut depth: i32 = 0;
1019 let mut current_token = String::new();
1020
1021 for ch in s.chars() {
1022 match ch {
1023 '<' | '(' | '{' => {
1024 depth += 1;
1025 current_token.push(ch);
1026 }
1027 '>' | ')' | '}' => {
1028 depth = (depth - 1).max(0);
1029 current_token.push(ch);
1030 }
1031 _ if ch.is_whitespace() && depth == 0 => {
1032 break;
1033 }
1034 _ => {
1035 current_token.push(ch);
1036 }
1037 }
1038 }
1039
1040 if current_token.ends_with(':') {
1044 let offset = current_token.len();
1045 let rest = s[offset..].trim_start();
1046 if !rest.is_empty() {
1047 let ret_type = extract_return_type(rest);
1048 current_token.push_str(&ret_type);
1049 }
1050 }
1051
1052 current_token.trim().to_string()
1053}
1054
1055fn split_union(s: &str) -> Vec<String> {
1056 let mut parts = Vec::new();
1057 let mut depth = 0;
1058 let mut current = String::new();
1059 for ch in s.chars() {
1060 match ch {
1061 '<' | '(' | '{' => {
1062 depth += 1;
1063 current.push(ch);
1064 }
1065 '>' | ')' | '}' => {
1066 depth -= 1;
1067 current.push(ch);
1068 }
1069 '|' if depth == 0 => {
1070 parts.push(current.trim().to_string());
1071 current = String::new();
1072 }
1073 _ => current.push(ch),
1074 }
1075 }
1076 if !current.trim().is_empty() {
1077 parts.push(current.trim().to_string());
1078 }
1079 parts
1080}
1081
1082fn split_intersection(s: &str) -> Vec<String> {
1084 let mut parts = Vec::new();
1085 let mut depth = 0i32;
1086 let mut current = String::new();
1087 for ch in s.chars() {
1088 match ch {
1089 '<' | '(' | '{' => {
1090 depth += 1;
1091 current.push(ch);
1092 }
1093 '>' | ')' | '}' => {
1094 depth -= 1;
1095 current.push(ch);
1096 }
1097 '&' if depth == 0 => {
1098 parts.push(current.trim().to_string());
1099 current = String::new();
1100 }
1101 _ => current.push(ch),
1102 }
1103 }
1104 if !current.trim().is_empty() {
1105 parts.push(current.trim().to_string());
1106 }
1107 parts
1108}
1109
1110fn is_balanced_parens(s: &str) -> bool {
1114 if !s.starts_with('(') || !s.ends_with(')') {
1115 return false;
1116 }
1117 let mut depth = 0i32;
1118 let chars: Vec<char> = s.chars().collect();
1119 let last = chars.len() - 1;
1120 for (i, ch) in chars.iter().enumerate() {
1121 match ch {
1122 '(' => depth += 1,
1123 ')' => {
1124 depth -= 1;
1125 if depth == 0 && i < last {
1128 return false;
1129 }
1130 }
1131 _ => {}
1132 }
1133 }
1134 depth == 0
1135}
1136
1137fn split_generics(s: &str) -> Vec<String> {
1138 let mut parts = Vec::new();
1139 let mut depth = 0;
1140 let mut current = String::new();
1141 for ch in s.chars() {
1142 match ch {
1143 '<' | '(' | '{' => {
1144 depth += 1;
1145 current.push(ch);
1146 }
1147 '>' | ')' | '}' => {
1148 depth -= 1;
1149 current.push(ch);
1150 }
1151 ',' if depth == 0 => {
1152 parts.push(current.trim().to_string());
1153 current = String::new();
1154 }
1155 _ => current.push(ch),
1156 }
1157 }
1158 if !current.trim().is_empty() {
1159 parts.push(current.trim().to_string());
1160 }
1161 parts
1162}
1163
1164fn extract_type_prefix(s: &str) -> &str {
1167 let mut depth = 0i32;
1168 let mut end = s.len();
1169 for (i, ch) in s.char_indices() {
1170 match ch {
1171 '<' | '(' | '{' => depth += 1,
1172 '>' | ')' | '}' => depth -= 1,
1173 _ if ch.is_whitespace() && depth == 0 => {
1174 end = i;
1175 break;
1176 }
1177 _ => {}
1178 }
1179 }
1180 &s[..end]
1181}
1182
1183fn is_inside_generics(s: &str) -> bool {
1184 let mut depth = 0i32;
1185 for ch in s.chars() {
1186 match ch {
1187 '<' | '(' | '{' => depth += 1,
1188 '>' | ')' | '}' => depth -= 1,
1189 _ => {}
1190 }
1191 }
1192 depth != 0
1193}
1194
1195fn parse_conditional_type(s: &str) -> Option<Type> {
1198 let is_pos = s.find(" is ")?;
1199 let param_raw = s[..is_pos].trim();
1200
1201 let param_name_str: &str = if let Some(name) = param_raw.strip_prefix('$') {
1203 if name.is_empty() {
1204 return None;
1205 }
1206 name
1207 } else {
1208 if param_raw.is_empty()
1211 || !param_raw.starts_with(|c: char| c.is_alphabetic() || c == '_')
1212 || !param_raw.chars().all(|c| c.is_alphanumeric() || c == '_')
1213 || !s.contains('?')
1214 {
1215 return None;
1216 }
1217 param_raw
1218 };
1219 let param_name = Some(mir_types::Name::new(param_name_str));
1220 let after_is = s[is_pos + 4..].trim();
1221 let q_pos = find_char_at_depth(after_is, '?')?;
1222 let subject_str = after_is[..q_pos].trim();
1223 let rest = after_is[q_pos + 1..].trim();
1224 let colon_pos = find_char_at_depth(rest, ':')?;
1225 let true_str = rest[..colon_pos].trim();
1226 let false_str = rest[colon_pos + 1..].trim();
1227 Some(Type::single(Atomic::TConditional {
1228 param_name,
1229 subject: Box::new(parse_type_string(subject_str)),
1230 if_true: Box::new(parse_type_string(true_str)),
1231 if_false: Box::new(parse_type_string(false_str)),
1232 }))
1233}
1234
1235fn find_char_at_depth(s: &str, target: char) -> Option<usize> {
1237 let mut depth = 0i32;
1238 for (i, ch) in s.char_indices() {
1239 match ch {
1240 '<' | '(' | '{' => depth += 1,
1241 '>' | ')' | '}' => depth -= 1,
1242 _ if ch == target && depth == 0 => return Some(i),
1243 _ => {}
1244 }
1245 }
1246 None
1247}
1248
1249fn normalize_fqcn(s: &str) -> String {
1250 s.trim_start_matches('\\').to_string()
1252}
1253
1254fn validate_type_str(s: &str, tag: &str) -> Option<String> {
1260 let s = s.trim();
1261 if s.is_empty() {
1262 return None;
1263 }
1264 if is_inside_generics(s) {
1265 return Some(format!("@{tag} has unclosed generic type `{s}`"));
1266 }
1267 let is_callable_type = s.to_lowercase().contains("callable") || s.contains("Closure");
1269 if !is_callable_type && has_empty_generics(s) {
1270 return Some(format!("@{tag} has empty generic type parameter in `{s}`"));
1271 }
1272 for part in split_union(s) {
1273 let p = part.trim();
1274 if p.starts_with('$') && p != "$this" {
1275 return Some(format!("@{tag} contains variable `{p}` in type position"));
1276 }
1277 }
1278 None
1279}
1280
1281fn has_empty_generics(s: &str) -> bool {
1282 let mut depth = 0;
1283 let mut prev_open = false;
1284 for ch in s.chars() {
1285 match ch {
1286 '<' | '(' | '{' => {
1287 if prev_open && depth == 0 {
1288 return true;
1289 }
1290 prev_open = true;
1291 depth += 1;
1292 }
1293 '>' | ')' | '}' => {
1294 depth -= 1;
1295 if depth == 0 {
1296 if prev_open {
1297 return true;
1298 }
1299 prev_open = false;
1300 }
1301 }
1302 c if !c.is_whitespace() => {
1303 prev_open = false;
1304 }
1305 _ => {}
1306 }
1307 }
1308 false
1309}
1310
1311fn parse_method_line(s: &str) -> Option<DocMethod> {
1313 let mut rest = s.trim();
1314 if rest.is_empty() {
1315 return None;
1316 }
1317 let is_static = rest
1318 .split_whitespace()
1319 .next()
1320 .map(|w| w.eq_ignore_ascii_case("static"))
1321 .unwrap_or(false);
1322 if is_static {
1323 rest = rest["static".len()..].trim_start();
1324 }
1325
1326 let open = rest.find('(').unwrap_or(rest.len());
1327 let prefix = rest[..open].trim();
1328 let mut parts: Vec<&str> = prefix.split_whitespace().collect();
1329 let name = parts.pop()?.to_string();
1330 if name.is_empty() {
1331 return None;
1332 }
1333 let return_type = parts.join(" ");
1334 Some(DocMethod {
1335 return_type,
1336 name,
1337 is_static,
1338 params: parse_method_params(rest),
1339 })
1340}
1341
1342fn parse_method_params(name_part: &str) -> Vec<DocMethodParam> {
1343 let Some(open) = name_part.find('(') else {
1344 return vec![];
1345 };
1346 let Some(close) = name_part.rfind(')') else {
1347 return vec![];
1348 };
1349 let inner = name_part[open + 1..close].trim();
1350 if inner.is_empty() {
1351 return vec![];
1352 }
1353
1354 split_generics(inner)
1355 .into_iter()
1356 .filter_map(|param| parse_method_param(¶m))
1357 .collect()
1358}
1359
1360fn parse_method_param(param: &str) -> Option<DocMethodParam> {
1361 let before_default = param.split('=').next()?.trim();
1362 let is_optional = param.contains('=');
1363 let mut tokens: Vec<&str> = before_default.split_whitespace().collect();
1364 let raw_name = tokens.pop()?;
1365 let is_variadic = raw_name.contains("...");
1366 let is_byref = raw_name.contains('&');
1367 let name = raw_name
1368 .trim_start_matches('&')
1369 .trim_start_matches("...")
1370 .trim_start_matches('&')
1371 .trim_start_matches('$')
1372 .to_string();
1373 if name.is_empty() {
1374 return None;
1375 }
1376 Some(DocMethodParam {
1377 name,
1378 type_hint: tokens.join(" "),
1379 is_variadic,
1380 is_byref,
1381 is_optional: is_optional || is_variadic,
1382 })
1383}
1384
1385#[cfg(test)]
1390mod tests {
1391 use super::*;
1392 use mir_types::Atomic;
1393
1394 #[test]
1395 fn parse_string() {
1396 let u = parse_type_string("string");
1397 assert_eq!(u.types.len(), 1);
1398 assert!(matches!(u.types[0], Atomic::TString));
1399 }
1400
1401 #[test]
1402 fn parse_nullable_string() {
1403 let u = parse_type_string("?string");
1404 assert!(u.is_nullable());
1405 assert!(u.contains(|t| matches!(t, Atomic::TString)));
1406 }
1407
1408 #[test]
1409 fn parse_union() {
1410 let u = parse_type_string("string|int|null");
1411 assert!(u.contains(|t| matches!(t, Atomic::TString)));
1412 assert!(u.contains(|t| matches!(t, Atomic::TInt)));
1413 assert!(u.is_nullable());
1414 }
1415
1416 #[test]
1417 fn parse_array_of_string() {
1418 let u = parse_type_string("array<string>");
1419 assert!(u.contains(|t| matches!(t, Atomic::TArray { .. })));
1420 }
1421
1422 #[test]
1423 fn parse_list_of_int() {
1424 let u = parse_type_string("list<int>");
1425 assert!(u.contains(|t| matches!(t, Atomic::TList { .. })));
1426 }
1427
1428 #[test]
1429 fn parse_named_class() {
1430 let u = parse_type_string("Foo\\Bar");
1431 assert!(u.contains(
1432 |t| matches!(t, Atomic::TNamedObject { fqcn, .. } if fqcn.as_ref() == "Foo\\Bar")
1433 ));
1434 }
1435
1436 #[test]
1437 fn parse_docblock_param_return() {
1438 let doc = r#"/**
1439 * @param string $name
1440 * @param int $age
1441 * @return bool
1442 */"#;
1443 let parsed = DocblockParser::parse(doc);
1444 assert_eq!(parsed.params.len(), 2);
1445 assert!(parsed.return_type.is_some());
1446 let ret = parsed.return_type.unwrap();
1447 assert!(ret.contains(|t| matches!(t, Atomic::TBool)));
1448 }
1449
1450 #[test]
1451 fn parse_template() {
1452 let doc = "/** @template T of object */";
1453 let parsed = DocblockParser::parse(doc);
1454 assert_eq!(parsed.templates.len(), 1);
1455 assert_eq!(parsed.templates[0].0, "T");
1456 assert!(parsed.templates[0].1.is_some());
1457 assert_eq!(parsed.templates[0].2, Variance::Invariant);
1458 }
1459
1460 #[test]
1461 fn parse_template_covariant() {
1462 let doc = "/** @template-covariant T */";
1463 let parsed = DocblockParser::parse(doc);
1464 assert_eq!(parsed.templates.len(), 1);
1465 assert_eq!(parsed.templates[0].0, "T");
1466 assert_eq!(parsed.templates[0].2, Variance::Covariant);
1467 }
1468
1469 #[test]
1470 fn parse_template_contravariant() {
1471 let doc = "/** @template-contravariant T */";
1472 let parsed = DocblockParser::parse(doc);
1473 assert_eq!(parsed.templates.len(), 1);
1474 assert_eq!(parsed.templates[0].0, "T");
1475 assert_eq!(parsed.templates[0].2, Variance::Contravariant);
1476 }
1477
1478 #[test]
1479 fn parse_deprecated() {
1480 let doc = "/** @deprecated use newMethod() instead */";
1481 let parsed = DocblockParser::parse(doc);
1482 assert!(parsed.is_deprecated);
1483 assert_eq!(
1484 parsed.deprecated.as_deref(),
1485 Some("use newMethod() instead")
1486 );
1487 }
1488
1489 #[test]
1490 fn parse_since_plain() {
1491 let parsed = DocblockParser::parse("/** @since 8.0 */");
1492 assert_eq!(parsed.since.as_deref(), Some("8.0"));
1493 assert_eq!(parsed.removed, None);
1494 }
1495
1496 #[test]
1497 fn parse_since_strips_trailing_description() {
1498 let parsed = DocblockParser::parse("/** @since 1.4.0 added \\$options argument */");
1501 assert_eq!(parsed.since.as_deref(), Some("1.4.0"));
1502 }
1503
1504 #[test]
1505 fn parse_removed_tag() {
1506 let parsed = DocblockParser::parse("/** @removed 8.0 use mb_convert_encoding */");
1507 assert_eq!(parsed.removed.as_deref(), Some("8.0"));
1508 }
1509
1510 #[test]
1511 fn parse_since_empty_body_is_none() {
1512 let parsed = DocblockParser::parse("/** @since */");
1513 assert_eq!(parsed.since, None);
1514 }
1515
1516 #[test]
1517 fn parse_description() {
1518 let doc = r#"/**
1519 * This is a description.
1520 * Spans two lines.
1521 * @param string $x
1522 */"#;
1523 let parsed = DocblockParser::parse(doc);
1524 assert!(parsed.description.contains("This is a description"));
1525 assert!(parsed.description.contains("Spans two lines"));
1526 }
1527
1528 #[test]
1529 fn parse_see_and_link() {
1530 let doc = "/** @see SomeClass\n * @link https://example.com */";
1531 let parsed = DocblockParser::parse(doc);
1532 assert_eq!(parsed.see.len(), 2);
1533 assert!(parsed.see.contains(&"SomeClass".to_string()));
1534 assert!(parsed.see.contains(&"https://example.com".to_string()));
1535 }
1536
1537 #[test]
1538 fn parse_mixin() {
1539 let doc = "/** @mixin SomeTrait */";
1540 let parsed = DocblockParser::parse(doc);
1541 assert_eq!(parsed.mixins, vec!["SomeTrait".to_string()]);
1542 }
1543
1544 #[test]
1545 fn parse_property_tags() {
1546 let doc = r#"/**
1547 * @property string $name
1548 * @property-read int $id
1549 * @property-write bool $active
1550 */"#;
1551 let parsed = DocblockParser::parse(doc);
1552 assert_eq!(parsed.properties.len(), 3);
1553 let name_prop = parsed.properties.iter().find(|p| p.name == "name").unwrap();
1554 assert_eq!(name_prop.type_hint, "string");
1555 assert!(!name_prop.read_only);
1556 assert!(!name_prop.write_only);
1557 let id_prop = parsed.properties.iter().find(|p| p.name == "id").unwrap();
1558 assert!(id_prop.read_only);
1559 let active_prop = parsed
1560 .properties
1561 .iter()
1562 .find(|p| p.name == "active")
1563 .unwrap();
1564 assert!(active_prop.write_only);
1565 }
1566
1567 #[test]
1568 fn parse_method_tag() {
1569 let doc = r#"/**
1570 * @method string getName()
1571 * @method static int create()
1572 */"#;
1573 let parsed = DocblockParser::parse(doc);
1574 assert_eq!(parsed.methods.len(), 2);
1575 let get_name = parsed.methods.iter().find(|m| m.name == "getName").unwrap();
1576 assert_eq!(get_name.return_type, "string");
1577 assert!(!get_name.is_static);
1578 let create = parsed.methods.iter().find(|m| m.name == "create").unwrap();
1579 assert!(create.is_static);
1580 }
1581
1582 #[test]
1583 fn parse_type_alias_tag() {
1584 let doc = "/** @psalm-type MyAlias = string|int */";
1585 let parsed = DocblockParser::parse(doc);
1586 assert_eq!(parsed.type_aliases.len(), 1);
1587 assert_eq!(parsed.type_aliases[0].name, "MyAlias");
1588 assert_eq!(parsed.type_aliases[0].type_expr, "string|int");
1589 }
1590
1591 #[test]
1592 fn parse_import_type_no_as() {
1593 let doc = "/** @psalm-import-type UserId from UserRepository */";
1594 let parsed = DocblockParser::parse(doc);
1595 assert_eq!(parsed.import_types.len(), 1);
1596 assert_eq!(parsed.import_types[0].original, "UserId");
1597 assert_eq!(parsed.import_types[0].local, "UserId");
1598 assert_eq!(parsed.import_types[0].from_class, "UserRepository");
1599 }
1600
1601 #[test]
1602 fn parse_import_type_with_as() {
1603 let doc = "/** @psalm-import-type UserId as LocalId from UserRepository */";
1604 let parsed = DocblockParser::parse(doc);
1605 assert_eq!(parsed.import_types.len(), 1);
1606 assert_eq!(parsed.import_types[0].original, "UserId");
1607 assert_eq!(parsed.import_types[0].local, "LocalId");
1608 assert_eq!(parsed.import_types[0].from_class, "UserRepository");
1609 }
1610
1611 #[test]
1612 fn parse_require_extends() {
1613 let doc = "/** @psalm-require-extends Model */";
1614 let parsed = DocblockParser::parse(doc);
1615 assert_eq!(parsed.require_extends, vec!["Model".to_string()]);
1616 }
1617
1618 #[test]
1619 fn parse_require_implements() {
1620 let doc = "/** @psalm-require-implements Countable */";
1621 let parsed = DocblockParser::parse(doc);
1622 assert_eq!(parsed.require_implements, vec!["Countable".to_string()]);
1623 }
1624
1625 #[test]
1626 fn parse_intersection_two_parts() {
1627 let u = parse_type_string("Iterator&Countable");
1628 assert_eq!(u.types.len(), 1);
1629 assert!(matches!(u.types[0], Atomic::TIntersection { ref parts } if parts.len() == 2));
1630 if let Atomic::TIntersection { parts } = &u.types[0] {
1631 assert!(parts[0].contains(
1632 |t| matches!(t, Atomic::TNamedObject { fqcn, .. } if fqcn.as_ref() == "Iterator")
1633 ));
1634 assert!(parts[1].contains(
1635 |t| matches!(t, Atomic::TNamedObject { fqcn, .. } if fqcn.as_ref() == "Countable")
1636 ));
1637 }
1638 }
1639
1640 #[test]
1641 fn parse_intersection_three_parts() {
1642 let u = parse_type_string("Iterator&Countable&Stringable");
1643 assert_eq!(u.types.len(), 1);
1644 let Atomic::TIntersection { parts } = &u.types[0] else {
1645 panic!("expected TIntersection");
1646 };
1647 assert_eq!(parts.len(), 3);
1648 assert!(parts[0].contains(
1649 |t| matches!(t, Atomic::TNamedObject { fqcn, .. } if fqcn.as_ref() == "Iterator")
1650 ));
1651 assert!(parts[1].contains(
1652 |t| matches!(t, Atomic::TNamedObject { fqcn, .. } if fqcn.as_ref() == "Countable")
1653 ));
1654 assert!(parts[2].contains(
1655 |t| matches!(t, Atomic::TNamedObject { fqcn, .. } if fqcn.as_ref() == "Stringable")
1656 ));
1657 }
1658
1659 #[test]
1660 fn parse_intersection_in_union_with_null() {
1661 let u = parse_type_string("Iterator&Countable|null");
1662 assert!(u.is_nullable());
1663 let intersection = u
1664 .types
1665 .iter()
1666 .find_map(|t| {
1667 if let Atomic::TIntersection { parts } = t {
1668 Some(parts)
1669 } else {
1670 None
1671 }
1672 })
1673 .expect("expected TIntersection");
1674 assert_eq!(intersection.len(), 2);
1675 assert!(intersection[0].contains(
1676 |t| matches!(t, Atomic::TNamedObject { fqcn, .. } if fqcn.as_ref() == "Iterator")
1677 ));
1678 assert!(intersection[1].contains(
1679 |t| matches!(t, Atomic::TNamedObject { fqcn, .. } if fqcn.as_ref() == "Countable")
1680 ));
1681 }
1682
1683 #[test]
1684 fn parse_intersection_in_union_with_scalar() {
1685 let u = parse_type_string("Iterator&Countable|string");
1686 assert!(u.contains(|t| matches!(t, Atomic::TString)));
1687 let intersection = u
1688 .types
1689 .iter()
1690 .find_map(|t| {
1691 if let Atomic::TIntersection { parts } = t {
1692 Some(parts)
1693 } else {
1694 None
1695 }
1696 })
1697 .expect("expected TIntersection");
1698 assert!(intersection[0].contains(
1699 |t| matches!(t, Atomic::TNamedObject { fqcn, .. } if fqcn.as_ref() == "Iterator")
1700 ));
1701 assert!(intersection[1].contains(
1702 |t| matches!(t, Atomic::TNamedObject { fqcn, .. } if fqcn.as_ref() == "Countable")
1703 ));
1704 }
1705
1706 #[test]
1707 fn validate_unclosed_generic_return() {
1708 let parsed = DocblockParser::parse("/** @return array< */");
1709 assert_eq!(parsed.invalid_annotations.len(), 1);
1710 assert!(
1711 parsed.invalid_annotations[0].contains("unclosed generic"),
1712 "got: {}",
1713 parsed.invalid_annotations[0]
1714 );
1715 }
1716
1717 #[test]
1718 fn parse_empty_generic_array_graceful() {
1719 let u = parse_type_string("array<>");
1720 assert!(u.contains(|t| matches!(t, Atomic::TArray { .. })));
1721 }
1722
1723 #[test]
1724 fn parse_empty_generic_iterable_graceful() {
1725 let u = parse_type_string("iterable<>");
1726 assert!(u.contains(|t| matches!(t, Atomic::TArray { .. })));
1727 }
1728
1729 #[test]
1730 fn parse_empty_generic_non_empty_array_graceful() {
1731 let u = parse_type_string("non-empty-array<>");
1732 assert!(u.contains(|t| matches!(t, Atomic::TNonEmptyArray { .. })));
1733 }
1734
1735 #[test]
1736 fn validate_variable_in_type_position_param() {
1737 let parsed = DocblockParser::parse("/** @param Foo|$invalid $x */");
1738 assert_eq!(parsed.invalid_annotations.len(), 1);
1739 assert!(
1740 parsed.invalid_annotations[0].contains("$invalid"),
1741 "got: {}",
1742 parsed.invalid_annotations[0]
1743 );
1744 }
1745
1746 #[test]
1747 fn validate_this_is_valid_in_type_position() {
1748 let parsed = DocblockParser::parse("/** @return $this */");
1749 assert!(
1750 parsed.invalid_annotations.is_empty(),
1751 "unexpected error: {:?}",
1752 parsed.invalid_annotations
1753 );
1754 }
1755
1756 #[test]
1757 fn validate_unclosed_generic_var() {
1758 let parsed = DocblockParser::parse("/** @var array<string */");
1759 assert_eq!(parsed.invalid_annotations.len(), 1);
1760 assert!(parsed.invalid_annotations[0].contains("@var"));
1761 }
1762
1763 #[test]
1764 fn validate_variable_in_template_bound() {
1765 let parsed = DocblockParser::parse("/** @template T of $invalid */");
1766 assert_eq!(parsed.invalid_annotations.len(), 1);
1767 assert!(parsed.invalid_annotations[0].contains("$invalid"));
1768 }
1769}