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
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
use std::sync::Arc;
use php_ast::owned::{ExprKind, StaticDynMethodCallExpr, StaticMethodCallExpr};
use php_ast::Span;
use mir_issues::{IssueKind, Severity};
use mir_types::{Atomic, Type};
use mir_codebase::definitions::{AssertionKind, DeclaredParam};
use mir_types::Name;
use rustc_hash::FxHashMap;
use crate::expr::ExpressionAnalyzer;
use crate::flow_state::{self_is_trait, FlowState};
use crate::narrowing::extract_expr_guard_key;
use crate::symbol::ReferenceKind;
use crate::taint::{is_expr_tainted, taint_sink_issue};
use super::args::{
check_args, check_method_visibility_with_magic, distinct_spans_for_expansion,
expand_sole_spread_arg, expr_can_be_passed_by_reference_owned, spread_element_type,
substitute_static_in_return, CheckArgsParams,
};
use super::method::resolve_method_from_db;
use super::CallAnalyzer;
use crate::generic::{
build_class_bindings, check_template_bounds_with_inheritance, infer_arg_template_bindings,
infer_template_bindings,
};
/// Widen scalar literal atomics to their base type before attaching an
/// inferred binding as a receiver's generic type param — mirrors
/// `expr::objects::widen_type_param` (kept separate since that module is
/// private to `expr`). Carrying a literal type param into the receiver
/// (e.g. `Box<42>` from `Box::make(42)`) is over-narrow and risks false
/// positives downstream (e.g. `$box->set(43)` where `set(T)` and `T=42`
/// would wrongly reject `43`).
fn widen_own_type_param(ty: &Type) -> Type {
let mut out = Type::empty();
out.from_docblock = ty.from_docblock;
out.possibly_undefined = ty.possibly_undefined;
for atomic in &ty.types {
let widened = match atomic {
Atomic::TLiteralInt(_) | Atomic::TIntRange { .. } => Atomic::TInt,
Atomic::TLiteralString(_) => Atomic::TString,
Atomic::TLiteralFloat(_, _) => Atomic::TFloat,
Atomic::TTrue | Atomic::TFalse => Atomic::TBool,
other => other.clone(),
};
out.add_type(widened);
}
out
}
fn extract_namespace(fqcn: &str) -> Option<&str> {
if let Some(pos) = fqcn.rfind('\\') {
Some(&fqcn[..pos])
} else {
None
}
}
/// First namespace segment ("root namespace"), or `None` for the global namespace.
/// `@internal` (no argument) scopes a symbol to its root namespace, so any
/// sub-namespace under the same root may use it (Psalm semantics).
fn namespace_root(ns: Option<&str>) -> Option<&str> {
ns.map(|n| n.trim_start_matches('\\'))
.and_then(|n| n.split('\\').next())
.filter(|seg| !seg.is_empty())
}
fn is_valid_class_name_type(ty: &Type) -> bool {
// Class names must be strings or class-string types.
// Mixed is allowed since it's already imprecise. Template params are
// allowed because their bound may be a class-string.
ty.contains(|t| {
matches!(
t,
Atomic::TString
| Atomic::TClassString(_)
| Atomic::TLiteralString(_)
| Atomic::TMixed
| Atomic::TTemplateParam { .. }
)
})
}
fn is_object_atomic(t: &Atomic) -> bool {
matches!(
t,
Atomic::TObject
| Atomic::TNamedObject { .. }
| Atomic::TStaticObject { .. }
| Atomic::TSelf { .. }
| Atomic::TParent { .. }
| Atomic::TIntersection { .. }
| Atomic::TNull
)
}
/// If `ty` is a uniform single-class object type (possibly nullable), return
/// its FQCN so the static call can be resolved against it. Returns `None`
/// for `object`, multi-class unions, or any non-object/non-null type component.
///
/// `$this::method()` and `$obj::method()` use LSB semantics at runtime; we
/// approximate here with the declared class, which is correct in the common
/// case and never produces a false positive. Null is skipped — null safety
/// on `::` is a separate concern from class-string validity.
///
/// Also covers `$cls::method()` where `$cls` holds a known class-string
/// (`TClassString(Some(fqcn))`, e.g. `$cls = Foo::class;`) — otherwise this
/// call form skips method resolution/reference-recording entirely, unlike
/// its already-handled `$cls::$prop` / `$cls::CONST` siblings.
fn extract_object_fqcn(ty: &Type) -> Option<String> {
let mut result: Option<String> = None;
for atom in ty.types.iter() {
let fqcn_str = match atom {
Atomic::TNamedObject { fqcn, .. }
| Atomic::TStaticObject { fqcn }
| Atomic::TSelf { fqcn }
| Atomic::TParent { fqcn } => fqcn.to_string(),
Atomic::TClassString(Some(fqcn)) => fqcn.to_string(),
Atomic::TNull => continue, // nullable object: skip null, resolve against class
_ => return None,
};
match &result {
None => result = Some(fqcn_str),
Some(existing) if *existing == fqcn_str => {}
_ => return None,
}
}
result
}
/// The concrete type args a `$var::method()`/`$this::method()` receiver
/// carries for its own class-level `@template` (e.g. `int` from a `Box<int>
/// $b` receiver in `$b::peek()`). Mirrors what `method.rs`'s instance-call
/// path reads straight off the `TNamedObject` atom — without this, a
/// receiver's own type args never reach the static-call template binding,
/// so a `@return T` leaks the raw template atom instead of resolving it.
fn extract_receiver_type_params(ty: &Type, fqcn: &str) -> Vec<Type> {
ty.types
.iter()
.find_map(|atom| match atom {
Atomic::TNamedObject {
fqcn: f,
type_params,
} if f.as_ref() == fqcn => Some(type_params.to_vec()),
_ => None,
})
.unwrap_or_default()
}
impl CallAnalyzer {
pub fn analyze_static_method_call<'a>(
ea: &mut ExpressionAnalyzer<'a>,
call: &StaticMethodCallExpr,
ctx: &mut FlowState,
span: Span,
) -> Type {
let method_name = match &call.method.kind {
ExprKind::Identifier(name) => name.as_ref(),
_ => return Type::mixed(),
};
let mut receiver_type_params: Vec<Type> = Vec::new();
// Only a real object receiver ($this::, $obj::) is guaranteed concrete
// at runtime — an abstract class can never be instantiated. A
// class-string receiver ($cls = Foo::class; $cls::method()) can hold
// the literal abstract class name itself, so it gets no such
// guarantee and must still be checked below.
let mut receiver_is_object_instance = false;
// A literal class-name receiver (`Foo::bar()`, including `self`/`static`/
// `parent`) is the only shape where an interface target is genuinely
// invalid PHP (interfaces have no implementation to dispatch to). A
// variable receiver (`$var::bar()`) — an object or class-string typed as
// the interface — dispatches at runtime to whatever concrete class it
// actually holds, which is valid PHP regardless of the declared type.
let is_literal_class_receiver = matches!(&call.class.kind, ExprKind::Identifier(_));
let fqcn = match &call.class.kind {
ExprKind::Identifier(name) => crate::db::resolve_name(ea.db, &ea.file, name.as_ref()),
_ => {
let ty = ea.analyze(&call.class, ctx);
// $obj::method() / $this::method(): resolve against the object's class
if let Some(fqcn) = extract_object_fqcn(&ty) {
if ty.is_nullable() && !ty.is_mixed() {
ea.emit(
IssueKind::PossiblyNullMethodCall {
method: method_name.to_string(),
},
Severity::Info,
call.class.span,
);
}
receiver_type_params = extract_receiver_type_params(&ty, &fqcn);
receiver_is_object_instance = ty.types.iter().any(|atom| {
matches!(
atom,
Atomic::TNamedObject { .. }
| Atomic::TStaticObject { .. }
| Atomic::TSelf { .. }
| Atomic::TParent { .. }
)
});
fqcn
} else {
// All-object unions (Foo|Bar, object) are valid PHP — skip error
if !is_valid_class_name_type(&ty) && !ty.types.iter().all(is_object_atomic) {
ea.emit(
IssueKind::InvalidStringClass {
actual: ty.to_string(),
},
Severity::Warning,
call.class.span,
);
}
return Type::mixed();
}
}
};
// Detect `parent::` used in a class that has no parent. Skip inside a
// trait: `parent::` there resolves against the using class at runtime,
// not the trait (which never has a parent).
if fqcn.eq_ignore_ascii_case("parent")
&& ctx.parent_fqcn.is_none()
&& ctx.self_fqcn.is_some()
&& !self_is_trait(ea.db, ctx)
{
ea.emit(IssueKind::ParentNotFound, Severity::Error, call.class.span);
}
// A `@template T of static` bound reflects the actual late-static-bound
// receiver at this call site, which is identical for `self::`/
// `static::`/`parent::` — it's whatever `static::` would resolve to
// here, regardless of which keyword was used to reach the method.
// `$var::method()`/`$this::method()` calls (the `_` catch-all in
// `resolve_static_class`) already carry their own concrete receiver
// class in `fqcn` at this point, which is already correct.
let is_self_static_or_parent_keyword = matches!(
crate::util::php_ident_lowercase(&fqcn).as_str(),
"self" | "static" | "parent"
);
let fqcn = resolve_static_class(&fqcn, ctx);
let bound_receiver_fqcn: String = if is_self_static_or_parent_keyword {
resolve_static_class("static", ctx)
} else {
fqcn.clone()
};
if is_literal_class_receiver {
ea.record_ref(Arc::from(format!("cls:{fqcn}")), call.class.span);
// Record a symbol on the class token itself so hover / go-to-definition
// works when the cursor sits on the class name — including the
// `self`/`parent`/`static` keywords, which `resolve_static_class`
// has already mapped to a concrete FQCN. Mirrors `new Foo` and
// `instanceof Foo`. Skip the literal keywords that failed to
// resolve (e.g. `parent::` with no parent), which carry no class.
if !matches!(fqcn.as_str(), "self" | "static" | "parent") {
ea.record_symbol(
call.class.span,
ReferenceKind::ClassReference(Arc::from(fqcn.as_str())),
Type::single(Atomic::TClassString(None)),
);
}
// Check if the class is deprecated (skip self/static/parent)
if !matches!(fqcn.as_str(), "self" | "static" | "parent") {
let here = crate::db::Fqcn::from_str(ea.db, fqcn.as_str());
if let Some(class) = crate::db::find_class_like(ea.db, here) {
if let Some(msg) = class.deprecated() {
ea.emit(
IssueKind::DeprecatedClass {
name: fqcn.clone(),
message: Some(msg.clone()).filter(|m| !m.is_empty()),
},
Severity::Info,
call.class.span,
);
}
// Check for case mismatch between the written class name and canonical
if let Some((used, canonical_str)) =
crate::fqcn_case_mismatch(fqcn.as_str(), class.fqcn().as_ref())
{
ea.emit(
IssueKind::WrongCaseClass {
used,
canonical: canonical_str,
},
Severity::Info,
call.class.span,
);
}
}
}
}
let fqcn_arc: Arc<str> = Arc::from(fqcn.as_str());
let method_name_lower = crate::util::php_ident_lowercase(method_name);
// Pre-mark by-reference argument variables as defined before evaluating
// the arguments, so passing an undefined variable to an out-param (e.g.
// `Registry::build($items, $out)` where `$out` is `@param-out`) does
// not produce a false UndefinedVariable.
if let Some(pre_resolved) = resolve_method_from_db(ea.db, &fqcn_arc, &method_name_lower) {
super::premark_byref_arg_vars(&pre_resolved.params, &call.args, ctx);
}
let mut sole_spread_ty: Option<Type> = None;
let mut arg_types: Vec<Type> = Vec::with_capacity(call.args.len());
for arg in call.args.iter() {
// `None` is a PHP 8.6 partial-application placeholder (`?`/`...`)
// — not yet modeled; keep positional slots aligned with `mixed`.
let Some(value) = &arg.value else {
arg_types.push(Type::mixed());
continue;
};
let ty = ea.analyze(value, ctx);
super::consume_arg_assignment(value, ctx);
if arg.unpack {
if call.args.len() == 1 {
sole_spread_ty = Some(ty.clone());
}
arg_types.push(spread_element_type(ea.db, &ty));
} else {
arg_types.push(ty);
}
}
let mut arg_spans: Vec<Span> = call.args.iter().map(|a| a.span).collect();
// Check if trying to call static method on an interface (not allowed)
// — only for a literal class-name receiver; see `is_literal_class_receiver`.
if is_literal_class_receiver && crate::db::class_exists(ea.db, &fqcn) {
let here = crate::db::Fqcn::from_str(ea.db, fqcn_arc.as_ref());
let is_interface = crate::db::find_class_like(ea.db, here)
.map(|c| c.is_interface())
.unwrap_or(false);
if is_interface {
ea.emit(
IssueKind::UndefinedClass { name: fqcn.clone() },
Severity::Error,
call.class.span,
);
return Type::mixed();
}
}
// Closure::bind($closure, $newThis, $newScope = 'static'): ?Closure
// Preserve the closure's params and return_type, update this_type
if fqcn_arc.as_ref() == "Closure" && method_name_lower == "bind" {
if let Some(closure_arg) = arg_types.first() {
for atomic in &closure_arg.types {
if let mir_types::Atomic::TClosure { data } = atomic {
let new_this = arg_types.get(1).cloned().unwrap_or_else(Type::null);
let this_type = {
let non_null = new_this.remove_null();
if non_null.is_empty() {
None
} else {
Some(non_null)
}
};
let mut result = Type::single(mir_types::Atomic::TClosure {
data: Box::new(mir_types::atomic::ClosureData {
params: data.params.clone(),
return_type: data.return_type.clone(),
this_type,
}),
});
result.add_type(mir_types::Atomic::TNull);
return result;
}
}
}
// If we can't determine the closure type from the first arg, fall through to stub resolution
}
// Closure::fromCallable('helper') / Closure::fromCallable('Foo::bar'):
// a bare string callable argument is a real runtime reference, same as
// call_user_func('name') — record it, or a function/method reachable
// only this way is falsely flagged dead code.
if fqcn_arc.as_ref() == "Closure" && method_name_lower == "fromcallable" {
if let (Some(callback_ty), Some(&callback_span)) =
(arg_types.first(), arg_spans.first())
{
super::callable::record_callable_string_ref(ea, callback_ty, callback_span);
}
}
let resolved = resolve_method_from_db(ea.db, &fqcn_arc, &method_name_lower);
if let Some(resolved) = resolved {
ea.record_ref(
Arc::from(format!(
"meth:{}::{}",
resolved.owner_fqcn,
crate::util::php_ident_lowercase(method_name)
)),
call.method.span,
);
if let Some(msg) = resolved.deprecated.clone() {
ea.emit(
IssueKind::DeprecatedMethodCall {
class: fqcn.clone(),
method: method_name.to_string(),
message: Some(msg).filter(|m| !m.is_empty()),
},
Severity::Info,
span,
);
}
// Detect call to an abstract method via an explicit class name.
// `$this::method()` is self-referential too (LSB against the
// current instance), same as the `self`/`static`/`parent`
// keywords — otherwise it falls into the "explicit class name"
// path below and produces a false `InvalidStaticInvocation` on
// a non-static method, and drops `@psalm-self-out` narrowing.
// Hoisted above the purity checks below — the immutable check
// needs it too, to scope itself to a self/parent/$this call the
// same way method.rs's instance-call counterpart scopes to $this.
let is_self_parent_call = match &call.class.kind {
ExprKind::Identifier(id) => matches!(id.as_ref(), "self" | "static" | "parent"),
ExprKind::Variable(name) => name.trim_start_matches('$') == "this",
_ => false,
};
// Purity check: a static call has no receiver to scope the
// "only externally-visible mutations matter" exception to (unlike
// instance calls on a local object) — any non-pure static/self::/
// parent:: call inside a @pure function can touch static state,
// so it's flagged unconditionally, mirroring the plain
// function-call check in call/function.rs.
if ctx.is_in_pure_fn && !resolved.is_pure {
ea.emit(
IssueKind::ImpureMethodCall {
method: method_name.to_string(),
},
Severity::Warning,
span,
);
}
// Immutability check: calling a non-mutation-free method via
// self::/parent:: (i.e. still operating on the same $this) inside
// a @psalm-immutable class or @psalm-mutation-free method may
// indirectly mutate object state — mirrors method.rs's identical
// check for the `$this->method()` call form, which this bypassed
// entirely (only `is_pure` was ever checked for a static call).
if ctx.is_in_immutable_method
&& !resolved.is_mutation_free
&& !resolved.is_pure
&& !resolved.is_static
&& is_self_parent_call
{
ea.emit(
IssueKind::ImpureMethodCall {
method: method_name.to_string(),
},
Severity::Warning,
span,
);
}
// Same "argument passed into a not-provably-safe callee" check
// as `new X(...)` and free-function calls — a genuinely static
// call (`Foo::bar($this)`) or a variable-class-string call
// (`$param::method($this)`) has no `$this`-mutation vector of
// its own (unlike the self::/parent:: case just above), but can
// still store/mutate an object argument reachable from `$this`/
// a parameter just as easily as an instance method call can.
if !is_self_parent_call
&& (ctx.is_in_immutable_method || ctx.is_in_external_mutation_free_method)
&& !resolved.is_pure
&& !resolved.is_mutation_free
{
for arg in call.args.iter() {
let Some(value) = &arg.value else { continue };
let Some(recv_name) = crate::expr::root_receiver_var(value) else {
continue;
};
let recv_stripped = recv_name.trim_start_matches('$');
let reachable = (ctx.is_in_immutable_method && recv_stripped == "this")
|| (ctx.is_in_external_mutation_free_method
&& recv_stripped != "this"
&& ctx.param_names.contains(&Name::from(recv_stripped)));
if !reachable {
continue;
}
let arg_is_object = crate::expr::assignment::resolve_chained_receiver_type(
value, ctx, ea.db, &ea.file,
)
.is_some_and(|ty| {
ty.types.iter().any(|a| {
matches!(
a,
Atomic::TNamedObject { .. }
| Atomic::TSelf { .. }
| Atomic::TStaticObject { .. }
| Atomic::TParent { .. }
)
})
});
if arg_is_object {
ea.emit(
IssueKind::ImpureMethodCall {
method: method_name.to_string(),
},
Severity::Warning,
span,
);
break;
}
}
}
if method_name != resolved.name.as_ref()
&& method_name.eq_ignore_ascii_case(resolved.name.as_ref())
{
ea.emit(
IssueKind::WrongCaseMethod {
class: fqcn.clone(),
used: method_name.to_string(),
canonical: resolved.name.to_string(),
},
Severity::Info,
call.method.span,
);
}
// static::, $this::, and $var:: (when $var holds an object) all
// use LSB and resolve to the concrete runtime class — an abstract
// class can never be instantiated, so an object receiver is
// always a concrete instance. self::, parent::, an explicit class
// name, and a class-string receiver (which may hold the literal
// abstract class name itself) get no such guarantee.
let uses_late_static_binding = match &call.class.kind {
ExprKind::Identifier(id) => id.as_ref() == "static",
_ => receiver_is_object_instance,
};
if resolved.is_abstract && !uses_late_static_binding {
ea.emit(
IssueKind::AbstractMethodCall {
class: fqcn.clone(),
method: method_name.to_string(),
},
Severity::Error,
span,
);
}
if !resolved.is_static
&& !method_name.starts_with("__")
&& !is_self_parent_call
&& !crate::db::has_method_in_chain(ea.db, fqcn.as_str(), "__callStatic")
{
ea.emit(
IssueKind::InvalidStaticInvocation {
class: fqcn.clone(),
method: method_name.to_string(),
},
Severity::Error,
span,
);
}
// Detect non-static method called via self::/static:: from a static context.
// Note: __callStatic only intercepts UNDEFINED methods, so we don't suppress here
// when the method is explicitly defined as non-static.
if !resolved.is_static
&& !method_name.starts_with("__")
&& is_self_parent_call
&& ctx.inside_static_method
{
ea.emit(
IssueKind::NonStaticSelfCall {
class: fqcn.clone(),
method: method_name.to_string(),
},
Severity::Error,
span,
);
}
if resolved.is_internal {
let calling_ns = ea.db.file_namespace(&ea.file);
let calling_root = namespace_root(calling_ns.as_deref());
let owner_root = namespace_root(extract_namespace(&resolved.owner_fqcn));
// self::/static::/parent:: calls are self-calls; also allow when calling
// on a class that is the current self (trait @internal methods included).
let is_self_call = is_self_parent_call
|| ctx
.self_fqcn
.as_deref()
.map(|s| s.eq_ignore_ascii_case(fqcn.as_str()))
.unwrap_or(false);
if calling_root != owner_root && !is_self_call {
ea.emit(
IssueKind::InternalMethod {
class: fqcn.clone(),
method: method_name.to_string(),
},
Severity::Warning,
span,
);
}
}
// Only checked for genuinely static methods: a non-static method
// called via `Foo::bar()`/self::/static:: already gets a more
// precise `InvalidStaticInvocation`/`NonStaticSelfCall` above —
// piling on a visibility error for the same call site is noise.
if resolved.is_static {
check_method_visibility_with_magic(
ea,
resolved.visibility,
&resolved.owner_fqcn,
&resolved.name,
ctx,
span,
"__callStatic",
);
}
let mut arg_names: Vec<Option<String>> = call
.args
.iter()
.map(|a| a.name.as_ref().map(crate::parser::name_to_string_owned))
.collect();
let mut arg_can_be_byref: Vec<bool> = call
.args
.iter()
.map(|a| {
a.value
.as_ref()
.is_some_and(expr_can_be_passed_by_reference_owned)
})
.collect();
let mut has_spread = call.args.iter().any(|a| a.unpack);
let mut arity_unknown = has_spread;
// A sole spread arg over a literal, sequentially-keyed shape can be
// expanded into one binding per element so each parameter (and
// template-binding inference below) is checked individually instead
// of only the first (see expand_sole_spread_arg). `arity_unknown`
// stays true even after expansion — PHP allows extra/spread
// positional args, so a concretely-known count still shouldn't
// trigger TooFew/TooManyArguments.
if let Some(expanded) = sole_spread_ty
.take()
.and_then(|t| expand_sole_spread_arg(&t))
{
arg_spans = distinct_spans_for_expansion(arg_spans[0], expanded.len());
arg_names = vec![None; expanded.len()];
arg_can_be_byref = vec![false; expanded.len()];
arg_types = expanded;
has_spread = false;
arity_unknown = true;
}
// `Foo::bar()` has no receiver value to carry type params, so the
// seed is empty and class-level bindings come solely from `fqcn`'s
// own `@extends`/`@implements` chain. `$var::bar()`/`$this::bar()`
// seeds `receiver_type_params` from the receiver's own concrete
// type args (e.g. `int` from a `Box<int>` receiver) the same way
// method.rs's instance-call path does, so a class-level `@template`
// bound on the receiver resolves instead of leaking through raw.
let class_tps = crate::db::class_template_params(ea.db, &fqcn).unwrap_or_default();
let mut class_bindings = build_class_bindings(&class_tps, &receiver_type_params);
let inherited_class_bindings =
crate::db::inherited_template_bindings(ea.db, &fqcn, &class_bindings);
// The resolved method's params/return/out-types are declared on
// `resolved.owner_fqcn` — a bare template name in its signature
// is the RECEIVER's own template only when the receiver itself
// declares the method; otherwise it's scoped to the ancestor
// that actually declares it (same collision the property-access/
// instance-method-call/foreach/array-access sites already guard
// against).
if resolved.owner_fqcn.as_ref() == fqcn.as_str() {
for (k, v) in inherited_class_bindings {
class_bindings.entry(k).or_insert(v);
}
} else {
class_bindings.extend(inherited_class_bindings);
}
// A class-level `@template T of Bound` was previously only ever
// checked at `new Box(...)` construction sites — a receiver typed
// `Box<NotAnimal>` via a docblock/param annotation instead sailed
// through every static/self/parent call unchecked, regardless of
// whether the called method itself declares its own template params.
for (name, inferred, bound) in check_template_bounds_with_inheritance(
ea.db,
&class_bindings,
&class_tps,
&Default::default(),
Some(bound_receiver_fqcn.as_str()),
) {
ea.emit(
IssueKind::InvalidTemplateParam {
name: name.to_string(),
expected_bound: format!("{bound}"),
actual: format!("{inferred}"),
},
Severity::Error,
span,
);
}
let mut param_bindings = class_bindings.clone();
for tp in resolved.template_params.iter() {
param_bindings.remove(&Name::from(tp.name.as_ref()));
}
let substituted_params: Vec<DeclaredParam>;
let effective_params: &[DeclaredParam] = if param_bindings.is_empty() {
&resolved.params
} else {
substituted_params = resolved
.params
.iter()
.map(|p| DeclaredParam {
ty: mir_codebase::wrap_param_type(
p.ty.as_ref()
.map(|t| t.substitute_templates(¶m_bindings)),
),
..p.clone()
})
.collect();
&substituted_params
};
check_args(
ea,
CheckArgsParams {
fn_name: method_name,
params: effective_params,
arg_types: &arg_types,
arg_spans: &arg_spans,
arg_names: &arg_names,
arg_can_be_byref: &arg_can_be_byref,
call_span: span,
has_spread,
arity_unknown,
too_many_arity_unknown: false,
template_params: &resolved.template_params,
no_named_arguments: resolved.no_named_arguments,
},
);
// `self::`/`static::`/`parent::`/`$this::` forwarding a
// non-static method call still runs against the current `$this`
// — a call we can't prove pure/mutation-free may reassign its
// properties, staling narrowing recorded before the call.
if is_self_parent_call
&& !resolved.is_static
&& !resolved.is_pure
&& !resolved.is_mutation_free
{
ctx.invalidate_prop_refined_receiver("this");
}
// A genuinely static call (`Foo::bar()`) has no receiver object,
// but may still mutate `fqcn`'s own static properties — only
// `is_pure` (not `is_mutation_free`, which is documented as
// scoped to `$this`) is a trustworthy "touches nothing" signal
// here, mirroring the `is_in_pure_fn` check above.
if resolved.is_static && !resolved.is_pure {
ctx.invalidate_prop_refined_receiver(&fqcn);
}
// An object passed as an argument may have its own properties
// reassigned inside a callee that isn't proven pure/external-
// mutation-free, regardless of what's being called on.
if !resolved.is_pure && !resolved.is_external_mutation_free {
for arg in call.args.iter() {
if let Some(ExprKind::Variable(name)) = arg.value.as_ref().map(|v| &v.kind) {
ctx.invalidate_prop_refined_receiver(name);
}
}
}
// Taint sink check: emit the matching Tainted* issue when a tainted
// value reaches a @taint-sink annotated parameter. Mirrors the
// instance-call check in call/method.rs, which this static-call
// path never had at all.
if !resolved.taint_sink_params.is_empty() {
for (param_name, sink_kind) in &resolved.taint_sink_params {
let param_idx = resolved
.params
.iter()
.position(|p| p.name.as_ref() == param_name.as_ref());
let is_variadic = param_idx
.and_then(|idx| resolved.params.get(idx))
.is_some_and(|p| p.is_variadic);
let args: Vec<&php_ast::owned::Arg> = if is_variadic {
let idx = param_idx.unwrap();
call.args
.iter()
.filter(|a| a.name.is_none())
.skip(idx)
.collect()
} else {
let positional = param_idx.and_then(|idx| call.args.get(idx));
let named_arg = call.args.iter().find(|a| {
a.name
.as_ref()
.map(|n| {
crate::parser::name_to_string_owned(n) == param_name.as_ref()
})
.unwrap_or(false)
});
positional.or(named_arg).into_iter().collect()
};
for arg in args {
let Some(value) = &arg.value else { continue };
if is_expr_tainted(value, ctx, ea.db, &ea.file) {
ea.emit(taint_sink_issue(sink_kind), Severity::Error, span);
}
}
}
}
let owner_fqcn = resolved.owner_fqcn.clone();
let ret_raw = resolved.return_ty_raw;
let method_bindings = if !resolved.template_params.is_empty() {
let (bindings, unchecked) = infer_template_bindings(
ea.db,
&resolved.template_params,
effective_params,
&arg_types,
&arg_names,
);
// Static calls (`Foo::bar()`, `self::bar()`, `parent::bar()`)
// previously never checked the method's own `@template ... of
// Bound` at all — only instance-method and function calls did.
for (name, inferred, bound) in check_template_bounds_with_inheritance(
ea.db,
&bindings,
&resolved.template_params,
&unchecked,
Some(bound_receiver_fqcn.as_str()),
) {
ea.emit(
IssueKind::InvalidTemplateParam {
name: name.to_string(),
expected_bound: format!("{bound}"),
actual: format!("{inferred}"),
},
Severity::Error,
span,
);
}
// Only warn about template shadowing when the declaring class lives
// in the file under analysis — mirrors method.rs's instance-call
// check, which a static call (Foo::bar()) previously never got at
// all despite computing an equivalent class_bindings/method
// bindings pair right here.
let declared_here = crate::db::class_like_decl_file(
ea.db,
crate::db::Fqcn::from_str(ea.db, resolved.owner_fqcn.as_ref()),
)
.is_some_and(|f| f.as_ref() == ea.file.as_ref());
if declared_here {
for key in bindings.keys() {
if class_bindings.contains_key(key) {
ea.emit(
IssueKind::ShadowedTemplateParam {
name: key.to_string(),
},
Severity::Info,
span,
);
}
}
}
Some(bindings)
} else {
None
};
// The CLASS's own template (as opposed to `resolved.template_params`,
// the METHOD's own separately-declared templates) isn't otherwise
// bound for a bare `Foo::make(...)` call with no concretizing
// subclass — infer it from the call's arguments the same way `new
// Foo(...)` does for constructors (`infer_new_type_params`), so a
// `@return static`/`@return T` on a static factory resolves to
// the concrete type instead of leaking the bare class template. A
// declared binding (from `@extends`/`@implements`, e.g. a
// concretizing subclass) still takes precedence over one merely
// inferred from this call's arguments.
// A plain subclass that doesn't redeclare `@template` (`class
// IntBox extends Box {}`) still shares Box's template slot, so
// `IntBox::make(42)` must infer against Box's declared params —
// walk up to the nearest ancestor that actually declares them.
// (`class_tps` is already computed above, alongside `class_bindings`.)
let class_arg_bindings: FxHashMap<Name, Type> = if class_tps.is_empty() {
FxHashMap::default()
} else {
infer_arg_template_bindings(
ea.db,
&class_tps,
&resolved.params,
&arg_types,
&arg_names,
)
.0
.into_iter()
.map(|(name, ty)| (name, widen_own_type_param(&ty)))
.collect()
};
let return_class_bindings: FxHashMap<Name, Type> = if class_arg_bindings.is_empty() {
class_bindings.clone()
} else {
let mut merged = class_arg_bindings;
for (name, ty) in class_bindings.iter() {
merged.insert(*name, ty.clone());
}
merged
};
// `static`'s receiver type params come from the CLASS's own
// template params, not the method's — attach them before
// substituting `static`/`self` in the return type, or a bare
// `@return static` resolves to an unparameterized `Box` and
// erases them entirely.
let own_type_params: Vec<Type> = class_tps
.iter()
.map(|tp| {
return_class_bindings
.get(&Name::from(tp.name.as_ref()))
.cloned()
.unwrap_or_else(Type::mixed)
})
.collect();
let ret_substituted = substitute_static_in_return(ret_raw, &fqcn_arc, &own_type_params);
let ret_substituted = if return_class_bindings.is_empty() {
ret_substituted
} else {
ret_substituted.substitute_templates(&return_class_bindings)
};
let ret = match &method_bindings {
Some(bindings) => ret_substituted.substitute_templates(bindings),
None => ret_substituted,
};
let ret = crate::call::resolve_conditional_return(ret, ea.db, |param_name| {
// `@return ($this is X ? A : B)`: `self::method()`/
// `static::method()`/`parent::method()` still has a real
// `$this` when called from inside an instance method —
// resolve it to the same receiver `static`/`self` already
// substitutes into the return type above, instead of
// leaving it permanently unresolved (never a declared
// parameter).
if param_name == "this" {
return Some(Type::single(mir_types::Atomic::TNamedObject {
fqcn: Name::new(fqcn_arc.as_ref()),
type_params: own_type_params.clone().into(),
}));
}
resolved
.params
.iter()
.position(|p| p.name.as_ref() == param_name)
.and_then(|idx| {
crate::call::resolve_named_arg_type_index(&resolved.params, &call.args, idx)
})
.and_then(|idx| arg_types.get(idx))
.cloned()
});
// Write @param-out types back to caller variables for by-ref params.
// Substitute the same bindings the return type uses (class template
// from `@extends`/inferred-from-args, then the method's own), so a
// generic method's out-type resolves the class's bound type param
// instead of leaking the bare template name to the caller.
let mut out_bindings = return_class_bindings.clone();
if let Some(mb) = &method_bindings {
for (k, v) in mb.iter() {
out_bindings.insert(*k, v.clone());
}
}
// A by-ref argument that's a property mutates it exactly as much
// as an explicit write would, regardless of whether the param
// also declares `@param-out` — checked in its own pass since the
// loop below only ever runs for `@param-out`-declared params.
for (i, param) in resolved.params.iter().enumerate() {
if !param.is_byref {
continue;
}
if param.is_variadic {
for arg in call.args.iter().skip(i) {
let Some(value) = &arg.value else { continue };
ea.check_byref_arg_purity(value, ctx, value.span);
}
} else if let Some(value) =
crate::call::resolve_named_arg_type_index(&resolved.params, &call.args, i)
.and_then(|idx| call.args.get(idx))
.and_then(|arg| arg.value.as_ref())
{
ea.check_byref_arg_purity(value, ctx, value.span);
}
}
// A by-ref output parameter's written-back value derives from
// the call's own arguments (e.g. `preg_match`'s `$matches`
// derives from the tainted subject) — conservatively taint (or
// clear) it the same "sticky" way `.=`/`??=` already treat
// their own result, rather than leaving its taint bit untouched
// from whatever it happened to hold before the call.
let any_arg_tainted = call.args.iter().any(|arg| {
arg.value
.as_ref()
.is_some_and(|v| is_expr_tainted(v, ctx, ea.db, &ea.file))
});
for (i, param) in resolved.params.iter().enumerate() {
let Some(out_ty) = param.out_ty.as_ref() else {
continue;
};
// `@param-out self`/`@param-out static` must resolve to the receiver's
// concrete class, the same way `@return static` already does.
let out_ty =
substitute_static_in_return((**out_ty).clone(), &fqcn_arc, &own_type_params);
let out_ty = if out_bindings.is_empty() {
out_ty
} else {
out_ty.substitute_templates(&out_bindings)
};
if param.is_variadic {
for arg in call.args.iter().skip(i) {
let Some(value) = &arg.value else { continue };
if let ExprKind::Variable(name) = &value.kind {
let var_name = name.as_ref().trim_start_matches('$');
ctx.set_var(var_name, out_ty.clone());
if any_arg_tainted {
ctx.taint_var(var_name);
} else {
ctx.clear_var_taint(var_name);
}
}
}
} else if let Some(value) =
crate::call::resolve_named_arg_type_index(&resolved.params, &call.args, i)
.and_then(|idx| call.args.get(idx))
.and_then(|arg| arg.value.as_ref())
{
if let ExprKind::Variable(name) = &value.kind {
let var_name = name.as_ref().trim_start_matches('$');
ctx.set_var(var_name, out_ty);
if any_arg_tainted {
ctx.taint_var(var_name);
} else {
ctx.clear_var_taint(var_name);
}
}
}
}
// Bare-statement `@psalm-assert` — the static-call counterpart
// of `call/function.rs`'s unconditional-assert block and
// `call/method.rs`'s instance-call one. Reuses the exact
// per-assertion body the conditional if-true/if-false dispatch
// uses (`apply_one_assertion`), which this hand-duplicated loop
// never did: it never read `assertion.param_key`, never handled
// a variadic param, and never resolved a named argument.
// `out_bindings` is the fully merged class + method template
// scope computed above.
for assertion in resolved
.assertions
.iter()
.filter(|a| a.kind == AssertionKind::Assert)
{
crate::narrowing::apply_one_assertion(
assertion,
&resolved.params,
&call.args,
Some(&call.class),
ctx,
Some(&out_bindings),
ea.db,
&ea.file,
);
}
// `@if-this-is X<Y>` on a method reached through self::/static::/
// parent:: — mirrors the instance-call-syntax handling in
// `resolve_method_return`, which `analyze_static_method_call` never
// invoked at all, so this idiom silently never fired for the
// (more common) self::/static:: call syntax, only `$this->method()`.
// Also applies to `$var::staticMethod()` through an object-typed
// variable (the `_` catch-all match arm above, which already
// extracted `fqcn`/`receiver_type_params` from the receiver's own
// concrete type for return-type substitution) — previously only
// self/static/parent/`$this` calls were checked at all.
let is_object_var_call = !matches!(&call.class.kind, ExprKind::Identifier(_));
if is_self_parent_call || is_object_var_call {
if let Some(original_constraint) = resolved.if_this_is.clone() {
// Substitute this call's own inferred method-level
// template bindings (`out_bindings`, already the fully
// merged class + method map by this point) before the
// comparison — otherwise a constraint referencing the
// METHOD's own `@template` (as opposed to the class's,
// already resolved into `receiver_type_params`) always
// compared against a bare, unsubstituted atom and could
// never actually contradict. Mirrors the identical fix
// in `resolve_method_return` (call/method.rs).
let constraint = original_constraint.substitute_templates(&out_bindings);
let receiver_type_params = if is_self_parent_call {
extract_receiver_type_params(&ctx.get_var("this"), &fqcn_arc)
} else {
receiver_type_params.clone()
};
let constraint_has_params = constraint.types.iter().any(|a| {
matches!(a, Atomic::TNamedObject { type_params, .. } if !type_params.is_empty())
});
let receiver_has_unresolved_template = receiver_type_params.iter().any(|t| {
t.types
.iter()
.any(|a| matches!(a, Atomic::TTemplateParam { .. }))
});
if !receiver_has_unresolved_template
&& (!receiver_type_params.is_empty() || !constraint_has_params)
{
let receiver = Type::single(Atomic::TNamedObject {
fqcn: Name::new(fqcn_arc.as_ref()),
type_params: receiver_type_params.to_vec().into(),
});
if !crate::subtype::is_subtype(ea.db, &receiver, &constraint) {
ea.emit(
IssueKind::IfThisIsMismatch {
class: fqcn.clone(),
method: method_name.to_string(),
// Display the original (unsubstituted)
// constraint — an unbindable method
// template defaults to mixed, which
// renders as if the generic were absent
// entirely (see call/method.rs's
// identical fix for the full rationale).
expected: format!("{original_constraint}"),
actual: format!("{receiver}"),
},
Severity::Info,
span,
);
}
}
}
}
// `@psalm-self-out Type` on a method reached through self::/static::/
// parent:: retypes the implicit `$this` receiver, mirroring the
// instance-call-syntax handling in `analyze_method_call`. A plain
// `Foo::bar()` (not a self-referential call) has no `$this` receiver
// for this call to have narrowed, so it's left alone.
if is_self_parent_call {
if let Some(self_out_raw) = resolved.self_out.clone() {
// Mirrors the plain-return-type computation above: `static<T>`
// in `@psalm-self-out` needs the same receiver type params
// (own template args inferred from this call's arguments,
// merged with any `@extends`/`@implements`-declared binding)
// or the class's own type argument is erased entirely.
let self_out_ty = substitute_static_in_return(
(*self_out_raw).clone(),
&fqcn_arc,
&own_type_params,
);
let self_out_ty = if return_class_bindings.is_empty() {
self_out_ty
} else {
self_out_ty.substitute_templates(&return_class_bindings)
};
let self_out_ty = if !resolved.template_params.is_empty() {
let (mut method_bindings, _unchecked) = infer_template_bindings(
ea.db,
&resolved.template_params,
effective_params,
&arg_types,
&arg_names,
);
for v in method_bindings.values_mut() {
*v = crate::stmt::widen_for_check(v.clone());
}
self_out_ty.substitute_templates(&method_bindings)
} else {
self_out_ty
};
ctx.set_var("this", self_out_ty);
}
}
ea.record_symbol(
call.method.span,
ReferenceKind::StaticCall {
class: owner_fqcn,
method: Arc::from(method_name),
},
ret.clone(),
);
ret
} else if crate::db::class_exists(ea.db, &fqcn)
&& !crate::db::has_unknown_ancestor(ea.db, &fqcn)
{
let (is_abstract, is_trait) = crate::db::class_kind(ea.db, &fqcn)
.map(|k| (k.is_abstract, k.is_trait))
.unwrap_or((false, false));
// Check for __callStatic in the full inheritance chain (not just direct methods)
let has_callstatic_magic = crate::db::has_method_in_chain(ea.db, &fqcn, "__callstatic");
// Suppress when caller guarded with `method_exists(Foo::class, 'method')`
// (literal class name — keyed by the already-resolved `fqcn`) or
// `method_exists($cls, 'method')` (dynamic class-string variable).
let guard_key: Option<Arc<str>> = match &call.class.kind {
ExprKind::Identifier(_) => Some(Arc::from(format!("cls:{fqcn}").as_str())),
_ => extract_expr_guard_key(&call.class, ctx, ea.db, &ea.file),
};
let guarded_by_method_exists = guard_key
.map(|key| {
ctx.method_exists_guards.contains(&(
key,
Arc::from(crate::util::php_ident_lowercase(method_name).as_str()),
))
})
.unwrap_or(false);
// The method didn't resolve, but the class itself is real
// (`class_exists` above) — scope the posting to it directly
// rather than the class-agnostic `methname:` bucket. The bare
// bucket is reserved for genuinely un-nameable dynamic dispatch
// (`analyze_static_dyn_method_call`'s `dyn:`/mixed-receiver
// fallback); using it here let an `UndefinedMethod` call on this
// class collide with an unrelated same-named method anywhere else
// in the workspace — both a find-references false positive and,
// on a common name like `__construct`, a bucket-size blowup.
ea.record_ref(
Arc::from(format!(
"meth:{fqcn}::{}",
crate::util::php_ident_lowercase(method_name)
)),
call.method.span,
);
if is_trait {
// The call may be satisfied by whichever class ends up consuming
// this trait — record a per-trait marker so DeadCodeAnalyzer can
// credit any composing class's own private method of this name
// as used, instead of only ever seeing the trait's own (failed)
// resolution attempt. Mirrors the instance-call path in method.rs.
ea.record_ref(
Arc::from(format!("traituse:{fqcn}::{method_name_lower}")),
call.method.span,
);
}
// In a trait body, self::/static:: resolve to the consuming class,
// which may provide the method — not undefined.
if is_abstract || is_trait || has_callstatic_magic || guarded_by_method_exists {
Type::mixed()
} else {
ea.emit(
IssueKind::UndefinedMethod {
class: fqcn,
method: method_name.to_string(),
},
Severity::Error,
span,
);
Type::mixed()
}
} else if !crate::db::class_exists(ea.db, &fqcn)
&& !matches!(fqcn.as_str(), "self" | "static" | "parent")
&& !ctx.is_class_guarded(fqcn.as_str())
{
// The class itself couldn't be resolved, but `fqcn` is still a
// concrete name (e.g. an external/vendor FQCN we just have no
// source for) — scope the posting to it, same reasoning as the
// known-class-unresolved-method branch above. This is what keeps
// e.g. `parent::__construct()` through an unresolved external
// base class from colliding with an unrelated `Foo::__construct`
// in the bare `methname:__construct` bucket.
ea.record_ref(
Arc::from(format!(
"meth:{fqcn}::{}",
crate::util::php_ident_lowercase(method_name)
)),
call.method.span,
);
ea.emit(
IssueKind::UndefinedClass { name: fqcn },
Severity::Error,
call.class.span,
);
Type::mixed()
} else {
// Reached when: the class exists but has an unresolved ancestor
// (method resolution can't be fully verified), the class doesn't
// exist but is guarded by a `class_exists()`/`extension_loaded()`
// check, or `self`/`static`/`parent` itself never resolved to a
// concrete class (e.g. used outside a class body). Only the last
// case has no real class name to scope the posting to.
let key = if matches!(fqcn.as_str(), "self" | "static" | "parent") {
format!("methname:{}", crate::util::php_ident_lowercase(method_name))
} else {
format!(
"meth:{fqcn}::{}",
crate::util::php_ident_lowercase(method_name)
)
};
ea.record_ref(Arc::from(key), call.method.span);
Type::mixed()
}
}
pub fn analyze_static_dyn_method_call<'a>(
ea: &mut ExpressionAnalyzer<'a>,
call: &StaticDynMethodCallExpr,
ctx: &mut FlowState,
) -> Type {
// The called method's name isn't statically known — mark the target
// class as dynamically accessed so DeadCodeAnalyzer doesn't flag its
// private members as unused, mirroring the instance-call fallback.
if let ExprKind::Identifier(name) = &call.class.kind {
let resolved = crate::db::resolve_name(ea.db, &ea.file, name.as_ref());
let fqcn = resolve_static_class(&resolved, ctx);
if !matches!(fqcn.as_str(), "self" | "static" | "parent") {
ea.record_ref(Arc::from(format!("dyn:{fqcn}")), call.method.span);
}
} else {
let class_ty = ea.analyze(&call.class, ctx);
ea.record_dynamic_member_access(&class_ty, call.method.span);
}
ea.analyze(&call.method, ctx);
for arg in call.args.iter() {
let Some(value) = &arg.value else { continue };
ea.analyze(value, ctx);
super::consume_arg_assignment(value, ctx);
if let ExprKind::Variable(name) = &value.kind {
ctx.invalidate_prop_refined_receiver(name);
}
}
// The called method's name is unknown, so its purity can't be
// checked — conservatively assume it may mutate `$this` (a
// self::/static::/parent:: forward) and, when the target class is
// known, that class's own static properties.
ctx.invalidate_prop_refined_receiver("this");
if let ExprKind::Identifier(name) = &call.class.kind {
let resolved = crate::db::resolve_name(ea.db, &ea.file, name.as_ref());
let fqcn = resolve_static_class(&resolved, ctx);
ctx.invalidate_prop_refined_receiver(&fqcn);
}
Type::mixed()
}
}
fn resolve_static_class(name: &str, ctx: &FlowState) -> String {
match crate::util::php_ident_lowercase(name).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(),
}
}