mist_parser/parser/common/
decl.rs1use crate::{
2 Rule,
3 ast::*,
4 ast_expr,
5 error::{AstError, AstResult, IntoErr},
6 parser::listen_rule,
7};
8
9impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for VarDeclStmt {
10 type Error = AstError<'a, Self>;
11
12 fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
13 match pair.as_rule() {
14 Rule::var_decl_statement => {
15 let mut inner = pair.into_inner();
16
17 ast_expr!(VarDeclStmt {
18 decl: inner.next().unwrap().try_into(),
19 init: inner.next().map(Expression::try_from).transpose()
20 })
21 }
22
23 _ => AstError::bug_unimplemented(pair),
24 }
25 }
26}
27
28impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FieldDeclStmt {
29 type Error = AstError<'a, Self>;
30
31 fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
32 match pair.as_rule() {
33 Rule::class_field => {
34 let mut inner = pair.into_inner();
35
36 ast_expr!(FieldDeclStmt {
37 decl: inner.next().unwrap().try_into(),
38 init: inner.next().map(Expression::try_from).transpose(),
39 })
40 }
41
42 _ => AstError::bug_unimplemented(pair),
43 }
44 }
45}
46
47impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for VarDecl {
48 type Error = AstError<'a, Self>;
49
50 fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
51 match pair.as_rule() {
52 Rule::var_decl => {
53 let mut inner = pair.into_inner();
54
55 let type_ = inner
56 .next()
57 .and_then(|pair| {
58 if pair.as_str().trim() == "var" {
59 None
60 } else {
61 Some(TypeExpr::try_from(pair))
62 }
63 })
64 .transpose();
65
66 let mutable: AstResult<'_, bool> = Ok(listen_rule(&mut inner, Rule::mutable));
67
68 let name = Pattern::try_from(inner.next().unwrap());
69
70 ast_expr!(VarDecl {
71 type_: type_,
72 mutable: mutable,
73 name: name,
74 })
75 }
76
77 _ => AstError::bug_unimplemented(pair),
78 }
79 }
80}
81
82impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FieldDecl {
83 type Error = AstError<'a, Self>;
84
85 fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
86 match pair.as_rule() {
87 Rule::field => {
88 let mut inner = pair.into_inner();
89
90 ast_expr!(FieldDecl {
91 visibility: Visibility::try_from(&mut inner),
92 type_: TypeExpr::try_from(inner.next().unwrap()),
93 name: Identifier::try_from(inner.next().unwrap()),
94 })
95 }
96
97 _ => AstError::bug_unimplemented(pair),
98 }
99 }
100}