y_lang/ast/
definition.rs

1use pest::iterators::Pair;
2
3use super::{Expression, Ident, Position, Rule};
4
5#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
6pub struct Definition<T> {
7    pub ident: Ident<T>,
8    pub value: Expression<T>,
9    pub position: Position,
10    pub is_mutable: bool,
11    pub info: T,
12}
13
14impl Definition<()> {
15    pub fn from_pair(pair: Pair<Rule>, file: &str) -> Definition<()> {
16        let mut inner = pair.clone().into_inner();
17
18        let (line, col) = pair.line_col();
19
20        let mut is_mutable = false;
21
22        let ident_or_mut = inner.next().unwrap_or_else(|| {
23            panic!(
24                "Expected lvalue or 'mut' in definition '{}' at {}:{}",
25                pair.as_str(),
26                pair.line_col().0,
27                pair.line_col().1
28            )
29        });
30
31        let ident = if ident_or_mut.as_rule() == Rule::mutKeyword {
32            is_mutable = true;
33            inner.next().unwrap_or_else(|| {
34                panic!(
35                    "Expected lvalue in definition '{}' at {}:{}",
36                    pair.as_str(),
37                    pair.line_col().0,
38                    pair.line_col().1
39                )
40            })
41        } else {
42            ident_or_mut
43        };
44
45        let ident = Ident::from_pair(ident, file);
46
47        let value = inner.next().unwrap_or_else(|| {
48            panic!(
49                "Expected rvalue in definition '{}' at {}:{}",
50                pair.as_str(),
51                pair.line_col().0,
52                pair.line_col().1
53            )
54        });
55        let value = Expression::from_pair(value, file);
56
57        Definition {
58            ident,
59            value,
60            position: (file.to_owned(), line, col),
61            is_mutable,
62            info: (),
63        }
64    }
65}