mago-analyzer 1.47.5

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
//! `sprintf()` / format-string return type provider.
//!
//! When all arguments are known literals, resolves the exact result string.
//! When the format string is known but arguments are not all literals,
//! infers `non-empty-string` or `truthy-string` when the output is guaranteed
//! to be non-empty or longer than one character.
//!
//! The core logic is exposed via [`resolve_sprintf`] so it can be reused by
//! other providers (e.g. `Psl\Str\format`).

use std::fmt::Write;

use mago_codex::ttype::atomic::TAtomic;
use mago_codex::ttype::atomic::scalar::TScalar;
use mago_codex::ttype::get_literal_string;
use mago_codex::ttype::get_non_empty_string;
use mago_codex::ttype::get_truthy_string;
use mago_codex::ttype::union::TUnion;
use mago_word::word;

use crate::plugin::context::InvocationInfo;
use crate::plugin::context::ProviderContext;
use crate::plugin::provider::Provider;
use crate::plugin::provider::ProviderMeta;
use crate::plugin::provider::function::FunctionReturnTypeProvider;
use crate::plugin::provider::function::FunctionTarget;

static META: ProviderMeta =
    ProviderMeta::new("php::string::sprintf", "sprintf", "Resolves literal string for sprintf with literal args");

#[derive(Default)]
pub struct SprintfProvider;

impl Provider for SprintfProvider {
    fn meta() -> &'static ProviderMeta {
        &META
    }
}

impl FunctionReturnTypeProvider for SprintfProvider {
    fn targets() -> FunctionTarget {
        FunctionTarget::Exact(b"sprintf")
    }

    fn get_return_type(
        &self,
        context: &ProviderContext<'_, '_, '_>,
        invocation: &InvocationInfo<'_, '_, '_>,
    ) -> Option<TUnion> {
        resolve_sprintf(context, invocation)
    }
}

/// Resolve the return type of a sprintf-like call.
///
/// Expects the first argument to be the format string and subsequent arguments
/// to be the format values (standard `sprintf` / `Psl\Str\format` signature).
pub fn resolve_sprintf(
    context: &ProviderContext<'_, '_, '_>,
    invocation: &InvocationInfo<'_, '_, '_>,
) -> Option<TUnion> {
    let format_argument = invocation.get_argument(0, &[b"format"])?;
    let format_type = context.get_expression_type(format_argument)?;
    let format_str = format_type.get_single_literal_string_value()?;

    if let Some(result) = resolve_literal(format_str, context, invocation) {
        return Some(get_literal_string(word(&result)));
    }

    let min_len = analyze_min_length(format_str, context, invocation);
    if min_len >= 2 {
        Some(get_truthy_string())
    } else if min_len >= 1 {
        Some(get_non_empty_string())
    } else {
        None
    }
}

fn argument_string_min_length(
    context: &ProviderContext<'_, '_, '_>,
    invocation: &InvocationInfo<'_, '_, '_>,
    arg_index: usize,
) -> usize {
    let Some(arg) = invocation.get_argument(arg_index, &[]) else {
        return 0;
    };

    let Some(arg_type) = context.get_expression_type(arg) else {
        return 0;
    };

    if let Some(literal) = arg_type.get_single_literal_string_value() {
        return literal.len();
    }

    let mut min_len = usize::MAX;
    for atomic in arg_type.types.as_ref() {
        let atomic_min = match atomic {
            TAtomic::Scalar(TScalar::String(string)) if string.is_non_empty || string.is_numeric => 1,
            _ => 0,
        };

        if atomic_min < min_len {
            min_len = atomic_min;
        }

        if min_len == 0 {
            return 0;
        }
    }

    if min_len == usize::MAX { 0 } else { min_len }
}

