Skip to main content

mago_codex/metadata/
parameter.rs

1use mago_span::HasSpan;
2use mago_span::Span;
3
4use crate::metadata::attribute::AttributeMetadata;
5use crate::metadata::flags::MetadataFlags;
6use crate::metadata::ttype::TypeMetadata;
7use crate::misc::VariableIdentifier;
8use crate::ttype::atomic::TAtomic;
9
10/// Contains metadata associated with a single parameter within a function, method, or closure signature.
11///
12/// This captures details like the parameter's name, type hint, attributes, default value,
13/// pass-by-reference status, variadic nature, and other PHP features like property promotion.
14#[derive(Debug, Clone, PartialEq, Eq, Hash)]
15#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
16#[non_exhaustive]
17pub struct FunctionLikeParameterMetadata {
18    /// Attributes attached to the parameter declaration.
19    pub attributes: Vec<AttributeMetadata>,
20
21    /// The identifier (name) of the parameter, including the leading '$'.
22    pub name: VariableIdentifier,
23
24    /// The native type declaration from the function signature.
25    ///
26    /// This is the type hint specified in the code (e.g., `string $name`), not from docblocks.
27    /// Can be `None` if no type hint is specified in the signature.
28    pub type_declaration_metadata: Option<TypeMetadata>,
29
30    /// The explicit type declaration (type hint) or docblock type (`@param`).
31    ///
32    /// If there's a docblock `@param` annotation, this will contain that type (with `from_docblock=true`).
33    /// Otherwise, this will be the same as `type_declaration_metadata`.
34    /// Can be `None` if no type is specified.
35    pub type_metadata: Option<TypeMetadata>,
36
37    /// The type specified by a `@param-out` docblock tag.
38    ///
39    /// This indicates the expected type of a pass-by-reference parameter *after* the function executes.
40    pub out_type: Option<TypeMetadata>,
41
42    /// The type specified by a `@param-closure-this` docblock tag.
43    ///
44    /// When this parameter receives a closure, that closure is invoked with `$this` bound to an
45    /// instance of this type. A closure literal passed here is analyzed with `$this` set accordingly.
46    pub closure_this_type: Option<TypeMetadata>,
47
48    /// The inferred type of the parameter's default value, if `has_default` is true and the
49    /// type could be determined.
50    ///
51    /// `None` if there is no default or the default value's type couldn't be inferred.
52    pub default_type: Option<TypeMetadata>,
53
54    /// The source code location (span) covering the entire parameter declaration.
55    pub span: Span,
56
57    /// The specific source code location (span) of the parameter's name identifier.
58    pub name_span: Span,
59
60    /// Flags indicating various properties of the parameter.
61    pub flags: MetadataFlags,
62}
63
64/// Contains metadata associated with a single parameter within a function, method, or closure signature.
65///
66/// This captures details like the parameter's name, type hint, attributes, default value,
67/// pass-by-reference status, variadic nature, and other PHP features like property promotion.
68impl FunctionLikeParameterMetadata {
69    /// Creates new `FunctionLikeParameterMetadata` for a basic parameter.
70    /// Initializes most flags to false and optional fields to None.
71    ///
72    /// # Arguments
73    ///
74    /// * `name`: The identifier (name) of the parameter (e.g., `$userId`).
75    /// * `span`: The source code location covering the entire parameter declaration.
76    /// * `name_span`: The source code location of the parameter's name identifier (`$userId`).
77    #[must_use]
78    pub fn new(name: VariableIdentifier, span: Span, name_span: Span, flags: MetadataFlags) -> Self {
79        Self {
80            attributes: Vec::new(),
81            name,
82            flags,
83            span,
84            name_span,
85            type_declaration_metadata: None,
86            type_metadata: None,
87            out_type: None,
88            closure_this_type: None,
89            default_type: None,
90        }
91    }
92
93    /// Returns a reference to the parameter's name identifier (e.g., `$userId`).
94    #[inline]
95    #[must_use]
96    pub fn get_name(&self) -> &VariableIdentifier {
97        &self.name
98    }
99
100    /// Returns the span covering the entire parameter declaration.
101    #[inline]
102    #[must_use]
103    pub fn get_span(&self) -> Span {
104        self.span
105    }
106
107    /// Returns the span covering the parameter's name identifier.
108    #[inline]
109    #[must_use]
110    pub fn get_name_span(&self) -> Span {
111        self.name_span
112    }
113
114    /// Returns a reference to the parameter's type metadata (effective type with docblock).
115    #[inline]
116    #[must_use]
117    pub fn get_type_metadata(&self) -> Option<&TypeMetadata> {
118        self.type_metadata.as_ref()
119    }
120
121    /// Returns a reference to the parameter's native type declaration metadata.
122    #[inline]
123    #[must_use]
124    pub fn get_type_declaration_metadata(&self) -> Option<&TypeMetadata> {
125        self.type_declaration_metadata.as_ref()
126    }
127
128    /// Returns a reference to the inferred type of the default value, if known.
129    #[inline]
130    #[must_use]
131    pub fn get_default_type(&self) -> Option<&TypeMetadata> {
132        self.default_type.as_ref()
133    }
134
135    /// Sets the attributes, replacing any existing ones.
136    pub fn set_attributes(&mut self, attributes: impl IntoIterator<Item = AttributeMetadata>) {
137        self.attributes = attributes.into_iter().collect();
138    }
139
140    /// Returns a new instance with the attributes replaced.
141    #[must_use]
142    pub fn with_attributes(mut self, attributes: impl IntoIterator<Item = AttributeMetadata>) -> Self {
143        self.set_attributes(attributes);
144        self
145    }
146
147    /// Sets the parameter's type metadata (effective type with docblock).
148    #[inline]
149    pub fn set_type_metadata(&mut self, type_metadata: Option<TypeMetadata>) {
150        self.type_metadata = type_metadata;
151    }
152
153    /// Sets the parameter's native type declaration metadata.
154    ///
155    /// If `type_metadata` is not set, it will be initialized with the same value.
156    #[inline]
157    pub fn set_type_declaration_metadata(&mut self, type_declaration: Option<TypeMetadata>) {
158        if self.type_metadata.is_none() {
159            self.type_metadata.clone_from(&type_declaration);
160        }
161
162        self.type_declaration_metadata = type_declaration;
163    }
164
165    /// Adds `null` to a docblock-only type when the parameter defaults to `null`.
166    ///
167    /// `@param string $x` with `$x = null` accepts `null`, the same way PHP makes a native
168    /// `string $x = null` nullable. This does not depend on the PHP version, because an
169    /// untyped parameter can default to `null` on every version.
170    ///
171    /// A parameter with a native type is left alone. The scanner makes that native type
172    /// nullable where PHP does, and a docblock type keeps the `null` when merged with it.
173    pub fn add_null_from_null_default(&mut self) {
174        if self.type_declaration_metadata.is_some()
175            || !self.default_type.as_ref().is_some_and(|default_type| default_type.type_union.is_null())
176        {
177            return;
178        }
179
180        let Some(type_metadata) = self.type_metadata.as_mut() else {
181            return;
182        };
183
184        if type_metadata.type_union.accepts_null() || type_metadata.type_union.types.iter().any(TAtomic::is_conditional)
185        {
186            return;
187        }
188
189        type_metadata.type_union = type_metadata.type_union.clone().as_nullable();
190    }
191}
192
193impl HasSpan for FunctionLikeParameterMetadata {
194    fn span(&self) -> Span {
195        self.span
196    }
197}