summaryrefslogtreecommitdiffstats
path: root/crates/rebel-parse/src/grammar/recipe.rs
blob: d00c6726733d6e798c838d9ac26063b11435df10 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
use crate::{
	ast::{
		self,
		expr::{self, Expr},
		typ::{self, Type},
	},
	token::*,
};

pub use rules::*;

peg::parser! {
	pub grammar rules<'a>() for TokenStream<'a> {
		use expr::OpBinary::*;
		use expr::OpUnary::*;

		pub rule recipe() -> ast::Recipe<'a>
			= recipe:recipe_stmt()* { recipe }

		pub rule recipe_stmt() -> ast::RecipeStmt<'a>
			= [Token::Keyword(Keyword::Fetch)] name:ident() p('{') body:body() p('}') {
				ast::RecipeStmt::Fetch { name, body: ast::Body(Vec::new()) }
			}
			/ [Token::Keyword(Keyword::Task)] name:ident() p('(') params:func_params() p(')')
			  p('{') body:body() p('}') {
				ast::RecipeStmt::Task { name, params, body }
			}
			/ stmt:body_stmt() p(';') {
				ast::RecipeStmt::BodyStmt(stmt)
			}

		pub rule body() -> ast::Body<'a>
			= body:body_stmt() ++ p(';') { ast::Body(body) }

		pub rule body_stmt() -> ast::BodyStmt<'a>
			= dest:typed_expr() op:assign_op() expr:expr() {
				ast::BodyStmt::assign(dest, op, false, expr)
			}
			/ dest:typed_expr() p2('=', '+') expr:expr() {
				ast::BodyStmt::assign(dest, Some(Add), true, expr)
			}
			/ expr:expr() {
				ast::BodyStmt::Expr { expr: Box::new(expr) }
			}
			/ { ast::BodyStmt::Empty }

		rule assign_op() -> Option<expr::OpBinary>
			= p('=') { None }
			/ p2('+', '=') { Some(Add) }
			/ p2('-', '=') { Some(Sub) }
			/ p2('*', '=') { Some(Mul) }
			/ p2('/', '=') { Some(Div) }
			/ p2('%', '=') { Some(Rem) }

		rule typed_expr() -> ast::TypedExpr<'a>
			= expr:expr() typ:tagged(<p(':')>, <typ()>)? { ast::TypedExpr { expr, typ } }

		rule typ() -> Type<'a>
			= lit:typ_literal() { Type::Literal(lit) }
			/ path:path() { Type::Path(path) }
			/ p('(') t:typ() p(')') { Type::Paren(Box::new(t)) }

		rule typ_literal() -> typ::Literal<'a>
			= p('(') p(')') { typ::Literal::Unit }
			/ p('(') elements:(typ() ** p(',')) p(',')? p(')') {
				typ::Literal::Tuple(elements)
			}
			/ p('[') typ:typ() len:tagged(<p(';')>, <number()>)? p(']') { ?
				let len = len
					.map(|n| usize::try_from(n).or(Err("Invalid array length")))
					.transpose()?;
				Ok(typ::Literal::Array(Box::new(typ), len))
			}
			/ p('{') entries:delimited(<struct_field_typ()>, <p(',')>) p('}') {
				typ::Literal::Struct(entries)
			}

		rule struct_field_typ() -> typ::StructField<'a>
			= field:field() p(':') typ:typ() {
				typ::StructField { name: field.name, typ }
			}

		pub rule expr() -> Expr<'a> = precedence! {
			left:(@) p2('|', '|') right:@ { Expr::binary(left, Or, right) }
			--
			left:(@) p2('&', '&') right:@ { Expr::binary(left, And, right) }
			--
			left:(@) p2('=', '=') right:@ { Expr::binary(left, Eq, right) }
			left:(@) p2('!', '=') right:@ { Expr::binary(left, Ne, right) }
			left:(@) p('<')  right:@ { Expr::binary(left, Lt, right) }
			left:(@) p('>')  right:@ { Expr::binary(left, Gt, right) }
			left:(@) p2('<', '=') right:@ { Expr::binary(left, Le, right) }
			left:(@) p2('>', '=') right:@ { Expr::binary(left, Ge, right) }
			--
			left:(@) p('+')  right:@ { Expr::binary(left, Add, right) }
			left:(@) p('-')  right:@ { Expr::binary(left, Sub, right) }
			--
			left:(@) p('*')  right:@ { Expr::binary(left, Mul, right) }
			left:(@) p('/')  right:@ { Expr::binary(left, Div, right) }
			left:(@) p('%')  right:@ { Expr::binary(left, Rem, right) }
			--
			p('-') expr:@ { Expr::unary(Neg, expr) }
			p('!') expr:@ { Expr::unary(Not, expr) }
			--
			expr:@ p('(') params:call_params() p(')') {
				Expr::apply(expr, params)
			}
			expr:@ p('[') index:expr() p(']') { Expr::index(expr, index) }
			--
			expr:@ p('.') method:field() p('(') params:call_params() p(')') {
				Expr::method(expr, method, params)
			}
			expr:@ p('.') field:field() { Expr::field(expr, field) }
			--
			p('(') e:expr() p(')') { Expr::paren(e) }
			e:atom() { e }
		}

		rule atom() -> Expr<'a>
			= lit:literal() { Expr::Literal(lit) }
			/ path:path() { Expr::Path(path) }

		rule call_params() -> Vec<expr::Expr<'a>>
			= args:delimited(<expr()>, <p(',')>) { args }

		rule func_params() -> Vec<ast::FuncParam<'a>>
			= params:delimited(<func_param()>, <p(',')>) { params }

		rule func_param() -> ast::FuncParam<'a>
			= name:ident() p(':') typ:typ() { ast::FuncParam { name, typ } }

		rule literal() -> expr::Literal<'a>
			= [Token::Keyword(Keyword::True)] { expr::Literal::Bool(true) }
			/ [Token::Keyword(Keyword::False)] { expr::Literal::Bool(false) }
			/ n:number() { expr::Literal::Int(n) }
			/ [Token::Str(Str { pieces, kind })] { ?
				let pieces = pieces
					.iter()
					.map(|piece| piece.try_into())
					.collect::<Result<_, _>>()?;
				Ok(expr::Literal::Str{ pieces, kind: *kind })
			}
			/ p('(') p(')') { expr::Literal::Unit }
			/ p('(') elements:(expr() ** p(',')) p(',')? p(')') {
				expr::Literal::Tuple(elements)
			}
			/ p('[') elements:delimited(<expr()>, <p(',')>) p(']') {
				expr::Literal::Array(elements)
			}
			/ p('{') entries:delimited(<struct_field()>, <p(',')>) p('}') {
				expr::Literal::Struct(entries)
			}

		rule struct_field() -> expr::StructField<'a>
			= field:field() p('=') value:expr() {
				expr::StructField { name: field.name, value }
			}

		rule path() -> ast::Path<'a>
			= components:ident() ++ p2(':', ':') { ast::Path { components } }

		rule field() -> ast::Ident<'a>
			= ident()
			/ [Token::Number(content)] {
				ast::Ident { name: content }
			}

		rule number() -> u64
			= [Token::Number(s)] { ?
				let (radix, rest) = if let Some(rest) = s.strip_prefix("0x") {
					(16, rest)
				} else if let Some(rest) = s.strip_prefix("0o") {
					(8, rest)
				} else if let Some(rest) = s.strip_prefix("0b") {
					(2, rest)
				} else {
					(10, *s)
				};
				let digits = rest.replace('_', "");
				u64::from_str_radix(&digits, radix).or(Err("number"))
			}

		rule p_(ch: char)
			= [Token::Punct(Punct(c, Spacing::Joint)) if *c == ch] {}

		rule p(ch: char) -> ()
			= [Token::Punct(Punct(c, _)) if *c == ch] {}

		rule p2(ch1: char, ch2: char)
			= p_(ch1) p(ch2)

		rule ident() -> ast::Ident<'a>
			= [Token::Ident(name)] { ast::Ident { name } }

		rule delimited<T>(expr: rule<T>, delim: rule<()>) -> Vec<T>
			= values:(expr() ++ delim()) delim()? { values }
			/ { Vec::new() }

		rule tagged<T>(tag: rule<()>, value: rule<T>) -> T
			= tag() v:value() { v }
	}
}