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