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
use super::helpers::{
    apply_doc_param_types, ast_params_to_fn_params_resolved, resolve_named_objects_in_union,
};
use super::ExpressionAnalyzer;
use crate::flow_state::FlowState;
use crate::stmt::{mir_check_matches, return_type_is_invalid, widen_for_check};
use crate::symbol::ReferenceKind;
use mir_issues::{IssueKind, Severity};
use mir_types::{Atomic, Name, Type};
use php_ast::owned::{ArrowFunctionExpr, ClosureExpr, ExprKind, Param};
use php_ast::Span;
use std::sync::Arc;

fn param_name_span(source: &str, p: &Param) -> Span {
    let Some(raw) = p.name.as_deref() else {
        return p.span;
    };
    let bare = raw.trim_start_matches('$');
    let range_start = p.span.start as usize;
    let range_end = (p.span.end as usize).min(source.len());
    let slice = &source[range_start..range_end];
    let needle = format!("${bare}");
    if let Some(rel) = slice.find(needle.as_str()) {
        let start = p.span.start + rel as u32;
        Span {
            start,
            end: start + needle.len() as u32,
        }
    } else {
        p.span
    }
}

/// Carry a `$this->prop` narrowing proven before a closure/arrow function
/// literal into the closure's own scope, but only for `readonly` properties.
/// An ordinary mutable property could still change between the guard and
/// whenever the closure actually runs, so resetting it is correct; a
/// `readonly` property can never change after construction, so the guard's
/// proof stays valid no matter when the closure is invoked.
fn propagate_readonly_prop_refinements(
    db: &dyn crate::db::MirDatabase,
    ctx: &FlowState,
    inner_ctx: &mut FlowState,
) {
    let Some(self_fqcn) = ctx.self_fqcn.clone() else {
        return;
    };
    let this_sym = mir_types::Name::from("this");
    let here = crate::db::Fqcn::from_str(db, self_fqcn.as_ref());
    for ((obj_var, prop), ty) in ctx.prop_refined.iter() {
        if *obj_var != this_sym {
            continue;
        }
        if let Some((_, p_def)) = crate::db::find_property_in_chain(db, here, prop.as_str()) {
            if p_def.is_readonly {
                inner_ctx.set_prop_refined("this", prop.as_str(), (**ty).clone());
            }
        }
    }
}

impl<'a> ExpressionAnalyzer<'a> {
    /// Local type aliases (`@psalm-type`/`@phpstan-type`) declared in the
    /// enclosing class-like's (or, for a closure declared inside a free
    /// function, that function's own) docblock never expanded inside a
    /// nested closure/arrow-function's OWN `@param`/`@return` docblock —
    /// every usage site showed the literal unresolved alias name instead of
    /// its expansion. Mirrors `stmt/mod.rs`'s `extract_var_annotation_from`,
    /// which already does this for a bare `@var` annotation; not cached the
    /// way that helper is, since a closure body is analyzed once per
    /// enclosing function, not once per statement.
    fn expand_local_type_aliases_in_doc(
        &self,
        doc: &mut crate::parser::ParsedDocblock,
        ctx: &FlowState,
    ) {
        let aliases = if let Some(fqcn) = ctx.self_fqcn.as_deref() {
            crate::db::find_class_like(self.db, crate::db::Fqcn::from_str(self.db, fqcn))
                .map(|cl| cl.type_aliases().clone())
        } else if let Some(fqn) = ctx.current_function_fqn.as_deref() {
            crate::db::find_function(self.db, crate::db::Fqcn::from_str(self.db, fqn))
                .map(|f| f.type_aliases.clone())
        } else {
            None
        };
        let Some(aliases) = aliases else { return };
        if aliases.is_empty() {
            return;
        }
        for (_, ty) in doc.params.iter_mut() {
            *ty = crate::collector::expand_aliases_only(ty.clone(), &aliases);
        }
        if let Some(rt) = doc.return_type.take() {
            doc.return_type = Some(crate::collector::expand_aliases_only(rt, &aliases));
        }
    }

