mir-analyzer 0.32.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
use std::sync::Arc;

use crate::db::{class_exists, resolve_name, MirDatabase};
use crate::php_version::PhpVersion;

// ---------------------------------------------------------------------------
// Stored-location → Issue Location passthrough
// ---------------------------------------------------------------------------

/// Convert a stored `mir_types::Location` reference into an `Issue` `Location`,
/// passing all fields through unchanged.  Use this for diagnostics whose stored
/// span is already tight (property, method, function declarations).
/// For class-level spans that cover the entire body, use the clamping logic in
/// `class.rs::issue_location` instead.
pub(crate) fn storage_loc_to_location(loc: Option<&mir_types::Location>) -> mir_issues::Location {
    match loc {
        Some(l) => mir_issues::Location {
            file: l.file.clone(),
            line: l.line,
            line_end: l.line_end,
            col_start: l.col_start,
            col_end: l.col_end,
        },
        None => mir_issues::Location {
            file: Arc::from("<unknown>"),
            line: 1,
            line_end: 1,
            col_start: 0,
            col_end: 1,
        },
    }
}

// ---------------------------------------------------------------------------
// Offset to char-count column conversion (1-indexed)
// ---------------------------------------------------------------------------

pub(crate) fn offset_to_line_col(
    source: &str,
    offset: u32,
    source_map: &php_rs_parser::source_map::SourceMap,
) -> (u32, u16) {
    let lc = source_map.offset_to_line_col(offset);
    let line = lc.line + 1;

    let byte_offset = offset as usize;
    let line_start_byte = if byte_offset == 0 {
        0
    } else {
        source[..byte_offset]
            .rfind('\n')
            .map(|p| p + 1)
            .unwrap_or(0)
    };

    let col = (source[line_start_byte..byte_offset].chars().count() + 1) as u16;

    (line, col)
}

// ---------------------------------------------------------------------------
// Type-hint class existence checker
// ---------------------------------------------------------------------------

pub(crate) fn check_type_hint_classes(
    hint: &php_ast::owned::TypeHint,
    db: &dyn MirDatabase,
    file: &Arc<str>,
    source: &str,
    source_map: &php_rs_parser::source_map::SourceMap,
    issues: &mut Vec<mir_issues::Issue>,
    php_version: PhpVersion,
) {
    use php_ast::owned::TypeHintKind;
    match &hint.kind {
        TypeHintKind::Named(name) => {
            let name_str = crate::parser::name_to_string_owned(name);
            if is_pseudo_type(&name_str) {
                return;
            }
            let resolved = resolve_name(db, file.as_ref(), &name_str);
            if !class_exists(db, &resolved) {
                // Soft-fallback: build-time stub index recognises this class
                // as a PHP built-in → assume lazy-stub timing rather than
                // user error. See call/function.rs for the parallel path.
                // However, don't suppress if the class is version-filtered.
                if let Some(stub_path) = crate::stubs::stub_path_for_class(&resolved) {
                    if let Some(stub_src) = crate::stubs::stub_content_for_path(stub_path) {
                        if let Some(docblock_text) =
                            crate::call::extract_class_docblock(stub_src, &resolved)
                        {
                            let doc = crate::parser::DocblockParser::parse(docblock_text);
                            if php_version
                                .includes_symbol(doc.since.as_deref(), doc.removed.as_deref())
                            {
                                return;
                            }
                        } else {
                            return;
                        }
                    }
                }
                let (line, col_start) = offset_to_line_col(source, hint.span.start, source_map);
                let (line_end, col_end) = if hint.span.start < hint.span.end {
                    let (end_line, end_col) = offset_to_line_col(source, hint.span.end, source_map);
                    (end_line, end_col)
                } else {
                    (line, col_start)
                };
                issues.push(
                    mir_issues::Issue::new(
                        mir_issues::IssueKind::UndefinedClass { name: resolved },
                        mir_issues::Location {
                            file: file.clone(),
                            line,
                            line_end,
                            col_start,
                            col_end: col_end.max(col_start + 1),
                        },
                    )
                    .with_snippet(crate::parser::span_text(source, hint.span).unwrap_or_default()),
                );
            } else {
                // Class exists — check if it's deprecated
                let here = crate::db::Fqcn::from_str(db, resolved.as_str());
                if let Some(class) = crate::db::find_class_like(db, here) {
                    if let Some(msg) = class.deprecated() {
                        let (line, col_start) =
                            offset_to_line_col(source, hint.span.start, source_map);
                        let (line_end, col_end) = if hint.span.start < hint.span.end {
                            offset_to_line_col(source, hint.span.end, source_map)
                        } else {
                            (line, col_start)
                        };
                        issues.push(mir_issues::Issue::new(
                            mir_issues::IssueKind::DeprecatedClass {
                                name: resolved,
                                message: Some(msg.clone()).filter(|m| !m.is_empty()),
                            },
                            mir_issues::Location {
                                file: file.clone(),
                                line,
                                line_end,
                                col_start,
                                col_end: col_end.max(col_start + 1),
                            },
                        ));
                    }
                }
            }
        }
        TypeHintKind::Nullable(inner) => {
            check_type_hint_classes(inner, db, file, source, source_map, issues, php_version);
        }
        TypeHintKind::Union(parts) | TypeHintKind::Intersection(parts) => {
            for part in parts.iter() {
                check_type_hint_classes(part, db, file, source, source_map, issues, php_version);
            }
        }
        TypeHintKind::Keyword(_, _) => {}
    }
}

