blob: 65a3902047572c0d0015aa4fd5377f5849f71d93 [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 Tolnay89e05672016-10-02 14:39:42 -0700337 use {FnArg, FnDecl, FunctionRetTy, Ident, Lifetime, Path, QSelf, 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 Tolnay89e05672016-10-02 14:39:42 -0700342 use ty::parsing::{mutability, path, path_segment, 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
376 |
377 expr_qpath
David Tolnaya96a3fa2016-09-24 07:17:42 -0700378 // TODO: AddrOf
Gregory Katzfd6935d2016-09-30 22:51:25 -0400379 |
380 expr_break
381 |
382 expr_continue
383 |
384 expr_ret
David Tolnaya96a3fa2016-09-24 07:17:42 -0700385 // TODO: Mac
386 // TODO: Struct
387 // TODO: Repeat
David Tolnayfa0edf22016-09-23 22:58:24 -0700388 ) >>
389 many0!(alt!(
David Tolnay939766a2016-09-23 23:48:12 -0700390 tap!(args: and_call => {
391 e = Expr::Call(Box::new(e), args);
David Tolnayfa0edf22016-09-23 22:58:24 -0700392 })
393 |
David Tolnay939766a2016-09-23 23:48:12 -0700394 tap!(more: and_method_call => {
395 let (method, ascript, mut args) = more;
David Tolnayfa0edf22016-09-23 22:58:24 -0700396 args.insert(0, e);
397 e = Expr::MethodCall(method, ascript, args);
398 })
399 |
David Tolnay939766a2016-09-23 23:48:12 -0700400 tap!(more: and_binary => {
401 let (op, other) = more;
David Tolnayfa0edf22016-09-23 22:58:24 -0700402 e = Expr::Binary(op, Box::new(e), Box::new(other));
403 })
David Tolnay939766a2016-09-23 23:48:12 -0700404 |
405 tap!(ty: and_cast => {
406 e = Expr::Cast(Box::new(e), Box::new(ty));
407 })
408 |
409 tap!(ty: and_ascription => {
410 e = Expr::Type(Box::new(e), Box::new(ty));
411 })
David Tolnaya96a3fa2016-09-24 07:17:42 -0700412 // TODO: Assign
413 // TODO: AssignOp
414 // TODO: Field
415 // TODO: TupField
416 // TODO: Index
417 // TODO: Range
418 // TODO: Try
David Tolnayfa0edf22016-09-23 22:58:24 -0700419 )) >>
420 (e)
David Tolnayb9c8e322016-09-23 20:48:37 -0700421 ));
422
David Tolnay89e05672016-10-02 14:39:42 -0700423 named!(expr_paren -> Expr, do_parse!(
424 punct!("(") >>
425 e: expr >>
426 punct!(")") >>
427 (Expr::Paren(Box::new(e)))
428 ));
429
David Tolnay939766a2016-09-23 23:48:12 -0700430 named!(expr_box -> Expr, do_parse!(
David Tolnay10413f02016-09-30 09:12:02 -0700431 keyword!("box") >>
David Tolnayb9c8e322016-09-23 20:48:37 -0700432 inner: expr >>
433 (Expr::Box(Box::new(inner)))
434 ));
David Tolnayfa0edf22016-09-23 22:58:24 -0700435
David Tolnay939766a2016-09-23 23:48:12 -0700436 named!(expr_vec -> Expr, do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700437 punct!("[") >>
438 elems: separated_list!(punct!(","), expr) >>
439 punct!("]") >>
440 (Expr::Vec(elems))
441 ));
442
David Tolnay939766a2016-09-23 23:48:12 -0700443 named!(and_call -> Vec<Expr>, do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700444 punct!("(") >>
445 args: separated_list!(punct!(","), expr) >>
446 punct!(")") >>
447 (args)
448 ));
449
David Tolnay939766a2016-09-23 23:48:12 -0700450 named!(and_method_call -> (Ident, Vec<Ty>, Vec<Expr>), do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700451 punct!(".") >>
452 method: ident >>
453 ascript: opt_vec!(delimited!(
454 punct!("<"),
455 separated_list!(punct!(","), ty),
456 punct!(">")
457 )) >>
458 punct!("(") >>
459 args: separated_list!(punct!(","), expr) >>
460 punct!(")") >>
461 (method, ascript, args)
462 ));
463
David Tolnay939766a2016-09-23 23:48:12 -0700464 named!(expr_tup -> Expr, do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700465 punct!("(") >>
466 elems: separated_list!(punct!(","), expr) >>
David Tolnay89e05672016-10-02 14:39:42 -0700467 option!(punct!(",")) >>
David Tolnayfa0edf22016-09-23 22:58:24 -0700468 punct!(")") >>
469 (Expr::Tup(elems))
470 ));
471
David Tolnay939766a2016-09-23 23:48:12 -0700472 named!(and_binary -> (BinOp, Expr), tuple!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700473 alt!(
474 punct!("&&") => { |_| BinOp::And }
475 |
476 punct!("||") => { |_| BinOp::Or }
477 |
478 punct!("<<") => { |_| BinOp::Shl }
479 |
480 punct!(">>") => { |_| BinOp::Shr }
481 |
482 punct!("==") => { |_| BinOp::Eq }
483 |
484 punct!("<=") => { |_| BinOp::Le }
485 |
486 punct!("!=") => { |_| BinOp::Ne }
487 |
488 punct!(">=") => { |_| BinOp::Ge }
489 |
490 punct!("+") => { |_| BinOp::Add }
491 |
492 punct!("-") => { |_| BinOp::Sub }
493 |
494 punct!("*") => { |_| BinOp::Mul }
495 |
496 punct!("/") => { |_| BinOp::Div }
497 |
498 punct!("%") => { |_| BinOp::Rem }
499 |
500 punct!("^") => { |_| BinOp::BitXor }
501 |
502 punct!("&") => { |_| BinOp::BitAnd }
503 |
504 punct!("|") => { |_| BinOp::BitOr }
505 |
506 punct!("<") => { |_| BinOp::Lt }
507 |
508 punct!(">") => { |_| BinOp::Gt }
509 ),
510 expr
511 ));
512
David Tolnay939766a2016-09-23 23:48:12 -0700513 named!(expr_unary -> Expr, do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700514 operator: alt!(
515 punct!("*") => { |_| UnOp::Deref }
516 |
517 punct!("!") => { |_| UnOp::Not }
518 |
519 punct!("-") => { |_| UnOp::Neg }
520 ) >>
521 operand: expr >>
522 (Expr::Unary(operator, Box::new(operand)))
523 ));
David Tolnay939766a2016-09-23 23:48:12 -0700524
525 named!(expr_lit -> Expr, map!(lit, Expr::Lit));
526
527 named!(and_cast -> Ty, do_parse!(
David Tolnay10413f02016-09-30 09:12:02 -0700528 keyword!("as") >>
David Tolnay939766a2016-09-23 23:48:12 -0700529 ty: ty >>
530 (ty)
531 ));
532
533 named!(and_ascription -> Ty, preceded!(punct!(":"), ty));
534
535 named!(expr_if -> Expr, do_parse!(
David Tolnay10413f02016-09-30 09:12:02 -0700536 keyword!("if") >>
David Tolnay939766a2016-09-23 23:48:12 -0700537 cond: expr >>
538 punct!("{") >>
539 then_block: within_block >>
540 punct!("}") >>
541 else_block: option!(preceded!(
David Tolnay10413f02016-09-30 09:12:02 -0700542 keyword!("else"),
David Tolnay939766a2016-09-23 23:48:12 -0700543 alt!(
544 expr_if
545 |
546 do_parse!(
547 punct!("{") >>
548 else_block: within_block >>
549 punct!("}") >>
David Tolnay89e05672016-10-02 14:39:42 -0700550 (Expr::Block(BlockCheckMode::Default, Block {
David Tolnay939766a2016-09-23 23:48:12 -0700551 stmts: else_block,
David Tolnay89e05672016-10-02 14:39:42 -0700552 }))
David Tolnay939766a2016-09-23 23:48:12 -0700553 )
554 )
555 )) >>
556 (Expr::If(
557 Box::new(cond),
David Tolnay89e05672016-10-02 14:39:42 -0700558 Block {
David Tolnay939766a2016-09-23 23:48:12 -0700559 stmts: then_block,
David Tolnay89e05672016-10-02 14:39:42 -0700560 },
David Tolnay939766a2016-09-23 23:48:12 -0700561 else_block.map(Box::new),
562 ))
563 ));
564
Gregory Katze5f35682016-09-27 14:20:55 -0400565 named!(expr_loop -> Expr, do_parse!(
David Tolnay8b07f372016-09-30 10:28:40 -0700566 lbl: option!(terminated!(label, punct!(":"))) >>
David Tolnay10413f02016-09-30 09:12:02 -0700567 keyword!("loop") >>
Gregory Katze5f35682016-09-27 14:20:55 -0400568 loop_block: block >>
David Tolnay89e05672016-10-02 14:39:42 -0700569 (Expr::Loop(loop_block, lbl))
Gregory Katze5f35682016-09-27 14:20:55 -0400570 ));
571
David Tolnayb4ad3b52016-10-01 21:58:13 -0700572 named!(expr_match -> Expr, do_parse!(
573 keyword!("match") >>
574 obj: expr >>
575 punct!("{") >>
576 arms: many0!(do_parse!(
577 attrs: many0!(outer_attr) >>
578 pats: separated_nonempty_list!(punct!("|"), pat) >>
579 guard: option!(preceded!(keyword!("if"), expr)) >>
580 punct!("=>") >>
581 body: alt!(
582 terminated!(expr, punct!(","))
583 |
David Tolnay89e05672016-10-02 14:39:42 -0700584 map!(block, |blk| Expr::Block(BlockCheckMode::Default, blk))
David Tolnayb4ad3b52016-10-01 21:58:13 -0700585 ) >>
586 (Arm {
587 attrs: attrs,
588 pats: pats,
589 guard: guard.map(Box::new),
590 body: Box::new(body),
591 })
592 )) >>
593 punct!("}") >>
594 (Expr::Match(Box::new(obj), arms))
595 ));
596
David Tolnay89e05672016-10-02 14:39:42 -0700597 named!(expr_closure -> Expr, do_parse!(
598 capture: capture_by >>
599 punct!("|") >>
600 inputs: separated_list!(punct!(","), closure_arg) >>
601 punct!("|") >>
602 ret_and_body: alt!(
603 do_parse!(
604 punct!("->") >>
605 ty: ty >>
606 body: block >>
607 ((FunctionRetTy::Ty(ty), body))
608 )
609 |
610 map!(expr, |e| (
611 FunctionRetTy::Default,
612 Block {
613 stmts: vec![Stmt::Expr(Box::new(e))],
614 },
615 ))
616 ) >>
617 (Expr::Closure(
618 capture,
619 Box::new(FnDecl {
620 inputs: inputs,
621 output: ret_and_body.0,
622 }),
623 ret_and_body.1,
624 ))
625 ));
626
627 named!(closure_arg -> FnArg, do_parse!(
628 pat: pat >>
629 ty: option!(preceded!(punct!(":"), ty)) >>
630 (FnArg {
631 pat: pat,
632 ty: ty.unwrap_or(Ty::Infer),
633 })
634 ));
635
Gregory Katz3e562cc2016-09-28 18:33:02 -0400636 named!(expr_while -> Expr, do_parse!(
David Tolnay8b07f372016-09-30 10:28:40 -0700637 lbl: option!(terminated!(label, punct!(":"))) >>
David Tolnay57ffbde2016-09-30 09:38:04 -0700638 keyword!("while") >>
Gregory Katz3e562cc2016-09-28 18:33:02 -0400639 cond: expr >>
640 while_block: block >>
641 (Expr::While(
642 Box::new(cond),
David Tolnay89e05672016-10-02 14:39:42 -0700643 while_block,
David Tolnay8b07f372016-09-30 10:28:40 -0700644 lbl,
Gregory Katz3e562cc2016-09-28 18:33:02 -0400645 ))
646 ));
647
Gregory Katzfd6935d2016-09-30 22:51:25 -0400648 named!(expr_continue -> Expr, do_parse!(
649 keyword!("continue") >>
650 lbl: option!(label) >>
651 (Expr::Continue(
652 lbl,
653 ))
654 ));
655
656 named!(expr_break -> Expr, do_parse!(
657 keyword!("break") >>
658 lbl: option!(label) >>
659 (Expr::Break(
660 lbl,
661 ))
662 ));
663
664 named!(expr_ret -> Expr, do_parse!(
665 keyword!("return") >>
666 ret_value: option!(expr) >>
667 (Expr::Ret(
668 ret_value.map(Box::new),
669 ))
670 ));
671
David Tolnay42602292016-10-01 22:25:45 -0700672 named!(expr_block -> Expr, do_parse!(
David Tolnay939766a2016-09-23 23:48:12 -0700673 rules: block_check_mode >>
David Tolnay42602292016-10-01 22:25:45 -0700674 b: block >>
David Tolnay89e05672016-10-02 14:39:42 -0700675 (Expr::Block(rules, Block {
David Tolnay42602292016-10-01 22:25:45 -0700676 stmts: b.stmts,
David Tolnay89e05672016-10-02 14:39:42 -0700677 }))
678 ));
679
680 named!(expr_path -> Expr, map!(path, |p| Expr::Path(None, p)));
681
682 named!(expr_qpath -> Expr, do_parse!(
683 punct!("<") >>
684 this: map!(ty, Box::new) >>
685 path: option!(preceded!(
686 keyword!("as"),
687 path
688 )) >>
689 punct!(">") >>
690 punct!("::") >>
691 rest: separated_nonempty_list!(punct!("::"), path_segment) >>
692 ({
693 match path {
694 Some(mut path) => {
695 let pos = path.segments.len();
696 path.segments.extend(rest);
697 Expr::Path(Some(QSelf { ty: this, position: pos }), path)
698 }
699 None => {
700 Expr::Path(Some(QSelf { ty: this, position: 0 }), Path {
701 global: false,
702 segments: rest,
703 })
704 }
705 }
706 })
David Tolnay42602292016-10-01 22:25:45 -0700707 ));
708
709 named!(pub block -> Block, do_parse!(
David Tolnay939766a2016-09-23 23:48:12 -0700710 punct!("{") >>
711 stmts: within_block >>
712 punct!("}") >>
713 (Block {
714 stmts: stmts,
David Tolnay939766a2016-09-23 23:48:12 -0700715 })
716 ));
717
718 named!(block_check_mode -> BlockCheckMode, alt!(
David Tolnay10413f02016-09-30 09:12:02 -0700719 keyword!("unsafe") => { |_| BlockCheckMode::Unsafe }
David Tolnay939766a2016-09-23 23:48:12 -0700720 |
721 epsilon!() => { |_| BlockCheckMode::Default }
722 ));
723
724 named!(within_block -> Vec<Stmt>, do_parse!(
David Tolnay181bac52016-09-24 00:10:05 -0700725 mut most: many0!(standalone_stmt) >>
David Tolnay939766a2016-09-23 23:48:12 -0700726 last: option!(expr) >>
727 (match last {
728 None => most,
729 Some(last) => {
David Tolnay939766a2016-09-23 23:48:12 -0700730 most.push(Stmt::Expr(Box::new(last)));
731 most
732 }
733 })
734 ));
735
736 named!(standalone_stmt -> Stmt, alt!(
David Tolnaya96a3fa2016-09-24 07:17:42 -0700737 // TODO: local
738 // TODO: item
739 // TODO: expr
David Tolnay939766a2016-09-23 23:48:12 -0700740 stmt_semi
David Tolnaya96a3fa2016-09-24 07:17:42 -0700741 // TODO: mac
David Tolnay939766a2016-09-23 23:48:12 -0700742 ));
743
744 named!(stmt_semi -> Stmt, do_parse!(
745 e: expr >>
746 punct!(";") >>
747 (Stmt::Semi(Box::new(e)))
748 ));
David Tolnay8b07f372016-09-30 10:28:40 -0700749
David Tolnay42602292016-10-01 22:25:45 -0700750 named!(pub pat -> Pat, alt!(
David Tolnayb4ad3b52016-10-01 21:58:13 -0700751 pat_wild
752 |
753 pat_ident
754 // TODO: Struct
755 // TODO: TupleStruct
756 // TODO: Path
757 // TODO: Tuple
758 // TODO: Box
759 // TODO: Ref
760 // TODO: Lit
761 // TODO: Range
762 // TODO: Vec
763 // TODO: Mac
764 ));
765
766 named!(pat_wild -> Pat, map!(keyword!("_"), |_| Pat::Wild));
767
768 named!(pat_ident -> Pat, do_parse!(
769 mode: option!(keyword!("ref")) >>
770 mutability: mutability >>
771 name: ident >>
772 subpat: option!(preceded!(punct!("@"), pat)) >>
773 (Pat::Ident(
774 if mode.is_some() {
775 BindingMode::ByRef(mutability)
776 } else {
777 BindingMode::ByValue(mutability)
778 },
779 name,
780 subpat.map(Box::new),
781 ))
782 ));
783
David Tolnay89e05672016-10-02 14:39:42 -0700784 named!(capture_by -> CaptureBy, alt!(
785 keyword!("move") => { |_| CaptureBy::Value }
786 |
787 epsilon!() => { |_| CaptureBy::Ref }
788 ));
789
David Tolnay8b07f372016-09-30 10:28:40 -0700790 named!(label -> Ident, map!(lifetime, |lt: Lifetime| lt.ident));
David Tolnayb9c8e322016-09-23 20:48:37 -0700791}
792
David Tolnayf4bbbd92016-09-23 14:41:55 -0700793#[cfg(feature = "printing")]
794mod printing {
795 use super::*;
David Tolnay89e05672016-10-02 14:39:42 -0700796 use {FunctionRetTy, Mutability, Ty};
David Tolnayf4bbbd92016-09-23 14:41:55 -0700797 use quote::{Tokens, ToTokens};
798
799 impl ToTokens for Expr {
800 fn to_tokens(&self, tokens: &mut Tokens) {
801 match *self {
David Tolnay47a877c2016-10-01 16:50:55 -0700802 Expr::Box(ref _inner) => unimplemented!(),
803 Expr::Vec(ref _inner) => unimplemented!(),
804 Expr::Call(ref _func, ref _args) => unimplemented!(),
805 Expr::MethodCall(ref _ident, ref _ascript, ref _args) => unimplemented!(),
806 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 Tolnay47a877c2016-10-01 16:50:55 -0700819 Expr::Unary(_op, ref _expr) => unimplemented!(),
David Tolnayf4bbbd92016-09-23 14:41:55 -0700820 Expr::Lit(ref lit) => lit.to_tokens(tokens),
David Tolnay47a877c2016-10-01 16:50:55 -0700821 Expr::Cast(ref _expr, ref _ty) => unimplemented!(),
822 Expr::Type(ref _expr, ref _ty) => unimplemented!(),
823 Expr::If(ref _cond, ref _then_block, ref _else_block) => unimplemented!(),
824 Expr::IfLet(ref _pat, ref _expr, ref _then_block, ref _else_block) => unimplemented!(),
825 Expr::While(ref _cond, ref _body, ref _label) => unimplemented!(),
826 Expr::WhileLet(ref _pat, ref _expr, ref _body, ref _label) => unimplemented!(),
827 Expr::ForLoop(ref _pat, ref _expr, ref _body, ref _label) => unimplemented!(),
828 Expr::Loop(ref _body, ref _label) => unimplemented!(),
David Tolnayb4ad3b52016-10-01 21:58:13 -0700829 Expr::Match(ref expr, ref arms) => {
830 tokens.append("match");
831 expr.to_tokens(tokens);
832 tokens.append("{");
833 tokens.append_separated(arms, ",");
834 tokens.append("}");
835 }
David Tolnay89e05672016-10-02 14:39:42 -0700836 Expr::Closure(capture, ref decl, ref body) => {
837 capture.to_tokens(tokens);
838 tokens.append("|");
839 for (i, input) in decl.inputs.iter().enumerate() {
840 if i > 0 {
841 tokens.append(",");
842 }
843 input.pat.to_tokens(tokens);
844 match input.ty {
845 Ty::Infer => { /* nothing */ }
846 _ => {
847 tokens.append(":");
848 input.ty.to_tokens(tokens);
849 }
850 }
851 }
852 tokens.append("|");
853 match decl.output {
854 FunctionRetTy::Default => {
855 if body.stmts.len() == 1 {
856 if let Stmt::Expr(ref expr) = body.stmts[0] {
857 expr.to_tokens(tokens);
858 } else {
859 body.to_tokens(tokens);
860 }
861 } else {
862 body.to_tokens(tokens);
863 }
864 }
865 FunctionRetTy::Ty(ref ty) => {
866 tokens.append("->");
867 ty.to_tokens(tokens);
868 body.to_tokens(tokens);
869 }
870 }
871 }
872 Expr::Block(rules, ref block) => {
873 rules.to_tokens(tokens);
874 block.to_tokens(tokens);
875 }
David Tolnay47a877c2016-10-01 16:50:55 -0700876 Expr::Assign(ref _var, ref _expr) => unimplemented!(),
877 Expr::AssignOp(_op, ref _var, ref _expr) => unimplemented!(),
878 Expr::Field(ref _expr, ref _field) => unimplemented!(),
879 Expr::TupField(ref _expr, _field) => unimplemented!(),
880 Expr::Index(ref _expr, ref _index) => unimplemented!(),
881 Expr::Range(ref _from, ref _to, _limits) => unimplemented!(),
David Tolnay89e05672016-10-02 14:39:42 -0700882 Expr::Path(None, ref path) => {
883 path.to_tokens(tokens);
884 }
885 Expr::Path(Some(ref qself), ref path) => {
886 tokens.append("<");
887 qself.ty.to_tokens(tokens);
888 if qself.position > 0 {
889 tokens.append("as");
890 for (i, segment) in path.segments.iter()
891 .take(qself.position)
892 .enumerate()
893 {
894 if i > 0 || path.global {
895 tokens.append("::");
896 }
897 segment.to_tokens(tokens);
898 }
899 }
900 tokens.append(">");
901 for segment in path.segments.iter().skip(qself.position) {
902 tokens.append("::");
903 segment.to_tokens(tokens);
904 }
905 }
David Tolnay47a877c2016-10-01 16:50:55 -0700906 Expr::AddrOf(_mutability, ref _expr) => unimplemented!(),
907 Expr::Break(ref _label) => unimplemented!(),
908 Expr::Continue(ref _label) => unimplemented!(),
David Tolnay42602292016-10-01 22:25:45 -0700909 Expr::Ret(ref opt_expr) => {
910 tokens.append("return");
911 opt_expr.to_tokens(tokens);
912 }
David Tolnay47a877c2016-10-01 16:50:55 -0700913 Expr::Mac(ref _mac) => unimplemented!(),
914 Expr::Struct(ref _path, ref _fields, ref _base) => unimplemented!(),
915 Expr::Repeat(ref _expr, ref _times) => unimplemented!(),
David Tolnay89e05672016-10-02 14:39:42 -0700916 Expr::Paren(ref expr) => {
917 tokens.append("(");
918 expr.to_tokens(tokens);
919 tokens.append(")");
920 }
David Tolnay47a877c2016-10-01 16:50:55 -0700921 Expr::Try(ref _expr) => unimplemented!(),
David Tolnayf4bbbd92016-09-23 14:41:55 -0700922 }
923 }
924 }
David Tolnayb4ad3b52016-10-01 21:58:13 -0700925
David Tolnay89e05672016-10-02 14:39:42 -0700926 impl ToTokens for BinOp {
927 fn to_tokens(&self, tokens: &mut Tokens) {
928 match *self {
929 BinOp::Add => tokens.append("+"),
930 BinOp::Sub => tokens.append("-"),
931 BinOp::Mul => tokens.append("*"),
932 BinOp::Div => tokens.append("/"),
933 BinOp::Rem => tokens.append("%"),
934 BinOp::And => tokens.append("&&"),
935 BinOp::Or => tokens.append("||"),
936 BinOp::BitXor => tokens.append("^"),
937 BinOp::BitAnd => tokens.append("&"),
938 BinOp::BitOr => tokens.append("|"),
939 BinOp::Shl => tokens.append("<<"),
940 BinOp::Shr => tokens.append(">>"),
941 BinOp::Eq => tokens.append("=="),
942 BinOp::Lt => tokens.append("<"),
943 BinOp::Le => tokens.append("<="),
944 BinOp::Ne => tokens.append("!="),
945 BinOp::Ge => tokens.append(">="),
946 BinOp::Gt => tokens.append(">"),
947 }
948 }
949 }
950
David Tolnayb4ad3b52016-10-01 21:58:13 -0700951 impl ToTokens for Arm {
952 fn to_tokens(&self, tokens: &mut Tokens) {
953 for attr in &self.attrs {
954 attr.to_tokens(tokens);
955 }
956 tokens.append_separated(&self.pats, "|");
957 if let Some(ref guard) = self.guard {
958 tokens.append("if");
959 guard.to_tokens(tokens);
960 }
961 tokens.append("=>");
962 self.body.to_tokens(tokens);
963 match *self.body {
David Tolnay89e05672016-10-02 14:39:42 -0700964 Expr::Block(_, _) => { /* no comma */ }
David Tolnayb4ad3b52016-10-01 21:58:13 -0700965 _ => tokens.append(","),
966 }
967 }
968 }
969
970 impl ToTokens for Pat {
971 fn to_tokens(&self, tokens: &mut Tokens) {
972 match *self {
973 Pat::Wild => tokens.append("_"),
974 Pat::Ident(mode, ref ident, ref subpat) => {
975 mode.to_tokens(tokens);
976 ident.to_tokens(tokens);
977 if let Some(ref subpat) = *subpat {
978 tokens.append("@");
979 subpat.to_tokens(tokens);
980 }
981 }
982 Pat::Struct(ref _path, ref _fields, _dots) => unimplemented!(),
983 Pat::TupleStruct(ref _path, ref _pats, _dotpos) => unimplemented!(),
984 Pat::Path(ref _qself, ref _path) => unimplemented!(),
985 Pat::Tuple(ref _pats, _dotpos) => unimplemented!(),
986 Pat::Box(ref _inner) => unimplemented!(),
987 Pat::Ref(ref _target, _mutability) => unimplemented!(),
988 Pat::Lit(ref _expr) => unimplemented!(),
989 Pat::Range(ref _lower, ref _upper) => unimplemented!(),
990 Pat::Vec(ref _before, ref _dots, ref _after) => unimplemented!(),
991 Pat::Mac(ref _mac) => unimplemented!(),
992 }
993 }
994 }
995
996 impl ToTokens for BindingMode {
997 fn to_tokens(&self, tokens: &mut Tokens) {
998 match *self {
999 BindingMode::ByRef(Mutability::Immutable) => {
1000 tokens.append("ref");
1001 }
1002 BindingMode::ByRef(Mutability::Mutable) => {
1003 tokens.append("ref");
1004 tokens.append("mut");
1005 }
1006 BindingMode::ByValue(Mutability::Immutable) => {}
1007 BindingMode::ByValue(Mutability::Mutable) => {
1008 tokens.append("mut");
1009 }
1010 }
1011 }
1012 }
David Tolnay42602292016-10-01 22:25:45 -07001013
David Tolnay89e05672016-10-02 14:39:42 -07001014 impl ToTokens for CaptureBy {
1015 fn to_tokens(&self, tokens: &mut Tokens) {
1016 match *self {
1017 CaptureBy::Value => tokens.append("move"),
1018 CaptureBy::Ref => { /* nothing */ }
1019 }
1020 }
1021 }
1022
David Tolnay42602292016-10-01 22:25:45 -07001023 impl ToTokens for Block {
1024 fn to_tokens(&self, tokens: &mut Tokens) {
David Tolnay42602292016-10-01 22:25:45 -07001025 tokens.append("{");
1026 for stmt in &self.stmts {
1027 stmt.to_tokens(tokens);
1028 }
1029 tokens.append("}");
1030 }
1031 }
1032
1033 impl ToTokens for BlockCheckMode {
1034 fn to_tokens(&self, tokens: &mut Tokens) {
1035 match *self {
David Tolnay89e05672016-10-02 14:39:42 -07001036 BlockCheckMode::Default => { /* nothing */ }
David Tolnay42602292016-10-01 22:25:45 -07001037 BlockCheckMode::Unsafe => tokens.append("unsafe"),
1038 }
1039 }
1040 }
1041
1042 impl ToTokens for Stmt {
1043 fn to_tokens(&self, tokens: &mut Tokens) {
1044 match *self {
1045 Stmt::Local(ref _local) => unimplemented!(),
1046 Stmt::Item(ref item) => item.to_tokens(tokens),
1047 Stmt::Expr(ref expr) => expr.to_tokens(tokens),
1048 Stmt::Semi(ref expr) => {
1049 expr.to_tokens(tokens);
1050 tokens.append(";");
1051 }
1052 Stmt::Mac(ref _mac) => unimplemented!(),
1053 }
1054 }
1055 }
David Tolnayf4bbbd92016-09-23 14:41:55 -07001056}