mago_codex/metadata/
function_like.rs

1use std::collections::BTreeMap;
2
3use serde::Deserialize;
4use serde::Serialize;
5
6use mago_atom::Atom;
7use mago_atom::AtomMap;
8use mago_reporting::Issue;
9use mago_span::Span;
10
11use crate::assertion::Assertion;
12use crate::metadata::attribute::AttributeMetadata;
13use crate::metadata::flags::MetadataFlags;
14use crate::metadata::parameter::FunctionLikeParameterMetadata;
15use crate::metadata::ttype::TypeMetadata;
16use crate::misc::GenericParent;
17use crate::ttype::resolution::TypeResolutionContext;
18use crate::ttype::union::TUnion;
19use crate::visibility::Visibility;
20
21pub type TemplateTuple = (Atom, Vec<(GenericParent, TUnion)>);
22
23/// Contains metadata specific to methods defined within classes, interfaces, enums, or traits.
24///
25/// This complements the more general `FunctionLikeMetadata`.
26#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
27pub struct MethodMetadata {
28    /// Marks whether this method is declared as `final`, preventing further overriding.
29    pub is_final: bool,
30
31    /// Marks whether this method is declared as `abstract`, requiring implementation in subclasses.
32    pub is_abstract: bool,
33
34    /// Marks whether this method is declared as `static`, allowing it to be called without an instance.
35    pub is_static: bool,
36
37    /// Marks whether this method is a constructor (`__construct`).
38    pub is_constructor: bool,
39
40    /// Marks whether this method is declared as `public`, `protected`, or `private`.
41    pub visibility: Visibility,
42
43    /// A map of constraints defined by `@where` docblock tags.
44    ///
45    /// The key is the name of a class-level template parameter (e.g., `T`), and the value
46    /// is the `TUnion` type constraint that `T` must satisfy for this specific method
47    /// to be considered callable.
48    pub where_constraints: AtomMap<TypeMetadata>,
49}
50
51/// Distinguishes between different kinds of callable constructs in PHP.
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
53pub enum FunctionLikeKind {
54    /// Represents a standard function declared in the global scope or a namespace (`function foo() {}`).
55    Function,
56    /// Represents a method defined within a class, trait, enum, or interface (`class C { function bar() {} }`).
57    Method,
58    /// Represents an anonymous function created using `function() {}`.
59    Closure,
60    /// Represents an arrow function (short closure syntax) introduced in PHP 7.4 (`fn() => ...`).
61    ArrowFunction,
62}
63
64#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
65pub struct FunctionLikeMetadata {
66    /// The kind of function-like structure this metadata represents.
67    pub kind: FunctionLikeKind,
68
69    /// The source code location (span) covering the entire function/method/closure definition.
70    /// For closures/arrow functions, this covers the `function(...) { ... }` or `fn(...) => ...` part.
71    pub span: Span,
72
73    /// The name of the function or method, lowercased, if applicable.
74    /// `None` for closures and arrow functions unless assigned to a variable later.
75    /// Example: `processRequest`, `__construct`, `my_global_func`.
76    pub name: Option<Atom>,
77
78    /// The original name of the function or method, in its original case.
79    pub original_name: Option<Atom>,
80
81    /// The specific source code location (span) of the function or method name identifier.
82    /// `None` if the function/method has no name (closures/arrow functions).
83    pub name_span: Option<Span>,
84
85    /// Ordered list of metadata for each parameter defined in the signature.
86    pub parameters: Vec<FunctionLikeParameterMetadata>,
87
88    /// The explicit return type declaration (type hint).
89    ///
90    /// Example: For `function getName(): string`, this holds metadata for `string`.
91    /// `None` if no return type is specified.
92    pub return_type_declaration_metadata: Option<TypeMetadata>,
93
94    /// The explicit return type declaration (type hint) or docblock type (`@return`).
95    ///
96    /// Example: For `function getName(): string`, this holds metadata for `string`,
97    /// or for ` /** @return string */ function getName() { .. }`, this holds metadata for `string`.
98    /// `None` if neither is specified.
99    pub return_type_metadata: Option<TypeMetadata>,
100
101    /// Generic type parameters (templates) defined for the function/method (e.g., `@template T`).
102    /// Stores the template name and its constraints (parent type and bound type).
103    /// Example: `[("T", [(GenericParent::Function("funcName"), Arc<TUnion::object()>)])]`
104    pub template_types: Vec<TemplateTuple>,
105
106    /// Attributes attached to the function/method/closure declaration (`#[Attribute] function foo() {}`).
107    pub attributes: Vec<AttributeMetadata>,
108
109    /// Specific metadata relevant only to methods (visibility, final, static, etc.).
110    /// This is `Some` if `kind` is `FunctionLikeKind::Method`, `None` otherwise.
111    pub method_metadata: Option<MethodMetadata>,
112
113    /// Contains context information needed for resolving types within this function's scope
114    /// (e.g., `use` statements, current namespace, class context). Often populated during analysis.
115    pub type_resolution_context: Option<TypeResolutionContext>,
116
117    /// A list of types that this function/method might throw, derived from `@throws` docblock tags
118    /// or inferred from `throw` statements within the body.
119    pub thrown_types: Vec<TypeMetadata>,
120
121    /// List of issues specifically related to parsing or interpreting this function's docblock.
122    pub issues: Vec<Issue>,
123
124    /// Assertions about parameter types or variable types that are guaranteed to be true
125    /// *after* this function/method returns normally. From `@psalm-assert`, `@phpstan-assert`, etc.
126    /// Maps variable/parameter name to a list of type assertions.
127    pub assertions: BTreeMap<Atom, Vec<Assertion>>,
128
129    /// Assertions about parameter/variable types that are guaranteed to be true if this
130    /// function/method returns `true`. From `@psalm-assert-if-true`, etc.
131    pub if_true_assertions: BTreeMap<Atom, Vec<Assertion>>,
132
133    /// Assertions about parameter/variable types that are guaranteed to be true if this
134    /// function/method returns `false`. From `@psalm-assert-if-false`, etc.
135    pub if_false_assertions: BTreeMap<Atom, Vec<Assertion>>,
136
137    /// Tracks whether this function/method has a docblock comment.
138    /// Used to determine if docblock inheritance should occur implicitly.
139    pub has_docblock: bool,
140
141    pub flags: MetadataFlags,
142}
143
144impl FunctionLikeKind {
145    /// Checks if this kind represents a class/trait/enum/interface method.
146    #[inline]
147    #[must_use]
148    pub const fn is_method(&self) -> bool {
149        matches!(self, Self::Method)
150    }
151
152    /// Checks if this kind represents a globally/namespace-scoped function.
153    #[inline]
154    #[must_use]
155    pub const fn is_function(&self) -> bool {
156        matches!(self, Self::Function)
157    }
158
159    /// Checks if this kind represents an anonymous function (`function() {}`).
160    #[inline]
161    #[must_use]
162    pub const fn is_closure(&self) -> bool {
163        matches!(self, Self::Closure)
164    }
165
166    /// Checks if this kind represents an arrow function (`fn() => ...`).
167    #[inline]
168    #[must_use]
169    pub const fn is_arrow_function(&self) -> bool {
170        matches!(self, Self::ArrowFunction)
171    }
172}
173
174/// Contains comprehensive metadata for any function-like structure in PHP.
175impl FunctionLikeMetadata {
176    /// Creates new `FunctionLikeMetadata` with basic information and default flags.
177    #[must_use]
178    pub fn new(kind: FunctionLikeKind, span: Span, flags: MetadataFlags) -> Self {
179        let method_metadata = if kind.is_method() { Some(MethodMetadata::default()) } else { None };
180
181        Self {
182            kind,
183            span,
184            flags,
185            name: None,
186            original_name: None,
187            name_span: None,
188            parameters: vec![],
189            return_type_declaration_metadata: None,
190            return_type_metadata: None,
191            template_types: vec![],
192            attributes: vec![],
193            method_metadata,
194            type_resolution_context: None,
195            thrown_types: vec![],
196            assertions: BTreeMap::new(),
197            if_true_assertions: BTreeMap::new(),
198            if_false_assertions: BTreeMap::new(),
199            has_docblock: false,
200            issues: vec![],
201        }
202    }
203
204    /// Returns the kind of function-like (Function, Method, Closure, `ArrowFunction`).
205    #[inline]
206    #[must_use]
207    pub fn get_kind(&self) -> FunctionLikeKind {
208        self.kind
209    }
210
211    /// Returns a mutable slice of the parameter metadata.
212    #[inline]
213    pub fn get_parameters_mut(&mut self) -> &mut [FunctionLikeParameterMetadata] {
214        &mut self.parameters
215    }
216
217    /// Returns a reference to specific parameter metadata by name, if it exists.
218    #[inline]
219    #[must_use]
220    pub fn get_parameter(&self, name: Atom) -> Option<&FunctionLikeParameterMetadata> {
221        self.parameters.iter().find(|parameter| parameter.get_name().0 == name)
222    }
223
224    /// Returns a mutable reference to specific parameter metadata by name, if it exists.
225    #[inline]
226    pub fn get_parameter_mut(&mut self, name: Atom) -> Option<&mut FunctionLikeParameterMetadata> {
227        self.parameters.iter_mut().find(|parameter| parameter.get_name().0 == name)
228    }
229
230    /// Returns a mutable slice of the template type parameters.
231    #[inline]
232    pub fn get_template_types_mut(&mut self) -> &mut [TemplateTuple] {
233        &mut self.template_types
234    }
235
236    /// Returns a slice of the attributes.
237    #[inline]
238    #[must_use]
239    pub fn get_attributes(&self) -> &[AttributeMetadata] {
240        &self.attributes
241    }
242
243    /// Returns a mutable reference to the method-specific info, if this is a method.
244    #[inline]
245    pub fn get_method_metadata_mut(&mut self) -> Option<&mut MethodMetadata> {
246        self.method_metadata.as_mut()
247    }
248
249    /// Returns a mutable slice of docblock issues.
250    #[inline]
251    pub fn take_issues(&mut self) -> Vec<Issue> {
252        std::mem::take(&mut self.issues)
253    }
254
255    /// Sets the parameters, replacing existing ones.
256    #[inline]
257    pub fn set_parameters(&mut self, parameters: impl IntoIterator<Item = FunctionLikeParameterMetadata>) {
258        self.parameters = parameters.into_iter().collect();
259    }
260
261    /// Returns a new instance with the parameters replaced.
262    #[inline]
263    pub fn with_parameters(mut self, parameters: impl IntoIterator<Item = FunctionLikeParameterMetadata>) -> Self {
264        self.set_parameters(parameters);
265        self
266    }
267
268    #[inline]
269    pub fn set_return_type_metadata(&mut self, return_type: Option<TypeMetadata>) {
270        self.return_type_metadata = return_type;
271    }
272
273    #[inline]
274    pub fn set_return_type_declaration_metadata(&mut self, return_type: Option<TypeMetadata>) {
275        if self.return_type_metadata.is_none() {
276            self.return_type_metadata.clone_from(&return_type);
277        }
278
279        self.return_type_declaration_metadata = return_type;
280    }
281
282    /// Adds a single template type definition.
283    #[inline]
284    pub fn add_template_type(&mut self, template: TemplateTuple) {
285        self.template_types.push(template);
286    }
287
288    /// Determines if this function/method needs docblock inheritance.
289    ///
290    /// Returns `true` if:
291    /// - The method has an explicit `@inheritDoc` or `@inheritDocs` tag (`INHERITS_DOCS` flag set), OR
292    /// - The method has NO docblock at all (implicit inheritance)
293    ///
294    /// Returns `false` otherwise (method has a docblock but no @inheritDoc).
295    #[inline]
296    #[must_use]
297    pub fn needs_docblock_inheritance(&self) -> bool {
298        self.flags.contains(MetadataFlags::INHERITS_DOCS) || !self.has_docblock
299    }
300}