/// Collect all resolved Named class FQCNs referenced in a type hint, regardless
/// of whether those classes exist. Used to record dependency edges even for
/// classes that are defined (not just missing ones).
pub(crate) fn collect_type_hint_class_refs(
    hint: &php_ast::owned::TypeHint,
    db: &dyn MirDatabase,
    file: &Arc<str>,
) -> Vec<(Arc<str>, php_ast::Span)> {
    let mut out = Vec::new();
    collect_type_hint_class_refs_inner(hint, db, file, &mut out);
    out
}

fn collect_type_hint_class_refs_inner(
    hint: &php_ast::owned::TypeHint,
    db: &dyn MirDatabase,
    file: &Arc<str>,
    out: &mut Vec<(Arc<str>, php_ast::Span)>,
) {
    use php_ast::owned::TypeHintKind;
    match &hint.kind {
        TypeHintKind::Named(name) => {
            let name_str = crate::parser::name_to_string_owned(name);
            if is_pseudo_type(&name_str) {
                return;
            }
            let resolved = resolve_name(db, file.as_ref(), &name_str);
            out.push((Arc::from(resolved.as_str()), hint.span));
        }
        TypeHintKind::Nullable(inner) => {
            collect_type_hint_class_refs_inner(inner, db, file, out);
        }
        TypeHintKind::Union(parts) | TypeHintKind::Intersection(parts) => {
            for part in parts.iter() {
                collect_type_hint_class_refs_inner(part, db, file, out);
            }
        }
        TypeHintKind::Keyword(_, _) => {}
    }
}

pub(crate) fn check_name_class(
    name: &php_ast::owned::Name,
    db: &dyn MirDatabase,
    file: &Arc<str>,
    source: &str,
    source_map: &php_rs_parser::source_map::SourceMap,
    issues: &mut Vec<mir_issues::Issue>,
    php_version: PhpVersion,
) {
    check_name_class_with_context(
        name,
        db,
        file,
        source,
        source_map,
        issues,
        php_version,
        false,
    );
}

pub(crate) fn check_name_class_for_extends(
    name: &php_ast::owned::Name,
    db: &dyn MirDatabase,
    file: &Arc<str>,
    source: &str,
    source_map: &php_rs_parser::source_map::SourceMap,
    issues: &mut Vec<mir_issues::Issue>,
    php_version: PhpVersion,
) {
    check_name_class_with_context(
        name,
        db,
        file,
        source,
        source_map,
        issues,
        php_version,
        true,
    );
}

