1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
/// Call analyzer — resolves function/method calls, checks arguments, returns
/// the inferred return type.
use std::sync::Arc;
use php_ast::ast::{ExprKind, MethodCallExpr, FunctionCallExpr, StaticMethodCallExpr};
use php_ast::Span;
use mir_codebase::storage::{FnParam, MethodStorage, Visibility};
use mir_issues::{IssueKind, Severity};
use mir_types::{Atomic, Union};
use crate::context::Context;
use crate::expr::ExpressionAnalyzer;
use crate::generic::{check_template_bounds, infer_template_bindings};
use crate::taint::{classify_sink, is_expr_tainted, SinkKind};
// ---------------------------------------------------------------------------
// CallAnalyzer
// ---------------------------------------------------------------------------
pub struct CallAnalyzer;
impl CallAnalyzer {
// -----------------------------------------------------------------------
// Function calls: name(args)
// -----------------------------------------------------------------------
pub fn analyze_function_call<'a, 'arena, 'src>(
ea: &mut ExpressionAnalyzer<'a>,
call: &FunctionCallExpr<'arena, 'src>,
ctx: &mut Context,
span: Span,
) -> Union {
// Resolve function name first (needed for sink check before arg eval)
let fn_name = match &call.name.kind {
ExprKind::Identifier(name) => name.as_ref().to_string(),
ExprKind::Variable(_) => {
// dynamic call — evaluate args anyway
for arg in call.args.iter() { ea.analyze(&arg.value, ctx); }
return Union::mixed();
}
_ => {
for arg in call.args.iter() { ea.analyze(&arg.value, ctx); }
return Union::mixed();
}
};
// Taint sink check (M19): before evaluating args so we can inspect raw exprs
if let Some(sink_kind) = classify_sink(&fn_name) {
for arg in call.args.iter() {
if is_expr_tainted(&arg.value, ctx) {
let issue_kind = match sink_kind {
SinkKind::Html => IssueKind::TaintedHtml,
SinkKind::Sql => IssueKind::TaintedSql,
SinkKind::Shell => IssueKind::TaintedShell,
};
ea.emit(issue_kind, Severity::Error, span);
break; // one report per call site is enough
}
}
}
// Resolve the function name: try namespace-qualified first, then global fallback.
// PHP resolves `foo()` as `\App\Ns\foo` first, then `\foo` if not found.
// A leading `\` means explicit global namespace (e.g. `\assert` = global `assert`).
let fn_name = fn_name.strip_prefix('\\').map(|s| s.to_string()).unwrap_or(fn_name);
let resolved_fn_name: String = {
let qualified = ea.codebase.resolve_class_name(&ea.file, &fn_name);
if ea.codebase.functions.contains_key(qualified.as_str()) {
qualified
} else if ea.codebase.functions.contains_key(fn_name.as_str()) {
fn_name.clone()
} else {
// Keep the qualified name so the "unknown" error is informative
qualified
}
};
// Pre-mark by-reference parameter variables as defined BEFORE evaluating args,
// so that passing an uninitialized variable to a by-ref param does not emit
// UndefinedVariable (the function will initialize it).
if let Some(func) = ea.codebase.functions.get(resolved_fn_name.as_str()) {
for (i, param) in func.params.iter().enumerate() {
if param.is_byref {
if let Some(arg) = call.args.get(i) {
if let ExprKind::Variable(name) = &arg.value.kind {
let var_name = name.as_ref().trim_start_matches('$');
if !ctx.var_is_defined(var_name) {
ctx.set_var(var_name, Union::mixed());
}
}
}
}
}
}
// Evaluate all arguments
let arg_types: Vec<Union> = call
.args
.iter()
.map(|arg| {
let ty = ea.analyze(&arg.value, ctx);
if arg.unpack { spread_element_type(&ty) } else { ty }
})
.collect();
// Look up user-defined function in codebase
if let Some(func) = ea.codebase.functions.get(resolved_fn_name.as_str()) {
ea.codebase.mark_function_referenced(&func.fqn.clone());
let params = func.params.clone();
let template_params = func.template_params.clone();
let return_ty_raw = func.effective_return_type().cloned().unwrap_or_else(Union::mixed);
check_args(
ea,
&fn_name,
¶ms,
&arg_types,
&call.args.iter().map(|a| a.span).collect::<Vec<_>>(),
&call.args.iter().map(|a| a.name.as_ref().map(|n| n.to_string())).collect::<Vec<_>>(),
span,
call.args.iter().any(|a| a.unpack),
);
// Also ensure by-ref vars are defined after the call (for post-call usage)
for (i, param) in params.iter().enumerate() {
if param.is_byref {
if let Some(arg) = call.args.get(i) {
if let ExprKind::Variable(name) = &arg.value.kind {
let var_name = name.as_ref().trim_start_matches('$');
ctx.set_var(var_name, Union::mixed());
}
}
}
}
// Generic: substitute template params in return type
let return_ty = if !template_params.is_empty() {
let bindings = infer_template_bindings(&template_params, ¶ms, &arg_types);
// Check bounds
for (name, inferred, bound) in check_template_bounds(&bindings, &template_params) {
ea.emit(
IssueKind::InvalidTemplateParam {
name: name.to_string(),
expected_bound: format!("{}", bound),
actual: format!("{}", inferred),
},
Severity::Error,
span,
);
}
return_ty_raw.substitute_templates(&bindings)
} else {
return_ty_raw
};
return return_ty;
}
// Unknown function — report the unqualified name to keep the message readable
ea.emit(
IssueKind::UndefinedFunction { name: fn_name },
Severity::Error,
span,
);
Union::mixed()
}
// -----------------------------------------------------------------------
// Method calls: $obj->method(args)
// -----------------------------------------------------------------------
pub fn analyze_method_call<'a, 'arena, 'src>(
ea: &mut ExpressionAnalyzer<'a>,
call: &MethodCallExpr<'arena, 'src>,
ctx: &mut Context,
span: Span,
nullsafe: bool,
) -> Union {
let obj_ty = ea.analyze(call.object, ctx);
let method_name = match &call.method.kind {
ExprKind::Identifier(name) | ExprKind::Variable(name) => name.as_ref().to_string(),
_ => return Union::mixed(),
};
// Null checks
if obj_ty.contains(|t| matches!(t, Atomic::TNull)) {
if nullsafe {
// ?-> is fine, just returns null on null receiver
} else if obj_ty.is_single() {
ea.emit(
IssueKind::NullMethodCall { method: method_name.clone() },
Severity::Error,
span,
);
return Union::mixed();
} else {
ea.emit(
IssueKind::PossiblyNullMethodCall { method: method_name.clone() },
Severity::Info,
span,
);
}
}
// Mixed receiver
if obj_ty.is_mixed() {
ea.emit(
IssueKind::MixedMethodCall { method: method_name.clone() },
Severity::Info,
span,
);
return Union::mixed();
}
let arg_types: Vec<Union> = call
.args
.iter()
.map(|arg| {
let ty = ea.analyze(&arg.value, ctx);
if arg.unpack { spread_element_type(&ty) } else { ty }
})
.collect();
let arg_spans: Vec<Span> = call.args.iter().map(|a| a.span).collect();
let receiver = obj_ty.remove_null();
let mut result = Union::empty();
for atomic in &receiver.types {
match atomic {
Atomic::TNamedObject { fqcn, .. }
| Atomic::TSelf { fqcn }
| Atomic::TStaticObject { fqcn }
| Atomic::TParent { fqcn } => {
// Resolve short names to FQCN — docblock types may not be fully qualified.
let fqcn_resolved = ea.codebase.resolve_class_name(&ea.file, fqcn);
let fqcn = &std::sync::Arc::from(fqcn_resolved.as_str());
if let Some(method) = ea.codebase.get_method(fqcn, &method_name) {
// Record reference for dead-code detection (M18)
ea.codebase.mark_method_referenced(fqcn, &method_name);
// Visibility check (simplified — only checks private from outside)
check_method_visibility(ea, &method, ctx, span);
// Arg type check
let arg_names: Vec<Option<String>> = call.args.iter()
.map(|a| a.name.as_ref().map(|n| n.to_string())).collect();
check_args(ea, &method_name, &method.params, &arg_types, &arg_spans, &arg_names, span, call.args.iter().any(|a| a.unpack));
let ret_raw = method.effective_return_type().cloned().unwrap_or_else(Union::mixed);
// Bind `static` return type to the actual receiver class (LSB).
let ret_raw = substitute_static_in_return(ret_raw, fqcn);
let ret = if !method.template_params.is_empty() {
let bindings = infer_template_bindings(
&method.template_params, &method.params, &arg_types,
);
for (name, inferred, bound) in
check_template_bounds(&bindings, &method.template_params)
{
ea.emit(
IssueKind::InvalidTemplateParam {
name: name.to_string(),
expected_bound: format!("{}", bound),
actual: format!("{}", inferred),
},
Severity::Error,
span,
);
}
ret_raw.substitute_templates(&bindings)
} else {
ret_raw
};
result = Union::merge(&result, &ret);
} else if ea.codebase.type_exists(fqcn) && !ea.codebase.has_unknown_ancestor(fqcn) {
// Class is known AND has no unscanned ancestors → genuine UndefinedMethod.
// If the class has an external/unscanned parent (e.g. a PHPUnit TestCase),
// the method might be inherited from that parent; skip to avoid false positives.
// Classes with __call handle any method dynamically — suppress.
// Interface types: method may exist on the concrete implementation — suppress
// (UndefinedInterfaceMethod is not emitted at default error level).
let is_interface = ea.codebase.interfaces.contains_key(fqcn.as_ref());
if is_interface || ea.codebase.get_method(fqcn, "__call").is_some() {
result = Union::merge(&result, &Union::mixed());
} else {
ea.emit(
IssueKind::UndefinedMethod {
class: fqcn.to_string(),
method: method_name.clone(),
},
Severity::Error,
span,
);
result = Union::merge(&result, &Union::mixed());
}
} else {
result = Union::merge(&result, &Union::mixed());
}
}
Atomic::TObject => {
result = Union::merge(&result, &Union::mixed());
}
_ => {
result = Union::merge(&result, &Union::mixed());
}
}
}
if nullsafe && obj_ty.is_nullable() {
result.add_type(Atomic::TNull);
}
if result.is_empty() { Union::mixed() } else { result }
}
// -----------------------------------------------------------------------
// Static method calls: ClassName::method(args)
// -----------------------------------------------------------------------
pub fn analyze_static_method_call<'a, 'arena, 'src>(
ea: &mut ExpressionAnalyzer<'a>,
call: &StaticMethodCallExpr<'arena, 'src>,
ctx: &mut Context,
span: Span,
) -> Union {
let method_name = call.method.as_ref();
let fqcn = match &call.class.kind {
ExprKind::Identifier(name) => ea.codebase.resolve_class_name(&ea.file, name.as_ref()),
_ => return Union::mixed(),
};
let fqcn = resolve_static_class(&fqcn, ctx);
let arg_types: Vec<Union> = call
.args
.iter()
.map(|arg| {
let ty = ea.analyze(&arg.value, ctx);
if arg.unpack { spread_element_type(&ty) } else { ty }
})
.collect();
let arg_spans: Vec<Span> = call.args.iter().map(|a| a.span).collect();
if let Some(method) = ea.codebase.get_method(&fqcn, method_name) {
ea.codebase.mark_method_referenced(&fqcn, method_name);
let arg_names: Vec<Option<String>> = call.args.iter()
.map(|a| a.name.as_ref().map(|n| n.to_string())).collect();
check_args(ea, method_name, &method.params, &arg_types, &arg_spans, &arg_names, span, call.args.iter().any(|a| a.unpack));
let ret_raw = method.effective_return_type().cloned().unwrap_or_else(Union::mixed);
let fqcn_arc: std::sync::Arc<str> = Arc::from(fqcn.as_str());
substitute_static_in_return(ret_raw, &fqcn_arc)
} else if ea.codebase.type_exists(&fqcn) && !ea.codebase.has_unknown_ancestor(&fqcn) {
// Class is known AND has no unscanned ancestors → genuine UndefinedMethod.
// Classes with __call handle any method dynamically — suppress.
// Interface: concrete impl may have the method — suppress at default error level.
let is_interface = ea.codebase.interfaces.contains_key(fqcn.as_str());
if is_interface || ea.codebase.get_method(&fqcn, "__call").is_some() {
Union::mixed()
} else {
ea.emit(
IssueKind::UndefinedMethod {
class: fqcn,
method: method_name.to_string(),
},
Severity::Error,
span,
);
Union::mixed()
}
} else {
// Unknown/external class or class with unscanned ancestor — do not emit false positive
Union::mixed()
}
}
}
// ---------------------------------------------------------------------------
// Public helper for constructor argument checking (used by expr.rs)
// ---------------------------------------------------------------------------
pub fn check_constructor_args(
ea: &mut ExpressionAnalyzer<'_>,
class_name: &str,
params: &[FnParam],
arg_types: &[Union],
arg_spans: &[Span],
arg_names: &[Option<String>],
call_span: Span,
has_spread: bool,
) {
check_args(ea, &format!("{}::__construct", class_name), params, arg_types, arg_spans, arg_names, call_span, has_spread);
}
// ---------------------------------------------------------------------------
// Argument type checking
// ---------------------------------------------------------------------------
fn check_args(
ea: &mut ExpressionAnalyzer<'_>,
fn_name: &str,
params: &[FnParam],
arg_types: &[Union],
arg_spans: &[Span],
arg_names: &[Option<String>],
call_span: Span,
has_spread: bool,
) {
// Build a remapped (param_index → (arg_type, arg_span)) map that handles
// named arguments (PHP 8.0+).
let has_named = arg_names.iter().any(|n| n.is_some());
// param_to_arg maps param index → (Union, Span)
let mut param_to_arg: Vec<Option<(Union, Span)>> = vec![None; params.len()];
if has_named {
let mut positional = 0usize;
for (i, (ty, span)) in arg_types.iter().zip(arg_spans.iter()).enumerate() {
if let Some(Some(name)) = arg_names.get(i) {
// Named arg: find the param by name
if let Some(pi) = params.iter().position(|p| p.name.as_ref() == name.as_str()) {
param_to_arg[pi] = Some((ty.clone(), *span));
}
} else {
// Positional arg: fill the next unfilled slot
while positional < params.len() && param_to_arg[positional].is_some() {
positional += 1;
}
if positional < params.len() {
param_to_arg[positional] = Some((ty.clone(), *span));
positional += 1;
}
}
}
} else {
// Pure positional — fast path
for (i, (ty, span)) in arg_types.iter().zip(arg_spans.iter()).enumerate() {
if i < params.len() {
param_to_arg[i] = Some((ty.clone(), *span));
}
}
}
let required_count = params.iter().filter(|p| !p.is_optional && !p.is_variadic).count();
let provided_count = if params.iter().any(|p| p.is_variadic) {
arg_types.len()
} else {
arg_types.len().min(params.len())
};
if provided_count < required_count && !has_spread {
ea.emit(
IssueKind::InvalidArgument {
param: format!("#{}", provided_count + 1),
fn_name: fn_name.to_string(),
expected: format!("{} argument(s)", required_count),
actual: format!("{} provided", provided_count),
},
Severity::Error,
call_span,
);
return;
}
for (i, (param, slot)) in params.iter().zip(param_to_arg.iter()).enumerate() {
let (arg_ty, arg_span) = match slot {
Some(pair) => pair,
None => continue, // optional param not supplied
};
let arg_span = *arg_span;
let _ = i;
if let Some(raw_param_ty) = ¶m.ty {
// For variadic params annotated as list<T>, each argument should match T, not list<T>.
let param_ty_owned;
let param_ty: &Union = if param.is_variadic {
if let Some(elem_ty) = raw_param_ty.types.iter().find_map(|a| match a {
Atomic::TList { value } | Atomic::TNonEmptyList { value } => Some(*value.clone()),
_ => None,
}) {
param_ty_owned = elem_ty;
¶m_ty_owned
} else {
raw_param_ty
}
} else {
raw_param_ty
};
// Null check: param is not nullable but arg could be null
if !param_ty.is_nullable() && arg_ty.is_nullable() {
ea.emit(
IssueKind::PossiblyNullArgument {
param: param.name.to_string(),
fn_name: fn_name.to_string(),
},
Severity::Info,
arg_span,
);
} else if !param_ty.is_nullable()
&& arg_ty.contains(|t| matches!(t, Atomic::TNull))
&& arg_ty.is_single()
{
ea.emit(
IssueKind::NullArgument {
param: param.name.to_string(),
fn_name: fn_name.to_string(),
},
Severity::Error,
arg_span,
);
}
// Type compatibility check: first try the fast structural check, then fall
// back to a codebase-aware check that handles class hierarchy and FQCN resolution.
if !arg_ty.is_subtype_of_simple(param_ty)
&& !param_ty.is_mixed()
&& !arg_ty.is_mixed()
&& !named_object_subtype(arg_ty, param_ty, ea)
&& !param_contains_template_or_unknown(param_ty, ea)
&& !param_contains_template_or_unknown(arg_ty, ea)
&& !array_list_compatible(arg_ty, param_ty, ea)
// Skip when param is more specific than arg (coercion, not hard error):
// e.g. string → non-empty-string, int → positive-int, string → string|null
&& !param_ty.is_subtype_of_simple(arg_ty)
// Skip when non-null part of param is a subtype of arg (e.g. non-empty-string|null ← string)
&& !param_ty.remove_null().is_subtype_of_simple(arg_ty)
// Skip when any atomic in param is a subtype of arg (e.g. non-empty-string|list ← string)
&& !param_ty.types.iter().any(|p| Union::single(p.clone()).is_subtype_of_simple(arg_ty))
// Skip when arg is compatible after removing null/false (PossiblyNull/FalseArgument
// handles these separately and they may appear in the baseline)
&& !arg_ty.remove_null().is_subtype_of_simple(param_ty)
&& !arg_ty.remove_false().is_subtype_of_simple(param_ty)
&& !named_object_subtype(&arg_ty.remove_null(), param_ty, ea)
&& !named_object_subtype(&arg_ty.remove_false(), param_ty, ea)
{
ea.emit(
IssueKind::InvalidArgument {
param: param.name.to_string(),
fn_name: fn_name.to_string(),
expected: format!("{}", param_ty),
actual: format!("{}", arg_ty),
},
Severity::Error,
arg_span,
);
}
}
}
}
/// Returns true if every atomic in `arg` can be assigned to some atomic in `param`
/// using codebase-aware class hierarchy checks.
///
/// Handles two common false-positive cases:
/// 1. `BackOffBuilder` stored as short name in param vs FQCN in arg → resolve both.
/// 2. `DateTimeImmutable` extends `DateTimeInterface` → use `extends_or_implements`.
fn named_object_subtype(arg: &Union, param: &Union, ea: &ExpressionAnalyzer<'_>) -> bool {
use mir_types::Atomic;
// Every atomic in arg must satisfy the param
arg.types.iter().all(|a_atomic| {
// Extract FQCN from the arg atomic — handles TNamedObject, TSelf, TStaticObject, TParent
let arg_fqcn: &Arc<str> = match a_atomic {
Atomic::TNamedObject { fqcn, .. } => fqcn,
Atomic::TSelf { fqcn } | Atomic::TStaticObject { fqcn } => {
// If the self/static refers to a trait, we can't know the concrete class — skip
if ea.codebase.traits.contains_key(fqcn.as_ref()) {
return true;
}
fqcn
}
Atomic::TParent { fqcn } => fqcn,
// TNever is bottom type — compatible with any param
Atomic::TNever => return true,
// Closure() types satisfy Closure or callable param
Atomic::TClosure { .. } => {
return param.types.iter().any(|p| match p {
Atomic::TClosure { .. } | Atomic::TCallable { .. } => true,
Atomic::TNamedObject { fqcn, .. } => fqcn.as_ref() == "Closure",
_ => false,
});
}
// callable satisfies Closure param (not flagged at default error level)
Atomic::TCallable { .. } => {
return param.types.iter().any(|p| match p {
Atomic::TCallable { .. } | Atomic::TClosure { .. } => true,
Atomic::TNamedObject { fqcn, .. } => fqcn.as_ref() == "Closure",
_ => false,
});
}
// class-string<X> is compatible with class-string<Y> if X extends/implements Y
Atomic::TClassString(Some(arg_cls)) => {
return param.types.iter().any(|p| match p {
Atomic::TClassString(None) | Atomic::TString => true,
Atomic::TClassString(Some(param_cls)) => {
arg_cls == param_cls
|| ea.codebase.extends_or_implements(arg_cls.as_ref(), param_cls.as_ref())
}
_ => false,
});
}
// Null satisfies param if param also contains null
Atomic::TNull => {
return param.types.iter().any(|p| matches!(p, Atomic::TNull));
}
// False satisfies param if param contains false or bool
Atomic::TFalse => {
return param.types.iter().any(|p| matches!(p, Atomic::TFalse | Atomic::TBool));
}
_ => return false, // non-named-object: not handled here
};
// An object with __invoke satisfies callable|null
if param.types.iter().any(|p| matches!(p, Atomic::TCallable { .. })) {
let resolved_arg = ea.codebase.resolve_class_name(&ea.file, arg_fqcn.as_ref());
if ea.codebase.get_method(&resolved_arg, "__invoke").is_some()
|| ea.codebase.get_method(arg_fqcn.as_ref(), "__invoke").is_some()
{
return true;
}
}
param.types.iter().any(|p_atomic| {
let param_fqcn: &Arc<str> = match p_atomic {
Atomic::TNamedObject { fqcn, .. } => fqcn,
Atomic::TSelf { fqcn } => fqcn,
Atomic::TStaticObject { fqcn } => fqcn,
Atomic::TParent { fqcn } => fqcn,
_ => return false,
};
// Resolve param_fqcn in case it's a short name stored from a type hint
let resolved_param = ea.codebase.resolve_class_name(&ea.file, param_fqcn.as_ref());
let resolved_arg = ea.codebase.resolve_class_name(&ea.file, arg_fqcn.as_ref());
if resolved_param == resolved_arg
|| arg_fqcn.as_ref() == resolved_param.as_str()
|| resolved_arg == param_fqcn.as_ref()
|| ea.codebase.extends_or_implements(arg_fqcn.as_ref(), &resolved_param)
|| ea.codebase.extends_or_implements(arg_fqcn.as_ref(), param_fqcn.as_ref())
|| ea.codebase.extends_or_implements(&resolved_arg, &resolved_param)
// ArgumentTypeCoercion (suppressed at level 3): param extends arg — arg is
// broader than param. Not a hard error; only flagged at stricter error levels.
|| ea.codebase.extends_or_implements(param_fqcn.as_ref(), &resolved_arg)
|| ea.codebase.extends_or_implements(param_fqcn.as_ref(), arg_fqcn.as_ref())
|| ea.codebase.extends_or_implements(&resolved_param, &resolved_arg)
{
return true;
}
// If arg_fqcn is a short name (no namespace) that didn't resolve through the caller
// file's imports (e.g., return type from a vendor method like `NonNull` from
// `Type::nonNull()`), search codebase for any class with that short_name and check
// if it satisfies the param type.
if !arg_fqcn.contains('\\') && !ea.codebase.type_exists(&resolved_arg) {
for entry in ea.codebase.classes.iter() {
if entry.value().short_name.as_ref() == arg_fqcn.as_ref() {
let actual_fqcn = entry.key().clone();
if ea.codebase.extends_or_implements(actual_fqcn.as_ref(), &resolved_param)
|| ea.codebase.extends_or_implements(actual_fqcn.as_ref(), param_fqcn.as_ref())
{
return true;
}
}
}
}
// If arg_fqcn is an interface, check if any known concrete class both implements
// the interface AND extends/implements the param. This handles cases like
// `ValueNode` (interface) whose implementations all extend `Node` (abstract class).
let iface_key = if ea.codebase.interfaces.contains_key(arg_fqcn.as_ref()) {
Some(arg_fqcn.as_ref())
} else if ea.codebase.interfaces.contains_key(resolved_arg.as_str()) {
Some(resolved_arg.as_str())
} else {
None
};
if let Some(iface_fqcn) = iface_key {
let compatible = ea.codebase.classes.iter().any(|entry| {
let cls = entry.value();
cls.all_parents.iter().any(|p| p.as_ref() == iface_fqcn)
&& (ea.codebase.extends_or_implements(entry.key().as_ref(), param_fqcn.as_ref())
|| ea.codebase.extends_or_implements(entry.key().as_ref(), &resolved_param))
});
if compatible {
return true;
}
}
// If arg is a fully-qualified vendor class not in our codebase, we can't verify
// the hierarchy — suppress to avoid false positives on external libraries.
if arg_fqcn.contains('\\') && !ea.codebase.type_exists(arg_fqcn.as_ref()) && !ea.codebase.type_exists(&resolved_arg) {
return true;
}
// If param is a fully-qualified vendor class not in our codebase, we can't verify
// the required type — suppress to avoid false positives on external library params.
if param_fqcn.contains('\\') && !ea.codebase.type_exists(param_fqcn.as_ref()) && !ea.codebase.type_exists(&resolved_param) {
return true;
}
false
})
})
}
/// Returns true if the param type contains a template-like type (a TNamedObject whose FQCN
/// is a single uppercase letter or doesn't exist in the codebase) indicating the function
/// uses generics. We can't validate the argument type without full template instantiation.
fn param_contains_template_or_unknown(param_ty: &Union, ea: &ExpressionAnalyzer<'_>) -> bool {
param_ty.types.iter().any(|atomic| match atomic {
Atomic::TTemplateParam { .. } => true,
Atomic::TNamedObject { fqcn, .. } => {
!fqcn.contains('\\') && !ea.codebase.type_exists(fqcn.as_ref())
}
// class-string<T> where T is a template param (single-letter or unknown)
Atomic::TClassString(Some(inner)) => {
!inner.contains('\\') && !ea.codebase.type_exists(inner.as_ref())
}
Atomic::TArray { key: _, value } | Atomic::TList { value }
| Atomic::TNonEmptyArray { key: _, value } | Atomic::TNonEmptyList { value } => {
value.types.iter().any(|v| match v {
Atomic::TTemplateParam { .. } => true,
Atomic::TNamedObject { fqcn, .. } => {
!fqcn.contains('\\') && !ea.codebase.type_exists(fqcn.as_ref())
}
_ => false,
})
}
_ => false,
})
}
/// Replace `TStaticObject` / `TSelf` in a method's return type with the actual receiver FQCN.
/// `static` (LSB) and `self` in trait context both resolve to the concrete receiver class.
fn substitute_static_in_return(ret: Union, receiver_fqcn: &Arc<str>) -> Union {
use mir_types::Atomic;
let from_docblock = ret.from_docblock;
let types: Vec<Atomic> = ret.types.into_iter().map(|a| {
match a {
Atomic::TStaticObject { .. } | Atomic::TSelf { .. } => Atomic::TNamedObject {
fqcn: receiver_fqcn.clone(),
type_params: vec![],
},
other => other,
}
}).collect();
let mut result = Union::from_vec(types);
result.from_docblock = from_docblock;
result
}
/// For a spread (`...`) argument, return the union of value types across all array atomics.
/// E.g. `array<int, int>` → `int`, `list<string>` → `string`, `mixed` → `mixed`.
/// This lets us compare the element type against the variadic param type.
pub fn spread_element_type(arr_ty: &Union) -> Union {
use mir_types::Atomic;
let mut result = Union::empty();
for atomic in arr_ty.types.iter() {
match atomic {
Atomic::TArray { value, .. }
| Atomic::TNonEmptyArray { value, .. }
| Atomic::TList { value }
| Atomic::TNonEmptyList { value } => {
for t in value.types.iter() {
result.add_type(t.clone());
}
}
Atomic::TKeyedArray { properties, .. } => {
for (_key, prop) in properties.iter() {
for t in prop.ty.types.iter() {
result.add_type(t.clone());
}
}
}
// If the spread value isn't an array (or is mixed), treat as mixed
_ => return Union::mixed(),
}
}
if result.types.is_empty() { Union::mixed() } else { result }
}
/// Returns true if both arg and param are array/list types whose value types are compatible
/// with FQCN resolution (e.g., `array<int, FQCN>` satisfies `list<ShortName>`).
/// Recursive codebase-aware union compatibility check.
/// Returns true if every atomic in `arg_ty` is compatible with `param_ty`,
/// handling nested lists/arrays and FQCN resolution.
fn union_compatible(arg_ty: &Union, param_ty: &Union, ea: &ExpressionAnalyzer<'_>) -> bool {
arg_ty.types.iter().all(|av| {
// Named object: use FQCN resolution
let av_fqcn: &Arc<str> = match av {
Atomic::TNamedObject { fqcn, .. } => fqcn,
Atomic::TSelf { fqcn } | Atomic::TStaticObject { fqcn } | Atomic::TParent { fqcn } => fqcn,
// Nested list/array: recurse
Atomic::TArray { value, .. } | Atomic::TNonEmptyArray { value, .. }
| Atomic::TList { value } | Atomic::TNonEmptyList { value } => {
return param_ty.types.iter().any(|pv| {
let pv_val: &Union = match pv {
Atomic::TArray { value, .. } | Atomic::TNonEmptyArray { value, .. }
| Atomic::TList { value } | Atomic::TNonEmptyList { value } => value,
_ => return false,
};
union_compatible(value, pv_val, ea)
});
}
Atomic::TKeyedArray { .. } => return true,
_ => return Union::single(av.clone()).is_subtype_of_simple(param_ty),
};
param_ty.types.iter().any(|pv| {
let pv_fqcn: &Arc<str> = match pv {
Atomic::TNamedObject { fqcn, .. } => fqcn,
Atomic::TSelf { fqcn } | Atomic::TStaticObject { fqcn } | Atomic::TParent { fqcn } => fqcn,
_ => return false,
};
// Template param wildcard
if !pv_fqcn.contains('\\') && !ea.codebase.type_exists(pv_fqcn.as_ref()) {
return true;
}
let resolved_param = ea.codebase.resolve_class_name(&ea.file, pv_fqcn.as_ref());
let resolved_arg = ea.codebase.resolve_class_name(&ea.file, av_fqcn.as_ref());
resolved_param == resolved_arg
|| ea.codebase.extends_or_implements(av_fqcn.as_ref(), &resolved_param)
|| ea.codebase.extends_or_implements(&resolved_arg, &resolved_param)
|| ea.codebase.extends_or_implements(pv_fqcn.as_ref(), &resolved_arg)
|| ea.codebase.extends_or_implements(&resolved_param, &resolved_arg)
})
})
}
fn array_list_compatible(arg_ty: &Union, param_ty: &Union, ea: &ExpressionAnalyzer<'_>) -> bool {
arg_ty.types.iter().all(|a_atomic| {
let arg_value: &Union = match a_atomic {
Atomic::TArray { value, .. } | Atomic::TNonEmptyArray { value, .. }
| Atomic::TList { value } | Atomic::TNonEmptyList { value } => value,
Atomic::TKeyedArray { .. } => return true, // keyed arrays are compatible with any list/array
_ => return false,
};
param_ty.types.iter().any(|p_atomic| {
let param_value: &Union = match p_atomic {
Atomic::TArray { value, .. } | Atomic::TNonEmptyArray { value, .. }
| Atomic::TList { value } | Atomic::TNonEmptyList { value } => value,
_ => return false,
};
union_compatible(arg_value, param_value, ea)
})
})
}
fn check_method_visibility(
ea: &mut ExpressionAnalyzer<'_>,
method: &MethodStorage,
ctx: &Context,
span: Span,
) {
match method.visibility {
Visibility::Private => {
// Private methods can only be called from within the same class
let caller_fqcn = ctx.self_fqcn.as_deref().unwrap_or("");
if caller_fqcn != method.fqcn.as_ref() {
ea.emit(
IssueKind::UndefinedMethod {
class: method.fqcn.to_string(),
method: method.name.to_string(),
},
Severity::Error,
span,
);
}
}
Visibility::Protected => {
// Protected: callable only from within the declaring class or its subclasses
let caller_fqcn = ctx.self_fqcn.as_deref().unwrap_or("");
if caller_fqcn.is_empty() {
// Called from outside any class — not allowed
ea.emit(
IssueKind::UndefinedMethod {
class: method.fqcn.to_string(),
method: method.name.to_string(),
},
Severity::Error,
span,
);
} else {
// Caller must be the method's class or a subclass of it
let allowed = caller_fqcn == method.fqcn.as_ref()
|| ea.codebase.extends_or_implements(caller_fqcn, method.fqcn.as_ref());
if !allowed {
ea.emit(
IssueKind::UndefinedMethod {
class: method.fqcn.to_string(),
method: method.name.to_string(),
},
Severity::Error,
span,
);
}
}
}
Visibility::Public => {}
}
}
fn resolve_static_class(name: &str, ctx: &Context) -> String {
match name.to_lowercase().as_str() {
"self" => ctx.self_fqcn.as_deref().unwrap_or("self").to_string(),
"parent" => ctx.parent_fqcn.as_deref().unwrap_or("parent").to_string(),
"static" => ctx.static_fqcn.as_deref().unwrap_or(ctx.self_fqcn.as_deref().unwrap_or("static")).to_string(),
_ => name.to_string(),
}
}