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
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
/// Analysis dataflow and lexical scope state — carries type state through statement/expression analysis.
use rustc_hash::{FxHashMap, FxHashSet};
use std::sync::Arc;
use mir_types::{Name, Type};
/// FQCNs known to exist in the current branch due to a `class_exists()` /
/// `interface_exists()` / `trait_exists()` guard. Not Arc-wrapped — it is
/// small and branch-local (cleared at merge unless one branch diverges).
type ClassExistsGuards = FxHashSet<Arc<str>>;
/// A dead write: `(variable, line, col_start, line_end, col_end)`.
type DeadWrite = (Name, u32, u16, u32, u16);
/// Append `src` dead writes onto `dst`, skipping entries already present.
///
/// Critical for bounding memory in `merge_branches`: both branch contexts are
/// derived from `pre`, so each already contains all of `pre`'s dead writes.
/// Naively concatenating them onto a `pre`-derived `dst` re-includes `pre`'s
/// entries on every merge — under nested-loop fixpoint analysis the `Vec` then
/// grows multiplicatively (≈3× per merge → exponential, reaching gigabytes).
/// A dead write is uniquely identified by its `(variable, location)` tuple, so
/// deduplication is also semantically correct (one diagnostic per location).
fn extend_dead_writes_dedup(dst: &mut Vec<DeadWrite>, src: Vec<DeadWrite>) {
if src.is_empty() {
return;
}
let mut seen: FxHashSet<DeadWrite> = dst.iter().copied().collect();
for dw in src {
if seen.insert(dw) {
dst.push(dw);
}
}
}
// ---------------------------------------------------------------------------
// FlowState
// ---------------------------------------------------------------------------
#[derive(Debug, Clone)]
pub struct FlowState {
/// Types of variables at this point in execution.
/// Arc-wrapped for COW semantics: fork() is O(1); mutations trigger a copy only on first write.
/// Values are Arc<Type> so ptr_eq short-circuits merge_branches for unchanged vars.
pub vars: Arc<FxHashMap<Name, Arc<Type>>>,
/// Variables that are definitely assigned at this point.
pub assigned_vars: Arc<FxHashSet<Name>>,
/// Variables that *might* be assigned (e.g. only in one if branch).
pub possibly_assigned_vars: Arc<FxHashSet<Name>>,
/// The class in whose body we are analysing (`self`).
pub self_fqcn: Option<Arc<str>>,
/// The parent class (`parent`).
pub parent_fqcn: Option<Arc<str>>,
/// Late-static-binding class (`static`).
pub static_fqcn: Option<Arc<str>>,
/// Declared return type for the current function/method.
pub fn_return_type: Option<Type>,
/// Declared exception types for the current function/method (@throws).
pub fn_declared_throws: Arc<[Arc<str>]>,
/// Whether we are currently inside a loop.
pub inside_loop: bool,
/// Whether we are currently inside a finally block.
pub inside_finally: bool,
/// Whether the current function body contains a `yield` expression, making
/// it a generator. Set via pre-scan before statement analysis begins so
/// that early `return;` before the first yield is not misreported.
pub is_generator: bool,
/// Whether we are inside a constructor.
pub inside_constructor: bool,
/// The name of the method currently being analyzed (e.g. `"__wakeup"`).
/// `None` for free functions and closures.
pub current_method_name: Option<Arc<str>>,
/// The FQN of the free function currently being analyzed, if any.
/// `None` for methods (use `self_fqcn` + `current_method_name` instead)
/// and for closures. Lets a callee identify "which function am I in" so
/// it can look up its own declared parameters — e.g. to resolve an
/// opaque `callable` parameter's return type from how *callers* invoke
/// this function (`call::opaque_callback`).
pub current_function_fqn: Option<Arc<str>>,
/// Whether we are inside a @pure function/method body.
pub is_in_pure_fn: bool,
/// Whether we are inside a non-constructor method of a `@psalm-immutable` class.
/// Triggers `ImmutablePropertyModification` on `$this->prop = ...` assignments.
pub is_in_immutable_method: bool,
/// Whether we are inside a `@psalm-external-mutation-free` method.
/// Triggers `ImpureMethodCall`/`ImpurePropertyAssignment` when mutating objects
/// received as parameters (but allows `$this` mutations).
pub is_in_external_mutation_free_method: bool,
/// Whether we are inside a static method body.
pub inside_static_method: bool,
/// Whether `strict_types=1` is declared for this file.
pub strict_types: bool,
/// Variables that carry tainted (user-controlled) values at this point.
/// Used by taint analysis (M19).
pub tainted_vars: FxHashSet<Name>,
/// Instance properties that carry tainted (user-controlled) values at
/// this point, tracked the same way `prop_refined` tracks narrowed
/// types. Key: `(object_var, prop_name)`. Set by a tainted property
/// assignment (`$obj->prop = $_GET['x']`); read by `taint::is_expr_tainted`
/// so a later `$obj->prop` access is recognized as tainted.
pub tainted_props: FxHashSet<(Name, Name)>,
/// Static properties that carry tainted (user-controlled) values at this
/// point. Key: `(fqcn, prop_name)`, mirroring how `prop_refined`'s static
/// counterpart is keyed by FQCN instead of a receiver variable name (a
/// FQCN can never collide with a real PHP variable name).
pub tainted_static_props: FxHashSet<(Name, Name)>,
/// Local variables ref-aliased directly to a var-receiver property
/// (`$x =& $this->prop;`), keyed by the alias variable name, value is
/// `(receiver_var, prop_name)`. A later PLAIN `$x = value` write mutates
/// the aliased property through the reference — consulted by
/// `check_property_write_purity_by_name` so that write runs the same
/// purity/immutability gate a direct `$this->prop = value` write already
/// does. Narrow: only this one AST-visible pattern is tracked, not
/// general PHP reference semantics (ref params, `foreach(&$v)`, ref
/// returns, chained aliases). Once set, an alias is never cleared within
/// a scope — a plain reassignment of `$x` does not break the PHP
/// reference, so every subsequent `$x = value` keeps mutating the
/// property too.
pub ref_aliases: FxHashMap<Name, (Name, Name)>,
/// Local variables directly assigned from a bare `clone $expr` expression
/// (`$clone = clone $this;`), keyed by the variable's own name. A write
/// through such a variable (`$clone->x = $value;`, the standard immutable
/// "wither" idiom) is not an externally-visible mutation the way a write
/// through a parameter or `$this` would be — the clone is a fresh,
/// unaliased object nothing else can observe yet — so
/// `check_property_write_purity`'s cross-class immutable-write check
/// consults this set to exempt it. Cleared on any subsequent plain
/// reassignment of the same variable to something that isn't itself a
/// clone, since the new value may no longer be a fresh, unaliased object.
pub cloned_local_vars: FxHashSet<Name>,
/// Variables that have been read at least once in this scope.
/// Used by UnusedParam detection (M18).
pub read_vars: FxHashSet<Name>,
/// Names of function/method parameters in this scope (stripped of `$`).
/// Used to exclude parameters from UnusedVariable detection.
/// Arc-shared — set once at context construction, never mutated during analysis.
pub param_names: Arc<FxHashSet<Name>>,
/// Names of by-reference parameters in this scope (stripped of `$`).
/// Assigning to these is externally observable, so it counts as usage.
/// Arc-shared — set once at context construction, never mutated during analysis.
pub byref_param_names: Arc<FxHashSet<Name>>,
/// Names of `static $var`-declared local variables (stripped of `$`),
/// inserted dynamically as each declaration is analyzed (mirrors
/// `byref_param_names`'s own dynamic insertion for `global $x;`).
/// Consulted by `check_var_write_purity`/`assign_to_target`'s `Variable`
/// arm so a later WRITE to the persistent cross-call state a `static`
/// var holds can be checked under @mutation-free/@external-mutation-free
/// — unlike the declaration site's own `is_in_pure_fn`-only check, which
/// already covers @pure regardless of whether the var is later written.
pub static_var_names: Arc<FxHashSet<Name>>,
/// Each parameter's declared (docblock-merged) type, stripped of `$`.
/// Unlike `vars`, this is never updated by narrowing — it's the original
/// contract, used as a generalization ceiling when a narrowed array type
/// widens back out (e.g. after a shape grows past its size cap).
/// Arc-shared — set once at context construction, never mutated during analysis.
pub declared_var_types: Arc<FxHashMap<Name, Type>>,
/// Whether every execution path through this context has diverged
/// (returned, thrown, or exited). Used to detect "all catch branches
/// return" so that variables assigned only in the try body are
/// considered definitely assigned after the try/catch.
pub diverges: bool,
/// Set once a variable-variable assignment (`${$name} = …`) whose target
/// name cannot be resolved statically is seen on this path. Such an
/// assignment may define arbitrarily-named variables, so subsequent reads of
/// otherwise-unknown variables must not be reported as `UndefinedVariable`
/// (matching Psalm). Monotonic: once set it propagates through clones/merges.
pub has_dynamic_var_def: bool,
/// Set once a dynamic-name `compact()` call (`compact($names)`/`compact(...$names)`)
/// is seen on this path. Such a call reads an arbitrarily-named set of variables,
/// so a write anywhere in scope must not be reported as `UnusedVariable`/dead-write.
/// Monotonic like `has_dynamic_var_def`, for the same reason.
pub has_dynamic_var_read: bool,
/// Set once an `extract()` call whose source array is tainted is seen on
/// this path (`extract($_GET)`). `extract()` defines variables whose
/// names are only known at runtime (`has_dynamic_var_def` already
/// handles the "don't report undefined" side of that) — this is the
/// taint counterpart: any later read of an otherwise-untracked variable
/// must be treated as possibly tainted too, since it may be one
/// `extract()` just defined from attacker-controlled data. Monotonic
/// like `has_dynamic_var_def`, for the same reason.
pub has_dynamic_tainted_var_def: bool,
/// Pre-converted (line, col_start, line_end, col_end) of the first assignment
/// to each variable. Used to emit accurate locations for UnusedVariable / UnusedParam.
pub var_locations: FxHashMap<Name, (u32, u16, u32, u16)>,
/// Tracks unread write locations per variable.
/// When a variable is written, its entry is replaced. When the variable
/// is read as an r-value, its entry is removed (the writes were consumed).
/// Entries remaining at end-of-scope are dead (last write never read).
/// Multiple locations arise from branch merges where different paths left
/// different writes pending (e.g. a pre-loop write and a loop-body write):
/// a later read consumes ALL of them, since any could be the live value.
pub last_write_locs: FxHashMap<Name, Vec<(u32, u16, u32, u16)>>,
/// Dead writes collected during analysis: writes that were overwritten
/// without being read first. Accumulated via union across branches.
pub dead_writes: Vec<(Name, u32, u16, u32, u16)>,
/// Write locations that were consumed by a read on SOME path. A write is
/// only dead if NO path reads it, so consumption is permanent: merges
/// union this set and filter pending/dead writes against it, and the
/// end-of-scope report skips consumed locations. Fixes false positives
/// like `$x = new stdClass; foreach (...) { $x = $v; } return $x === ...`
/// where the pre-loop write is overwritten in the body but read on the
/// loop-never-ran path.
pub consumed_write_locs: FxHashSet<(Name, (u32, u16, u32, u16))>,
/// Variables that are foreach iteration values in this scope.
/// Used to emit UnusedForeachValue instead of UnusedVariable for these names.
pub foreach_value_var_names: FxHashSet<Name>,
/// Variables bound by a by-reference foreach (`foreach ($arr as &$val)`).
/// Writes to these variables always have a side effect (they mutate the
/// source array through the reference), so dead-write detection must not
/// flag them as UnusedVariable.
pub foreach_byref_var_names: FxHashSet<Name>,
/// Variables bound by a catch clause (`catch (Exception $e)`).
/// These are declared by the runtime, not by developer assignment, so an
/// unused catch variable must not produce an UnusedVariable diagnostic.
pub catch_var_names: FxHashSet<Name>,
/// Names of template parameters in the current function/method.
/// Used during type narrowing to correctly handle generic template variables.
/// Arc-shared — set once at context construction, never mutated during analysis.
pub template_param_names: Arc<FxHashSet<Name>>,
/// Names of function/method parameters whose declared types were expanded
/// from template param bounds (e.g. `@template T of Exception` + `@param T $e`).
/// Throw analysis uses this to suppress `MissingThrowsDocblock` when a
/// parameter of generic exception type is re-thrown — the caller owns the
/// `@throws` declaration, not the generic helper.
pub template_typed_params: Arc<FxHashSet<Name>>,
/// FQCNs proven to exist in this branch via a `class_exists()` /
/// `interface_exists()` / `trait_exists()` guard. Used to suppress
/// `UndefinedClass` diagnostics inside guarded branches.
pub class_exists_guards: ClassExistsGuards,
/// Constant names proven to exist in this branch via a `defined('NAME')`
/// guard. Used to suppress `UndefinedConstant` inside guarded branches.
pub defined_guards: ClassExistsGuards,
/// Function names proven to exist in this branch via a
/// `function_exists('fn')` guard. Used to suppress `UndefinedFunction`
/// inside guarded branches.
pub function_exists_guards: ClassExistsGuards,
/// `(expr_key, method_name)` pairs proven to exist via a `method_exists($expr, 'method')`
/// guard. Used to suppress `UndefinedMethod` inside guarded branches.
/// `expr_key` is a compact string like `"this->notification"` or `"foo"`.
pub method_exists_guards: FxHashSet<(Arc<str>, Arc<str>)>,
/// `(expr_key, property_name)` pairs proven to exist via a
/// `property_exists($expr, 'prop')` or `isset($expr->prop)` guard. Used to
/// suppress `UndefinedProperty` inside guarded branches (dynamic/BC
/// properties not declared on the class). Same `expr_key` shape as
/// `method_exists_guards`.
pub property_exists_guards: FxHashSet<(Arc<str>, Arc<str>)>,
/// Extension names proven to be loaded via an `extension_loaded('name')` guard.
/// When non-empty, `UndefinedClass` is suppressed for any class in the guarded
/// block — the calling code explicitly verified the extension is present.
pub extension_loaded_guards: FxHashSet<Arc<str>>,
/// Narrowed/refined types for instance-property accesses tracked through
/// the current scope. Key: `(object_var, prop_name)` e.g. `("this", "id")`.
/// Set by property assignments and null-guard narrowing; read by
/// `analyze_property_access` before falling back to the declared type.
pub prop_refined: Arc<FxHashMap<(Name, Name), Arc<Type>>>,
/// Readonly properties (native or `@readonly`) definitely assigned at
/// least once on every path reaching this point, keyed like
/// `prop_refined`. Populated only for writes inside the scope PHP allows
/// to initialize a readonly property (the declaring class's constructor,
/// or — for native `readonly` — any method of the declaring class).
/// Consulted before recording a further write to the same property, to
/// catch PHP's "cannot modify readonly property once initialized" at
/// analysis time (e.g. two assignments to the same property in one
/// constructor). Merged by intersection across branches: a property
/// written on only one of two branches isn't *definitely* initialized
/// afterward, so a later write there isn't certainly a re-init.
pub readonly_initialized: Arc<FxHashSet<(Name, Name)>>,
/// `$this->prop = value` (plain assignment only) property names
/// definitely written on every path reaching this point in the current
/// constructor. Used by the constructor definite-assignment check (a
/// native-typed, non-nullable, default-less own property must be
/// assigned before the constructor can exit) — merged by intersection
/// like `readonly_initialized`, for the same reason: a write on only one
/// branch isn't certain on every path.
pub assigned_this_props: Arc<FxHashSet<Name>>,
/// Set once `$this` is passed to, or a call is made through, something
/// whose body isn't analyzed here (a method/function call on or passing
/// `$this`, a static forwarding call, a closure invocation) — such a
/// call might initialize a property on `$this`'s behalf. Monotonic, like
/// `has_dynamic_var_def`: once true it stays true across merges. The
/// constructor definite-assignment check abstains entirely when this is
/// set, rather than risk flagging a property actually initialized by a
/// delegating helper call it can't see into.
pub this_escaped_to_call: bool,
}
/// Pre-built superglobal initial state, shared across all FlowState instances.
///
/// PHP superglobals are always in scope. Building them fresh per scope costs
/// ~11 Arc allocations + map insertions per function/method. A static snapshot
/// lets each new scope start with a cheap Arc clone; the first local-variable
/// write triggers `Arc::make_mut`, which COW-copies at that point — identical
/// semantics, zero extra allocations on the common path.
fn superglobal_vars() -> &'static Arc<FxHashMap<Name, Arc<Type>>> {
static VARS: std::sync::OnceLock<Arc<FxHashMap<Name, Arc<Type>>>> = std::sync::OnceLock::new();
VARS.get_or_init(|| {
let mixed = Arc::new(mir_types::Type::mixed());
let mut map = FxHashMap::default();
for sg in &[
"_SERVER", "_GET", "_POST", "_REQUEST", "_SESSION", "_COOKIE", "_FILES", "_ENV",
"GLOBALS", "argv", "argc",
] {
map.insert(Name::from(*sg), Arc::clone(&mixed));
}
Arc::new(map)
})
}
fn superglobal_assigned() -> &'static Arc<FxHashSet<Name>> {
static ASSIGNED: std::sync::OnceLock<Arc<FxHashSet<Name>>> = std::sync::OnceLock::new();
ASSIGNED.get_or_init(|| {
let set: FxHashSet<Name> = [
"_SERVER", "_GET", "_POST", "_REQUEST", "_SESSION", "_COOKIE", "_FILES", "_ENV",
"GLOBALS", "argv", "argc",
]
.iter()
.map(|s| Name::from(*s))
.collect();
Arc::new(set)
})
}
impl FlowState {
pub fn new() -> Self {
Self {
vars: Arc::clone(superglobal_vars()),
assigned_vars: Arc::clone(superglobal_assigned()),
possibly_assigned_vars: Arc::new(FxHashSet::default()),
self_fqcn: None,
parent_fqcn: None,
static_fqcn: None,
fn_return_type: None,
fn_declared_throws: Arc::from([]),
inside_loop: false,
has_dynamic_var_def: false,
has_dynamic_var_read: false,
has_dynamic_tainted_var_def: false,
inside_finally: false,
is_generator: false,
inside_constructor: false,
current_method_name: None,
current_function_fqn: None,
is_in_pure_fn: false,
is_in_immutable_method: false,
is_in_external_mutation_free_method: false,
inside_static_method: false,
strict_types: false,
tainted_vars: FxHashSet::default(),
tainted_props: FxHashSet::default(),
tainted_static_props: FxHashSet::default(),
ref_aliases: FxHashMap::default(),
cloned_local_vars: FxHashSet::default(),
read_vars: FxHashSet::default(),
param_names: Arc::new(FxHashSet::default()),
byref_param_names: Arc::new(FxHashSet::default()),
static_var_names: Arc::new(FxHashSet::default()),
declared_var_types: Arc::new(FxHashMap::default()),
diverges: false,
var_locations: FxHashMap::default(),
last_write_locs: FxHashMap::default(),
dead_writes: Vec::new(),
consumed_write_locs: FxHashSet::default(),
foreach_value_var_names: FxHashSet::default(),
foreach_byref_var_names: FxHashSet::default(),
catch_var_names: FxHashSet::default(),
template_param_names: Arc::new(FxHashSet::default()),
template_typed_params: Arc::new(FxHashSet::default()),
class_exists_guards: FxHashSet::default(),
defined_guards: FxHashSet::default(),
function_exists_guards: FxHashSet::default(),
method_exists_guards: FxHashSet::default(),
property_exists_guards: FxHashSet::default(),
extension_loaded_guards: FxHashSet::default(),
prop_refined: Arc::new(FxHashMap::default()),
readonly_initialized: Arc::new(FxHashSet::default()),
assigned_this_props: Arc::new(FxHashSet::default()),
this_escaped_to_call: false,
}
}
/// Returns true if the given FQCN is suppressed by a `class_exists()` or
/// `extension_loaded()` guard in the current branch. Use this instead of
/// directly consulting `class_exists_guards` so that both guard kinds are
/// respected uniformly.
pub fn is_class_guarded(&self, fqcn: &str) -> bool {
self.class_exists_guards.contains(fqcn) || !self.extension_loaded_guards.is_empty()
}
/// Create a context seeded with the given parameters.
#[allow(clippy::too_many_arguments)]
pub fn for_function(
params: &[mir_codebase::DeclaredParam],
return_type: Option<Type>,
declared_throws: Arc<[Arc<str>]>,
self_fqcn: Option<Arc<str>>,
parent_fqcn: Option<Arc<str>>,
static_fqcn: Option<Arc<str>>,
strict_types: bool,
is_static: bool,
) -> Self {
Self::for_method(
params,
return_type,
declared_throws,
self_fqcn,
parent_fqcn,
static_fqcn,
strict_types,
false,
is_static,
)
}
/// Like `for_function` but also sets `inside_constructor`.
#[allow(clippy::too_many_arguments)]
pub fn for_method(
params: &[mir_codebase::DeclaredParam],
return_type: Option<Type>,
declared_throws: Arc<[Arc<str>]>,
self_fqcn: Option<Arc<str>>,
parent_fqcn: Option<Arc<str>>,
static_fqcn: Option<Arc<str>>,
strict_types: bool,
inside_constructor: bool,
is_static: bool,
) -> Self {
Self::for_method_with_templates(
params,
return_type,
declared_throws,
self_fqcn,
parent_fqcn,
static_fqcn,
strict_types,
inside_constructor,
is_static,
None,
)
}
/// Like `for_method` but also accepts template parameters.
#[allow(clippy::too_many_arguments)]
pub fn for_method_with_templates(
params: &[mir_codebase::DeclaredParam],
return_type: Option<Type>,
declared_throws: Arc<[Arc<str>]>,
self_fqcn: Option<Arc<str>>,
parent_fqcn: Option<Arc<str>>,
static_fqcn: Option<Arc<str>>,
strict_types: bool,
inside_constructor: bool,
is_static: bool,
template_params: Option<&[mir_codebase::TemplateParam]>,
) -> Self {
let mut ctx = Self::new();
ctx.fn_return_type = return_type;
ctx.fn_declared_throws = declared_throws;
ctx.self_fqcn = self_fqcn.clone();
ctx.parent_fqcn = parent_fqcn;
ctx.static_fqcn = static_fqcn;
ctx.strict_types = strict_types;
ctx.inside_constructor = inside_constructor;
// Build local sets — wrap in Arc at the end (set-once, never mutated during analysis).
let mut template_param_names: FxHashSet<Name> = FxHashSet::default();
let mut template_typed_params: FxHashSet<Name> = FxHashSet::default();
let mut param_names: FxHashSet<Name> = FxHashSet::default();
let mut byref_param_names: FxHashSet<Name> = FxHashSet::default();
let mut declared_var_types: FxHashMap<Name, Type> = FxHashMap::default();
// Build a map of template names to their bounds for parameter type resolution
let mut template_bounds_map: FxHashMap<Name, Type> = FxHashMap::default();
if let Some(templates) = template_params {
for tp in templates {
let tp_sym = Name::from(tp.name.as_ref());
template_param_names.insert(tp_sym);
if let Some(bound) = &tp.bound {
template_bounds_map.insert(tp_sym, (**bound).clone());
}
}
}
for p in params {
let mut elem_ty =
p.ty.as_ref()
.map(|arc| (**arc).clone())
.unwrap_or_else(Type::mixed);
// Resolve template references to their bounds
// If the parameter type is a bare unqualified name matching a template parameter,
// replace it with the template's bound
let mut is_template_typed = false;
if elem_ty.types.len() == 1 {
match &elem_ty.types[0] {
mir_types::Atomic::TNamedObject { fqcn, type_params }
if type_params.is_empty() && !fqcn.contains('\\') =>
{
if let Some(bound) = template_bounds_map.get(fqcn) {
elem_ty = bound.clone();
is_template_typed = true;
}
}
mir_types::Atomic::TTemplateParam { as_type, .. } if !as_type.is_mixed() => {
// If the template has a non-mixed bound, use it
// Otherwise keep the TTemplateParam to avoid MixedMethodCall errors
elem_ty = (**as_type).clone();
is_template_typed = true;
}
_ => {}
}
}
// Variadic params like `Type ...$name` are accessed as `list<Type>` in the body.
// If the docblock already provides a list/array collection type, don't double-wrap.
let ty = if p.is_variadic {
// A string-only key (`@param array<string,int> ...$maps`) means
// each argument IS a whole string-keyed array, not a bare V —
// same distinction `crate::generic::variadic_element_type`
// already draws for call-site argument checking. Without this
// guard, `$maps` itself bound to the flat aggregate type
// instead of `list<array<string,int>>`, corrupting every
// per-argument use (e.g. a `foreach` over `$maps`).
let already_collection = elem_ty.types.iter().any(|a| {
matches!(
a,
mir_types::Atomic::TList { .. } | mir_types::Atomic::TNonEmptyList { .. }
) || matches!(
a,
mir_types::Atomic::TArray { key, .. }
| mir_types::Atomic::TNonEmptyArray { key, .. }
if crate::generic::key_admits_int_variadic_index(key)
)
});
if already_collection {
elem_ty
} else {
mir_types::Type::single(mir_types::Atomic::TList {
value: Box::new(elem_ty),
})
}
} else {
elem_ty
};
let name = Name::from(p.name.as_ref().trim_start_matches('$'));
declared_var_types.insert(name, ty.clone());
Arc::make_mut(&mut ctx.vars).insert(name, mir_codebase::definitions::wrap_var_type(ty));
Arc::make_mut(&mut ctx.assigned_vars).insert(name);
param_names.insert(name);
if is_template_typed {
template_typed_params.insert(name);
}
if p.is_byref {
byref_param_names.insert(name);
}
}
ctx.inside_static_method = is_static;
// Inject $this for non-static methods so that $this->method() can be
// resolved without hitting the mixed-receiver early-return guard.
if !is_static {
if let Some(fqcn) = self_fqcn {
let this_ty = mir_types::Type::single(mir_types::Atomic::TNamedObject {
fqcn: mir_types::Name::from(fqcn.as_ref()),
type_params: mir_types::union::empty_type_params(),
});
let this_sym = Name::from("this");
Arc::make_mut(&mut ctx.vars)
.insert(this_sym, mir_codebase::definitions::wrap_var_type(this_ty));
Arc::make_mut(&mut ctx.assigned_vars).insert(this_sym);
}
}
ctx.param_names = Arc::new(param_names);
ctx.byref_param_names = Arc::new(byref_param_names);
ctx.declared_var_types = Arc::new(declared_var_types);
ctx.template_param_names = Arc::new(template_param_names);
ctx.template_typed_params = Arc::new(template_typed_params);
ctx
}
/// Get the type of a variable. Returns `mixed` if not found.
pub fn get_var(&self, name: &str) -> Type {
self.get_var_sym(Name::from(name.trim_start_matches('$')))
}
/// [`Self::get_var`] for an already-interned name — lets per-expression
/// callers intern once instead of re-hashing the string per call.
pub fn get_var_sym(&self, sym: Name) -> Type {
self.vars
.get(&sym)
.map(|a| (**a).clone())
.unwrap_or_else(Type::mixed)
}
/// Set the type of a variable and mark it as assigned.
pub fn set_var(&mut self, name: &str, ty: Type) {
let name = Name::from(name.trim_start_matches('$'));
Arc::make_mut(&mut self.vars).insert(name, mir_codebase::definitions::wrap_var_type(ty));
Arc::make_mut(&mut self.assigned_vars).insert(name);
}
/// Check if a variable is definitely in scope.
pub fn var_is_defined(&self, name: &str) -> bool {
self.var_is_defined_sym(Name::from(name.trim_start_matches('$')))
}
/// [`Self::var_is_defined`] for an already-interned name.
pub fn var_is_defined_sym(&self, sym: Name) -> bool {
self.assigned_vars.contains(&sym)
}
/// Check if a variable might be defined (but not certainly).
pub fn var_possibly_defined(&self, name: &str) -> bool {
self.var_possibly_defined_sym(Name::from(name.trim_start_matches('$')))
}
/// [`Self::var_possibly_defined`] for an already-interned name.
pub fn var_possibly_defined_sym(&self, sym: Name) -> bool {
self.assigned_vars.contains(&sym) || self.possibly_assigned_vars.contains(&sym)
}
/// Return the narrowed type for an instance-property access, if any.
/// `obj_var` is the receiver variable name (e.g. `"this"`).
pub fn get_prop_refined(&self, obj_var: &str, prop: &str) -> Option<&Type> {
let key = (
Name::from(obj_var.trim_start_matches('$')),
Name::from(prop),
);
self.prop_refined.get(&key).map(|t| t.as_ref())
}
/// Record a narrowed/refined type for an instance property.
pub fn set_prop_refined(&mut self, obj_var: &str, prop: &str, ty: Type) {
let key = (
Name::from(obj_var.trim_start_matches('$')),
Name::from(prop),
);
Arc::make_mut(&mut self.prop_refined)
.insert(key, mir_codebase::definitions::wrap_var_type(ty));
}
/// Discard any narrowed type for an instance property (call on write to
/// invalidate stale refinements from a prior guard).
pub fn clear_prop_refined(&mut self, obj_var: &str, prop: &str) {
let key = (
Name::from(obj_var.trim_start_matches('$')),
Name::from(prop),
);
if self.prop_refined.contains_key(&key) {
Arc::make_mut(&mut self.prop_refined).remove(&key);
}
}
/// Returns true if `obj_var`'s readonly property `prop` is definitely
/// already initialized on every path reaching this point.
pub fn is_readonly_initialized(&self, obj_var: &str, prop: &str) -> bool {
let key = (
Name::from(obj_var.trim_start_matches('$')),
Name::from(prop),
);
self.readonly_initialized.contains(&key)
}
/// Record that `obj_var`'s readonly property `prop` has now been
/// assigned on this path.
pub fn mark_readonly_initialized(&mut self, obj_var: &str, prop: &str) {
let key = (
Name::from(obj_var.trim_start_matches('$')),
Name::from(prop),
);
if !self.readonly_initialized.contains(&key) {
Arc::make_mut(&mut self.readonly_initialized).insert(key);
}
}
/// Record that `$this->prop` has been definitely assigned on this path
/// (constructor definite-assignment tracking).
pub fn mark_this_prop_assigned(&mut self, prop: &str) {
let key = Name::from(prop);
if !self.assigned_this_props.contains(&key) {
Arc::make_mut(&mut self.assigned_this_props).insert(key);
}
}
/// Mark that `$this` may have escaped to an unanalyzed call on this path
/// (see `this_escaped_to_call`).
pub fn mark_this_escaped_to_call(&mut self) {
self.this_escaped_to_call = true;
}
/// Discard every narrowed property type recorded for one receiver (e.g.
/// `"this"`, another object variable, or a static-fqcn key). Call this
/// after a call we can't prove pure/mutation-free where `receiver` names
/// the object: the callee's `$this` is that object, so it may reassign
/// any of its own properties, making prior narrowing stale.
pub fn invalidate_prop_refined_receiver(&mut self, receiver: &str) {
let stripped = receiver.trim_start_matches('$');
// Every call site that invalidates `$this`'s own narrowing this way
// is, by construction, also a call/argument the analyzer can't see
// into — exactly the signal `this_escaped_to_call` needs (see its
// doc comment), so piggyback here instead of duplicating this check
// at every one of those call sites.
if stripped == "this" {
self.mark_this_escaped_to_call();
}
let receiver = Name::from(stripped);
// A 2-hop chained receiver key (`chained_prop_receiver_key`) encodes
// as `"{receiver}->{prop}"` — an entry keyed this way is also stale
// once `receiver` itself may have been reassigned by an opaque call,
// not just an entry keyed by `receiver` exactly.
let chain_prefix = format!("{stripped}->");
if self
.prop_refined
.keys()
.any(|(obj, _)| *obj == receiver || obj.as_ref().starts_with(chain_prefix.as_str()))
{
Arc::make_mut(&mut self.prop_refined).retain(|(obj, _), _| {
*obj != receiver && !obj.as_ref().starts_with(chain_prefix.as_str())
});
}
}
/// Mark a variable as carrying tainted (user-controlled) data.
pub fn taint_var(&mut self, name: &str) {
let name = Name::from(name.trim_start_matches('$'));
self.tainted_vars.insert(name);
}
/// Returns true if the variable is known to carry tainted data.
pub fn is_tainted(&self, name: &str) -> bool {
let sym = Name::from(name.trim_start_matches('$'));
self.tainted_vars.contains(&sym)
}
/// Clear a previously-recorded variable taint — used when the variable is
/// overwritten with a value proven not tainted, so stale taint doesn't
/// survive the reassignment.
pub fn clear_var_taint(&mut self, name: &str) {
let sym = Name::from(name.trim_start_matches('$'));
self.tainted_vars.remove(&sym);
}
/// Mark an instance property as carrying tainted (user-controlled) data.
pub fn taint_prop(&mut self, obj_var: &str, prop: &str) {
let key = (
Name::from(obj_var.trim_start_matches('$')),
Name::from(prop),
);
self.tainted_props.insert(key);
}
/// Returns true if the instance property is known to carry tainted data.
pub fn is_prop_tainted(&self, obj_var: &str, prop: &str) -> bool {
let key = (
Name::from(obj_var.trim_start_matches('$')),
Name::from(prop),
);
self.tainted_props.contains(&key)
}
/// Clear a previously-recorded property taint — used when the property is
/// overwritten with a value proven not tainted, so stale taint doesn't
/// survive the reassignment.
pub fn clear_prop_taint(&mut self, obj_var: &str, prop: &str) {
let key = (
Name::from(obj_var.trim_start_matches('$')),
Name::from(prop),
);
self.tainted_props.remove(&key);
}
/// Mark a static property as carrying tainted (user-controlled) data.
pub fn taint_static_prop(&mut self, fqcn: &str, prop: &str) {
let key = (Name::from(fqcn), Name::from(prop));
self.tainted_static_props.insert(key);
}
/// Returns true if the static property is known to carry tainted data.
pub fn is_static_prop_tainted(&self, fqcn: &str, prop: &str) -> bool {
let key = (Name::from(fqcn), Name::from(prop));
self.tainted_static_props.contains(&key)
}
/// Clear a previously-recorded static-property taint — used when the
/// property is overwritten with a value proven not tainted.
pub fn clear_static_prop_taint(&mut self, fqcn: &str, prop: &str) {
let key = (Name::from(fqcn), Name::from(prop));
self.tainted_static_props.remove(&key);
}
/// Record `var_name` as ref-aliased to `recv_name`'s `prop` property
/// (`$var_name =& $recv_name->prop;`).
pub fn set_ref_alias(&mut self, var_name: &str, recv_name: &str, prop: &str) {
let var = Name::from(var_name.trim_start_matches('$'));
let recv = Name::from(recv_name.trim_start_matches('$'));
self.ref_aliases.insert(var, (recv, Name::from(prop)));
}
/// Returns `(receiver_var, prop_name)` if `var_name` is ref-aliased to a
/// property in this scope.
pub fn get_ref_alias(&self, var_name: &str) -> Option<(Name, Name)> {
let var = Name::from(var_name.trim_start_matches('$'));
self.ref_aliases.get(&var).copied()
}
/// Record `var_name` as directly holding a fresh `clone $expr` result.
pub fn mark_cloned_local(&mut self, var_name: &str) {
let var = Name::from(var_name.trim_start_matches('$'));
self.cloned_local_vars.insert(var);
}
/// Returns true if `var_name` is known to directly hold a fresh, unaliased
/// `clone $expr` result in this scope.
pub fn is_cloned_local(&self, var_name: &str) -> bool {
let var = Name::from(var_name.trim_start_matches('$'));
self.cloned_local_vars.contains(&var)
}
/// Clear a previously-recorded clone marker — used when the variable is
/// overwritten with a value that isn't itself a fresh clone.
pub fn clear_cloned_local(&mut self, var_name: &str) {
let var = Name::from(var_name.trim_start_matches('$'));
self.cloned_local_vars.remove(&var);
}
/// Record the location of the first assignment to a variable (first-write-wins)
/// and update the dead-write tracking for this variable.
pub fn record_var_location(
&mut self,
name: &str,
line: u32,
col_start: u16,
line_end: u32,
col_end: u16,
) {
let sym = Name::from(name.trim_start_matches('$'));
self.var_locations
.entry(sym)
.or_insert((line, col_start, line_end, col_end));
self.record_write(name, line, col_start, line_end, col_end);
}
/// Record a write to a variable for dead-write tracking.
///
/// If the variable had an unread write since the last read, that previous
/// write is collected as a dead write. The new write location becomes the
/// current pending write.
///
/// Call this alongside `record_var_location` at every PHP-level assignment
/// (but NOT for type-narrowing `set_var` calls in the narrowing engine).
pub fn record_write(
&mut self,
name: &str,
line: u32,
col_start: u16,
line_end: u32,
col_end: u16,
) {
let sym = Name::from(name.trim_start_matches('$'));
if let Some(old_locs) = self.last_write_locs.remove(&sym) {
// Previous write(s) overwritten without being read → dead writes.
for old_loc in old_locs {
self.dead_writes
.push((sym, old_loc.0, old_loc.1, old_loc.2, old_loc.3));
}
}
self.last_write_locs
.insert(sym, vec![(line, col_start, line_end, col_end)]);
}
/// Mark a variable as consumed by an r-value read.
///
/// This clears the pending write entry so the write is no longer considered
/// dead. Call this whenever a variable is used as an expression value.
pub fn mark_consumed(&mut self, name: &str) {
self.mark_consumed_sym(Name::from(name.trim_start_matches('$')));
}
/// [`Self::mark_consumed`] for an already-interned name.
pub fn mark_consumed_sym(&mut self, sym: Name) {
if let Some(locs) = self.last_write_locs.remove(&sym) {
// Consumption is permanent across branch merges: see
// `consumed_write_locs`.
for loc in locs {
self.consumed_write_locs.insert((sym, loc));
}
}
}
/// Propagate reads observed in a branch-scoped context (ternary arm,
/// match arm, closure body) back into this context: variables read there
/// count as read here, and write locations they consumed stay consumed.
pub fn absorb_branch_reads(&mut self, branch: &FlowState) {
for name in branch.read_vars.iter() {
self.read_vars.insert(*name);
}
for key in branch.consumed_write_locs.iter() {
self.consumed_write_locs.insert(*key);
}
let consumed = &self.consumed_write_locs;
self.last_write_locs.retain(|name, locs| {
locs.retain(|loc| !consumed.contains(&(*name, *loc)));
!locs.is_empty()
});
}
/// Remove a variable from the context (after `unset`).
pub fn unset_var(&mut self, name: &str) {
let sym = Name::from(name.trim_start_matches('$'));
Arc::make_mut(&mut self.vars).remove(&sym);
Arc::make_mut(&mut self.assigned_vars).remove(&sym);
Arc::make_mut(&mut self.possibly_assigned_vars).remove(&sym);
}
/// Clone this context to analyze a conditional branch (`if`, `elseif`,
/// `else`, `case`, ternary arm, …). The returned context can be mutated
/// independently and later reconciled via [`Self::merge_branches`].
pub fn branch(&self) -> FlowState {
crate::metrics::record_flow_branch(
self.read_vars.len(),
self.var_locations.len(),
self.last_write_locs.len(),
);
self.clone()
}
/// Merge two branch contexts at a join point (e.g. end of if/else).
///
/// - vars present in both: merged union of types
/// - vars present in only one branch: marked `possibly_undefined`
/// - pre-existing vars from before the branch: preserved
pub fn merge_branches(
pre: &FlowState,
if_ctx: FlowState,
else_ctx: Option<FlowState>,
) -> FlowState {
let else_ctx = else_ctx.unwrap_or_else(|| pre.clone());
// A dynamic variable definition seen on any incoming path is sticky: it
// must survive every merge so later undefined-variable checks stay
// suppressed (see `FlowState::has_dynamic_var_def`).
let dynamic_var_def =
pre.has_dynamic_var_def || if_ctx.has_dynamic_var_def || else_ctx.has_dynamic_var_def;
let dynamic_var_read = pre.has_dynamic_var_read
|| if_ctx.has_dynamic_var_read
|| else_ctx.has_dynamic_var_read;
let dynamic_tainted_var_def = pre.has_dynamic_tainted_var_def
|| if_ctx.has_dynamic_tainted_var_def
|| else_ctx.has_dynamic_tainted_var_def;
// `this_escaped_to_call` is sticky the same way: once `$this` may
// have reached an unanalyzed call on any path, the constructor
// definite-assignment check must abstain on every path afterward.
let this_escaped = pre.this_escaped_to_call
|| if_ctx.this_escaped_to_call
|| else_ctx.this_escaped_to_call;
// If the then-branch always diverges, the code after the if runs only
// in the else-branch — use that as the result directly.
if if_ctx.diverges && !else_ctx.diverges {
let mut result = else_ctx;
result.diverges = false;
// Variables read in the diverging branch still count as used.
for name in if_ctx.read_vars.iter() {
result.read_vars.insert(*name);
}
result
.consumed_write_locs
.extend(if_ctx.consumed_write_locs.iter().copied());
// Remove pending writes that were consumed in the diverging branch.
// Use consumed_write_locs rather than read_vars to avoid incorrectly
// removing writes that appear in read_vars only due to loop-iteration
// accumulation (not because they were actually consumed this iteration).
{
let consumed = &result.consumed_write_locs;
result.last_write_locs.retain(|name, locs| {
locs.retain(|loc| !consumed.contains(&(*name, *loc)));
!locs.is_empty()
});
}
// Dead writes from the diverging branch are still dead.
extend_dead_writes_dedup(&mut result.dead_writes, if_ctx.dead_writes);
for name in if_ctx.foreach_value_var_names.iter() {
result.foreach_value_var_names.insert(*name);
}
for name in if_ctx.foreach_byref_var_names.iter() {
result.foreach_byref_var_names.insert(*name);
}
for name in if_ctx.catch_var_names.iter() {
result.catch_var_names.insert(*name);
}
result.has_dynamic_var_def = dynamic_var_def;
result.this_escaped_to_call = this_escaped;
result.has_dynamic_var_read = dynamic_var_read;
result.has_dynamic_tainted_var_def = dynamic_tainted_var_def;
return result;
}
// If the else-branch always diverges, code after the if runs only
// in the then-branch.
if else_ctx.diverges && !if_ctx.diverges {
let mut result = if_ctx;
result.diverges = false;
// Variables read in the diverging branch still count as used.
for name in else_ctx.read_vars.iter() {
result.read_vars.insert(*name);
}
result
.consumed_write_locs
.extend(else_ctx.consumed_write_locs.iter().copied());
// Remove pending writes consumed in the diverging branch.
{
let consumed = &result.consumed_write_locs;
result.last_write_locs.retain(|name, locs| {
locs.retain(|loc| !consumed.contains(&(*name, *loc)));
!locs.is_empty()
});
}
extend_dead_writes_dedup(&mut result.dead_writes, else_ctx.dead_writes);
for name in else_ctx.foreach_value_var_names.iter() {
result.foreach_value_var_names.insert(*name);
}
for name in else_ctx.foreach_byref_var_names.iter() {
result.foreach_byref_var_names.insert(*name);
}
for name in else_ctx.catch_var_names.iter() {
result.catch_var_names.insert(*name);
}
result.has_dynamic_var_def = dynamic_var_def;
result.this_escaped_to_call = this_escaped;
result.has_dynamic_var_read = dynamic_var_read;
result.has_dynamic_tainted_var_def = dynamic_tainted_var_def;
return result;
}
// If both diverge, the code after the if is unreachable.
if if_ctx.diverges && else_ctx.diverges {
let mut result = pre.clone();
result.diverges = true;
// Variables read in either diverging branch still count as used.
for name in if_ctx.read_vars.iter().chain(else_ctx.read_vars.iter()) {
result.read_vars.insert(*name);
}
result
.consumed_write_locs
.extend(if_ctx.consumed_write_locs.iter().copied());
result
.consumed_write_locs
.extend(else_ctx.consumed_write_locs.iter().copied());
// `result` is `pre.clone()`; both branches already contain pre's
// dead writes, so rebuild deduped rather than concatenating.
result.dead_writes.clear();
extend_dead_writes_dedup(&mut result.dead_writes, if_ctx.dead_writes);
extend_dead_writes_dedup(&mut result.dead_writes, else_ctx.dead_writes);
for name in if_ctx
.foreach_value_var_names
.iter()
.chain(else_ctx.foreach_value_var_names.iter())
{
result.foreach_value_var_names.insert(*name);
}
for name in if_ctx
.foreach_byref_var_names
.iter()
.chain(else_ctx.foreach_byref_var_names.iter())
{
result.foreach_byref_var_names.insert(*name);
}
for name in if_ctx
.catch_var_names
.iter()
.chain(else_ctx.catch_var_names.iter())
{
result.catch_var_names.insert(*name);
}
result.has_dynamic_var_def = dynamic_var_def;
result.this_escaped_to_call = this_escaped;
result.has_dynamic_var_read = dynamic_var_read;
result.has_dynamic_tainted_var_def = dynamic_tainted_var_def;
return result;
}
let mut result = pre.clone();
// Collect all variable names from both branch contexts
let all_names: FxHashSet<Name> = if_ctx
.vars
.keys()
.chain(else_ctx.vars.keys())
.copied()
.collect();
{
let result_vars = Arc::make_mut(&mut result.vars);
let result_assigned = Arc::make_mut(&mut result.assigned_vars);
let result_possibly = Arc::make_mut(&mut result.possibly_assigned_vars);
for name in all_names {
let in_if = if_ctx.assigned_vars.contains(&name);
let in_else = else_ctx.assigned_vars.contains(&name);
let in_pre = pre.assigned_vars.contains(&name);
let ty_if = if_ctx.vars.get(&name);
let ty_else = else_ctx.vars.get(&name);
match (ty_if, ty_else) {
(Some(a), Some(b)) => {
let merged = if Arc::ptr_eq(a, b) {
a.clone()
} else {
let mut m = (**a).clone();
m.merge_with(b);
mir_codebase::definitions::wrap_var_type(m)
};
result_vars.insert(name, merged);
if in_if && in_else {
result_assigned.insert(name);
} else {
result_possibly.insert(name);
}
}
(Some(a), None) => {
if in_pre {
let pre_arc = pre.vars.get(&name);
let merged = match pre_arc {
Some(pt) if Arc::ptr_eq(a, pt) => a.clone(),
Some(pt) => {
let mut m = (**a).clone();
m.merge_with(pt);
mir_codebase::definitions::wrap_var_type(m)
}
None => {
let mut m = (**a).clone();
m.merge_with(&Type::mixed());
mir_codebase::definitions::wrap_var_type(m)
}
};
result_vars.insert(name, merged);
result_assigned.insert(name);
} else {
let ty = mir_codebase::definitions::wrap_var_type(
(**a).clone().possibly_undefined(),
);
result_vars.insert(name, ty);
result_possibly.insert(name);
}
}
(None, Some(b)) => {
if in_pre {
let pre_arc = pre.vars.get(&name);
let merged = match pre_arc {
Some(pt) if Arc::ptr_eq(b, pt) => b.clone(),
Some(pt) => {
let mut m = (**pt).clone();
m.merge_with(b);
mir_codebase::definitions::wrap_var_type(m)
}
None => {
let mut m = Type::mixed();
m.merge_with(b);
mir_codebase::definitions::wrap_var_type(m)
}
};
result_vars.insert(name, merged);
result_assigned.insert(name);
} else {
let ty = mir_codebase::definitions::wrap_var_type(
(**b).clone().possibly_undefined(),
);
result_vars.insert(name, ty);
result_possibly.insert(name);
}
}
(None, None) => {}
}
}
}
// Class-exists guards: intersection — a guard survives the merge only if
// both branches have it, meaning the class is guaranteed to exist on every
// path. In the common case (only the then-branch has the guard) the
// intersection is empty, which is correct: after the if/else the guard no
// longer applies.
result.class_exists_guards = if_ctx
.class_exists_guards
.intersection(&else_ctx.class_exists_guards)
.cloned()
.collect();
result.defined_guards = if_ctx
.defined_guards
.intersection(&else_ctx.defined_guards)
.cloned()
.collect();
result.function_exists_guards = if_ctx
.function_exists_guards
.intersection(&else_ctx.function_exists_guards)
.cloned()
.collect();
result.method_exists_guards = if_ctx
.method_exists_guards
.intersection(&else_ctx.method_exists_guards)
.cloned()
.collect();
result.property_exists_guards = if_ctx
.property_exists_guards
.intersection(&else_ctx.property_exists_guards)
.cloned()
.collect();
result.extension_loaded_guards = if_ctx
.extension_loaded_guards
.intersection(&else_ctx.extension_loaded_guards)
.cloned()
.collect();
// Readonly-initialized: intersection, same reasoning as the guard
// sets above — a property written on only one branch was NOT
// definitely written on every path reaching the merge point, so it
// must not be treated as certainly initialized afterward.
result.readonly_initialized = Arc::new(
if_ctx
.readonly_initialized
.intersection(&else_ctx.readonly_initialized)
.cloned()
.collect(),
);
// Same reasoning again for constructor definite-assignment: a
// property assigned on only one branch isn't definitely assigned on
// every path reaching the merge point.
result.assigned_this_props = Arc::new(
if_ctx
.assigned_this_props
.intersection(&else_ctx.assigned_this_props)
.cloned()
.collect(),
);
// Property refinements: keep only keys present in BOTH branches with the
// union of their types. A refinement present in only one branch cannot
// be relied upon after the merge (the other path didn't narrow it).
{
let mut merged_props: FxHashMap<(Name, Name), Arc<Type>> = FxHashMap::default();
for (key, if_ty) in if_ctx.prop_refined.iter() {
if let Some(else_ty) = else_ctx.prop_refined.get(key) {
let merged = if Arc::ptr_eq(if_ty, else_ty) {
if_ty.clone()
} else {
let mut m = (**if_ty).clone();
m.merge_with(else_ty);
mir_codebase::definitions::wrap_var_type(m)
};
merged_props.insert(*key, merged);
}
}
result.prop_refined = Arc::new(merged_props);
}
// Taint: conservative union — if either branch taints a var, it stays tainted
for name in if_ctx
.tainted_vars
.iter()
.chain(else_ctx.tainted_vars.iter())
{
result.tainted_vars.insert(*name);
}
// Same conservative union for tainted instance properties.
for key in if_ctx
.tainted_props
.iter()
.chain(else_ctx.tainted_props.iter())
{
result.tainted_props.insert(*key);
}
// Same conservative union for tainted static properties.
for key in if_ctx
.tainted_static_props
.iter()
.chain(else_ctx.tainted_static_props.iter())
{
result.tainted_static_props.insert(*key);
}
// Same conservative union for ref-aliases — once either branch
// records `$x =& $this->prop;`, later code on the merged path must
// still treat writes to `$x` as writes to the property.
for (var, alias) in if_ctx.ref_aliases.iter().chain(else_ctx.ref_aliases.iter()) {
result.ref_aliases.insert(*var, *alias);
}
// Read vars: union — if either branch reads a var, it counts as read
for name in if_ctx.read_vars.iter().chain(else_ctx.read_vars.iter()) {
result.read_vars.insert(*name);
}
result.has_dynamic_var_def = dynamic_var_def;
result.this_escaped_to_call = this_escaped;
result.has_dynamic_tainted_var_def = dynamic_tainted_var_def;
// Foreach value var names: union — if either branch marks a var as a foreach value, keep it
for name in if_ctx
.foreach_value_var_names
.iter()
.chain(else_ctx.foreach_value_var_names.iter())
{
result.foreach_value_var_names.insert(*name);
}
// Foreach by-ref var names: union — if either branch marks a var as by-ref, keep it
for name in if_ctx
.foreach_byref_var_names
.iter()
.chain(else_ctx.foreach_byref_var_names.iter())
{
result.foreach_byref_var_names.insert(*name);
}
// Catch var names: union — catch variables from any branch must not be reported
for name in if_ctx
.catch_var_names
.iter()
.chain(else_ctx.catch_var_names.iter())
{
result.catch_var_names.insert(*name);
}
// Var locations: keep the earliest known span for each variable
for (name, loc) in if_ctx
.var_locations
.iter()
.chain(else_ctx.var_locations.iter())
{
result.var_locations.entry(*name).or_insert(*loc);
}
// Dead writes: union of both branches, deduplicated. `result` is
// `pre.clone()` and both branches descend from `pre`, so they already
// contain pre's dead writes — rebuild from the branches rather than
// concatenating onto pre's copy (which would grow the Vec ~3× per merge
// → exponential under nested-loop fixpoint analysis; see
// `extend_dead_writes_dedup`).
result.dead_writes.clear();
extend_dead_writes_dedup(&mut result.dead_writes, if_ctx.dead_writes);
extend_dead_writes_dedup(&mut result.dead_writes, else_ctx.dead_writes);
// Consumed write locations: union — a write read on ANY path is used.
result.consumed_write_locs = if_ctx.consumed_write_locs;
result
.consumed_write_locs
.extend(else_ctx.consumed_write_locs.iter().copied());
// Last write locs: union from both branches, plus pre_ctx variables that
// are still pending in BOTH branches (meaning neither branch nor the
// condition consumed them). Variables present in pre_ctx but absent from
// both branches were consumed on all paths (e.g. read in condition) and
// must not be re-added. Entries whose location was consumed on either
// path are filtered — that write is used.
result.last_write_locs = FxHashMap::default();
{
let consumed = &result.consumed_write_locs;
let add = |map: &mut FxHashMap<Name, Vec<(u32, u16, u32, u16)>>,
name: &Name,
loc: &(u32, u16, u32, u16)| {
if !consumed.contains(&(*name, *loc)) {
let entry = map.entry(*name).or_default();
if !entry.contains(loc) {
entry.push(*loc);
}
}
};
// Branch contexts inherit pre's pending entries, so unioning the two
// branch maps already covers pre-existing writes: a pre write still
// pending in either branch survives; one overwritten in BOTH
// branches (dead on every path) is gone from both maps and stays
// out. No separate pre re-add is needed — re-adding by name would
// resurrect pre locations that both branches overwrote.
for (name, locs) in if_ctx
.last_write_locs
.iter()
.chain(else_ctx.last_write_locs.iter())
{
for loc in locs.iter() {
add(&mut result.last_write_locs, name, loc);
}
}
}
// After merging branches, the merged context does not diverge
// (at least one path through the merge reaches the next statement).
result.diverges = false;
result
}
}
impl Default for FlowState {
fn default() -> Self {
Self::new()
}
}
/// True when the method/closure currently being analyzed belongs to a trait
/// (i.e. `self_fqcn` names a trait). Trait bodies are analyzed standalone, so
/// `self`/`static`/`parent`/`$this` resolve against the trait rather than the
/// (unknown) using class — callers use this to suppress class-resolution
/// false positives that only hold for the trait in isolation.
pub(crate) fn self_is_trait(db: &dyn crate::db::MirDatabase, ctx: &FlowState) -> bool {
ctx.self_fqcn
.as_deref()
.is_some_and(|f| crate::db::class_kind(db, f).is_some_and(|k| k.is_trait))
}