mago-analyzer 1.21.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
use mago_atom::AtomMap;
use mago_atom::ascii_lowercase_atom;
use mago_codex::identifier::function_like::FunctionLikeIdentifier;
use mago_codex::ttype::atomic::TAtomic;
use mago_codex::ttype::atomic::callable::TCallable;
use mago_codex::ttype::expander::get_signature_of_function_like_identifier;
use mago_codex::ttype::get_mixed_closure;
use mago_codex::ttype::get_never;
use mago_codex::ttype::template::TemplateResult;
use mago_codex::ttype::union::TUnion;
use mago_span::HasSpan;
use mago_syntax::ast::MethodPartialApplication;

use crate::analyzable::Analyzable;
use crate::artifacts::AnalysisArtifacts;
use crate::context::Context;
use crate::context::block::BlockContext;
use crate::error::AnalysisError;
use crate::expression::partial_application::create_closure_from_partial_application;
use crate::invocation::Invocation;
use crate::invocation::InvocationArgumentsSource;
use crate::invocation::InvocationTarget;
use crate::invocation::InvocationTargetParameter;
use crate::invocation::MethodTargetContext;
use crate::invocation::analyzer::analyze_invocation;
use crate::resolver::method::resolve_method_targets;

impl<'ast, 'arena> Analyzable<'ast, 'arena> for MethodPartialApplication<'arena> {
    fn analyze<'ctx>(
        &'ast self,
        context: &mut Context<'ctx, 'arena>,
        block_context: &mut BlockContext<'ctx>,
        artifacts: &mut AnalysisArtifacts,
    ) -> Result<(), AnalysisError> {
        let method_resolution =
            resolve_method_targets(context, block_context, artifacts, self.object, &self.method, false, self.span())?;

        let mut identifiers = vec![];
        for resolved_method in &method_resolution.resolved_methods {
            let class_name = ascii_lowercase_atom(resolved_method.method_identifier.get_class_name().as_ref());
            let method_name = resolved_method.method_identifier.get_method_name();
            artifacts.symbol_references.add_reference_to_class_member(
                &block_context.scope,
                (class_name, method_name),
                false,
            );

            identifiers.push(FunctionLikeIdentifier::Method(
                resolved_method.method_identifier.get_class_name(),
                resolved_method.method_identifier.get_method_name(),
            ));
        }

        let resulting_type = if self.argument_list.is_first_class_callable() {
            if identifiers.is_empty() {
                if method_resolution.has_invalid_target { get_never() } else { get_mixed_closure() }
            } else {
                TUnion::from_vec(
                    identifiers.into_iter().map(|identifier| TAtomic::Callable(TCallable::Alias(identifier))).collect(),
                )
            }
        } else {
            let mut closure_types = Vec::new();
            for resolved_method in method_resolution.resolved_methods {
                let identifier = FunctionLikeIdentifier::Method(
                    resolved_method.method_identifier.get_class_name(),
                    resolved_method.method_identifier.get_method_name(),
                );

                let Some(signature) = get_signature_of_function_like_identifier(&identifier, context.codebase) else {
                    continue;
                };

                let Some(method_metadata) = context.codebase.get_function_like(&identifier) else {
                    continue;
                };

                let class_metadata = context
                    .codebase
                    .get_class_like(&resolved_method.classname)
                    .expect("class-like metadata should exist for resolved method");

                let method_target_context = MethodTargetContext {
                    declaring_method_id: Some(resolved_method.method_identifier),
                    class_like_metadata: class_metadata,
                    class_type: resolved_method.static_class_type,
                };

                let original_parameters: Vec<_> =
                    method_metadata.parameters.iter().map(InvocationTargetParameter::FunctionLike).collect();

                let invocation_target = InvocationTarget::FunctionLike {
                    identifier,
                    metadata: method_metadata,
                    inferred_return_type: None,
                    method_context: Some(method_target_context),
                    span: self.method.span(),
                };

                let invocation = Invocation::new(
                    invocation_target,
                    InvocationArgumentsSource::PartialArgumentList(&self.argument_list),
                    self.span(),
                );

                let mut template_result = TemplateResult::default();
                let mut parameter_types = AtomMap::default();

                analyze_invocation(
                    context,
                    block_context,
                    artifacts,
                    &invocation,
                    Some((resolved_method.classname, None)),
                    &mut template_result,
                    &mut parameter_types,
                )?;

                closure_types.push(create_closure_from_partial_application(
                    &signature,
                    &self.argument_list,
                    &original_parameters,
                    &template_result,
                    context.codebase,
                ));
            }

            if closure_types.is_empty() {
                if method_resolution.has_invalid_target { get_never() } else { get_mixed_closure() }
            } else {
                TUnion::from_vec(closure_types)
            }
        };

        artifacts.set_expression_type(self, resulting_type);

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use crate::code::IssueCode;
    use crate::test_analysis;
    use indoc::indoc;

    test_analysis! {
        name = method_closure_creation_happy_path,
        code = indoc! {r#"
            <?php
            class Greeter {
                public function greet(string $name): string {
                    return "Hello, " . $name;
                }
            }

            /** @param (callable(string):string) $cb */
            function call_it(callable $cb): void {
                echo $cb("World");
            }

            $greeter = new Greeter();
            $closure = $greeter->greet(...);
            call_it($closure);
        "#},
        issues = []
    }

    test_analysis! {
        name = method_closure_creation_on_non_object,
        code = indoc! {r#"
            <?php
            $my_string = "hello";
            $closure = $my_string->method(...);
        "#},
        issues = [
            IssueCode::InvalidMethodAccess,
            IssueCode::ImpossibleAssignment,
        ]
    }

    test_analysis! {
        name = method_closure_creation_on_ambiguous_object,
        code = indoc! {r"
            <?php
            /** @param object $obj */
            function test($obj) {
                $_closure = $obj->method(...);
            }
        "},
        issues = [
            IssueCode::AmbiguousObjectMethodAccess,
        ]
    }

    test_analysis! {
        name = method_closure_creation_basic_happy_path,
        code = indoc! {r#"
            <?php
            class Greeter {
                public function greet(string $name): string {
                    return "Hello, " . $name;
                }
            }
            /** @param callable(string):string $cb */
            function call_it(callable $cb): void {
                echo $cb("World");
            }

            $greeter = new Greeter();
            $closure = $greeter->greet(...);
            call_it($closure);
        "#},
        issues = []
    }

    test_analysis! {
        name = method_closure_creation_from_parent_method,
        code = indoc! {r#"
            <?php
            class ParentGreeter {
                public function say_hi(): string { return "hi"; }
            }

            class ChildGreeter extends ParentGreeter {}

            /** @param callable():string $_cb */
            function call_it(callable $_cb): void {}

            $greeter = new ChildGreeter();
            $closure = $greeter->say_hi(...);
            call_it($closure);
        "#},
    }

    test_analysis! {
        name = method_closure_creation_from_interface_method,
        code = indoc! {r"
            <?php
            interface Logger { public function log(string $message): void; }
            class FileLogger implements Logger {
                public function log(string $message): void {}
            }

            /** @param callable(string):void $_cb */
            function call_it(callable $_cb): void {}

            $logger = new FileLogger();
            $closure = $logger->log(...);
            call_it($closure);
        "},
    }

    test_analysis! {
        name = method_closure_creation_with_dynamic_literal_string_name,
        code = indoc! {r#"
            <?php
            class DynamicCaller {
                public function method(): int { return 1; }
            }

            /** @param callable():int $_cb */
            function call_it(callable $_cb): void {}

            $obj = new DynamicCaller();
            $method = "method";
            $closure = $obj->{$method}(...);
            call_it($closure);
        "#},
        issues = []
    }

    test_analysis! {
        name = method_closure_creation_non_existent_method,
        code = indoc! {r"
            <?php
            class MyClass {}
            $obj = new MyClass();
            $closure = $obj->undefinedMethod(...);
        "},
        issues = [
            IssueCode::NonExistentMethod,
            IssueCode::ImpossibleAssignment,
        ]
    }

    test_analysis! {
        name = method_closure_creation_on_non_object_type,
        code = indoc! {r#"
            <?php
            $my_string = "hello";
            $closure = $my_string->method(...);
        "#},
        issues = [
            IssueCode::InvalidMethodAccess,
            IssueCode::ImpossibleAssignment,
        ]
    }

    test_analysis! {
        name = method_closure_creation_on_definitely_null,
        code = indoc! {r"
            <?php
            $obj = null;
            $closure = $obj->method(...);
        "},
        issues = [
            IssueCode::MethodAccessOnNull,
            IssueCode::ImpossibleAssignment,
        ]
    }

    test_analysis! {
        name = method_closure_creation_on_possibly_null_object,
        code = indoc! {r"
            <?php
            class MyClass { public function method(): void {} }
            /** @param MyClass|null $obj */
            function test($obj) {
                $_closure = $obj->method(...);
            }
        "},
        issues = [
            IssueCode::PossibleMethodAccessOnNull,
        ]
    }

    test_analysis! {
        name = method_closure_creation_on_mixed_type,
        code = indoc! {r"
            <?php
            /** @param mixed $obj */
            function test($obj) {
                $_closure = $obj->method(...);
            }
        "},
        issues = [
            IssueCode::MixedMethodAccess,
        ]
    }

    test_analysis! {
        name = method_closure_creation_on_generic_object,
        code = indoc! {r"
            <?php
            /** @param object $obj */
            function test($obj) {
                $_closure = $obj->method(...);
            }
        "},
        issues = [
            IssueCode::AmbiguousObjectMethodAccess,
        ]
    }

    test_analysis! {
        name = method_closure_creation_with_string_name,
        code = indoc! {r#"
            <?php
            class DynamicCaller {
                public function method_foo(): int { return 1; }
            }
            $obj = new DynamicCaller();
            $methodName = "method" . "_foo"; // non-literal string

            $_closure = $obj->{$methodName}(...);
        "#},
    }

    test_analysis! {
        name = method_closure_creation_with_invalid_selector_type,
        code = indoc! {r"
            <?php
            class DynamicCaller {
                public function methodA(): int { return 1; }
            }
            $obj = new DynamicCaller();
            $methodName = 123;
            $_closure = $obj->{$methodName}(...);
        "},
        issues = [
            IssueCode::InvalidMemberSelector,
            IssueCode::ImpossibleAssignment,
        ]
    }

    test_analysis! {
        name = method_closure_creation_on_union_of_object_and_non_object,
        code = indoc! {r"
            <?php

            class MyClass { public function method(): void {} }

            function test(MyClass|int $val) {
                $_closure = $val->method(...);
            }
        "},
        issues = [
            IssueCode::InvalidMethodAccess,
        ]
    }

    test_analysis! {
        name = method_closure_creation_on_union_where_one_lacks_method,
        code = indoc! {r"
            <?php
            class ClassA { public function thing(): void {} }
            class ClassB { /* has no thing method */ }

            function test(ClassA|ClassB $obj) {
                $_closure = $obj->thing(...);
            }
        "},
        issues = [
            IssueCode::NonExistentMethod,
        ]
    }
}