mir-analyzer 0.45.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
use php_ast::owned::{ExprKind, FunctionCallExpr};
use php_ast::Span;

use std::sync::Arc;

use mir_codebase::storage::{Assertion, AssertionKind, FnParam, TemplateParam};
use mir_issues::{IssueKind, Severity};
use mir_types::atomic::FnParam as TypeFnParam;
use mir_types::{Atomic, Name, Type};

use crate::expr::ExpressionAnalyzer;
use crate::flow_state::FlowState;
use crate::generic::{check_template_bounds_with_inheritance, infer_template_bindings};
use crate::symbol::ReferenceKind;
use crate::taint::{classify_sink, is_expr_tainted, SinkKind};

use super::args::{
    check_args, expr_can_be_passed_by_reference_owned, spread_element_type, CheckArgsParams,
};
use super::callable::extract_callable_params;
use super::CallAnalyzer;

struct ResolvedFn {
    fqn: std::sync::Arc<str>,
    deprecated: Option<std::sync::Arc<str>>,
    params: Vec<FnParam>,
    template_params: Vec<TemplateParam>,
    assertions: Vec<Assertion>,
    return_ty_raw: Type,
    throws: Arc<[Arc<str>]>,
    no_named_arguments: bool,
    is_pure: bool,
}

fn resolve_fn(ea: &ExpressionAnalyzer<'_>, fqn: &str) -> Option<ResolvedFn> {
    let db = ea.db;
    let inferred = crate::db::inferred_function_return_type_demand(db, fqn);
    let here = crate::db::Fqcn::from_str(db, fqn);
    if let Some(f) = crate::db::find_function(db, here) {
        let return_ty_raw = f
            .return_type
            .clone()
            .or(inferred)
            .map(|t| (*t).clone())
            .unwrap_or_else(Type::mixed);
        return Some(ResolvedFn {
            fqn: f.fqn.clone(),
            deprecated: f.deprecated.clone(),
            params: f.params.to_vec(),
            template_params: f.template_params.clone(),
            assertions: f.assertions.clone(),
            return_ty_raw,
            throws: Arc::<[Arc<str>]>::from(f.throws.as_slice()),
            no_named_arguments: f.no_named_arguments,
            is_pure: f.is_pure,
        });
    }
    None
}

