mago-analyzer 1.12.0

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
use std::sync::Arc;

use mago_atom::Atom;
use mago_codex::identifier::function_like::FunctionLikeIdentifier;
use mago_codex::identifier::method::MethodIdentifier;
use mago_codex::metadata::class_like::ClassLikeMetadata;
use mago_codex::metadata::class_like::TemplateTypes;
use mago_codex::metadata::function_like::FunctionLikeMetadata;
use mago_codex::metadata::parameter::FunctionLikeParameterMetadata;
use mago_codex::misc::VariableIdentifier;
use mago_codex::ttype::atomic::callable::TCallableSignature;
use mago_codex::ttype::atomic::callable::parameter::TCallableParameter;
use mago_codex::ttype::expander::StaticClassType;
use mago_codex::ttype::union::TUnion;
use mago_span::HasSpan;
use mago_span::Span;
use mago_syntax::ast::Argument;
use mago_syntax::ast::ArgumentList;
use mago_syntax::ast::Expression;
use mago_syntax::ast::NamedArgument;
use mago_syntax::ast::NamedPlaceholderArgument;
use mago_syntax::ast::PartialArgument;
use mago_syntax::ast::PartialArgumentList;
use mago_syntax::ast::Pipe;
use mago_syntax::ast::PlaceholderArgument;
use mago_syntax::ast::PositionalArgument;
use mago_syntax::ast::VariadicPlaceholderArgument;

mod resolver;
mod template_inference;

pub(crate) mod arguments;

pub mod analyzer;
pub mod post_process;
pub mod return_type_fetcher;
pub mod template_result;

/// Represents a resolved function, method, or callable invocation.
#[derive(Debug, Clone)]
pub struct Invocation<'ctx, 'ast, 'arena> {
    /// The target being called (function, method, or callable).
    pub target: InvocationTarget<'ctx>,
    /// The arguments passed to the call.
    pub arguments_source: InvocationArgumentsSource<'ast, 'arena>,
    /// The source span of the entire invocation.
    pub span: Span,
}

/// Context information for method call resolution.
#[derive(Debug, Clone)]
pub struct MethodTargetContext<'ctx> {
    /// The method identifier, if statically resolved.
    pub declaring_method_id: Option<MethodIdentifier>,
    /// Metadata for the class the method is being called on (not necessarily where it's declared).
    /// This is used for resolving `self` types in return values.
    pub class_like_metadata: &'ctx ClassLikeMetadata,
    /// The class type for resolving static references.
    pub class_type: StaticClassType,
}

/// The target of an invocation (function, method, or callable).
#[derive(Debug, Clone)]
pub enum InvocationTarget<'ctx> {
    /// A dynamic callable (closure, invocable object, etc.).
    Callable {
        /// The original function/method identifier, if traceable.
        source: Option<FunctionLikeIdentifier>,
        /// The callable's type signature.
        signature: TCallableSignature,
        /// The span of the callable expression.
        span: Span,
    },
    /// A statically resolved function or method.
    FunctionLike {
        /// The function/method identifier.
        identifier: FunctionLikeIdentifier,
        /// Function/method metadata.
        metadata: &'ctx FunctionLikeMetadata,
        /// Inferred return type (used for closures/arrow functions).
        inferred_return_type: Option<Arc<TUnion>>,
        /// Method call context, if applicable.
        method_context: Option<MethodTargetContext<'ctx>>,
        /// The span of the callable part.
        span: Span,
    },
}