/// Parse flags from a format specifier. Advances `i` past all flag characters.
/// Returns `None` if the format string is malformed (unexpected end).
fn parse_flags(bytes: &[u8], i: &mut usize) -> Option<(char, bool, bool)> {
    let len = bytes.len();
    let mut pad_char = ' ';
    let mut left_align = false;
    let mut show_sign = false;

    loop {
        if *i >= len {
            return None;
        }
        match bytes[*i] {
            b'-' => {
                left_align = true;
                *i += 1;
            }
            b'+' => {
                show_sign = true;
                *i += 1;
            }
            b' ' => *i += 1,
            b'0' => {
                pad_char = '0';
                *i += 1;
            }
            b'\'' => {
                *i += 1;
                if *i >= len {
                    return None;
                }

                pad_char = bytes[*i] as char;
                *i += 1;
            }
            _ => break,
        }
    }

    Some((pad_char, left_align, show_sign))
}

/// Parse a decimal number from `bytes` starting at `i`. Advances `i` past all digits.
fn parse_number(bytes: &[u8], i: &mut usize) -> usize {
    let len = bytes.len();
    let mut n: usize = 0;
    while *i < len && bytes[*i].is_ascii_digit() {
        n = n * 10 + (bytes[*i] - b'0') as usize;
        *i += 1;
    }

    n
}

/// Parse optional precision (`.N`). Advances `i` past the precision if present.
fn parse_precision(bytes: &[u8], i: &mut usize) -> Option<usize> {
    if *i < bytes.len() && bytes[*i] == b'.' {
        *i += 1;
        Some(parse_number(bytes, i))
    } else {
        None
    }
}

/// Try to fully resolve sprintf to a literal string when all arguments are known literals.
fn resolve_literal(
    format_str: &[u8],
    context: &ProviderContext<'_, '_, '_>,
    invocation: &InvocationInfo<'_, '_, '_>,
) -> Option<String> {
    let format_str_utf8 = std::str::from_utf8(format_str).ok()?;
    let mut result = String::with_capacity(format_str.len());
    let mut buf = String::new();
    let bytes = format_str;
    let len = bytes.len();
    let mut i = 0;
    let mut arg_index: usize = 1;

    while i < len {
        if bytes[i] != b'%' {
            let start = i;
            i += 1;
            while i < len && bytes[i] != b'%' {
                i += 1;
            }

            result.push_str(&format_str_utf8[start..i]);
            continue;
        }

        i += 1;
        if i >= len {
            return None;
        }

        if bytes[i] == b'%' {
            result.push('%');
            i += 1;
            continue;
        }

        let (pad_char, left_align, show_sign) = parse_flags(bytes, &mut i)?;
        let width = parse_number(bytes, &mut i);
        let precision = parse_precision(bytes, &mut i);

        if i >= len {
            return None;
        }

        let specifier = bytes[i];
        let arg = invocation.get_argument(arg_index, &[])?;
        let arg_type = context.get_expression_type(arg)?;

        i += 1;
        arg_index += 1;

        let needs_buf = width > 0 || specifier == b'e' || specifier == b'E';
        let target = if needs_buf {
            buf.clear();
            &mut buf
        } else {
            &mut result
        };

        match specifier {
            b's' => {
                let value = arg_type.get_single_literal_string_value()?;
                let value_str = std::str::from_utf8(value).ok()?;
                if let Some(prec) = precision {
                    target.push_str(&value_str[..value_str.len().min(prec)]);
                } else {
                    target.push_str(value_str);
                }
            }
            b'd' => {
                let value = arg_type.get_single_literal_int_value()?;
                if show_sign && value >= 0 {
                    target.push('+');
                }

                let _ = write!(target, "{value}");
            }
            b'u' => {
                let value = arg_type.get_single_literal_int_value()?;
                let _ = write!(target, "{}", value as u64);
            }
            b'f' | b'F' => {
                let value = get_float_value(arg_type)?;
                let prec = precision.unwrap_or(6);
                if show_sign && value >= 0.0 {
                    target.push('+');
                }

                let _ = write!(target, "{value:.prec$}");
            }
            b'e' | b'E' => {
                let value = get_float_value(arg_type)?;
                let prec = precision.unwrap_or(6);
                if show_sign && value >= 0.0 {
                    target.push('+');
                }

                let mark = target.len();
                if specifier == b'e' {
                    let _ = write!(target, "{value:.prec$e}");
                } else {
                    let _ = write!(target, "{value:.prec$E}");
                }

                // Rust writes e.g. `1e0`, PHP writes `1e+0`. Insert `+` if needed.
                normalize_scientific_in_place(target, mark);
            }
            b'x' => {
                let value = arg_type.get_single_literal_int_value()?;
                let _ = write!(target, "{:x}", value as u64);
            }
            b'X' => {
                let value = arg_type.get_single_literal_int_value()?;
                let _ = write!(target, "{:X}", value as u64);
            }
            b'o' => {
                let value = arg_type.get_single_literal_int_value()?;
                let _ = write!(target, "{:o}", value as u64);
            }
            b'b' => {
                let value = arg_type.get_single_literal_int_value()?;
                let _ = write!(target, "{:b}", value as u64);
            }
            b'c' => {
                let value = arg_type.get_single_literal_int_value()?;
                target.push(char::from_u32(value as u32)?);
            }
            _ => return None,
        }

        if needs_buf {
            if width > 0 && buf.len() < width {
                let padding = width - buf.len();
                if left_align {
                    result.push_str(&buf);
                    for _ in 0..padding {
                        result.push(' ');
                    }
                } else {
                    for _ in 0..padding {
                        result.push(pad_char);
                    }
                    result.push_str(&buf);
                }
            } else {
                result.push_str(&buf);
            }
        }
    }

    Some(result)
}

