darklua_core/nodes/
variable.rs

1use crate::nodes::{FieldExpression, Identifier, IndexExpression, Token};
2
3/// Represents a variable reference.
4#[derive(Clone, Debug, PartialEq, Eq)]
5pub enum Variable {
6    /// A simple named variable (e.g., `x`, `count`, `self`).
7    Identifier(Identifier),
8    /// A field access on a table or object using dot notation (e.g., `table.field`, `self.name`).
9    Field(Box<FieldExpression>),
10    /// An index access on a table using bracket notation (e.g., `array[1]`, `table[key]`).
11    Index(Box<IndexExpression>),
12}
13
14impl Variable {
15    /// Creates a new variable from an identifier name.
16    pub fn new<S: Into<String>>(name: S) -> Self {
17        Self::Identifier(Identifier::new(name))
18    }
19
20    /// Returns a mutable reference to the first token for this variable,
21    /// creating it if missing.
22    pub fn mutate_first_token(&mut self) -> &mut Token {
23        match self {
24            Variable::Identifier(identifier) => {
25                if identifier.get_token().is_none() {
26                    let name = identifier.get_name().to_owned();
27                    identifier.set_token(Token::from_content(name));
28                }
29                identifier.mutate_token().unwrap()
30            }
31            Variable::Field(field) => field.mutate_first_token(),
32            Variable::Index(index) => index.mutate_first_token(),
33        }
34    }
35
36    /// Returns a mutable reference to the last token for this variable,
37    /// creating it if missing.
38    pub fn mutate_last_token(&mut self) -> &mut Token {
39        match self {
40            Variable::Identifier(identifier) => identifier.mutate_or_insert_token(),
41            Variable::Field(field) => field.mutate_last_token(),
42            Variable::Index(index) => index.mutate_last_token(),
43        }
44    }
45}
46
47impl From<Identifier> for Variable {
48    fn from(identifier: Identifier) -> Self {
49        Self::Identifier(identifier)
50    }
51}
52
53impl From<FieldExpression> for Variable {
54    fn from(field: FieldExpression) -> Self {
55        Self::Field(field.into())
56    }
57}
58
59impl From<IndexExpression> for Variable {
60    fn from(index: IndexExpression) -> Self {
61        Self::Index(index.into())
62    }
63}