    pub(super) fn analyze_closure(
        &mut self,
        c: &ClosureExpr,
        expr_span: php_ast::Span,
        ctx: &mut FlowState,
    ) -> Type {
        for param in c.params.iter() {
            if let Some(hint) = &param.type_hint {
                self.check_type_hint(hint);
            }
        }
        if let Some(hint) = &c.return_type {
            self.check_type_hint(hint);
        }

        let mut leading_doc = crate::parser::find_preceding_docblock(self.source, expr_span.start)
            .map(|doc| crate::parser::DocblockParser::parse(&doc));
        if let Some(doc) = &mut leading_doc {
            self.expand_local_type_aliases_in_doc(doc, ctx);
        }

        let mut params = ast_params_to_fn_params_resolved(
            &c.params,
            ctx.self_fqcn.as_deref(),
            self.db,
            &self.file,
        );
        if let Some(doc) = &leading_doc {
            apply_doc_param_types(&mut params, &c.params, &doc.params, self.db, &self.file);
        }
        let return_ty_hint = c
            .return_type
            .as_ref()
            .map(|h| crate::parser::type_from_hint_owned(h, ctx.self_fqcn.as_deref()))
            .map(|u| resolve_named_objects_in_union(u, self.db, &self.file))
            .or_else(|| {
                // Fall back to `@return` docblock preceding the `function` keyword.
                leading_doc
                    .as_ref()
                    .and_then(|doc| doc.return_type.clone())
                    .map(|ty| resolve_named_objects_in_union(ty, self.db, &self.file))
            });

        if return_ty_hint.is_none() && self.mode == crate::expr::AnalysisMode::Full {
            self.emit(
                mir_issues::IssueKind::MissingClosureReturnType,
                mir_issues::Severity::Info,
                expr_span,
            );
        }

        let mut closure_ctx = crate::flow_state::FlowState::for_function(
            &params,
            return_ty_hint.clone(),
            Arc::from([]),
            ctx.self_fqcn.clone(),
            ctx.parent_fqcn.clone(),
            ctx.static_fqcn.clone(),
            ctx.strict_types,
            c.is_static,
        );
        // A non-static closure declared outside any class body doesn't get `$this`
        // injected by `for_function` (no `self_fqcn`), but it's still valid PHP for
        // it to reference `$this` if the closure is later rebound to an object via
        // `Closure::bind()`/`bindTo()`/`call()` — a common macro/PHPUnit idiom.
        // Model that by seeding `$this` as an object of unknown type rather than
        // leaving it undefined, which would otherwise misfire `InvalidScope`.
        if ctx.self_fqcn.is_none() && !c.is_static {
            let this_sym = Name::from("this");
            Arc::make_mut(&mut closure_ctx.vars).insert(
                this_sym,
                mir_codebase::definitions::wrap_var_type(Type::single(Atomic::TObject)),
            );
            Arc::make_mut(&mut closure_ctx.assigned_vars).insert(this_sym);
        }
        // Closures see the enclosing function/method's template params (e.g. a
        // captured `@template T`-typed variable assigned to a typed property
        // inside the closure body) — without this, `type_refs_any_template`
        // checks against an empty set and treats the value as a concrete type,
        // producing spurious InvalidPropertyAssignment/instanceof narrowing bugs.
        closure_ctx.template_param_names = Arc::clone(&ctx.template_param_names);
        // A closure invoked from inside a @pure/@psalm-immutable/
        // @psalm-external-mutation-free body can still smuggle out an
        // observable side effect, so it must inherit that purity context
        // rather than starting fresh — an immediately-invoked closure that
        // mutates a captured object would otherwise go completely unchecked.
        closure_ctx.is_in_pure_fn = ctx.is_in_pure_fn;
        closure_ctx.is_in_immutable_method = ctx.is_in_immutable_method;
        closure_ctx.is_in_external_mutation_free_method = ctx.is_in_external_mutation_free_method;
        propagate_readonly_prop_refinements(self.db, ctx, &mut closure_ctx);
        for p in c.params.iter() {
            if let Some(raw) = p.name.as_deref() {
                let trimmed = raw.trim_start_matches('$');
                let ty = closure_ctx.get_var(trimmed);
                self.record_symbol(
                    param_name_span(self.source, p),
                    ReferenceKind::Variable(Arc::from(trimmed)),
                    ty,
                );
            }
        }
        for use_var in c.use_vars.iter() {
            let name = use_var.name.trim_start_matches('$');
            // A by-ref capture (`use (&$f)`) binds by reference and auto-creates
            // the variable in the parent scope if it does not yet exist, so it is
            // never "undefined" — this is what makes a self-referential closure
            // `$f = function () use (&$f) {...}` valid. Define it in both scopes
            // and skip the undefined check.
            if use_var.by_ref {
                if !ctx.var_is_defined(name) {
                    // Type an auto-created by-ref capture as a callable of
                    // unknown arity: the dominant case is the self-referential
                    // closure `$f = function () use (&$f)`, where `$f` is the
                    // closure being assigned. This avoids spurious
                    // MixedFunctionCall / arity errors when the body calls it.
                    ctx.set_var(
                        name,
                        Type::single(mir_types::Atomic::TCallable {
                            params: None,
                            return_type: None,
                        }),
                    );
                }
            } else if !ctx.var_is_defined(name) {
                if ctx.var_possibly_defined(name) {
                    self.emit(
                        mir_issues::IssueKind::PossiblyUndefinedVariable {
                            name: name.to_string(),
                        },
                        mir_issues::Severity::Warning,
                        use_var.span,
                    );
                } else {
                    self.emit(
                        mir_issues::IssueKind::UndefinedVariable {
                            name: name.to_string(),
                        },
                        mir_issues::Severity::Error,
                        use_var.span,
                    );
                }
            }
            closure_ctx.set_var(name, ctx.get_var(name));
            if ctx.is_tainted(name) {
                closure_ctx.taint_var(name);
            }
            // Mark the captured variable as read in the parent context, and
            // consume its pending write so it isn't reported as a dead write.
            ctx.read_vars.insert(mir_types::Name::from(name));
            ctx.mark_consumed(name);
        }

        // A capture (by value OR by reference) of a variable that is itself a
        // parameter of the enclosing function is still externally owned by
        // the caller, so calling a mutating method on it inside the closure
        // body is an externally observable side effect — exactly like
        // calling one on a real parameter. Extend `param_names` so the
        // existing pure/immutable/external-mutation-free method-call checks
        // (which key off that set) also catch such captures. A capture of a
        // locally-created object stays out of this set, matching the "local
        // objects are exempt" rule the same checks already apply to real
        // params. Previously only a by-value capture was covered here — a
        // by-ref capture (`use (&$c)`) is the SAME external variable, not a
        // copy, so it's just as reachable, yet was silently excluded.
        if closure_ctx.is_in_pure_fn
            || closure_ctx.is_in_immutable_method
            || closure_ctx.is_in_external_mutation_free_method
        {
            let mut extended_param_names = (*closure_ctx.param_names).clone();
            // A by-ref capture of the enclosing function's OWN by-ref
            // parameter (`use (&$x)` where `&$x` is itself a by-ref
            // parameter) is the SAME reference, not a copy — a write
            // through it inside the closure body is exactly as
            // externally observable as writing `$x` directly in the
            // enclosing scope, but `check_var_write_purity`/
            // `assign_to_target`'s `Variable` arm (both keyed on
            // `byref_param_names`) could never see it, since that set was
            // never propagated into a closure's own `FlowState` at all.
            let mut extended_byref_param_names = (*closure_ctx.byref_param_names).clone();
            for use_var in c.use_vars.iter() {
                let name = use_var.name.trim_start_matches('$');
                if ctx.param_names.contains(&Name::from(name)) {
                    extended_param_names.insert(Name::from(name));
                }
                if use_var.by_ref && ctx.byref_param_names.contains(&Name::from(name)) {
                    extended_byref_param_names.insert(Name::from(name));
                }
            }
            closure_ctx.param_names = Arc::new(extended_param_names);
            closure_ctx.byref_param_names = Arc::new(extended_byref_param_names);
        }

        let mut sa = crate::stmt::StatementsAnalyzer::new(
            self.db,
            self.file.clone(),
            self.source,
            self.source_map,
            self.issues,
            self.symbols,
            self.php_version,
            self.mode,
        );

        sa.collect_symbols = self.collect_symbols;
        sa.analyze_stmts(&c.body.stmts, &mut closure_ctx);
        let inferred_return = crate::body_analysis::merge_return_types(&sa.return_types);
        // A closure containing `yield` always returns a Generator, regardless
        // of what (if anything) it `return`s — same inference as a top-level
        // function/method (see `build_generator_return_type`), which this
        // closure-local `sa` otherwise silently dropped by only reading
        // `return_types`.
        let inferred_return = if sa.yielded_types.is_empty() {
            inferred_return
        } else {
            crate::body_analysis::build_generator_return_type(&sa.yielded_types, inferred_return)
        };

        // If the closure reads an outer-scope variable without capturing it via `use`,
        // mark that variable as read in the outer context to suppress false UnusedParam.
        for name in &closure_ctx.read_vars {
            if ctx.var_is_defined(name) || ctx.var_possibly_defined(name) {
                ctx.read_vars.insert(*name);
                ctx.mark_consumed(name.as_str());
            }
        }

        let return_ty = return_ty_hint.unwrap_or(inferred_return);
        let closure_params: Box<[mir_types::atomic::FnParam]> = params
            .iter()
            .map(|p| mir_types::atomic::FnParam {
                name: Name::from(p.name.as_ref()),
                ty: p
                    .ty
                    .as_ref()
                    .map(|arc| mir_types::SimpleType::from_union((**arc).clone())),
                out_ty: None,
                default: if p.has_default {
                    Some(mir_types::SimpleType::from_union(Type::mixed()))
                } else {
                    None
                },
                is_variadic: p.is_variadic,
                is_byref: p.is_byref,
                is_optional: p.is_optional,
            })
            .collect();

        Type::single(Atomic::TClosure {
            data: Box::new(mir_types::atomic::ClosureData {
                params: closure_params,
                return_type: return_ty,
                this_type: ctx.self_fqcn.clone().map(|f| {
                    Type::single(Atomic::TNamedObject {
                        fqcn: Name::from(f.as_ref()),
                        type_params: mir_types::union::empty_type_params(),
                    })
                }),
            }),
        })
    }

