Skip to main content

aldrin_parser/ast/
array_len.rs

1use super::{LitInt, NamedRef};
2use crate::Span;
3use crate::error::{
4    ConstIntNotFound, ExpectedConstIntFoundService, ExpectedConstIntFoundString,
5    ExpectedConstIntFoundType, ExpectedConstIntFoundUuid, InvalidArrayLen,
6};
7use crate::grammar::Rule;
8use crate::validate::Validate;
9use pest::iterators::Pair;
10use std::fmt;
11
12#[derive(Debug, Clone)]
13pub struct ArrayLen {
14    span: Span,
15    value: ArrayLenValue,
16}
17
18impl ArrayLen {
19    pub(crate) fn parse(pair: Pair<Rule>) -> Self {
20        assert_eq!(pair.as_rule(), Rule::array_len);
21
22        let span = Span::from_pair(&pair);
23
24        let mut pairs = pair.into_inner();
25        let pair = pairs.next().unwrap();
26        let value = ArrayLenValue::parse(pair);
27
28        Self { span, value }
29    }
30
31    pub(crate) fn validate(&self, validate: &mut Validate) {
32        InvalidArrayLen::validate(self, validate);
33
34        self.value.validate(validate);
35    }
36
37    pub fn span(&self) -> Span {
38        self.span
39    }
40
41    pub fn value(&self) -> &ArrayLenValue {
42        &self.value
43    }
44}
45
46#[derive(Debug, Clone)]
47pub enum ArrayLenValue {
48    Literal(LitInt),
49    Ref(NamedRef),
50}
51
52impl ArrayLenValue {
53    fn parse(pair: Pair<Rule>) -> Self {
54        #[expect(clippy::wildcard_enum_match_arm)]
55        match pair.as_rule() {
56            Rule::lit_int => Self::Literal(LitInt::parse(&pair)),
57            Rule::named_ref => Self::Ref(NamedRef::parse(pair)),
58            _ => unreachable!(),
59        }
60    }
61
62    fn validate(&self, validate: &mut Validate) {
63        match self {
64            Self::Literal(_) => {}
65
66            Self::Ref(ty) => {
67                ConstIntNotFound::validate(ty, validate);
68                ExpectedConstIntFoundService::validate(ty, validate);
69                ExpectedConstIntFoundString::validate(ty, validate);
70                ExpectedConstIntFoundType::validate(ty, validate);
71                ExpectedConstIntFoundUuid::validate(ty, validate);
72
73                ty.validate(validate);
74            }
75        }
76    }
77}
78
79impl fmt::Display for ArrayLenValue {
80    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
81        match self {
82            Self::Literal(lit) => lit.value().fmt(f),
83            Self::Ref(named_ref) => named_ref.kind().fmt(f),
84        }
85    }
86}