blob: fa7cdf7d4a6d53837c8161935fb13b238cfcec25 [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)]
192pub enum Pat {
193 /// Represents a wildcard pattern (`_`)
194 Wild,
195
David Tolnay432afc02016-09-24 07:37:13 -0700196 /// A `Pat::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
David Tolnayf4bbbd92016-09-23 14:41:55 -0700197 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
198 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
199 /// during name resolution.
200 Ident(BindingMode, Ident, Option<Box<Pat>>),
201
202 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
203 /// The `bool` is `true` in the presence of a `..`.
204 Struct(Path, Vec<FieldPat>, bool),
205
206 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
207 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
208 /// 0 <= position <= subpats.len()
209 TupleStruct(Path, Vec<Pat>, Option<usize>),
210
211 /// A possibly qualified path pattern.
212 /// Unquailfied path patterns `A::B::C` can legally refer to variants, structs, constants
213 /// or associated constants. Quailfied path patterns `<A>::B::C`/`<A as Trait>::B::C` can
214 /// only legally refer to associated constants.
215 Path(Option<QSelf>, Path),
216
217 /// A tuple pattern `(a, b)`.
218 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
219 /// 0 <= position <= subpats.len()
220 Tuple(Vec<Pat>, Option<usize>),
221 /// A `box` pattern
222 Box(Box<Pat>),
223 /// A reference pattern, e.g. `&mut (a, b)`
224 Ref(Box<Pat>, Mutability),
225 /// A literal
David Tolnay8b308c22016-10-03 01:24:10 -0700226 Lit(Box<Lit>),
David Tolnayf4bbbd92016-09-23 14:41:55 -0700227 /// A range pattern, e.g. `1...2`
David Tolnay8b308c22016-10-03 01:24:10 -0700228 Range(Box<Lit>, Box<Lit>),
David Tolnayf4bbbd92016-09-23 14:41:55 -0700229 /// `[a, b, ..i, y, z]` is represented as:
David Tolnay16709ba2016-10-05 23:11:32 -0700230 /// `Pat::Slice(box [a, b], Some(i), box [y, z])`
231 Slice(Vec<Pat>, Option<Box<Pat>>, Vec<Pat>),
David Tolnayf4bbbd92016-09-23 14:41:55 -0700232 /// A macro pattern; pre-expansion
233 Mac(Mac),
234}
235
David Tolnay771ecf42016-09-23 19:26:37 -0700236/// An arm of a 'match'.
237///
238/// E.g. `0...10 => { println!("match!") }` as in
239///
240/// ```rust,ignore
241/// match n {
242/// 0...10 => { println!("match!") },
243/// // ..
244/// }
245/// ```
David Tolnayf4bbbd92016-09-23 14:41:55 -0700246#[derive(Debug, Clone, Eq, PartialEq)]
247pub struct Arm {
248 pub attrs: Vec<Attribute>,
249 pub pats: Vec<Pat>,
250 pub guard: Option<Box<Expr>>,
251 pub body: Box<Expr>,
252}
253
254/// A capture clause
255#[derive(Debug, Copy, Clone, Eq, PartialEq)]
256pub enum CaptureBy {
257 Value,
258 Ref,
259}
260
261/// Limit types of a range (inclusive or exclusive)
262#[derive(Debug, Copy, Clone, Eq, PartialEq)]
263pub enum RangeLimits {
264 /// Inclusive at the beginning, exclusive at the end
265 HalfOpen,
266 /// Inclusive at the beginning and end
267 Closed,
268}
269
270/// A single field in a struct pattern
271///
272/// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
David Tolnay181bac52016-09-24 00:10:05 -0700273/// are treated the same as `x: x, y: ref y, z: ref mut z`,
David Tolnayaed77b02016-09-23 20:50:31 -0700274/// except `is_shorthand` is true
David Tolnayf4bbbd92016-09-23 14:41:55 -0700275#[derive(Debug, Clone, Eq, PartialEq)]
276pub struct FieldPat {
277 /// The identifier for the field
278 pub ident: Ident,
279 /// The pattern the field is destructured to
280 pub pat: Box<Pat>,
281 pub is_shorthand: bool,
282}
283
284#[derive(Debug, Copy, Clone, Eq, PartialEq)]
285pub enum BindingMode {
286 ByRef(Mutability),
287 ByValue(Mutability),
288}
289
David Tolnayb9c8e322016-09-23 20:48:37 -0700290#[cfg(feature = "parsing")]
291pub mod parsing {
292 use super::*;
David Tolnay3cb23a92016-10-07 23:02:21 -0700293 use {BinOp, Delimited, DelimToken, FnArg, FnDecl, FunctionRetTy, Ident, Lifetime, TokenTree, Ty};
David Tolnayb4ad3b52016-10-01 21:58:13 -0700294 use attr::parsing::outer_attr;
Gregory Katz1b69f682016-09-27 21:06:09 -0400295 use generics::parsing::lifetime;
David Tolnayfa0edf22016-09-23 22:58:24 -0700296 use ident::parsing::ident;
David Tolnay191e0582016-10-02 18:31:09 -0700297 use item::parsing::item;
David Tolnayfa0edf22016-09-23 22:58:24 -0700298 use lit::parsing::lit;
David Tolnay84aa0752016-10-02 23:01:13 -0700299 use mac::parsing::mac;
David Tolnaycfe55022016-10-02 22:02:27 -0700300 use nom::IResult::Error;
David Tolnay3cb23a92016-10-07 23:02:21 -0700301 use op::parsing::{binop, unop};
David Tolnay055a7042016-10-02 19:23:54 -0700302 use ty::parsing::{mutability, path, qpath, ty};
David Tolnayb9c8e322016-09-23 20:48:37 -0700303
David Tolnayfa0edf22016-09-23 22:58:24 -0700304 named!(pub expr -> Expr, do_parse!(
305 mut e: alt!(
David Tolnayfa94b6f2016-10-05 23:26:11 -0700306 expr_lit // must be before expr_struct
David Tolnay055a7042016-10-02 19:23:54 -0700307 |
David Tolnayfa94b6f2016-10-05 23:26:11 -0700308 expr_struct // must be before expr_path
David Tolnay055a7042016-10-02 19:23:54 -0700309 |
David Tolnayfa94b6f2016-10-05 23:26:11 -0700310 expr_paren // must be before expr_tup
311 |
312 expr_mac // must be before expr_path
David Tolnay89e05672016-10-02 14:39:42 -0700313 |
David Tolnay4c9be372016-10-06 00:47:37 -0700314 expr_break // must be before expr_path
315 |
316 expr_continue // must be before expr_path
317 |
318 expr_ret // must be before expr_path
319 |
David Tolnay939766a2016-09-23 23:48:12 -0700320 expr_box
David Tolnayfa0edf22016-09-23 22:58:24 -0700321 |
David Tolnay939766a2016-09-23 23:48:12 -0700322 expr_vec
David Tolnayfa0edf22016-09-23 22:58:24 -0700323 |
David Tolnay939766a2016-09-23 23:48:12 -0700324 expr_tup
David Tolnayfa0edf22016-09-23 22:58:24 -0700325 |
David Tolnay939766a2016-09-23 23:48:12 -0700326 expr_unary
David Tolnayfa0edf22016-09-23 22:58:24 -0700327 |
David Tolnay939766a2016-09-23 23:48:12 -0700328 expr_if
Gregory Katz3e562cc2016-09-28 18:33:02 -0400329 |
330 expr_while
David Tolnaybb6feae2016-10-02 21:25:20 -0700331 |
332 expr_for_loop
Gregory Katze5f35682016-09-27 14:20:55 -0400333 |
334 expr_loop
David Tolnayb4ad3b52016-10-01 21:58:13 -0700335 |
336 expr_match
David Tolnay89e05672016-10-02 14:39:42 -0700337 |
338 expr_closure
David Tolnay939766a2016-09-23 23:48:12 -0700339 |
340 expr_block
David Tolnay89e05672016-10-02 14:39:42 -0700341 |
342 expr_path
David Tolnay3c2467c2016-10-02 17:55:08 -0700343 |
344 expr_addr_of
Gregory Katzfd6935d2016-09-30 22:51:25 -0400345 |
David Tolnay055a7042016-10-02 19:23:54 -0700346 expr_repeat
David Tolnayfa0edf22016-09-23 22:58:24 -0700347 ) >>
348 many0!(alt!(
David Tolnay939766a2016-09-23 23:48:12 -0700349 tap!(args: and_call => {
350 e = Expr::Call(Box::new(e), args);
David Tolnayfa0edf22016-09-23 22:58:24 -0700351 })
352 |
David Tolnay939766a2016-09-23 23:48:12 -0700353 tap!(more: and_method_call => {
354 let (method, ascript, mut args) = more;
David Tolnayfa0edf22016-09-23 22:58:24 -0700355 args.insert(0, e);
356 e = Expr::MethodCall(method, ascript, args);
357 })
358 |
David Tolnay939766a2016-09-23 23:48:12 -0700359 tap!(more: and_binary => {
360 let (op, other) = more;
David Tolnayfa0edf22016-09-23 22:58:24 -0700361 e = Expr::Binary(op, Box::new(e), Box::new(other));
362 })
David Tolnay939766a2016-09-23 23:48:12 -0700363 |
364 tap!(ty: and_cast => {
365 e = Expr::Cast(Box::new(e), Box::new(ty));
366 })
367 |
368 tap!(ty: and_ascription => {
369 e = Expr::Type(Box::new(e), Box::new(ty));
370 })
David Tolnaydaaf7742016-10-03 11:11:43 -0700371 // TODO: Assign
372 // TODO: AssignOp
373 // TODO: Field
374 // TODO: TupField
375 // TODO: Index
376 // TODO: Range
David Tolnay055a7042016-10-02 19:23:54 -0700377 |
378 tap!(_try: punct!("?") => {
379 e = Expr::Try(Box::new(e));
380 })
David Tolnayfa0edf22016-09-23 22:58:24 -0700381 )) >>
382 (e)
David Tolnayb9c8e322016-09-23 20:48:37 -0700383 ));
384
David Tolnay84aa0752016-10-02 23:01:13 -0700385 named!(expr_mac -> Expr, map!(mac, Expr::Mac));
386
David Tolnay89e05672016-10-02 14:39:42 -0700387 named!(expr_paren -> Expr, do_parse!(
388 punct!("(") >>
389 e: expr >>
390 punct!(")") >>
391 (Expr::Paren(Box::new(e)))
392 ));
393
David Tolnay939766a2016-09-23 23:48:12 -0700394 named!(expr_box -> Expr, do_parse!(
David Tolnay10413f02016-09-30 09:12:02 -0700395 keyword!("box") >>
David Tolnayb9c8e322016-09-23 20:48:37 -0700396 inner: expr >>
397 (Expr::Box(Box::new(inner)))
398 ));
David Tolnayfa0edf22016-09-23 22:58:24 -0700399
David Tolnay939766a2016-09-23 23:48:12 -0700400 named!(expr_vec -> Expr, do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700401 punct!("[") >>
402 elems: separated_list!(punct!(","), expr) >>
403 punct!("]") >>
404 (Expr::Vec(elems))
405 ));
406
David Tolnay939766a2016-09-23 23:48:12 -0700407 named!(and_call -> Vec<Expr>, do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700408 punct!("(") >>
409 args: separated_list!(punct!(","), expr) >>
410 punct!(")") >>
411 (args)
412 ));
413
David Tolnay939766a2016-09-23 23:48:12 -0700414 named!(and_method_call -> (Ident, Vec<Ty>, Vec<Expr>), do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700415 punct!(".") >>
416 method: ident >>
417 ascript: opt_vec!(delimited!(
418 punct!("<"),
419 separated_list!(punct!(","), ty),
420 punct!(">")
421 )) >>
422 punct!("(") >>
423 args: separated_list!(punct!(","), expr) >>
424 punct!(")") >>
425 (method, ascript, args)
426 ));
427
David Tolnay939766a2016-09-23 23:48:12 -0700428 named!(expr_tup -> Expr, do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700429 punct!("(") >>
430 elems: separated_list!(punct!(","), expr) >>
David Tolnay89e05672016-10-02 14:39:42 -0700431 option!(punct!(",")) >>
David Tolnayfa0edf22016-09-23 22:58:24 -0700432 punct!(")") >>
433 (Expr::Tup(elems))
434 ));
435
David Tolnay3cb23a92016-10-07 23:02:21 -0700436 named!(and_binary -> (BinOp, Expr), tuple!(binop, expr));
David Tolnayfa0edf22016-09-23 22:58:24 -0700437
David Tolnay939766a2016-09-23 23:48:12 -0700438 named!(expr_unary -> Expr, do_parse!(
David Tolnay3cb23a92016-10-07 23:02:21 -0700439 operator: unop >>
David Tolnayfa0edf22016-09-23 22:58:24 -0700440 operand: expr >>
441 (Expr::Unary(operator, Box::new(operand)))
442 ));
David Tolnay939766a2016-09-23 23:48:12 -0700443
444 named!(expr_lit -> Expr, map!(lit, Expr::Lit));
445
446 named!(and_cast -> Ty, do_parse!(
David Tolnay10413f02016-09-30 09:12:02 -0700447 keyword!("as") >>
David Tolnay939766a2016-09-23 23:48:12 -0700448 ty: ty >>
449 (ty)
450 ));
451
452 named!(and_ascription -> Ty, preceded!(punct!(":"), ty));
453
David Tolnaybb6feae2016-10-02 21:25:20 -0700454 enum Cond {
David Tolnay29f9ce12016-10-02 20:58:40 -0700455 Let(Pat, Expr),
456 Expr(Expr),
457 }
458
David Tolnaybb6feae2016-10-02 21:25:20 -0700459 named!(cond -> Cond, alt!(
460 do_parse!(
461 keyword!("let") >>
462 pat: pat >>
463 punct!("=") >>
464 value: expr >>
465 (Cond::Let(pat, value))
466 )
467 |
468 map!(expr, Cond::Expr)
469 ));
470
David Tolnay939766a2016-09-23 23:48:12 -0700471 named!(expr_if -> Expr, do_parse!(
David Tolnay10413f02016-09-30 09:12:02 -0700472 keyword!("if") >>
David Tolnaybb6feae2016-10-02 21:25:20 -0700473 cond: cond >>
David Tolnay939766a2016-09-23 23:48:12 -0700474 punct!("{") >>
475 then_block: within_block >>
476 punct!("}") >>
477 else_block: option!(preceded!(
David Tolnay10413f02016-09-30 09:12:02 -0700478 keyword!("else"),
David Tolnay939766a2016-09-23 23:48:12 -0700479 alt!(
480 expr_if
481 |
482 do_parse!(
483 punct!("{") >>
484 else_block: within_block >>
485 punct!("}") >>
David Tolnay89e05672016-10-02 14:39:42 -0700486 (Expr::Block(BlockCheckMode::Default, Block {
David Tolnay939766a2016-09-23 23:48:12 -0700487 stmts: else_block,
David Tolnay89e05672016-10-02 14:39:42 -0700488 }))
David Tolnay939766a2016-09-23 23:48:12 -0700489 )
490 )
491 )) >>
David Tolnay29f9ce12016-10-02 20:58:40 -0700492 (match cond {
David Tolnaybb6feae2016-10-02 21:25:20 -0700493 Cond::Let(pat, expr) => Expr::IfLet(
David Tolnay29f9ce12016-10-02 20:58:40 -0700494 Box::new(pat),
495 Box::new(expr),
496 Block {
497 stmts: then_block,
498 },
499 else_block.map(Box::new),
500 ),
David Tolnaybb6feae2016-10-02 21:25:20 -0700501 Cond::Expr(cond) => Expr::If(
David Tolnay29f9ce12016-10-02 20:58:40 -0700502 Box::new(cond),
503 Block {
504 stmts: then_block,
505 },
506 else_block.map(Box::new),
507 ),
508 })
David Tolnay939766a2016-09-23 23:48:12 -0700509 ));
510
David Tolnaybb6feae2016-10-02 21:25:20 -0700511 named!(expr_for_loop -> Expr, do_parse!(
512 lbl: option!(terminated!(label, punct!(":"))) >>
513 keyword!("for") >>
514 pat: pat >>
515 keyword!("in") >>
516 expr: expr >>
517 loop_block: block >>
518 (Expr::ForLoop(Box::new(pat), Box::new(expr), loop_block, lbl))
519 ));
520
Gregory Katze5f35682016-09-27 14:20:55 -0400521 named!(expr_loop -> Expr, do_parse!(
David Tolnay8b07f372016-09-30 10:28:40 -0700522 lbl: option!(terminated!(label, punct!(":"))) >>
David Tolnay10413f02016-09-30 09:12:02 -0700523 keyword!("loop") >>
Gregory Katze5f35682016-09-27 14:20:55 -0400524 loop_block: block >>
David Tolnay89e05672016-10-02 14:39:42 -0700525 (Expr::Loop(loop_block, lbl))
Gregory Katze5f35682016-09-27 14:20:55 -0400526 ));
527
David Tolnayb4ad3b52016-10-01 21:58:13 -0700528 named!(expr_match -> Expr, do_parse!(
529 keyword!("match") >>
530 obj: expr >>
531 punct!("{") >>
532 arms: many0!(do_parse!(
533 attrs: many0!(outer_attr) >>
534 pats: separated_nonempty_list!(punct!("|"), pat) >>
535 guard: option!(preceded!(keyword!("if"), expr)) >>
536 punct!("=>") >>
537 body: alt!(
538 terminated!(expr, punct!(","))
539 |
David Tolnay89e05672016-10-02 14:39:42 -0700540 map!(block, |blk| Expr::Block(BlockCheckMode::Default, blk))
David Tolnayb4ad3b52016-10-01 21:58:13 -0700541 ) >>
542 (Arm {
543 attrs: attrs,
544 pats: pats,
545 guard: guard.map(Box::new),
546 body: Box::new(body),
547 })
548 )) >>
549 punct!("}") >>
550 (Expr::Match(Box::new(obj), arms))
551 ));
552
David Tolnay89e05672016-10-02 14:39:42 -0700553 named!(expr_closure -> Expr, do_parse!(
554 capture: capture_by >>
555 punct!("|") >>
556 inputs: separated_list!(punct!(","), closure_arg) >>
557 punct!("|") >>
558 ret_and_body: alt!(
559 do_parse!(
560 punct!("->") >>
561 ty: ty >>
562 body: block >>
563 ((FunctionRetTy::Ty(ty), body))
564 )
565 |
566 map!(expr, |e| (
567 FunctionRetTy::Default,
568 Block {
569 stmts: vec![Stmt::Expr(Box::new(e))],
570 },
571 ))
572 ) >>
573 (Expr::Closure(
574 capture,
575 Box::new(FnDecl {
576 inputs: inputs,
577 output: ret_and_body.0,
578 }),
579 ret_and_body.1,
580 ))
581 ));
582
583 named!(closure_arg -> FnArg, do_parse!(
584 pat: pat >>
585 ty: option!(preceded!(punct!(":"), ty)) >>
David Tolnayca085422016-10-04 00:12:38 -0700586 (FnArg::Captured(pat, ty.unwrap_or(Ty::Infer)))
David Tolnay89e05672016-10-02 14:39:42 -0700587 ));
588
Gregory Katz3e562cc2016-09-28 18:33:02 -0400589 named!(expr_while -> Expr, do_parse!(
David Tolnay8b07f372016-09-30 10:28:40 -0700590 lbl: option!(terminated!(label, punct!(":"))) >>
David Tolnay57ffbde2016-09-30 09:38:04 -0700591 keyword!("while") >>
David Tolnaybb6feae2016-10-02 21:25:20 -0700592 cond: cond >>
Gregory Katz3e562cc2016-09-28 18:33:02 -0400593 while_block: block >>
David Tolnaybb6feae2016-10-02 21:25:20 -0700594 (match cond {
595 Cond::Let(pat, expr) => Expr::WhileLet(
596 Box::new(pat),
597 Box::new(expr),
598 while_block,
599 lbl,
600 ),
601 Cond::Expr(cond) => Expr::While(
602 Box::new(cond),
603 while_block,
604 lbl,
605 ),
606 })
Gregory Katz3e562cc2016-09-28 18:33:02 -0400607 ));
608
Gregory Katzfd6935d2016-09-30 22:51:25 -0400609 named!(expr_continue -> Expr, do_parse!(
610 keyword!("continue") >>
611 lbl: option!(label) >>
David Tolnay055a7042016-10-02 19:23:54 -0700612 (Expr::Continue(lbl))
Gregory Katzfd6935d2016-09-30 22:51:25 -0400613 ));
614
615 named!(expr_break -> Expr, do_parse!(
616 keyword!("break") >>
617 lbl: option!(label) >>
David Tolnay055a7042016-10-02 19:23:54 -0700618 (Expr::Break(lbl))
Gregory Katzfd6935d2016-09-30 22:51:25 -0400619 ));
620
621 named!(expr_ret -> Expr, do_parse!(
622 keyword!("return") >>
623 ret_value: option!(expr) >>
David Tolnay055a7042016-10-02 19:23:54 -0700624 (Expr::Ret(ret_value.map(Box::new)))
625 ));
626
627 named!(expr_struct -> Expr, do_parse!(
628 path: path >>
629 punct!("{") >>
630 fields: separated_list!(punct!(","), field_value) >>
631 base: option!(do_parse!(
632 cond!(!fields.is_empty(), punct!(",")) >>
633 punct!("..") >>
634 base: expr >>
635 (base)
636 )) >>
637 punct!("}") >>
638 (Expr::Struct(path, fields, base.map(Box::new)))
639 ));
640
641 named!(field_value -> FieldValue, do_parse!(
642 name: ident >>
643 punct!(":") >>
644 value: expr >>
645 (FieldValue {
646 ident: name,
647 expr: value,
648 })
649 ));
650
651 named!(expr_repeat -> Expr, do_parse!(
652 punct!("[") >>
653 value: expr >>
654 punct!(";") >>
655 times: expr >>
656 punct!("]") >>
657 (Expr::Repeat(Box::new(value), Box::new(times)))
Gregory Katzfd6935d2016-09-30 22:51:25 -0400658 ));
659
David Tolnay42602292016-10-01 22:25:45 -0700660 named!(expr_block -> Expr, do_parse!(
David Tolnay939766a2016-09-23 23:48:12 -0700661 rules: block_check_mode >>
David Tolnay42602292016-10-01 22:25:45 -0700662 b: block >>
David Tolnay89e05672016-10-02 14:39:42 -0700663 (Expr::Block(rules, Block {
David Tolnay42602292016-10-01 22:25:45 -0700664 stmts: b.stmts,
David Tolnay89e05672016-10-02 14:39:42 -0700665 }))
666 ));
667
David Tolnay9636c052016-10-02 17:11:17 -0700668 named!(expr_path -> Expr, map!(qpath, |(qself, path)| Expr::Path(qself, path)));
David Tolnay42602292016-10-01 22:25:45 -0700669
David Tolnay3c2467c2016-10-02 17:55:08 -0700670 named!(expr_addr_of -> Expr, do_parse!(
671 punct!("&") >>
672 mutability: mutability >>
673 expr: expr >>
674 (Expr::AddrOf(mutability, Box::new(expr)))
675 ));
676
David Tolnay42602292016-10-01 22:25:45 -0700677 named!(pub block -> Block, do_parse!(
David Tolnay939766a2016-09-23 23:48:12 -0700678 punct!("{") >>
679 stmts: within_block >>
680 punct!("}") >>
681 (Block {
682 stmts: stmts,
David Tolnay939766a2016-09-23 23:48:12 -0700683 })
684 ));
685
686 named!(block_check_mode -> BlockCheckMode, alt!(
David Tolnay10413f02016-09-30 09:12:02 -0700687 keyword!("unsafe") => { |_| BlockCheckMode::Unsafe }
David Tolnay939766a2016-09-23 23:48:12 -0700688 |
689 epsilon!() => { |_| BlockCheckMode::Default }
690 ));
691
692 named!(within_block -> Vec<Stmt>, do_parse!(
David Tolnaycfe55022016-10-02 22:02:27 -0700693 many0!(punct!(";")) >>
694 mut standalone: many0!(terminated!(standalone_stmt, many0!(punct!(";")))) >>
David Tolnay939766a2016-09-23 23:48:12 -0700695 last: option!(expr) >>
696 (match last {
David Tolnaycfe55022016-10-02 22:02:27 -0700697 None => standalone,
David Tolnay939766a2016-09-23 23:48:12 -0700698 Some(last) => {
David Tolnaycfe55022016-10-02 22:02:27 -0700699 standalone.push(Stmt::Expr(Box::new(last)));
700 standalone
David Tolnay939766a2016-09-23 23:48:12 -0700701 }
702 })
703 ));
704
705 named!(standalone_stmt -> Stmt, alt!(
David Tolnay13b3d352016-10-03 00:31:15 -0700706 stmt_mac
707 |
David Tolnay191e0582016-10-02 18:31:09 -0700708 stmt_local
709 |
710 stmt_item
711 |
David Tolnaycfe55022016-10-02 22:02:27 -0700712 stmt_expr
David Tolnay939766a2016-09-23 23:48:12 -0700713 ));
714
David Tolnay13b3d352016-10-03 00:31:15 -0700715 named!(stmt_mac -> Stmt, do_parse!(
716 attrs: many0!(outer_attr) >>
717 mac: mac >>
718 semi: option!(punct!(";")) >>
719 ({
720 let style = if semi.is_some() {
721 MacStmtStyle::Semicolon
722 } else if let Some(&TokenTree::Delimited(Delimited { delim, .. })) = mac.tts.last() {
723 match delim {
724 DelimToken::Paren | DelimToken::Bracket => MacStmtStyle::NoBraces,
725 DelimToken::Brace => MacStmtStyle::Braces,
726 }
727 } else {
728 MacStmtStyle::NoBraces
729 };
730 Stmt::Mac(Box::new((mac, style, attrs)))
731 })
732 ));
733
David Tolnay191e0582016-10-02 18:31:09 -0700734 named!(stmt_local -> Stmt, do_parse!(
735 attrs: many0!(outer_attr) >>
736 keyword!("let") >>
737 pat: pat >>
738 ty: option!(preceded!(punct!(":"), ty)) >>
739 init: option!(preceded!(punct!("="), expr)) >>
740 punct!(";") >>
741 (Stmt::Local(Box::new(Local {
742 pat: Box::new(pat),
743 ty: ty.map(Box::new),
744 init: init.map(Box::new),
745 attrs: attrs,
746 })))
747 ));
748
749 named!(stmt_item -> Stmt, map!(item, |i| Stmt::Item(Box::new(i))));
750
David Tolnaycfe55022016-10-02 22:02:27 -0700751 fn requires_semi(e: &Expr) -> bool {
752 match *e {
David Tolnaycfe55022016-10-02 22:02:27 -0700753 Expr::If(_, _, _) |
754 Expr::IfLet(_, _, _, _) |
755 Expr::While(_, _, _) |
756 Expr::WhileLet(_, _, _, _) |
757 Expr::ForLoop(_, _, _, _) |
758 Expr::Loop(_, _) |
759 Expr::Match(_, _) |
760 Expr::Block(_, _) => false,
761
762 _ => true,
763 }
764 }
765
766 named!(stmt_expr -> Stmt, do_parse!(
David Tolnay939766a2016-09-23 23:48:12 -0700767 e: expr >>
David Tolnaycfe55022016-10-02 22:02:27 -0700768 semi: option!(punct!(";")) >>
769 (if semi.is_some() {
770 Stmt::Semi(Box::new(e))
771 } else if requires_semi(&e) {
772 return Error;
773 } else {
774 Stmt::Expr(Box::new(e))
775 })
David Tolnay939766a2016-09-23 23:48:12 -0700776 ));
David Tolnay8b07f372016-09-30 10:28:40 -0700777
David Tolnay42602292016-10-01 22:25:45 -0700778 named!(pub pat -> Pat, alt!(
David Tolnayfbb73232016-10-03 01:00:06 -0700779 pat_wild // must be before pat_ident
780 |
781 pat_box // must be before pat_ident
David Tolnayb4ad3b52016-10-01 21:58:13 -0700782 |
David Tolnay8b308c22016-10-03 01:24:10 -0700783 pat_range // must be before pat_lit
784 |
David Tolnayaa610942016-10-03 22:22:49 -0700785 pat_tuple_struct // must be before pat_ident
786 |
David Tolnay8d9e81a2016-10-03 22:36:32 -0700787 pat_struct // must be before pat_ident
788 |
David Tolnayaa610942016-10-03 22:22:49 -0700789 pat_mac // must be before pat_ident
790 |
David Tolnay8b308c22016-10-03 01:24:10 -0700791 pat_ident // must be before pat_path
David Tolnay9636c052016-10-02 17:11:17 -0700792 |
793 pat_path
David Tolnayfbb73232016-10-03 01:00:06 -0700794 |
795 pat_tuple
David Tolnayffdb97f2016-10-03 01:28:33 -0700796 |
797 pat_ref
David Tolnay8b308c22016-10-03 01:24:10 -0700798 |
799 pat_lit
David Tolnaydaaf7742016-10-03 11:11:43 -0700800 // TODO: Vec
David Tolnayb4ad3b52016-10-01 21:58:13 -0700801 ));
802
David Tolnay84aa0752016-10-02 23:01:13 -0700803 named!(pat_mac -> Pat, map!(mac, Pat::Mac));
804
David Tolnayb4ad3b52016-10-01 21:58:13 -0700805 named!(pat_wild -> Pat, map!(keyword!("_"), |_| Pat::Wild));
806
David Tolnayfbb73232016-10-03 01:00:06 -0700807 named!(pat_box -> Pat, do_parse!(
808 keyword!("box") >>
809 pat: pat >>
810 (Pat::Box(Box::new(pat)))
811 ));
812
David Tolnayb4ad3b52016-10-01 21:58:13 -0700813 named!(pat_ident -> Pat, do_parse!(
814 mode: option!(keyword!("ref")) >>
815 mutability: mutability >>
816 name: ident >>
David Tolnay8b308c22016-10-03 01:24:10 -0700817 not!(peek!(punct!("<"))) >>
818 not!(peek!(punct!("::"))) >>
David Tolnayb4ad3b52016-10-01 21:58:13 -0700819 subpat: option!(preceded!(punct!("@"), pat)) >>
820 (Pat::Ident(
821 if mode.is_some() {
822 BindingMode::ByRef(mutability)
823 } else {
824 BindingMode::ByValue(mutability)
825 },
826 name,
827 subpat.map(Box::new),
828 ))
829 ));
830
David Tolnayaa610942016-10-03 22:22:49 -0700831 named!(pat_tuple_struct -> Pat, do_parse!(
832 path: path >>
833 tuple: pat_tuple_helper >>
834 (Pat::TupleStruct(path, tuple.0, tuple.1))
835 ));
836
David Tolnay8d9e81a2016-10-03 22:36:32 -0700837 named!(pat_struct -> Pat, do_parse!(
838 path: path >>
839 punct!("{") >>
840 fields: separated_list!(punct!(","), field_pat) >>
841 more: option!(preceded!(
842 cond!(!fields.is_empty(), punct!(",")),
843 punct!("..")
844 )) >>
845 punct!("}") >>
846 (Pat::Struct(path, fields, more.is_some()))
847 ));
848
849 named!(field_pat -> FieldPat, alt!(
850 do_parse!(
851 ident: ident >>
852 punct!(":") >>
853 pat: pat >>
854 (FieldPat {
855 ident: ident,
856 pat: Box::new(pat),
857 is_shorthand: false,
858 })
859 )
860 |
861 do_parse!(
862 mode: option!(keyword!("ref")) >>
863 mutability: mutability >>
864 ident: ident >>
865 (FieldPat {
866 ident: ident.clone(),
867 pat: Box::new(Pat::Ident(
868 if mode.is_some() {
869 BindingMode::ByRef(mutability)
870 } else {
871 BindingMode::ByValue(mutability)
872 },
873 ident,
874 None,
875 )),
876 is_shorthand: true,
877 })
878 )
879 ));
880
David Tolnay9636c052016-10-02 17:11:17 -0700881 named!(pat_path -> Pat, map!(qpath, |(qself, path)| Pat::Path(qself, path)));
882
David Tolnayaa610942016-10-03 22:22:49 -0700883 named!(pat_tuple -> Pat, map!(
884 pat_tuple_helper,
885 |(pats, dotdot)| Pat::Tuple(pats, dotdot)
886 ));
887
888 named!(pat_tuple_helper -> (Vec<Pat>, Option<usize>), do_parse!(
David Tolnayfbb73232016-10-03 01:00:06 -0700889 punct!("(") >>
890 mut elems: separated_list!(punct!(","), pat) >>
891 dotdot: option!(do_parse!(
892 cond!(!elems.is_empty(), punct!(",")) >>
893 punct!("..") >>
894 rest: many0!(preceded!(punct!(","), pat)) >>
895 cond!(!rest.is_empty(), option!(punct!(","))) >>
896 (rest)
897 )) >>
898 cond!(!elems.is_empty() && dotdot.is_none(), option!(punct!(","))) >>
899 punct!(")") >>
900 (match dotdot {
901 Some(rest) => {
902 let pos = elems.len();
903 elems.extend(rest);
David Tolnayaa610942016-10-03 22:22:49 -0700904 (elems, Some(pos))
David Tolnayfbb73232016-10-03 01:00:06 -0700905 }
David Tolnayaa610942016-10-03 22:22:49 -0700906 None => (elems, None),
David Tolnayfbb73232016-10-03 01:00:06 -0700907 })
908 ));
909
David Tolnayffdb97f2016-10-03 01:28:33 -0700910 named!(pat_ref -> Pat, do_parse!(
911 punct!("&") >>
912 mutability: mutability >>
913 pat: pat >>
914 (Pat::Ref(Box::new(pat), mutability))
915 ));
916
David Tolnay8b308c22016-10-03 01:24:10 -0700917 named!(pat_lit -> Pat, map!(lit, |lit| Pat::Lit(Box::new(lit))));
918
919 named!(pat_range -> Pat, do_parse!(
920 lo: lit >>
921 punct!("...") >>
922 hi: lit >>
923 (Pat::Range(Box::new(lo), Box::new(hi)))
924 ));
925
David Tolnay89e05672016-10-02 14:39:42 -0700926 named!(capture_by -> CaptureBy, alt!(
927 keyword!("move") => { |_| CaptureBy::Value }
928 |
929 epsilon!() => { |_| CaptureBy::Ref }
930 ));
931
David Tolnay8b07f372016-09-30 10:28:40 -0700932 named!(label -> Ident, map!(lifetime, |lt: Lifetime| lt.ident));
David Tolnayb9c8e322016-09-23 20:48:37 -0700933}
934
David Tolnayf4bbbd92016-09-23 14:41:55 -0700935#[cfg(feature = "printing")]
936mod printing {
937 use super::*;
David Tolnayca085422016-10-04 00:12:38 -0700938 use {FnArg, FunctionRetTy, Mutability, Ty};
David Tolnay13b3d352016-10-03 00:31:15 -0700939 use attr::FilterAttrs;
David Tolnayf4bbbd92016-09-23 14:41:55 -0700940 use quote::{Tokens, ToTokens};
941
942 impl ToTokens for Expr {
943 fn to_tokens(&self, tokens: &mut Tokens) {
944 match *self {
David Tolnaybb6feae2016-10-02 21:25:20 -0700945 Expr::Box(ref inner) => {
946 tokens.append("box");
947 inner.to_tokens(tokens);
948 }
949 Expr::Vec(ref tys) => {
950 tokens.append("[");
951 tokens.append_separated(tys, ",");
952 tokens.append("]");
953 }
David Tolnay9636c052016-10-02 17:11:17 -0700954 Expr::Call(ref func, ref args) => {
955 func.to_tokens(tokens);
956 tokens.append("(");
957 tokens.append_separated(args, ",");
958 tokens.append(")");
959 }
960 Expr::MethodCall(ref ident, ref ascript, ref args) => {
961 args[0].to_tokens(tokens);
962 tokens.append(".");
963 ident.to_tokens(tokens);
964 if ascript.len() > 0 {
965 tokens.append("::");
966 tokens.append("<");
967 tokens.append_separated(ascript, ",");
968 tokens.append(">");
969 }
970 tokens.append("(");
971 tokens.append_separated(&args[1..], ",");
972 tokens.append(")");
973 }
David Tolnay47a877c2016-10-01 16:50:55 -0700974 Expr::Tup(ref fields) => {
975 tokens.append("(");
976 tokens.append_separated(fields, ",");
977 if fields.len() == 1 {
978 tokens.append(",");
979 }
980 tokens.append(")");
981 }
David Tolnay89e05672016-10-02 14:39:42 -0700982 Expr::Binary(op, ref left, ref right) => {
983 left.to_tokens(tokens);
984 op.to_tokens(tokens);
985 right.to_tokens(tokens);
986 }
David Tolnay3c2467c2016-10-02 17:55:08 -0700987 Expr::Unary(op, ref expr) => {
988 op.to_tokens(tokens);
989 expr.to_tokens(tokens);
990 }
David Tolnayf4bbbd92016-09-23 14:41:55 -0700991 Expr::Lit(ref lit) => lit.to_tokens(tokens),
David Tolnay3c2467c2016-10-02 17:55:08 -0700992 Expr::Cast(ref expr, ref ty) => {
993 expr.to_tokens(tokens);
994 tokens.append("as");
995 ty.to_tokens(tokens);
996 }
997 Expr::Type(ref expr, ref ty) => {
998 expr.to_tokens(tokens);
999 tokens.append(":");
1000 ty.to_tokens(tokens);
1001 }
1002 Expr::If(ref cond, ref then_block, ref else_block) => {
1003 tokens.append("if");
1004 cond.to_tokens(tokens);
1005 then_block.to_tokens(tokens);
1006 if let Some(ref else_block) = *else_block {
1007 tokens.append("else");
1008 else_block.to_tokens(tokens);
1009 }
1010 }
David Tolnay29f9ce12016-10-02 20:58:40 -07001011 Expr::IfLet(ref pat, ref expr, ref then_block, ref else_block) => {
1012 tokens.append("if");
1013 tokens.append("let");
1014 pat.to_tokens(tokens);
1015 tokens.append("=");
1016 expr.to_tokens(tokens);
1017 then_block.to_tokens(tokens);
1018 if let Some(ref else_block) = *else_block {
1019 tokens.append("else");
1020 else_block.to_tokens(tokens);
1021 }
1022 }
David Tolnaybb6feae2016-10-02 21:25:20 -07001023 Expr::While(ref cond, ref body, ref label) => {
1024 if let Some(ref label) = *label {
1025 label.to_tokens(tokens);
1026 tokens.append(":");
1027 }
1028 tokens.append("while");
1029 cond.to_tokens(tokens);
1030 body.to_tokens(tokens);
1031 }
1032 Expr::WhileLet(ref pat, ref expr, ref body, ref label) => {
1033 if let Some(ref label) = *label {
1034 label.to_tokens(tokens);
1035 tokens.append(":");
1036 }
1037 tokens.append("while");
1038 tokens.append("let");
1039 pat.to_tokens(tokens);
1040 tokens.append("=");
1041 expr.to_tokens(tokens);
1042 body.to_tokens(tokens);
1043 }
1044 Expr::ForLoop(ref pat, ref expr, ref body, ref label) => {
1045 if let Some(ref label) = *label {
1046 label.to_tokens(tokens);
1047 tokens.append(":");
1048 }
1049 tokens.append("for");
1050 pat.to_tokens(tokens);
1051 tokens.append("in");
1052 expr.to_tokens(tokens);
1053 body.to_tokens(tokens);
1054 }
1055 Expr::Loop(ref body, ref label) => {
1056 if let Some(ref label) = *label {
1057 label.to_tokens(tokens);
1058 tokens.append(":");
1059 }
1060 tokens.append("loop");
1061 body.to_tokens(tokens);
1062 }
David Tolnayb4ad3b52016-10-01 21:58:13 -07001063 Expr::Match(ref expr, ref arms) => {
1064 tokens.append("match");
1065 expr.to_tokens(tokens);
1066 tokens.append("{");
1067 tokens.append_separated(arms, ",");
1068 tokens.append("}");
1069 }
David Tolnay89e05672016-10-02 14:39:42 -07001070 Expr::Closure(capture, ref decl, ref body) => {
1071 capture.to_tokens(tokens);
1072 tokens.append("|");
1073 for (i, input) in decl.inputs.iter().enumerate() {
1074 if i > 0 {
1075 tokens.append(",");
1076 }
David Tolnayca085422016-10-04 00:12:38 -07001077 match *input {
1078 FnArg::Captured(ref pat, Ty::Infer) => {
1079 pat.to_tokens(tokens);
David Tolnaydaaf7742016-10-03 11:11:43 -07001080 }
David Tolnayca085422016-10-04 00:12:38 -07001081 _ => input.to_tokens(tokens),
David Tolnay89e05672016-10-02 14:39:42 -07001082 }
1083 }
1084 tokens.append("|");
1085 match decl.output {
1086 FunctionRetTy::Default => {
1087 if body.stmts.len() == 1 {
1088 if let Stmt::Expr(ref expr) = body.stmts[0] {
1089 expr.to_tokens(tokens);
1090 } else {
1091 body.to_tokens(tokens);
1092 }
1093 } else {
1094 body.to_tokens(tokens);
1095 }
1096 }
1097 FunctionRetTy::Ty(ref ty) => {
1098 tokens.append("->");
1099 ty.to_tokens(tokens);
1100 body.to_tokens(tokens);
1101 }
1102 }
1103 }
1104 Expr::Block(rules, ref block) => {
1105 rules.to_tokens(tokens);
1106 block.to_tokens(tokens);
1107 }
David Tolnaybb6feae2016-10-02 21:25:20 -07001108 Expr::Assign(ref var, ref expr) => {
1109 var.to_tokens(tokens);
1110 tokens.append("=");
1111 expr.to_tokens(tokens);
1112 }
1113 Expr::AssignOp(op, ref var, ref expr) => {
1114 var.to_tokens(tokens);
David Tolnay3cb23a92016-10-07 23:02:21 -07001115 tokens.append(op.assign_op().unwrap());
David Tolnaybb6feae2016-10-02 21:25:20 -07001116 expr.to_tokens(tokens);
1117 }
1118 Expr::Field(ref expr, ref field) => {
1119 expr.to_tokens(tokens);
1120 tokens.append(".");
1121 field.to_tokens(tokens);
1122 }
1123 Expr::TupField(ref expr, field) => {
1124 expr.to_tokens(tokens);
1125 tokens.append(".");
1126 tokens.append(&field.to_string());
1127 }
1128 Expr::Index(ref expr, ref index) => {
1129 expr.to_tokens(tokens);
1130 tokens.append("[");
1131 index.to_tokens(tokens);
1132 tokens.append("]");
1133 }
1134 Expr::Range(ref from, ref to, limits) => {
1135 from.to_tokens(tokens);
1136 match limits {
1137 RangeLimits::HalfOpen => tokens.append(".."),
1138 RangeLimits::Closed => tokens.append("..."),
1139 }
1140 to.to_tokens(tokens);
1141 }
David Tolnay8b308c22016-10-03 01:24:10 -07001142 Expr::Path(None, ref path) => path.to_tokens(tokens),
David Tolnay89e05672016-10-02 14:39:42 -07001143 Expr::Path(Some(ref qself), ref path) => {
1144 tokens.append("<");
1145 qself.ty.to_tokens(tokens);
1146 if qself.position > 0 {
1147 tokens.append("as");
David Tolnaydaaf7742016-10-03 11:11:43 -07001148 for (i, segment) in path.segments
1149 .iter()
1150 .take(qself.position)
1151 .enumerate() {
David Tolnay89e05672016-10-02 14:39:42 -07001152 if i > 0 || path.global {
1153 tokens.append("::");
1154 }
1155 segment.to_tokens(tokens);
1156 }
1157 }
1158 tokens.append(">");
1159 for segment in path.segments.iter().skip(qself.position) {
1160 tokens.append("::");
1161 segment.to_tokens(tokens);
1162 }
1163 }
David Tolnay3c2467c2016-10-02 17:55:08 -07001164 Expr::AddrOf(mutability, ref expr) => {
1165 tokens.append("&");
1166 mutability.to_tokens(tokens);
1167 expr.to_tokens(tokens);
1168 }
1169 Expr::Break(ref opt_label) => {
1170 tokens.append("break");
1171 opt_label.to_tokens(tokens);
1172 }
1173 Expr::Continue(ref opt_label) => {
1174 tokens.append("continue");
1175 opt_label.to_tokens(tokens);
1176 }
David Tolnay42602292016-10-01 22:25:45 -07001177 Expr::Ret(ref opt_expr) => {
1178 tokens.append("return");
1179 opt_expr.to_tokens(tokens);
1180 }
David Tolnaycc3d66e2016-10-02 23:36:05 -07001181 Expr::Mac(ref mac) => mac.to_tokens(tokens),
David Tolnay055a7042016-10-02 19:23:54 -07001182 Expr::Struct(ref path, ref fields, ref base) => {
1183 path.to_tokens(tokens);
1184 tokens.append("{");
1185 tokens.append_separated(fields, ",");
1186 if let Some(ref base) = *base {
1187 if !fields.is_empty() {
1188 tokens.append(",");
1189 }
1190 tokens.append("..");
1191 base.to_tokens(tokens);
1192 }
1193 tokens.append("}");
1194 }
1195 Expr::Repeat(ref expr, ref times) => {
1196 tokens.append("[");
1197 expr.to_tokens(tokens);
1198 tokens.append(";");
1199 times.to_tokens(tokens);
1200 tokens.append("]");
1201 }
David Tolnay89e05672016-10-02 14:39:42 -07001202 Expr::Paren(ref expr) => {
1203 tokens.append("(");
1204 expr.to_tokens(tokens);
1205 tokens.append(")");
1206 }
David Tolnay3c2467c2016-10-02 17:55:08 -07001207 Expr::Try(ref expr) => {
1208 expr.to_tokens(tokens);
1209 tokens.append("?");
1210 }
David Tolnayf4bbbd92016-09-23 14:41:55 -07001211 }
1212 }
1213 }
David Tolnayb4ad3b52016-10-01 21:58:13 -07001214
David Tolnay055a7042016-10-02 19:23:54 -07001215 impl ToTokens for FieldValue {
1216 fn to_tokens(&self, tokens: &mut Tokens) {
1217 self.ident.to_tokens(tokens);
1218 tokens.append(":");
1219 self.expr.to_tokens(tokens);
1220 }
1221 }
1222
David Tolnayb4ad3b52016-10-01 21:58:13 -07001223 impl ToTokens for Arm {
1224 fn to_tokens(&self, tokens: &mut Tokens) {
1225 for attr in &self.attrs {
1226 attr.to_tokens(tokens);
1227 }
1228 tokens.append_separated(&self.pats, "|");
1229 if let Some(ref guard) = self.guard {
1230 tokens.append("if");
1231 guard.to_tokens(tokens);
1232 }
1233 tokens.append("=>");
1234 self.body.to_tokens(tokens);
1235 match *self.body {
David Tolnaydaaf7742016-10-03 11:11:43 -07001236 Expr::Block(_, _) => {
1237 // no comma
1238 }
David Tolnayb4ad3b52016-10-01 21:58:13 -07001239 _ => tokens.append(","),
1240 }
1241 }
1242 }
1243
1244 impl ToTokens for Pat {
1245 fn to_tokens(&self, tokens: &mut Tokens) {
1246 match *self {
1247 Pat::Wild => tokens.append("_"),
1248 Pat::Ident(mode, ref ident, ref subpat) => {
1249 mode.to_tokens(tokens);
1250 ident.to_tokens(tokens);
1251 if let Some(ref subpat) = *subpat {
1252 tokens.append("@");
1253 subpat.to_tokens(tokens);
1254 }
1255 }
David Tolnay8d9e81a2016-10-03 22:36:32 -07001256 Pat::Struct(ref path, ref fields, dots) => {
1257 path.to_tokens(tokens);
1258 tokens.append("{");
1259 tokens.append_separated(fields, ",");
1260 if dots {
1261 if !fields.is_empty() {
1262 tokens.append(",");
1263 }
1264 tokens.append("..");
1265 }
1266 tokens.append("}");
1267 }
David Tolnayaa610942016-10-03 22:22:49 -07001268 Pat::TupleStruct(ref path, ref pats, dotpos) => {
1269 path.to_tokens(tokens);
1270 tokens.append("(");
1271 match dotpos {
1272 Some(pos) => {
1273 if pos > 0 {
1274 tokens.append_separated(&pats[..pos], ",");
1275 tokens.append(",");
1276 }
1277 tokens.append("..");
1278 if pos < pats.len() {
1279 tokens.append(",");
1280 tokens.append_separated(&pats[pos..], ",");
1281 }
1282 }
1283 None => tokens.append_separated(pats, ","),
1284 }
1285 tokens.append(")");
1286 }
David Tolnay8b308c22016-10-03 01:24:10 -07001287 Pat::Path(None, ref path) => path.to_tokens(tokens),
1288 Pat::Path(Some(ref qself), ref path) => {
1289 tokens.append("<");
1290 qself.ty.to_tokens(tokens);
1291 if qself.position > 0 {
1292 tokens.append("as");
David Tolnaydaaf7742016-10-03 11:11:43 -07001293 for (i, segment) in path.segments
1294 .iter()
1295 .take(qself.position)
1296 .enumerate() {
David Tolnay8b308c22016-10-03 01:24:10 -07001297 if i > 0 || path.global {
1298 tokens.append("::");
1299 }
1300 segment.to_tokens(tokens);
1301 }
1302 }
1303 tokens.append(">");
1304 for segment in path.segments.iter().skip(qself.position) {
1305 tokens.append("::");
1306 segment.to_tokens(tokens);
1307 }
1308 }
David Tolnayfbb73232016-10-03 01:00:06 -07001309 Pat::Tuple(ref pats, dotpos) => {
1310 tokens.append("(");
1311 match dotpos {
1312 Some(pos) => {
1313 if pos > 0 {
1314 tokens.append_separated(&pats[..pos], ",");
1315 tokens.append(",");
1316 }
1317 tokens.append("..");
1318 if pos < pats.len() {
1319 tokens.append(",");
1320 tokens.append_separated(&pats[pos..], ",");
1321 }
1322 }
1323 None => tokens.append_separated(pats, ","),
1324 }
1325 tokens.append(")");
1326 }
1327 Pat::Box(ref inner) => {
1328 tokens.append("box");
1329 inner.to_tokens(tokens);
1330 }
David Tolnayffdb97f2016-10-03 01:28:33 -07001331 Pat::Ref(ref target, mutability) => {
1332 tokens.append("&");
1333 mutability.to_tokens(tokens);
1334 target.to_tokens(tokens);
1335 }
David Tolnay8b308c22016-10-03 01:24:10 -07001336 Pat::Lit(ref lit) => lit.to_tokens(tokens),
1337 Pat::Range(ref lo, ref hi) => {
1338 lo.to_tokens(tokens);
1339 tokens.append("...");
1340 hi.to_tokens(tokens);
1341 }
David Tolnay16709ba2016-10-05 23:11:32 -07001342 Pat::Slice(ref _before, ref _dots, ref _after) => unimplemented!(),
David Tolnaycc3d66e2016-10-02 23:36:05 -07001343 Pat::Mac(ref mac) => mac.to_tokens(tokens),
David Tolnayb4ad3b52016-10-01 21:58:13 -07001344 }
1345 }
1346 }
1347
David Tolnay8d9e81a2016-10-03 22:36:32 -07001348 impl ToTokens for FieldPat {
1349 fn to_tokens(&self, tokens: &mut Tokens) {
1350 if !self.is_shorthand {
1351 self.ident.to_tokens(tokens);
1352 tokens.append(":");
1353 }
1354 self.pat.to_tokens(tokens);
1355 }
1356 }
1357
David Tolnayb4ad3b52016-10-01 21:58:13 -07001358 impl ToTokens for BindingMode {
1359 fn to_tokens(&self, tokens: &mut Tokens) {
1360 match *self {
1361 BindingMode::ByRef(Mutability::Immutable) => {
1362 tokens.append("ref");
1363 }
1364 BindingMode::ByRef(Mutability::Mutable) => {
1365 tokens.append("ref");
1366 tokens.append("mut");
1367 }
1368 BindingMode::ByValue(Mutability::Immutable) => {}
1369 BindingMode::ByValue(Mutability::Mutable) => {
1370 tokens.append("mut");
1371 }
1372 }
1373 }
1374 }
David Tolnay42602292016-10-01 22:25:45 -07001375
David Tolnay89e05672016-10-02 14:39:42 -07001376 impl ToTokens for CaptureBy {
1377 fn to_tokens(&self, tokens: &mut Tokens) {
1378 match *self {
1379 CaptureBy::Value => tokens.append("move"),
David Tolnaydaaf7742016-10-03 11:11:43 -07001380 CaptureBy::Ref => {
1381 // nothing
1382 }
David Tolnay89e05672016-10-02 14:39:42 -07001383 }
1384 }
1385 }
1386
David Tolnay42602292016-10-01 22:25:45 -07001387 impl ToTokens for Block {
1388 fn to_tokens(&self, tokens: &mut Tokens) {
David Tolnay42602292016-10-01 22:25:45 -07001389 tokens.append("{");
1390 for stmt in &self.stmts {
1391 stmt.to_tokens(tokens);
1392 }
1393 tokens.append("}");
1394 }
1395 }
1396
1397 impl ToTokens for BlockCheckMode {
1398 fn to_tokens(&self, tokens: &mut Tokens) {
1399 match *self {
David Tolnaydaaf7742016-10-03 11:11:43 -07001400 BlockCheckMode::Default => {
1401 // nothing
1402 }
David Tolnay42602292016-10-01 22:25:45 -07001403 BlockCheckMode::Unsafe => tokens.append("unsafe"),
1404 }
1405 }
1406 }
1407
1408 impl ToTokens for Stmt {
1409 fn to_tokens(&self, tokens: &mut Tokens) {
1410 match *self {
David Tolnay191e0582016-10-02 18:31:09 -07001411 Stmt::Local(ref local) => local.to_tokens(tokens),
David Tolnay42602292016-10-01 22:25:45 -07001412 Stmt::Item(ref item) => item.to_tokens(tokens),
1413 Stmt::Expr(ref expr) => expr.to_tokens(tokens),
1414 Stmt::Semi(ref expr) => {
1415 expr.to_tokens(tokens);
1416 tokens.append(";");
1417 }
David Tolnay13b3d352016-10-03 00:31:15 -07001418 Stmt::Mac(ref mac) => {
1419 let (ref mac, style, ref attrs) = **mac;
1420 for attr in attrs.outer() {
1421 attr.to_tokens(tokens);
1422 }
1423 mac.to_tokens(tokens);
1424 match style {
1425 MacStmtStyle::Semicolon => tokens.append(";"),
David Tolnaydaaf7742016-10-03 11:11:43 -07001426 MacStmtStyle::Braces | MacStmtStyle::NoBraces => {
1427 // no semicolon
1428 }
David Tolnay13b3d352016-10-03 00:31:15 -07001429 }
1430 }
David Tolnay42602292016-10-01 22:25:45 -07001431 }
1432 }
1433 }
David Tolnay191e0582016-10-02 18:31:09 -07001434
1435 impl ToTokens for Local {
1436 fn to_tokens(&self, tokens: &mut Tokens) {
1437 tokens.append("let");
1438 self.pat.to_tokens(tokens);
1439 if let Some(ref ty) = self.ty {
1440 tokens.append(":");
1441 ty.to_tokens(tokens);
1442 }
1443 if let Some(ref init) = self.init {
1444 tokens.append("=");
1445 init.to_tokens(tokens);
1446 }
1447 tokens.append(";");
1448 }
1449 }
David Tolnayf4bbbd92016-09-23 14:41:55 -07001450}