/// Extract a float value from a type union, accepting either a literal float or literal int.
fn get_float_value(t: &TUnion) -> Option<f64> {
    if let Some(v) = t.get_single_literal_float_value() {
        Some(v)
    } else {
        t.get_single_literal_int_value().map(|v| v as f64)
    }
}

/// Insert a `+` sign after `e`/`E` in scientific notation if Rust omitted it.
/// Only scans bytes from `start` onward.
fn normalize_scientific_in_place(s: &mut String, start: usize) {
    let bytes = s.as_bytes();
    for j in start..bytes.len() {
        if bytes[j] == b'e' || bytes[j] == b'E' {
            if j + 1 < bytes.len() && bytes[j + 1] != b'+' && bytes[j + 1] != b'-' {
                s.insert(j + 1, '+');
            }
            return;
        }
    }
}

fn analyze_min_length(
    format_str: &[u8],
    context: &ProviderContext<'_, '_, '_>,
    invocation: &InvocationInfo<'_, '_, '_>,
) -> usize {
    let bytes = format_str;
    let len = bytes.len();
    let mut i = 0;
    let mut min_len: usize = 0;
    let mut arg_index: usize = 1;

    while i < len {
        if bytes[i] != b'%' {
            let start = i;
            i += 1;
            while i < len && bytes[i] != b'%' {
                i += 1;
            }

            min_len += i - start;
            continue;
        }

        i += 1;
        if i >= len {
            return min_len;
        }

        if bytes[i] == b'%' {
            min_len += 1;
            i += 1;
            continue;
        }

        // Skip flags.
        loop {
            if i >= len {
                return min_len;
            }

            match bytes[i] {
                b'-' | b'+' | b' ' | b'0' => i += 1,
                b'\'' => {
                    i += 2;
                    if i > len {
                        return min_len;
                    }
                }
                _ => break,
            }
        }

        let width = parse_number(bytes, &mut i);
        let precision = parse_precision(bytes, &mut i);

        if i >= len {
            return min_len;
        }

        let specifier = bytes[i];
        i += 1;

        let specifier_min = match specifier {
            b's' => {
                let mut from_arg = argument_string_min_length(context, invocation, arg_index);
                if let Some(prec) = precision {
                    from_arg = from_arg.min(prec);
                }

                from_arg
            }
            b'd' | b'u' | b'f' | b'F' | b'e' | b'E' | b'x' | b'X' | b'o' | b'b' | b'c' => 1,
            _ => 0,
        };

        arg_index += 1;
        min_len += specifier_min.max(width);
    }

    min_len
}