mir-analyzer 0.65.0

Analysis engine for the mir PHP static analyzer
Documentation
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
use std::sync::Arc;

use php_ast::Span;

use mir_issues::{IssueKind, Severity};
use mir_types::atomic::FnParam;
use mir_types::{Atomic, Type};

use crate::expr::ExpressionAnalyzer;

/// A bare string-literal callback (`array_map('formatRow', ...)`, `usort($a, 'my_cmp')`,
/// `usort($a, 'MyComparator::compare')`) is a real runtime reference to the named
/// function/method, same as `call_user_func('name')` — record it, or a function/method
/// reachable only through one of these builtins is falsely flagged as dead code.
pub(crate) fn record_callable_string_ref(
    ea: &ExpressionAnalyzer<'_>,
    callback_ty: &Type,
    callback_span: Span,
) {
    for atomic in &callback_ty.types {
        let Atomic::TLiteralString(name) = atomic else {
            continue;
        };
        if name.is_empty() {
            continue;
        }
        if let Some((class_name, method_name)) = name.as_ref().split_once("::") {
            let resolved_class = crate::db::resolve_name(ea.db, &ea.file, class_name);
            let here = crate::db::Fqcn::from_str(ea.db, &resolved_class);
            // Precedence-aware so a trait-conflict-resolved callable string
            // ('Class::method' where two composed traits both declare it, or
            // an aliased name) credits the actual winning method, not
            // whichever trait a plain ancestor walk happens to hit first.
            if let Some((owner_fqcn, method)) =
                crate::db::find_method_respecting_precedence(ea.db, here, method_name)
            {
                ea.record_ref(Arc::from(format!("cls:{resolved_class}")), callback_span);
                ea.record_ref(
                    Arc::from(format!(
                        "meth:{owner_fqcn}::{}",
                        crate::util::php_ident_lowercase(&method.name)
                    )),
                    callback_span,
                );
            }
        } else {
            let fqn = name.as_ref().trim_start_matches('\\');
            let here = crate::db::Fqcn::from_str(ea.db, fqn);
            let canonical_fqn: Option<Arc<str>> =
                crate::db::find_function(ea.db, here).map(|f| f.fqn.clone());
            if let Some(canonical_fqn) = canonical_fqn {
                ea.record_ref(Arc::from(format!("fn:{canonical_fqn}")), callback_span);
            }
        }
    }
}

/// Simple param info for arity checking (works with both mir_codebase::DeclaredParam and mir_types::atomic::FnParam)
#[derive(Clone)]
pub(crate) struct ParamInfo {
    pub(crate) is_optional: bool,
    pub(crate) is_variadic: bool,
    /// The parameter's declared type, when known — used for the parameter-type
    /// contravariance check in `check_typed_callable_arg`. `None` for untyped params
    /// (treated as accepting anything).
    pub(crate) ty: Option<Type>,
}

/// Collect the resolvable callable parameter lists for *every* candidate atomic in a
/// union (closures, resolvable named functions, intersection members) — not just the
/// first match. A union like `Closure(string):void|Closure(string,string):void` (e.g.
/// produced by a ternary) must have every branch checked, since the runtime value could
/// be either one; stopping at the first match silently ignores the others.
fn extract_all_callable_candidates(
    union: &Type,
    ea: &ExpressionAnalyzer<'_>,
) -> Vec<Vec<ParamInfo>> {
    let mut out = Vec::new();
    for atomic in &union.types {
        match atomic {
            Atomic::TClosure { data } => {
                out.push(
                    data.params
                        .iter()
                        .map(|p| ParamInfo {
                            is_optional: p.is_optional,
                            is_variadic: p.is_variadic,
                            ty: p.ty.as_ref().map(|t| t.to_union()),
                        })
                        .collect(),
                );
            }
            Atomic::TLiteralString(fn_name) => {
                if fn_name.is_empty() {
                    continue;
                }

                // Try to resolve the function name. Only collect params if found (don't fail for unknown strings).
                // This allows arity checking for both documented callables and literal function names in code.
                let here = crate::db::Fqcn::from_str(ea.db, fn_name.as_ref());
                if let Some(f) = crate::db::find_function(ea.db, here) {
                    out.push(
                        f.params
                            .iter()
                            .map(|p| ParamInfo {
                                is_optional: p.is_optional,
                                is_variadic: p.is_variadic,
                                ty: p.ty.as_deref().cloned(),
                            })
                            .collect(),
                    );
                }
            }
            Atomic::TCallable {
                params: Some(params),
                ..
            } => {
                out.push(
                    params
                        .iter()
                        .map(|p| ParamInfo {
                            is_optional: p.is_optional,
                            is_variadic: p.is_variadic,
                            ty: p.ty.as_ref().map(|t| t.to_union()),
                        })
                        .collect(),
                );
            }
            Atomic::TIntersection { parts } => {
                for part in parts.iter() {
                    out.extend(extract_all_callable_candidates(part, ea));
                }
            }
            _ => {}
        }
    }
    out
}

/// Sibling of `extract_all_callable_candidates`: collect each candidate's return
/// type instead of its param list, for the same reason (a union of closures with
/// different return types must have every branch checked, not just the first).
fn extract_all_callable_return_types(union: &Type, ea: &ExpressionAnalyzer<'_>) -> Vec<Type> {
    let mut out = Vec::new();
    for atomic in &union.types {
        match atomic {
            Atomic::TClosure { data } => out.push(data.return_type.clone()),
            Atomic::TLiteralString(fn_name) => {
                if fn_name.is_empty() {
                    continue;
                }
                let here = crate::db::Fqcn::from_str(ea.db, fn_name.as_ref());
                if let Some(f) = crate::db::find_function(ea.db, here) {
                    if let Some(ret) = f.return_type.as_deref() {
                        out.push(ret.clone());
                    }
                }
            }
            Atomic::TCallable {
                return_type: Some(ret),
                ..
            } => out.push((**ret).clone()),
            Atomic::TIntersection { parts } => {
                for part in parts.iter() {
                    out.extend(extract_all_callable_return_types(part, ea));
                }
            }
            _ => {}
        }
    }
    out
}

