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