impl CallAnalyzer {
    pub fn analyze_function_call<'a>(
        ea: &mut ExpressionAnalyzer<'a>,
        call: &FunctionCallExpr,
        ctx: &mut FlowState,
        span: Span,
    ) -> Type {
        let fn_name = match &call.name.kind {
            ExprKind::Identifier(name) => name.as_ref().to_string(),
            _ => {
                let callee_ty = ea.analyze(&call.name, ctx);

                if callee_ty.is_mixed() {
                    ea.emit(IssueKind::MixedFunctionCall, Severity::Info, span);
                }

                // Collect arg types, spans, names and byref flags for type checking.
                let mut inner_arg_types: Vec<Type> = Vec::with_capacity(call.args.len());
                for arg in call.args.iter() {
                    let ty = ea.analyze(&arg.value, ctx);
                    super::consume_arg_assignment(&arg.value, ctx);
                    inner_arg_types.push(if arg.unpack {
                        spread_element_type(&ty)
                    } else {
                        ty
                    });
                }
                let inner_arg_spans: Vec<Span> = call.args.iter().map(|a| a.span).collect();
                let inner_arg_names: Vec<Option<String>> = call
                    .args
                    .iter()
                    .map(|a| a.name.as_ref().map(crate::parser::name_to_string_owned))
                    .collect();
                let inner_arg_byref: Vec<bool> = call
                    .args
                    .iter()
                    .map(|a| expr_can_be_passed_by_reference_owned(&a.value))
                    .collect();
                let has_spread = call.args.iter().any(|a| a.unpack);

                if let Some((callee_fn_name, params)) = typed_params_from_callee(&callee_ty, ea) {
                    // Full type + arity checking via check_args.
                    check_args(
                        ea,
                        CheckArgsParams {
                            fn_name: &callee_fn_name,
                            params: &params,
                            arg_types: &inner_arg_types,
                            arg_spans: &inner_arg_spans,
                            arg_names: &inner_arg_names,
                            arg_can_be_byref: &inner_arg_byref,
                            call_span: span,
                            has_spread,
                            template_params: &[],
                            no_named_arguments: false,
                        },
                    );
                } else if let Some(params) = extract_callable_params(&callee_ty, ea) {
                    // Arity-only fallback when full param types are unavailable.
                    let required_count = params
                        .iter()
                        .filter(|p| !p.is_optional && !p.is_variadic)
                        .count();
                    let has_variadic = params.iter().any(|p| p.is_variadic);
                    let max_params = params.len();
                    let actual_count = call.args.len();

                    if actual_count < required_count {
                        ea.emit(
                            IssueKind::TooFewArguments {
                                fn_name: "callable".to_string(),
                                expected: required_count,
                                actual: actual_count,
                            },
                            Severity::Error,
                            span,
                        );
                    } else if !has_variadic && actual_count > max_params {
                        ea.emit(
                            IssueKind::TooManyArguments {
                                fn_name: "callable".to_string(),
                                expected: max_params,
                                actual: actual_count,
                            },
                            Severity::Error,
                            span,
                        );
                    }
                }

                for atomic in &callee_ty.types {
                    match atomic {
                        Atomic::TClosure { return_type, .. } => return *return_type.clone(),
                        Atomic::TCallable {
                            return_type: Some(rt),
                            ..
                        } => return *rt.clone(),
                        _ => {}
                    }
                }
                return Type::mixed();
            }
        };

        // Taint sink check (M19): before evaluating args so we can inspect raw exprs
        if let Some(sink_kind) = classify_sink(&fn_name) {
            let relevant = sink_kind.tainted_arg_indices();
            for (i, arg) in call.args.iter().enumerate() {
                // Path/payload sinks only care about their specific argument
                // (e.g. a tainted *path*, not tainted *data* written to a
                // constant path); output/query/command sinks check any arg.
                if relevant.is_some_and(|idxs| !idxs.contains(&i)) {
                    continue;
                }
                if is_expr_tainted(&arg.value, ctx) {
                    let issue_kind = match sink_kind {
                        SinkKind::Html => IssueKind::TaintedHtml,
                        SinkKind::Sql => IssueKind::TaintedSql,
                        SinkKind::Shell => IssueKind::TaintedShell,
                        SinkKind::File => IssueKind::TaintedInput {
                            sink: "file".to_string(),
                        },
                        SinkKind::Unserialize => IssueKind::TaintedInput {
                            sink: "unserialize".to_string(),
                        },
                    };
                    ea.emit(issue_kind, Severity::Error, span);
                    break;
                }
            }
        }

        // PHP resolves `foo()` as `\App\Ns\foo` first, then `\foo` if not found.
        // A leading `\` means explicit global namespace.
        let fn_name = fn_name
            .strip_prefix('\\')
            .map(|s: &str| s.to_string())
            .unwrap_or(fn_name);
        if matches!(
            fn_name.to_ascii_lowercase().as_str(),
            "var_dump" | "shell_exec"
        ) {
            ea.emit(
                IssueKind::ForbiddenCode {
                    message: format!("Use of {} is forbidden", fn_name),
                },
                Severity::Warning,
                span,
            );
        }
        let resolved_fn_name: String = {
            let imports = ea.db.file_imports(&ea.file);
            let qualified = if let Some(imported) = imports.get(&Name::new(fn_name.as_str())) {
                imported.as_str().to_string()
            } else if fn_name.contains('\\') {
                crate::db::resolve_name(ea.db, &ea.file, &fn_name)
            } else if let Some(ns) = ea.db.file_namespace(&ea.file) {
                format!("{}\\{}", ns, fn_name)
            } else {
                fn_name.clone()
            };
            let fn_exists = |name: &str| -> bool {
                let db = ea.db;
                let here = crate::db::Fqcn::from_str(db, name);
                crate::db::find_function(db, here).is_some()
            };
            if fn_exists(qualified.as_str()) {
                qualified
            } else if fn_exists(fn_name.as_str()) {
                fn_name.clone()
            } else {
                qualified
            }
        };

        // Resolve once; reused below for by-ref pre-marking and full analysis.
        let resolved = resolve_fn(ea, resolved_fn_name.as_str());

        // Pre-mark by-reference parameter variables as defined BEFORE evaluating args
        if let Some(ref resolved) = resolved {
            for (i, param) in resolved.params.iter().enumerate() {
                if param.is_byref {
                    if param.is_variadic {
                        for arg in call.args.iter().skip(i) {
                            if let ExprKind::Variable(name) = &arg.value.kind {
                                let var_name = name.as_ref().trim_start_matches('$');
                                if !ctx.var_is_defined(var_name) {
                                    ctx.set_var(var_name, Type::mixed());
                                }
                            }
                        }
                    } else if let Some(arg) = call.args.get(i) {
                        if let ExprKind::Variable(name) = &arg.value.kind {
                            let var_name = name.as_ref().trim_start_matches('$');
                            if !ctx.var_is_defined(var_name) {
                                ctx.set_var(var_name, Type::mixed());
                            }
                        }
                    }
                }
            }
        }

        let mut arg_types = super::ARG_TYPES_BUF
            .with(|b| b.borrow_mut().take())
            .unwrap_or_default();
        arg_types.clear();
        for arg in call.args.iter() {
            let ty = ea.analyze(&arg.value, ctx);
            super::consume_arg_assignment(&arg.value, ctx);
            arg_types.push(if arg.unpack {
                spread_element_type(&ty)
            } else {
                ty
            });
        }

        let arg_spans: Vec<Span> = call.args.iter().map(|a| a.span).collect();

        // When call_user_func / call_user_func_array is called with a bare string
        // literal as the callable argument, treat that string as a direct FQN
        // reference so the named function is not flagged as dead code.
        // Note: 'helper' always resolves to \helper (global) — no namespace
        // fallback applies to runtime callable strings.
        let mut call_user_func_string_arg = false;
        if matches!(
            resolved_fn_name.as_str(),
            "call_user_func" | "call_user_func_array"
        ) {
            if let Some(arg) = call.args.first() {
                if let ExprKind::String(name) = &arg.value.kind {
                    call_user_func_string_arg = true;
                    // Always look in global namespace (with explicit backslash prefix)
                    let fqn = if name.as_ref().starts_with('\\') {
                        name.as_ref().to_string()
                    } else {
                        format!("\\{}", name.as_ref())
                    };
                    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(canonical_fqn.as_ref()), arg.span);
                    }
                }
            }
        }

        // compact() reads variables by string name at runtime; mark each string-literal arg as read
        if fn_name == "compact" {
            for arg in call.args.iter() {
                if let ExprKind::String(name) = &arg.value.kind {
                    ctx.read_vars.insert(mir_types::Name::from(name.as_ref()));
                    ctx.mark_consumed(name.as_ref());
                }
            }
        }

        if let Some(resolved) = resolved {
            ea.record_ref(resolved.fqn.clone(), call.name.span);
            let deprecated = resolved.deprecated;
            let params = resolved.params;
            let template_params = resolved.template_params;
            let return_ty_raw = resolved.return_ty_raw;
            let no_named_arguments = resolved.no_named_arguments;
            let is_pure = resolved.is_pure;

            if ctx.is_in_pure_fn && !is_pure {
                ea.emit(
                    IssueKind::ImpureFunctionCall {
                        fn_name: fn_name.rsplit('\\').next().unwrap_or(&fn_name).to_string(),
                    },
                    Severity::Warning,
                    span,
                );
            }

            if let Some(msg) = deprecated {
                ea.emit(
                    IssueKind::DeprecatedCall {
                        name: resolved_fn_name.clone(),
                        message: Some(msg).filter(|m| !m.is_empty()),
                    },
                    Severity::Info,
                    span,
                );
            }

            if let Some((used, canonical_str)) =
                crate::fqcn_case_mismatch(&resolved_fn_name, resolved.fqn.as_ref())
            {
                ea.emit(
                    IssueKind::WrongCaseFunction {
                        used,
                        canonical: canonical_str,
                    },
                    Severity::Info,
                    call.name.span,
                );
            }

            check_args(
                ea,
                CheckArgsParams {
                    fn_name: &fn_name,
                    params: &params,
                    arg_types: &arg_types,
                    arg_spans: &arg_spans,
                    arg_names: &call
                        .args
                        .iter()
                        .map(|a| a.name.as_ref().map(crate::parser::name_to_string_owned))
                        .collect::<Vec<_>>(),
                    arg_can_be_byref: &call
                        .args
                        .iter()
                        .map(|a| expr_can_be_passed_by_reference_owned(&a.value))
                        .collect::<Vec<_>>(),
                    call_span: span,
                    has_spread: call.args.iter().any(|a| a.unpack),
                    template_params: &template_params,
                    no_named_arguments,
                },
            );

            // Validate callbacks for built-in PHP functions with special callback requirements.
            // Functions with dynamic or mode-dependent arity use specialized handlers.
            // Functions with a fixed minimum arity are declared in callback_min_arity_spec.
            match resolved_fn_name.as_str() {
                "array_map" => {
                    super::callable::check_array_map_callback(ea, &arg_types, &arg_spans)
                }
                "array_filter" => {
                    super::callable::check_array_filter_callback(ea, &arg_types, &arg_spans)
                }
                fn_name => {
                    if let Some((cb_idx, min_arity)) =
                        super::callable::callback_min_arity_spec(fn_name)
                    {
                        super::callable::check_min_arity_callback(
                            ea, fn_name, cb_idx, min_arity, &arg_types, &arg_spans,
                        );
                    }
                }
            }

            for (i, param) in params.iter().enumerate() {
                if param.is_byref {
                    let output_ty = param
                        .ty
                        .as_ref()
                        .map(|t| (**t).clone())
                        .unwrap_or_else(Type::mixed);
                    if param.is_variadic {
                        for arg in call.args.iter().skip(i) {
                            if let ExprKind::Variable(name) = &arg.value.kind {
                                let var_name = name.as_ref().trim_start_matches('$');
                                ctx.set_var(var_name, output_ty.clone());
                            }
                        }
                    } else if let Some(arg) = call.args.get(i) {
                        if let ExprKind::Variable(name) = &arg.value.kind {
                            let var_name = name.as_ref().trim_start_matches('$');
                            ctx.set_var(var_name, output_ty);
                        }
                    }
                }
            }

            let template_bindings = if !template_params.is_empty() {
                let bindings = infer_template_bindings(&template_params, &params, &arg_types);
                for (name, inferred, bound) in
                    check_template_bounds_with_inheritance(ea.db, &bindings, &template_params)
                {
                    ea.emit(
                        IssueKind::InvalidTemplateParam {
                            name: name.to_string(),
                            expected_bound: format!("{bound}"),
                            actual: format!("{inferred}"),
                        },
                        Severity::Error,
                        span,
                    );
                }
                Some(bindings)
            } else {
                None
            };

            for assertion in resolved
                .assertions
                .iter()
                .filter(|a| a.kind == AssertionKind::Assert)
            {
                if let Some(index) = params.iter().position(|p| p.name == assertion.param) {
                    if let Some(arg) = call.args.get(index) {
                        if let ExprKind::Variable(name) = &arg.value.kind {
                            let asserted_ty = match &template_bindings {
                                Some(b) => assertion.ty.substitute_templates(b),
                                None => assertion.ty.clone(),
                            };
                            ctx.set_var(name.as_ref().trim_start_matches('$'), asserted_ty);
                        }
                    }
                }
            }

            let return_ty = match &template_bindings {
                Some(bindings) => return_ty_raw.substitute_templates(bindings),
                None => return_ty_raw,
            };

            let return_ty = return_ty.resolve_conditional_returns(|param_name| {
                params
                    .iter()
                    .position(|p| p.name.as_ref() == param_name)
                    .and_then(|idx| arg_types.get(idx))
                    .cloned()
            });

            // Built-in array transformers whose stub return type is a generic
            // `array`: refine the element type from the callback / source array
            // so binding sites (e.g. `foreach` over the result) get a usable
            // value type. Falls back to the stub return when inference is unsure.
            let return_ty = match resolved_fn_name.as_str() {
                "array_map" => {
                    super::callable::infer_array_map_return(ea, &arg_types).unwrap_or(return_ty)
                }
                "array_filter" => {
                    super::callable::infer_array_filter_return(&arg_types).unwrap_or(return_ty)
                }
                "array_values" => {
                    super::callable::infer_array_values_return(&arg_types).unwrap_or(return_ty)
                }
                "array_merge" => {
                    super::callable::infer_array_merge_return(&arg_types).unwrap_or(return_ty)
                }
                // array_fill with a positive count returns a non-empty list.
                "array_fill" => {
                    super::callable::array_fill_return_type(&arg_types).unwrap_or(return_ty)
                }
                // implode/join with a non-empty array of non-empty strings returns non-empty-string.
                "implode" | "join" => {
                    super::callable::implode_return_type(&arg_types).unwrap_or(return_ty)
                }
                // str_split with a non-empty string returns a non-empty list<non-empty-string>.
                "str_split" => {
                    super::callable::str_split_return_type(&arg_types).unwrap_or(return_ty)
                }
                // explode with a non-empty separator always returns non-empty-list<string>.
                "explode" => super::callable::explode_return_type(&arg_types, &return_ty)
                    .unwrap_or(return_ty),
                // array_slice preserves the element type (and list structure when not
                // preserving keys).
                "array_slice" => {
                    super::callable::array_slice_return_type(&arg_types).unwrap_or(return_ty)
                }
                // array_keys of a non-empty array returns a non-empty list (preserving the
                // stub's key type from template resolution).
                "array_keys" => super::callable::array_keys_return_type(&arg_types, &return_ty),
                // array_reverse preserves the non-emptiness of the source array.
                "array_reverse" => {
                    super::callable::array_reverse_return_type(&arg_types).unwrap_or(return_ty)
                }
                // array_unique preserves key/value types and non-empty status.
                "array_unique" => {
                    super::callable::array_unique_return(&arg_types).unwrap_or(return_ty)
                }
                // range($start, $end) with integer bounds returns non-empty-list<int<min,max>>.
                "range" => super::callable::range_return_type(&arg_types).unwrap_or(return_ty),
                // array_key_first/array_key_last: non-null for non-empty input; int for lists.
                "array_key_first" | "array_key_last" => {
                    super::callable::array_key_first_last_return(&arg_types).unwrap_or(return_ty)
                }
                // array_pop/array_shift: return value type (not mixed) when source is typed.
                "array_pop" | "array_shift" => {
                    super::callable::array_pop_shift_return(&arg_types).unwrap_or(return_ty)
                }
                // Faithful integer-range returns: counts and lengths are
                // non-negative (and counts of non-empty collections are `>= 1`).
                "count" | "sizeof" => {
                    super::callable::count_return_type(&arg_types).unwrap_or(return_ty)
                }
                "strlen" | "mb_strlen" => super::callable::strlen_return_type(&arg_types),
                "abs" => super::callable::abs_return_type(&arg_types).unwrap_or(return_ty),
                "intdiv" => super::callable::intdiv_return_type(&arg_types).unwrap_or(return_ty),
                "min" => super::callable::min_return_type(&arg_types).unwrap_or(return_ty),
                "max" => super::callable::max_return_type(&arg_types).unwrap_or(return_ty),
                "rand" | "mt_rand" | "random_int" => {
                    super::callable::rand_return_type(&arg_types).unwrap_or(return_ty)
                }
                // preg_match returns 1 on match, 0 on no-match, false on error.
                "preg_match" => {
                    let mut ty = Type::single(Atomic::TIntRange {
                        min: Some(0),
                        max: Some(1),
                    });
                    ty.add_type(Atomic::TFalse);
                    ty
                }
                // preg_match_all returns the count of matches (>= 0) or false on error.
                "preg_match_all" => {
                    let mut ty = Type::single(Atomic::TNonNegativeInt);
                    ty.add_type(Atomic::TFalse);
                    ty
                }
                // Case-folding, encoding, and similar string functions that preserve non-emptiness:
                // a non-empty input always produces a non-empty output, and these functions
                // always return string (not string|false).
                "strtolower"
                | "strtoupper"
                | "mb_strtolower"
                | "mb_strtoupper"
                | "ucfirst"
                | "lcfirst"
                | "ucwords"
                | "mb_convert_case"
                | "mb_convert_kana"
                | "htmlspecialchars"
                | "htmlentities"
                | "html_entity_decode"
                | "htmlspecialchars_decode"
                | "addslashes"
                | "addcslashes"
                | "nl2br"
                | "urlencode"
                | "urldecode"
                | "rawurlencode"
                | "rawurldecode"
                | "base64_encode"
                | "quoted_printable_encode"
                | "quoted_printable_decode"
                | "str_rot13"
                | "str_pad"
                | "chunk_split"
                | "wordwrap" => {
                    super::callable::string_preserve_non_empty(&arg_types).unwrap_or(return_ty)
                }
                // sprintf/vsprintf: non-empty when the format string guarantees it.
                "sprintf" => super::callable::sprintf_return_type(&arg_types).unwrap_or(return_ty),
                // number_format() always returns a non-empty string.
                "number_format" => super::callable::number_format_return_type(),
                // str_repeat() with a non-empty string and positive count returns non-empty.
                "str_repeat" => {
                    super::callable::str_repeat_return_type(&arg_types).unwrap_or(return_ty)
                }
                // array_chunk splits an array into sub-arrays; outer list is non-empty when
                // source is non-empty; chunks are list<T> by default (preserve_keys=false).
                "array_chunk" => {
                    super::callable::array_chunk_return_type(&arg_types).unwrap_or(return_ty)
                }
                // array_fill_keys uses the values of $keys as result keys and $value as each result value.
                "array_fill_keys" => {
                    super::callable::array_fill_keys_return_type(&arg_types).unwrap_or(return_ty)
                }
                // preg_split with default flags always returns at least one part.
                "preg_split" => {
                    super::callable::preg_split_return_type(&arg_types).unwrap_or(return_ty)
                }
                // array_search: narrow key type from haystack rather than returning string|int|false.
                "array_search" => {
                    super::callable::array_search_return_type(&arg_types).unwrap_or(return_ty)
                }
                // date/time formatting functions always return non-empty strings.
                "date" | "gmdate" | "date_format" => Type::single(Atomic::TNonEmptyString),
                _ => return_ty,
            };

            // array_push/array_unshift: the by-ref loop above set $arr to the stub's
            // generic `array` type — replace it with the precise post-push type derived
            // from the original array type (arg_types[0]) and the pushed value types.
            if matches!(resolved_fn_name.as_str(), "array_push" | "array_unshift") {
                if let (Some(arr_arg), Some(original_arr)) = (call.args.first(), arg_types.first())
                {
                    if let ExprKind::Variable(name) = &arr_arg.value.kind {
                        let var_name = name.as_ref().trim_start_matches('$');
                        let push_types: Vec<Type> = arg_types.iter().skip(1).cloned().collect();
                        let new_type = super::callable::array_push_unshift_byref_type(
                            original_arr,
                            &push_types,
                        );
                        ctx.set_var(var_name, new_type);
                    }
                }
            }

            // Sort functions: the by-ref loop above set $arr to generic `array`; restore
            // the original element type. Re-indexing sorts also convert to a list.
            {
                let reindex = matches!(
                    resolved_fn_name.as_str(),
                    "sort" | "rsort" | "usort" | "shuffle"
                );
                let preserve = matches!(
                    resolved_fn_name.as_str(),
                    "asort" | "arsort" | "ksort" | "krsort" | "uasort" | "uksort"
                );
                if reindex || preserve {
                    if let (Some(arr_arg), Some(original_arr)) =
                        (call.args.first(), arg_types.first())
                    {
                        if let ExprKind::Variable(name) = &arr_arg.value.kind {
                            let var_name = name.as_ref().trim_start_matches('$');
                            let new_type = super::callable::sort_byref_type(original_arr, reindex);
                            ctx.set_var(var_name, new_type);
                        }
                    }
                }
            }

            super::ARG_TYPES_BUF.with(|b| {
                let mut g = b.borrow_mut();
                if g.as_ref().map_or(0, |v| v.capacity()) < arg_types.capacity() {
                    *g = Some(arg_types);
                }
            });

            // Check inter-procedural throws: if callee declares @throws, check if caller covers them.
            // Unchecked exceptions (RuntimeException / LogicException descendants) are skipped by
            // PHP convention — see [`is_unchecked_exception`].
            for callee_throw in resolved.throws.iter() {
                if crate::db::is_unchecked_exception(ea.db, callee_throw.as_ref()) {
                    continue;
                }
                if !ctx.fn_declared_throws.iter().any(|declared| {
                    declared.as_ref() == callee_throw.as_ref()
                        || crate::db::extends_or_implements(
                            ea.db,
                            callee_throw.as_ref(),
                            declared.as_ref(),
                        )
                }) {
                    ea.emit(
                        IssueKind::MissingThrowsDocblock {
                            class: callee_throw.to_string(),
                        },
                        Severity::Info,
                        span,
                    );
                }
            }

            ea.record_symbol(
                call.name.span,
                ReferenceKind::FunctionCall(resolved.fqn.clone()),
                return_ty.clone(),
            );
            return return_ty;
        }

        // Soft-fallback: if the build-time stub index recognises this name as
        // a PHP built-in, the codebase miss is a stub-loading race rather
        // than user error — the auto-discovery scanner missed it, the
        // session is in essentials-only mode without auto-discovery, or the
        // analyzer is mid-ingest. Suppressing the diagnostic avoids a class
        // of false positives that would otherwise plague consumers running
        // the lazy-stub setup. However, don't suppress if the function is
        // version-filtered (e.g. @removed in the target version) — it should
        // be reported as undefined.
        if let Some(stub_path) = crate::stubs::stub_path_for_function(&fn_name) {
            if let Some(stub_src) = crate::stubs::stub_content_for_path(stub_path) {
                // Parse the stub to check if this function is version-compatible.
                if let Some(docblock_text) = extract_function_docblock(stub_src, &fn_name) {
                    let doc = crate::parser::DocblockParser::parse(docblock_text);
                    // Check if the function is available in the current PHP version.
                    if ea
                        .php_version
                        .includes_symbol(doc.since.as_deref(), doc.removed.as_deref())
                    {
                        return Type::mixed();
                    }
                } else {
                    // No docblock found; assume the function is available (conservative).
                    return Type::mixed();
                }
            }
        }
        // Don't emit UndefinedFunction if call_user_func/call_user_func_array with string arg
        // - string args are runtime callable names that may not exist at compile time
        // Also skip when guarded by `function_exists('fn')` (PHP function names
        // are case-insensitive). The short name is matched too, since a bare
        // call in a namespace falls back to the global function the guard names.
        let short_fn = fn_name.rsplit('\\').next().unwrap_or(&fn_name);
        let guarded = ctx
            .function_exists_guards
            .iter()
            .any(|g| g.eq_ignore_ascii_case(&fn_name) || g.eq_ignore_ascii_case(short_fn));
        if !call_user_func_string_arg && !guarded {
            ea.emit(
                IssueKind::UndefinedFunction { name: fn_name },
                Severity::Error,
                span,
            );
        }
        Type::mixed()
    }
}