/// Extract callable parameter list for arity checking from a union when it can be determined statically:
/// - TClosure: return params directly
/// - TLiteralString: resolve to function only if from documented type annotation (issue #5)
/// - TIntersection: check parts for callable/closure types
/// - Everything else: None (param list is unknown at compile time)
///
/// Returns only the *first* resolvable candidate — callers that must consider every
/// union member (e.g. a union of closures with different arities) should use
/// `extract_all_callable_candidates` instead.
pub(crate) fn extract_callable_params(
    union: &Type,
    ea: &ExpressionAnalyzer<'_>,
) -> Option<Vec<ParamInfo>> {
    // If the union contains a bare callable (unknown arity), we cannot determine
    // arity statically — bail out to avoid false positives from sibling TClosure members.
    if union
        .types
        .iter()
        .any(|a| matches!(a, Atomic::TCallable { params: None, .. }))
    {
        return None;
    }

    extract_all_callable_candidates(union, ea)
        .into_iter()
        .next()
}

/// Check if a union type is valid for use as a callable.
///
/// Returns false only for types that are clearly NOT callable at runtime:
/// - TList<T>, TNonEmptyList<T> — sequential arrays, never callable
/// - TArray, TNonEmptyArray — general arrays, not valid callables
/// - TKeyedArray marked as is_list — known to be a numeric list, not callable
///
/// Returns true (safe fallback) for:
/// - TClosure, TCallable, TString, TLiteralString, TNull
/// - TKeyedArray NOT marked as is_list (could be [$obj, 'method'] form)
/// - Unknown/other types
pub(crate) fn is_valid_callable_type(union: &Type) -> bool {
    for atomic in &union.types {
        match atomic {
            Atomic::TClosure { .. }
            | Atomic::TCallable { .. }
            | Atomic::TString
            | Atomic::TNonEmptyString
            | Atomic::TLiteralString(_)
            | Atomic::TNull => {
                return true;
            }
            Atomic::TKeyedArray { is_list, .. } => {
                // A numeric-keyed list is only callable in the `[$obj, 'method']`
                // / `['Class', 'method']` 2-element form.
                if *is_list {
                    return super::array_builtins::is_callable_array_pair(union);
                }
                // Otherwise it could be [obj, 'method'] form, accept it
                return true;
            }
            Atomic::TList { .. }
            | Atomic::TNonEmptyList { .. }
            | Atomic::TArray { .. }
            | Atomic::TNonEmptyArray { .. } => {
                return false;
            }
            _ => {
                continue;
            }
        }
    }
    true
}

/// Whether every member of `ty` is a statically non-empty collection, so a
/// `count()` over it is guaranteed `>= 1`. Conservative: any member that could
/// be empty (or a `Countable` object of unknown size) yields `false`.
pub(super) fn is_non_empty_collection(ty: &Type) -> bool {
    !ty.types.is_empty()
        && ty.types.iter().all(|a| match a {
            Atomic::TNonEmptyArray { .. } | Atomic::TNonEmptyList { .. } => true,
            // A keyed array (shape) is non-empty iff it declares a required key.
            Atomic::TKeyedArray { properties, .. } => properties.values().any(|p| !p.optional),
            _ => false,
        })
}

/// Result type of `count($value)` / `sizeof($value)`: the integer count is
/// always `>= 0`, and `>= 1` when the argument is a statically non-empty
/// collection. Modeling this as `int<0, max>` / `int<1, max>` is the faithful
/// type and feeds range-aware arithmetic at use sites.
pub(crate) fn count_return_type(arg_types: &[Type]) -> Option<Type> {
    // Fast path: single sealed keyed-array shape with an exact known count.
    if let Some(ty) = arg_types.first() {
        if ty.types.len() == 1 {
            if let Atomic::TKeyedArray {
                properties,
                is_open,
                ..
            } = &ty.types[0]
            {
                if !is_open && properties.values().all(|p| !p.optional) {
                    return Some(Type::single(Atomic::TLiteralInt(properties.len() as i64)));
                }
            }
        }
    }
    let min = match arg_types.first() {
        Some(t) if is_non_empty_collection(t) => 1,
        _ => 0,
    };
    Some(Type::single(Atomic::TIntRange {
        min: Some(min),
        max: None,
    }))
}

/// Result type of `strlen($s)` / `mb_strlen($s)`: `int<0, max>` normally,
/// `int<1, max>` when the argument is statically non-empty, or a literal
/// `int<n, n>` when the argument is a known literal string.
pub(crate) fn strlen_return_type(arg_types: &[Type]) -> Type {
    // Fast path: single literal string with a statically known length.
    if let Some(ty) = arg_types.first() {
        if ty.types.len() == 1 {
            if let Atomic::TLiteralString(s) = &ty.types[0] {
                return Type::single(Atomic::TLiteralInt(s.len() as i64));
            }
        }
    }
    let min = match arg_types.first() {
        Some(t) if is_non_empty_string(t) => 1,
        _ => 0,
    };
    Type::single(Atomic::TIntRange {
        min: Some(min),
        max: None,
    })
}

fn is_non_empty_string(ty: &Type) -> bool {
    !ty.types.is_empty()
        && ty.types.iter().all(|a| {
            matches!(
                a,
                Atomic::TNonEmptyString
                    | Atomic::TClassString(_)
                    | Atomic::TInterfaceString(_)
                    | Atomic::TEnumString
                    | Atomic::TTraitString
            ) || matches!(a, Atomic::TLiteralString(s) if !s.is_empty())
        })
}

/// Infer the return type of a string function that preserves non-emptiness:
/// `strtolower`, `strtoupper`, `mb_strtolower`, `mb_strtoupper`, `ucfirst`,
/// `lcfirst`, `ucwords`.
///
/// These functions can never return an empty string when given a non-empty
/// input (they only change casing, never remove characters). When the argument
/// is provably non-empty, we return `non-empty-string` instead of the stub's
/// plain `string`.
pub(crate) fn string_preserve_non_empty(arg_types: &[Type]) -> Option<Type> {
    let arg = arg_types.first()?;
    if is_non_empty_string(arg) {
        Some(Type::single(Atomic::TNonEmptyString))
    } else {
        None
    }
}

