mago_reflection/
attribute.rs

1use serde::Deserialize;
2use serde::Serialize;
3
4use mago_source::HasSource;
5use mago_source::SourceIdentifier;
6use mago_span::HasSpan;
7use mago_span::Span;
8
9use crate::identifier::Name;
10use crate::r#type::TypeReflection;
11
12/// Represents an attribute applied to a class, function, or other PHP constructs.
13///
14/// Attributes provide metadata for the construct they are applied to, often used
15/// for annotations or configuration in frameworks and libraries.
16///
17/// Example:
18///
19/// ```php
20/// #[Foo, Bar]
21/// class Example {}
22/// ```
23#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize, PartialOrd, Ord)]
24pub struct AttributeReflection {
25    /// The name of the attribute.
26    pub name: Name,
27
28    /// Optional list of arguments provided to the attribute.
29    pub arguments: Option<AttributeArgumentListReflection>,
30
31    /// The span of the attribute in the source code.
32    pub span: Span,
33}
34
35/// Represents a list of arguments for an attribute.
36#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize, PartialOrd, Ord)]
37pub struct AttributeArgumentListReflection {
38    /// The list of arguments for the attribute.
39    pub arguments: Vec<AttributeArgumentReflection>,
40}
41
42/// Represents a single argument in an attribute.
43///
44/// Arguments can either be positional (e.g., `#[Foo("value")]`) or named (e.g., `#[Foo(name: "value")]`).
45#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize, PartialOrd, Ord)]
46pub enum AttributeArgumentReflection {
47    /// A positional argument, such as `#[Foo("value")]`.
48    Positional {
49        /// The type reflection of the argument's value.
50        value_type_reflection: TypeReflection,
51
52        /// The span of the argument in the source code.
53        span: Span,
54    },
55
56    /// A named argument, such as `#[Foo(name: "value")]`.
57    Named {
58        /// The name of the argument.
59        name: Name,
60
61        /// The type reflection of the argument's value.
62        value_type_reflection: TypeReflection,
63
64        /// The span of the argument in the source code.
65        span: Span,
66    },
67}
68
69impl HasSource for AttributeReflection {
70    /// Returns the source identifier of the file containing this attribute.
71    fn source(&self) -> SourceIdentifier {
72        self.span.source()
73    }
74}
75
76impl HasSpan for AttributeReflection {
77    /// Returns the span of the attribute in the source code.
78    ///
79    /// This includes the entire range of the attribute, including its arguments if present.
80    fn span(&self) -> Span {
81        self.span
82    }
83}