blob: 5784a7333449bfc8527828ca1c76ef841410519a [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,
651 }),
652 ret_and_body.1,
653 ))
654 ));
655
656 named!(closure_arg -> FnArg, do_parse!(
657 pat: pat >>
658 ty: option!(preceded!(punct!(":"), ty)) >>
David Tolnayca085422016-10-04 00:12:38 -0700659 (FnArg::Captured(pat, ty.unwrap_or(Ty::Infer)))
David Tolnay89e05672016-10-02 14:39:42 -0700660 ));
661
Gregory Katz3e562cc2016-09-28 18:33:02 -0400662 named!(expr_while -> Expr, do_parse!(
David Tolnay8b07f372016-09-30 10:28:40 -0700663 lbl: option!(terminated!(label, punct!(":"))) >>
David Tolnay57ffbde2016-09-30 09:38:04 -0700664 keyword!("while") >>
David Tolnaybb6feae2016-10-02 21:25:20 -0700665 cond: cond >>
Gregory Katz3e562cc2016-09-28 18:33:02 -0400666 while_block: block >>
David Tolnaybb6feae2016-10-02 21:25:20 -0700667 (match cond {
668 Cond::Let(pat, expr) => Expr::WhileLet(
669 Box::new(pat),
670 Box::new(expr),
671 while_block,
672 lbl,
673 ),
674 Cond::Expr(cond) => Expr::While(
675 Box::new(cond),
676 while_block,
677 lbl,
678 ),
679 })
Gregory Katz3e562cc2016-09-28 18:33:02 -0400680 ));
681
Gregory Katzfd6935d2016-09-30 22:51:25 -0400682 named!(expr_continue -> Expr, do_parse!(
683 keyword!("continue") >>
684 lbl: option!(label) >>
David Tolnay055a7042016-10-02 19:23:54 -0700685 (Expr::Continue(lbl))
Gregory Katzfd6935d2016-09-30 22:51:25 -0400686 ));
687
688 named!(expr_break -> Expr, do_parse!(
689 keyword!("break") >>
690 lbl: option!(label) >>
David Tolnay055a7042016-10-02 19:23:54 -0700691 (Expr::Break(lbl))
Gregory Katzfd6935d2016-09-30 22:51:25 -0400692 ));
693
David Tolnayaf2557e2016-10-24 11:52:21 -0700694 named_ambiguous_expr!(expr_ret -> Expr, allow_struct, do_parse!(
Gregory Katzfd6935d2016-09-30 22:51:25 -0400695 keyword!("return") >>
David Tolnayaf2557e2016-10-24 11:52:21 -0700696 ret_value: option!(ambiguous_expr!(allow_struct)) >>
David Tolnay055a7042016-10-02 19:23:54 -0700697 (Expr::Ret(ret_value.map(Box::new)))
698 ));
699
700 named!(expr_struct -> Expr, do_parse!(
701 path: path >>
702 punct!("{") >>
703 fields: separated_list!(punct!(","), field_value) >>
704 base: option!(do_parse!(
705 cond!(!fields.is_empty(), punct!(",")) >>
706 punct!("..") >>
707 base: expr >>
708 (base)
709 )) >>
David Tolnayf6c74402016-10-08 02:31:26 -0700710 cond!(!fields.is_empty() && base.is_none(), option!(punct!(","))) >>
David Tolnay055a7042016-10-02 19:23:54 -0700711 punct!("}") >>
712 (Expr::Struct(path, fields, base.map(Box::new)))
713 ));
714
715 named!(field_value -> FieldValue, do_parse!(
716 name: ident >>
717 punct!(":") >>
718 value: expr >>
719 (FieldValue {
720 ident: name,
721 expr: value,
722 })
723 ));
724
725 named!(expr_repeat -> Expr, do_parse!(
726 punct!("[") >>
727 value: expr >>
728 punct!(";") >>
729 times: expr >>
730 punct!("]") >>
731 (Expr::Repeat(Box::new(value), Box::new(times)))
Gregory Katzfd6935d2016-09-30 22:51:25 -0400732 ));
733
David Tolnay42602292016-10-01 22:25:45 -0700734 named!(expr_block -> Expr, do_parse!(
David Tolnay939766a2016-09-23 23:48:12 -0700735 rules: block_check_mode >>
David Tolnay42602292016-10-01 22:25:45 -0700736 b: block >>
David Tolnay89e05672016-10-02 14:39:42 -0700737 (Expr::Block(rules, Block {
David Tolnay42602292016-10-01 22:25:45 -0700738 stmts: b.stmts,
David Tolnay89e05672016-10-02 14:39:42 -0700739 }))
740 ));
741
David Tolnayaf2557e2016-10-24 11:52:21 -0700742 named_ambiguous_expr!(expr_range -> Expr, allow_struct, do_parse!(
David Tolnay438c9052016-10-07 23:24:48 -0700743 limits: range_limits >>
David Tolnayaf2557e2016-10-24 11:52:21 -0700744 hi: option!(ambiguous_expr!(allow_struct)) >>
David Tolnay438c9052016-10-07 23:24:48 -0700745 (Expr::Range(None, hi.map(Box::new), limits))
746 ));
747
748 named!(range_limits -> RangeLimits, alt!(
749 punct!("...") => { |_| RangeLimits::Closed }
750 |
751 punct!("..") => { |_| RangeLimits::HalfOpen }
752 ));
753
David Tolnay9636c052016-10-02 17:11:17 -0700754 named!(expr_path -> Expr, map!(qpath, |(qself, path)| Expr::Path(qself, path)));
David Tolnay42602292016-10-01 22:25:45 -0700755
David Tolnayaf2557e2016-10-24 11:52:21 -0700756 named_ambiguous_expr!(expr_addr_of -> Expr, allow_struct, do_parse!(
David Tolnay3c2467c2016-10-02 17:55:08 -0700757 punct!("&") >>
758 mutability: mutability >>
David Tolnayaf2557e2016-10-24 11:52:21 -0700759 expr: ambiguous_expr!(allow_struct) >>
David Tolnay3c2467c2016-10-02 17:55:08 -0700760 (Expr::AddrOf(mutability, Box::new(expr)))
761 ));
762
David Tolnayaf2557e2016-10-24 11:52:21 -0700763 named_ambiguous_expr!(and_assign -> Expr, allow_struct, preceded!(
764 punct!("="),
765 ambiguous_expr!(allow_struct)
766 ));
David Tolnay438c9052016-10-07 23:24:48 -0700767
David Tolnayaf2557e2016-10-24 11:52:21 -0700768 named_ambiguous_expr!(and_assign_op -> (BinOp, Expr), allow_struct, tuple!(
769 assign_op,
770 ambiguous_expr!(allow_struct)
771 ));
David Tolnay438c9052016-10-07 23:24:48 -0700772
773 named!(and_field -> Ident, preceded!(punct!("."), ident));
774
775 named!(and_tup_field -> u64, preceded!(punct!("."), digits));
776
777 named!(and_index -> Expr, delimited!(punct!("["), expr, punct!("]")));
778
David Tolnayaf2557e2016-10-24 11:52:21 -0700779 named_ambiguous_expr!(and_range -> (RangeLimits, Option<Expr>), allow_struct, tuple!(
780 range_limits,
David Tolnay54e854d2016-10-24 12:03:30 -0700781 option!(call!(ambiguous_expr, allow_struct, false))
David Tolnayaf2557e2016-10-24 11:52:21 -0700782 ));
David Tolnay438c9052016-10-07 23:24:48 -0700783
David Tolnay42602292016-10-01 22:25:45 -0700784 named!(pub block -> Block, do_parse!(
David Tolnay939766a2016-09-23 23:48:12 -0700785 punct!("{") >>
786 stmts: within_block >>
787 punct!("}") >>
788 (Block {
789 stmts: stmts,
David Tolnay939766a2016-09-23 23:48:12 -0700790 })
791 ));
792
793 named!(block_check_mode -> BlockCheckMode, alt!(
David Tolnay10413f02016-09-30 09:12:02 -0700794 keyword!("unsafe") => { |_| BlockCheckMode::Unsafe }
David Tolnay939766a2016-09-23 23:48:12 -0700795 |
796 epsilon!() => { |_| BlockCheckMode::Default }
797 ));
798
799 named!(within_block -> Vec<Stmt>, do_parse!(
David Tolnaycfe55022016-10-02 22:02:27 -0700800 many0!(punct!(";")) >>
801 mut standalone: many0!(terminated!(standalone_stmt, many0!(punct!(";")))) >>
David Tolnay939766a2016-09-23 23:48:12 -0700802 last: option!(expr) >>
803 (match last {
David Tolnaycfe55022016-10-02 22:02:27 -0700804 None => standalone,
David Tolnay939766a2016-09-23 23:48:12 -0700805 Some(last) => {
David Tolnaycfe55022016-10-02 22:02:27 -0700806 standalone.push(Stmt::Expr(Box::new(last)));
807 standalone
David Tolnay939766a2016-09-23 23:48:12 -0700808 }
809 })
810 ));
811
812 named!(standalone_stmt -> Stmt, alt!(
David Tolnay13b3d352016-10-03 00:31:15 -0700813 stmt_mac
814 |
David Tolnay191e0582016-10-02 18:31:09 -0700815 stmt_local
816 |
817 stmt_item
818 |
David Tolnaycfe55022016-10-02 22:02:27 -0700819 stmt_expr
David Tolnay939766a2016-09-23 23:48:12 -0700820 ));
821
David Tolnay13b3d352016-10-03 00:31:15 -0700822 named!(stmt_mac -> Stmt, do_parse!(
823 attrs: many0!(outer_attr) >>
David Tolnayeea28d62016-10-25 20:44:08 -0700824 name: ident >>
825 punct!("!") >>
826 // Only parse braces here; paren and bracket will get parsed as
827 // expression statements
828 punct!("{") >>
829 tts: token_trees >>
830 punct!("}") >>
831 (Stmt::Mac(Box::new((
832 Mac {
833 path: name.into(),
834 tts: vec![TokenTree::Delimited(Delimited {
835 delim: DelimToken::Brace,
836 tts: tts,
837 })],
838 },
839 MacStmtStyle::Braces,
840 attrs,
841 ))))
David Tolnay13b3d352016-10-03 00:31:15 -0700842 ));
843
David Tolnay191e0582016-10-02 18:31:09 -0700844 named!(stmt_local -> Stmt, do_parse!(
845 attrs: many0!(outer_attr) >>
846 keyword!("let") >>
847 pat: pat >>
848 ty: option!(preceded!(punct!(":"), ty)) >>
849 init: option!(preceded!(punct!("="), expr)) >>
850 punct!(";") >>
851 (Stmt::Local(Box::new(Local {
852 pat: Box::new(pat),
853 ty: ty.map(Box::new),
854 init: init.map(Box::new),
855 attrs: attrs,
856 })))
857 ));
858
859 named!(stmt_item -> Stmt, map!(item, |i| Stmt::Item(Box::new(i))));
860
David Tolnaycfe55022016-10-02 22:02:27 -0700861 fn requires_semi(e: &Expr) -> bool {
862 match *e {
David Tolnaycfe55022016-10-02 22:02:27 -0700863 Expr::If(_, _, _) |
864 Expr::IfLet(_, _, _, _) |
865 Expr::While(_, _, _) |
866 Expr::WhileLet(_, _, _, _) |
867 Expr::ForLoop(_, _, _, _) |
868 Expr::Loop(_, _) |
869 Expr::Match(_, _) |
870 Expr::Block(_, _) => false,
871
872 _ => true,
873 }
874 }
875
876 named!(stmt_expr -> Stmt, do_parse!(
David Tolnay939766a2016-09-23 23:48:12 -0700877 e: expr >>
David Tolnaycfe55022016-10-02 22:02:27 -0700878 semi: option!(punct!(";")) >>
879 (if semi.is_some() {
880 Stmt::Semi(Box::new(e))
881 } else if requires_semi(&e) {
882 return Error;
883 } else {
884 Stmt::Expr(Box::new(e))
885 })
David Tolnay939766a2016-09-23 23:48:12 -0700886 ));
David Tolnay8b07f372016-09-30 10:28:40 -0700887
David Tolnay42602292016-10-01 22:25:45 -0700888 named!(pub pat -> Pat, alt!(
David Tolnayfbb73232016-10-03 01:00:06 -0700889 pat_wild // must be before pat_ident
890 |
891 pat_box // must be before pat_ident
David Tolnayb4ad3b52016-10-01 21:58:13 -0700892 |
David Tolnay8b308c22016-10-03 01:24:10 -0700893 pat_range // must be before pat_lit
894 |
David Tolnayaa610942016-10-03 22:22:49 -0700895 pat_tuple_struct // must be before pat_ident
896 |
David Tolnay8d9e81a2016-10-03 22:36:32 -0700897 pat_struct // must be before pat_ident
898 |
David Tolnayaa610942016-10-03 22:22:49 -0700899 pat_mac // must be before pat_ident
900 |
David Tolnaybcdbdd02016-10-24 23:05:02 -0700901 pat_lit // must be before pat_ident
902 |
David Tolnay8b308c22016-10-03 01:24:10 -0700903 pat_ident // must be before pat_path
David Tolnay9636c052016-10-02 17:11:17 -0700904 |
905 pat_path
David Tolnayfbb73232016-10-03 01:00:06 -0700906 |
907 pat_tuple
David Tolnayffdb97f2016-10-03 01:28:33 -0700908 |
909 pat_ref
David Tolnaydaaf7742016-10-03 11:11:43 -0700910 // TODO: Vec
David Tolnayb4ad3b52016-10-01 21:58:13 -0700911 ));
912
David Tolnay84aa0752016-10-02 23:01:13 -0700913 named!(pat_mac -> Pat, map!(mac, Pat::Mac));
914
David Tolnayb4ad3b52016-10-01 21:58:13 -0700915 named!(pat_wild -> Pat, map!(keyword!("_"), |_| Pat::Wild));
916
David Tolnayfbb73232016-10-03 01:00:06 -0700917 named!(pat_box -> Pat, do_parse!(
918 keyword!("box") >>
919 pat: pat >>
920 (Pat::Box(Box::new(pat)))
921 ));
922
David Tolnayb4ad3b52016-10-01 21:58:13 -0700923 named!(pat_ident -> Pat, do_parse!(
924 mode: option!(keyword!("ref")) >>
925 mutability: mutability >>
David Tolnay8d4d2fa2016-10-25 22:08:07 -0700926 name: alt!(
927 ident
928 |
929 keyword!("self") => { Into::into }
930 ) >>
David Tolnay8b308c22016-10-03 01:24:10 -0700931 not!(peek!(punct!("<"))) >>
932 not!(peek!(punct!("::"))) >>
David Tolnayb4ad3b52016-10-01 21:58:13 -0700933 subpat: option!(preceded!(punct!("@"), pat)) >>
934 (Pat::Ident(
935 if mode.is_some() {
936 BindingMode::ByRef(mutability)
937 } else {
938 BindingMode::ByValue(mutability)
939 },
940 name,
941 subpat.map(Box::new),
942 ))
943 ));
944
David Tolnayaa610942016-10-03 22:22:49 -0700945 named!(pat_tuple_struct -> Pat, do_parse!(
946 path: path >>
947 tuple: pat_tuple_helper >>
948 (Pat::TupleStruct(path, tuple.0, tuple.1))
949 ));
950
David Tolnay8d9e81a2016-10-03 22:36:32 -0700951 named!(pat_struct -> Pat, do_parse!(
952 path: path >>
953 punct!("{") >>
954 fields: separated_list!(punct!(","), field_pat) >>
955 more: option!(preceded!(
956 cond!(!fields.is_empty(), punct!(",")),
957 punct!("..")
958 )) >>
David Tolnayff46fd22016-10-08 13:53:28 -0700959 cond!(!fields.is_empty() && more.is_none(), option!(punct!(","))) >>
David Tolnay8d9e81a2016-10-03 22:36:32 -0700960 punct!("}") >>
961 (Pat::Struct(path, fields, more.is_some()))
962 ));
963
964 named!(field_pat -> FieldPat, alt!(
965 do_parse!(
966 ident: ident >>
967 punct!(":") >>
968 pat: pat >>
969 (FieldPat {
970 ident: ident,
971 pat: Box::new(pat),
972 is_shorthand: false,
973 })
974 )
975 |
976 do_parse!(
977 mode: option!(keyword!("ref")) >>
978 mutability: mutability >>
979 ident: ident >>
980 (FieldPat {
981 ident: ident.clone(),
982 pat: Box::new(Pat::Ident(
983 if mode.is_some() {
984 BindingMode::ByRef(mutability)
985 } else {
986 BindingMode::ByValue(mutability)
987 },
988 ident,
989 None,
990 )),
991 is_shorthand: true,
992 })
993 )
994 ));
995
David Tolnay9636c052016-10-02 17:11:17 -0700996 named!(pat_path -> Pat, map!(qpath, |(qself, path)| Pat::Path(qself, path)));
997
David Tolnayaa610942016-10-03 22:22:49 -0700998 named!(pat_tuple -> Pat, map!(
999 pat_tuple_helper,
1000 |(pats, dotdot)| Pat::Tuple(pats, dotdot)
1001 ));
1002
1003 named!(pat_tuple_helper -> (Vec<Pat>, Option<usize>), do_parse!(
David Tolnayfbb73232016-10-03 01:00:06 -07001004 punct!("(") >>
1005 mut elems: separated_list!(punct!(","), pat) >>
1006 dotdot: option!(do_parse!(
1007 cond!(!elems.is_empty(), punct!(",")) >>
1008 punct!("..") >>
1009 rest: many0!(preceded!(punct!(","), pat)) >>
1010 cond!(!rest.is_empty(), option!(punct!(","))) >>
1011 (rest)
1012 )) >>
1013 cond!(!elems.is_empty() && dotdot.is_none(), option!(punct!(","))) >>
1014 punct!(")") >>
1015 (match dotdot {
1016 Some(rest) => {
1017 let pos = elems.len();
1018 elems.extend(rest);
David Tolnayaa610942016-10-03 22:22:49 -07001019 (elems, Some(pos))
David Tolnayfbb73232016-10-03 01:00:06 -07001020 }
David Tolnayaa610942016-10-03 22:22:49 -07001021 None => (elems, None),
David Tolnayfbb73232016-10-03 01:00:06 -07001022 })
1023 ));
1024
David Tolnayffdb97f2016-10-03 01:28:33 -07001025 named!(pat_ref -> Pat, do_parse!(
1026 punct!("&") >>
1027 mutability: mutability >>
1028 pat: pat >>
1029 (Pat::Ref(Box::new(pat), mutability))
1030 ));
1031
David Tolnay8b308c22016-10-03 01:24:10 -07001032 named!(pat_lit -> Pat, map!(lit, |lit| Pat::Lit(Box::new(lit))));
1033
1034 named!(pat_range -> Pat, do_parse!(
1035 lo: lit >>
1036 punct!("...") >>
1037 hi: lit >>
1038 (Pat::Range(Box::new(lo), Box::new(hi)))
1039 ));
1040
David Tolnay89e05672016-10-02 14:39:42 -07001041 named!(capture_by -> CaptureBy, alt!(
1042 keyword!("move") => { |_| CaptureBy::Value }
1043 |
1044 epsilon!() => { |_| CaptureBy::Ref }
1045 ));
1046
David Tolnay8b07f372016-09-30 10:28:40 -07001047 named!(label -> Ident, map!(lifetime, |lt: Lifetime| lt.ident));
David Tolnayb9c8e322016-09-23 20:48:37 -07001048}
1049
David Tolnayf4bbbd92016-09-23 14:41:55 -07001050#[cfg(feature = "printing")]
1051mod printing {
1052 use super::*;
David Tolnayca085422016-10-04 00:12:38 -07001053 use {FnArg, FunctionRetTy, Mutability, Ty};
David Tolnay13b3d352016-10-03 00:31:15 -07001054 use attr::FilterAttrs;
David Tolnayf4bbbd92016-09-23 14:41:55 -07001055 use quote::{Tokens, ToTokens};
1056
1057 impl ToTokens for Expr {
1058 fn to_tokens(&self, tokens: &mut Tokens) {
1059 match *self {
David Tolnaybb6feae2016-10-02 21:25:20 -07001060 Expr::Box(ref inner) => {
1061 tokens.append("box");
1062 inner.to_tokens(tokens);
1063 }
1064 Expr::Vec(ref tys) => {
1065 tokens.append("[");
1066 tokens.append_separated(tys, ",");
1067 tokens.append("]");
1068 }
David Tolnay9636c052016-10-02 17:11:17 -07001069 Expr::Call(ref func, ref args) => {
1070 func.to_tokens(tokens);
1071 tokens.append("(");
1072 tokens.append_separated(args, ",");
1073 tokens.append(")");
1074 }
1075 Expr::MethodCall(ref ident, ref ascript, ref args) => {
1076 args[0].to_tokens(tokens);
1077 tokens.append(".");
1078 ident.to_tokens(tokens);
David Tolnay58f6f672016-10-19 08:44:25 -07001079 if !ascript.is_empty() {
David Tolnay9636c052016-10-02 17:11:17 -07001080 tokens.append("::");
1081 tokens.append("<");
1082 tokens.append_separated(ascript, ",");
1083 tokens.append(">");
1084 }
1085 tokens.append("(");
1086 tokens.append_separated(&args[1..], ",");
1087 tokens.append(")");
1088 }
David Tolnay47a877c2016-10-01 16:50:55 -07001089 Expr::Tup(ref fields) => {
1090 tokens.append("(");
1091 tokens.append_separated(fields, ",");
1092 if fields.len() == 1 {
1093 tokens.append(",");
1094 }
1095 tokens.append(")");
1096 }
David Tolnay89e05672016-10-02 14:39:42 -07001097 Expr::Binary(op, ref left, ref right) => {
1098 left.to_tokens(tokens);
1099 op.to_tokens(tokens);
1100 right.to_tokens(tokens);
1101 }
David Tolnay3c2467c2016-10-02 17:55:08 -07001102 Expr::Unary(op, ref expr) => {
1103 op.to_tokens(tokens);
1104 expr.to_tokens(tokens);
1105 }
David Tolnayf4bbbd92016-09-23 14:41:55 -07001106 Expr::Lit(ref lit) => lit.to_tokens(tokens),
David Tolnay3c2467c2016-10-02 17:55:08 -07001107 Expr::Cast(ref expr, ref ty) => {
1108 expr.to_tokens(tokens);
1109 tokens.append("as");
1110 ty.to_tokens(tokens);
1111 }
1112 Expr::Type(ref expr, ref ty) => {
1113 expr.to_tokens(tokens);
1114 tokens.append(":");
1115 ty.to_tokens(tokens);
1116 }
1117 Expr::If(ref cond, ref then_block, ref else_block) => {
1118 tokens.append("if");
1119 cond.to_tokens(tokens);
1120 then_block.to_tokens(tokens);
1121 if let Some(ref else_block) = *else_block {
1122 tokens.append("else");
1123 else_block.to_tokens(tokens);
1124 }
1125 }
David Tolnay29f9ce12016-10-02 20:58:40 -07001126 Expr::IfLet(ref pat, ref expr, ref then_block, ref else_block) => {
1127 tokens.append("if");
1128 tokens.append("let");
1129 pat.to_tokens(tokens);
1130 tokens.append("=");
1131 expr.to_tokens(tokens);
1132 then_block.to_tokens(tokens);
1133 if let Some(ref else_block) = *else_block {
1134 tokens.append("else");
1135 else_block.to_tokens(tokens);
1136 }
1137 }
David Tolnaybb6feae2016-10-02 21:25:20 -07001138 Expr::While(ref cond, ref body, ref label) => {
1139 if let Some(ref label) = *label {
1140 label.to_tokens(tokens);
1141 tokens.append(":");
1142 }
1143 tokens.append("while");
1144 cond.to_tokens(tokens);
1145 body.to_tokens(tokens);
1146 }
1147 Expr::WhileLet(ref pat, ref expr, ref body, ref label) => {
1148 if let Some(ref label) = *label {
1149 label.to_tokens(tokens);
1150 tokens.append(":");
1151 }
1152 tokens.append("while");
1153 tokens.append("let");
1154 pat.to_tokens(tokens);
1155 tokens.append("=");
1156 expr.to_tokens(tokens);
1157 body.to_tokens(tokens);
1158 }
1159 Expr::ForLoop(ref pat, ref expr, ref body, ref label) => {
1160 if let Some(ref label) = *label {
1161 label.to_tokens(tokens);
1162 tokens.append(":");
1163 }
1164 tokens.append("for");
1165 pat.to_tokens(tokens);
1166 tokens.append("in");
1167 expr.to_tokens(tokens);
1168 body.to_tokens(tokens);
1169 }
1170 Expr::Loop(ref body, ref label) => {
1171 if let Some(ref label) = *label {
1172 label.to_tokens(tokens);
1173 tokens.append(":");
1174 }
1175 tokens.append("loop");
1176 body.to_tokens(tokens);
1177 }
David Tolnayb4ad3b52016-10-01 21:58:13 -07001178 Expr::Match(ref expr, ref arms) => {
1179 tokens.append("match");
1180 expr.to_tokens(tokens);
1181 tokens.append("{");
David Tolnay2165b042016-10-08 00:04:23 -07001182 tokens.append_all(arms);
David Tolnayb4ad3b52016-10-01 21:58:13 -07001183 tokens.append("}");
1184 }
David Tolnay89e05672016-10-02 14:39:42 -07001185 Expr::Closure(capture, ref decl, ref body) => {
1186 capture.to_tokens(tokens);
1187 tokens.append("|");
1188 for (i, input) in decl.inputs.iter().enumerate() {
1189 if i > 0 {
1190 tokens.append(",");
1191 }
David Tolnayca085422016-10-04 00:12:38 -07001192 match *input {
1193 FnArg::Captured(ref pat, Ty::Infer) => {
1194 pat.to_tokens(tokens);
David Tolnaydaaf7742016-10-03 11:11:43 -07001195 }
David Tolnayca085422016-10-04 00:12:38 -07001196 _ => input.to_tokens(tokens),
David Tolnay89e05672016-10-02 14:39:42 -07001197 }
1198 }
1199 tokens.append("|");
1200 match decl.output {
1201 FunctionRetTy::Default => {
1202 if body.stmts.len() == 1 {
1203 if let Stmt::Expr(ref expr) = body.stmts[0] {
1204 expr.to_tokens(tokens);
1205 } else {
1206 body.to_tokens(tokens);
1207 }
1208 } else {
1209 body.to_tokens(tokens);
1210 }
1211 }
1212 FunctionRetTy::Ty(ref ty) => {
1213 tokens.append("->");
1214 ty.to_tokens(tokens);
1215 body.to_tokens(tokens);
1216 }
1217 }
1218 }
1219 Expr::Block(rules, ref block) => {
1220 rules.to_tokens(tokens);
1221 block.to_tokens(tokens);
1222 }
David Tolnaybb6feae2016-10-02 21:25:20 -07001223 Expr::Assign(ref var, ref expr) => {
1224 var.to_tokens(tokens);
1225 tokens.append("=");
1226 expr.to_tokens(tokens);
1227 }
1228 Expr::AssignOp(op, ref var, ref expr) => {
1229 var.to_tokens(tokens);
David Tolnay3cb23a92016-10-07 23:02:21 -07001230 tokens.append(op.assign_op().unwrap());
David Tolnaybb6feae2016-10-02 21:25:20 -07001231 expr.to_tokens(tokens);
1232 }
1233 Expr::Field(ref expr, ref field) => {
1234 expr.to_tokens(tokens);
1235 tokens.append(".");
1236 field.to_tokens(tokens);
1237 }
1238 Expr::TupField(ref expr, field) => {
1239 expr.to_tokens(tokens);
1240 tokens.append(".");
1241 tokens.append(&field.to_string());
1242 }
1243 Expr::Index(ref expr, ref index) => {
1244 expr.to_tokens(tokens);
1245 tokens.append("[");
1246 index.to_tokens(tokens);
1247 tokens.append("]");
1248 }
1249 Expr::Range(ref from, ref to, limits) => {
1250 from.to_tokens(tokens);
1251 match limits {
1252 RangeLimits::HalfOpen => tokens.append(".."),
1253 RangeLimits::Closed => tokens.append("..."),
1254 }
1255 to.to_tokens(tokens);
1256 }
David Tolnay8b308c22016-10-03 01:24:10 -07001257 Expr::Path(None, ref path) => path.to_tokens(tokens),
David Tolnay89e05672016-10-02 14:39:42 -07001258 Expr::Path(Some(ref qself), ref path) => {
1259 tokens.append("<");
1260 qself.ty.to_tokens(tokens);
1261 if qself.position > 0 {
1262 tokens.append("as");
David Tolnaydaaf7742016-10-03 11:11:43 -07001263 for (i, segment) in path.segments
1264 .iter()
1265 .take(qself.position)
1266 .enumerate() {
David Tolnay89e05672016-10-02 14:39:42 -07001267 if i > 0 || path.global {
1268 tokens.append("::");
1269 }
1270 segment.to_tokens(tokens);
1271 }
1272 }
1273 tokens.append(">");
1274 for segment in path.segments.iter().skip(qself.position) {
1275 tokens.append("::");
1276 segment.to_tokens(tokens);
1277 }
1278 }
David Tolnay3c2467c2016-10-02 17:55:08 -07001279 Expr::AddrOf(mutability, ref expr) => {
1280 tokens.append("&");
1281 mutability.to_tokens(tokens);
1282 expr.to_tokens(tokens);
1283 }
1284 Expr::Break(ref opt_label) => {
1285 tokens.append("break");
1286 opt_label.to_tokens(tokens);
1287 }
1288 Expr::Continue(ref opt_label) => {
1289 tokens.append("continue");
1290 opt_label.to_tokens(tokens);
1291 }
David Tolnay42602292016-10-01 22:25:45 -07001292 Expr::Ret(ref opt_expr) => {
1293 tokens.append("return");
1294 opt_expr.to_tokens(tokens);
1295 }
David Tolnaycc3d66e2016-10-02 23:36:05 -07001296 Expr::Mac(ref mac) => mac.to_tokens(tokens),
David Tolnay055a7042016-10-02 19:23:54 -07001297 Expr::Struct(ref path, ref fields, ref base) => {
1298 path.to_tokens(tokens);
1299 tokens.append("{");
1300 tokens.append_separated(fields, ",");
1301 if let Some(ref base) = *base {
1302 if !fields.is_empty() {
1303 tokens.append(",");
1304 }
1305 tokens.append("..");
1306 base.to_tokens(tokens);
1307 }
1308 tokens.append("}");
1309 }
1310 Expr::Repeat(ref expr, ref times) => {
1311 tokens.append("[");
1312 expr.to_tokens(tokens);
1313 tokens.append(";");
1314 times.to_tokens(tokens);
1315 tokens.append("]");
1316 }
David Tolnay89e05672016-10-02 14:39:42 -07001317 Expr::Paren(ref expr) => {
1318 tokens.append("(");
1319 expr.to_tokens(tokens);
1320 tokens.append(")");
1321 }
David Tolnay3c2467c2016-10-02 17:55:08 -07001322 Expr::Try(ref expr) => {
1323 expr.to_tokens(tokens);
1324 tokens.append("?");
1325 }
David Tolnayf4bbbd92016-09-23 14:41:55 -07001326 }
1327 }
1328 }
David Tolnayb4ad3b52016-10-01 21:58:13 -07001329
David Tolnay055a7042016-10-02 19:23:54 -07001330 impl ToTokens for FieldValue {
1331 fn to_tokens(&self, tokens: &mut Tokens) {
1332 self.ident.to_tokens(tokens);
1333 tokens.append(":");
1334 self.expr.to_tokens(tokens);
1335 }
1336 }
1337
David Tolnayb4ad3b52016-10-01 21:58:13 -07001338 impl ToTokens for Arm {
1339 fn to_tokens(&self, tokens: &mut Tokens) {
1340 for attr in &self.attrs {
1341 attr.to_tokens(tokens);
1342 }
1343 tokens.append_separated(&self.pats, "|");
1344 if let Some(ref guard) = self.guard {
1345 tokens.append("if");
1346 guard.to_tokens(tokens);
1347 }
1348 tokens.append("=>");
1349 self.body.to_tokens(tokens);
1350 match *self.body {
David Tolnay1978c672016-10-27 22:05:52 -07001351 Expr::Block(BlockCheckMode::Default, _) => {
David Tolnaydaaf7742016-10-03 11:11:43 -07001352 // no comma
1353 }
David Tolnayb4ad3b52016-10-01 21:58:13 -07001354 _ => tokens.append(","),
1355 }
1356 }
1357 }
1358
1359 impl ToTokens for Pat {
1360 fn to_tokens(&self, tokens: &mut Tokens) {
1361 match *self {
1362 Pat::Wild => tokens.append("_"),
1363 Pat::Ident(mode, ref ident, ref subpat) => {
1364 mode.to_tokens(tokens);
1365 ident.to_tokens(tokens);
1366 if let Some(ref subpat) = *subpat {
1367 tokens.append("@");
1368 subpat.to_tokens(tokens);
1369 }
1370 }
David Tolnay8d9e81a2016-10-03 22:36:32 -07001371 Pat::Struct(ref path, ref fields, dots) => {
1372 path.to_tokens(tokens);
1373 tokens.append("{");
1374 tokens.append_separated(fields, ",");
1375 if dots {
1376 if !fields.is_empty() {
1377 tokens.append(",");
1378 }
1379 tokens.append("..");
1380 }
1381 tokens.append("}");
1382 }
David Tolnayaa610942016-10-03 22:22:49 -07001383 Pat::TupleStruct(ref path, ref pats, dotpos) => {
1384 path.to_tokens(tokens);
1385 tokens.append("(");
1386 match dotpos {
1387 Some(pos) => {
1388 if pos > 0 {
1389 tokens.append_separated(&pats[..pos], ",");
1390 tokens.append(",");
1391 }
1392 tokens.append("..");
1393 if pos < pats.len() {
1394 tokens.append(",");
1395 tokens.append_separated(&pats[pos..], ",");
1396 }
1397 }
1398 None => tokens.append_separated(pats, ","),
1399 }
1400 tokens.append(")");
1401 }
David Tolnay8b308c22016-10-03 01:24:10 -07001402 Pat::Path(None, ref path) => path.to_tokens(tokens),
1403 Pat::Path(Some(ref qself), ref path) => {
1404 tokens.append("<");
1405 qself.ty.to_tokens(tokens);
1406 if qself.position > 0 {
1407 tokens.append("as");
David Tolnaydaaf7742016-10-03 11:11:43 -07001408 for (i, segment) in path.segments
1409 .iter()
1410 .take(qself.position)
1411 .enumerate() {
David Tolnay8b308c22016-10-03 01:24:10 -07001412 if i > 0 || path.global {
1413 tokens.append("::");
1414 }
1415 segment.to_tokens(tokens);
1416 }
1417 }
1418 tokens.append(">");
1419 for segment in path.segments.iter().skip(qself.position) {
1420 tokens.append("::");
1421 segment.to_tokens(tokens);
1422 }
1423 }
David Tolnayfbb73232016-10-03 01:00:06 -07001424 Pat::Tuple(ref pats, dotpos) => {
1425 tokens.append("(");
1426 match dotpos {
1427 Some(pos) => {
1428 if pos > 0 {
1429 tokens.append_separated(&pats[..pos], ",");
1430 tokens.append(",");
1431 }
1432 tokens.append("..");
1433 if pos < pats.len() {
1434 tokens.append(",");
1435 tokens.append_separated(&pats[pos..], ",");
1436 }
1437 }
1438 None => tokens.append_separated(pats, ","),
1439 }
1440 tokens.append(")");
1441 }
1442 Pat::Box(ref inner) => {
1443 tokens.append("box");
1444 inner.to_tokens(tokens);
1445 }
David Tolnayffdb97f2016-10-03 01:28:33 -07001446 Pat::Ref(ref target, mutability) => {
1447 tokens.append("&");
1448 mutability.to_tokens(tokens);
1449 target.to_tokens(tokens);
1450 }
David Tolnay8b308c22016-10-03 01:24:10 -07001451 Pat::Lit(ref lit) => lit.to_tokens(tokens),
1452 Pat::Range(ref lo, ref hi) => {
1453 lo.to_tokens(tokens);
1454 tokens.append("...");
1455 hi.to_tokens(tokens);
1456 }
David Tolnay16709ba2016-10-05 23:11:32 -07001457 Pat::Slice(ref _before, ref _dots, ref _after) => unimplemented!(),
David Tolnaycc3d66e2016-10-02 23:36:05 -07001458 Pat::Mac(ref mac) => mac.to_tokens(tokens),
David Tolnayb4ad3b52016-10-01 21:58:13 -07001459 }
1460 }
1461 }
1462
David Tolnay8d9e81a2016-10-03 22:36:32 -07001463 impl ToTokens for FieldPat {
1464 fn to_tokens(&self, tokens: &mut Tokens) {
1465 if !self.is_shorthand {
1466 self.ident.to_tokens(tokens);
1467 tokens.append(":");
1468 }
1469 self.pat.to_tokens(tokens);
1470 }
1471 }
1472
David Tolnayb4ad3b52016-10-01 21:58:13 -07001473 impl ToTokens for BindingMode {
1474 fn to_tokens(&self, tokens: &mut Tokens) {
1475 match *self {
1476 BindingMode::ByRef(Mutability::Immutable) => {
1477 tokens.append("ref");
1478 }
1479 BindingMode::ByRef(Mutability::Mutable) => {
1480 tokens.append("ref");
1481 tokens.append("mut");
1482 }
1483 BindingMode::ByValue(Mutability::Immutable) => {}
1484 BindingMode::ByValue(Mutability::Mutable) => {
1485 tokens.append("mut");
1486 }
1487 }
1488 }
1489 }
David Tolnay42602292016-10-01 22:25:45 -07001490
David Tolnay89e05672016-10-02 14:39:42 -07001491 impl ToTokens for CaptureBy {
1492 fn to_tokens(&self, tokens: &mut Tokens) {
1493 match *self {
1494 CaptureBy::Value => tokens.append("move"),
David Tolnaydaaf7742016-10-03 11:11:43 -07001495 CaptureBy::Ref => {
1496 // nothing
1497 }
David Tolnay89e05672016-10-02 14:39:42 -07001498 }
1499 }
1500 }
1501
David Tolnay42602292016-10-01 22:25:45 -07001502 impl ToTokens for Block {
1503 fn to_tokens(&self, tokens: &mut Tokens) {
David Tolnay42602292016-10-01 22:25:45 -07001504 tokens.append("{");
1505 for stmt in &self.stmts {
1506 stmt.to_tokens(tokens);
1507 }
1508 tokens.append("}");
1509 }
1510 }
1511
1512 impl ToTokens for BlockCheckMode {
1513 fn to_tokens(&self, tokens: &mut Tokens) {
1514 match *self {
David Tolnaydaaf7742016-10-03 11:11:43 -07001515 BlockCheckMode::Default => {
1516 // nothing
1517 }
David Tolnay42602292016-10-01 22:25:45 -07001518 BlockCheckMode::Unsafe => tokens.append("unsafe"),
1519 }
1520 }
1521 }
1522
1523 impl ToTokens for Stmt {
1524 fn to_tokens(&self, tokens: &mut Tokens) {
1525 match *self {
David Tolnay191e0582016-10-02 18:31:09 -07001526 Stmt::Local(ref local) => local.to_tokens(tokens),
David Tolnay42602292016-10-01 22:25:45 -07001527 Stmt::Item(ref item) => item.to_tokens(tokens),
1528 Stmt::Expr(ref expr) => expr.to_tokens(tokens),
1529 Stmt::Semi(ref expr) => {
1530 expr.to_tokens(tokens);
1531 tokens.append(";");
1532 }
David Tolnay13b3d352016-10-03 00:31:15 -07001533 Stmt::Mac(ref mac) => {
1534 let (ref mac, style, ref attrs) = **mac;
1535 for attr in attrs.outer() {
1536 attr.to_tokens(tokens);
1537 }
1538 mac.to_tokens(tokens);
1539 match style {
1540 MacStmtStyle::Semicolon => tokens.append(";"),
David Tolnaydaaf7742016-10-03 11:11:43 -07001541 MacStmtStyle::Braces | MacStmtStyle::NoBraces => {
1542 // no semicolon
1543 }
David Tolnay13b3d352016-10-03 00:31:15 -07001544 }
1545 }
David Tolnay42602292016-10-01 22:25:45 -07001546 }
1547 }
1548 }
David Tolnay191e0582016-10-02 18:31:09 -07001549
1550 impl ToTokens for Local {
1551 fn to_tokens(&self, tokens: &mut Tokens) {
1552 tokens.append("let");
1553 self.pat.to_tokens(tokens);
1554 if let Some(ref ty) = self.ty {
1555 tokens.append(":");
1556 ty.to_tokens(tokens);
1557 }
1558 if let Some(ref init) = self.init {
1559 tokens.append("=");
1560 init.to_tokens(tokens);
1561 }
1562 tokens.append(";");
1563 }
1564 }
David Tolnayf4bbbd92016-09-23 14:41:55 -07001565}