blob: e0cf9aadf2c4ae169c670868238919b9a686f530 [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 Tolnaya96a3fa2016-09-24 07:17:42 -0700376 // TODO: AddrOf
Gregory Katzfd6935d2016-09-30 22:51:25 -0400377 |
378 expr_break
379 |
380 expr_continue
381 |
382 expr_ret
David Tolnaya96a3fa2016-09-24 07:17:42 -0700383 // TODO: Mac
384 // TODO: Struct
385 // TODO: Repeat
David Tolnayfa0edf22016-09-23 22:58:24 -0700386 ) >>
387 many0!(alt!(
David Tolnay939766a2016-09-23 23:48:12 -0700388 tap!(args: and_call => {
389 e = Expr::Call(Box::new(e), args);
David Tolnayfa0edf22016-09-23 22:58:24 -0700390 })
391 |
David Tolnay939766a2016-09-23 23:48:12 -0700392 tap!(more: and_method_call => {
393 let (method, ascript, mut args) = more;
David Tolnayfa0edf22016-09-23 22:58:24 -0700394 args.insert(0, e);
395 e = Expr::MethodCall(method, ascript, args);
396 })
397 |
David Tolnay939766a2016-09-23 23:48:12 -0700398 tap!(more: and_binary => {
399 let (op, other) = more;
David Tolnayfa0edf22016-09-23 22:58:24 -0700400 e = Expr::Binary(op, Box::new(e), Box::new(other));
401 })
David Tolnay939766a2016-09-23 23:48:12 -0700402 |
403 tap!(ty: and_cast => {
404 e = Expr::Cast(Box::new(e), Box::new(ty));
405 })
406 |
407 tap!(ty: and_ascription => {
408 e = Expr::Type(Box::new(e), Box::new(ty));
409 })
David Tolnaya96a3fa2016-09-24 07:17:42 -0700410 // TODO: Assign
411 // TODO: AssignOp
412 // TODO: Field
413 // TODO: TupField
414 // TODO: Index
415 // TODO: Range
416 // TODO: Try
David Tolnayfa0edf22016-09-23 22:58:24 -0700417 )) >>
418 (e)
David Tolnayb9c8e322016-09-23 20:48:37 -0700419 ));
420
David Tolnay89e05672016-10-02 14:39:42 -0700421 named!(expr_paren -> Expr, do_parse!(
422 punct!("(") >>
423 e: expr >>
424 punct!(")") >>
425 (Expr::Paren(Box::new(e)))
426 ));
427
David Tolnay939766a2016-09-23 23:48:12 -0700428 named!(expr_box -> Expr, do_parse!(
David Tolnay10413f02016-09-30 09:12:02 -0700429 keyword!("box") >>
David Tolnayb9c8e322016-09-23 20:48:37 -0700430 inner: expr >>
431 (Expr::Box(Box::new(inner)))
432 ));
David Tolnayfa0edf22016-09-23 22:58:24 -0700433
David Tolnay939766a2016-09-23 23:48:12 -0700434 named!(expr_vec -> Expr, do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700435 punct!("[") >>
436 elems: separated_list!(punct!(","), expr) >>
437 punct!("]") >>
438 (Expr::Vec(elems))
439 ));
440
David Tolnay939766a2016-09-23 23:48:12 -0700441 named!(and_call -> Vec<Expr>, do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700442 punct!("(") >>
443 args: separated_list!(punct!(","), expr) >>
444 punct!(")") >>
445 (args)
446 ));
447
David Tolnay939766a2016-09-23 23:48:12 -0700448 named!(and_method_call -> (Ident, Vec<Ty>, Vec<Expr>), do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700449 punct!(".") >>
450 method: ident >>
451 ascript: opt_vec!(delimited!(
452 punct!("<"),
453 separated_list!(punct!(","), ty),
454 punct!(">")
455 )) >>
456 punct!("(") >>
457 args: separated_list!(punct!(","), expr) >>
458 punct!(")") >>
459 (method, ascript, args)
460 ));
461
David Tolnay939766a2016-09-23 23:48:12 -0700462 named!(expr_tup -> Expr, do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700463 punct!("(") >>
464 elems: separated_list!(punct!(","), expr) >>
David Tolnay89e05672016-10-02 14:39:42 -0700465 option!(punct!(",")) >>
David Tolnayfa0edf22016-09-23 22:58:24 -0700466 punct!(")") >>
467 (Expr::Tup(elems))
468 ));
469
David Tolnay939766a2016-09-23 23:48:12 -0700470 named!(and_binary -> (BinOp, Expr), tuple!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700471 alt!(
472 punct!("&&") => { |_| BinOp::And }
473 |
474 punct!("||") => { |_| BinOp::Or }
475 |
476 punct!("<<") => { |_| BinOp::Shl }
477 |
478 punct!(">>") => { |_| BinOp::Shr }
479 |
480 punct!("==") => { |_| BinOp::Eq }
481 |
482 punct!("<=") => { |_| BinOp::Le }
483 |
484 punct!("!=") => { |_| BinOp::Ne }
485 |
486 punct!(">=") => { |_| BinOp::Ge }
487 |
488 punct!("+") => { |_| BinOp::Add }
489 |
490 punct!("-") => { |_| BinOp::Sub }
491 |
492 punct!("*") => { |_| BinOp::Mul }
493 |
494 punct!("/") => { |_| BinOp::Div }
495 |
496 punct!("%") => { |_| BinOp::Rem }
497 |
498 punct!("^") => { |_| BinOp::BitXor }
499 |
500 punct!("&") => { |_| BinOp::BitAnd }
501 |
502 punct!("|") => { |_| BinOp::BitOr }
503 |
504 punct!("<") => { |_| BinOp::Lt }
505 |
506 punct!(">") => { |_| BinOp::Gt }
507 ),
508 expr
509 ));
510
David Tolnay939766a2016-09-23 23:48:12 -0700511 named!(expr_unary -> Expr, do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700512 operator: alt!(
513 punct!("*") => { |_| UnOp::Deref }
514 |
515 punct!("!") => { |_| UnOp::Not }
516 |
517 punct!("-") => { |_| UnOp::Neg }
518 ) >>
519 operand: expr >>
520 (Expr::Unary(operator, Box::new(operand)))
521 ));
David Tolnay939766a2016-09-23 23:48:12 -0700522
523 named!(expr_lit -> Expr, map!(lit, Expr::Lit));
524
525 named!(and_cast -> Ty, do_parse!(
David Tolnay10413f02016-09-30 09:12:02 -0700526 keyword!("as") >>
David Tolnay939766a2016-09-23 23:48:12 -0700527 ty: ty >>
528 (ty)
529 ));
530
531 named!(and_ascription -> Ty, preceded!(punct!(":"), ty));
532
533 named!(expr_if -> Expr, do_parse!(
David Tolnay10413f02016-09-30 09:12:02 -0700534 keyword!("if") >>
David Tolnay939766a2016-09-23 23:48:12 -0700535 cond: expr >>
536 punct!("{") >>
537 then_block: within_block >>
538 punct!("}") >>
539 else_block: option!(preceded!(
David Tolnay10413f02016-09-30 09:12:02 -0700540 keyword!("else"),
David Tolnay939766a2016-09-23 23:48:12 -0700541 alt!(
542 expr_if
543 |
544 do_parse!(
545 punct!("{") >>
546 else_block: within_block >>
547 punct!("}") >>
David Tolnay89e05672016-10-02 14:39:42 -0700548 (Expr::Block(BlockCheckMode::Default, Block {
David Tolnay939766a2016-09-23 23:48:12 -0700549 stmts: else_block,
David Tolnay89e05672016-10-02 14:39:42 -0700550 }))
David Tolnay939766a2016-09-23 23:48:12 -0700551 )
552 )
553 )) >>
554 (Expr::If(
555 Box::new(cond),
David Tolnay89e05672016-10-02 14:39:42 -0700556 Block {
David Tolnay939766a2016-09-23 23:48:12 -0700557 stmts: then_block,
David Tolnay89e05672016-10-02 14:39:42 -0700558 },
David Tolnay939766a2016-09-23 23:48:12 -0700559 else_block.map(Box::new),
560 ))
561 ));
562
Gregory Katze5f35682016-09-27 14:20:55 -0400563 named!(expr_loop -> Expr, do_parse!(
David Tolnay8b07f372016-09-30 10:28:40 -0700564 lbl: option!(terminated!(label, punct!(":"))) >>
David Tolnay10413f02016-09-30 09:12:02 -0700565 keyword!("loop") >>
Gregory Katze5f35682016-09-27 14:20:55 -0400566 loop_block: block >>
David Tolnay89e05672016-10-02 14:39:42 -0700567 (Expr::Loop(loop_block, lbl))
Gregory Katze5f35682016-09-27 14:20:55 -0400568 ));
569
David Tolnayb4ad3b52016-10-01 21:58:13 -0700570 named!(expr_match -> Expr, do_parse!(
571 keyword!("match") >>
572 obj: expr >>
573 punct!("{") >>
574 arms: many0!(do_parse!(
575 attrs: many0!(outer_attr) >>
576 pats: separated_nonempty_list!(punct!("|"), pat) >>
577 guard: option!(preceded!(keyword!("if"), expr)) >>
578 punct!("=>") >>
579 body: alt!(
580 terminated!(expr, punct!(","))
581 |
David Tolnay89e05672016-10-02 14:39:42 -0700582 map!(block, |blk| Expr::Block(BlockCheckMode::Default, blk))
David Tolnayb4ad3b52016-10-01 21:58:13 -0700583 ) >>
584 (Arm {
585 attrs: attrs,
586 pats: pats,
587 guard: guard.map(Box::new),
588 body: Box::new(body),
589 })
590 )) >>
591 punct!("}") >>
592 (Expr::Match(Box::new(obj), arms))
593 ));
594
David Tolnay89e05672016-10-02 14:39:42 -0700595 named!(expr_closure -> Expr, do_parse!(
596 capture: capture_by >>
597 punct!("|") >>
598 inputs: separated_list!(punct!(","), closure_arg) >>
599 punct!("|") >>
600 ret_and_body: alt!(
601 do_parse!(
602 punct!("->") >>
603 ty: ty >>
604 body: block >>
605 ((FunctionRetTy::Ty(ty), body))
606 )
607 |
608 map!(expr, |e| (
609 FunctionRetTy::Default,
610 Block {
611 stmts: vec![Stmt::Expr(Box::new(e))],
612 },
613 ))
614 ) >>
615 (Expr::Closure(
616 capture,
617 Box::new(FnDecl {
618 inputs: inputs,
619 output: ret_and_body.0,
620 }),
621 ret_and_body.1,
622 ))
623 ));
624
625 named!(closure_arg -> FnArg, do_parse!(
626 pat: pat >>
627 ty: option!(preceded!(punct!(":"), ty)) >>
628 (FnArg {
629 pat: pat,
630 ty: ty.unwrap_or(Ty::Infer),
631 })
632 ));
633
Gregory Katz3e562cc2016-09-28 18:33:02 -0400634 named!(expr_while -> Expr, do_parse!(
David Tolnay8b07f372016-09-30 10:28:40 -0700635 lbl: option!(terminated!(label, punct!(":"))) >>
David Tolnay57ffbde2016-09-30 09:38:04 -0700636 keyword!("while") >>
Gregory Katz3e562cc2016-09-28 18:33:02 -0400637 cond: expr >>
638 while_block: block >>
639 (Expr::While(
640 Box::new(cond),
David Tolnay89e05672016-10-02 14:39:42 -0700641 while_block,
David Tolnay8b07f372016-09-30 10:28:40 -0700642 lbl,
Gregory Katz3e562cc2016-09-28 18:33:02 -0400643 ))
644 ));
645
Gregory Katzfd6935d2016-09-30 22:51:25 -0400646 named!(expr_continue -> Expr, do_parse!(
647 keyword!("continue") >>
648 lbl: option!(label) >>
649 (Expr::Continue(
650 lbl,
651 ))
652 ));
653
654 named!(expr_break -> Expr, do_parse!(
655 keyword!("break") >>
656 lbl: option!(label) >>
657 (Expr::Break(
658 lbl,
659 ))
660 ));
661
662 named!(expr_ret -> Expr, do_parse!(
663 keyword!("return") >>
664 ret_value: option!(expr) >>
665 (Expr::Ret(
666 ret_value.map(Box::new),
667 ))
668 ));
669
David Tolnay42602292016-10-01 22:25:45 -0700670 named!(expr_block -> Expr, do_parse!(
David Tolnay939766a2016-09-23 23:48:12 -0700671 rules: block_check_mode >>
David Tolnay42602292016-10-01 22:25:45 -0700672 b: block >>
David Tolnay89e05672016-10-02 14:39:42 -0700673 (Expr::Block(rules, Block {
David Tolnay42602292016-10-01 22:25:45 -0700674 stmts: b.stmts,
David Tolnay89e05672016-10-02 14:39:42 -0700675 }))
676 ));
677
David Tolnay9636c052016-10-02 17:11:17 -0700678 named!(expr_path -> Expr, map!(qpath, |(qself, path)| Expr::Path(qself, path)));
David Tolnay42602292016-10-01 22:25:45 -0700679
680 named!(pub block -> Block, do_parse!(
David Tolnay939766a2016-09-23 23:48:12 -0700681 punct!("{") >>
682 stmts: within_block >>
683 punct!("}") >>
684 (Block {
685 stmts: stmts,
David Tolnay939766a2016-09-23 23:48:12 -0700686 })
687 ));
688
689 named!(block_check_mode -> BlockCheckMode, alt!(
David Tolnay10413f02016-09-30 09:12:02 -0700690 keyword!("unsafe") => { |_| BlockCheckMode::Unsafe }
David Tolnay939766a2016-09-23 23:48:12 -0700691 |
692 epsilon!() => { |_| BlockCheckMode::Default }
693 ));
694
695 named!(within_block -> Vec<Stmt>, do_parse!(
David Tolnay181bac52016-09-24 00:10:05 -0700696 mut most: many0!(standalone_stmt) >>
David Tolnay939766a2016-09-23 23:48:12 -0700697 last: option!(expr) >>
698 (match last {
699 None => most,
700 Some(last) => {
David Tolnay939766a2016-09-23 23:48:12 -0700701 most.push(Stmt::Expr(Box::new(last)));
702 most
703 }
704 })
705 ));
706
707 named!(standalone_stmt -> Stmt, alt!(
David Tolnaya96a3fa2016-09-24 07:17:42 -0700708 // TODO: local
709 // TODO: item
710 // TODO: expr
David Tolnay939766a2016-09-23 23:48:12 -0700711 stmt_semi
David Tolnaya96a3fa2016-09-24 07:17:42 -0700712 // TODO: mac
David Tolnay939766a2016-09-23 23:48:12 -0700713 ));
714
715 named!(stmt_semi -> Stmt, do_parse!(
716 e: expr >>
717 punct!(";") >>
718 (Stmt::Semi(Box::new(e)))
719 ));
David Tolnay8b07f372016-09-30 10:28:40 -0700720
David Tolnay42602292016-10-01 22:25:45 -0700721 named!(pub pat -> Pat, alt!(
David Tolnayb4ad3b52016-10-01 21:58:13 -0700722 pat_wild
723 |
724 pat_ident
725 // TODO: Struct
726 // TODO: TupleStruct
David Tolnay9636c052016-10-02 17:11:17 -0700727 |
728 pat_path
David Tolnayb4ad3b52016-10-01 21:58:13 -0700729 // TODO: Tuple
730 // TODO: Box
731 // TODO: Ref
732 // TODO: Lit
733 // TODO: Range
734 // TODO: Vec
735 // TODO: Mac
736 ));
737
738 named!(pat_wild -> Pat, map!(keyword!("_"), |_| Pat::Wild));
739
740 named!(pat_ident -> Pat, do_parse!(
741 mode: option!(keyword!("ref")) >>
742 mutability: mutability >>
743 name: ident >>
744 subpat: option!(preceded!(punct!("@"), pat)) >>
745 (Pat::Ident(
746 if mode.is_some() {
747 BindingMode::ByRef(mutability)
748 } else {
749 BindingMode::ByValue(mutability)
750 },
751 name,
752 subpat.map(Box::new),
753 ))
754 ));
755
David Tolnay9636c052016-10-02 17:11:17 -0700756 named!(pat_path -> Pat, map!(qpath, |(qself, path)| Pat::Path(qself, path)));
757
David Tolnay89e05672016-10-02 14:39:42 -0700758 named!(capture_by -> CaptureBy, alt!(
759 keyword!("move") => { |_| CaptureBy::Value }
760 |
761 epsilon!() => { |_| CaptureBy::Ref }
762 ));
763
David Tolnay8b07f372016-09-30 10:28:40 -0700764 named!(label -> Ident, map!(lifetime, |lt: Lifetime| lt.ident));
David Tolnayb9c8e322016-09-23 20:48:37 -0700765}
766
David Tolnayf4bbbd92016-09-23 14:41:55 -0700767#[cfg(feature = "printing")]
768mod printing {
769 use super::*;
David Tolnay89e05672016-10-02 14:39:42 -0700770 use {FunctionRetTy, Mutability, Ty};
David Tolnayf4bbbd92016-09-23 14:41:55 -0700771 use quote::{Tokens, ToTokens};
772
773 impl ToTokens for Expr {
774 fn to_tokens(&self, tokens: &mut Tokens) {
775 match *self {
David Tolnay47a877c2016-10-01 16:50:55 -0700776 Expr::Box(ref _inner) => unimplemented!(),
777 Expr::Vec(ref _inner) => unimplemented!(),
David Tolnay9636c052016-10-02 17:11:17 -0700778 Expr::Call(ref func, ref args) => {
779 func.to_tokens(tokens);
780 tokens.append("(");
781 tokens.append_separated(args, ",");
782 tokens.append(")");
783 }
784 Expr::MethodCall(ref ident, ref ascript, ref args) => {
785 args[0].to_tokens(tokens);
786 tokens.append(".");
787 ident.to_tokens(tokens);
788 if ascript.len() > 0 {
789 tokens.append("::");
790 tokens.append("<");
791 tokens.append_separated(ascript, ",");
792 tokens.append(">");
793 }
794 tokens.append("(");
795 tokens.append_separated(&args[1..], ",");
796 tokens.append(")");
797 }
David Tolnay47a877c2016-10-01 16:50:55 -0700798 Expr::Tup(ref fields) => {
799 tokens.append("(");
800 tokens.append_separated(fields, ",");
801 if fields.len() == 1 {
802 tokens.append(",");
803 }
804 tokens.append(")");
805 }
David Tolnay89e05672016-10-02 14:39:42 -0700806 Expr::Binary(op, ref left, ref right) => {
807 left.to_tokens(tokens);
808 op.to_tokens(tokens);
809 right.to_tokens(tokens);
810 }
David Tolnay47a877c2016-10-01 16:50:55 -0700811 Expr::Unary(_op, ref _expr) => unimplemented!(),
David Tolnayf4bbbd92016-09-23 14:41:55 -0700812 Expr::Lit(ref lit) => lit.to_tokens(tokens),
David Tolnay47a877c2016-10-01 16:50:55 -0700813 Expr::Cast(ref _expr, ref _ty) => unimplemented!(),
814 Expr::Type(ref _expr, ref _ty) => unimplemented!(),
815 Expr::If(ref _cond, ref _then_block, ref _else_block) => unimplemented!(),
816 Expr::IfLet(ref _pat, ref _expr, ref _then_block, ref _else_block) => unimplemented!(),
817 Expr::While(ref _cond, ref _body, ref _label) => unimplemented!(),
818 Expr::WhileLet(ref _pat, ref _expr, ref _body, ref _label) => unimplemented!(),
819 Expr::ForLoop(ref _pat, ref _expr, ref _body, ref _label) => unimplemented!(),
820 Expr::Loop(ref _body, ref _label) => unimplemented!(),
David Tolnayb4ad3b52016-10-01 21:58:13 -0700821 Expr::Match(ref expr, ref arms) => {
822 tokens.append("match");
823 expr.to_tokens(tokens);
824 tokens.append("{");
825 tokens.append_separated(arms, ",");
826 tokens.append("}");
827 }
David Tolnay89e05672016-10-02 14:39:42 -0700828 Expr::Closure(capture, ref decl, ref body) => {
829 capture.to_tokens(tokens);
830 tokens.append("|");
831 for (i, input) in decl.inputs.iter().enumerate() {
832 if i > 0 {
833 tokens.append(",");
834 }
835 input.pat.to_tokens(tokens);
836 match input.ty {
837 Ty::Infer => { /* nothing */ }
838 _ => {
839 tokens.append(":");
840 input.ty.to_tokens(tokens);
841 }
842 }
843 }
844 tokens.append("|");
845 match decl.output {
846 FunctionRetTy::Default => {
847 if body.stmts.len() == 1 {
848 if let Stmt::Expr(ref expr) = body.stmts[0] {
849 expr.to_tokens(tokens);
850 } else {
851 body.to_tokens(tokens);
852 }
853 } else {
854 body.to_tokens(tokens);
855 }
856 }
857 FunctionRetTy::Ty(ref ty) => {
858 tokens.append("->");
859 ty.to_tokens(tokens);
860 body.to_tokens(tokens);
861 }
862 }
863 }
864 Expr::Block(rules, ref block) => {
865 rules.to_tokens(tokens);
866 block.to_tokens(tokens);
867 }
David Tolnay47a877c2016-10-01 16:50:55 -0700868 Expr::Assign(ref _var, ref _expr) => unimplemented!(),
869 Expr::AssignOp(_op, ref _var, ref _expr) => unimplemented!(),
870 Expr::Field(ref _expr, ref _field) => unimplemented!(),
871 Expr::TupField(ref _expr, _field) => unimplemented!(),
872 Expr::Index(ref _expr, ref _index) => unimplemented!(),
873 Expr::Range(ref _from, ref _to, _limits) => unimplemented!(),
David Tolnay89e05672016-10-02 14:39:42 -0700874 Expr::Path(None, ref path) => {
875 path.to_tokens(tokens);
876 }
877 Expr::Path(Some(ref qself), ref path) => {
878 tokens.append("<");
879 qself.ty.to_tokens(tokens);
880 if qself.position > 0 {
881 tokens.append("as");
882 for (i, segment) in path.segments.iter()
883 .take(qself.position)
884 .enumerate()
885 {
886 if i > 0 || path.global {
887 tokens.append("::");
888 }
889 segment.to_tokens(tokens);
890 }
891 }
892 tokens.append(">");
893 for segment in path.segments.iter().skip(qself.position) {
894 tokens.append("::");
895 segment.to_tokens(tokens);
896 }
897 }
David Tolnay47a877c2016-10-01 16:50:55 -0700898 Expr::AddrOf(_mutability, ref _expr) => unimplemented!(),
899 Expr::Break(ref _label) => unimplemented!(),
900 Expr::Continue(ref _label) => unimplemented!(),
David Tolnay42602292016-10-01 22:25:45 -0700901 Expr::Ret(ref opt_expr) => {
902 tokens.append("return");
903 opt_expr.to_tokens(tokens);
904 }
David Tolnay47a877c2016-10-01 16:50:55 -0700905 Expr::Mac(ref _mac) => unimplemented!(),
906 Expr::Struct(ref _path, ref _fields, ref _base) => unimplemented!(),
907 Expr::Repeat(ref _expr, ref _times) => unimplemented!(),
David Tolnay89e05672016-10-02 14:39:42 -0700908 Expr::Paren(ref expr) => {
909 tokens.append("(");
910 expr.to_tokens(tokens);
911 tokens.append(")");
912 }
David Tolnay47a877c2016-10-01 16:50:55 -0700913 Expr::Try(ref _expr) => unimplemented!(),
David Tolnayf4bbbd92016-09-23 14:41:55 -0700914 }
915 }
916 }
David Tolnayb4ad3b52016-10-01 21:58:13 -0700917
David Tolnay89e05672016-10-02 14:39:42 -0700918 impl ToTokens for BinOp {
919 fn to_tokens(&self, tokens: &mut Tokens) {
920 match *self {
921 BinOp::Add => tokens.append("+"),
922 BinOp::Sub => tokens.append("-"),
923 BinOp::Mul => tokens.append("*"),
924 BinOp::Div => tokens.append("/"),
925 BinOp::Rem => tokens.append("%"),
926 BinOp::And => tokens.append("&&"),
927 BinOp::Or => tokens.append("||"),
928 BinOp::BitXor => tokens.append("^"),
929 BinOp::BitAnd => tokens.append("&"),
930 BinOp::BitOr => tokens.append("|"),
931 BinOp::Shl => tokens.append("<<"),
932 BinOp::Shr => tokens.append(">>"),
933 BinOp::Eq => tokens.append("=="),
934 BinOp::Lt => tokens.append("<"),
935 BinOp::Le => tokens.append("<="),
936 BinOp::Ne => tokens.append("!="),
937 BinOp::Ge => tokens.append(">="),
938 BinOp::Gt => tokens.append(">"),
939 }
940 }
941 }
942
David Tolnayb4ad3b52016-10-01 21:58:13 -0700943 impl ToTokens for Arm {
944 fn to_tokens(&self, tokens: &mut Tokens) {
945 for attr in &self.attrs {
946 attr.to_tokens(tokens);
947 }
948 tokens.append_separated(&self.pats, "|");
949 if let Some(ref guard) = self.guard {
950 tokens.append("if");
951 guard.to_tokens(tokens);
952 }
953 tokens.append("=>");
954 self.body.to_tokens(tokens);
955 match *self.body {
David Tolnay89e05672016-10-02 14:39:42 -0700956 Expr::Block(_, _) => { /* no comma */ }
David Tolnayb4ad3b52016-10-01 21:58:13 -0700957 _ => tokens.append(","),
958 }
959 }
960 }
961
962 impl ToTokens for Pat {
963 fn to_tokens(&self, tokens: &mut Tokens) {
964 match *self {
965 Pat::Wild => tokens.append("_"),
966 Pat::Ident(mode, ref ident, ref subpat) => {
967 mode.to_tokens(tokens);
968 ident.to_tokens(tokens);
969 if let Some(ref subpat) = *subpat {
970 tokens.append("@");
971 subpat.to_tokens(tokens);
972 }
973 }
974 Pat::Struct(ref _path, ref _fields, _dots) => unimplemented!(),
975 Pat::TupleStruct(ref _path, ref _pats, _dotpos) => unimplemented!(),
976 Pat::Path(ref _qself, ref _path) => unimplemented!(),
977 Pat::Tuple(ref _pats, _dotpos) => unimplemented!(),
978 Pat::Box(ref _inner) => unimplemented!(),
979 Pat::Ref(ref _target, _mutability) => unimplemented!(),
980 Pat::Lit(ref _expr) => unimplemented!(),
981 Pat::Range(ref _lower, ref _upper) => unimplemented!(),
982 Pat::Vec(ref _before, ref _dots, ref _after) => unimplemented!(),
983 Pat::Mac(ref _mac) => unimplemented!(),
984 }
985 }
986 }
987
988 impl ToTokens for BindingMode {
989 fn to_tokens(&self, tokens: &mut Tokens) {
990 match *self {
991 BindingMode::ByRef(Mutability::Immutable) => {
992 tokens.append("ref");
993 }
994 BindingMode::ByRef(Mutability::Mutable) => {
995 tokens.append("ref");
996 tokens.append("mut");
997 }
998 BindingMode::ByValue(Mutability::Immutable) => {}
999 BindingMode::ByValue(Mutability::Mutable) => {
1000 tokens.append("mut");
1001 }
1002 }
1003 }
1004 }
David Tolnay42602292016-10-01 22:25:45 -07001005
David Tolnay89e05672016-10-02 14:39:42 -07001006 impl ToTokens for CaptureBy {
1007 fn to_tokens(&self, tokens: &mut Tokens) {
1008 match *self {
1009 CaptureBy::Value => tokens.append("move"),
1010 CaptureBy::Ref => { /* nothing */ }
1011 }
1012 }
1013 }
1014
David Tolnay42602292016-10-01 22:25:45 -07001015 impl ToTokens for Block {
1016 fn to_tokens(&self, tokens: &mut Tokens) {
David Tolnay42602292016-10-01 22:25:45 -07001017 tokens.append("{");
1018 for stmt in &self.stmts {
1019 stmt.to_tokens(tokens);
1020 }
1021 tokens.append("}");
1022 }
1023 }
1024
1025 impl ToTokens for BlockCheckMode {
1026 fn to_tokens(&self, tokens: &mut Tokens) {
1027 match *self {
David Tolnay89e05672016-10-02 14:39:42 -07001028 BlockCheckMode::Default => { /* nothing */ }
David Tolnay42602292016-10-01 22:25:45 -07001029 BlockCheckMode::Unsafe => tokens.append("unsafe"),
1030 }
1031 }
1032 }
1033
1034 impl ToTokens for Stmt {
1035 fn to_tokens(&self, tokens: &mut Tokens) {
1036 match *self {
1037 Stmt::Local(ref _local) => unimplemented!(),
1038 Stmt::Item(ref item) => item.to_tokens(tokens),
1039 Stmt::Expr(ref expr) => expr.to_tokens(tokens),
1040 Stmt::Semi(ref expr) => {
1041 expr.to_tokens(tokens);
1042 tokens.append(";");
1043 }
1044 Stmt::Mac(ref _mac) => unimplemented!(),
1045 }
1046 }
1047 }
David Tolnayf4bbbd92016-09-23 14:41:55 -07001048}