#[allow(clippy::too_many_arguments)]
fn check_name_class_with_context(
    name: &php_ast::owned::Name,
    db: &dyn MirDatabase,
    file: &Arc<str>,
    source: &str,
    source_map: &php_rs_parser::source_map::SourceMap,
    issues: &mut Vec<mir_issues::Issue>,
    php_version: PhpVersion,
    is_extends: bool,
) {
    let name_str = crate::parser::name_to_string_owned(name);
    let resolved = resolve_name(db, file.as_ref(), &name_str);
    if !class_exists(db, &resolved) {
        // Soft-fallback: see call/function.rs for the rationale.
        // However, don't suppress if the class is version-filtered.
        if let Some(stub_path) = crate::stubs::stub_path_for_class(&resolved) {
            if let Some(stub_src) = crate::stubs::stub_content_for_path(stub_path) {
                if let Some(docblock_text) =
                    crate::call::extract_class_docblock(stub_src, &resolved)
                {
                    let doc = crate::parser::DocblockParser::parse(docblock_text);
                    if php_version.includes_symbol(doc.since.as_deref(), doc.removed.as_deref()) {
                        return;
                    }
                } else {
                    return;
                }
            }
        }
        let span = name.span;
        let (line, col_start) = offset_to_line_col(source, span.start, source_map);
        let (line_end, col_end) = offset_to_line_col(source, span.end, source_map);
        issues.push(
            mir_issues::Issue::new(
                mir_issues::IssueKind::UndefinedClass { name: resolved },
                mir_issues::Location {
                    file: file.clone(),
                    line,
                    line_end,
                    col_start,
                    col_end: col_end.max(col_start + 1),
                },
            )
            .with_snippet(crate::parser::span_text(source, span).unwrap_or_default()),
        );
        return;
    }

    // Check if extending an interface
    if is_extends {
        let here = crate::db::Fqcn::from_str(db, resolved.as_str());
        let is_iface = crate::db::find_class_like(db, here)
            .map(|c| c.is_interface())
            .unwrap_or(false);
        if is_iface {
            {
                let span = name.span;
                let (line, col_start) = offset_to_line_col(source, span.start, source_map);
                let (line_end, col_end) = offset_to_line_col(source, span.end, source_map);
                issues.push(
                    mir_issues::Issue::new(
                        mir_issues::IssueKind::UndefinedClass { name: resolved },
                        mir_issues::Location {
                            file: file.clone(),
                            line,
                            line_end,
                            col_start,
                            col_end: col_end.max(col_start + 1),
                        },
                    )
                    .with_snippet(crate::parser::span_text(source, span).unwrap_or_default()),
                );
            }
        }
    }
}

fn is_pseudo_type(name: &str) -> bool {
    matches!(
        name.to_lowercase().as_str(),
        "self"
            | "static"
            | "parent"
            | "null"
            | "true"
            | "false"
            | "never"
            | "void"
            | "mixed"
            | "object"
            | "callable"
            | "iterable"
    )
}

// ---------------------------------------------------------------------------
// Expression class checking
// ---------------------------------------------------------------------------

