Skip to main content

mago_codex/metadata/
constant.rs

1use mago_php_version::PHPVersion;
2use mago_php_version::PHPVersionRange;
3use serde::Deserialize;
4use serde::Serialize;
5
6use mago_reporting::Issue;
7use mago_span::HasSpan;
8use mago_span::Span;
9use mago_word::Word;
10
11use crate::metadata::attribute::AttributeMetadata;
12use crate::metadata::flags::MetadataFlags;
13use crate::metadata::ttype::TypeMetadata;
14use crate::metadata::version_constraint::VersionConstraint;
15use crate::ttype::union::TUnion;
16
17/// Contains metadata associated with a global constant defined using `const`.
18///
19/// Represents a single constant declaration item, potentially within a grouped declaration,
20/// like `MAX_RETRIES = 3` in `const MAX_RETRIES = 3;` or `B = 2` in `const A = 1, B = 2;`.
21#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
22#[non_exhaustive]
23pub struct ConstantMetadata {
24    pub attributes: Vec<AttributeMetadata>,
25    pub name: Word,
26    pub span: Span,
27    pub type_metadata: Option<TypeMetadata>,
28    pub inferred_type: Option<TUnion>,
29    pub flags: MetadataFlags,
30    pub issues: Vec<Issue>,
31    pub version_constraint: VersionConstraint,
32}
33
34impl ConstantMetadata {
35    /// Creates new `ConstantMetadata` for a non-deprecated, non-internal global constant item.
36    ///
37    /// # Arguments
38    ///
39    /// * `name`: The identifier (name) of the constant.
40    /// * `span`: The source code location of this specific constant's definition item (`NAME = value`).
41    #[inline]
42    #[must_use]
43    pub fn new(name: Word, span: Span, flags: MetadataFlags) -> Self {
44        Self {
45            attributes: Vec::new(),
46            name,
47            span,
48            flags,
49            type_metadata: None,
50            inferred_type: None,
51            issues: Vec::new(),
52            version_constraint: VersionConstraint::unconstrained(),
53        }
54    }
55
56    /// Returns a mutable slice of docblock issues.
57    #[inline]
58    pub fn take_issues(&mut self) -> Vec<Issue> {
59        std::mem::take(&mut self.issues)
60    }
61
62    /// Returns `true` when this constant is available in the given PHP version.
63    #[inline]
64    #[must_use]
65    pub fn is_available_in_version(&self, version: PHPVersion) -> bool {
66        self.version_constraint.allows_version(version)
67    }
68
69    /// Returns `true` when this constant is available across the entire
70    /// supplied [`PHPVersionRange`].
71    #[inline]
72    #[must_use]
73    pub fn is_available_in_version_range(&self, range: PHPVersionRange) -> bool {
74        self.version_constraint.allows_version_range(range)
75    }
76}
77
78impl HasSpan for ConstantMetadata {
79    fn span(&self) -> Span {
80        self.span
81    }
82}