/// Represents a parameter definition, abstracting over parameters from statically
/// known functions/methods and parameters from dynamic `TCallableSignature`s.
///
/// This allows argument checking logic to treat both sources of parameter information
/// uniformly.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InvocationTargetParameter<'ctx> {
    /// Parameter from a statically defined function or method.
    FunctionLike(&'ctx FunctionLikeParameterMetadata),
    /// Parameter from a `TCallableSignature` (e.g., from a closure type or `callable` type hint).
    Callable(&'ctx TCallableParameter),
}

/// Represents the source of arguments for an invocation.
///
/// This distinguishes between standard argument lists `func(args)` and
/// arguments provided via the pipe operator `$input |> func`.
#[derive(Debug, Clone, Copy)]
pub enum InvocationArgumentsSource<'ast, 'arena> {
    /// No arguments are present, e.g., calling `__construct` via `new Foo`,
    /// or `__toString` via `(string) $foo`.
    None(Span),
    /// Arguments are provided in a standard list, like `foo($a, $b)`.
    ArgumentList(&'ast ArgumentList<'arena>),
    /// The single argument is the input from a pipe operator, like `$input` in `$input |> foo(...)`.
    PipeInput(&'ast Pipe<'arena>),
    /// Arguments from a partial application, which may include placeholders.
    PartialArgumentList(&'ast PartialArgumentList<'arena>),
}

/// Represents a single argument passed during an invocation, abstracting whether
/// it's a standard argument or a value piped in.
///
/// This allows iteration over "effective arguments" regardless of how they were supplied.
#[derive(Debug, Clone, Copy)]
pub enum InvocationArgument<'ast, 'arena> {
    /// The value provided as input via the pipe operator. This is treated as the first positional argument.
    PipedValue(&'ast Expression<'arena>),
    /// A positional argument.
    Positional(&'ast PositionalArgument<'arena>),
    /// A named argument.
    Named(&'ast NamedArgument<'arena>),
    /// A positional placeholder (`?`) in partial application.
    Placeholder(&'ast PlaceholderArgument),
    /// A named placeholder (`name: ?`) in partial application.
    NamedPlaceholder(&'ast NamedPlaceholderArgument<'arena>),
    /// A variadic placeholder (`...`) in partial application.
    VariadicPlaceholder(&'ast VariadicPlaceholderArgument),
}

impl<'ctx, 'ast, 'arena> Invocation<'ctx, 'ast, 'arena> {
    pub fn new(target: InvocationTarget<'ctx>, arguments: InvocationArgumentsSource<'ast, 'arena>, span: Span) -> Self {
        Self { target, arguments_source: arguments, span }
    }
}

impl<'ctx> InvocationTarget<'ctx> {
    /// Attempts to guess a human-readable name for the callable target.
    ///
    /// Returns the name of a function/method if statically known,
    /// or "Closure" or "callable" for dynamic callables.
    pub fn guess_name(&self) -> String {
        self.get_function_like_identifier()
            .map(mago_codex::identifier::function_like::FunctionLikeIdentifier::as_string)
            .unwrap_or_else(
                || {
                    if self.is_non_closure_callable() { "callable".to_string() } else { "Closure".to_string() }
                },
            )
    }

    /// Guesses the kind of the callable target (e.g., "function", "method", "closure", "callable").
    pub fn guess_kind(&self) -> &'static str {
        match self.get_function_like_identifier() {
            Some(identifier) => match identifier {
                FunctionLikeIdentifier::Function(_) => "function",
                FunctionLikeIdentifier::Method(_, _) => "method",
                FunctionLikeIdentifier::Closure(_, _) => "closure",
            },
            None => {
                if self.is_non_closure_callable() {
                    "callable"
                } else {
                    "closure"
                }
            }
        }
    }

    pub const fn is_method_call(&self) -> bool {
        matches!(self.get_function_like_identifier(), Some(FunctionLikeIdentifier::Method(_, _)))
    }

    /// Checks if the target is a dynamic callable that is not explicitly a closure type.
    /// This can be true for `callable` type hints or invocable objects that aren't closures.
    #[inline]
    pub const fn is_non_closure_callable(&self) -> bool {
        match self {
            InvocationTarget::Callable { signature, .. } => !signature.is_closure(),
            _ => false,
        }
    }

    /// Returns the metadata if this target is a statically known function or method.
    #[inline]
    pub const fn get_function_like_metadata(&self) -> Option<&'ctx FunctionLikeMetadata> {
        match self {
            InvocationTarget::FunctionLike { metadata, .. } => Some(metadata),
            _ => None,
        }
    }

    /// Returns the `FunctionLikeIdentifier` if available (for static functions/methods or traced callables).
    #[inline]
    pub const fn get_function_like_identifier(&self) -> Option<&FunctionLikeIdentifier> {
        match self {
            InvocationTarget::Callable { source, .. } => source.as_ref(),
            InvocationTarget::FunctionLike { identifier, .. } => Some(identifier),
        }
    }

    /// If this target is a method, returns the fully qualified name of the class it belongs to.
    #[inline]
    #[allow(dead_code)]
    pub const fn get_method_class_like_name(&self) -> Option<Atom> {
        match self.get_function_like_identifier() {
            Some(FunctionLikeIdentifier::Method(fq_class_like_name, _)) => Some(*fq_class_like_name),
            _ => None,
        }
    }

    /// If this target is a method, returns its `MethodIdentifier`.
    #[inline]
    #[allow(dead_code)]
    pub const fn get_method_identifier(&self) -> Option<MethodIdentifier> {
        match self {
            InvocationTarget::FunctionLike { identifier, .. } => identifier.as_method_identifier(),
            _ => None,
        }
    }

    /// Checks if the target function/method is known to potentially throw exceptions (e.g., has `@throws` tags).
    #[inline]
    #[allow(dead_code)]
    pub const fn has_throw(&self) -> bool {
        match self {
            InvocationTarget::FunctionLike { metadata, .. } => metadata.flags.has_throw(),
            _ => false,
        }
    }

    /// Returns the template type definitions if the target is a generic function or method.
    #[inline]
    pub fn get_template_types(&self) -> Option<&'ctx TemplateTypes> {
        match self {
            InvocationTarget::FunctionLike { metadata, .. } => Some(&metadata.template_types),
            _ => None,
        }
    }

    /// Checks if the target function/method allows named arguments.
    #[inline]
    pub const fn allows_named_arguments(&self) -> bool {
        match self {
            InvocationTarget::FunctionLike { metadata, .. } => !metadata.flags.forbids_named_arguments(),
            _ => false,
        }
    }

    /// Returns the `MethodTargetContext` if this invocation is a method call.
    #[inline]
    pub const fn get_method_context(&self) -> Option<&MethodTargetContext<'ctx>> {
        match self {
            InvocationTarget::FunctionLike { method_context, .. } => method_context.as_ref(),
            _ => None,
        }
    }

    /// Retrieves a list of parameters for the invocation target.
    ///
    /// Parameters are wrapped in `InvocationTargetParameter` to abstract over
    /// `FunctionLikeParameterMetadata` and `TCallableParameter`.
    #[inline]
    pub fn get_parameters<'target>(&'target self) -> Vec<InvocationTargetParameter<'target>>
    where
        'ctx: 'target,
    {
        match self {
            InvocationTarget::Callable { signature, .. } => {
                signature.parameters.iter().map(InvocationTargetParameter::Callable).collect()
            }
            InvocationTarget::FunctionLike { metadata, .. } => {
                metadata.parameters.iter().map(InvocationTargetParameter::FunctionLike).collect()
            }
        }
    }

    /// Retrieves the return type of the invocation target, if known.
    #[inline]
    pub fn get_return_type(&self) -> Option<&TUnion> {
        match self {
            InvocationTarget::Callable { signature, .. } => signature.get_return_type(),
            InvocationTarget::FunctionLike { metadata, inferred_return_type, .. } => inferred_return_type
                .as_deref()
                .or_else(|| metadata.return_type_metadata.as_ref().map(|type_metadata| &type_metadata.type_union)),
        }
    }
}

