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