mago-analyzer 1.18.1

A PHP static analyzer that can detect type errors in PHP code, and provide suggestions for fixing them.
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
use std::cell::RefCell;
use std::collections::hash_map::Entry;
use std::rc::Rc;

use mago_atom::Atom;
use mago_atom::AtomMap;
use mago_atom::AtomSet;
use mago_atom::atom;

use mago_codex::ttype;
use mago_codex::ttype::atomic::TAtomic;
use mago_codex::ttype::atomic::object::TObject;
use mago_codex::ttype::atomic::object::named::TNamedObject;
use mago_codex::ttype::combiner::CombinerOptions;
use mago_codex::ttype::union::TUnion;
use mago_reporting::Annotation;
use mago_reporting::Issue;
use mago_span::HasSpan;
use mago_span::Span;
use mago_syntax::ast::Hint;
use mago_syntax::ast::Try;

use crate::analyzable::Analyzable;
use crate::artifacts::AnalysisArtifacts;
use crate::code::IssueCode;
use crate::context::Context;
use crate::context::block::BlockContext;
use crate::context::scope::control_action::ControlAction;
use crate::context::scope::finally_scope::FinallyScope;
use crate::context::utils::inherit_branch_context_properties;
use crate::error::AnalysisError;
use crate::statement::analyze_statements;