/// Extract the docblock for a function from PHP stub source code.
/// Returns the docblock text (without /** */ delimiters) if found.
fn extract_function_docblock<'a>(src: &'a str, fn_name: &str) -> Option<&'a str> {
    // Simple extraction: find /** ... */ followed by function declaration.
    let fn_pattern = format!("function {fn_name}");
    extract_docblock_before(src, &fn_pattern)
}

/// Extract the docblock for a class from PHP stub source code.
/// Returns the docblock text (without /** */ delimiters) if found.
pub(crate) fn extract_class_docblock<'a>(src: &'a str, class_name: &str) -> Option<&'a str> {
    // Handle both class and interface declarations.
    // Extract the short name (after last backslash if present).
    let short_name = class_name.split('\\').next_back().unwrap_or(class_name);

    // Try case-insensitive matching for "class" declarations.
    let class_pattern_lower = format!("class {}", short_name.to_lowercase());
    if let Some(docblock) = extract_docblock_case_insensitive(src, &class_pattern_lower) {
        return Some(docblock);
    }

    // Try case-insensitive matching for "interface" declarations.
    let interface_pattern_lower = format!("interface {}", short_name.to_lowercase());
    extract_docblock_case_insensitive(src, &interface_pattern_lower)
}

/// Generic docblock extraction: find /** ... */ before a pattern (case-sensitive).
fn extract_docblock_before<'a>(src: &'a str, pattern: &str) -> Option<&'a str> {
    if let Some(pos) = src.find(pattern) {
        extract_docblock_at_position(src, pos)
    } else {
        None
    }
}

