Skip to main content

mago_syntax/cst/cst/
variable.rs

1use strum::Display;
2
3use mago_span::HasSpan;
4use mago_span::Span;
5
6use crate::cst::cst::expression::Expression;
7
8/// Represents a variable.
9///
10/// # Examples
11///
12/// ```php
13/// $foo
14/// ${foo}
15/// $$foo
16/// ```
17#[derive(Debug, Clone, Eq, PartialEq, Hash, PartialOrd, Ord, Display)]
18#[cfg_attr(feature = "serde", derive(serde::Serialize))]
19#[cfg_attr(feature = "serde", serde(tag = "type", content = "value"))]
20pub enum Variable<'arena> {
21    Direct(DirectVariable<'arena>),
22    Indirect(IndirectVariable<'arena>),
23    Nested(NestedVariable<'arena>),
24}
25
26/// Represents a direct variable.
27///
28/// A direct variable is a variable that is directly referenced by its name.
29///
30/// # Examples
31///
32/// ```php
33/// $foo
34/// ```
35#[derive(Debug, Clone, Eq, PartialEq, Hash, PartialOrd, Ord)]
36#[cfg_attr(feature = "serde", derive(serde::Serialize))]
37pub struct DirectVariable<'arena> {
38    pub span: Span,
39    pub name: &'arena [u8],
40}
41
42/// Represents an indirect variable.
43///
44/// An indirect variable is a variable whose name is determined by evaluating an expression at runtime.
45///
46/// The expression is enclosed in curly braces `{}` following a dollar sign `$`.
47///
48/// # Examples
49///
50/// ```php
51/// ${foo}
52/// ```
53#[derive(Debug, Clone, Eq, PartialEq, Hash, PartialOrd, Ord)]
54#[cfg_attr(feature = "serde", derive(serde::Serialize))]
55pub struct IndirectVariable<'arena> {
56    pub dollar_left_brace: Span,
57    pub expression: &'arena Expression<'arena>,
58    pub right_brace: Span,
59}
60
61/// Represents a nested variable.
62///
63/// A nested variable is a variable that is nested inside another variable, commonly known as a variable variable.
64///
65/// # Examples
66///
67/// ```php
68/// $$foo
69/// $${foo}
70/// $$$foo
71/// ```
72#[derive(Debug, Clone, Eq, PartialEq, Hash, PartialOrd, Ord)]
73#[cfg_attr(feature = "serde", derive(serde::Serialize))]
74pub struct NestedVariable<'arena> {
75    pub dollar: Span,
76    pub variable: &'arena Variable<'arena>,
77}
78
79impl HasSpan for Variable<'_> {
80    fn span(&self) -> Span {
81        match self {
82            Variable::Direct(node) => node.span(),
83            Variable::Indirect(node) => node.span(),
84            Variable::Nested(node) => node.span(),
85        }
86    }
87}
88
89impl HasSpan for DirectVariable<'_> {
90    fn span(&self) -> Span {
91        self.span
92    }
93}
94
95impl HasSpan for IndirectVariable<'_> {
96    fn span(&self) -> Span {
97        Span::between(self.dollar_left_brace, self.right_brace)
98    }
99}
100
101impl HasSpan for NestedVariable<'_> {
102    fn span(&self) -> Span {
103        Span::between(self.dollar, self.variable.span())
104    }
105}