impl<'ast, 'arena> Analyzable<'ast, 'arena> for Try<'arena> {
    fn analyze<'ctx>(
        &'ast self,
        context: &mut Context<'ctx, 'arena>,
        block_context: &mut BlockContext<'ctx>,
        artifacts: &mut AnalysisArtifacts,
    ) -> Result<(), AnalysisError> {
        let mut catch_actions = vec![];
        let mut all_catches_leave = !self.catch_clauses.is_empty();

        for catch_clause in &self.catch_clauses {
            let actions = ControlAction::from_statements(
                catch_clause.block.statements.iter().collect::<Vec<_>>(),
                vec![],
                Some(artifacts),
                true,
            );

            all_catches_leave = all_catches_leave && !actions.contains(ControlAction::None);
            catch_actions.push(actions);
        }

        let existing_thrown_exceptions = std::mem::take(&mut block_context.possibly_thrown_exceptions);
        let old_block_context_locals = block_context.locals.clone();
        let mut try_block_context = block_context.clone();

        if self.finally_clause.is_some() {
            try_block_context.finally_scope = Some(Rc::new(RefCell::new(FinallyScope::new())));
        }

        let assigned_variable_ids = std::mem::take(&mut block_context.assigned_variable_ids);

        let was_inside_try = block_context.flags.inside_try();
        block_context.flags.set_inside_try(true);
        analyze_statements(self.block.statements.as_slice(), context, block_context, artifacts)?;
        block_context.flags.set_inside_try(was_inside_try);
        if !self.catch_clauses.is_empty() {
            block_context.flags.set_has_returned(false);
        }

        let try_block_control_actions = ControlAction::from_statements(
            self.block.statements.iter().collect::<Vec<_>>(),
            vec![],
            Some(artifacts),
            true,
        );

        let newly_assigned_variable_ids = std::mem::take(&mut block_context.assigned_variable_ids);
        block_context.assigned_variable_ids.extend(assigned_variable_ids);
        block_context.assigned_variable_ids.extend(newly_assigned_variable_ids.iter().map(|(v, u)| (*v, *u)));

        for (variable_id, variable_type) in std::mem::take(&mut block_context.locals) {
            match try_block_context.locals.entry(variable_id) {
                Entry::Occupied(mut occupied_entry) => {
                    let combined_type = ttype::combine_union_types(
                        occupied_entry.get(),
                        variable_type.as_ref(),
                        context.codebase,
                        CombinerOptions::default(),
                    );

                    occupied_entry.insert(Rc::new(combined_type));

                    block_context.locals.insert(variable_id, variable_type);
                }
                Entry::Vacant(vacant_entry) => {
                    let mut possibly_undefined_type = (*variable_type).clone();
                    possibly_undefined_type.set_possibly_undefined(true, Some(true));

                    vacant_entry.insert(variable_type);
                    block_context.locals.insert(variable_id, Rc::new(possibly_undefined_type));
                }
            }
        }

        if let Some(try_scope) = &try_block_context.finally_scope {
            let mut mutable_try_scope = try_scope.borrow_mut();

            for (variable_id, variable_type) in &block_context.locals {
                if let Some(existing_type) = mutable_try_scope.locals.get_mut(variable_id) {
                    let combined_type = ttype::combine_union_types(
                        existing_type,
                        variable_type.as_ref(),
                        context.codebase,
                        CombinerOptions::default(),
                    );

                    *existing_type = Rc::new(combined_type);
                } else {
                    mutable_try_scope.locals.insert(*variable_id, variable_type.clone());
                }
            }
        }

        try_block_context.possibly_thrown_exceptions = block_context.possibly_thrown_exceptions.clone();
        try_block_context.variables_possibly_in_scope = block_context.variables_possibly_in_scope.clone();

        let try_leaves_loop = artifacts
            .loop_scope
            .as_ref()
            .is_some_and(|loop_scope| !loop_scope.final_actions.contains(ControlAction::None));

        if all_catches_leave {
            for assigned_variable_id in newly_assigned_variable_ids.keys() {
                try_block_context.remove_variable_from_conflicting_clauses(context, *assigned_variable_id, None);
            }
        } else {
            for assigned_variable_id in newly_assigned_variable_ids.keys() {
                block_context.remove_variable_from_conflicting_clauses(context, *assigned_variable_id, None);
            }
        }

        let mut original_block_context = try_block_context.clone();
        let mut definitely_newly_assigned_var_ids = newly_assigned_variable_ids;

        for (i, catch_clause) in self.catch_clauses.iter().enumerate() {
            let mut catch_block_context = original_block_context.clone();
            catch_block_context.flags.set_has_returned(false);
            for (variable_id, variable_type) in &mut catch_block_context.locals {
                if let Some(old_type) = old_block_context_locals.get(variable_id) {
                    *variable_type = Rc::new(ttype::combine_union_types(
                        variable_type.as_ref(),
                        old_type,
                        context.codebase,
                        CombinerOptions::default(),
                    ));
                } else {
                    let mut possibly_undefined_type = (**variable_type).clone();
                    possibly_undefined_type.set_possibly_undefined(variable_type.possibly_undefined(), Some(true));

                    *variable_type = Rc::new(possibly_undefined_type);
                }
            }

            let caught_classes = get_caught_classes(context, &catch_clause.hint);

            for caught in &caught_classes {
                if context.codebase.is_instance_of(caught, &atom("Error")) {
                    context.collector.report_with_code(
                        IssueCode::AvoidCatchingError,
                        Issue::warning("Avoid catching 'Error' class instances.")
                            .with_annotation(Annotation::primary(catch_clause.hint.span()).with_message(
                                "This throwable is an instance of the `Error` class or one of its sub-classes.",
                            ))
                            .with_annotation(
                                Annotation::secondary(catch_clause.block.span())
                                    .with_message("This catch clause intercepts a critical error."),
                            )
                            .with_note("Catching these errors hides issues that should crash your app.")
                            .with_help("Remove or adjust this catch clause so errors propagate naturally."),
                    );
                }
            }

            let possibly_thrown_exceptions = std::mem::take(&mut catch_block_context.possibly_thrown_exceptions);
            for caught_class in &caught_classes {
                for possibly_thrown_exception in possibly_thrown_exceptions.keys() {
                    if possibly_thrown_exception.eq_ignore_ascii_case(caught_class)
                        || context.codebase.is_instance_of(possibly_thrown_exception, caught_class)
                    {
                        original_block_context.possibly_thrown_exceptions.remove(possibly_thrown_exception);
                        block_context.possibly_thrown_exceptions.remove(possibly_thrown_exception);
                        catch_block_context.possibly_thrown_exceptions.remove(possibly_thrown_exception);
                    }
                }
            }

            catch_block_context.clauses = vec![];
            if let Some(catch_variable) = catch_clause.variable.as_ref() {
                let exception_type = TUnion::new(
                    caught_classes
                        .iter()
                        .map(|caught_class| TAtomic::Object(TObject::Named(TNamedObject::new(*caught_class))))
                        .collect(),
                );

                let catch_var_name = Atom::from(catch_variable.name);
                catch_block_context.locals.insert(catch_var_name, Rc::new(exception_type));
                catch_block_context.remove_variable_from_conflicting_clauses(context, catch_var_name, None);
                catch_block_context.variables_possibly_in_scope.insert(catch_var_name);
            }

            let old_catch_assigned_variable_ids = std::mem::take(&mut catch_block_context.assigned_variable_ids);

            analyze_statements(catch_clause.block.statements.as_slice(), context, &mut catch_block_context, artifacts)?;

            // recalculate in case there's a no-return clause
            if let Some(actions) = catch_actions.get_mut(i) {
                *actions = ControlAction::from_statements(
                    catch_clause.block.statements.iter().collect::<Vec<_>>(),
                    vec![],
                    Some(artifacts),
                    true,
                );
            }

            all_catches_leave = catch_actions.iter().all(|actions| !actions.contains(ControlAction::None));

            let new_catch_assigned_variables_ids = catch_block_context.assigned_variable_ids.clone();
            catch_block_context.assigned_variable_ids.extend(old_catch_assigned_variable_ids);

            inherit_branch_context_properties(context, block_context, &catch_block_context);

            let catch_doesnt_leave_parent_scope = catch_actions[i].contains(ControlAction::None);

            if catch_doesnt_leave_parent_scope {
                definitely_newly_assigned_var_ids = new_catch_assigned_variables_ids
                    .iter()
                    .filter(|(key, _)| definitely_newly_assigned_var_ids.contains_key(*key))
                    .map(|(key, value)| (*key, *value))
                    .collect();

                let end_action_only =
                    try_block_control_actions.len() == 1 && try_block_control_actions.contains(ControlAction::End);

                for (variable_id, variable_type) in &catch_block_context.locals {
                    if end_action_only {
                        block_context.locals.insert(*variable_id, variable_type.clone());
                    } else if let Some(existing_type) = block_context.locals.get(variable_id) {
                        block_context.locals.insert(
                            *variable_id,
                            Rc::new(ttype::combine_union_types(
                                existing_type.as_ref(),
                                variable_type.as_ref(),
                                context.codebase,
                                CombinerOptions::default(),
                            )),
                        );
                    }
                }

                block_context.variables_possibly_in_scope.extend(catch_block_context.variables_possibly_in_scope);
            } else if self.finally_clause.is_some() {
                block_context.variables_possibly_in_scope.extend(catch_block_context.variables_possibly_in_scope);
            }

            if let Some(mut finally_scope) = try_block_context.finally_scope.as_ref().map(|s| s.borrow_mut()) {
                for (variable_id, variable_type) in &catch_block_context.locals {
                    let resulting_type = if let Some(finally_variable_type) = finally_scope.locals.get(variable_id) {
                        ttype::combine_union_types(
                            finally_variable_type.as_ref(),
                            variable_type.as_ref(),
                            context.codebase,
                            CombinerOptions::default(),
                        )
                    } else {
                        let mut finally_variable_type = (**variable_type).clone();
                        finally_variable_type.set_possibly_undefined(true, Some(true));

                        finally_variable_type
                    };

                    finally_scope.locals.insert(*variable_id, Rc::new(resulting_type));
                }
            }
        }

        if !try_leaves_loop && let Some(loop_scope) = artifacts.loop_scope.as_mut() {
            loop_scope.final_actions.insert(ControlAction::None);
        }

        let mut finally_has_returned = false;
        if let Some(finally_clause) = self.finally_clause.as_ref() {
            let finally_scope = unsafe {
                try_block_context
                    .finally_scope
                    .take()
                    .map(|scope| scope.as_ref().clone())
                    .map(std::cell::RefCell::into_inner)
                    .unwrap_unchecked()
            };

            let mut finally_block_context = block_context.clone();
            finally_block_context.assigned_variable_ids = AtomMap::default();
            finally_block_context.possibly_assigned_variable_ids = AtomSet::default();
            finally_block_context.locals = finally_scope.locals;
            finally_block_context.flags.set_has_returned(false);

            analyze_statements(
                finally_clause.block.statements.as_slice(),
                context,
                &mut finally_block_context,
                artifacts,
            )?;

            finally_has_returned = finally_block_context.flags.has_returned();

            for (variable_id, _) in finally_block_context.assigned_variable_ids {
                let finally_variable_type = finally_block_context.locals.remove(&variable_id);
                if let Some(finally_variable_type) = finally_variable_type {
                    let resulting_type = match block_context.locals.remove(&variable_id) {
                        Some(existing_type) => {
                            let possibly_undefined = finally_variable_type.possibly_undefined_from_try()
                                && existing_type.possibly_undefined();

                            let mut combined_type = ttype::combine_union_types(
                                existing_type.as_ref(),
                                finally_variable_type.as_ref(),
                                context.codebase,
                                CombinerOptions::default(),
                            );

                            if possibly_undefined {
                                combined_type.set_possibly_undefined(false, Some(false));
                            }

                            Rc::new(combined_type)
                        }
                        None => finally_variable_type,
                    };

                    block_context.locals.insert(variable_id, resulting_type);
                }
            }
        }

        for (variable_id, _) in definitely_newly_assigned_var_ids {
            let Some(variable_type) = block_context.locals.get_mut(&variable_id) else {
                continue;
            };

            if !variable_type.possibly_undefined_from_try() {
                continue;
            }

            let mut defined_variable_type = (**variable_type).clone();
            defined_variable_type.set_possibly_undefined(false, Some(false));

            *variable_type = Rc::new(defined_variable_type);
        }

        for (possibly_thrown_exception, throw_spans) in existing_thrown_exceptions {
            block_context.possibly_thrown_exceptions.entry(possibly_thrown_exception).or_default().extend(throw_spans);
        }

        block_context.flags.set_has_returned(if finally_has_returned {
            true
        } else if !try_block_control_actions.contains(ControlAction::None) {
            self.catch_clauses.is_empty() || all_catches_leave
        } else {
            false
        });

        Ok(())
    }
}