/// Return `TString` (or `TNonEmptyString`) when the argument at `idx` is a string
/// type — strips false/null/array from the stub return for functions that are
/// effectively total when called with a string argument.
pub(crate) fn string_if_string_arg(arg_types: &[Type], idx: usize) -> Option<Type> {
    let arg = arg_types.get(idx)?;
    if is_non_empty_string(arg) {
        Some(Type::single(Atomic::TNonEmptyString))
    } else if !arg.types.is_empty() && arg.types.iter().all(|a| a.is_string()) {
        Some(Type::single(Atomic::TString))
    } else {
        None
    }
}

/// Infer the return type of `number_format()`.
///
/// `number_format()` always returns a non-empty string — even `number_format(0)`
/// returns "0". The stub declares `string`; we refine that here.
pub(crate) fn number_format_return_type() -> Type {
    Type::single(Atomic::TNonEmptyString)
}

/// Infer the return type of `str_repeat($input, $count)`.
///
/// When the input is provably non-empty AND the count is a positive literal,
/// the result is guaranteed non-empty. Falls through (returns `None`) for
/// the general case so the stub's `string` is used.
pub(crate) fn str_repeat_return_type(arg_types: &[Type]) -> Option<Type> {
    let input = arg_types.first()?;
    let count = arg_types.get(1)?;
    let count_is_positive = count.types.iter().any(|a| match a {
        Atomic::TLiteralInt(n) => *n >= 1,
        Atomic::TPositiveInt => true,
        Atomic::TIntRange { min, .. } => min.is_some_and(|m| m >= 1),
        _ => false,
    }) && count.types.iter().all(|a| match a {
        Atomic::TLiteralInt(n) => *n >= 1,
        Atomic::TPositiveInt => true,
        Atomic::TIntRange { min, .. } => min.is_some_and(|m| m >= 1),
        _ => false,
    });
    if count_is_positive && is_non_empty_string(input) {
        Some(Type::single(Atomic::TNonEmptyString))
    } else {
        None
    }
}

/// Infer the return type of `implode($separator, $array)` / `join($separator, $array)`.
///
/// When the array argument is a non-empty collection of non-empty strings,
/// the result is a `non-empty-string`. Falls through to `None` otherwise.
pub(crate) fn implode_return_type(arg_types: &[Type]) -> Option<Type> {
    // implode supports both 1-arg (array only) and 2-arg (separator, array) forms.
    let arr = if arg_types.len() == 1 {
        arg_types.first()?
    } else {
        arg_types.get(1)?
    };
    if !is_non_empty_collection(arr) {
        return None;
    }
    // Check that all elements of the array are non-empty strings.
    let all_elements_non_empty = arr.types.iter().all(|a| match a {
        Atomic::TNonEmptyList { value } | Atomic::TList { value } => is_non_empty_string(value),
        Atomic::TNonEmptyArray { value, .. } | Atomic::TArray { value, .. } => {
            is_non_empty_string(value)
        }
        Atomic::TKeyedArray { properties, .. } => {
            properties.values().all(|p| is_non_empty_string(&p.ty))
        }
        _ => false,
    });
    if all_elements_non_empty {
        Some(Type::single(Atomic::TNonEmptyString))
    } else {
        None
    }
}

/// Infer the return type of `str_split($string, $length)`.
///
/// When the string argument is provably non-empty, every chunk is non-empty
/// and there is at least one chunk, so the result is `non-empty-list<non-empty-string>`.
pub(crate) fn str_split_return_type(arg_types: &[Type]) -> Option<Type> {
    let s = arg_types.first()?;
    if is_non_empty_string(s) {
        Some(Type::single(Atomic::TNonEmptyList {
            value: Box::new(Type::single(Atomic::TNonEmptyString)),
        }))
    } else {
        None
    }
}

/// Returns true when a `sprintf` format string guarantees a non-empty result.
///
/// The result is non-empty when:
/// - the format string has any literal character that isn't consumed by a `%s`
///   specifier (literal prefix/suffix, or any non-`%s` specifier like `%d`, `%%`)
///
/// This is conservative: we return false for any format that cannot be proven
/// non-empty from the format string alone (e.g. pure `%s%s`).
fn sprintf_format_guarantees_non_empty(fmt: &str) -> bool {
    let bytes = fmt.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%' {
            i += 1;
            if i >= bytes.len() {
                // Dangling `%` — treated as literal
                return true;
            }
            // Skip optional flags, width, precision
            while i < bytes.len()
                && matches!(
                    bytes[i],
                    b'+' | b'-' | b' ' | b'0'..=b'9' | b'.' | b'\'' | b'('
                )
            {
                i += 1;
            }
            if i >= bytes.len() {
                return true;
            }
            match bytes[i] {
                // `%%` is a literal `%` — always non-empty
                b'%' => return true,
                // `%s` can produce an empty string — skip without declaring non-empty
                b's' => {}
                // All other specifiers produce non-empty output
                _ => return true,
            }
            i += 1;
        } else {
            // Literal character outside any format specifier
            return true;
        }
    }
    false
}

/// Infer the return type of `sprintf($format, ...)`.
///
/// Infer the result type of `explode($separator, $string, $limit)`.
///
/// When the separator is provably non-empty, PHP always returns at least one
/// element (the whole subject string when the separator is not found). Upgrades
/// the array portion of `stub_return` to `non-empty-list<string>` while
/// preserving any `false` component (PHP 7.x stub). Returns `None` when the
/// separator's non-emptiness cannot be proven so the stub type is used as-is.
pub(crate) fn explode_return_type(arg_types: &[Type], stub_return: &Type) -> Option<Type> {
    let separator = arg_types.first()?;
    let sep_non_empty = separator.types.iter().any(|a| {
        matches!(a, Atomic::TNonEmptyString)
            || matches!(a, Atomic::TLiteralString(s) if !s.as_ref().is_empty())
    });
    if !sep_non_empty {
        return None;
    }
    let mut result = Type::single(Atomic::TNonEmptyList {
        value: Box::new(Type::single(Atomic::TString)),
    });
    // Preserve the `|false` that phpstorm-stubs emits for PHP < 8.0.
    if stub_return
        .types
        .iter()
        .any(|a| matches!(a, Atomic::TFalse))
    {
        result.add_type(Atomic::TFalse);
    }
    Some(result)
}