impl<'a> InvocationTargetParameter<'a> {
    /// Gets the type (`TUnion`) of the parameter.
    #[inline]
    pub fn get_out_type(&self) -> Option<&'a TUnion> {
        match self {
            InvocationTargetParameter::FunctionLike(metadata) => {
                metadata.out_type.as_ref().map(|type_metadata| &type_metadata.type_union)
            }
            _ => None,
        }
    }

    /// Gets the type (`TUnion`) of the parameter.
    #[inline]
    pub fn get_type(&self) -> Option<&'a TUnion> {
        match self {
            InvocationTargetParameter::FunctionLike(metadata) => {
                metadata.get_type_metadata().map(|type_metadata| &type_metadata.type_union)
            }
            InvocationTargetParameter::Callable(parameter) => parameter.get_type_signature(),
        }
    }

    /// Gets the name of the parameter as a `VariableIdentifier`, if available
    /// (primarily for `FunctionLike` parameters).
    #[inline]
    pub fn get_name(&self) -> Option<&'a VariableIdentifier> {
        // Changed to &'a
        match self {
            InvocationTargetParameter::FunctionLike(metadata) => Some(metadata.get_name()),
            InvocationTargetParameter::Callable(_) => None,
        }
    }

    /// Checks if the parameter is passed by reference (`&`).
    #[inline]
    #[allow(dead_code)]
    pub const fn is_by_reference(&self) -> bool {
        match self {
            InvocationTargetParameter::FunctionLike(metadata) => metadata.flags.is_by_reference(),
            InvocationTargetParameter::Callable(parameter) => parameter.is_by_reference(),
        }
    }

    /// Checks if the parameter is variadic (`...`).
    #[inline]
    pub const fn is_variadic(&self) -> bool {
        match self {
            InvocationTargetParameter::FunctionLike(metadata) => metadata.flags.is_variadic(),
            InvocationTargetParameter::Callable(parameter) => parameter.is_variadic(),
        }
    }

    /// Checks if the parameter has a default value.
    #[inline]
    pub const fn has_default(&self) -> bool {
        match self {
            InvocationTargetParameter::FunctionLike(metadata) => metadata.flags.has_default(),
            InvocationTargetParameter::Callable(parameter) => parameter.has_default(),
        }
    }

    /// Get the default value type for the parameter
    #[inline]
    pub fn get_default_type(&self) -> Option<&'a TUnion> {
        match self {
            InvocationTargetParameter::FunctionLike(metadata) => {
                metadata.get_default_type().map(|type_metadata| &type_metadata.type_union)
            }
            InvocationTargetParameter::Callable(_) => None,
        }
    }
}