pub(crate) fn check_expr_for_undefined_classes(
    expr: &php_ast::owned::Expr,
    db: &dyn MirDatabase,
    file: &Arc<str>,
    source: &str,
    source_map: &php_rs_parser::source_map::SourceMap,
    issues: &mut Vec<mir_issues::Issue>,
    _php_version: PhpVersion,
) {
    use php_ast::owned::ExprKind;
    if let ExprKind::ClassConstAccess(cca) = &expr.kind {
        // Check for undefined class in ::CONSTANT or ::class
        if let ExprKind::Identifier(class_name) = &cca.class.kind {
            let name_str = class_name.to_string();
            let resolved = resolve_name(db, file.as_ref(), &name_str);
            if !class_exists(db, &resolved) {
                let (line, col_start) =
                    offset_to_line_col(source, cca.class.span.start, source_map);
                let (line_end, col_end) =
                    offset_to_line_col(source, cca.class.span.end, source_map);
                issues.push(
                    mir_issues::Issue::new(
                        mir_issues::IssueKind::UndefinedClass { name: resolved },
                        mir_issues::Location {
                            file: file.clone(),
                            line,
                            line_end,
                            col_start,
                            col_end: col_end.max(col_start + 1),
                        },
                    )
                    .with_snippet(
                        crate::parser::span_text(source, cca.class.span).unwrap_or_default(),
                    ),
                );
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Unused param / variable emission
// ---------------------------------------------------------------------------

const MAGIC_METHODS_WITH_RUNTIME_PARAMS: &[&str] = &[
    "__get",
    "__set",
    "__call",
    "__callStatic",
    "__isset",
    "__unset",
    "__unserialize",
];

pub(crate) fn emit_unused_params(
    params: &[mir_codebase::FnParam],
    ctx: &crate::flow_state::FlowState,
    method_name: &str,
    file: &Arc<str>,
    issues: &mut Vec<mir_issues::Issue>,
) {
    if MAGIC_METHODS_WITH_RUNTIME_PARAMS.contains(&method_name) {
        return;
    }
    for p in params {
        let name = p.name.as_ref().trim_start_matches('$');
        // Skip the synthetic variadic param injected by func_get_args() detection —
        // its name "..." is not a valid PHP identifier and never appears in source.
        if name == "..." {
            continue;
        }
        let name_sym = mir_types::Name::from(name);
        if !ctx.read_vars.contains(&name_sym) {
            let (line, col_start, line_end, col_end) = ctx
                .var_locations
                .get(&name_sym)
                .copied()
                .unwrap_or((1, 0, 1, 0));
            issues.push(
                mir_issues::Issue::new(
                    mir_issues::IssueKind::UnusedParam {
                        name: name.to_string(),
                    },
                    mir_issues::Location {
                        file: file.clone(),
                        line,
                        line_end,
                        col_start,
                        col_end: col_end.max(col_start + 1),
                    },
                )
                .with_snippet(format!("${name}")),
            );
        }
    }
}

/// A `__toString` method must return a `string`. Emits `InvalidToString` when
/// the effective return type (declared if present, else inferred from the body)
/// is definitely not a string. Conservative: `mixed`/empty types are skipped so
/// incomplete inference never produces a false positive.
#[allow(clippy::too_many_arguments)]
pub(crate) fn check_to_string_return(
    fqcn: &str,
    declared_return: Option<&mir_types::Type>,
    inferred: &mir_types::Type,
    body_span: &php_ast::Span,
    file: &Arc<str>,
    source: &str,
    source_map: &php_rs_parser::source_map::SourceMap,
    issues: &mut Vec<mir_issues::Issue>,
) {
    let effective = declared_return.unwrap_or(inferred);
    if effective.is_mixed() || effective.is_empty() {
        return;
    }
    if effective.types.iter().all(|a| a.is_string()) {
        return;
    }
    let (line, col_start) = offset_to_line_col(source, body_span.start, source_map);
    let (line_end, col_end) = offset_to_line_col(source, body_span.end, source_map);
    issues.push(mir_issues::Issue::new(
        mir_issues::IssueKind::InvalidToString {
            class: fqcn.to_string(),
        },
        mir_issues::Location {
            file: file.clone(),
            line,
            line_end,
            col_start,
            col_end: col_end.max(col_start + 1),
        },
    ));
}

/// True when a declared return type obliges every code path to `return` a
/// value, so falling off the end of the body is an error. Conservative:
/// `void`/`never`/`mixed`/nullable returns are exempt (falling off yields
/// `null`, which those accept or which is moot), and iterable/generator-like
/// returns are exempt because a generator body legitimately never returns.
fn return_requires_value(t: &mir_types::Type) -> bool {
    use mir_types::Atomic;
    if t.is_empty() || t.is_void() || t.is_never() || t.is_mixed() || t.is_nullable() {
        return false;
    }
    // Conditional and template return types are resolved per-call/contextually;
    // an empty-bodied stub with such a return must not be flagged (mirrors the
    // exemption in `analyze_return_stmt`).
    if t.types.iter().any(|a| {
        matches!(
            a,
            Atomic::TConditional { .. } | Atomic::TTemplateParam { .. }
        )
    }) {
        return false;
    }
    !t.types.iter().any(|a| match a {
        Atomic::TNamedObject { fqcn, .. } => {
            let n = fqcn.trim_start_matches('\\');
            n.eq_ignore_ascii_case("Generator")
                || n.eq_ignore_ascii_case("Iterator")
                || n.eq_ignore_ascii_case("IteratorAggregate")
                || n.eq_ignore_ascii_case("Traversable")
                || n.eq_ignore_ascii_case("iterable")
        }
        // `iterable` and array returns also cover generator bodies.
        Atomic::TArray { .. }
        | Atomic::TList { .. }
        | Atomic::TNonEmptyArray { .. }
        | Atomic::TNonEmptyList { .. }
        | Atomic::TKeyedArray { .. } => true,
        _ => false,
    })
}

/// Emit `InvalidReturnType` when a value-returning function/method can reach the
/// end of its body without returning. `diverges` is the flow flag after body
/// analysis: `true` means every path already returned/threw/exited.
#[allow(clippy::too_many_arguments)]
pub(crate) fn check_missing_return(
    declared_return: Option<&mir_types::Type>,
    diverges: bool,
    body_span: &php_ast::Span,
    file: &Arc<str>,
    source: &str,
    source_map: &php_rs_parser::source_map::SourceMap,
    issues: &mut Vec<mir_issues::Issue>,
) {
    if diverges {
        return;
    }
    let Some(declared) = declared_return else {
        return;
    };
    if !return_requires_value(declared) {
        return;
    }
    let (line, col_start) = offset_to_line_col(source, body_span.start, source_map);
    let (line_end, col_end) = offset_to_line_col(source, body_span.end, source_map);
    issues.push(mir_issues::Issue::new(
        mir_issues::IssueKind::InvalidReturnType {
            expected: format!("{declared}"),
            actual: "void".to_string(),
        },
        mir_issues::Location {
            file: file.clone(),
            line,
            line_end,
            col_start,
            col_end: col_end.max(col_start + 1),
        },
    ));
}

pub(crate) fn emit_unused_variables(
    ctx: &crate::flow_state::FlowState,
    file: &Arc<str>,
    issues: &mut Vec<mir_issues::Issue>,
) {
    const SUPERGLOBALS: &[&str] = &[
        "_SERVER", "_GET", "_POST", "_REQUEST", "_SESSION", "_COOKIE", "_FILES", "_ENV", "GLOBALS",
        "argv", "argc",
    ];

    // Helper: should we skip this variable name?
    let skip = |name: &mir_types::Name| -> bool {
        ctx.param_names.contains(name)
            || SUPERGLOBALS.contains(&name.as_str())
            || name == "this"
            || name.starts_with('_')
    };

    // Emit at most one UnusedVariable/UnusedForeachValue per variable name to avoid
    // noise from multiple dead-write occurrences in complex control flow.
    let mut emitted_names: rustc_hash::FxHashSet<mir_types::Name> =
        rustc_hash::FxHashSet::default();

    let mut push = |name: mir_types::Name, // Name is Copy
                    line: u32,
                    col_start: u16,
                    line_end: u32,
                    col_end: u16,
                    issues: &mut Vec<mir_issues::Issue>| {
        if emitted_names.insert(name) {
            let kind = if ctx.foreach_value_var_names.contains(&name) {
                mir_issues::IssueKind::UnusedForeachValue {
                    name: name.to_string(),
                }
            } else {
                mir_issues::IssueKind::UnusedVariable {
                    name: name.to_string(),
                }
            };
            issues.push(mir_issues::Issue::new(
                kind,
                mir_issues::Location {
                    file: file.clone(),
                    line,
                    line_end,
                    col_start,
                    col_end: col_end.max(col_start + 1),
                },
            ));
        }
    };

    // Dead writes: values overwritten without being read (detected at overwrite time).
    // These are emitted at the location of the overwritten (dead) write.
    for (name, line, col_start, line_end, col_end) in &ctx.dead_writes {
        if skip(name) {
            continue;
        }
        push(*name, *line, *col_start, *line_end, *col_end, issues);
    }

    // Remaining pending writes: variables with a write that was never consumed.
    // This covers both "variable never read at all" and compound-op results not read.
    for (name, (line, col_start, line_end, col_end)) in &ctx.last_write_locs {
        if skip(name) {
            continue;
        }
        push(*name, *line, *col_start, *line_end, *col_end, issues);
    }

    // Fallback for variables in assigned_vars that lack last_write_locs entries
    // (e.g. created via set_var without record_var_location in older code paths).
    for name in ctx.assigned_vars.iter() {
        if skip(name) {
            continue;
        }
        if !ctx.read_vars.contains(name) && !ctx.last_write_locs.contains_key(name) {
            let (line, col_start, line_end, col_end) =
                ctx.var_locations.get(name).copied().unwrap_or((1, 0, 1, 0));
            push(*name, line, col_start, line_end, col_end, issues);
        }
    }
}