bluejay_parser/ast/executable/
variable_definition.rs1use crate::ast::try_from_tokens::TryFromTokens;
2use crate::ast::{
3 executable::VariableType, ConstDirectives, ConstValue, FromTokens, ParseError, Tokens,
4};
5use crate::lexical_token::{PunctuatorType, Variable};
6
7#[derive(Debug)]
8pub struct VariableDefinition<'a> {
9 variable: Variable<'a>,
10 r#type: VariableType<'a>,
11 default_value: Option<ConstValue<'a>>,
12 directives: Option<ConstDirectives<'a>>,
13}
14
15impl<'a> FromTokens<'a> for VariableDefinition<'a> {
16 #[inline]
17 fn from_tokens(tokens: &mut impl Tokens<'a>) -> Result<Self, ParseError> {
18 let variable = tokens.expect_variable()?;
19 tokens.expect_punctuator(PunctuatorType::Colon)?;
20 let r#type = VariableType::from_tokens(tokens)?;
21 let default_value: Option<ConstValue> =
22 if tokens.next_if_punctuator(PunctuatorType::Equals).is_some() {
23 Some(ConstValue::from_tokens(tokens)?)
24 } else {
25 None
26 };
27 let directives = ConstDirectives::try_from_tokens(tokens).transpose()?;
28 Ok(Self {
29 variable,
30 r#type,
31 default_value,
32 directives,
33 })
34 }
35}
36
37impl<'a> VariableDefinition<'a> {
38 pub fn variable(&self) -> &Variable {
39 &self.variable
40 }
41
42 pub fn r#type(&self) -> &VariableType {
43 &self.r#type
44 }
45
46 pub fn default_value(&self) -> Option<&ConstValue> {
47 self.default_value.as_ref()
48 }
49}
50
51impl<'a> bluejay_core::executable::VariableDefinition for VariableDefinition<'a> {
52 type Value = ConstValue<'a>;
53 type VariableType = VariableType<'a>;
54 type Directives = ConstDirectives<'a>;
55
56 fn variable(&self) -> &str {
57 self.variable.as_str()
58 }
59
60 fn r#type(&self) -> &Self::VariableType {
61 &self.r#type
62 }
63
64 fn directives(&self) -> Option<&Self::Directives> {
65 self.directives.as_ref()
66 }
67
68 fn default_value(&self) -> Option<&Self::Value> {
69 self.default_value.as_ref()
70 }
71}