impl<'ast, 'arena> InvocationArgumentsSource<'ast, 'arena> {
    /// Returns a `Vec` of `InvocationArgument` which abstracts over standard arguments
    /// and piped input. For pipe input, it's a single `PipedValue`.
    #[inline]
    pub fn get_arguments(&self) -> Vec<InvocationArgument<'ast, 'arena>> {
        match self {
            InvocationArgumentsSource::ArgumentList(arg_list) => arg_list
                .arguments
                .iter()
                .map(|arg| match arg {
                    Argument::Positional(pos_arg) => InvocationArgument::Positional(pos_arg),
                    Argument::Named(named_arg) => InvocationArgument::Named(named_arg),
                })
                .collect(),
            InvocationArgumentsSource::PipeInput(pipe) => {
                vec![InvocationArgument::PipedValue(pipe.input)]
            }
            InvocationArgumentsSource::None(_) => {
                vec![]
            }
            InvocationArgumentsSource::PartialArgumentList(partial_arg_list) => partial_arg_list
                .arguments
                .iter()
                .map(|partial_arg| match partial_arg {
                    PartialArgument::Positional(pos_arg) => InvocationArgument::Positional(pos_arg),
                    PartialArgument::Named(named_arg) => InvocationArgument::Named(named_arg),
                    PartialArgument::Placeholder(placeholder) => InvocationArgument::Placeholder(placeholder),
                    PartialArgument::NamedPlaceholder(named_placeholder) => {
                        InvocationArgument::NamedPlaceholder(named_placeholder)
                    }
                    PartialArgument::VariadicPlaceholder(variadic_placeholder) => {
                        InvocationArgument::VariadicPlaceholder(variadic_placeholder)
                    }
                })
                .collect(),
        }
    }
}