/// Case-insensitive docblock extraction: find /** ... */ before a pattern.
fn extract_docblock_case_insensitive<'a>(src: &'a str, pattern: &str) -> Option<&'a str> {
    let src_lower = src.to_lowercase();
    if let Some(pos) = src_lower.find(pattern) {
        extract_docblock_at_position(src, pos)
    } else {
        None
    }
}

/// Convert `mir_types::atomic::FnParam` (from TClosure) to `mir_codebase::storage::FnParam`
/// so they can be passed to `check_args`.
fn type_param_to_storage_param(p: &TypeFnParam) -> FnParam {
    FnParam {
        name: p.name,
        ty: p.ty.as_ref().map(|t| Arc::new(t.to_union())),
        has_default: p.default.is_some(),
        is_variadic: p.is_variadic,
        is_byref: p.is_byref,
        is_optional: p.is_optional,
    }
}

/// Try to extract a callable name and full typed params from a callee type union.
/// Returns `Some((name, params))` for:
/// - `TClosure` — name is `"{closure}"`, params from the closure's param list
/// - `TNamedObject` with `__invoke` method — name is `"Fqcn::__invoke"`, params from DB
///
/// Returns `None` if the union contains a bare `TCallable { params: None }` (unknown arity),
/// same guard as `extract_callable_params`.
fn typed_params_from_callee(
    union: &Type,
    ea: &ExpressionAnalyzer<'_>,
) -> Option<(String, Vec<FnParam>)> {
    // Bare callable with unknown arity — we cannot determine params statically.
    if union
        .types
        .iter()
        .any(|a| matches!(a, Atomic::TCallable { params: None, .. }))
    {
        return None;
    }

    for atomic in &union.types {
        match atomic {
            Atomic::TClosure { params, .. } => {
                let storage_params = params.iter().map(type_param_to_storage_param).collect();
                return Some(("{closure}".to_string(), storage_params));
            }
            Atomic::TNamedObject { fqcn, .. } => {
                if let Some((_, storage)) = crate::db::find_method_respecting_precedence(
                    ea.db,
                    crate::db::Fqcn::from_str(ea.db, fqcn.as_ref()),
                    "__invoke",
                ) {
                    let fn_name = format!("{}::__invoke", fqcn);
                    return Some((fn_name, storage.params.to_vec()));
                }
            }
            _ => {}
        }
    }
    None
}

/// Extract docblock before a given byte position in the source.
fn extract_docblock_at_position(src: &str, pos: usize) -> Option<&str> {
    // Look back for /** from the position.
    if let Some(doc_start_pos) = src[..pos].rfind("/**") {
        if let Some(doc_end_pos) = src[doc_start_pos..].find("*/") {
            let end_abs = doc_start_pos + doc_end_pos;
            let docblock_raw = &src[doc_start_pos + 3..end_abs];
            return Some(docblock_raw);
        }
    }
    None
}