blob: ff2bac991fea103359f9f9abc9786b041a2d6b41 [file] [log] [blame]
David Tolnayf4bbbd92016-09-23 14:41:55 -07001use super::*;
2
3#[derive(Debug, Clone, Eq, PartialEq)]
4pub enum Expr {
5 /// A `box x` expression.
6 Box(Box<Expr>),
David Tolnayf4bbbd92016-09-23 14:41:55 -07007 /// An array (`[a, b, c, d]`)
8 Vec(Vec<Expr>),
9 /// A function call
10 ///
11 /// The first field resolves to the function itself,
12 /// and the second field is the list of arguments
13 Call(Box<Expr>, Vec<Expr>),
14 /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
15 ///
16 /// The `Ident` is the identifier for the method name.
17 /// The vector of `Ty`s are the ascripted type parameters for the method
18 /// (within the angle brackets).
19 ///
20 /// The first element of the vector of `Expr`s is the expression that evaluates
21 /// to the object on which the method is being called on (the receiver),
22 /// and the remaining elements are the rest of the arguments.
23 ///
24 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
25 /// `ExprKind::MethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
26 MethodCall(Ident, Vec<Ty>, Vec<Expr>),
27 /// A tuple (`(a, b, c, d)`)
28 Tup(Vec<Expr>),
29 /// A binary operation (For example: `a + b`, `a * b`)
30 Binary(BinOp, Box<Expr>, Box<Expr>),
31 /// A unary operation (For example: `!x`, `*x`)
32 Unary(UnOp, Box<Expr>),
33 /// A literal (For example: `1`, `"foo"`)
34 Lit(Lit),
35 /// A cast (`foo as f64`)
36 Cast(Box<Expr>, Box<Ty>),
David Tolnay939766a2016-09-23 23:48:12 -070037 /// Type ascription (`foo: f64`)
David Tolnayf4bbbd92016-09-23 14:41:55 -070038 Type(Box<Expr>, Box<Ty>),
39 /// An `if` block, with an optional else block
40 ///
41 /// `if expr { block } else { expr }`
David Tolnay89e05672016-10-02 14:39:42 -070042 If(Box<Expr>, Block, Option<Box<Expr>>),
David Tolnayf4bbbd92016-09-23 14:41:55 -070043 /// An `if let` expression with an optional else block
44 ///
45 /// `if let pat = expr { block } else { expr }`
46 ///
47 /// This is desugared to a `match` expression.
David Tolnay89e05672016-10-02 14:39:42 -070048 IfLet(Box<Pat>, Box<Expr>, Block, Option<Box<Expr>>),
David Tolnayf4bbbd92016-09-23 14:41:55 -070049 /// A while loop, with an optional label
50 ///
51 /// `'label: while expr { block }`
David Tolnay89e05672016-10-02 14:39:42 -070052 While(Box<Expr>, Block, Option<Ident>),
David Tolnayf4bbbd92016-09-23 14:41:55 -070053 /// A while-let loop, with an optional label
54 ///
55 /// `'label: while let pat = expr { block }`
56 ///
57 /// This is desugared to a combination of `loop` and `match` expressions.
David Tolnay89e05672016-10-02 14:39:42 -070058 WhileLet(Box<Pat>, Box<Expr>, Block, Option<Ident>),
David Tolnayf4bbbd92016-09-23 14:41:55 -070059 /// A for loop, with an optional label
60 ///
61 /// `'label: for pat in expr { block }`
62 ///
63 /// This is desugared to a combination of `loop` and `match` expressions.
David Tolnay89e05672016-10-02 14:39:42 -070064 ForLoop(Box<Pat>, Box<Expr>, Block, Option<Ident>),
David Tolnayf4bbbd92016-09-23 14:41:55 -070065 /// Conditionless loop (can be exited with break, continue, or return)
66 ///
67 /// `'label: loop { block }`
David Tolnay89e05672016-10-02 14:39:42 -070068 Loop(Block, Option<Ident>),
David Tolnayf4bbbd92016-09-23 14:41:55 -070069 /// A `match` block.
70 Match(Box<Expr>, Vec<Arm>),
71 /// A closure (for example, `move |a, b, c| {a + b + c}`)
David Tolnay89e05672016-10-02 14:39:42 -070072 Closure(CaptureBy, Box<FnDecl>, Block),
73 /// A block (`{ ... }` or `unsafe { ... }`)
74 Block(BlockCheckMode, Block),
David Tolnayf4bbbd92016-09-23 14:41:55 -070075
76 /// An assignment (`a = foo()`)
77 Assign(Box<Expr>, Box<Expr>),
78 /// An assignment with an operator
79 ///
80 /// For example, `a += 1`.
81 AssignOp(BinOp, Box<Expr>, Box<Expr>),
82 /// Access of a named struct field (`obj.foo`)
83 Field(Box<Expr>, Ident),
84 /// Access of an unnamed field of a struct or tuple-struct
85 ///
86 /// For example, `foo.0`.
87 TupField(Box<Expr>, usize),
88 /// An indexing operation (`foo[2]`)
89 Index(Box<Expr>, Box<Expr>),
90 /// A range (`1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`)
91 Range(Option<Box<Expr>>, Option<Box<Expr>>, RangeLimits),
92
93 /// Variable reference, possibly containing `::` and/or type
94 /// parameters, e.g. foo::bar::<baz>.
95 ///
96 /// Optionally "qualified",
97 /// E.g. `<Vec<T> as SomeTrait>::SomeType`.
98 Path(Option<QSelf>, Path),
99
100 /// A referencing operation (`&a` or `&mut a`)
101 AddrOf(Mutability, Box<Expr>),
102 /// A `break`, with an optional label to break
103 Break(Option<Ident>),
104 /// A `continue`, with an optional label
105 Continue(Option<Ident>),
106 /// A `return`, with an optional value to be returned
107 Ret(Option<Box<Expr>>),
108
109 /// A macro invocation; pre-expansion
110 Mac(Mac),
111
112 /// A struct literal expression.
113 ///
114 /// For example, `Foo {x: 1, y: 2}`, or
115 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
116 Struct(Path, Vec<Field>, Option<Box<Expr>>),
117
118 /// An array literal constructed from one repeated element.
119 ///
120 /// For example, `[1; 5]`. The first expression is the element
121 /// to be repeated; the second is the number of times to repeat it.
122 Repeat(Box<Expr>, Box<Expr>),
123
124 /// No-op: used solely so we can pretty-print faithfully
125 Paren(Box<Expr>),
126
127 /// `expr?`
128 Try(Box<Expr>),
129}
130
131/// A Block (`{ .. }`).
132///
133/// E.g. `{ .. }` as in `fn foo() { .. }`
134#[derive(Debug, Clone, Eq, PartialEq)]
135pub struct Block {
136 /// Statements in a block
137 pub stmts: Vec<Stmt>,
David Tolnayf4bbbd92016-09-23 14:41:55 -0700138}
139
140#[derive(Debug, Copy, Clone, Eq, PartialEq)]
141pub enum BlockCheckMode {
142 Default,
143 Unsafe,
144}
145
146#[derive(Debug, Clone, Eq, PartialEq)]
147pub enum Stmt {
148 /// A local (let) binding.
149 Local(Box<Local>),
150
151 /// An item definition.
152 Item(Box<Item>),
153
154 /// Expr without trailing semi-colon.
155 Expr(Box<Expr>),
156
157 Semi(Box<Expr>),
158
159 Mac(Box<(Mac, MacStmtStyle, Vec<Attribute>)>),
160}
161
162#[derive(Debug, Copy, Clone, Eq, PartialEq)]
163pub enum MacStmtStyle {
164 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
165 /// `foo!(...);`, `foo![...];`
166 Semicolon,
167 /// The macro statement had braces; e.g. foo! { ... }
168 Braces,
169 /// The macro statement had parentheses or brackets and no semicolon; e.g.
170 /// `foo!(...)`. All of these will end up being converted into macro
171 /// expressions.
172 NoBraces,
173}
174
175/// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
176#[derive(Debug, Clone, Eq, PartialEq)]
177pub struct Local {
178 pub pat: Box<Pat>,
179 pub ty: Option<Box<Ty>>,
180 /// Initializer expression to set the value, if any
181 pub init: Option<Box<Expr>>,
182 pub attrs: Vec<Attribute>,
183}
184
185#[derive(Debug, Copy, Clone, Eq, PartialEq)]
186pub enum BinOp {
187 /// The `+` operator (addition)
188 Add,
189 /// The `-` operator (subtraction)
190 Sub,
191 /// The `*` operator (multiplication)
192 Mul,
193 /// The `/` operator (division)
194 Div,
195 /// The `%` operator (modulus)
196 Rem,
197 /// The `&&` operator (logical and)
198 And,
199 /// The `||` operator (logical or)
200 Or,
201 /// The `^` operator (bitwise xor)
202 BitXor,
203 /// The `&` operator (bitwise and)
204 BitAnd,
205 /// The `|` operator (bitwise or)
206 BitOr,
207 /// The `<<` operator (shift left)
208 Shl,
209 /// The `>>` operator (shift right)
210 Shr,
211 /// The `==` operator (equality)
212 Eq,
213 /// The `<` operator (less than)
214 Lt,
215 /// The `<=` operator (less than or equal to)
216 Le,
217 /// The `!=` operator (not equal to)
218 Ne,
219 /// The `>=` operator (greater than or equal to)
220 Ge,
221 /// The `>` operator (greater than)
222 Gt,
223}
224
225#[derive(Debug, Copy, Clone, Eq, PartialEq)]
226pub enum UnOp {
227 /// The `*` operator for dereferencing
228 Deref,
229 /// The `!` operator for logical inversion
230 Not,
231 /// The `-` operator for negation
232 Neg,
233}
234
235#[derive(Debug, Clone, Eq, PartialEq)]
236pub enum Pat {
237 /// Represents a wildcard pattern (`_`)
238 Wild,
239
David Tolnay432afc02016-09-24 07:37:13 -0700240 /// A `Pat::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
David Tolnayf4bbbd92016-09-23 14:41:55 -0700241 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
242 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
243 /// during name resolution.
244 Ident(BindingMode, Ident, Option<Box<Pat>>),
245
246 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
247 /// The `bool` is `true` in the presence of a `..`.
248 Struct(Path, Vec<FieldPat>, bool),
249
250 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
251 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
252 /// 0 <= position <= subpats.len()
253 TupleStruct(Path, Vec<Pat>, Option<usize>),
254
255 /// A possibly qualified path pattern.
256 /// Unquailfied path patterns `A::B::C` can legally refer to variants, structs, constants
257 /// or associated constants. Quailfied path patterns `<A>::B::C`/`<A as Trait>::B::C` can
258 /// only legally refer to associated constants.
259 Path(Option<QSelf>, Path),
260
261 /// A tuple pattern `(a, b)`.
262 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
263 /// 0 <= position <= subpats.len()
264 Tuple(Vec<Pat>, Option<usize>),
265 /// A `box` pattern
266 Box(Box<Pat>),
267 /// A reference pattern, e.g. `&mut (a, b)`
268 Ref(Box<Pat>, Mutability),
269 /// A literal
270 Lit(Box<Expr>),
271 /// A range pattern, e.g. `1...2`
272 Range(Box<Expr>, Box<Expr>),
273 /// `[a, b, ..i, y, z]` is represented as:
David Tolnay432afc02016-09-24 07:37:13 -0700274 /// `Pat::Vec(box [a, b], Some(i), box [y, z])`
David Tolnayf4bbbd92016-09-23 14:41:55 -0700275 Vec(Vec<Pat>, Option<Box<Pat>>, Vec<Pat>),
276 /// A macro pattern; pre-expansion
277 Mac(Mac),
278}
279
David Tolnay771ecf42016-09-23 19:26:37 -0700280/// An arm of a 'match'.
281///
282/// E.g. `0...10 => { println!("match!") }` as in
283///
284/// ```rust,ignore
285/// match n {
286/// 0...10 => { println!("match!") },
287/// // ..
288/// }
289/// ```
David Tolnayf4bbbd92016-09-23 14:41:55 -0700290#[derive(Debug, Clone, Eq, PartialEq)]
291pub struct Arm {
292 pub attrs: Vec<Attribute>,
293 pub pats: Vec<Pat>,
294 pub guard: Option<Box<Expr>>,
295 pub body: Box<Expr>,
296}
297
298/// A capture clause
299#[derive(Debug, Copy, Clone, Eq, PartialEq)]
300pub enum CaptureBy {
301 Value,
302 Ref,
303}
304
305/// Limit types of a range (inclusive or exclusive)
306#[derive(Debug, Copy, Clone, Eq, PartialEq)]
307pub enum RangeLimits {
308 /// Inclusive at the beginning, exclusive at the end
309 HalfOpen,
310 /// Inclusive at the beginning and end
311 Closed,
312}
313
314/// A single field in a struct pattern
315///
316/// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
David Tolnay181bac52016-09-24 00:10:05 -0700317/// are treated the same as `x: x, y: ref y, z: ref mut z`,
David Tolnayaed77b02016-09-23 20:50:31 -0700318/// except `is_shorthand` is true
David Tolnayf4bbbd92016-09-23 14:41:55 -0700319#[derive(Debug, Clone, Eq, PartialEq)]
320pub struct FieldPat {
321 /// The identifier for the field
322 pub ident: Ident,
323 /// The pattern the field is destructured to
324 pub pat: Box<Pat>,
325 pub is_shorthand: bool,
326}
327
328#[derive(Debug, Copy, Clone, Eq, PartialEq)]
329pub enum BindingMode {
330 ByRef(Mutability),
331 ByValue(Mutability),
332}
333
David Tolnayb9c8e322016-09-23 20:48:37 -0700334#[cfg(feature = "parsing")]
335pub mod parsing {
336 use super::*;
David Tolnay9636c052016-10-02 17:11:17 -0700337 use {FnArg, FnDecl, FunctionRetTy, Ident, Lifetime, Ty};
David Tolnayb4ad3b52016-10-01 21:58:13 -0700338 use attr::parsing::outer_attr;
Gregory Katz1b69f682016-09-27 21:06:09 -0400339 use generics::parsing::lifetime;
David Tolnayfa0edf22016-09-23 22:58:24 -0700340 use ident::parsing::ident;
341 use lit::parsing::lit;
David Tolnay9636c052016-10-02 17:11:17 -0700342 use ty::parsing::{mutability, qpath, ty};
David Tolnayb9c8e322016-09-23 20:48:37 -0700343
David Tolnayfa0edf22016-09-23 22:58:24 -0700344 named!(pub expr -> Expr, do_parse!(
345 mut e: alt!(
David Tolnay89e05672016-10-02 14:39:42 -0700346 expr_paren
347 |
David Tolnay939766a2016-09-23 23:48:12 -0700348 expr_box
David Tolnayfa0edf22016-09-23 22:58:24 -0700349 |
David Tolnay939766a2016-09-23 23:48:12 -0700350 expr_vec
David Tolnayfa0edf22016-09-23 22:58:24 -0700351 |
David Tolnay939766a2016-09-23 23:48:12 -0700352 expr_tup
David Tolnayfa0edf22016-09-23 22:58:24 -0700353 |
David Tolnay939766a2016-09-23 23:48:12 -0700354 expr_unary
David Tolnayfa0edf22016-09-23 22:58:24 -0700355 |
David Tolnay939766a2016-09-23 23:48:12 -0700356 expr_lit
357 |
358 expr_if
David Tolnaya96a3fa2016-09-24 07:17:42 -0700359 // TODO: IfLet
Gregory Katz3e562cc2016-09-28 18:33:02 -0400360 |
361 expr_while
David Tolnaya96a3fa2016-09-24 07:17:42 -0700362 // TODO: WhileLet
363 // TODO: ForLoop
364 // TODO: Loop
365 // TODO: ForLoop
Gregory Katze5f35682016-09-27 14:20:55 -0400366 |
367 expr_loop
David Tolnayb4ad3b52016-10-01 21:58:13 -0700368 |
369 expr_match
David Tolnay89e05672016-10-02 14:39:42 -0700370 |
371 expr_closure
David Tolnay939766a2016-09-23 23:48:12 -0700372 |
373 expr_block
David Tolnay89e05672016-10-02 14:39:42 -0700374 |
375 expr_path
David Tolnay3c2467c2016-10-02 17:55:08 -0700376 |
377 expr_addr_of
Gregory Katzfd6935d2016-09-30 22:51:25 -0400378 |
379 expr_break
380 |
381 expr_continue
382 |
383 expr_ret
David Tolnaya96a3fa2016-09-24 07:17:42 -0700384 // TODO: Mac
385 // TODO: Struct
386 // TODO: Repeat
David Tolnayfa0edf22016-09-23 22:58:24 -0700387 ) >>
388 many0!(alt!(
David Tolnay939766a2016-09-23 23:48:12 -0700389 tap!(args: and_call => {
390 e = Expr::Call(Box::new(e), args);
David Tolnayfa0edf22016-09-23 22:58:24 -0700391 })
392 |
David Tolnay939766a2016-09-23 23:48:12 -0700393 tap!(more: and_method_call => {
394 let (method, ascript, mut args) = more;
David Tolnayfa0edf22016-09-23 22:58:24 -0700395 args.insert(0, e);
396 e = Expr::MethodCall(method, ascript, args);
397 })
398 |
David Tolnay939766a2016-09-23 23:48:12 -0700399 tap!(more: and_binary => {
400 let (op, other) = more;
David Tolnayfa0edf22016-09-23 22:58:24 -0700401 e = Expr::Binary(op, Box::new(e), Box::new(other));
402 })
David Tolnay939766a2016-09-23 23:48:12 -0700403 |
404 tap!(ty: and_cast => {
405 e = Expr::Cast(Box::new(e), Box::new(ty));
406 })
407 |
408 tap!(ty: and_ascription => {
409 e = Expr::Type(Box::new(e), Box::new(ty));
410 })
David Tolnaya96a3fa2016-09-24 07:17:42 -0700411 // TODO: Assign
412 // TODO: AssignOp
413 // TODO: Field
414 // TODO: TupField
415 // TODO: Index
416 // TODO: Range
417 // TODO: Try
David Tolnayfa0edf22016-09-23 22:58:24 -0700418 )) >>
419 (e)
David Tolnayb9c8e322016-09-23 20:48:37 -0700420 ));
421
David Tolnay89e05672016-10-02 14:39:42 -0700422 named!(expr_paren -> Expr, do_parse!(
423 punct!("(") >>
424 e: expr >>
425 punct!(")") >>
426 (Expr::Paren(Box::new(e)))
427 ));
428
David Tolnay939766a2016-09-23 23:48:12 -0700429 named!(expr_box -> Expr, do_parse!(
David Tolnay10413f02016-09-30 09:12:02 -0700430 keyword!("box") >>
David Tolnayb9c8e322016-09-23 20:48:37 -0700431 inner: expr >>
432 (Expr::Box(Box::new(inner)))
433 ));
David Tolnayfa0edf22016-09-23 22:58:24 -0700434
David Tolnay939766a2016-09-23 23:48:12 -0700435 named!(expr_vec -> Expr, do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700436 punct!("[") >>
437 elems: separated_list!(punct!(","), expr) >>
438 punct!("]") >>
439 (Expr::Vec(elems))
440 ));
441
David Tolnay939766a2016-09-23 23:48:12 -0700442 named!(and_call -> Vec<Expr>, do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700443 punct!("(") >>
444 args: separated_list!(punct!(","), expr) >>
445 punct!(")") >>
446 (args)
447 ));
448
David Tolnay939766a2016-09-23 23:48:12 -0700449 named!(and_method_call -> (Ident, Vec<Ty>, Vec<Expr>), do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700450 punct!(".") >>
451 method: ident >>
452 ascript: opt_vec!(delimited!(
453 punct!("<"),
454 separated_list!(punct!(","), ty),
455 punct!(">")
456 )) >>
457 punct!("(") >>
458 args: separated_list!(punct!(","), expr) >>
459 punct!(")") >>
460 (method, ascript, args)
461 ));
462
David Tolnay939766a2016-09-23 23:48:12 -0700463 named!(expr_tup -> Expr, do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700464 punct!("(") >>
465 elems: separated_list!(punct!(","), expr) >>
David Tolnay89e05672016-10-02 14:39:42 -0700466 option!(punct!(",")) >>
David Tolnayfa0edf22016-09-23 22:58:24 -0700467 punct!(")") >>
468 (Expr::Tup(elems))
469 ));
470
David Tolnay939766a2016-09-23 23:48:12 -0700471 named!(and_binary -> (BinOp, Expr), tuple!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700472 alt!(
473 punct!("&&") => { |_| BinOp::And }
474 |
475 punct!("||") => { |_| BinOp::Or }
476 |
477 punct!("<<") => { |_| BinOp::Shl }
478 |
479 punct!(">>") => { |_| BinOp::Shr }
480 |
481 punct!("==") => { |_| BinOp::Eq }
482 |
483 punct!("<=") => { |_| BinOp::Le }
484 |
485 punct!("!=") => { |_| BinOp::Ne }
486 |
487 punct!(">=") => { |_| BinOp::Ge }
488 |
489 punct!("+") => { |_| BinOp::Add }
490 |
491 punct!("-") => { |_| BinOp::Sub }
492 |
493 punct!("*") => { |_| BinOp::Mul }
494 |
495 punct!("/") => { |_| BinOp::Div }
496 |
497 punct!("%") => { |_| BinOp::Rem }
498 |
499 punct!("^") => { |_| BinOp::BitXor }
500 |
501 punct!("&") => { |_| BinOp::BitAnd }
502 |
503 punct!("|") => { |_| BinOp::BitOr }
504 |
505 punct!("<") => { |_| BinOp::Lt }
506 |
507 punct!(">") => { |_| BinOp::Gt }
508 ),
509 expr
510 ));
511
David Tolnay939766a2016-09-23 23:48:12 -0700512 named!(expr_unary -> Expr, do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700513 operator: alt!(
514 punct!("*") => { |_| UnOp::Deref }
515 |
516 punct!("!") => { |_| UnOp::Not }
517 |
518 punct!("-") => { |_| UnOp::Neg }
519 ) >>
520 operand: expr >>
521 (Expr::Unary(operator, Box::new(operand)))
522 ));
David Tolnay939766a2016-09-23 23:48:12 -0700523
524 named!(expr_lit -> Expr, map!(lit, Expr::Lit));
525
526 named!(and_cast -> Ty, do_parse!(
David Tolnay10413f02016-09-30 09:12:02 -0700527 keyword!("as") >>
David Tolnay939766a2016-09-23 23:48:12 -0700528 ty: ty >>
529 (ty)
530 ));
531
532 named!(and_ascription -> Ty, preceded!(punct!(":"), ty));
533
534 named!(expr_if -> Expr, do_parse!(
David Tolnay10413f02016-09-30 09:12:02 -0700535 keyword!("if") >>
David Tolnay939766a2016-09-23 23:48:12 -0700536 cond: expr >>
537 punct!("{") >>
538 then_block: within_block >>
539 punct!("}") >>
540 else_block: option!(preceded!(
David Tolnay10413f02016-09-30 09:12:02 -0700541 keyword!("else"),
David Tolnay939766a2016-09-23 23:48:12 -0700542 alt!(
543 expr_if
544 |
545 do_parse!(
546 punct!("{") >>
547 else_block: within_block >>
548 punct!("}") >>
David Tolnay89e05672016-10-02 14:39:42 -0700549 (Expr::Block(BlockCheckMode::Default, Block {
David Tolnay939766a2016-09-23 23:48:12 -0700550 stmts: else_block,
David Tolnay89e05672016-10-02 14:39:42 -0700551 }))
David Tolnay939766a2016-09-23 23:48:12 -0700552 )
553 )
554 )) >>
555 (Expr::If(
556 Box::new(cond),
David Tolnay89e05672016-10-02 14:39:42 -0700557 Block {
David Tolnay939766a2016-09-23 23:48:12 -0700558 stmts: then_block,
David Tolnay89e05672016-10-02 14:39:42 -0700559 },
David Tolnay939766a2016-09-23 23:48:12 -0700560 else_block.map(Box::new),
561 ))
562 ));
563
Gregory Katze5f35682016-09-27 14:20:55 -0400564 named!(expr_loop -> Expr, do_parse!(
David Tolnay8b07f372016-09-30 10:28:40 -0700565 lbl: option!(terminated!(label, punct!(":"))) >>
David Tolnay10413f02016-09-30 09:12:02 -0700566 keyword!("loop") >>
Gregory Katze5f35682016-09-27 14:20:55 -0400567 loop_block: block >>
David Tolnay89e05672016-10-02 14:39:42 -0700568 (Expr::Loop(loop_block, lbl))
Gregory Katze5f35682016-09-27 14:20:55 -0400569 ));
570
David Tolnayb4ad3b52016-10-01 21:58:13 -0700571 named!(expr_match -> Expr, do_parse!(
572 keyword!("match") >>
573 obj: expr >>
574 punct!("{") >>
575 arms: many0!(do_parse!(
576 attrs: many0!(outer_attr) >>
577 pats: separated_nonempty_list!(punct!("|"), pat) >>
578 guard: option!(preceded!(keyword!("if"), expr)) >>
579 punct!("=>") >>
580 body: alt!(
581 terminated!(expr, punct!(","))
582 |
David Tolnay89e05672016-10-02 14:39:42 -0700583 map!(block, |blk| Expr::Block(BlockCheckMode::Default, blk))
David Tolnayb4ad3b52016-10-01 21:58:13 -0700584 ) >>
585 (Arm {
586 attrs: attrs,
587 pats: pats,
588 guard: guard.map(Box::new),
589 body: Box::new(body),
590 })
591 )) >>
592 punct!("}") >>
593 (Expr::Match(Box::new(obj), arms))
594 ));
595
David Tolnay89e05672016-10-02 14:39:42 -0700596 named!(expr_closure -> Expr, do_parse!(
597 capture: capture_by >>
598 punct!("|") >>
599 inputs: separated_list!(punct!(","), closure_arg) >>
600 punct!("|") >>
601 ret_and_body: alt!(
602 do_parse!(
603 punct!("->") >>
604 ty: ty >>
605 body: block >>
606 ((FunctionRetTy::Ty(ty), body))
607 )
608 |
609 map!(expr, |e| (
610 FunctionRetTy::Default,
611 Block {
612 stmts: vec![Stmt::Expr(Box::new(e))],
613 },
614 ))
615 ) >>
616 (Expr::Closure(
617 capture,
618 Box::new(FnDecl {
619 inputs: inputs,
620 output: ret_and_body.0,
621 }),
622 ret_and_body.1,
623 ))
624 ));
625
626 named!(closure_arg -> FnArg, do_parse!(
627 pat: pat >>
628 ty: option!(preceded!(punct!(":"), ty)) >>
629 (FnArg {
630 pat: pat,
631 ty: ty.unwrap_or(Ty::Infer),
632 })
633 ));
634
Gregory Katz3e562cc2016-09-28 18:33:02 -0400635 named!(expr_while -> Expr, do_parse!(
David Tolnay8b07f372016-09-30 10:28:40 -0700636 lbl: option!(terminated!(label, punct!(":"))) >>
David Tolnay57ffbde2016-09-30 09:38:04 -0700637 keyword!("while") >>
Gregory Katz3e562cc2016-09-28 18:33:02 -0400638 cond: expr >>
639 while_block: block >>
640 (Expr::While(
641 Box::new(cond),
David Tolnay89e05672016-10-02 14:39:42 -0700642 while_block,
David Tolnay8b07f372016-09-30 10:28:40 -0700643 lbl,
Gregory Katz3e562cc2016-09-28 18:33:02 -0400644 ))
645 ));
646
Gregory Katzfd6935d2016-09-30 22:51:25 -0400647 named!(expr_continue -> Expr, do_parse!(
648 keyword!("continue") >>
649 lbl: option!(label) >>
650 (Expr::Continue(
651 lbl,
652 ))
653 ));
654
655 named!(expr_break -> Expr, do_parse!(
656 keyword!("break") >>
657 lbl: option!(label) >>
658 (Expr::Break(
659 lbl,
660 ))
661 ));
662
663 named!(expr_ret -> Expr, do_parse!(
664 keyword!("return") >>
665 ret_value: option!(expr) >>
666 (Expr::Ret(
667 ret_value.map(Box::new),
668 ))
669 ));
670
David Tolnay42602292016-10-01 22:25:45 -0700671 named!(expr_block -> Expr, do_parse!(
David Tolnay939766a2016-09-23 23:48:12 -0700672 rules: block_check_mode >>
David Tolnay42602292016-10-01 22:25:45 -0700673 b: block >>
David Tolnay89e05672016-10-02 14:39:42 -0700674 (Expr::Block(rules, Block {
David Tolnay42602292016-10-01 22:25:45 -0700675 stmts: b.stmts,
David Tolnay89e05672016-10-02 14:39:42 -0700676 }))
677 ));
678
David Tolnay9636c052016-10-02 17:11:17 -0700679 named!(expr_path -> Expr, map!(qpath, |(qself, path)| Expr::Path(qself, path)));
David Tolnay42602292016-10-01 22:25:45 -0700680
David Tolnay3c2467c2016-10-02 17:55:08 -0700681 named!(expr_addr_of -> Expr, do_parse!(
682 punct!("&") >>
683 mutability: mutability >>
684 expr: expr >>
685 (Expr::AddrOf(mutability, Box::new(expr)))
686 ));
687
David Tolnay42602292016-10-01 22:25:45 -0700688 named!(pub block -> Block, do_parse!(
David Tolnay939766a2016-09-23 23:48:12 -0700689 punct!("{") >>
690 stmts: within_block >>
691 punct!("}") >>
692 (Block {
693 stmts: stmts,
David Tolnay939766a2016-09-23 23:48:12 -0700694 })
695 ));
696
697 named!(block_check_mode -> BlockCheckMode, alt!(
David Tolnay10413f02016-09-30 09:12:02 -0700698 keyword!("unsafe") => { |_| BlockCheckMode::Unsafe }
David Tolnay939766a2016-09-23 23:48:12 -0700699 |
700 epsilon!() => { |_| BlockCheckMode::Default }
701 ));
702
703 named!(within_block -> Vec<Stmt>, do_parse!(
David Tolnay181bac52016-09-24 00:10:05 -0700704 mut most: many0!(standalone_stmt) >>
David Tolnay939766a2016-09-23 23:48:12 -0700705 last: option!(expr) >>
706 (match last {
707 None => most,
708 Some(last) => {
David Tolnay939766a2016-09-23 23:48:12 -0700709 most.push(Stmt::Expr(Box::new(last)));
710 most
711 }
712 })
713 ));
714
715 named!(standalone_stmt -> Stmt, alt!(
David Tolnaya96a3fa2016-09-24 07:17:42 -0700716 // TODO: local
717 // TODO: item
718 // TODO: expr
David Tolnay939766a2016-09-23 23:48:12 -0700719 stmt_semi
David Tolnaya96a3fa2016-09-24 07:17:42 -0700720 // TODO: mac
David Tolnay939766a2016-09-23 23:48:12 -0700721 ));
722
723 named!(stmt_semi -> Stmt, do_parse!(
724 e: expr >>
725 punct!(";") >>
726 (Stmt::Semi(Box::new(e)))
727 ));
David Tolnay8b07f372016-09-30 10:28:40 -0700728
David Tolnay42602292016-10-01 22:25:45 -0700729 named!(pub pat -> Pat, alt!(
David Tolnayb4ad3b52016-10-01 21:58:13 -0700730 pat_wild
731 |
732 pat_ident
733 // TODO: Struct
734 // TODO: TupleStruct
David Tolnay9636c052016-10-02 17:11:17 -0700735 |
736 pat_path
David Tolnayb4ad3b52016-10-01 21:58:13 -0700737 // TODO: Tuple
738 // TODO: Box
739 // TODO: Ref
740 // TODO: Lit
741 // TODO: Range
742 // TODO: Vec
743 // TODO: Mac
744 ));
745
746 named!(pat_wild -> Pat, map!(keyword!("_"), |_| Pat::Wild));
747
748 named!(pat_ident -> Pat, do_parse!(
749 mode: option!(keyword!("ref")) >>
750 mutability: mutability >>
751 name: ident >>
752 subpat: option!(preceded!(punct!("@"), pat)) >>
753 (Pat::Ident(
754 if mode.is_some() {
755 BindingMode::ByRef(mutability)
756 } else {
757 BindingMode::ByValue(mutability)
758 },
759 name,
760 subpat.map(Box::new),
761 ))
762 ));
763
David Tolnay9636c052016-10-02 17:11:17 -0700764 named!(pat_path -> Pat, map!(qpath, |(qself, path)| Pat::Path(qself, path)));
765
David Tolnay89e05672016-10-02 14:39:42 -0700766 named!(capture_by -> CaptureBy, alt!(
767 keyword!("move") => { |_| CaptureBy::Value }
768 |
769 epsilon!() => { |_| CaptureBy::Ref }
770 ));
771
David Tolnay8b07f372016-09-30 10:28:40 -0700772 named!(label -> Ident, map!(lifetime, |lt: Lifetime| lt.ident));
David Tolnayb9c8e322016-09-23 20:48:37 -0700773}
774
David Tolnayf4bbbd92016-09-23 14:41:55 -0700775#[cfg(feature = "printing")]
776mod printing {
777 use super::*;
David Tolnay89e05672016-10-02 14:39:42 -0700778 use {FunctionRetTy, Mutability, Ty};
David Tolnayf4bbbd92016-09-23 14:41:55 -0700779 use quote::{Tokens, ToTokens};
780
781 impl ToTokens for Expr {
782 fn to_tokens(&self, tokens: &mut Tokens) {
783 match *self {
David Tolnay47a877c2016-10-01 16:50:55 -0700784 Expr::Box(ref _inner) => unimplemented!(),
785 Expr::Vec(ref _inner) => unimplemented!(),
David Tolnay9636c052016-10-02 17:11:17 -0700786 Expr::Call(ref func, ref args) => {
787 func.to_tokens(tokens);
788 tokens.append("(");
789 tokens.append_separated(args, ",");
790 tokens.append(")");
791 }
792 Expr::MethodCall(ref ident, ref ascript, ref args) => {
793 args[0].to_tokens(tokens);
794 tokens.append(".");
795 ident.to_tokens(tokens);
796 if ascript.len() > 0 {
797 tokens.append("::");
798 tokens.append("<");
799 tokens.append_separated(ascript, ",");
800 tokens.append(">");
801 }
802 tokens.append("(");
803 tokens.append_separated(&args[1..], ",");
804 tokens.append(")");
805 }
David Tolnay47a877c2016-10-01 16:50:55 -0700806 Expr::Tup(ref fields) => {
807 tokens.append("(");
808 tokens.append_separated(fields, ",");
809 if fields.len() == 1 {
810 tokens.append(",");
811 }
812 tokens.append(")");
813 }
David Tolnay89e05672016-10-02 14:39:42 -0700814 Expr::Binary(op, ref left, ref right) => {
815 left.to_tokens(tokens);
816 op.to_tokens(tokens);
817 right.to_tokens(tokens);
818 }
David Tolnay3c2467c2016-10-02 17:55:08 -0700819 Expr::Unary(op, ref expr) => {
820 op.to_tokens(tokens);
821 expr.to_tokens(tokens);
822 }
David Tolnayf4bbbd92016-09-23 14:41:55 -0700823 Expr::Lit(ref lit) => lit.to_tokens(tokens),
David Tolnay3c2467c2016-10-02 17:55:08 -0700824 Expr::Cast(ref expr, ref ty) => {
825 expr.to_tokens(tokens);
826 tokens.append("as");
827 ty.to_tokens(tokens);
828 }
829 Expr::Type(ref expr, ref ty) => {
830 expr.to_tokens(tokens);
831 tokens.append(":");
832 ty.to_tokens(tokens);
833 }
834 Expr::If(ref cond, ref then_block, ref else_block) => {
835 tokens.append("if");
836 cond.to_tokens(tokens);
837 then_block.to_tokens(tokens);
838 if let Some(ref else_block) = *else_block {
839 tokens.append("else");
840 else_block.to_tokens(tokens);
841 }
842 }
David Tolnay47a877c2016-10-01 16:50:55 -0700843 Expr::IfLet(ref _pat, ref _expr, ref _then_block, ref _else_block) => unimplemented!(),
844 Expr::While(ref _cond, ref _body, ref _label) => unimplemented!(),
845 Expr::WhileLet(ref _pat, ref _expr, ref _body, ref _label) => unimplemented!(),
846 Expr::ForLoop(ref _pat, ref _expr, ref _body, ref _label) => unimplemented!(),
847 Expr::Loop(ref _body, ref _label) => unimplemented!(),
David Tolnayb4ad3b52016-10-01 21:58:13 -0700848 Expr::Match(ref expr, ref arms) => {
849 tokens.append("match");
850 expr.to_tokens(tokens);
851 tokens.append("{");
852 tokens.append_separated(arms, ",");
853 tokens.append("}");
854 }
David Tolnay89e05672016-10-02 14:39:42 -0700855 Expr::Closure(capture, ref decl, ref body) => {
856 capture.to_tokens(tokens);
857 tokens.append("|");
858 for (i, input) in decl.inputs.iter().enumerate() {
859 if i > 0 {
860 tokens.append(",");
861 }
862 input.pat.to_tokens(tokens);
863 match input.ty {
864 Ty::Infer => { /* nothing */ }
865 _ => {
866 tokens.append(":");
867 input.ty.to_tokens(tokens);
868 }
869 }
870 }
871 tokens.append("|");
872 match decl.output {
873 FunctionRetTy::Default => {
874 if body.stmts.len() == 1 {
875 if let Stmt::Expr(ref expr) = body.stmts[0] {
876 expr.to_tokens(tokens);
877 } else {
878 body.to_tokens(tokens);
879 }
880 } else {
881 body.to_tokens(tokens);
882 }
883 }
884 FunctionRetTy::Ty(ref ty) => {
885 tokens.append("->");
886 ty.to_tokens(tokens);
887 body.to_tokens(tokens);
888 }
889 }
890 }
891 Expr::Block(rules, ref block) => {
892 rules.to_tokens(tokens);
893 block.to_tokens(tokens);
894 }
David Tolnay47a877c2016-10-01 16:50:55 -0700895 Expr::Assign(ref _var, ref _expr) => unimplemented!(),
896 Expr::AssignOp(_op, ref _var, ref _expr) => unimplemented!(),
897 Expr::Field(ref _expr, ref _field) => unimplemented!(),
898 Expr::TupField(ref _expr, _field) => unimplemented!(),
899 Expr::Index(ref _expr, ref _index) => unimplemented!(),
900 Expr::Range(ref _from, ref _to, _limits) => unimplemented!(),
David Tolnay89e05672016-10-02 14:39:42 -0700901 Expr::Path(None, ref path) => {
902 path.to_tokens(tokens);
903 }
904 Expr::Path(Some(ref qself), ref path) => {
905 tokens.append("<");
906 qself.ty.to_tokens(tokens);
907 if qself.position > 0 {
908 tokens.append("as");
909 for (i, segment) in path.segments.iter()
910 .take(qself.position)
911 .enumerate()
912 {
913 if i > 0 || path.global {
914 tokens.append("::");
915 }
916 segment.to_tokens(tokens);
917 }
918 }
919 tokens.append(">");
920 for segment in path.segments.iter().skip(qself.position) {
921 tokens.append("::");
922 segment.to_tokens(tokens);
923 }
924 }
David Tolnay3c2467c2016-10-02 17:55:08 -0700925 Expr::AddrOf(mutability, ref expr) => {
926 tokens.append("&");
927 mutability.to_tokens(tokens);
928 expr.to_tokens(tokens);
929 }
930 Expr::Break(ref opt_label) => {
931 tokens.append("break");
932 opt_label.to_tokens(tokens);
933 }
934 Expr::Continue(ref opt_label) => {
935 tokens.append("continue");
936 opt_label.to_tokens(tokens);
937 }
David Tolnay42602292016-10-01 22:25:45 -0700938 Expr::Ret(ref opt_expr) => {
939 tokens.append("return");
940 opt_expr.to_tokens(tokens);
941 }
David Tolnay47a877c2016-10-01 16:50:55 -0700942 Expr::Mac(ref _mac) => unimplemented!(),
943 Expr::Struct(ref _path, ref _fields, ref _base) => unimplemented!(),
944 Expr::Repeat(ref _expr, ref _times) => unimplemented!(),
David Tolnay89e05672016-10-02 14:39:42 -0700945 Expr::Paren(ref expr) => {
946 tokens.append("(");
947 expr.to_tokens(tokens);
948 tokens.append(")");
949 }
David Tolnay3c2467c2016-10-02 17:55:08 -0700950 Expr::Try(ref expr) => {
951 expr.to_tokens(tokens);
952 tokens.append("?");
953 }
David Tolnayf4bbbd92016-09-23 14:41:55 -0700954 }
955 }
956 }
David Tolnayb4ad3b52016-10-01 21:58:13 -0700957
David Tolnay89e05672016-10-02 14:39:42 -0700958 impl ToTokens for BinOp {
959 fn to_tokens(&self, tokens: &mut Tokens) {
960 match *self {
961 BinOp::Add => tokens.append("+"),
962 BinOp::Sub => tokens.append("-"),
963 BinOp::Mul => tokens.append("*"),
964 BinOp::Div => tokens.append("/"),
965 BinOp::Rem => tokens.append("%"),
966 BinOp::And => tokens.append("&&"),
967 BinOp::Or => tokens.append("||"),
968 BinOp::BitXor => tokens.append("^"),
969 BinOp::BitAnd => tokens.append("&"),
970 BinOp::BitOr => tokens.append("|"),
971 BinOp::Shl => tokens.append("<<"),
972 BinOp::Shr => tokens.append(">>"),
973 BinOp::Eq => tokens.append("=="),
974 BinOp::Lt => tokens.append("<"),
975 BinOp::Le => tokens.append("<="),
976 BinOp::Ne => tokens.append("!="),
977 BinOp::Ge => tokens.append(">="),
978 BinOp::Gt => tokens.append(">"),
979 }
980 }
981 }
982
David Tolnay3c2467c2016-10-02 17:55:08 -0700983 impl ToTokens for UnOp {
984 fn to_tokens(&self, tokens: &mut Tokens) {
985 match *self {
986 UnOp::Deref => tokens.append("*"),
987 UnOp::Not => tokens.append("!"),
988 UnOp::Neg => tokens.append("-"),
989 }
990 }
991 }
992
David Tolnayb4ad3b52016-10-01 21:58:13 -0700993 impl ToTokens for Arm {
994 fn to_tokens(&self, tokens: &mut Tokens) {
995 for attr in &self.attrs {
996 attr.to_tokens(tokens);
997 }
998 tokens.append_separated(&self.pats, "|");
999 if let Some(ref guard) = self.guard {
1000 tokens.append("if");
1001 guard.to_tokens(tokens);
1002 }
1003 tokens.append("=>");
1004 self.body.to_tokens(tokens);
1005 match *self.body {
David Tolnay89e05672016-10-02 14:39:42 -07001006 Expr::Block(_, _) => { /* no comma */ }
David Tolnayb4ad3b52016-10-01 21:58:13 -07001007 _ => tokens.append(","),
1008 }
1009 }
1010 }
1011
1012 impl ToTokens for Pat {
1013 fn to_tokens(&self, tokens: &mut Tokens) {
1014 match *self {
1015 Pat::Wild => tokens.append("_"),
1016 Pat::Ident(mode, ref ident, ref subpat) => {
1017 mode.to_tokens(tokens);
1018 ident.to_tokens(tokens);
1019 if let Some(ref subpat) = *subpat {
1020 tokens.append("@");
1021 subpat.to_tokens(tokens);
1022 }
1023 }
1024 Pat::Struct(ref _path, ref _fields, _dots) => unimplemented!(),
1025 Pat::TupleStruct(ref _path, ref _pats, _dotpos) => unimplemented!(),
1026 Pat::Path(ref _qself, ref _path) => unimplemented!(),
1027 Pat::Tuple(ref _pats, _dotpos) => unimplemented!(),
1028 Pat::Box(ref _inner) => unimplemented!(),
1029 Pat::Ref(ref _target, _mutability) => unimplemented!(),
1030 Pat::Lit(ref _expr) => unimplemented!(),
1031 Pat::Range(ref _lower, ref _upper) => unimplemented!(),
1032 Pat::Vec(ref _before, ref _dots, ref _after) => unimplemented!(),
1033 Pat::Mac(ref _mac) => unimplemented!(),
1034 }
1035 }
1036 }
1037
1038 impl ToTokens for BindingMode {
1039 fn to_tokens(&self, tokens: &mut Tokens) {
1040 match *self {
1041 BindingMode::ByRef(Mutability::Immutable) => {
1042 tokens.append("ref");
1043 }
1044 BindingMode::ByRef(Mutability::Mutable) => {
1045 tokens.append("ref");
1046 tokens.append("mut");
1047 }
1048 BindingMode::ByValue(Mutability::Immutable) => {}
1049 BindingMode::ByValue(Mutability::Mutable) => {
1050 tokens.append("mut");
1051 }
1052 }
1053 }
1054 }
David Tolnay42602292016-10-01 22:25:45 -07001055
David Tolnay89e05672016-10-02 14:39:42 -07001056 impl ToTokens for CaptureBy {
1057 fn to_tokens(&self, tokens: &mut Tokens) {
1058 match *self {
1059 CaptureBy::Value => tokens.append("move"),
1060 CaptureBy::Ref => { /* nothing */ }
1061 }
1062 }
1063 }
1064
David Tolnay42602292016-10-01 22:25:45 -07001065 impl ToTokens for Block {
1066 fn to_tokens(&self, tokens: &mut Tokens) {
David Tolnay42602292016-10-01 22:25:45 -07001067 tokens.append("{");
1068 for stmt in &self.stmts {
1069 stmt.to_tokens(tokens);
1070 }
1071 tokens.append("}");
1072 }
1073 }
1074
1075 impl ToTokens for BlockCheckMode {
1076 fn to_tokens(&self, tokens: &mut Tokens) {
1077 match *self {
David Tolnay89e05672016-10-02 14:39:42 -07001078 BlockCheckMode::Default => { /* nothing */ }
David Tolnay42602292016-10-01 22:25:45 -07001079 BlockCheckMode::Unsafe => tokens.append("unsafe"),
1080 }
1081 }
1082 }
1083
1084 impl ToTokens for Stmt {
1085 fn to_tokens(&self, tokens: &mut Tokens) {
1086 match *self {
1087 Stmt::Local(ref _local) => unimplemented!(),
1088 Stmt::Item(ref item) => item.to_tokens(tokens),
1089 Stmt::Expr(ref expr) => expr.to_tokens(tokens),
1090 Stmt::Semi(ref expr) => {
1091 expr.to_tokens(tokens);
1092 tokens.append(";");
1093 }
1094 Stmt::Mac(ref _mac) => unimplemented!(),
1095 }
1096 }
1097 }
David Tolnayf4bbbd92016-09-23 14:41:55 -07001098}