Skip to main content

mago_codex/metadata/
function_like.rs

1use std::collections::BTreeMap;
2
3use mago_php_version::PHPVersion;
4use mago_php_version::PHPVersionRange;
5
6use mago_reporting::Annotation;
7use mago_reporting::Issue;
8use mago_span::Span;
9use mago_word::Word;
10use mago_word::WordMap;
11use mago_word::WordSet;
12
13use crate::assertion::Assertion;
14use crate::issue::ScanningIssueKind;
15use crate::metadata::attribute::AttributeMetadata;
16use crate::metadata::class_like::TemplateTypes;
17use crate::metadata::flags::MetadataFlags;
18use crate::metadata::parameter::FunctionLikeParameterMetadata;
19use crate::metadata::patch::PATCHABLE_FUNCTION_DOCBLOCK_FLAGS;
20use crate::metadata::patch::merge_explicit_docblock_flags;
21use crate::metadata::ttype::TypeMetadata;
22use crate::metadata::version_constraint::VersionConstraint;
23use crate::ttype::resolution::TypeResolutionContext;
24use crate::ttype::template::GenericTemplate;
25use crate::visibility::Visibility;
26
27/// Contains metadata specific to methods defined within classes, interfaces, enums, or traits.
28///
29/// This complements the more general `FunctionLikeMetadata`.
30#[derive(Debug, Clone, PartialEq, Eq, Default)]
31#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
32#[non_exhaustive]
33pub struct MethodMetadata {
34    /// Marks whether this method is declared as `final`, preventing further overriding.
35    pub is_final: bool,
36
37    /// Marks whether this method is declared as `abstract`, requiring implementation in subclasses.
38    pub is_abstract: bool,
39
40    /// Marks whether this method is declared as `static`, allowing it to be called without an instance.
41    pub is_static: bool,
42
43    /// Marks whether this method is a constructor (`__construct`).
44    pub is_constructor: bool,
45
46    /// Marks whether this method is declared as `public`, `protected`, or `private`.
47    pub visibility: Visibility,
48
49    /// A map of constraints defined by `@where` docblock tags.
50    ///
51    /// The key is the name of a class-level template parameter (e.g., `T`), and the value
52    /// is the `TUnion` type constraint that `T` must satisfy for this specific method
53    /// to be considered callable.
54    pub where_constraints: WordMap<TypeMetadata>,
55
56    /// The type of `$this` after the call, from `@this-out` or `@self-out`.
57    pub this_out_type: Option<TypeMetadata>,
58}
59
60/// Distinguishes between different kinds of callable constructs in PHP.
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
62#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
63pub enum FunctionLikeKind {
64    /// Represents a standard function declared in the global scope or a namespace (`function foo() {}`).
65    Function,
66    /// Represents a method defined within a class, trait, enum, or interface (`class C { function bar() {} }`).
67    Method,
68    /// Represents an anonymous function created using `function() {}`.
69    Closure,
70    /// Represents an arrow function (short closure syntax) introduced in PHP 7.4 (`fn() => ...`).
71    ArrowFunction,
72}
73
74#[derive(Debug, Clone, PartialEq, Eq)]
75#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
76pub struct FunctionLikeMetadata {
77    /// The kind of function-like structure this metadata represents.
78    pub kind: FunctionLikeKind,
79
80    /// The source code location (span) covering the entire function/method/closure definition.
81    /// For closures/arrow functions, this covers the `function(...) { ... }` or `fn(...) => ...` part.
82    pub span: Span,
83
84    /// The lookup name of the function or method. For named functions and
85    /// methods this is the lowercased identifier (PHP-style case-insensitive
86    /// lookup); for closures and arrow functions it is the synthetic
87    /// `{closure:path:line:col}` word produced by
88    /// [`crate::build_synthetic_name`]. Always set.
89    /// Example: `processrequest`, `__construct`, `my_global_func`,
90    /// `{closure:src/foo.php:12:5}`.
91    pub name: Word,
92
93    /// The original-case name. Matches the source identifier for named
94    /// functions/methods, and matches [`Self::name`] verbatim for closures.
95    pub original_name: Word,
96
97    /// The specific source code location (span) of the function or method name identifier.
98    /// `None` if the function/method has no name (closures/arrow functions).
99    pub name_span: Option<Span>,
100
101    /// Ordered list of metadata for each parameter defined in the signature.
102    pub parameters: Vec<FunctionLikeParameterMetadata>,
103
104    /// The explicit return type declaration (type hint).
105    ///
106    /// Example: For `function getName(): string`, this holds metadata for `string`.
107    /// `None` if no return type is specified.
108    pub return_type_declaration_metadata: Option<TypeMetadata>,
109
110    /// The explicit return type declaration (type hint) or docblock type (`@return`).
111    ///
112    /// Example: For `function getName(): string`, this holds metadata for `string`,
113    /// or for ` /** @return string */ function getName() { .. }`, this holds metadata for `string`.
114    /// `None` if neither is specified.
115    pub return_type_metadata: Option<TypeMetadata>,
116
117    /// Generic type parameters (templates) defined for the function/method (e.g., `@template T`).
118    /// Stores the template name and its constraint (defining entity and bound type).
119    /// Example: `{ "T" => (GenericParent::FunctionLike(("funcName", "")), TUnion::object()) }`
120    pub template_types: TemplateTypes,
121
122    /// Attributes attached to the function/method/closure declaration (`#[Attribute] function foo() {}`).
123    pub attributes: Vec<AttributeMetadata>,
124
125    /// Specific metadata relevant only to methods (visibility, final, static, etc.).
126    /// This is `Some` if `kind` is `FunctionLikeKind::Method`, `None` otherwise.
127    pub method_metadata: Option<MethodMetadata>,
128
129    /// Contains context information needed for resolving types within this function's scope
130    /// (e.g., `use` statements, current namespace, class context). Often populated during analysis.
131    pub type_resolution_context: Option<TypeResolutionContext>,
132
133    /// A list of types that this function/method might throw, derived from `@throws` docblock tags
134    /// or inferred from `throw` statements within the body.
135    pub thrown_types: Vec<TypeMetadata>,
136
137    /// List of issues specifically related to parsing or interpreting this function's docblock.
138    pub issues: Vec<Issue>,
139
140    /// Assertions about parameter types or variable types that are guaranteed to be true
141    /// *after* this function/method returns normally. From `@psalm-assert`, `@phpstan-assert`, etc.
142    /// Maps variable/parameter name to a list of type assertions.
143    pub assertions: BTreeMap<Word, Vec<Assertion>>,
144
145    /// Assertions about parameter/variable types that are guaranteed to be true if this
146    /// function/method returns `true`. From `@psalm-assert-if-true`, etc.
147    pub if_true_assertions: BTreeMap<Word, Vec<Assertion>>,
148
149    /// Assertions about parameter/variable types that are guaranteed to be true if this
150    /// function/method returns `false`. From `@psalm-assert-if-false`, etc.
151    pub if_false_assertions: BTreeMap<Word, Vec<Assertion>>,
152
153    /// Set when the assertions in `if_true_assertions` / `if_false_assertions` were
154    /// auto-inferred from the body rather than declared explicitly via docblock. The
155    /// populator uses this to know it can safely override them with assertions
156    /// inherited from a parent method, so explicit contracts on a parent always win.
157    pub assertions_inferred: bool,
158
159    /// Names of variables this function/method imports from the global scope via a
160    /// `global $x;` statement anywhere in its body. Used by the invocation post-processor
161    /// to invalidate caller-side narrowings of those globals on every call, since the
162    /// callee can reassign them behind the caller's back.
163    pub globals_accessed: WordSet,
164
165    /// Tracks whether this function/method has a docblock comment.
166    /// Used to determine if docblock inheritance should occur implicitly.
167    pub has_docblock: bool,
168
169    pub flags: MetadataFlags,
170
171    #[cfg_attr(feature = "serde", serde(default))]
172    pub(crate) explicit_docblock_flags: MetadataFlags,
173
174    /// PHP version range in which this function-like is available, derived
175    /// from `Mago\AvailableSince` / `Mago\AvailableUntil` attributes during
176    /// scanning.
177    pub version_constraint: VersionConstraint,
178}
179
180impl FunctionLikeKind {
181    /// Checks if this kind represents a class/trait/enum/interface method.
182    #[inline]
183    #[must_use]
184    pub const fn is_method(&self) -> bool {
185        matches!(self, Self::Method)
186    }
187
188    /// Checks if this kind represents a globally/namespace-scoped function.
189    #[inline]
190    #[must_use]
191    pub const fn is_function(&self) -> bool {
192        matches!(self, Self::Function)
193    }
194
195    /// Checks if this kind represents an anonymous function (`function() {}`).
196    #[inline]
197    #[must_use]
198    pub const fn is_closure(&self) -> bool {
199        matches!(self, Self::Closure)
200    }
201
202    /// Checks if this kind represents an arrow function (`fn() => ...`).
203    #[inline]
204    #[must_use]
205    pub const fn is_arrow_function(&self) -> bool {
206        matches!(self, Self::ArrowFunction)
207    }
208}
209
210/// Contains comprehensive metadata for any function-like structure in PHP.
211impl FunctionLikeMetadata {
212    /// Creates new `FunctionLikeMetadata` with basic information and default flags.
213    ///
214    /// Pass the lookup `name` (lowercased identifier for named functions/methods,
215    /// synthetic `{closure:...}` word for closures) and `original_name` (source
216    /// casing for named items, identical to `name` for closures).
217    #[must_use]
218    pub fn new(kind: FunctionLikeKind, name: Word, original_name: Word, span: Span, flags: MetadataFlags) -> Self {
219        let method_metadata = if kind.is_method() { Some(MethodMetadata::default()) } else { None };
220
221        Self {
222            kind,
223            span,
224            flags,
225            name,
226            original_name,
227            name_span: None,
228            parameters: vec![],
229            return_type_declaration_metadata: None,
230            return_type_metadata: None,
231            template_types: TemplateTypes::default(),
232            attributes: vec![],
233            method_metadata,
234            type_resolution_context: None,
235            thrown_types: vec![],
236            assertions: BTreeMap::new(),
237            if_true_assertions: BTreeMap::new(),
238            if_false_assertions: BTreeMap::new(),
239            assertions_inferred: false,
240            globals_accessed: WordSet::default(),
241            has_docblock: false,
242            explicit_docblock_flags: MetadataFlags::empty(),
243            issues: vec![],
244            version_constraint: VersionConstraint::unconstrained(),
245        }
246    }
247
248    /// Returns `true` when this function-like is available in the given PHP
249    /// version.
250    #[inline]
251    #[must_use]
252    pub fn is_available_in_version(&self, version: PHPVersion) -> bool {
253        self.version_constraint.allows_version(version)
254    }
255
256    /// Returns `true` when this function-like is available across the entire
257    /// supplied [`PHPVersionRange`].
258    #[inline]
259    #[must_use]
260    pub fn is_available_in_version_range(&self, range: PHPVersionRange) -> bool {
261        self.version_constraint.allows_version_range(range)
262    }
263
264    /// Returns the kind of function-like (Function, Method, Closure, `ArrowFunction`).
265    #[inline]
266    #[must_use]
267    pub fn get_kind(&self) -> FunctionLikeKind {
268        self.kind
269    }
270
271    /// Returns a mutable slice of the parameter metadata.
272    #[inline]
273    pub fn get_parameters_mut(&mut self) -> &mut [FunctionLikeParameterMetadata] {
274        &mut self.parameters
275    }
276
277    /// Returns a reference to specific parameter metadata by name, if it exists.
278    #[inline]
279    #[must_use]
280    pub fn get_parameter(&self, name: Word) -> Option<&FunctionLikeParameterMetadata> {
281        self.parameters.iter().find(|parameter| parameter.get_name().0 == name)
282    }
283
284    /// Returns a mutable reference to specific parameter metadata by name, if it exists.
285    #[inline]
286    pub fn get_parameter_mut(&mut self, name: Word) -> Option<&mut FunctionLikeParameterMetadata> {
287        self.parameters.iter_mut().find(|parameter| parameter.get_name().0 == name)
288    }
289
290    /// Returns a slice of the attributes.
291    #[inline]
292    #[must_use]
293    pub fn get_attributes(&self) -> &[AttributeMetadata] {
294        &self.attributes
295    }
296
297    /// Returns a mutable reference to the method-specific info, if this is a method.
298    #[inline]
299    pub fn get_method_metadata_mut(&mut self) -> Option<&mut MethodMetadata> {
300        self.method_metadata.as_mut()
301    }
302
303    /// Returns a mutable slice of docblock issues.
304    #[inline]
305    pub fn take_issues(&mut self) -> Vec<Issue> {
306        std::mem::take(&mut self.issues)
307    }
308
309    /// Sets the parameters, replacing existing ones.
310    #[inline]
311    pub fn set_parameters(&mut self, parameters: impl IntoIterator<Item = FunctionLikeParameterMetadata>) {
312        self.parameters = parameters.into_iter().collect();
313    }
314
315    /// Returns a new instance with the parameters replaced.
316    #[inline]
317    #[must_use]
318    pub fn with_parameters(mut self, parameters: impl IntoIterator<Item = FunctionLikeParameterMetadata>) -> Self {
319        self.set_parameters(parameters);
320        self
321    }
322
323    #[inline]
324    pub fn set_return_type_metadata(&mut self, return_type: Option<TypeMetadata>) {
325        self.return_type_metadata = return_type;
326    }
327
328    #[inline]
329    pub fn set_return_type_declaration_metadata(&mut self, return_type: Option<TypeMetadata>) {
330        if self.return_type_metadata.is_none() {
331            self.return_type_metadata.clone_from(&return_type);
332        }
333
334        self.return_type_declaration_metadata = return_type;
335    }
336
337    /// Adds a single template type definition.
338    #[inline]
339    pub fn add_template_type(&mut self, name: Word, constraint: GenericTemplate) {
340        self.template_types.insert(name, constraint);
341    }
342
343    /// Applies a patch to this entry in place, refining type information and supported docblock flags.
344    ///
345    /// Refined fields — return type, per-parameter types, `@param-out`, default-value types,
346    /// `@throws`, `@template`, and assertions — are each copied only when the patch specifies
347    /// them, so a sparsely-typed patch never erases richer existing information. Structural
348    /// identity (span, file, kind, parameter count, visibility) is left to whichever non-patch
349    /// source declared the symbol. Diagnostics are appended to `patch.issues`; the full set of
350    /// patching rules is documented in the `[source]` patching guide.
351    pub fn apply_patch(&mut self, patch: &mut FunctionLikeMetadata) {
352        // A parameter count or name mismatch means types cannot be mapped positionally;
353        // reject the patch wholesale rather than risk a silent misapply.
354        if self.report_parameter_count_mismatch(patch) || self.report_parameter_name_mismatch(patch) {
355            return;
356        }
357
358        self.report_method_structural_mismatch(patch);
359
360        self.patch_return_type(patch);
361        self.patch_parameters(patch);
362        self.patch_templates(patch);
363        self.patch_throws_and_assertions(patch);
364        merge_explicit_docblock_flags(
365            &mut self.flags,
366            patch.flags,
367            patch.explicit_docblock_flags,
368            PATCHABLE_FUNCTION_DOCBLOCK_FLAGS,
369        );
370    }
371
372    /// Reports a parameter count mismatch between the patch and the original.
373    ///
374    /// Returns `true` when the counts differ, in which case the patch must be rejected
375    /// wholesale — there is no sensible positional mapping.
376    fn report_parameter_count_mismatch(&self, patch: &mut FunctionLikeMetadata) -> bool {
377        if patch.parameters.len() == self.parameters.len() {
378            return false;
379        }
380
381        patch.issues.push(
382            Issue::error(format!(
383                "Patch for `{}` declares {} parameter(s) but the original has {}; \
384                 patches cannot change the number of parameters.",
385                patch.original_name,
386                patch.parameters.len(),
387                self.parameters.len(),
388            ))
389            .with_code(ScanningIssueKind::PatchFunctionParameterMismatch)
390            .with_annotation(Annotation::primary(patch.span))
391            .with_help(format!(
392                "Declare exactly {} parameter(s) in the patch to match the original signature. \
393                 Patches refine parameter types only and cannot add or remove parameters.",
394                self.parameters.len(),
395            )),
396        );
397
398        true
399    }
400
401    /// Reports a parameter name mismatch at any position.
402    ///
403    /// Types are refined by position, so a name mismatch (a wrong order, or a patch drifted
404    /// out of sync with the vendor code) would apply them to the wrong parameter. Returns
405    /// `true` on the first mismatch so the patch is rejected wholesale.
406    fn report_parameter_name_mismatch(&self, patch: &mut FunctionLikeMetadata) -> bool {
407        for (index, (base_param, patch_param)) in self.parameters.iter().zip(patch.parameters.iter()).enumerate() {
408            if base_param.name != patch_param.name {
409                patch.issues.push(
410                    Issue::error(format!(
411                        "Patch for `{}` names parameter #{} `{}` but the original declares `{}` there; \
412                         patches refine parameter types by position and the names must match.",
413                        patch.original_name,
414                        index + 1,
415                        patch_param.name.0,
416                        base_param.name.0,
417                    ))
418                    .with_code(ScanningIssueKind::PatchFunctionParameterNameMismatch)
419                    .with_annotation(Annotation::primary(patch_param.name_span))
420                    .with_help(
421                        "Declare the patch's parameters with the same names in the same order as the \
422                         original signature so their types are applied to the intended parameters.",
423                    ),
424                );
425                return true;
426            }
427        }
428
429        false
430    }
431
432    /// Reports structural method-attribute mismatches.
433    ///
434    /// For methods, visibility, static, and removing final are all structural changes a patch
435    /// may not make. Adding final is allowed. This is reported as an error but does not abort
436    /// the patch — type annotations and supported docblock flags are still applied.
437    ///
438    /// `abstract` is deliberately excluded: it is implied by writing the method with a trailing
439    /// `;` instead of a `{}` body — the idiomatic form for a signature-only type patch — rather
440    /// than being an explicit modifier the author chose. The patch never changes the original's
441    /// abstractness either way, so a difference is harmless and would only produce a spurious
442    /// error for the natural patch syntax.
443    fn report_method_structural_mismatch(&self, patch: &mut FunctionLikeMetadata) {
444        let (Some(patch_m), Some(base_m)) = (&patch.method_metadata, &self.method_metadata) else {
445            return;
446        };
447
448        let visibility_mismatch = patch_m.visibility != base_m.visibility;
449        let static_mismatch = patch_m.is_static != base_m.is_static;
450        let final_removed = base_m.is_final && !patch_m.is_final;
451
452        if visibility_mismatch || static_mismatch || final_removed {
453            patch.issues.push(
454                Issue::error(format!(
455                    "Patch for `{}` declares structural attributes (visibility, static, or \
456                     removing final) that differ from the original; only type annotations are applied.",
457                    patch.original_name,
458                ))
459                .with_code(ScanningIssueKind::PatchMethodStructuralMismatch)
460                .with_annotation(Annotation::primary(patch.span))
461                .with_help(
462                    "Declare the method with the same visibility and the same `static` and \
463                     `final` modifiers as the original (adding `final` is allowed); \
464                     a patch may only refine the method's types.",
465                ),
466            );
467        }
468    }
469
470    /// Refines the return type (declaration and docblock) when the patch specifies it.
471    fn patch_return_type(&mut self, patch: &FunctionLikeMetadata) {
472        if let Some(decl) = &patch.return_type_declaration_metadata {
473            self.return_type_declaration_metadata = Some(decl.clone());
474        }
475        if let Some(ty) = &patch.return_type_metadata {
476            self.return_type_metadata = Some(ty.clone());
477        }
478    }
479
480    /// Refines per-parameter types by position; each field is copied only when the patch
481    /// specifies it, so a sparsely-typed patch does not erase richer existing information.
482    fn patch_parameters(&mut self, patch: &FunctionLikeMetadata) {
483        for (slot, replacement) in self.parameters.iter_mut().zip(patch.parameters.iter()) {
484            if let Some(decl) = &replacement.type_declaration_metadata {
485                slot.type_declaration_metadata = Some(decl.clone());
486            }
487            if let Some(ty) = &replacement.type_metadata {
488                slot.type_metadata = Some(ty.clone());
489            }
490            if let Some(out) = &replacement.out_type {
491                slot.out_type = Some(out.clone());
492            }
493            if let Some(default) = &replacement.default_type {
494                slot.default_type = Some(default.clone());
495            }
496        }
497    }
498
499    /// Merges `@template` declarations from the patch.
500    fn patch_templates(&mut self, patch: &FunctionLikeMetadata) {
501        if !patch.template_types.is_empty() {
502            self.template_types.extend(patch.template_types.iter().map(|(k, v)| (*k, v.clone())));
503        }
504    }
505
506    /// Replaces `@throws` and `@psalm-assert`-style annotations when the patch declares any.
507    fn patch_throws_and_assertions(&mut self, patch: &FunctionLikeMetadata) {
508        if !patch.thrown_types.is_empty() {
509            self.thrown_types.clone_from(&patch.thrown_types);
510        }
511        if !patch.assertions.is_empty() {
512            self.assertions = patch.assertions.clone();
513        }
514        if !patch.if_true_assertions.is_empty() {
515            self.if_true_assertions = patch.if_true_assertions.clone();
516        }
517        if !patch.if_false_assertions.is_empty() {
518            self.if_false_assertions = patch.if_false_assertions.clone();
519        }
520    }
521}