blob: 126b4d44f174e3fdbe371df3e51faa69fb8d0e14 [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>`.
David Tolnay055a7042016-10-02 19:23:54 -0700116 Struct(Path, Vec<FieldValue>, Option<Box<Expr>>),
David Tolnayf4bbbd92016-09-23 14:41:55 -0700117
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
David Tolnay055a7042016-10-02 19:23:54 -0700131#[derive(Debug, Clone, Eq, PartialEq)]
132pub struct FieldValue {
133 pub ident: Ident,
134 pub expr: Expr,
135}
136
David Tolnayf4bbbd92016-09-23 14:41:55 -0700137/// A Block (`{ .. }`).
138///
139/// E.g. `{ .. }` as in `fn foo() { .. }`
140#[derive(Debug, Clone, Eq, PartialEq)]
141pub struct Block {
142 /// Statements in a block
143 pub stmts: Vec<Stmt>,
David Tolnayf4bbbd92016-09-23 14:41:55 -0700144}
145
146#[derive(Debug, Copy, Clone, Eq, PartialEq)]
147pub enum BlockCheckMode {
148 Default,
149 Unsafe,
150}
151
152#[derive(Debug, Clone, Eq, PartialEq)]
153pub enum Stmt {
154 /// A local (let) binding.
155 Local(Box<Local>),
156
157 /// An item definition.
158 Item(Box<Item>),
159
160 /// Expr without trailing semi-colon.
161 Expr(Box<Expr>),
162
163 Semi(Box<Expr>),
164
165 Mac(Box<(Mac, MacStmtStyle, Vec<Attribute>)>),
166}
167
168#[derive(Debug, Copy, Clone, Eq, PartialEq)]
169pub enum MacStmtStyle {
170 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
171 /// `foo!(...);`, `foo![...];`
172 Semicolon,
173 /// The macro statement had braces; e.g. foo! { ... }
174 Braces,
175 /// The macro statement had parentheses or brackets and no semicolon; e.g.
176 /// `foo!(...)`. All of these will end up being converted into macro
177 /// expressions.
178 NoBraces,
179}
180
181/// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
182#[derive(Debug, Clone, Eq, PartialEq)]
183pub struct Local {
184 pub pat: Box<Pat>,
185 pub ty: Option<Box<Ty>>,
186 /// Initializer expression to set the value, if any
187 pub init: Option<Box<Expr>>,
188 pub attrs: Vec<Attribute>,
189}
190
David Tolnayf4bbbd92016-09-23 14:41:55 -0700191#[derive(Debug, Clone, Eq, PartialEq)]
David Tolnay58f6f672016-10-19 08:44:25 -0700192// Clippy false positive
193// https://github.com/Manishearth/rust-clippy/issues/1241
194#[cfg_attr(feature = "clippy", allow(enum_variant_names))]
David Tolnayf4bbbd92016-09-23 14:41:55 -0700195pub enum Pat {
196 /// Represents a wildcard pattern (`_`)
197 Wild,
198
David Tolnay432afc02016-09-24 07:37:13 -0700199 /// A `Pat::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
David Tolnayf4bbbd92016-09-23 14:41:55 -0700200 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
201 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
202 /// during name resolution.
203 Ident(BindingMode, Ident, Option<Box<Pat>>),
204
205 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
206 /// The `bool` is `true` in the presence of a `..`.
207 Struct(Path, Vec<FieldPat>, bool),
208
209 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
210 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
211 /// 0 <= position <= subpats.len()
212 TupleStruct(Path, Vec<Pat>, Option<usize>),
213
214 /// A possibly qualified path pattern.
215 /// Unquailfied path patterns `A::B::C` can legally refer to variants, structs, constants
216 /// or associated constants. Quailfied path patterns `<A>::B::C`/`<A as Trait>::B::C` can
217 /// only legally refer to associated constants.
218 Path(Option<QSelf>, Path),
219
220 /// A tuple pattern `(a, b)`.
221 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
222 /// 0 <= position <= subpats.len()
223 Tuple(Vec<Pat>, Option<usize>),
224 /// A `box` pattern
225 Box(Box<Pat>),
226 /// A reference pattern, e.g. `&mut (a, b)`
227 Ref(Box<Pat>, Mutability),
228 /// A literal
David Tolnay8b308c22016-10-03 01:24:10 -0700229 Lit(Box<Lit>),
David Tolnayf4bbbd92016-09-23 14:41:55 -0700230 /// A range pattern, e.g. `1...2`
David Tolnay8b308c22016-10-03 01:24:10 -0700231 Range(Box<Lit>, Box<Lit>),
David Tolnayf4bbbd92016-09-23 14:41:55 -0700232 /// `[a, b, ..i, y, z]` is represented as:
David Tolnay16709ba2016-10-05 23:11:32 -0700233 /// `Pat::Slice(box [a, b], Some(i), box [y, z])`
234 Slice(Vec<Pat>, Option<Box<Pat>>, Vec<Pat>),
David Tolnayf4bbbd92016-09-23 14:41:55 -0700235 /// A macro pattern; pre-expansion
236 Mac(Mac),
237}
238
David Tolnay771ecf42016-09-23 19:26:37 -0700239/// An arm of a 'match'.
240///
241/// E.g. `0...10 => { println!("match!") }` as in
242///
243/// ```rust,ignore
244/// match n {
245/// 0...10 => { println!("match!") },
246/// // ..
247/// }
248/// ```
David Tolnayf4bbbd92016-09-23 14:41:55 -0700249#[derive(Debug, Clone, Eq, PartialEq)]
250pub struct Arm {
251 pub attrs: Vec<Attribute>,
252 pub pats: Vec<Pat>,
253 pub guard: Option<Box<Expr>>,
254 pub body: Box<Expr>,
255}
256
257/// A capture clause
258#[derive(Debug, Copy, Clone, Eq, PartialEq)]
259pub enum CaptureBy {
260 Value,
261 Ref,
262}
263
264/// Limit types of a range (inclusive or exclusive)
265#[derive(Debug, Copy, Clone, Eq, PartialEq)]
266pub enum RangeLimits {
267 /// Inclusive at the beginning, exclusive at the end
268 HalfOpen,
269 /// Inclusive at the beginning and end
270 Closed,
271}
272
273/// A single field in a struct pattern
274///
275/// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
David Tolnay181bac52016-09-24 00:10:05 -0700276/// are treated the same as `x: x, y: ref y, z: ref mut z`,
David Tolnayaed77b02016-09-23 20:50:31 -0700277/// except `is_shorthand` is true
David Tolnayf4bbbd92016-09-23 14:41:55 -0700278#[derive(Debug, Clone, Eq, PartialEq)]
279pub struct FieldPat {
280 /// The identifier for the field
281 pub ident: Ident,
282 /// The pattern the field is destructured to
283 pub pat: Box<Pat>,
284 pub is_shorthand: bool,
285}
286
287#[derive(Debug, Copy, Clone, Eq, PartialEq)]
288pub enum BindingMode {
289 ByRef(Mutability),
290 ByValue(Mutability),
291}
292
David Tolnayb9c8e322016-09-23 20:48:37 -0700293#[cfg(feature = "parsing")]
294pub mod parsing {
295 use super::*;
David Tolnayeea28d62016-10-25 20:44:08 -0700296 use {BinOp, Delimited, DelimToken, FnArg, FnDecl, FunctionRetTy, Ident, Lifetime, Mac,
297 TokenTree, Ty};
David Tolnayb4ad3b52016-10-01 21:58:13 -0700298 use attr::parsing::outer_attr;
Gregory Katz1b69f682016-09-27 21:06:09 -0400299 use generics::parsing::lifetime;
David Tolnayfa0edf22016-09-23 22:58:24 -0700300 use ident::parsing::ident;
David Tolnay191e0582016-10-02 18:31:09 -0700301 use item::parsing::item;
David Tolnay438c9052016-10-07 23:24:48 -0700302 use lit::parsing::{digits, lit};
David Tolnayeea28d62016-10-25 20:44:08 -0700303 use mac::parsing::{mac, token_trees};
David Tolnay54e854d2016-10-24 12:03:30 -0700304 use nom::IResult::{self, Error};
David Tolnay438c9052016-10-07 23:24:48 -0700305 use op::parsing::{assign_op, binop, unop};
David Tolnay055a7042016-10-02 19:23:54 -0700306 use ty::parsing::{mutability, path, qpath, ty};
David Tolnayb9c8e322016-09-23 20:48:37 -0700307
David Tolnayaf2557e2016-10-24 11:52:21 -0700308 // Struct literals are ambiguous in certain positions
309 // https://github.com/rust-lang/rfcs/pull/92
310 macro_rules! named_ambiguous_expr {
311 ($name:ident -> $o:ty, $allow_struct:ident, $submac:ident!( $($args:tt)* )) => {
312 fn $name(i: &str, $allow_struct: bool) -> $crate::nom::IResult<&str, $o> {
313 $submac!(i, $($args)*)
314 }
315 };
316 }
317
318 macro_rules! ambiguous_expr {
319 ($i:expr, $allow_struct:ident) => {
David Tolnay54e854d2016-10-24 12:03:30 -0700320 ambiguous_expr($i, $allow_struct, true)
David Tolnayaf2557e2016-10-24 11:52:21 -0700321 };
322 }
323
324 named!(pub expr -> Expr, ambiguous_expr!(true));
325
326 named!(expr_no_struct -> Expr, ambiguous_expr!(false));
327
David Tolnay54e854d2016-10-24 12:03:30 -0700328 fn ambiguous_expr(i: &str, allow_struct: bool, allow_block: bool) -> IResult<&str, Expr> {
329 do_parse!(
330 i,
331 mut e: alt!(
332 expr_lit // must be before expr_struct
333 |
334 cond_reduce!(allow_struct, expr_struct) // must be before expr_path
335 |
336 expr_paren // must be before expr_tup
337 |
338 expr_mac // must be before expr_path
339 |
340 expr_break // must be before expr_path
341 |
342 expr_continue // must be before expr_path
343 |
344 call!(expr_ret, allow_struct) // must be before expr_path
345 |
346 call!(expr_box, allow_struct)
347 |
348 expr_vec
349 |
350 expr_tup
351 |
352 call!(expr_unary, allow_struct)
353 |
354 expr_if
355 |
356 expr_while
357 |
358 expr_for_loop
359 |
360 expr_loop
361 |
362 expr_match
363 |
364 call!(expr_closure, allow_struct)
365 |
366 cond_reduce!(allow_block, expr_block)
367 |
368 call!(expr_range, allow_struct)
369 |
370 expr_path
371 |
372 call!(expr_addr_of, allow_struct)
373 |
374 expr_repeat
375 ) >>
376 many0!(alt!(
377 tap!(args: and_call => {
378 e = Expr::Call(Box::new(e), args);
379 })
380 |
381 tap!(more: and_method_call => {
382 let (method, ascript, mut args) = more;
383 args.insert(0, e);
384 e = Expr::MethodCall(method, ascript, args);
385 })
386 |
387 tap!(more: call!(and_binary, allow_struct) => {
388 let (op, other) = more;
389 e = Expr::Binary(op, Box::new(e), Box::new(other));
390 })
391 |
392 tap!(ty: and_cast => {
393 e = Expr::Cast(Box::new(e), Box::new(ty));
394 })
395 |
396 tap!(ty: and_ascription => {
397 e = Expr::Type(Box::new(e), Box::new(ty));
398 })
399 |
400 tap!(v: call!(and_assign, allow_struct) => {
401 e = Expr::Assign(Box::new(e), Box::new(v));
402 })
403 |
404 tap!(more: call!(and_assign_op, allow_struct) => {
405 let (op, v) = more;
406 e = Expr::AssignOp(op, Box::new(e), Box::new(v));
407 })
408 |
409 tap!(field: and_field => {
410 e = Expr::Field(Box::new(e), field);
411 })
412 |
413 tap!(field: and_tup_field => {
414 e = Expr::TupField(Box::new(e), field as usize);
415 })
416 |
417 tap!(i: and_index => {
418 e = Expr::Index(Box::new(e), Box::new(i));
419 })
420 |
421 tap!(more: call!(and_range, allow_struct) => {
422 let (limits, hi) = more;
423 e = Expr::Range(Some(Box::new(e)), hi.map(Box::new), limits);
424 })
425 |
426 tap!(_try: punct!("?") => {
427 e = Expr::Try(Box::new(e));
428 })
429 )) >>
430 (e)
431 )
432 }
David Tolnayb9c8e322016-09-23 20:48:37 -0700433
David Tolnay84aa0752016-10-02 23:01:13 -0700434 named!(expr_mac -> Expr, map!(mac, Expr::Mac));
435
David Tolnay89e05672016-10-02 14:39:42 -0700436 named!(expr_paren -> Expr, do_parse!(
437 punct!("(") >>
438 e: expr >>
439 punct!(")") >>
440 (Expr::Paren(Box::new(e)))
441 ));
442
David Tolnayaf2557e2016-10-24 11:52:21 -0700443 named_ambiguous_expr!(expr_box -> Expr, allow_struct, do_parse!(
David Tolnay10413f02016-09-30 09:12:02 -0700444 keyword!("box") >>
David Tolnayaf2557e2016-10-24 11:52:21 -0700445 inner: ambiguous_expr!(allow_struct) >>
David Tolnayb9c8e322016-09-23 20:48:37 -0700446 (Expr::Box(Box::new(inner)))
447 ));
David Tolnayfa0edf22016-09-23 22:58:24 -0700448
David Tolnay939766a2016-09-23 23:48:12 -0700449 named!(expr_vec -> Expr, do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700450 punct!("[") >>
David Tolnayff46fd22016-10-08 13:53:28 -0700451 elems: terminated_list!(punct!(","), expr) >>
David Tolnayfa0edf22016-09-23 22:58:24 -0700452 punct!("]") >>
453 (Expr::Vec(elems))
454 ));
455
David Tolnay939766a2016-09-23 23:48:12 -0700456 named!(and_call -> Vec<Expr>, do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700457 punct!("(") >>
David Tolnayff46fd22016-10-08 13:53:28 -0700458 args: terminated_list!(punct!(","), expr) >>
David Tolnayfa0edf22016-09-23 22:58:24 -0700459 punct!(")") >>
460 (args)
461 ));
462
David Tolnay939766a2016-09-23 23:48:12 -0700463 named!(and_method_call -> (Ident, Vec<Ty>, Vec<Expr>), do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700464 punct!(".") >>
465 method: ident >>
David Tolnayf6c74402016-10-08 02:31:26 -0700466 ascript: opt_vec!(preceded!(
467 punct!("::"),
468 delimited!(
469 punct!("<"),
David Tolnayff46fd22016-10-08 13:53:28 -0700470 terminated_list!(punct!(","), ty),
David Tolnayf6c74402016-10-08 02:31:26 -0700471 punct!(">")
472 )
David Tolnayfa0edf22016-09-23 22:58:24 -0700473 )) >>
474 punct!("(") >>
David Tolnayff46fd22016-10-08 13:53:28 -0700475 args: terminated_list!(punct!(","), expr) >>
David Tolnayfa0edf22016-09-23 22:58:24 -0700476 punct!(")") >>
477 (method, ascript, args)
478 ));
479
David Tolnay939766a2016-09-23 23:48:12 -0700480 named!(expr_tup -> Expr, do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700481 punct!("(") >>
David Tolnayff46fd22016-10-08 13:53:28 -0700482 elems: terminated_list!(punct!(","), expr) >>
David Tolnayfa0edf22016-09-23 22:58:24 -0700483 punct!(")") >>
484 (Expr::Tup(elems))
485 ));
486
David Tolnayaf2557e2016-10-24 11:52:21 -0700487 named_ambiguous_expr!(and_binary -> (BinOp, Expr), allow_struct, tuple!(
488 binop,
489 ambiguous_expr!(allow_struct)
490 ));
David Tolnayfa0edf22016-09-23 22:58:24 -0700491
David Tolnayaf2557e2016-10-24 11:52:21 -0700492 named_ambiguous_expr!(expr_unary -> Expr, allow_struct, do_parse!(
David Tolnay3cb23a92016-10-07 23:02:21 -0700493 operator: unop >>
David Tolnayaf2557e2016-10-24 11:52:21 -0700494 operand: ambiguous_expr!(allow_struct) >>
David Tolnayfa0edf22016-09-23 22:58:24 -0700495 (Expr::Unary(operator, Box::new(operand)))
496 ));
David Tolnay939766a2016-09-23 23:48:12 -0700497
498 named!(expr_lit -> Expr, map!(lit, Expr::Lit));
499
500 named!(and_cast -> Ty, do_parse!(
David Tolnay10413f02016-09-30 09:12:02 -0700501 keyword!("as") >>
David Tolnay939766a2016-09-23 23:48:12 -0700502 ty: ty >>
503 (ty)
504 ));
505
506 named!(and_ascription -> Ty, preceded!(punct!(":"), ty));
507
David Tolnaybb6feae2016-10-02 21:25:20 -0700508 enum Cond {
David Tolnay29f9ce12016-10-02 20:58:40 -0700509 Let(Pat, Expr),
510 Expr(Expr),
511 }
512
David Tolnaybb6feae2016-10-02 21:25:20 -0700513 named!(cond -> Cond, alt!(
514 do_parse!(
515 keyword!("let") >>
516 pat: pat >>
517 punct!("=") >>
David Tolnayaf2557e2016-10-24 11:52:21 -0700518 value: expr_no_struct >>
David Tolnaybb6feae2016-10-02 21:25:20 -0700519 (Cond::Let(pat, value))
520 )
521 |
David Tolnayaf2557e2016-10-24 11:52:21 -0700522 map!(expr_no_struct, Cond::Expr)
David Tolnaybb6feae2016-10-02 21:25:20 -0700523 ));
524
David Tolnay939766a2016-09-23 23:48:12 -0700525 named!(expr_if -> Expr, do_parse!(
David Tolnay10413f02016-09-30 09:12:02 -0700526 keyword!("if") >>
David Tolnaybb6feae2016-10-02 21:25:20 -0700527 cond: cond >>
David Tolnay939766a2016-09-23 23:48:12 -0700528 punct!("{") >>
529 then_block: within_block >>
530 punct!("}") >>
531 else_block: option!(preceded!(
David Tolnay10413f02016-09-30 09:12:02 -0700532 keyword!("else"),
David Tolnay939766a2016-09-23 23:48:12 -0700533 alt!(
534 expr_if
535 |
536 do_parse!(
537 punct!("{") >>
538 else_block: within_block >>
539 punct!("}") >>
David Tolnay89e05672016-10-02 14:39:42 -0700540 (Expr::Block(BlockCheckMode::Default, Block {
David Tolnay939766a2016-09-23 23:48:12 -0700541 stmts: else_block,
David Tolnay89e05672016-10-02 14:39:42 -0700542 }))
David Tolnay939766a2016-09-23 23:48:12 -0700543 )
544 )
545 )) >>
David Tolnay29f9ce12016-10-02 20:58:40 -0700546 (match cond {
David Tolnaybb6feae2016-10-02 21:25:20 -0700547 Cond::Let(pat, expr) => Expr::IfLet(
David Tolnay29f9ce12016-10-02 20:58:40 -0700548 Box::new(pat),
549 Box::new(expr),
550 Block {
551 stmts: then_block,
552 },
553 else_block.map(Box::new),
554 ),
David Tolnaybb6feae2016-10-02 21:25:20 -0700555 Cond::Expr(cond) => Expr::If(
David Tolnay29f9ce12016-10-02 20:58:40 -0700556 Box::new(cond),
557 Block {
558 stmts: then_block,
559 },
560 else_block.map(Box::new),
561 ),
562 })
David Tolnay939766a2016-09-23 23:48:12 -0700563 ));
564
David Tolnaybb6feae2016-10-02 21:25:20 -0700565 named!(expr_for_loop -> Expr, do_parse!(
566 lbl: option!(terminated!(label, punct!(":"))) >>
567 keyword!("for") >>
568 pat: pat >>
569 keyword!("in") >>
David Tolnayaf2557e2016-10-24 11:52:21 -0700570 expr: expr_no_struct >>
David Tolnaybb6feae2016-10-02 21:25:20 -0700571 loop_block: block >>
572 (Expr::ForLoop(Box::new(pat), Box::new(expr), loop_block, lbl))
573 ));
574
Gregory Katze5f35682016-09-27 14:20:55 -0400575 named!(expr_loop -> Expr, do_parse!(
David Tolnay8b07f372016-09-30 10:28:40 -0700576 lbl: option!(terminated!(label, punct!(":"))) >>
David Tolnay10413f02016-09-30 09:12:02 -0700577 keyword!("loop") >>
Gregory Katze5f35682016-09-27 14:20:55 -0400578 loop_block: block >>
David Tolnay89e05672016-10-02 14:39:42 -0700579 (Expr::Loop(loop_block, lbl))
Gregory Katze5f35682016-09-27 14:20:55 -0400580 ));
581
David Tolnayb4ad3b52016-10-01 21:58:13 -0700582 named!(expr_match -> Expr, do_parse!(
583 keyword!("match") >>
David Tolnayaf2557e2016-10-24 11:52:21 -0700584 obj: expr_no_struct >>
David Tolnayb4ad3b52016-10-01 21:58:13 -0700585 punct!("{") >>
David Tolnay1978c672016-10-27 22:05:52 -0700586 mut arms: many0!(do_parse!(
587 arm: match_arm >>
588 cond!(arm_requires_comma(&arm), punct!(",")) >>
589 cond!(!arm_requires_comma(&arm), option!(punct!(","))) >>
590 (arm)
David Tolnayb4ad3b52016-10-01 21:58:13 -0700591 )) >>
David Tolnay1978c672016-10-27 22:05:52 -0700592 last_arm: option!(match_arm) >>
David Tolnayb4ad3b52016-10-01 21:58:13 -0700593 punct!("}") >>
David Tolnay1978c672016-10-27 22:05:52 -0700594 (Expr::Match(Box::new(obj), {
595 arms.extend(last_arm);
596 arms
597 }))
598 ));
599
600 fn arm_requires_comma(arm: &Arm) -> bool {
601 if let Expr::Block(BlockCheckMode::Default, _) = *arm.body {
602 false
603 } else {
604 true
605 }
606 }
607
608 named!(match_arm -> Arm, do_parse!(
609 attrs: many0!(outer_attr) >>
610 pats: separated_nonempty_list!(punct!("|"), pat) >>
611 guard: option!(preceded!(keyword!("if"), expr)) >>
612 punct!("=>") >>
613 body: alt!(
614 map!(block, |blk| Expr::Block(BlockCheckMode::Default, blk))
615 |
616 expr
617 ) >>
618 (Arm {
619 attrs: attrs,
620 pats: pats,
621 guard: guard.map(Box::new),
622 body: Box::new(body),
623 })
David Tolnayb4ad3b52016-10-01 21:58:13 -0700624 ));
625
David Tolnayaf2557e2016-10-24 11:52:21 -0700626 named_ambiguous_expr!(expr_closure -> Expr, allow_struct, do_parse!(
David Tolnay89e05672016-10-02 14:39:42 -0700627 capture: capture_by >>
628 punct!("|") >>
David Tolnayff46fd22016-10-08 13:53:28 -0700629 inputs: terminated_list!(punct!(","), closure_arg) >>
David Tolnay89e05672016-10-02 14:39:42 -0700630 punct!("|") >>
631 ret_and_body: alt!(
632 do_parse!(
633 punct!("->") >>
634 ty: ty >>
635 body: block >>
636 ((FunctionRetTy::Ty(ty), body))
637 )
638 |
David Tolnayaf2557e2016-10-24 11:52:21 -0700639 map!(ambiguous_expr!(allow_struct), |e| (
David Tolnay89e05672016-10-02 14:39:42 -0700640 FunctionRetTy::Default,
641 Block {
642 stmts: vec![Stmt::Expr(Box::new(e))],
643 },
644 ))
645 ) >>
646 (Expr::Closure(
647 capture,
648 Box::new(FnDecl {
649 inputs: inputs,
650 output: ret_and_body.0,
David Tolnay292e6002016-10-29 22:03:51 -0700651 variadic: false,
David Tolnay89e05672016-10-02 14:39:42 -0700652 }),
653 ret_and_body.1,
654 ))
655 ));
656
657 named!(closure_arg -> FnArg, do_parse!(
658 pat: pat >>
659 ty: option!(preceded!(punct!(":"), ty)) >>
David Tolnayca085422016-10-04 00:12:38 -0700660 (FnArg::Captured(pat, ty.unwrap_or(Ty::Infer)))
David Tolnay89e05672016-10-02 14:39:42 -0700661 ));
662
Gregory Katz3e562cc2016-09-28 18:33:02 -0400663 named!(expr_while -> Expr, do_parse!(
David Tolnay8b07f372016-09-30 10:28:40 -0700664 lbl: option!(terminated!(label, punct!(":"))) >>
David Tolnay57ffbde2016-09-30 09:38:04 -0700665 keyword!("while") >>
David Tolnaybb6feae2016-10-02 21:25:20 -0700666 cond: cond >>
Gregory Katz3e562cc2016-09-28 18:33:02 -0400667 while_block: block >>
David Tolnaybb6feae2016-10-02 21:25:20 -0700668 (match cond {
669 Cond::Let(pat, expr) => Expr::WhileLet(
670 Box::new(pat),
671 Box::new(expr),
672 while_block,
673 lbl,
674 ),
675 Cond::Expr(cond) => Expr::While(
676 Box::new(cond),
677 while_block,
678 lbl,
679 ),
680 })
Gregory Katz3e562cc2016-09-28 18:33:02 -0400681 ));
682
Gregory Katzfd6935d2016-09-30 22:51:25 -0400683 named!(expr_continue -> Expr, do_parse!(
684 keyword!("continue") >>
685 lbl: option!(label) >>
David Tolnay055a7042016-10-02 19:23:54 -0700686 (Expr::Continue(lbl))
Gregory Katzfd6935d2016-09-30 22:51:25 -0400687 ));
688
689 named!(expr_break -> Expr, do_parse!(
690 keyword!("break") >>
691 lbl: option!(label) >>
David Tolnay055a7042016-10-02 19:23:54 -0700692 (Expr::Break(lbl))
Gregory Katzfd6935d2016-09-30 22:51:25 -0400693 ));
694
David Tolnayaf2557e2016-10-24 11:52:21 -0700695 named_ambiguous_expr!(expr_ret -> Expr, allow_struct, do_parse!(
Gregory Katzfd6935d2016-09-30 22:51:25 -0400696 keyword!("return") >>
David Tolnayaf2557e2016-10-24 11:52:21 -0700697 ret_value: option!(ambiguous_expr!(allow_struct)) >>
David Tolnay055a7042016-10-02 19:23:54 -0700698 (Expr::Ret(ret_value.map(Box::new)))
699 ));
700
701 named!(expr_struct -> Expr, do_parse!(
702 path: path >>
703 punct!("{") >>
704 fields: separated_list!(punct!(","), field_value) >>
705 base: option!(do_parse!(
706 cond!(!fields.is_empty(), punct!(",")) >>
707 punct!("..") >>
708 base: expr >>
709 (base)
710 )) >>
David Tolnayf6c74402016-10-08 02:31:26 -0700711 cond!(!fields.is_empty() && base.is_none(), option!(punct!(","))) >>
David Tolnay055a7042016-10-02 19:23:54 -0700712 punct!("}") >>
713 (Expr::Struct(path, fields, base.map(Box::new)))
714 ));
715
716 named!(field_value -> FieldValue, do_parse!(
717 name: ident >>
718 punct!(":") >>
719 value: expr >>
720 (FieldValue {
721 ident: name,
722 expr: value,
723 })
724 ));
725
726 named!(expr_repeat -> Expr, do_parse!(
727 punct!("[") >>
728 value: expr >>
729 punct!(";") >>
730 times: expr >>
731 punct!("]") >>
732 (Expr::Repeat(Box::new(value), Box::new(times)))
Gregory Katzfd6935d2016-09-30 22:51:25 -0400733 ));
734
David Tolnay42602292016-10-01 22:25:45 -0700735 named!(expr_block -> Expr, do_parse!(
David Tolnay939766a2016-09-23 23:48:12 -0700736 rules: block_check_mode >>
David Tolnay42602292016-10-01 22:25:45 -0700737 b: block >>
David Tolnay89e05672016-10-02 14:39:42 -0700738 (Expr::Block(rules, Block {
David Tolnay42602292016-10-01 22:25:45 -0700739 stmts: b.stmts,
David Tolnay89e05672016-10-02 14:39:42 -0700740 }))
741 ));
742
David Tolnayaf2557e2016-10-24 11:52:21 -0700743 named_ambiguous_expr!(expr_range -> Expr, allow_struct, do_parse!(
David Tolnay438c9052016-10-07 23:24:48 -0700744 limits: range_limits >>
David Tolnayaf2557e2016-10-24 11:52:21 -0700745 hi: option!(ambiguous_expr!(allow_struct)) >>
David Tolnay438c9052016-10-07 23:24:48 -0700746 (Expr::Range(None, hi.map(Box::new), limits))
747 ));
748
749 named!(range_limits -> RangeLimits, alt!(
750 punct!("...") => { |_| RangeLimits::Closed }
751 |
752 punct!("..") => { |_| RangeLimits::HalfOpen }
753 ));
754
David Tolnay9636c052016-10-02 17:11:17 -0700755 named!(expr_path -> Expr, map!(qpath, |(qself, path)| Expr::Path(qself, path)));
David Tolnay42602292016-10-01 22:25:45 -0700756
David Tolnayaf2557e2016-10-24 11:52:21 -0700757 named_ambiguous_expr!(expr_addr_of -> Expr, allow_struct, do_parse!(
David Tolnay3c2467c2016-10-02 17:55:08 -0700758 punct!("&") >>
759 mutability: mutability >>
David Tolnayaf2557e2016-10-24 11:52:21 -0700760 expr: ambiguous_expr!(allow_struct) >>
David Tolnay3c2467c2016-10-02 17:55:08 -0700761 (Expr::AddrOf(mutability, Box::new(expr)))
762 ));
763
David Tolnayaf2557e2016-10-24 11:52:21 -0700764 named_ambiguous_expr!(and_assign -> Expr, allow_struct, preceded!(
765 punct!("="),
766 ambiguous_expr!(allow_struct)
767 ));
David Tolnay438c9052016-10-07 23:24:48 -0700768
David Tolnayaf2557e2016-10-24 11:52:21 -0700769 named_ambiguous_expr!(and_assign_op -> (BinOp, Expr), allow_struct, tuple!(
770 assign_op,
771 ambiguous_expr!(allow_struct)
772 ));
David Tolnay438c9052016-10-07 23:24:48 -0700773
774 named!(and_field -> Ident, preceded!(punct!("."), ident));
775
776 named!(and_tup_field -> u64, preceded!(punct!("."), digits));
777
778 named!(and_index -> Expr, delimited!(punct!("["), expr, punct!("]")));
779
David Tolnayaf2557e2016-10-24 11:52:21 -0700780 named_ambiguous_expr!(and_range -> (RangeLimits, Option<Expr>), allow_struct, tuple!(
781 range_limits,
David Tolnay54e854d2016-10-24 12:03:30 -0700782 option!(call!(ambiguous_expr, allow_struct, false))
David Tolnayaf2557e2016-10-24 11:52:21 -0700783 ));
David Tolnay438c9052016-10-07 23:24:48 -0700784
David Tolnay42602292016-10-01 22:25:45 -0700785 named!(pub block -> Block, do_parse!(
David Tolnay939766a2016-09-23 23:48:12 -0700786 punct!("{") >>
787 stmts: within_block >>
788 punct!("}") >>
789 (Block {
790 stmts: stmts,
David Tolnay939766a2016-09-23 23:48:12 -0700791 })
792 ));
793
794 named!(block_check_mode -> BlockCheckMode, alt!(
David Tolnay10413f02016-09-30 09:12:02 -0700795 keyword!("unsafe") => { |_| BlockCheckMode::Unsafe }
David Tolnay939766a2016-09-23 23:48:12 -0700796 |
797 epsilon!() => { |_| BlockCheckMode::Default }
798 ));
799
800 named!(within_block -> Vec<Stmt>, do_parse!(
David Tolnaycfe55022016-10-02 22:02:27 -0700801 many0!(punct!(";")) >>
802 mut standalone: many0!(terminated!(standalone_stmt, many0!(punct!(";")))) >>
David Tolnay939766a2016-09-23 23:48:12 -0700803 last: option!(expr) >>
804 (match last {
David Tolnaycfe55022016-10-02 22:02:27 -0700805 None => standalone,
David Tolnay939766a2016-09-23 23:48:12 -0700806 Some(last) => {
David Tolnaycfe55022016-10-02 22:02:27 -0700807 standalone.push(Stmt::Expr(Box::new(last)));
808 standalone
David Tolnay939766a2016-09-23 23:48:12 -0700809 }
810 })
811 ));
812
813 named!(standalone_stmt -> Stmt, alt!(
David Tolnay13b3d352016-10-03 00:31:15 -0700814 stmt_mac
815 |
David Tolnay191e0582016-10-02 18:31:09 -0700816 stmt_local
817 |
818 stmt_item
819 |
David Tolnaycfe55022016-10-02 22:02:27 -0700820 stmt_expr
David Tolnay939766a2016-09-23 23:48:12 -0700821 ));
822
David Tolnay13b3d352016-10-03 00:31:15 -0700823 named!(stmt_mac -> Stmt, do_parse!(
824 attrs: many0!(outer_attr) >>
David Tolnayeea28d62016-10-25 20:44:08 -0700825 name: ident >>
826 punct!("!") >>
827 // Only parse braces here; paren and bracket will get parsed as
828 // expression statements
829 punct!("{") >>
830 tts: token_trees >>
831 punct!("}") >>
832 (Stmt::Mac(Box::new((
833 Mac {
834 path: name.into(),
835 tts: vec![TokenTree::Delimited(Delimited {
836 delim: DelimToken::Brace,
837 tts: tts,
838 })],
839 },
840 MacStmtStyle::Braces,
841 attrs,
842 ))))
David Tolnay13b3d352016-10-03 00:31:15 -0700843 ));
844
David Tolnay191e0582016-10-02 18:31:09 -0700845 named!(stmt_local -> Stmt, do_parse!(
846 attrs: many0!(outer_attr) >>
847 keyword!("let") >>
848 pat: pat >>
849 ty: option!(preceded!(punct!(":"), ty)) >>
850 init: option!(preceded!(punct!("="), expr)) >>
851 punct!(";") >>
852 (Stmt::Local(Box::new(Local {
853 pat: Box::new(pat),
854 ty: ty.map(Box::new),
855 init: init.map(Box::new),
856 attrs: attrs,
857 })))
858 ));
859
860 named!(stmt_item -> Stmt, map!(item, |i| Stmt::Item(Box::new(i))));
861
David Tolnaycfe55022016-10-02 22:02:27 -0700862 fn requires_semi(e: &Expr) -> bool {
863 match *e {
David Tolnaycfe55022016-10-02 22:02:27 -0700864 Expr::If(_, _, _) |
865 Expr::IfLet(_, _, _, _) |
866 Expr::While(_, _, _) |
867 Expr::WhileLet(_, _, _, _) |
868 Expr::ForLoop(_, _, _, _) |
869 Expr::Loop(_, _) |
870 Expr::Match(_, _) |
871 Expr::Block(_, _) => false,
872
873 _ => true,
874 }
875 }
876
877 named!(stmt_expr -> Stmt, do_parse!(
David Tolnay939766a2016-09-23 23:48:12 -0700878 e: expr >>
David Tolnaycfe55022016-10-02 22:02:27 -0700879 semi: option!(punct!(";")) >>
880 (if semi.is_some() {
881 Stmt::Semi(Box::new(e))
882 } else if requires_semi(&e) {
883 return Error;
884 } else {
885 Stmt::Expr(Box::new(e))
886 })
David Tolnay939766a2016-09-23 23:48:12 -0700887 ));
David Tolnay8b07f372016-09-30 10:28:40 -0700888
David Tolnay42602292016-10-01 22:25:45 -0700889 named!(pub pat -> Pat, alt!(
David Tolnayfbb73232016-10-03 01:00:06 -0700890 pat_wild // must be before pat_ident
891 |
892 pat_box // must be before pat_ident
David Tolnayb4ad3b52016-10-01 21:58:13 -0700893 |
David Tolnay8b308c22016-10-03 01:24:10 -0700894 pat_range // must be before pat_lit
895 |
David Tolnayaa610942016-10-03 22:22:49 -0700896 pat_tuple_struct // must be before pat_ident
897 |
David Tolnay8d9e81a2016-10-03 22:36:32 -0700898 pat_struct // must be before pat_ident
899 |
David Tolnayaa610942016-10-03 22:22:49 -0700900 pat_mac // must be before pat_ident
901 |
David Tolnaybcdbdd02016-10-24 23:05:02 -0700902 pat_lit // must be before pat_ident
903 |
David Tolnay8b308c22016-10-03 01:24:10 -0700904 pat_ident // must be before pat_path
David Tolnay9636c052016-10-02 17:11:17 -0700905 |
906 pat_path
David Tolnayfbb73232016-10-03 01:00:06 -0700907 |
908 pat_tuple
David Tolnayffdb97f2016-10-03 01:28:33 -0700909 |
910 pat_ref
David Tolnay435a9a82016-10-29 13:47:20 -0700911 |
912 pat_slice
David Tolnayb4ad3b52016-10-01 21:58:13 -0700913 ));
914
David Tolnay84aa0752016-10-02 23:01:13 -0700915 named!(pat_mac -> Pat, map!(mac, Pat::Mac));
916
David Tolnayb4ad3b52016-10-01 21:58:13 -0700917 named!(pat_wild -> Pat, map!(keyword!("_"), |_| Pat::Wild));
918
David Tolnayfbb73232016-10-03 01:00:06 -0700919 named!(pat_box -> Pat, do_parse!(
920 keyword!("box") >>
921 pat: pat >>
922 (Pat::Box(Box::new(pat)))
923 ));
924
David Tolnayb4ad3b52016-10-01 21:58:13 -0700925 named!(pat_ident -> Pat, do_parse!(
926 mode: option!(keyword!("ref")) >>
927 mutability: mutability >>
David Tolnay8d4d2fa2016-10-25 22:08:07 -0700928 name: alt!(
929 ident
930 |
931 keyword!("self") => { Into::into }
932 ) >>
David Tolnay8b308c22016-10-03 01:24:10 -0700933 not!(peek!(punct!("<"))) >>
934 not!(peek!(punct!("::"))) >>
David Tolnayb4ad3b52016-10-01 21:58:13 -0700935 subpat: option!(preceded!(punct!("@"), pat)) >>
936 (Pat::Ident(
937 if mode.is_some() {
938 BindingMode::ByRef(mutability)
939 } else {
940 BindingMode::ByValue(mutability)
941 },
942 name,
943 subpat.map(Box::new),
944 ))
945 ));
946
David Tolnayaa610942016-10-03 22:22:49 -0700947 named!(pat_tuple_struct -> Pat, do_parse!(
948 path: path >>
949 tuple: pat_tuple_helper >>
950 (Pat::TupleStruct(path, tuple.0, tuple.1))
951 ));
952
David Tolnay8d9e81a2016-10-03 22:36:32 -0700953 named!(pat_struct -> Pat, do_parse!(
954 path: path >>
955 punct!("{") >>
956 fields: separated_list!(punct!(","), field_pat) >>
957 more: option!(preceded!(
958 cond!(!fields.is_empty(), punct!(",")),
959 punct!("..")
960 )) >>
David Tolnayff46fd22016-10-08 13:53:28 -0700961 cond!(!fields.is_empty() && more.is_none(), option!(punct!(","))) >>
David Tolnay8d9e81a2016-10-03 22:36:32 -0700962 punct!("}") >>
963 (Pat::Struct(path, fields, more.is_some()))
964 ));
965
966 named!(field_pat -> FieldPat, alt!(
967 do_parse!(
968 ident: ident >>
969 punct!(":") >>
970 pat: pat >>
971 (FieldPat {
972 ident: ident,
973 pat: Box::new(pat),
974 is_shorthand: false,
975 })
976 )
977 |
978 do_parse!(
979 mode: option!(keyword!("ref")) >>
980 mutability: mutability >>
981 ident: ident >>
982 (FieldPat {
983 ident: ident.clone(),
984 pat: Box::new(Pat::Ident(
985 if mode.is_some() {
986 BindingMode::ByRef(mutability)
987 } else {
988 BindingMode::ByValue(mutability)
989 },
990 ident,
991 None,
992 )),
993 is_shorthand: true,
994 })
995 )
996 ));
997
David Tolnay9636c052016-10-02 17:11:17 -0700998 named!(pat_path -> Pat, map!(qpath, |(qself, path)| Pat::Path(qself, path)));
999
David Tolnayaa610942016-10-03 22:22:49 -07001000 named!(pat_tuple -> Pat, map!(
1001 pat_tuple_helper,
1002 |(pats, dotdot)| Pat::Tuple(pats, dotdot)
1003 ));
1004
1005 named!(pat_tuple_helper -> (Vec<Pat>, Option<usize>), do_parse!(
David Tolnayfbb73232016-10-03 01:00:06 -07001006 punct!("(") >>
1007 mut elems: separated_list!(punct!(","), pat) >>
1008 dotdot: option!(do_parse!(
1009 cond!(!elems.is_empty(), punct!(",")) >>
1010 punct!("..") >>
1011 rest: many0!(preceded!(punct!(","), pat)) >>
1012 cond!(!rest.is_empty(), option!(punct!(","))) >>
1013 (rest)
1014 )) >>
1015 cond!(!elems.is_empty() && dotdot.is_none(), option!(punct!(","))) >>
1016 punct!(")") >>
1017 (match dotdot {
1018 Some(rest) => {
1019 let pos = elems.len();
1020 elems.extend(rest);
David Tolnayaa610942016-10-03 22:22:49 -07001021 (elems, Some(pos))
David Tolnayfbb73232016-10-03 01:00:06 -07001022 }
David Tolnayaa610942016-10-03 22:22:49 -07001023 None => (elems, None),
David Tolnayfbb73232016-10-03 01:00:06 -07001024 })
1025 ));
1026
David Tolnayffdb97f2016-10-03 01:28:33 -07001027 named!(pat_ref -> Pat, do_parse!(
1028 punct!("&") >>
1029 mutability: mutability >>
1030 pat: pat >>
1031 (Pat::Ref(Box::new(pat), mutability))
1032 ));
1033
David Tolnay8b308c22016-10-03 01:24:10 -07001034 named!(pat_lit -> Pat, map!(lit, |lit| Pat::Lit(Box::new(lit))));
1035
1036 named!(pat_range -> Pat, do_parse!(
1037 lo: lit >>
1038 punct!("...") >>
1039 hi: lit >>
1040 (Pat::Range(Box::new(lo), Box::new(hi)))
1041 ));
1042
David Tolnay435a9a82016-10-29 13:47:20 -07001043 named!(pat_slice -> Pat, do_parse!(
1044 punct!("[") >>
1045 before: separated_list!(punct!(","), pat) >>
1046 after: option!(do_parse!(
1047 cond!(!before.is_empty(), punct!(",")) >>
1048 punct!("..") >>
1049 after: many0!(preceded!(punct!(","), pat)) >>
1050 cond!(!after.is_empty(), option!(punct!(","))) >>
1051 (after)
1052 )) >>
1053 punct!("]") >>
1054 (match after {
1055 Some(after) => Pat::Slice(before, Some(Box::new(Pat::Wild)), after),
1056 None => Pat::Slice(before, None, Vec::new()),
1057 })
1058 ));
1059
David Tolnay89e05672016-10-02 14:39:42 -07001060 named!(capture_by -> CaptureBy, alt!(
1061 keyword!("move") => { |_| CaptureBy::Value }
1062 |
1063 epsilon!() => { |_| CaptureBy::Ref }
1064 ));
1065
David Tolnay8b07f372016-09-30 10:28:40 -07001066 named!(label -> Ident, map!(lifetime, |lt: Lifetime| lt.ident));
David Tolnayb9c8e322016-09-23 20:48:37 -07001067}
1068
David Tolnayf4bbbd92016-09-23 14:41:55 -07001069#[cfg(feature = "printing")]
1070mod printing {
1071 use super::*;
David Tolnayca085422016-10-04 00:12:38 -07001072 use {FnArg, FunctionRetTy, Mutability, Ty};
David Tolnay13b3d352016-10-03 00:31:15 -07001073 use attr::FilterAttrs;
David Tolnayf4bbbd92016-09-23 14:41:55 -07001074 use quote::{Tokens, ToTokens};
1075
1076 impl ToTokens for Expr {
1077 fn to_tokens(&self, tokens: &mut Tokens) {
1078 match *self {
David Tolnaybb6feae2016-10-02 21:25:20 -07001079 Expr::Box(ref inner) => {
1080 tokens.append("box");
1081 inner.to_tokens(tokens);
1082 }
1083 Expr::Vec(ref tys) => {
1084 tokens.append("[");
1085 tokens.append_separated(tys, ",");
1086 tokens.append("]");
1087 }
David Tolnay9636c052016-10-02 17:11:17 -07001088 Expr::Call(ref func, ref args) => {
1089 func.to_tokens(tokens);
1090 tokens.append("(");
1091 tokens.append_separated(args, ",");
1092 tokens.append(")");
1093 }
1094 Expr::MethodCall(ref ident, ref ascript, ref args) => {
1095 args[0].to_tokens(tokens);
1096 tokens.append(".");
1097 ident.to_tokens(tokens);
David Tolnay58f6f672016-10-19 08:44:25 -07001098 if !ascript.is_empty() {
David Tolnay9636c052016-10-02 17:11:17 -07001099 tokens.append("::");
1100 tokens.append("<");
1101 tokens.append_separated(ascript, ",");
1102 tokens.append(">");
1103 }
1104 tokens.append("(");
1105 tokens.append_separated(&args[1..], ",");
1106 tokens.append(")");
1107 }
David Tolnay47a877c2016-10-01 16:50:55 -07001108 Expr::Tup(ref fields) => {
1109 tokens.append("(");
1110 tokens.append_separated(fields, ",");
1111 if fields.len() == 1 {
1112 tokens.append(",");
1113 }
1114 tokens.append(")");
1115 }
David Tolnay89e05672016-10-02 14:39:42 -07001116 Expr::Binary(op, ref left, ref right) => {
1117 left.to_tokens(tokens);
1118 op.to_tokens(tokens);
1119 right.to_tokens(tokens);
1120 }
David Tolnay3c2467c2016-10-02 17:55:08 -07001121 Expr::Unary(op, ref expr) => {
1122 op.to_tokens(tokens);
1123 expr.to_tokens(tokens);
1124 }
David Tolnayf4bbbd92016-09-23 14:41:55 -07001125 Expr::Lit(ref lit) => lit.to_tokens(tokens),
David Tolnay3c2467c2016-10-02 17:55:08 -07001126 Expr::Cast(ref expr, ref ty) => {
1127 expr.to_tokens(tokens);
1128 tokens.append("as");
1129 ty.to_tokens(tokens);
1130 }
1131 Expr::Type(ref expr, ref ty) => {
1132 expr.to_tokens(tokens);
1133 tokens.append(":");
1134 ty.to_tokens(tokens);
1135 }
1136 Expr::If(ref cond, ref then_block, ref else_block) => {
1137 tokens.append("if");
1138 cond.to_tokens(tokens);
1139 then_block.to_tokens(tokens);
1140 if let Some(ref else_block) = *else_block {
1141 tokens.append("else");
1142 else_block.to_tokens(tokens);
1143 }
1144 }
David Tolnay29f9ce12016-10-02 20:58:40 -07001145 Expr::IfLet(ref pat, ref expr, ref then_block, ref else_block) => {
1146 tokens.append("if");
1147 tokens.append("let");
1148 pat.to_tokens(tokens);
1149 tokens.append("=");
1150 expr.to_tokens(tokens);
1151 then_block.to_tokens(tokens);
1152 if let Some(ref else_block) = *else_block {
1153 tokens.append("else");
1154 else_block.to_tokens(tokens);
1155 }
1156 }
David Tolnaybb6feae2016-10-02 21:25:20 -07001157 Expr::While(ref cond, ref body, ref label) => {
1158 if let Some(ref label) = *label {
1159 label.to_tokens(tokens);
1160 tokens.append(":");
1161 }
1162 tokens.append("while");
1163 cond.to_tokens(tokens);
1164 body.to_tokens(tokens);
1165 }
1166 Expr::WhileLet(ref pat, ref expr, ref body, ref label) => {
1167 if let Some(ref label) = *label {
1168 label.to_tokens(tokens);
1169 tokens.append(":");
1170 }
1171 tokens.append("while");
1172 tokens.append("let");
1173 pat.to_tokens(tokens);
1174 tokens.append("=");
1175 expr.to_tokens(tokens);
1176 body.to_tokens(tokens);
1177 }
1178 Expr::ForLoop(ref pat, ref expr, ref body, ref label) => {
1179 if let Some(ref label) = *label {
1180 label.to_tokens(tokens);
1181 tokens.append(":");
1182 }
1183 tokens.append("for");
1184 pat.to_tokens(tokens);
1185 tokens.append("in");
1186 expr.to_tokens(tokens);
1187 body.to_tokens(tokens);
1188 }
1189 Expr::Loop(ref body, ref label) => {
1190 if let Some(ref label) = *label {
1191 label.to_tokens(tokens);
1192 tokens.append(":");
1193 }
1194 tokens.append("loop");
1195 body.to_tokens(tokens);
1196 }
David Tolnayb4ad3b52016-10-01 21:58:13 -07001197 Expr::Match(ref expr, ref arms) => {
1198 tokens.append("match");
1199 expr.to_tokens(tokens);
1200 tokens.append("{");
David Tolnay2165b042016-10-08 00:04:23 -07001201 tokens.append_all(arms);
David Tolnayb4ad3b52016-10-01 21:58:13 -07001202 tokens.append("}");
1203 }
David Tolnay89e05672016-10-02 14:39:42 -07001204 Expr::Closure(capture, ref decl, ref body) => {
1205 capture.to_tokens(tokens);
1206 tokens.append("|");
1207 for (i, input) in decl.inputs.iter().enumerate() {
1208 if i > 0 {
1209 tokens.append(",");
1210 }
David Tolnayca085422016-10-04 00:12:38 -07001211 match *input {
1212 FnArg::Captured(ref pat, Ty::Infer) => {
1213 pat.to_tokens(tokens);
David Tolnaydaaf7742016-10-03 11:11:43 -07001214 }
David Tolnayca085422016-10-04 00:12:38 -07001215 _ => input.to_tokens(tokens),
David Tolnay89e05672016-10-02 14:39:42 -07001216 }
1217 }
1218 tokens.append("|");
1219 match decl.output {
1220 FunctionRetTy::Default => {
1221 if body.stmts.len() == 1 {
1222 if let Stmt::Expr(ref expr) = body.stmts[0] {
1223 expr.to_tokens(tokens);
1224 } else {
1225 body.to_tokens(tokens);
1226 }
1227 } else {
1228 body.to_tokens(tokens);
1229 }
1230 }
1231 FunctionRetTy::Ty(ref ty) => {
1232 tokens.append("->");
1233 ty.to_tokens(tokens);
1234 body.to_tokens(tokens);
1235 }
1236 }
1237 }
1238 Expr::Block(rules, ref block) => {
1239 rules.to_tokens(tokens);
1240 block.to_tokens(tokens);
1241 }
David Tolnaybb6feae2016-10-02 21:25:20 -07001242 Expr::Assign(ref var, ref expr) => {
1243 var.to_tokens(tokens);
1244 tokens.append("=");
1245 expr.to_tokens(tokens);
1246 }
1247 Expr::AssignOp(op, ref var, ref expr) => {
1248 var.to_tokens(tokens);
David Tolnay3cb23a92016-10-07 23:02:21 -07001249 tokens.append(op.assign_op().unwrap());
David Tolnaybb6feae2016-10-02 21:25:20 -07001250 expr.to_tokens(tokens);
1251 }
1252 Expr::Field(ref expr, ref field) => {
1253 expr.to_tokens(tokens);
1254 tokens.append(".");
1255 field.to_tokens(tokens);
1256 }
1257 Expr::TupField(ref expr, field) => {
1258 expr.to_tokens(tokens);
1259 tokens.append(".");
1260 tokens.append(&field.to_string());
1261 }
1262 Expr::Index(ref expr, ref index) => {
1263 expr.to_tokens(tokens);
1264 tokens.append("[");
1265 index.to_tokens(tokens);
1266 tokens.append("]");
1267 }
1268 Expr::Range(ref from, ref to, limits) => {
1269 from.to_tokens(tokens);
1270 match limits {
1271 RangeLimits::HalfOpen => tokens.append(".."),
1272 RangeLimits::Closed => tokens.append("..."),
1273 }
1274 to.to_tokens(tokens);
1275 }
David Tolnay8b308c22016-10-03 01:24:10 -07001276 Expr::Path(None, ref path) => path.to_tokens(tokens),
David Tolnay89e05672016-10-02 14:39:42 -07001277 Expr::Path(Some(ref qself), ref path) => {
1278 tokens.append("<");
1279 qself.ty.to_tokens(tokens);
1280 if qself.position > 0 {
1281 tokens.append("as");
David Tolnaydaaf7742016-10-03 11:11:43 -07001282 for (i, segment) in path.segments
1283 .iter()
1284 .take(qself.position)
1285 .enumerate() {
David Tolnay89e05672016-10-02 14:39:42 -07001286 if i > 0 || path.global {
1287 tokens.append("::");
1288 }
1289 segment.to_tokens(tokens);
1290 }
1291 }
1292 tokens.append(">");
1293 for segment in path.segments.iter().skip(qself.position) {
1294 tokens.append("::");
1295 segment.to_tokens(tokens);
1296 }
1297 }
David Tolnay3c2467c2016-10-02 17:55:08 -07001298 Expr::AddrOf(mutability, ref expr) => {
1299 tokens.append("&");
1300 mutability.to_tokens(tokens);
1301 expr.to_tokens(tokens);
1302 }
1303 Expr::Break(ref opt_label) => {
1304 tokens.append("break");
1305 opt_label.to_tokens(tokens);
1306 }
1307 Expr::Continue(ref opt_label) => {
1308 tokens.append("continue");
1309 opt_label.to_tokens(tokens);
1310 }
David Tolnay42602292016-10-01 22:25:45 -07001311 Expr::Ret(ref opt_expr) => {
1312 tokens.append("return");
1313 opt_expr.to_tokens(tokens);
1314 }
David Tolnaycc3d66e2016-10-02 23:36:05 -07001315 Expr::Mac(ref mac) => mac.to_tokens(tokens),
David Tolnay055a7042016-10-02 19:23:54 -07001316 Expr::Struct(ref path, ref fields, ref base) => {
1317 path.to_tokens(tokens);
1318 tokens.append("{");
1319 tokens.append_separated(fields, ",");
1320 if let Some(ref base) = *base {
1321 if !fields.is_empty() {
1322 tokens.append(",");
1323 }
1324 tokens.append("..");
1325 base.to_tokens(tokens);
1326 }
1327 tokens.append("}");
1328 }
1329 Expr::Repeat(ref expr, ref times) => {
1330 tokens.append("[");
1331 expr.to_tokens(tokens);
1332 tokens.append(";");
1333 times.to_tokens(tokens);
1334 tokens.append("]");
1335 }
David Tolnay89e05672016-10-02 14:39:42 -07001336 Expr::Paren(ref expr) => {
1337 tokens.append("(");
1338 expr.to_tokens(tokens);
1339 tokens.append(")");
1340 }
David Tolnay3c2467c2016-10-02 17:55:08 -07001341 Expr::Try(ref expr) => {
1342 expr.to_tokens(tokens);
1343 tokens.append("?");
1344 }
David Tolnayf4bbbd92016-09-23 14:41:55 -07001345 }
1346 }
1347 }
David Tolnayb4ad3b52016-10-01 21:58:13 -07001348
David Tolnay055a7042016-10-02 19:23:54 -07001349 impl ToTokens for FieldValue {
1350 fn to_tokens(&self, tokens: &mut Tokens) {
1351 self.ident.to_tokens(tokens);
1352 tokens.append(":");
1353 self.expr.to_tokens(tokens);
1354 }
1355 }
1356
David Tolnayb4ad3b52016-10-01 21:58:13 -07001357 impl ToTokens for Arm {
1358 fn to_tokens(&self, tokens: &mut Tokens) {
1359 for attr in &self.attrs {
1360 attr.to_tokens(tokens);
1361 }
1362 tokens.append_separated(&self.pats, "|");
1363 if let Some(ref guard) = self.guard {
1364 tokens.append("if");
1365 guard.to_tokens(tokens);
1366 }
1367 tokens.append("=>");
1368 self.body.to_tokens(tokens);
1369 match *self.body {
David Tolnay1978c672016-10-27 22:05:52 -07001370 Expr::Block(BlockCheckMode::Default, _) => {
David Tolnaydaaf7742016-10-03 11:11:43 -07001371 // no comma
1372 }
David Tolnayb4ad3b52016-10-01 21:58:13 -07001373 _ => tokens.append(","),
1374 }
1375 }
1376 }
1377
1378 impl ToTokens for Pat {
1379 fn to_tokens(&self, tokens: &mut Tokens) {
1380 match *self {
1381 Pat::Wild => tokens.append("_"),
1382 Pat::Ident(mode, ref ident, ref subpat) => {
1383 mode.to_tokens(tokens);
1384 ident.to_tokens(tokens);
1385 if let Some(ref subpat) = *subpat {
1386 tokens.append("@");
1387 subpat.to_tokens(tokens);
1388 }
1389 }
David Tolnay8d9e81a2016-10-03 22:36:32 -07001390 Pat::Struct(ref path, ref fields, dots) => {
1391 path.to_tokens(tokens);
1392 tokens.append("{");
1393 tokens.append_separated(fields, ",");
1394 if dots {
1395 if !fields.is_empty() {
1396 tokens.append(",");
1397 }
1398 tokens.append("..");
1399 }
1400 tokens.append("}");
1401 }
David Tolnayaa610942016-10-03 22:22:49 -07001402 Pat::TupleStruct(ref path, ref pats, dotpos) => {
1403 path.to_tokens(tokens);
1404 tokens.append("(");
1405 match dotpos {
1406 Some(pos) => {
1407 if pos > 0 {
1408 tokens.append_separated(&pats[..pos], ",");
1409 tokens.append(",");
1410 }
1411 tokens.append("..");
1412 if pos < pats.len() {
1413 tokens.append(",");
1414 tokens.append_separated(&pats[pos..], ",");
1415 }
1416 }
1417 None => tokens.append_separated(pats, ","),
1418 }
1419 tokens.append(")");
1420 }
David Tolnay8b308c22016-10-03 01:24:10 -07001421 Pat::Path(None, ref path) => path.to_tokens(tokens),
1422 Pat::Path(Some(ref qself), ref path) => {
1423 tokens.append("<");
1424 qself.ty.to_tokens(tokens);
1425 if qself.position > 0 {
1426 tokens.append("as");
David Tolnaydaaf7742016-10-03 11:11:43 -07001427 for (i, segment) in path.segments
1428 .iter()
1429 .take(qself.position)
1430 .enumerate() {
David Tolnay8b308c22016-10-03 01:24:10 -07001431 if i > 0 || path.global {
1432 tokens.append("::");
1433 }
1434 segment.to_tokens(tokens);
1435 }
1436 }
1437 tokens.append(">");
1438 for segment in path.segments.iter().skip(qself.position) {
1439 tokens.append("::");
1440 segment.to_tokens(tokens);
1441 }
1442 }
David Tolnayfbb73232016-10-03 01:00:06 -07001443 Pat::Tuple(ref pats, dotpos) => {
1444 tokens.append("(");
1445 match dotpos {
1446 Some(pos) => {
1447 if pos > 0 {
1448 tokens.append_separated(&pats[..pos], ",");
1449 tokens.append(",");
1450 }
1451 tokens.append("..");
1452 if pos < pats.len() {
1453 tokens.append(",");
1454 tokens.append_separated(&pats[pos..], ",");
1455 }
1456 }
1457 None => tokens.append_separated(pats, ","),
1458 }
1459 tokens.append(")");
1460 }
1461 Pat::Box(ref inner) => {
1462 tokens.append("box");
1463 inner.to_tokens(tokens);
1464 }
David Tolnayffdb97f2016-10-03 01:28:33 -07001465 Pat::Ref(ref target, mutability) => {
1466 tokens.append("&");
1467 mutability.to_tokens(tokens);
1468 target.to_tokens(tokens);
1469 }
David Tolnay8b308c22016-10-03 01:24:10 -07001470 Pat::Lit(ref lit) => lit.to_tokens(tokens),
1471 Pat::Range(ref lo, ref hi) => {
1472 lo.to_tokens(tokens);
1473 tokens.append("...");
1474 hi.to_tokens(tokens);
1475 }
David Tolnay435a9a82016-10-29 13:47:20 -07001476 Pat::Slice(ref before, ref dots, ref after) => {
1477 tokens.append("[");
1478 tokens.append_separated(before, ",");
1479 match *dots {
1480 Some(ref dots) if **dots == Pat::Wild => {
1481 if !before.is_empty() {
1482 tokens.append(",");
1483 }
1484 tokens.append("..");
1485 if !after.is_empty() {
1486 tokens.append(",");
1487 }
1488 tokens.append_separated(after, ",");
1489 }
1490 None => {}
1491 _ => unimplemented!(),
1492 }
1493 tokens.append("]");
1494 }
David Tolnaycc3d66e2016-10-02 23:36:05 -07001495 Pat::Mac(ref mac) => mac.to_tokens(tokens),
David Tolnayb4ad3b52016-10-01 21:58:13 -07001496 }
1497 }
1498 }
1499
David Tolnay8d9e81a2016-10-03 22:36:32 -07001500 impl ToTokens for FieldPat {
1501 fn to_tokens(&self, tokens: &mut Tokens) {
1502 if !self.is_shorthand {
1503 self.ident.to_tokens(tokens);
1504 tokens.append(":");
1505 }
1506 self.pat.to_tokens(tokens);
1507 }
1508 }
1509
David Tolnayb4ad3b52016-10-01 21:58:13 -07001510 impl ToTokens for BindingMode {
1511 fn to_tokens(&self, tokens: &mut Tokens) {
1512 match *self {
1513 BindingMode::ByRef(Mutability::Immutable) => {
1514 tokens.append("ref");
1515 }
1516 BindingMode::ByRef(Mutability::Mutable) => {
1517 tokens.append("ref");
1518 tokens.append("mut");
1519 }
1520 BindingMode::ByValue(Mutability::Immutable) => {}
1521 BindingMode::ByValue(Mutability::Mutable) => {
1522 tokens.append("mut");
1523 }
1524 }
1525 }
1526 }
David Tolnay42602292016-10-01 22:25:45 -07001527
David Tolnay89e05672016-10-02 14:39:42 -07001528 impl ToTokens for CaptureBy {
1529 fn to_tokens(&self, tokens: &mut Tokens) {
1530 match *self {
1531 CaptureBy::Value => tokens.append("move"),
David Tolnaydaaf7742016-10-03 11:11:43 -07001532 CaptureBy::Ref => {
1533 // nothing
1534 }
David Tolnay89e05672016-10-02 14:39:42 -07001535 }
1536 }
1537 }
1538
David Tolnay42602292016-10-01 22:25:45 -07001539 impl ToTokens for Block {
1540 fn to_tokens(&self, tokens: &mut Tokens) {
David Tolnay42602292016-10-01 22:25:45 -07001541 tokens.append("{");
1542 for stmt in &self.stmts {
1543 stmt.to_tokens(tokens);
1544 }
1545 tokens.append("}");
1546 }
1547 }
1548
1549 impl ToTokens for BlockCheckMode {
1550 fn to_tokens(&self, tokens: &mut Tokens) {
1551 match *self {
David Tolnaydaaf7742016-10-03 11:11:43 -07001552 BlockCheckMode::Default => {
1553 // nothing
1554 }
David Tolnay42602292016-10-01 22:25:45 -07001555 BlockCheckMode::Unsafe => tokens.append("unsafe"),
1556 }
1557 }
1558 }
1559
1560 impl ToTokens for Stmt {
1561 fn to_tokens(&self, tokens: &mut Tokens) {
1562 match *self {
David Tolnay191e0582016-10-02 18:31:09 -07001563 Stmt::Local(ref local) => local.to_tokens(tokens),
David Tolnay42602292016-10-01 22:25:45 -07001564 Stmt::Item(ref item) => item.to_tokens(tokens),
1565 Stmt::Expr(ref expr) => expr.to_tokens(tokens),
1566 Stmt::Semi(ref expr) => {
1567 expr.to_tokens(tokens);
1568 tokens.append(";");
1569 }
David Tolnay13b3d352016-10-03 00:31:15 -07001570 Stmt::Mac(ref mac) => {
1571 let (ref mac, style, ref attrs) = **mac;
1572 for attr in attrs.outer() {
1573 attr.to_tokens(tokens);
1574 }
1575 mac.to_tokens(tokens);
1576 match style {
1577 MacStmtStyle::Semicolon => tokens.append(";"),
David Tolnaydaaf7742016-10-03 11:11:43 -07001578 MacStmtStyle::Braces | MacStmtStyle::NoBraces => {
1579 // no semicolon
1580 }
David Tolnay13b3d352016-10-03 00:31:15 -07001581 }
1582 }
David Tolnay42602292016-10-01 22:25:45 -07001583 }
1584 }
1585 }
David Tolnay191e0582016-10-02 18:31:09 -07001586
1587 impl ToTokens for Local {
1588 fn to_tokens(&self, tokens: &mut Tokens) {
1589 tokens.append("let");
1590 self.pat.to_tokens(tokens);
1591 if let Some(ref ty) = self.ty {
1592 tokens.append(":");
1593 ty.to_tokens(tokens);
1594 }
1595 if let Some(ref init) = self.init {
1596 tokens.append("=");
1597 init.to_tokens(tokens);
1598 }
1599 tokens.append(";");
1600 }
1601 }
David Tolnayf4bbbd92016-09-23 14:41:55 -07001602}