/// When the format string is a literal and `sprintf_format_guarantees_non_empty`
/// is true, the result is `non-empty-string`. Falls through to `None` otherwise.
pub(crate) fn sprintf_return_type(arg_types: &[Type]) -> Option<Type> {
    let fmt_ty = arg_types.first()?;
    if fmt_ty.types.len() != 1 {
        return None;
    }
    let fmt = match &fmt_ty.types[0] {
        Atomic::TLiteralString(s) => s.as_ref(),
        _ => return None,
    };
    if sprintf_format_guarantees_non_empty(fmt) {
        Some(Type::single(Atomic::TNonEmptyString))
    } else {
        None
    }
}

/// Infer the return type of `abs($num)`.
///
/// PHP semantics: abs always returns a non-negative value with the same type
/// (int → int, float → float). When the argument is a known int subtype or
/// range, we can tighten the result accordingly.
pub(crate) fn abs_return_type(arg_types: &[Type]) -> Option<Type> {
    let arg = arg_types.first()?;
    // Only engage when the argument is purely integer (no float components).
    // A float argument returns float per PHP semantics; we leave that to the stub.
    let all_int = arg.types.iter().all(|a| {
        matches!(
            a,
            Atomic::TInt
                | Atomic::TLiteralInt(_)
                | Atomic::TPositiveInt
                | Atomic::TNonNegativeInt
                | Atomic::TNegativeInt
                | Atomic::TIntRange { .. }
        )
    });
    if !all_int || arg.types.is_empty() {
        return None;
    }

    let mut result = Type::empty();
    for a in &arg.types {
        let atom = match a {
            // Already non-negative — abs is identity.
            Atomic::TPositiveInt | Atomic::TNonNegativeInt => a.clone(),
            // Any int → non-negative-int.
            Atomic::TInt => Atomic::TNonNegativeInt,
            // Literal fold: use checked_neg to avoid i64::MIN overflow.
            Atomic::TLiteralInt(n) => {
                let abs = if *n >= 0 {
                    *n
                } else {
                    n.checked_neg().unwrap_or(i64::MAX)
                };
                Atomic::TLiteralInt(abs)
            }
            // negative-int is int<-∞, -1>: abs gives int<1, ∞> = positive-int.
            Atomic::TNegativeInt => Atomic::TPositiveInt,
            Atomic::TIntRange { min, max } => {
                let (lo, hi) = (*min, *max);
                let lo_is_nn = lo.is_some_and(|m| m >= 0);
                let hi_is_np = hi.is_some_and(|m| m <= 0);
                // Safe abs of a bound: None → None, saturate at i64::MAX on overflow.
                let abs_bound = |v: Option<i64>| {
                    v.map(|n| {
                        if n >= 0 {
                            n
                        } else {
                            n.checked_neg().unwrap_or(i64::MAX)
                        }
                    })
                };
                if lo_is_nn {
                    // Range is entirely non-negative: abs is identity.
                    a.clone()
                } else if hi_is_np {
                    // Range is entirely non-positive: abs flips and negates.
                    Atomic::TIntRange {
                        min: abs_bound(hi),
                        max: abs_bound(lo),
                    }
                } else {
                    // Mixed range: result is int<0, max(|lo|, hi)>.
                    let new_max = match (abs_bound(lo), hi) {
                        (Some(a), Some(b)) => Some(a.max(b)),
                        _ => None, // unbounded in at least one direction
                    };
                    Atomic::TIntRange {
                        min: Some(0),
                        max: new_max,
                    }
                }
            }
            _ => return None,
        };
        result.add_type(atom);
    }
    Some(result)
}

/// Infer the return type of `intdiv($num1, $num2)`.
///
/// PHP semantics: intdiv returns the integer quotient (truncated toward zero).
/// When the dividend is non-negative and the divisor is positive, the result
/// is also non-negative. If both bounds are known we can narrow further.
pub(crate) fn intdiv_return_type(arg_types: &[Type]) -> Option<Type> {
    let (num1_ty, num2_ty) = (arg_types.first()?, arg_types.get(1)?);

    // Extract bounds from the first argument.
    let (n1_min, n1_max) = int_type_bounds(num1_ty)?;
    // Extract bounds from the divisor — only engage when divisor is positive.
    let (n2_min, _n2_max) = int_type_bounds(num2_ty)?;

    // Only infer when dividend is non-negative and divisor is strictly positive
    // to keep the logic simple and avoid dealing with rounding toward zero for
    // negative operands. Mixed-sign or zero-divisor cases fall through to `int`.
    let dividend_nn = n1_min.is_some_and(|m| m >= 0);
    let divisor_pos = n2_min.is_some_and(|m| m > 0);
    if !dividend_nn || !divisor_pos {
        return None;
    }

    // Result is in [0, n1_max / n2_min] when both are known; [0, ∞) otherwise.
    let new_max = match (n1_max, n2_min) {
        (Some(hi), Some(lo)) => hi.checked_div(lo),
        _ => None,
    };
    let atom = match (Some(0i64), new_max) {
        (Some(0), None) => Atomic::TNonNegativeInt,
        (Some(1), None) => Atomic::TPositiveInt,
        (min, max) => Atomic::TIntRange { min, max },
    };
    Some(Type::single(atom))
}