    pub(super) fn analyze_arrow_function(
        &mut self,
        af: &ArrowFunctionExpr,
        expr_span: php_ast::Span,
        ctx: &mut FlowState,
    ) -> Type {
        for param in af.params.iter() {
            if let Some(hint) = &param.type_hint {
                self.check_type_hint(hint);
            }
        }
        if let Some(hint) = &af.return_type {
            self.check_type_hint(hint);
        }

        let mut leading_doc = crate::parser::find_preceding_docblock(self.source, expr_span.start)
            .map(|doc| crate::parser::DocblockParser::parse(&doc));
        if let Some(doc) = &mut leading_doc {
            self.expand_local_type_aliases_in_doc(doc, ctx);
        }

        let mut params = ast_params_to_fn_params_resolved(
            &af.params,
            ctx.self_fqcn.as_deref(),
            self.db,
            &self.file,
        );
        if let Some(doc) = &leading_doc {
            apply_doc_param_types(&mut params, &af.params, &doc.params, self.db, &self.file);
        }
        let return_ty_hint = af
            .return_type
            .as_ref()
            .map(|h| crate::parser::type_from_hint_owned(h, ctx.self_fqcn.as_deref()))
            .map(|u| resolve_named_objects_in_union(u, self.db, &self.file))
            .or_else(|| {
                // Fall back to `@return` docblock preceding the `fn` keyword — mirrors
                // the same fallback in `analyze_closure` for `function(...) {...}`.
                leading_doc
                    .as_ref()
                    .and_then(|doc| doc.return_type.clone())
                    .map(|ty| resolve_named_objects_in_union(ty, self.db, &self.file))
            });

        let mut arrow_ctx = crate::flow_state::FlowState::for_function(
            &params,
            return_ty_hint.clone(),
            Arc::from([]),
            ctx.self_fqcn.clone(),
            ctx.parent_fqcn.clone(),
            ctx.static_fqcn.clone(),
            ctx.strict_types,
            af.is_static,
        );
        // See analyze_closure: propagate the enclosing scope's template params
        // so captured template-typed variables aren't misjudged as concrete.
        arrow_ctx.template_param_names = Arc::clone(&ctx.template_param_names);
        // See analyze_closure: an arrow function invoked from inside a
        // @pure/@psalm-immutable/@psalm-external-mutation-free body can still
        // smuggle out a side effect through an implicitly-captured variable —
        // `fn() => impure_fn()` or a tainted value flowing into a sink must be
        // checked the same way the equivalent `function(){...}` closure is.
        arrow_ctx.is_in_pure_fn = ctx.is_in_pure_fn;
        arrow_ctx.is_in_immutable_method = ctx.is_in_immutable_method;
        arrow_ctx.is_in_external_mutation_free_method = ctx.is_in_external_mutation_free_method;
        propagate_readonly_prop_refinements(self.db, ctx, &mut arrow_ctx);
        // Arrow functions auto-capture every outer variable by value (no
        // explicit `use()` list), so taint on any of them must carry over too.
        arrow_ctx.tainted_vars = ctx.tainted_vars.clone();
        let this_sym = mir_types::Name::from("this");
        for (name, ty) in ctx.vars.iter() {
            // Static arrow functions don't capture $this from the outer scope.
            if af.is_static && *name == this_sym {
                continue;
            }
            if !arrow_ctx.vars.contains_key(name) {
                std::sync::Arc::make_mut(&mut arrow_ctx.vars).insert(*name, ty.clone());
                std::sync::Arc::make_mut(&mut arrow_ctx.assigned_vars).insert(*name);
            }
        }
        // See analyze_closure: an arrow function outside any class also produces
        // a rebindable Closure, so `$this` may be validly late-bound even though
        // there's no enclosing `self_fqcn` to capture it from here.
        if !af.is_static && !arrow_ctx.vars.contains_key(&this_sym) {
            std::sync::Arc::make_mut(&mut arrow_ctx.vars).insert(
                this_sym,
                mir_codebase::definitions::wrap_var_type(Type::single(Atomic::TObject)),
            );
            std::sync::Arc::make_mut(&mut arrow_ctx.assigned_vars).insert(this_sym);
        }
        // See analyze_closure: a captured (by-value) outer parameter is still
        // externally owned by the caller, so mutating it via method call
        // inside the arrow body is an observable side effect just like a real
        // parameter — extend param_names so the existing pure/immutable/
        // external-mutation-free checks (which key off that set) catch it.
        // Every outer var is auto-captured, so union the whole set rather
        // than filtering by an explicit use() list.
        if arrow_ctx.is_in_pure_fn
            || arrow_ctx.is_in_immutable_method
            || arrow_ctx.is_in_external_mutation_free_method
        {
            let mut extended_param_names = (*arrow_ctx.param_names).clone();
            extended_param_names.extend(ctx.param_names.iter().copied());
            arrow_ctx.param_names = Arc::new(extended_param_names);
        }

        for p in af.params.iter() {
            if let Some(raw) = p.name.as_deref() {
                let trimmed = raw.trim_start_matches('$');
                // Use arrow_ctx.get_var to get the resolved type (params take priority
                // over outer-scope vars of the same name since they were inserted first).
                let ty = arrow_ctx.get_var(trimmed);
                self.record_symbol(
                    param_name_span(self.source, p),
                    ReferenceKind::Variable(Arc::from(trimmed)),
                    ty,
                );
            }
        }

        // Check @mir-check directives in the arrow function body.
        // If the body is parenthesized, look for docblocks before the inner expression.
        let check_target = match &af.body.kind {
            ExprKind::Parenthesized(inner) => inner.as_ref(),
            _ => &af.body,
        };
        if let Some(doc) =
            crate::parser::find_preceding_docblock(self.source, check_target.span.start)
        {
            let checks = crate::parser::DocblockParser::parse(&doc).mir_checks;
            for (expr_text, expected_str) in checks {
                let expected = crate::parser::docblock::parse_type_string(&expected_str);
                let actual_raw = self.eval_check_expr(&expr_text, &arrow_ctx);
                if !mir_check_matches(&expected, &actual_raw) {
                    self.emit(
                        IssueKind::TypeCheckMismatch {
                            var: expr_text,
                            expected: expected.to_string(),
                            actual: widen_for_check(actual_raw).to_string(),
                        },
                        Severity::Error,
                        check_target.span,
                    );
                }
            }
        }

        let inferred_return = self.analyze(&af.body, &mut arrow_ctx);
        // Arrow functions capture the whole outer scope by value: any variable
        // the body reads is a read (and consumed write) in the outer context.
        for name in &arrow_ctx.read_vars {
            ctx.read_vars.insert(*name);
            ctx.mark_consumed(name.as_str());
        }

        // The `=> expr` body is exactly one implicit `return expr;` — check it
        // against the declared return type the same way analyze_return_stmt does
        // for a regular closure/function body.
        if let Some(declared) = &return_ty_hint {
            let has_invalid = !declared.contains(|t| matches!(t, Atomic::TConditional { .. }))
                && ((declared.is_void()
                    && !inferred_return.is_void()
                    && !inferred_return.is_mixed())
                    || return_type_is_invalid(
                        &inferred_return,
                        declared,
                        ctx.strict_types,
                        self.db,
                        &self.file,
                    ));
            let is_mixed_return = !has_invalid
                && !declared.is_void()
                && !declared.is_mixed()
                && inferred_return.is_mixed()
                && !declared.contains(|t| matches!(t, Atomic::TConditional { .. }));
            if is_mixed_return {
                let kind = IssueKind::MixedReturnStatement {
                    declared: format!("{declared}"),
                };
                let severity = kind.default_severity();
                self.emit(kind, severity, check_target.span);
            } else if has_invalid {
                let kind = IssueKind::InvalidReturnType {
                    expected: format!("{declared}"),
                    actual: format!("{inferred_return}"),
                };
                let severity = kind.default_severity();
                self.emit(kind, severity, check_target.span);
            } else if !declared.is_void()
                && !declared.is_mixed()
                && !declared.contains(|t| matches!(t, Atomic::TNull))
                && !declared.contains(|t| matches!(t, Atomic::TConditional { .. }))
                && !declared.contains(|t| matches!(t, Atomic::TTemplateParam { .. }))
                && inferred_return.contains(|t| matches!(t, Atomic::TNull))
                && !inferred_return.remove_null().is_empty()
                && !return_type_is_invalid(
                    &inferred_return.remove_null(),
                    declared,
                    ctx.strict_types,
                    self.db,
                    &self.file,
                )
            {
                let kind = IssueKind::NullableReturnStatement {
                    expected: format!("{declared}"),
                    actual: format!("{inferred_return}"),
                };
                let severity = kind.default_severity();
                self.emit(kind, severity, check_target.span);
            }
        }

        let return_ty = return_ty_hint.unwrap_or(inferred_return);
        let closure_params: Box<[mir_types::atomic::FnParam]> = params
            .iter()
            .map(|p| mir_types::atomic::FnParam {
                name: Name::from(p.name.as_ref()),
                ty: p
                    .ty
                    .as_ref()
                    .map(|arc| mir_types::SimpleType::from_union((**arc).clone())),
                out_ty: None,
                default: if p.has_default {
                    Some(mir_types::SimpleType::from_union(Type::mixed()))
                } else {
                    None
                },
                is_variadic: p.is_variadic,
                is_byref: p.is_byref,
                is_optional: p.is_optional,
            })
            .collect();

        Type::single(Atomic::TClosure {
            data: Box::new(mir_types::atomic::ClosureData {
                params: closure_params,
                return_type: return_ty,
                this_type: if af.is_static {
                    None
                } else {
                    ctx.self_fqcn.clone().map(|f| {
                        Type::single(Atomic::TNamedObject {
                            fqcn: Name::from(f.as_ref()),
                            type_params: mir_types::union::empty_type_params(),
                        })
                    })
                },
            }),
        })
    }
}