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