/// Extract (min, max) int bounds from a type that consists entirely of int subtypes.
/// Returns `None` when the type contains non-integer components.
fn int_type_bounds(ty: &Type) -> Option<(Option<i64>, Option<i64>)> {
    if ty.types.is_empty() {
        return None;
    }
    let mut min: Option<i64> = Some(i64::MAX);
    let mut max: Option<i64> = Some(i64::MIN);
    for a in &ty.types {
        let (lo, hi) = match a {
            Atomic::TLiteralInt(n) => (Some(*n), Some(*n)),
            Atomic::TIntRange { min, max } => (*min, *max),
            Atomic::TPositiveInt => (Some(1), None),
            Atomic::TNonNegativeInt => (Some(0), None),
            Atomic::TNegativeInt => (None, Some(-1)),
            Atomic::TInt => (None, None),
            _ => return None,
        };
        min = match (min, lo) {
            (Some(m), Some(l)) => Some(m.min(l)),
            _ => None,
        };
        max = match (max, hi) {
            (Some(m), Some(h)) => Some(m.max(h)),
            _ => None,
        };
    }
    Some((min, max))
}

/// Infer the return type of `min($a, $b, ...)` when all arguments are purely integer.
///
/// For `min(a, b)`:
/// - result_min = min(a_min, b_min) — the smallest possible value we could see
/// - result_max = min(a_max, b_max) — the smallest of the upper bounds
pub(crate) fn min_return_type(arg_types: &[Type]) -> Option<Type> {
    if arg_types.is_empty() {
        return None;
    }
    // Only engage when every argument is purely integer.
    let bounds: Vec<(Option<i64>, Option<i64>)> = arg_types
        .iter()
        .map(int_type_bounds)
        .collect::<Option<_>>()?;
    let result_min = bounds.iter().fold(None::<Option<i64>>, |acc, (lo, _)| {
        Some(match (acc, lo) {
            (None, v) => *v,
            (Some(Some(a)), Some(b)) => Some(a.min(*b)),
            _ => None,
        })
    })?;
    let result_max = bounds.iter().fold(None::<Option<i64>>, |acc, (_, hi)| {
        Some(match (acc, hi) {
            (None, v) => *v,
            (Some(Some(a)), Some(b)) => Some(a.min(*b)),
            (Some(None), Some(b)) => Some(*b),
            (Some(Some(a)), None) => Some(a),
            _ => None,
        })
    })?;
    Some(Type::single(make_int_range_atom(result_min, result_max)))
}

/// Infer the return type of `max($a, $b, ...)` when all arguments are purely integer.
///
/// For `max(a, b)`:
/// - result_min = max(a_min, b_min) — the largest of the lower bounds
/// - result_max = max(a_max, b_max) — the largest possible value we could see
pub(crate) fn max_return_type(arg_types: &[Type]) -> Option<Type> {
    if arg_types.is_empty() {
        return None;
    }
    let bounds: Vec<(Option<i64>, Option<i64>)> = arg_types
        .iter()
        .map(int_type_bounds)
        .collect::<Option<_>>()?;
    let result_min = bounds.iter().fold(None::<Option<i64>>, |acc, (lo, _)| {
        Some(match (acc, lo) {
            (None, v) => *v,
            (Some(Some(a)), Some(b)) => Some(a.max(*b)),
            (Some(None), Some(b)) => Some(*b),
            (Some(Some(a)), None) => Some(a),
            _ => None,
        })
    })?;
    let result_max = bounds.iter().fold(None::<Option<i64>>, |acc, (_, hi)| {
        Some(match (acc, hi) {
            (None, v) => *v,
            (Some(Some(a)), Some(b)) => Some(a.max(*b)),
            _ => None,
        })
    })?;
    Some(Type::single(make_int_range_atom(result_min, result_max)))
}

/// Canonicalise (min, max) int bounds into the most specific int Atomic.
fn make_int_range_atom(min: Option<i64>, max: Option<i64>) -> Atomic {
    match (min, max) {
        (Some(1), None) => Atomic::TPositiveInt,
        (Some(0), None) => Atomic::TNonNegativeInt,
        (None, Some(-1)) => Atomic::TNegativeInt,
        (None, None) => Atomic::TInt,
        (min, max) => Atomic::TIntRange { min, max },
    }
}

/// Infer the return type of `rand($min, $max)` / `mt_rand($min, $max)` /
/// `random_int($min, $max)` when both bounds are known integer literals.
///
/// With no arguments, `rand()` / `mt_rand()` return an unspecified int — fall
/// through to the stub. With two literal bounds, narrow to `int<min, max>`.
pub(crate) fn rand_return_type(arg_types: &[Type]) -> Option<Type> {
    let (min_ty, max_ty) = (arg_types.first()?, arg_types.get(1)?);
    let extract_literal = |ty: &Type| {
        if ty.types.len() == 1 {
            if let Atomic::TLiteralInt(n) = ty.types[0] {
                return Some(n);
            }
        }
        None
    };
    let lo = extract_literal(min_ty)?;
    let hi = extract_literal(max_ty)?;
    if lo > hi {
        return None; // degenerate — let stub handle it
    }
    Some(Type::single(make_int_range_atom(Some(lo), Some(hi))))
}

/// Infer the return type of `range($start, $end, $step?)`.
///
/// When both bounds are integer literals (or single-value integer ranges), return
/// `non-empty-list<int<min, max>>`. Otherwise fall back to `None`.
/// `range()` always returns a list (re-indexed from 0) and is always non-empty.
pub(crate) fn range_return_type(arg_types: &[Type]) -> Option<Type> {
    let start = arg_types.first()?;
    let end = arg_types.get(1)?;

    fn single_int_bound(t: &Type) -> Option<i64> {
        if t.types.len() != 1 {
            return None;
        }
        match &t.types[0] {
            Atomic::TLiteralInt(n) => Some(*n),
            Atomic::TIntRange {
                min: Some(lo),
                max: Some(hi),
            } if lo == hi => Some(*lo),
            _ => None,
        }
    }

    let lo = single_int_bound(start)?;
    let hi = single_int_bound(end)?;
    let (range_min, range_max) = if lo <= hi { (lo, hi) } else { (hi, lo) };
    let elem = Atomic::TIntRange {
        min: Some(range_min),
        max: Some(range_max),
    };
    Some(Type::single(Atomic::TNonEmptyList {
        value: Box::new(Type::single(elem)),
    }))
}

