aldrin_parser/ast/
const_def.rs1use super::{Ident, LitInt, LitString, LitUuid};
2use crate::error::InvalidConstValue;
3use crate::grammar::Rule;
4use crate::validate::Validate;
5use crate::warning::NonShoutySnakeCaseConst;
6use crate::Span;
7use pest::iterators::Pair;
8
9#[derive(Debug, Clone)]
10pub struct ConstDef {
11 span: Span,
12 name: Ident,
13 value_span: Span,
14 value: ConstValue,
15}
16
17impl ConstDef {
18 pub(crate) fn parse(pair: Pair<Rule>) -> Self {
19 assert_eq!(pair.as_rule(), Rule::const_def);
20
21 let span = Span::from_pair(&pair);
22
23 let mut pairs = pair.into_inner();
24 pairs.next().unwrap(); let name = Ident::parse(pairs.next().unwrap());
27
28 pairs.next().unwrap(); let value_pair = pairs.next().unwrap();
31 let value_span = Span::from_pair(&value_pair);
32 let value = ConstValue::parse(value_pair);
33
34 Self {
35 span,
36 name,
37 value_span,
38 value,
39 }
40 }
41
42 pub(crate) fn validate(&self, validate: &mut Validate) {
43 NonShoutySnakeCaseConst::validate(self, validate);
44
45 self.name.validate(validate);
46 self.value.validate(validate);
47 }
48
49 pub fn span(&self) -> Span {
50 self.span
51 }
52
53 pub fn name(&self) -> &Ident {
54 &self.name
55 }
56
57 pub fn value_span(&self) -> Span {
58 self.value_span
59 }
60
61 pub fn value(&self) -> &ConstValue {
62 &self.value
63 }
64}
65
66#[derive(Debug, Clone)]
67pub enum ConstValue {
68 U8(LitInt),
69 I8(LitInt),
70 U16(LitInt),
71 I16(LitInt),
72 U32(LitInt),
73 I32(LitInt),
74 U64(LitInt),
75 I64(LitInt),
76 String(LitString),
77 Uuid(LitUuid),
78}
79
80impl ConstValue {
81 fn parse(pair: Pair<Rule>) -> Self {
82 assert_eq!(pair.as_rule(), Rule::const_value);
83 let mut pairs = pair.into_inner();
84 let pair = pairs.next().unwrap();
85
86 let rule = pair.as_rule();
87 let mut pairs = pair.into_inner();
88 pairs.next().unwrap(); pairs.next().unwrap(); let pair = pairs.next().unwrap();
91
92 match rule {
93 Rule::const_u8 => Self::U8(LitInt::parse(pair)),
94 Rule::const_i8 => Self::I8(LitInt::parse(pair)),
95 Rule::const_u16 => Self::U16(LitInt::parse(pair)),
96 Rule::const_i16 => Self::I16(LitInt::parse(pair)),
97 Rule::const_u32 => Self::U32(LitInt::parse(pair)),
98 Rule::const_i32 => Self::I32(LitInt::parse(pair)),
99 Rule::const_u64 => Self::U64(LitInt::parse(pair)),
100 Rule::const_i64 => Self::I64(LitInt::parse(pair)),
101 Rule::const_string => Self::String(LitString::parse(pair)),
102 Rule::const_uuid => Self::Uuid(LitUuid::parse(pair)),
103 _ => unreachable!(),
104 }
105 }
106
107 fn validate(&self, validate: &mut Validate) {
108 InvalidConstValue::validate(self, validate);
109 }
110}