fn get_caught_classes<'arena>(context: &mut Context<'_, 'arena>, hint: &Hint<'arena>) -> AtomSet {
    let mut caught_identifiers: AtomMap<Span> = AtomMap::default();

    fn walk<'arena>(context: &mut Context<'_, 'arena>, hint: &Hint<'arena>, caught: &mut AtomMap<Span>) {
        match hint {
            Hint::Identifier(identifier) => {
                let name = context.resolved_names.get(identifier);
                let id = atom(name);

                if let Some(&first_span) = caught.get(&id) {
                    context.collector.report_with_code(
                        IssueCode::DuplicateCaughtType,
                        Issue::error(format!(
                            "Type `{name}` is caught multiple times in the same `catch` clause.",
                        ))
                        .with_annotation(
                            Annotation::primary(hint.span())
                                .with_message("This type is a duplicate occurrence here"),
                        )
                        .with_annotation(
                            Annotation::secondary(first_span)
                                .with_message(format!("`{name}` was already specified here")),
                        )
                        .with_help("Remove the redundant type from the `catch` union. Each exception type should only be listed once."),
                    );
                } else {
                    caught.insert(id, hint.span());
                }
            }
            Hint::Union(union_hint) => {
                walk(context, union_hint.left, caught);
                walk(context, union_hint.right, caught);
            }
            _ => {
                context.collector.report_with_code(
                    IssueCode::InvalidCatchType,
                    Issue::error("Invalid type used in `catch` declaration. Only class or interface names are allowed.")
                    .with_annotation(
                        Annotation::primary(hint.span())
                            .with_message("This type is not a valid class or interface name for a `catch` block."),
                    )
                    .with_note(
                        "PHP `catch` blocks require a class or interface name to specify the type of exceptions to be caught. Primitive types (e.g., `int`, `string`), arrays, or other non-class types are not permitted here."
                    )
                    .with_help(
                        "Use a valid class or interface name (e.g., `Exception`, `MyCustomError`), or a union of them (e.g., `FooException | BarException`)."
                    ),
                );
            }
        }
    }

    walk(context, hint, &mut caught_identifiers);

    let throwable = atom("Throwable");
    let mut caught_classes = AtomSet::with_capacity_and_hasher(caught_identifiers.len(), Default::default());
    for (caught_type, caught_span) in caught_identifiers {
        if caught_type.eq_ignore_ascii_case("throwable")
            || caught_type.eq_ignore_ascii_case("exception")
            || caught_type.eq_ignore_ascii_case("error")
        {
            caught_classes.insert(caught_type);
            continue;
        }

        let Some(class_like_metadata) = context.codebase.get_class_like(&caught_type) else {
            context.collector.report_with_code(
                IssueCode::NonExistentCatchType,
                Issue::error(format!("Attempting to catch an undefined class or interface: `{caught_type}`."))
                .with_annotation(
                    Annotation::primary(caught_span)
                        .with_message(format!("Type `{caught_type}` is not defined or cannot be found")),
                )
                .with_note(
                    "Types used in `catch` blocks must be existing and autoloadable classes or interfaces."
                )
                .with_help(
                    "Check for typos in the type name. Ensure the class/interface is correctly defined, namespaced, and that your autoloader can find it."
                ),
            );

            continue;
        };

        if class_like_metadata.kind.is_enum() || class_like_metadata.kind.is_trait() {
            let kind_str = if class_like_metadata.kind.is_enum() { "an enum" } else { "a trait" };

            context.collector.report_with_code(
                IssueCode::InvalidCatchTypeNotClassOrInterface,
                Issue::error(format!(
                    "Only classes or interfaces can be caught, but `{caught_type}` is {kind_str}.",
                ))
                .with_annotation(
                    Annotation::primary(caught_span)
                        .with_message(format!("Cannot catch `{caught_type}` because it is {kind_str}")),
                )
                .with_annotation(
                    Annotation::secondary(class_like_metadata.name_span.unwrap_or(class_like_metadata.span))
                        .with_message(format!("`{caught_type}` is defined as {kind_str} here")),
                )
                .with_note("PHP `catch` blocks require a class or interface type. Enums and traits are not valid types for catching exceptions as they cannot be thrown or extend `Throwable`.")
                .with_help("Specify a class or interface that implements `Throwable` (e.g., `Exception`, `Error`, or a custom exception class)."),
            );

            continue;
        }

        let is_interface = class_like_metadata.kind.is_interface();
        let is_throwable = is_interface || context.codebase.is_instance_of(&caught_type, &throwable);
        if !is_throwable {
            context.collector.report_with_code(
                IssueCode::CatchTypeNotThrowable,
                Issue::error(format!(
                    "The type `{caught_type}` caught in a catch block must implement the `Throwable` interface.",
                ))
                .with_annotation(
                    Annotation::primary(caught_span)
                        .with_message(format!("`{caught_type}` is not an instance of `Throwable`")),
                )
                .with_annotation(
                    Annotation::secondary(class_like_metadata.name_span.unwrap_or(class_like_metadata.span))
                        .with_message(format!("`{caught_type}` defined here does not implement `Throwable`")),
                )
                .with_note("In PHP, only objects that implement the `Throwable` interface (this includes `Exception` and `Error` classes and their children) can be caught in a `catch` block.")
                .with_help(format!("Ensure that `{caught_type}` implements the `Throwable` interface, or catch a more general exception type like `Exception` or `Throwable` itself.")),
            );

            continue;
        }

        caught_classes.insert(caught_type);
    }

    if caught_classes.is_empty() {
        context.collector.report_with_code(
            IssueCode::NoValidCatchTypeFound,
            Issue::error(
                "None of the types specified in the `catch` declaration are valid catchable exceptions."
            )
            .with_annotation(
                Annotation::primary(hint.span())
                    .with_message("This type declaration does not resolve to any class/interface that can be caught."),
            )
            .with_help(
                "Ensure the type hint contains at least one valid class or interface name that implements `Throwable` (e.g., `\\Exception`, `\\MyCustomError`). If all types in the hint are invalid for catching, this `catch` block will not catch exceptions based on this type hint."
            )
            .with_note(
                "To be caught, a type must be a defined class or interface that implements the `Throwable` interface. This can occur if specified types are undefined, are enums/traits, are primitive types, or are classes/interfaces that do not implement `Throwable`."
            )
            .with_note(
                "For analysis purposes, if no valid types were found, Mago might internally default to treating this as `catch (\\Throwable $e)` for subsequent control flow analysis."
            ),
        );

        caught_classes.insert(throwable);
    }

    caught_classes
}