/// Returns `(callback_arg_index, min_required_arity)` for built-in functions that enforce a
/// minimum callback arity via `check_min_arity_callback`. Functions with more complex rules
/// (array_map, array_filter) use their own specialized handlers instead.
pub(crate) fn callback_min_arity_spec(fn_name: &str) -> Option<(usize, usize)> {
    match fn_name {
        "array_reduce" => Some((1, 2)),
        "usort" | "uasort" | "uksort" => Some((1, 2)),
        "array_walk" | "array_walk_recursive" => Some((1, 1)),
        _ => None,
    }
}

/// Validate a callback argument against a minimum required arity.
pub(crate) fn check_min_arity_callback(
    ea: &mut ExpressionAnalyzer<'_>,
    fn_name: &str,
    callback_idx: usize,
    min_arity: usize,
    arg_types: &[Type],
    arg_spans: &[Span],
) {
    if arg_types.len() <= callback_idx || arg_spans.len() <= callback_idx {
        return;
    }

    let callback_ty = &arg_types[callback_idx];
    let callback_span = arg_spans[callback_idx];

    if !is_valid_callable_type(callback_ty) {
        ea.emit(
            IssueKind::InvalidArgument {
                param: "callback".to_string(),
                fn_name: fn_name.to_string(),
                expected: "callable".to_string(),
                actual: callback_ty.to_string(),
            },
            Severity::Error,
            callback_span,
        );
        return;
    }

    record_callable_string_ref(ea, callback_ty, callback_span);

    if let Some(params) = extract_callable_params(callback_ty, ea) {
        let required_count = params
            .iter()
            .filter(|p| !p.is_optional && !p.is_variadic)
            .count();
        if required_count < min_arity {
            let expected_plural = if min_arity == 1 { "" } else { "s" };
            let actual_plural = if required_count == 1 { "" } else { "s" };
            ea.emit(
                IssueKind::InvalidArgument {
                    param: "callback".to_string(),
                    fn_name: fn_name.to_string(),
                    expected: format!(
                        "callable accepting at least {} argument{}",
                        min_arity, expected_plural
                    ),
                    actual: format!(
                        "callable accepting {} argument{}",
                        required_count, actual_plural
                    ),
                },
                Severity::Error,
                callback_span,
            );
        }
    }
}

/// True when `ty` contains an unresolved bareword named-object or an explicit template
/// param — almost certainly an unsubstituted generic (e.g. `TValue` in a Laravel-style
/// `callable(TValue): bool` docblock) rather than a real, checkable type. Comparing
/// against these would produce false positives for generic callable signatures.
///
/// `template_names` additionally catches the rare case where a bareword happens to name a
/// *real* class that shadows an unrelated `@template` of the same name (e.g. a project
/// class literally named `T`) — a plain `class_exists` check alone would treat that as a
/// resolvable type and compare against it, which is wrong: within this function/method,
/// the name refers to the template, not the shadowed class.
///
/// Recurses into containers (array/list key & value, keyed-array shapes, intersections,
/// generic type arguments, nested callable/closure signatures) — a shallow top-level-only
/// check would miss e.g. `array<TKey, TValue>` or `Collection<TValue>` used as a typed
/// callable's own parameter type.
fn contains_unresolvable_named_type(
    ty: &Type,
    ea: &ExpressionAnalyzer<'_>,
    template_names: &rustc_hash::FxHashSet<&str>,
) -> bool {
    ty.types
        .iter()
        .any(|a| atomic_contains_unresolvable_named_type(a, ea, template_names))
}

fn atomic_contains_unresolvable_named_type(
    a: &Atomic,
    ea: &ExpressionAnalyzer<'_>,
    template_names: &rustc_hash::FxHashSet<&str>,
) -> bool {
    match a {
        Atomic::TNamedObject { fqcn, type_params } => {
            (!fqcn.contains('\\')
                && (template_names.contains(fqcn.as_ref())
                    || !crate::db::class_exists(ea.db, fqcn.as_ref())))
                || type_params
                    .iter()
                    .any(|tp| contains_unresolvable_named_type(tp, ea, template_names))
        }
        Atomic::TTemplateParam { .. } => true,
        Atomic::TArray { key, value } | Atomic::TNonEmptyArray { key, value } => {
            contains_unresolvable_named_type(key, ea, template_names)
                || contains_unresolvable_named_type(value, ea, template_names)
        }
        Atomic::TList { value } | Atomic::TNonEmptyList { value } => {
            contains_unresolvable_named_type(value, ea, template_names)
        }
        Atomic::TKeyedArray { properties, .. } => properties
            .values()
            .any(|p| contains_unresolvable_named_type(&p.ty, ea, template_names)),
        Atomic::TIntersection { parts } => parts
            .iter()
            .any(|p| contains_unresolvable_named_type(p, ea, template_names)),
        Atomic::TCallable {
            params,
            return_type,
        } => {
            params.as_ref().is_some_and(|ps| {
                ps.iter().any(|p| {
                    p.ty.as_ref().is_some_and(|t| {
                        contains_unresolvable_named_type(&t.to_union(), ea, template_names)
                    })
                })
            }) || return_type
                .as_ref()
                .is_some_and(|r| contains_unresolvable_named_type(r, ea, template_names))
        }
        Atomic::TClosure { data } => {
            data.params.iter().any(|p| {
                p.ty.as_ref().is_some_and(|t| {
                    contains_unresolvable_named_type(&t.to_union(), ea, template_names)
                })
            }) || contains_unresolvable_named_type(&data.return_type, ea, template_names)
        }
        _ => false,
    }
}

/// True when a scalar union consists entirely of int/float atoms (no bool, no string).
fn is_int_or_float(t: &Type) -> bool {
    !t.types.is_empty()
        && t.types.iter().all(|a| {
            matches!(
                a,
                Atomic::TInt
                    | Atomic::TLiteralInt(_)
                    | Atomic::TIntRange { .. }
                    | Atomic::TPositiveInt
                    | Atomic::TNegativeInt
                    | Atomic::TNonNegativeInt
                    | Atomic::TFloat
                    | Atomic::TIntegralFloat
                    | Atomic::TLiteralFloat(..)
            )
        })
}