impl<'ast, 'arena> InvocationArgument<'ast, 'arena> {
    /// Checks if this argument is a placeholder (any placeholder variant).
    #[inline]
    pub const fn is_placeholder(&self) -> bool {
        matches!(
            self,
            InvocationArgument::Placeholder(_)
                | InvocationArgument::NamedPlaceholder(_)
                | InvocationArgument::VariadicPlaceholder(_)
        )
    }

    /// Checks if this argument is positional (not named).
    /// Piped values and positional placeholders are considered positional.
    #[inline]
    pub const fn is_positional(&self) -> bool {
        !matches!(self, InvocationArgument::NamedPlaceholder(_) | InvocationArgument::Named(_))
    }

    /// Checks if this argument is an unpacked argument (`...$args`).
    /// Variadic placeholders are considered unpacked.
    #[inline]
    pub const fn is_unpacked(&self) -> bool {
        match self {
            InvocationArgument::Positional(pos_arg) => pos_arg.ellipsis.is_some(),
            InvocationArgument::VariadicPlaceholder(_) => true,
            _ => false,
        }
    }

    /// Returns a reference to the underlying `Expression` of the argument's value.
    /// Returns `None` for placeholders which have no value expression.
    #[inline]
    pub const fn value(&self) -> Option<&'ast Expression<'arena>> {
        match self {
            InvocationArgument::PipedValue(expr) => Some(expr),
            InvocationArgument::Positional(pos_arg) => Some(pos_arg.value),
            InvocationArgument::Named(named_arg) => Some(named_arg.value),
            _ => None,
        }
    }

    /// If this argument is a standard named argument, returns a reference to it.
    /// Returns `None` for positional arguments, piped values, or placeholders.
    #[inline]
    pub const fn get_named_argument(&self) -> Option<&'ast NamedArgument<'arena>> {
        match self {
            InvocationArgument::Named(named_arg) => Some(named_arg),
            _ => None,
        }
    }

    /// Returns the parameter name if this argument specifies one (named arguments and named placeholders).
    /// Returns `None` for positional arguments and positional placeholders.
    #[inline]
    pub const fn get_parameter_name(&self) -> Option<&'arena str> {
        match self {
            InvocationArgument::Named(named_arg) => Some(named_arg.name.value),
            InvocationArgument::NamedPlaceholder(named_ph) => Some(named_ph.name.value),
            _ => None,
        }
    }
}

impl HasSpan for Invocation<'_, '_, '_> {
    fn span(&self) -> Span {
        self.span
    }
}

impl HasSpan for InvocationTarget<'_> {
    fn span(&self) -> Span {
        match self {
            InvocationTarget::Callable { span, .. } => *span,
            InvocationTarget::FunctionLike { span, .. } => *span,
        }
    }
}

impl HasSpan for InvocationArgumentsSource<'_, '_> {
    fn span(&self) -> Span {
        match self {
            InvocationArgumentsSource::ArgumentList(arg_list) => arg_list.span(),
            InvocationArgumentsSource::PipeInput(pipe) => pipe.span(),
            InvocationArgumentsSource::None(span) => *span,
            InvocationArgumentsSource::PartialArgumentList(partial_arg_list) => partial_arg_list.span(),
        }
    }
}

impl HasSpan for InvocationArgument<'_, '_> {
    fn span(&self) -> Span {
        match self {
            InvocationArgument::PipedValue(expr) => expr.span(),
            InvocationArgument::Positional(pos_arg) => pos_arg.span(),
            InvocationArgument::Named(named_arg) => named_arg.span(),
            InvocationArgument::Placeholder(placeholder) => placeholder.span(),
            InvocationArgument::NamedPlaceholder(named_placeholder) => named_placeholder.span(),
            InvocationArgument::VariadicPlaceholder(variadic_placeholder) => variadic_placeholder.span(),
        }
    }
}