/// Returns `true` when a value of type `expected` (what the documented callable signature
/// promises to pass) can safely reach a parameter declared as `actual` (the closure's own
/// parameter type).
///
/// Beyond structural/class-hierarchy subtyping (`is_subtype`), the only extra allowance is
/// int/float interconverting — mirroring `call/args/types.rs`'s `ImplicitFloatToIntCast`
/// handling, since PHP treats a lossy float->int narrowing as a deprecation notice, not a
/// `TypeError`, even in coercive mode (int->float is already covered by `is_subtype`
/// itself). Every other cross-scalar-family mismatch (`bool<->int`, `int/float->string`,
/// `string->int/float/bool`, ...) is deliberately left as a hard mismatch: it matches how
/// the same conversions are treated for direct argument checks (`InvalidArgument`, not a
/// silent pass), so this check stays consistent with the rest of the analyzer's severity
/// choices rather than inventing a more lenient policy just for typed-callable signatures.
fn expected_fits_actual_param(expected: &Type, actual: &Type, ea: &ExpressionAnalyzer<'_>) -> bool {
    if expected.is_mixed() || actual.is_mixed() {
        return true;
    }
    if crate::subtype::is_subtype(ea.db, expected, actual) {
        return true;
    }
    if ea.strict_types {
        return false;
    }
    is_int_or_float(expected) && is_int_or_float(actual)
}

/// Validate a callback argument against a typed callable parameter (e.g., callable(str,str,str):bool).
/// Emits InvalidArgument if the provided callable has more required params than expected, or if a
/// resolvable parameter type is declared too narrow to accept what the signature promises to pass.
#[allow(clippy::too_many_arguments)]
pub(crate) fn check_typed_callable_arg(
    ea: &mut ExpressionAnalyzer<'_>,
    fn_name: &str,
    param_name: &str,
    arg_ty: &Type,
    expected_params: &[FnParam],
    expected_return: Option<&Type>,
    arg_span: Span,
    template_params: &[mir_codebase::definitions::TemplateParam],
) {
    let template_names: rustc_hash::FxHashSet<&str> =
        template_params.iter().map(|tp| tp.name.as_ref()).collect();
    // A bare `callable` (unknown arity) anywhere in the union means we can't check
    // statically — bail out to avoid false positives from sibling closure members.
    if arg_ty
        .types
        .iter()
        .any(|a| matches!(a, Atomic::TCallable { params: None, .. }))
    {
        return;
    }
    // A union of closures (e.g. from a ternary) must have every candidate checked —
    // the runtime value could be any of them, not just the first.
    let candidates = extract_all_callable_candidates(arg_ty, ea);
    if candidates.is_empty() {
        return;
    }

    // The `=` suffix on a docblock callable param (`Closure(mixed, array=, T=):mixed`) marks
    // a parameter the implementing closure is free to leave out of its own signature — it
    // isn't a promise that invocations always omit it, so it doesn't lower how many required
    // params a closure may declare. The real ceiling is the full declared param count (a
    // trailing variadic accepts any number, so it never caps).
    let expected_required = expected_params.iter().filter(|p| !p.is_variadic).count();
    let actual_required = candidates
        .iter()
        .map(|params| {
            params
                .iter()
                .filter(|p| !p.is_optional && !p.is_variadic)
                .count()
        })
        .max()
        .unwrap_or(0);

    if actual_required > expected_required {
        ea.emit(
            IssueKind::InvalidArgument {
                param: param_name.to_string(),
                fn_name: fn_name.to_string(),
                expected: format!("callable with {} required parameter(s)", expected_required),
                actual: format!("callable with {} required parameter(s)", actual_required),
            },
            Severity::Error,
            arg_span,
        );
        return;
    }

    // Parameter-type contravariance: every candidate closure must be able to accept
    // whatever the documented signature promises to pass it. Only fires for simple,
    // fully-resolved types on both sides — templates/unresolved docblock types are
    // skipped entirely to avoid false positives on generic callable signatures.
    for params in &candidates {
        for (i, expected) in expected_params.iter().enumerate() {
            let Some(actual) = params.get(i) else {
                break;
            };
            // A default value (including a variadic's implicit default of "none passed")
            // often means the real accepted type is wider than the declared hint — the
            // common legacy `int $a = null` implicit-nullable pattern being the prime
            // example. Skip rather than risk a false positive we can't fully verify.
            if actual.is_optional || actual.is_variadic {
                continue;
            }
            let Some(expected_ty) = expected.ty.as_ref().map(|t| t.to_union()) else {
                continue;
            };
            let Some(actual_ty) = actual.ty.as_ref() else {
                continue;
            };
            if expected_ty.is_mixed() || actual_ty.is_mixed() {
                continue;
            }
            if contains_unresolvable_named_type(&expected_ty, ea, &template_names)
                || contains_unresolvable_named_type(actual_ty, ea, &template_names)
            {
                continue;
            }
            if !expected_fits_actual_param(&expected_ty, actual_ty, ea) {
                ea.emit(
                    IssueKind::InvalidArgument {
                        param: param_name.to_string(),
                        fn_name: fn_name.to_string(),
                        expected: format!(
                            "callable whose parameter #{} accepts {expected_ty}",
                            i + 1
                        ),
                        actual: format!(
                            "callable whose parameter #{} only accepts {actual_ty}",
                            i + 1
                        ),
                    },
                    Severity::Error,
                    arg_span,
                );
                return;
            }
        }
    }

    // Return-type covariance: every candidate's return type must be assignable to
    // the promised return type — the symmetric counterpart to the parameter
    // contravariance loop above (`callable(int):string` is a contract on both
    // halves of the signature, not just the params). Reuses
    // `expected_fits_actual_param`'s subtype+leniency logic with the argument
    // order swapped: here the *candidate's* return type plays the "expected"
    // (must-fit-into) role.
    if let Some(expected_ret) = expected_return {
        if !expected_ret.is_mixed()
            && !contains_unresolvable_named_type(expected_ret, ea, &template_names)
        {
            for actual_ret in extract_all_callable_return_types(arg_ty, ea) {
                if actual_ret.is_mixed()
                    || contains_unresolvable_named_type(&actual_ret, ea, &template_names)
                {
                    continue;
                }
                if !expected_fits_actual_param(&actual_ret, expected_ret, ea) {
                    ea.emit(
                        IssueKind::InvalidArgument {
                            param: param_name.to_string(),
                            fn_name: fn_name.to_string(),
                            expected: format!("callable returning {expected_ret}"),
                            actual: format!("callable returning {actual_ret}"),
                        },
                        Severity::Error,
                        arg_span,
                    );
                    return;
                }
            }
        }
    }
}

/// Infer the return type of `filter_var($value, $filter)`, mapping a literal
/// `FILTER_VALIDATE_*` constant to its real result type instead of the
/// stub's blanket `mixed`.
///
/// Deliberately bails (falls back to the stub) whenever a 3rd (`$options`)
/// argument is present: the `FILTER_NULL_ON_FAILURE` flag — settable either
/// as a bare int or nested in `['flags' => ...]` — changes the failure case
/// from `false` to `null`, and this doesn't attempt to evaluate that flag
/// out of the options argument. Only the exactly-2-argument call (no
/// options, so `FILTER_NULL_ON_FAILURE` cannot be set) gets a precise type.
pub(crate) fn filter_var_return_type(arg_types: &[Type]) -> Option<Type> {
    if arg_types.len() > 2 {
        return None;
    }
    let filter_arg = arg_types.get(1)?;
    let [Atomic::TLiteralInt(filter)] = filter_arg.types.as_slice() else {
        return None;
    };
    // Constant values from stubs/filter/filter.php.
    let mut ty = match filter {
        257 => Type::single(Atomic::TInt),   // FILTER_VALIDATE_INT
        259 => Type::single(Atomic::TFloat), // FILTER_VALIDATE_FLOAT
        // FILTER_VALIDATE_BOOLEAN/BOOL: bool already covers the no-options
        // failure case (false), so no |false needed.
        258 => return Some(Type::single(Atomic::TBool)),
        // FILTER_VALIDATE_REGEXP/URL/EMAIL/IP/MAC/DOMAIN
        272..=277 => Type::single(Atomic::TString),
        _ => return None,
    };
    ty.add_type(Atomic::TFalse);
    Some(ty)
}

/// Infer the return type of `preg_split($pattern, $subject, $limit?, $flags?)`.
///
/// `preg_split` always produces at least one string unless `PREG_SPLIT_NO_EMPTY` (value 1) is
/// set and every part is empty. When `$flags` is 0 (default) or absent, the result is
/// guaranteed non-empty: `non-empty-list<string>|false`. When `PREG_SPLIT_OFFSET_CAPTURE` (4)
/// is set each element is an array, which we don't model — falls back to stub.
/// Falls back to stub `array|false` for other flag combinations.
pub(crate) fn preg_split_return_type(arg_types: &[Type]) -> Option<Type> {
    // flags is the 4th argument (index 3). When absent the default is 0.
    let flags_ty = arg_types.get(3);
    let flags_zero = match flags_ty {
        None => true,
        Some(t) => t.types.len() == 1 && matches!(t.types.first(), Some(Atomic::TLiteralInt(0))),
    };
    if !flags_zero {
        return None;
    }
    // No PREG_SPLIT_NO_EMPTY → always at least one part. The false case only
    // fires on an invalid regex, which PHP code never handles in practice.
    let result = Type::single(Atomic::TNonEmptyList {
        value: Box::new(Type::single(Atomic::TString)),
    });
    Some(result)
}

/// Infer the new type of the by-ref array argument after `array_push($arr, ...$vals)` or
/// `array_unshift($arr, ...$vals)`.
///
/// Both functions append/prepend to the array and always make it non-empty when at least one
/// value is pushed. The value type grows to include all pushed types. List structure is
/// preserved: if the source is a list, the result is `non-empty-list<T>`.
///
/// Returns the original array type unchanged when inference is not possible (mixed input,
/// no pushed values, etc.).
/// Build `list<string>` or `list<array{0: string, 1: int}>` for `preg_match` `$matches`.
///
/// When bit 256 (`PREG_OFFSET_CAPTURE`) is set in `flags`, each entry is a shape
/// `array{0: string, 1: int}` holding the matched text and its byte offset.
pub(crate) fn preg_match_matches_type(flags: i64) -> Type {
    Type::single(Atomic::TList {
        value: Box::new(preg_match_leaf(flags)),
    })
}

/// Build `list<list<string>>` or `list<list<array{0: string, 1: int}>>` for `preg_match_all`.
///
/// `PREG_SET_ORDER` changes the ordering (sets vs. groups outer) but not the
/// per-match element types; `PREG_OFFSET_CAPTURE` adds an int offset to each leaf.
pub(crate) fn preg_match_all_matches_type(flags: i64) -> Type {
    let inner = Type::single(Atomic::TList {
        value: Box::new(preg_match_leaf(flags)),
    });
    Type::single(Atomic::TList {
        value: Box::new(inner),
    })
}

fn preg_match_leaf(flags: i64) -> Type {
    const PREG_OFFSET_CAPTURE: i64 = 256;
    if flags & PREG_OFFSET_CAPTURE != 0 {
        // array{0: string, 1: int}
        let mut props = indexmap::IndexMap::new();
        props.insert(
            mir_types::atomic::ArrayKey::Int(0),
            mir_types::atomic::KeyedProperty {
                ty: Type::single(Atomic::TString),
                optional: false,
            },
        );
        props.insert(
            mir_types::atomic::ArrayKey::Int(1),
            mir_types::atomic::KeyedProperty {
                ty: Type::single(Atomic::TInt),
                optional: false,
            },
        );
        Type::single(Atomic::TKeyedArray {
            properties: Box::new(props),
            is_open: false,
            is_list: true,
        })
    } else {
        Type::single(Atomic::TString)
    }
}