blob: d370f34de468efa7698f386c29f013b3b26713b6 [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 Tolnay3bcfb722016-10-08 11:58:36 -0700293 use {BinOp, Delimited, DelimToken, FnArg, FnDecl, FunctionRetTy, Ident, Lifetime, TokenTree,
294 Ty};
David Tolnayb4ad3b52016-10-01 21:58:13 -0700295 use attr::parsing::outer_attr;
Gregory Katz1b69f682016-09-27 21:06:09 -0400296 use generics::parsing::lifetime;
David Tolnayfa0edf22016-09-23 22:58:24 -0700297 use ident::parsing::ident;
David Tolnay191e0582016-10-02 18:31:09 -0700298 use item::parsing::item;
David Tolnay438c9052016-10-07 23:24:48 -0700299 use lit::parsing::{digits, lit};
David Tolnay84aa0752016-10-02 23:01:13 -0700300 use mac::parsing::mac;
David Tolnaycfe55022016-10-02 22:02:27 -0700301 use nom::IResult::Error;
David Tolnay438c9052016-10-07 23:24:48 -0700302 use op::parsing::{assign_op, binop, unop};
David Tolnay055a7042016-10-02 19:23:54 -0700303 use ty::parsing::{mutability, path, qpath, ty};
David Tolnayb9c8e322016-09-23 20:48:37 -0700304
David Tolnayfa0edf22016-09-23 22:58:24 -0700305 named!(pub expr -> Expr, do_parse!(
306 mut e: alt!(
David Tolnayfa94b6f2016-10-05 23:26:11 -0700307 expr_lit // must be before expr_struct
David Tolnay055a7042016-10-02 19:23:54 -0700308 |
David Tolnayfa94b6f2016-10-05 23:26:11 -0700309 expr_struct // must be before expr_path
David Tolnay055a7042016-10-02 19:23:54 -0700310 |
David Tolnayfa94b6f2016-10-05 23:26:11 -0700311 expr_paren // must be before expr_tup
312 |
313 expr_mac // must be before expr_path
David Tolnay89e05672016-10-02 14:39:42 -0700314 |
David Tolnay4c9be372016-10-06 00:47:37 -0700315 expr_break // must be before expr_path
316 |
317 expr_continue // must be before expr_path
318 |
319 expr_ret // must be before expr_path
320 |
David Tolnay939766a2016-09-23 23:48:12 -0700321 expr_box
David Tolnayfa0edf22016-09-23 22:58:24 -0700322 |
David Tolnay939766a2016-09-23 23:48:12 -0700323 expr_vec
David Tolnayfa0edf22016-09-23 22:58:24 -0700324 |
David Tolnay939766a2016-09-23 23:48:12 -0700325 expr_tup
David Tolnayfa0edf22016-09-23 22:58:24 -0700326 |
David Tolnay939766a2016-09-23 23:48:12 -0700327 expr_unary
David Tolnayfa0edf22016-09-23 22:58:24 -0700328 |
David Tolnay939766a2016-09-23 23:48:12 -0700329 expr_if
Gregory Katz3e562cc2016-09-28 18:33:02 -0400330 |
331 expr_while
David Tolnaybb6feae2016-10-02 21:25:20 -0700332 |
333 expr_for_loop
Gregory Katze5f35682016-09-27 14:20:55 -0400334 |
335 expr_loop
David Tolnayb4ad3b52016-10-01 21:58:13 -0700336 |
337 expr_match
David Tolnay89e05672016-10-02 14:39:42 -0700338 |
339 expr_closure
David Tolnay939766a2016-09-23 23:48:12 -0700340 |
341 expr_block
David Tolnay89e05672016-10-02 14:39:42 -0700342 |
David Tolnay438c9052016-10-07 23:24:48 -0700343 expr_range
344 |
David Tolnay89e05672016-10-02 14:39:42 -0700345 expr_path
David Tolnay3c2467c2016-10-02 17:55:08 -0700346 |
347 expr_addr_of
Gregory Katzfd6935d2016-09-30 22:51:25 -0400348 |
David Tolnay055a7042016-10-02 19:23:54 -0700349 expr_repeat
David Tolnayfa0edf22016-09-23 22:58:24 -0700350 ) >>
351 many0!(alt!(
David Tolnay939766a2016-09-23 23:48:12 -0700352 tap!(args: and_call => {
353 e = Expr::Call(Box::new(e), args);
David Tolnayfa0edf22016-09-23 22:58:24 -0700354 })
355 |
David Tolnay939766a2016-09-23 23:48:12 -0700356 tap!(more: and_method_call => {
357 let (method, ascript, mut args) = more;
David Tolnayfa0edf22016-09-23 22:58:24 -0700358 args.insert(0, e);
359 e = Expr::MethodCall(method, ascript, args);
360 })
361 |
David Tolnay939766a2016-09-23 23:48:12 -0700362 tap!(more: and_binary => {
363 let (op, other) = more;
David Tolnayfa0edf22016-09-23 22:58:24 -0700364 e = Expr::Binary(op, Box::new(e), Box::new(other));
365 })
David Tolnay939766a2016-09-23 23:48:12 -0700366 |
367 tap!(ty: and_cast => {
368 e = Expr::Cast(Box::new(e), Box::new(ty));
369 })
370 |
371 tap!(ty: and_ascription => {
372 e = Expr::Type(Box::new(e), Box::new(ty));
373 })
David Tolnay438c9052016-10-07 23:24:48 -0700374 |
375 tap!(v: and_assign => {
376 e = Expr::Assign(Box::new(e), Box::new(v));
377 })
378 |
379 tap!(more: and_assign_op => {
380 let (op, v) = more;
381 e = Expr::AssignOp(op, Box::new(e), Box::new(v));
382 })
383 |
384 tap!(field: and_field => {
385 e = Expr::Field(Box::new(e), field);
386 })
387 |
388 tap!(field: and_tup_field => {
389 e = Expr::TupField(Box::new(e), field as usize);
390 })
391 |
392 tap!(i: and_index => {
393 e = Expr::Index(Box::new(e), Box::new(i));
394 })
395 |
396 tap!(more: and_range => {
397 let (limits, hi) = more;
398 e = Expr::Range(Some(Box::new(e)), hi.map(Box::new), limits);
399 })
David Tolnay055a7042016-10-02 19:23:54 -0700400 |
401 tap!(_try: punct!("?") => {
402 e = Expr::Try(Box::new(e));
403 })
David Tolnayfa0edf22016-09-23 22:58:24 -0700404 )) >>
405 (e)
David Tolnayb9c8e322016-09-23 20:48:37 -0700406 ));
407
David Tolnay84aa0752016-10-02 23:01:13 -0700408 named!(expr_mac -> Expr, map!(mac, Expr::Mac));
409
David Tolnay89e05672016-10-02 14:39:42 -0700410 named!(expr_paren -> Expr, do_parse!(
411 punct!("(") >>
412 e: expr >>
413 punct!(")") >>
414 (Expr::Paren(Box::new(e)))
415 ));
416
David Tolnay939766a2016-09-23 23:48:12 -0700417 named!(expr_box -> Expr, do_parse!(
David Tolnay10413f02016-09-30 09:12:02 -0700418 keyword!("box") >>
David Tolnayb9c8e322016-09-23 20:48:37 -0700419 inner: expr >>
420 (Expr::Box(Box::new(inner)))
421 ));
David Tolnayfa0edf22016-09-23 22:58:24 -0700422
David Tolnay939766a2016-09-23 23:48:12 -0700423 named!(expr_vec -> Expr, do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700424 punct!("[") >>
425 elems: separated_list!(punct!(","), expr) >>
David Tolnayf6c74402016-10-08 02:31:26 -0700426 cond!(!elems.is_empty(), option!(punct!(","))) >>
David Tolnayfa0edf22016-09-23 22:58:24 -0700427 punct!("]") >>
428 (Expr::Vec(elems))
429 ));
430
David Tolnay939766a2016-09-23 23:48:12 -0700431 named!(and_call -> Vec<Expr>, do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700432 punct!("(") >>
433 args: separated_list!(punct!(","), expr) >>
David Tolnayf6c74402016-10-08 02:31:26 -0700434 cond!(!args.is_empty(), option!(punct!(","))) >>
David Tolnayfa0edf22016-09-23 22:58:24 -0700435 punct!(")") >>
436 (args)
437 ));
438
David Tolnay939766a2016-09-23 23:48:12 -0700439 named!(and_method_call -> (Ident, Vec<Ty>, Vec<Expr>), do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700440 punct!(".") >>
441 method: ident >>
David Tolnayf6c74402016-10-08 02:31:26 -0700442 ascript: opt_vec!(preceded!(
443 punct!("::"),
444 delimited!(
445 punct!("<"),
446 separated_list!(punct!(","), ty),
447 punct!(">")
448 )
David Tolnayfa0edf22016-09-23 22:58:24 -0700449 )) >>
450 punct!("(") >>
451 args: separated_list!(punct!(","), expr) >>
David Tolnayf6c74402016-10-08 02:31:26 -0700452 cond!(!args.is_empty(), option!(punct!(","))) >>
David Tolnayfa0edf22016-09-23 22:58:24 -0700453 punct!(")") >>
454 (method, ascript, args)
455 ));
456
David Tolnay939766a2016-09-23 23:48:12 -0700457 named!(expr_tup -> Expr, do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700458 punct!("(") >>
459 elems: separated_list!(punct!(","), expr) >>
David Tolnayf6c74402016-10-08 02:31:26 -0700460 cond!(!elems.is_empty(), option!(punct!(","))) >>
David Tolnayfa0edf22016-09-23 22:58:24 -0700461 punct!(")") >>
462 (Expr::Tup(elems))
463 ));
464
David Tolnay3cb23a92016-10-07 23:02:21 -0700465 named!(and_binary -> (BinOp, Expr), tuple!(binop, expr));
David Tolnayfa0edf22016-09-23 22:58:24 -0700466
David Tolnay939766a2016-09-23 23:48:12 -0700467 named!(expr_unary -> Expr, do_parse!(
David Tolnay3cb23a92016-10-07 23:02:21 -0700468 operator: unop >>
David Tolnayfa0edf22016-09-23 22:58:24 -0700469 operand: expr >>
470 (Expr::Unary(operator, Box::new(operand)))
471 ));
David Tolnay939766a2016-09-23 23:48:12 -0700472
473 named!(expr_lit -> Expr, map!(lit, Expr::Lit));
474
475 named!(and_cast -> Ty, do_parse!(
David Tolnay10413f02016-09-30 09:12:02 -0700476 keyword!("as") >>
David Tolnay939766a2016-09-23 23:48:12 -0700477 ty: ty >>
478 (ty)
479 ));
480
481 named!(and_ascription -> Ty, preceded!(punct!(":"), ty));
482
David Tolnaybb6feae2016-10-02 21:25:20 -0700483 enum Cond {
David Tolnay29f9ce12016-10-02 20:58:40 -0700484 Let(Pat, Expr),
485 Expr(Expr),
486 }
487
David Tolnaybb6feae2016-10-02 21:25:20 -0700488 named!(cond -> Cond, alt!(
489 do_parse!(
490 keyword!("let") >>
491 pat: pat >>
492 punct!("=") >>
493 value: expr >>
494 (Cond::Let(pat, value))
495 )
496 |
497 map!(expr, Cond::Expr)
498 ));
499
David Tolnay939766a2016-09-23 23:48:12 -0700500 named!(expr_if -> Expr, do_parse!(
David Tolnay10413f02016-09-30 09:12:02 -0700501 keyword!("if") >>
David Tolnaybb6feae2016-10-02 21:25:20 -0700502 cond: cond >>
David Tolnay939766a2016-09-23 23:48:12 -0700503 punct!("{") >>
504 then_block: within_block >>
505 punct!("}") >>
506 else_block: option!(preceded!(
David Tolnay10413f02016-09-30 09:12:02 -0700507 keyword!("else"),
David Tolnay939766a2016-09-23 23:48:12 -0700508 alt!(
509 expr_if
510 |
511 do_parse!(
512 punct!("{") >>
513 else_block: within_block >>
514 punct!("}") >>
David Tolnay89e05672016-10-02 14:39:42 -0700515 (Expr::Block(BlockCheckMode::Default, Block {
David Tolnay939766a2016-09-23 23:48:12 -0700516 stmts: else_block,
David Tolnay89e05672016-10-02 14:39:42 -0700517 }))
David Tolnay939766a2016-09-23 23:48:12 -0700518 )
519 )
520 )) >>
David Tolnay29f9ce12016-10-02 20:58:40 -0700521 (match cond {
David Tolnaybb6feae2016-10-02 21:25:20 -0700522 Cond::Let(pat, expr) => Expr::IfLet(
David Tolnay29f9ce12016-10-02 20:58:40 -0700523 Box::new(pat),
524 Box::new(expr),
525 Block {
526 stmts: then_block,
527 },
528 else_block.map(Box::new),
529 ),
David Tolnaybb6feae2016-10-02 21:25:20 -0700530 Cond::Expr(cond) => Expr::If(
David Tolnay29f9ce12016-10-02 20:58:40 -0700531 Box::new(cond),
532 Block {
533 stmts: then_block,
534 },
535 else_block.map(Box::new),
536 ),
537 })
David Tolnay939766a2016-09-23 23:48:12 -0700538 ));
539
David Tolnaybb6feae2016-10-02 21:25:20 -0700540 named!(expr_for_loop -> Expr, do_parse!(
541 lbl: option!(terminated!(label, punct!(":"))) >>
542 keyword!("for") >>
543 pat: pat >>
544 keyword!("in") >>
545 expr: expr >>
546 loop_block: block >>
547 (Expr::ForLoop(Box::new(pat), Box::new(expr), loop_block, lbl))
548 ));
549
Gregory Katze5f35682016-09-27 14:20:55 -0400550 named!(expr_loop -> Expr, do_parse!(
David Tolnay8b07f372016-09-30 10:28:40 -0700551 lbl: option!(terminated!(label, punct!(":"))) >>
David Tolnay10413f02016-09-30 09:12:02 -0700552 keyword!("loop") >>
Gregory Katze5f35682016-09-27 14:20:55 -0400553 loop_block: block >>
David Tolnay89e05672016-10-02 14:39:42 -0700554 (Expr::Loop(loop_block, lbl))
Gregory Katze5f35682016-09-27 14:20:55 -0400555 ));
556
David Tolnayb4ad3b52016-10-01 21:58:13 -0700557 named!(expr_match -> Expr, do_parse!(
558 keyword!("match") >>
559 obj: expr >>
560 punct!("{") >>
561 arms: many0!(do_parse!(
562 attrs: many0!(outer_attr) >>
563 pats: separated_nonempty_list!(punct!("|"), pat) >>
564 guard: option!(preceded!(keyword!("if"), expr)) >>
565 punct!("=>") >>
566 body: alt!(
David Tolnay89e05672016-10-02 14:39:42 -0700567 map!(block, |blk| Expr::Block(BlockCheckMode::Default, blk))
David Tolnayf6c74402016-10-08 02:31:26 -0700568 |
569 expr
David Tolnayb4ad3b52016-10-01 21:58:13 -0700570 ) >>
David Tolnayf6c74402016-10-08 02:31:26 -0700571 option!(punct!(",")) >>
David Tolnayb4ad3b52016-10-01 21:58:13 -0700572 (Arm {
573 attrs: attrs,
574 pats: pats,
575 guard: guard.map(Box::new),
576 body: Box::new(body),
577 })
578 )) >>
579 punct!("}") >>
580 (Expr::Match(Box::new(obj), arms))
581 ));
582
David Tolnay89e05672016-10-02 14:39:42 -0700583 named!(expr_closure -> Expr, do_parse!(
584 capture: capture_by >>
585 punct!("|") >>
586 inputs: separated_list!(punct!(","), closure_arg) >>
David Tolnayf6c74402016-10-08 02:31:26 -0700587 cond!(!inputs.is_empty(), option!(punct!(","))) >>
David Tolnay89e05672016-10-02 14:39:42 -0700588 punct!("|") >>
589 ret_and_body: alt!(
590 do_parse!(
591 punct!("->") >>
592 ty: ty >>
593 body: block >>
594 ((FunctionRetTy::Ty(ty), body))
595 )
596 |
597 map!(expr, |e| (
598 FunctionRetTy::Default,
599 Block {
600 stmts: vec![Stmt::Expr(Box::new(e))],
601 },
602 ))
603 ) >>
604 (Expr::Closure(
605 capture,
606 Box::new(FnDecl {
607 inputs: inputs,
608 output: ret_and_body.0,
609 }),
610 ret_and_body.1,
611 ))
612 ));
613
614 named!(closure_arg -> FnArg, do_parse!(
615 pat: pat >>
616 ty: option!(preceded!(punct!(":"), ty)) >>
David Tolnayca085422016-10-04 00:12:38 -0700617 (FnArg::Captured(pat, ty.unwrap_or(Ty::Infer)))
David Tolnay89e05672016-10-02 14:39:42 -0700618 ));
619
Gregory Katz3e562cc2016-09-28 18:33:02 -0400620 named!(expr_while -> Expr, do_parse!(
David Tolnay8b07f372016-09-30 10:28:40 -0700621 lbl: option!(terminated!(label, punct!(":"))) >>
David Tolnay57ffbde2016-09-30 09:38:04 -0700622 keyword!("while") >>
David Tolnaybb6feae2016-10-02 21:25:20 -0700623 cond: cond >>
Gregory Katz3e562cc2016-09-28 18:33:02 -0400624 while_block: block >>
David Tolnaybb6feae2016-10-02 21:25:20 -0700625 (match cond {
626 Cond::Let(pat, expr) => Expr::WhileLet(
627 Box::new(pat),
628 Box::new(expr),
629 while_block,
630 lbl,
631 ),
632 Cond::Expr(cond) => Expr::While(
633 Box::new(cond),
634 while_block,
635 lbl,
636 ),
637 })
Gregory Katz3e562cc2016-09-28 18:33:02 -0400638 ));
639
Gregory Katzfd6935d2016-09-30 22:51:25 -0400640 named!(expr_continue -> Expr, do_parse!(
641 keyword!("continue") >>
642 lbl: option!(label) >>
David Tolnay055a7042016-10-02 19:23:54 -0700643 (Expr::Continue(lbl))
Gregory Katzfd6935d2016-09-30 22:51:25 -0400644 ));
645
646 named!(expr_break -> Expr, do_parse!(
647 keyword!("break") >>
648 lbl: option!(label) >>
David Tolnay055a7042016-10-02 19:23:54 -0700649 (Expr::Break(lbl))
Gregory Katzfd6935d2016-09-30 22:51:25 -0400650 ));
651
652 named!(expr_ret -> Expr, do_parse!(
653 keyword!("return") >>
654 ret_value: option!(expr) >>
David Tolnay055a7042016-10-02 19:23:54 -0700655 (Expr::Ret(ret_value.map(Box::new)))
656 ));
657
658 named!(expr_struct -> Expr, do_parse!(
659 path: path >>
660 punct!("{") >>
661 fields: separated_list!(punct!(","), field_value) >>
662 base: option!(do_parse!(
663 cond!(!fields.is_empty(), punct!(",")) >>
664 punct!("..") >>
665 base: expr >>
666 (base)
667 )) >>
David Tolnayf6c74402016-10-08 02:31:26 -0700668 cond!(!fields.is_empty() && base.is_none(), option!(punct!(","))) >>
David Tolnay055a7042016-10-02 19:23:54 -0700669 punct!("}") >>
670 (Expr::Struct(path, fields, base.map(Box::new)))
671 ));
672
673 named!(field_value -> FieldValue, do_parse!(
674 name: ident >>
675 punct!(":") >>
676 value: expr >>
677 (FieldValue {
678 ident: name,
679 expr: value,
680 })
681 ));
682
683 named!(expr_repeat -> Expr, do_parse!(
684 punct!("[") >>
685 value: expr >>
686 punct!(";") >>
687 times: expr >>
688 punct!("]") >>
689 (Expr::Repeat(Box::new(value), Box::new(times)))
Gregory Katzfd6935d2016-09-30 22:51:25 -0400690 ));
691
David Tolnay42602292016-10-01 22:25:45 -0700692 named!(expr_block -> Expr, do_parse!(
David Tolnay939766a2016-09-23 23:48:12 -0700693 rules: block_check_mode >>
David Tolnay42602292016-10-01 22:25:45 -0700694 b: block >>
David Tolnay89e05672016-10-02 14:39:42 -0700695 (Expr::Block(rules, Block {
David Tolnay42602292016-10-01 22:25:45 -0700696 stmts: b.stmts,
David Tolnay89e05672016-10-02 14:39:42 -0700697 }))
698 ));
699
David Tolnay438c9052016-10-07 23:24:48 -0700700 named!(expr_range -> Expr, do_parse!(
701 limits: range_limits >>
702 hi: option!(expr) >>
703 (Expr::Range(None, hi.map(Box::new), limits))
704 ));
705
706 named!(range_limits -> RangeLimits, alt!(
707 punct!("...") => { |_| RangeLimits::Closed }
708 |
709 punct!("..") => { |_| RangeLimits::HalfOpen }
710 ));
711
David Tolnay9636c052016-10-02 17:11:17 -0700712 named!(expr_path -> Expr, map!(qpath, |(qself, path)| Expr::Path(qself, path)));
David Tolnay42602292016-10-01 22:25:45 -0700713
David Tolnay3c2467c2016-10-02 17:55:08 -0700714 named!(expr_addr_of -> Expr, do_parse!(
715 punct!("&") >>
716 mutability: mutability >>
717 expr: expr >>
718 (Expr::AddrOf(mutability, Box::new(expr)))
719 ));
720
David Tolnay438c9052016-10-07 23:24:48 -0700721 named!(and_assign -> Expr, preceded!(punct!("="), expr));
722
723 named!(and_assign_op -> (BinOp, Expr), tuple!(assign_op, expr));
724
725 named!(and_field -> Ident, preceded!(punct!("."), ident));
726
727 named!(and_tup_field -> u64, preceded!(punct!("."), digits));
728
729 named!(and_index -> Expr, delimited!(punct!("["), expr, punct!("]")));
730
731 named!(and_range -> (RangeLimits, Option<Expr>), tuple!(range_limits, option!(expr)));
732
David Tolnay42602292016-10-01 22:25:45 -0700733 named!(pub block -> Block, do_parse!(
David Tolnay939766a2016-09-23 23:48:12 -0700734 punct!("{") >>
735 stmts: within_block >>
736 punct!("}") >>
737 (Block {
738 stmts: stmts,
David Tolnay939766a2016-09-23 23:48:12 -0700739 })
740 ));
741
742 named!(block_check_mode -> BlockCheckMode, alt!(
David Tolnay10413f02016-09-30 09:12:02 -0700743 keyword!("unsafe") => { |_| BlockCheckMode::Unsafe }
David Tolnay939766a2016-09-23 23:48:12 -0700744 |
745 epsilon!() => { |_| BlockCheckMode::Default }
746 ));
747
748 named!(within_block -> Vec<Stmt>, do_parse!(
David Tolnaycfe55022016-10-02 22:02:27 -0700749 many0!(punct!(";")) >>
750 mut standalone: many0!(terminated!(standalone_stmt, many0!(punct!(";")))) >>
David Tolnay939766a2016-09-23 23:48:12 -0700751 last: option!(expr) >>
752 (match last {
David Tolnaycfe55022016-10-02 22:02:27 -0700753 None => standalone,
David Tolnay939766a2016-09-23 23:48:12 -0700754 Some(last) => {
David Tolnaycfe55022016-10-02 22:02:27 -0700755 standalone.push(Stmt::Expr(Box::new(last)));
756 standalone
David Tolnay939766a2016-09-23 23:48:12 -0700757 }
758 })
759 ));
760
761 named!(standalone_stmt -> Stmt, alt!(
David Tolnay13b3d352016-10-03 00:31:15 -0700762 stmt_mac
763 |
David Tolnay191e0582016-10-02 18:31:09 -0700764 stmt_local
765 |
766 stmt_item
767 |
David Tolnaycfe55022016-10-02 22:02:27 -0700768 stmt_expr
David Tolnay939766a2016-09-23 23:48:12 -0700769 ));
770
David Tolnay13b3d352016-10-03 00:31:15 -0700771 named!(stmt_mac -> Stmt, do_parse!(
772 attrs: many0!(outer_attr) >>
773 mac: mac >>
774 semi: option!(punct!(";")) >>
775 ({
776 let style = if semi.is_some() {
777 MacStmtStyle::Semicolon
778 } else if let Some(&TokenTree::Delimited(Delimited { delim, .. })) = mac.tts.last() {
779 match delim {
780 DelimToken::Paren | DelimToken::Bracket => MacStmtStyle::NoBraces,
781 DelimToken::Brace => MacStmtStyle::Braces,
782 }
783 } else {
784 MacStmtStyle::NoBraces
785 };
786 Stmt::Mac(Box::new((mac, style, attrs)))
787 })
788 ));
789
David Tolnay191e0582016-10-02 18:31:09 -0700790 named!(stmt_local -> Stmt, do_parse!(
791 attrs: many0!(outer_attr) >>
792 keyword!("let") >>
793 pat: pat >>
794 ty: option!(preceded!(punct!(":"), ty)) >>
795 init: option!(preceded!(punct!("="), expr)) >>
796 punct!(";") >>
797 (Stmt::Local(Box::new(Local {
798 pat: Box::new(pat),
799 ty: ty.map(Box::new),
800 init: init.map(Box::new),
801 attrs: attrs,
802 })))
803 ));
804
805 named!(stmt_item -> Stmt, map!(item, |i| Stmt::Item(Box::new(i))));
806
David Tolnaycfe55022016-10-02 22:02:27 -0700807 fn requires_semi(e: &Expr) -> bool {
808 match *e {
David Tolnaycfe55022016-10-02 22:02:27 -0700809 Expr::If(_, _, _) |
810 Expr::IfLet(_, _, _, _) |
811 Expr::While(_, _, _) |
812 Expr::WhileLet(_, _, _, _) |
813 Expr::ForLoop(_, _, _, _) |
814 Expr::Loop(_, _) |
815 Expr::Match(_, _) |
816 Expr::Block(_, _) => false,
817
818 _ => true,
819 }
820 }
821
822 named!(stmt_expr -> Stmt, do_parse!(
David Tolnay939766a2016-09-23 23:48:12 -0700823 e: expr >>
David Tolnaycfe55022016-10-02 22:02:27 -0700824 semi: option!(punct!(";")) >>
825 (if semi.is_some() {
826 Stmt::Semi(Box::new(e))
827 } else if requires_semi(&e) {
828 return Error;
829 } else {
830 Stmt::Expr(Box::new(e))
831 })
David Tolnay939766a2016-09-23 23:48:12 -0700832 ));
David Tolnay8b07f372016-09-30 10:28:40 -0700833
David Tolnay42602292016-10-01 22:25:45 -0700834 named!(pub pat -> Pat, alt!(
David Tolnayfbb73232016-10-03 01:00:06 -0700835 pat_wild // must be before pat_ident
836 |
837 pat_box // must be before pat_ident
David Tolnayb4ad3b52016-10-01 21:58:13 -0700838 |
David Tolnay8b308c22016-10-03 01:24:10 -0700839 pat_range // must be before pat_lit
840 |
David Tolnayaa610942016-10-03 22:22:49 -0700841 pat_tuple_struct // must be before pat_ident
842 |
David Tolnay8d9e81a2016-10-03 22:36:32 -0700843 pat_struct // must be before pat_ident
844 |
David Tolnayaa610942016-10-03 22:22:49 -0700845 pat_mac // must be before pat_ident
846 |
David Tolnay8b308c22016-10-03 01:24:10 -0700847 pat_ident // must be before pat_path
David Tolnay9636c052016-10-02 17:11:17 -0700848 |
849 pat_path
David Tolnayfbb73232016-10-03 01:00:06 -0700850 |
851 pat_tuple
David Tolnayffdb97f2016-10-03 01:28:33 -0700852 |
853 pat_ref
David Tolnay8b308c22016-10-03 01:24:10 -0700854 |
855 pat_lit
David Tolnaydaaf7742016-10-03 11:11:43 -0700856 // TODO: Vec
David Tolnayb4ad3b52016-10-01 21:58:13 -0700857 ));
858
David Tolnay84aa0752016-10-02 23:01:13 -0700859 named!(pat_mac -> Pat, map!(mac, Pat::Mac));
860
David Tolnayb4ad3b52016-10-01 21:58:13 -0700861 named!(pat_wild -> Pat, map!(keyword!("_"), |_| Pat::Wild));
862
David Tolnayfbb73232016-10-03 01:00:06 -0700863 named!(pat_box -> Pat, do_parse!(
864 keyword!("box") >>
865 pat: pat >>
866 (Pat::Box(Box::new(pat)))
867 ));
868
David Tolnayb4ad3b52016-10-01 21:58:13 -0700869 named!(pat_ident -> Pat, do_parse!(
870 mode: option!(keyword!("ref")) >>
871 mutability: mutability >>
872 name: ident >>
David Tolnay8b308c22016-10-03 01:24:10 -0700873 not!(peek!(punct!("<"))) >>
874 not!(peek!(punct!("::"))) >>
David Tolnayb4ad3b52016-10-01 21:58:13 -0700875 subpat: option!(preceded!(punct!("@"), pat)) >>
876 (Pat::Ident(
877 if mode.is_some() {
878 BindingMode::ByRef(mutability)
879 } else {
880 BindingMode::ByValue(mutability)
881 },
882 name,
883 subpat.map(Box::new),
884 ))
885 ));
886
David Tolnayaa610942016-10-03 22:22:49 -0700887 named!(pat_tuple_struct -> Pat, do_parse!(
888 path: path >>
889 tuple: pat_tuple_helper >>
890 (Pat::TupleStruct(path, tuple.0, tuple.1))
891 ));
892
David Tolnay8d9e81a2016-10-03 22:36:32 -0700893 named!(pat_struct -> Pat, do_parse!(
894 path: path >>
895 punct!("{") >>
896 fields: separated_list!(punct!(","), field_pat) >>
897 more: option!(preceded!(
898 cond!(!fields.is_empty(), punct!(",")),
899 punct!("..")
900 )) >>
901 punct!("}") >>
902 (Pat::Struct(path, fields, more.is_some()))
903 ));
904
905 named!(field_pat -> FieldPat, alt!(
906 do_parse!(
907 ident: ident >>
908 punct!(":") >>
909 pat: pat >>
910 (FieldPat {
911 ident: ident,
912 pat: Box::new(pat),
913 is_shorthand: false,
914 })
915 )
916 |
917 do_parse!(
918 mode: option!(keyword!("ref")) >>
919 mutability: mutability >>
920 ident: ident >>
921 (FieldPat {
922 ident: ident.clone(),
923 pat: Box::new(Pat::Ident(
924 if mode.is_some() {
925 BindingMode::ByRef(mutability)
926 } else {
927 BindingMode::ByValue(mutability)
928 },
929 ident,
930 None,
931 )),
932 is_shorthand: true,
933 })
934 )
935 ));
936
David Tolnay9636c052016-10-02 17:11:17 -0700937 named!(pat_path -> Pat, map!(qpath, |(qself, path)| Pat::Path(qself, path)));
938
David Tolnayaa610942016-10-03 22:22:49 -0700939 named!(pat_tuple -> Pat, map!(
940 pat_tuple_helper,
941 |(pats, dotdot)| Pat::Tuple(pats, dotdot)
942 ));
943
944 named!(pat_tuple_helper -> (Vec<Pat>, Option<usize>), do_parse!(
David Tolnayfbb73232016-10-03 01:00:06 -0700945 punct!("(") >>
946 mut elems: separated_list!(punct!(","), pat) >>
947 dotdot: option!(do_parse!(
948 cond!(!elems.is_empty(), punct!(",")) >>
949 punct!("..") >>
950 rest: many0!(preceded!(punct!(","), pat)) >>
951 cond!(!rest.is_empty(), option!(punct!(","))) >>
952 (rest)
953 )) >>
954 cond!(!elems.is_empty() && dotdot.is_none(), option!(punct!(","))) >>
955 punct!(")") >>
956 (match dotdot {
957 Some(rest) => {
958 let pos = elems.len();
959 elems.extend(rest);
David Tolnayaa610942016-10-03 22:22:49 -0700960 (elems, Some(pos))
David Tolnayfbb73232016-10-03 01:00:06 -0700961 }
David Tolnayaa610942016-10-03 22:22:49 -0700962 None => (elems, None),
David Tolnayfbb73232016-10-03 01:00:06 -0700963 })
964 ));
965
David Tolnayffdb97f2016-10-03 01:28:33 -0700966 named!(pat_ref -> Pat, do_parse!(
967 punct!("&") >>
968 mutability: mutability >>
969 pat: pat >>
970 (Pat::Ref(Box::new(pat), mutability))
971 ));
972
David Tolnay8b308c22016-10-03 01:24:10 -0700973 named!(pat_lit -> Pat, map!(lit, |lit| Pat::Lit(Box::new(lit))));
974
975 named!(pat_range -> Pat, do_parse!(
976 lo: lit >>
977 punct!("...") >>
978 hi: lit >>
979 (Pat::Range(Box::new(lo), Box::new(hi)))
980 ));
981
David Tolnay89e05672016-10-02 14:39:42 -0700982 named!(capture_by -> CaptureBy, alt!(
983 keyword!("move") => { |_| CaptureBy::Value }
984 |
985 epsilon!() => { |_| CaptureBy::Ref }
986 ));
987
David Tolnay8b07f372016-09-30 10:28:40 -0700988 named!(label -> Ident, map!(lifetime, |lt: Lifetime| lt.ident));
David Tolnayb9c8e322016-09-23 20:48:37 -0700989}
990
David Tolnayf4bbbd92016-09-23 14:41:55 -0700991#[cfg(feature = "printing")]
992mod printing {
993 use super::*;
David Tolnayca085422016-10-04 00:12:38 -0700994 use {FnArg, FunctionRetTy, Mutability, Ty};
David Tolnay13b3d352016-10-03 00:31:15 -0700995 use attr::FilterAttrs;
David Tolnayf4bbbd92016-09-23 14:41:55 -0700996 use quote::{Tokens, ToTokens};
997
998 impl ToTokens for Expr {
999 fn to_tokens(&self, tokens: &mut Tokens) {
1000 match *self {
David Tolnaybb6feae2016-10-02 21:25:20 -07001001 Expr::Box(ref inner) => {
1002 tokens.append("box");
1003 inner.to_tokens(tokens);
1004 }
1005 Expr::Vec(ref tys) => {
1006 tokens.append("[");
1007 tokens.append_separated(tys, ",");
1008 tokens.append("]");
1009 }
David Tolnay9636c052016-10-02 17:11:17 -07001010 Expr::Call(ref func, ref args) => {
1011 func.to_tokens(tokens);
1012 tokens.append("(");
1013 tokens.append_separated(args, ",");
1014 tokens.append(")");
1015 }
1016 Expr::MethodCall(ref ident, ref ascript, ref args) => {
1017 args[0].to_tokens(tokens);
1018 tokens.append(".");
1019 ident.to_tokens(tokens);
1020 if ascript.len() > 0 {
1021 tokens.append("::");
1022 tokens.append("<");
1023 tokens.append_separated(ascript, ",");
1024 tokens.append(">");
1025 }
1026 tokens.append("(");
1027 tokens.append_separated(&args[1..], ",");
1028 tokens.append(")");
1029 }
David Tolnay47a877c2016-10-01 16:50:55 -07001030 Expr::Tup(ref fields) => {
1031 tokens.append("(");
1032 tokens.append_separated(fields, ",");
1033 if fields.len() == 1 {
1034 tokens.append(",");
1035 }
1036 tokens.append(")");
1037 }
David Tolnay89e05672016-10-02 14:39:42 -07001038 Expr::Binary(op, ref left, ref right) => {
1039 left.to_tokens(tokens);
1040 op.to_tokens(tokens);
1041 right.to_tokens(tokens);
1042 }
David Tolnay3c2467c2016-10-02 17:55:08 -07001043 Expr::Unary(op, ref expr) => {
1044 op.to_tokens(tokens);
1045 expr.to_tokens(tokens);
1046 }
David Tolnayf4bbbd92016-09-23 14:41:55 -07001047 Expr::Lit(ref lit) => lit.to_tokens(tokens),
David Tolnay3c2467c2016-10-02 17:55:08 -07001048 Expr::Cast(ref expr, ref ty) => {
1049 expr.to_tokens(tokens);
1050 tokens.append("as");
1051 ty.to_tokens(tokens);
1052 }
1053 Expr::Type(ref expr, ref ty) => {
1054 expr.to_tokens(tokens);
1055 tokens.append(":");
1056 ty.to_tokens(tokens);
1057 }
1058 Expr::If(ref cond, ref then_block, ref else_block) => {
1059 tokens.append("if");
1060 cond.to_tokens(tokens);
1061 then_block.to_tokens(tokens);
1062 if let Some(ref else_block) = *else_block {
1063 tokens.append("else");
1064 else_block.to_tokens(tokens);
1065 }
1066 }
David Tolnay29f9ce12016-10-02 20:58:40 -07001067 Expr::IfLet(ref pat, ref expr, ref then_block, ref else_block) => {
1068 tokens.append("if");
1069 tokens.append("let");
1070 pat.to_tokens(tokens);
1071 tokens.append("=");
1072 expr.to_tokens(tokens);
1073 then_block.to_tokens(tokens);
1074 if let Some(ref else_block) = *else_block {
1075 tokens.append("else");
1076 else_block.to_tokens(tokens);
1077 }
1078 }
David Tolnaybb6feae2016-10-02 21:25:20 -07001079 Expr::While(ref cond, ref body, ref label) => {
1080 if let Some(ref label) = *label {
1081 label.to_tokens(tokens);
1082 tokens.append(":");
1083 }
1084 tokens.append("while");
1085 cond.to_tokens(tokens);
1086 body.to_tokens(tokens);
1087 }
1088 Expr::WhileLet(ref pat, ref expr, ref body, ref label) => {
1089 if let Some(ref label) = *label {
1090 label.to_tokens(tokens);
1091 tokens.append(":");
1092 }
1093 tokens.append("while");
1094 tokens.append("let");
1095 pat.to_tokens(tokens);
1096 tokens.append("=");
1097 expr.to_tokens(tokens);
1098 body.to_tokens(tokens);
1099 }
1100 Expr::ForLoop(ref pat, ref expr, ref body, ref label) => {
1101 if let Some(ref label) = *label {
1102 label.to_tokens(tokens);
1103 tokens.append(":");
1104 }
1105 tokens.append("for");
1106 pat.to_tokens(tokens);
1107 tokens.append("in");
1108 expr.to_tokens(tokens);
1109 body.to_tokens(tokens);
1110 }
1111 Expr::Loop(ref body, ref label) => {
1112 if let Some(ref label) = *label {
1113 label.to_tokens(tokens);
1114 tokens.append(":");
1115 }
1116 tokens.append("loop");
1117 body.to_tokens(tokens);
1118 }
David Tolnayb4ad3b52016-10-01 21:58:13 -07001119 Expr::Match(ref expr, ref arms) => {
1120 tokens.append("match");
1121 expr.to_tokens(tokens);
1122 tokens.append("{");
David Tolnay2165b042016-10-08 00:04:23 -07001123 tokens.append_all(arms);
David Tolnayb4ad3b52016-10-01 21:58:13 -07001124 tokens.append("}");
1125 }
David Tolnay89e05672016-10-02 14:39:42 -07001126 Expr::Closure(capture, ref decl, ref body) => {
1127 capture.to_tokens(tokens);
1128 tokens.append("|");
1129 for (i, input) in decl.inputs.iter().enumerate() {
1130 if i > 0 {
1131 tokens.append(",");
1132 }
David Tolnayca085422016-10-04 00:12:38 -07001133 match *input {
1134 FnArg::Captured(ref pat, Ty::Infer) => {
1135 pat.to_tokens(tokens);
David Tolnaydaaf7742016-10-03 11:11:43 -07001136 }
David Tolnayca085422016-10-04 00:12:38 -07001137 _ => input.to_tokens(tokens),
David Tolnay89e05672016-10-02 14:39:42 -07001138 }
1139 }
1140 tokens.append("|");
1141 match decl.output {
1142 FunctionRetTy::Default => {
1143 if body.stmts.len() == 1 {
1144 if let Stmt::Expr(ref expr) = body.stmts[0] {
1145 expr.to_tokens(tokens);
1146 } else {
1147 body.to_tokens(tokens);
1148 }
1149 } else {
1150 body.to_tokens(tokens);
1151 }
1152 }
1153 FunctionRetTy::Ty(ref ty) => {
1154 tokens.append("->");
1155 ty.to_tokens(tokens);
1156 body.to_tokens(tokens);
1157 }
1158 }
1159 }
1160 Expr::Block(rules, ref block) => {
1161 rules.to_tokens(tokens);
1162 block.to_tokens(tokens);
1163 }
David Tolnaybb6feae2016-10-02 21:25:20 -07001164 Expr::Assign(ref var, ref expr) => {
1165 var.to_tokens(tokens);
1166 tokens.append("=");
1167 expr.to_tokens(tokens);
1168 }
1169 Expr::AssignOp(op, ref var, ref expr) => {
1170 var.to_tokens(tokens);
David Tolnay3cb23a92016-10-07 23:02:21 -07001171 tokens.append(op.assign_op().unwrap());
David Tolnaybb6feae2016-10-02 21:25:20 -07001172 expr.to_tokens(tokens);
1173 }
1174 Expr::Field(ref expr, ref field) => {
1175 expr.to_tokens(tokens);
1176 tokens.append(".");
1177 field.to_tokens(tokens);
1178 }
1179 Expr::TupField(ref expr, field) => {
1180 expr.to_tokens(tokens);
1181 tokens.append(".");
1182 tokens.append(&field.to_string());
1183 }
1184 Expr::Index(ref expr, ref index) => {
1185 expr.to_tokens(tokens);
1186 tokens.append("[");
1187 index.to_tokens(tokens);
1188 tokens.append("]");
1189 }
1190 Expr::Range(ref from, ref to, limits) => {
1191 from.to_tokens(tokens);
1192 match limits {
1193 RangeLimits::HalfOpen => tokens.append(".."),
1194 RangeLimits::Closed => tokens.append("..."),
1195 }
1196 to.to_tokens(tokens);
1197 }
David Tolnay8b308c22016-10-03 01:24:10 -07001198 Expr::Path(None, ref path) => path.to_tokens(tokens),
David Tolnay89e05672016-10-02 14:39:42 -07001199 Expr::Path(Some(ref qself), ref path) => {
1200 tokens.append("<");
1201 qself.ty.to_tokens(tokens);
1202 if qself.position > 0 {
1203 tokens.append("as");
David Tolnaydaaf7742016-10-03 11:11:43 -07001204 for (i, segment) in path.segments
1205 .iter()
1206 .take(qself.position)
1207 .enumerate() {
David Tolnay89e05672016-10-02 14:39:42 -07001208 if i > 0 || path.global {
1209 tokens.append("::");
1210 }
1211 segment.to_tokens(tokens);
1212 }
1213 }
1214 tokens.append(">");
1215 for segment in path.segments.iter().skip(qself.position) {
1216 tokens.append("::");
1217 segment.to_tokens(tokens);
1218 }
1219 }
David Tolnay3c2467c2016-10-02 17:55:08 -07001220 Expr::AddrOf(mutability, ref expr) => {
1221 tokens.append("&");
1222 mutability.to_tokens(tokens);
1223 expr.to_tokens(tokens);
1224 }
1225 Expr::Break(ref opt_label) => {
1226 tokens.append("break");
1227 opt_label.to_tokens(tokens);
1228 }
1229 Expr::Continue(ref opt_label) => {
1230 tokens.append("continue");
1231 opt_label.to_tokens(tokens);
1232 }
David Tolnay42602292016-10-01 22:25:45 -07001233 Expr::Ret(ref opt_expr) => {
1234 tokens.append("return");
1235 opt_expr.to_tokens(tokens);
1236 }
David Tolnaycc3d66e2016-10-02 23:36:05 -07001237 Expr::Mac(ref mac) => mac.to_tokens(tokens),
David Tolnay055a7042016-10-02 19:23:54 -07001238 Expr::Struct(ref path, ref fields, ref base) => {
1239 path.to_tokens(tokens);
1240 tokens.append("{");
1241 tokens.append_separated(fields, ",");
1242 if let Some(ref base) = *base {
1243 if !fields.is_empty() {
1244 tokens.append(",");
1245 }
1246 tokens.append("..");
1247 base.to_tokens(tokens);
1248 }
1249 tokens.append("}");
1250 }
1251 Expr::Repeat(ref expr, ref times) => {
1252 tokens.append("[");
1253 expr.to_tokens(tokens);
1254 tokens.append(";");
1255 times.to_tokens(tokens);
1256 tokens.append("]");
1257 }
David Tolnay89e05672016-10-02 14:39:42 -07001258 Expr::Paren(ref expr) => {
1259 tokens.append("(");
1260 expr.to_tokens(tokens);
1261 tokens.append(")");
1262 }
David Tolnay3c2467c2016-10-02 17:55:08 -07001263 Expr::Try(ref expr) => {
1264 expr.to_tokens(tokens);
1265 tokens.append("?");
1266 }
David Tolnayf4bbbd92016-09-23 14:41:55 -07001267 }
1268 }
1269 }
David Tolnayb4ad3b52016-10-01 21:58:13 -07001270
David Tolnay055a7042016-10-02 19:23:54 -07001271 impl ToTokens for FieldValue {
1272 fn to_tokens(&self, tokens: &mut Tokens) {
1273 self.ident.to_tokens(tokens);
1274 tokens.append(":");
1275 self.expr.to_tokens(tokens);
1276 }
1277 }
1278
David Tolnayb4ad3b52016-10-01 21:58:13 -07001279 impl ToTokens for Arm {
1280 fn to_tokens(&self, tokens: &mut Tokens) {
1281 for attr in &self.attrs {
1282 attr.to_tokens(tokens);
1283 }
1284 tokens.append_separated(&self.pats, "|");
1285 if let Some(ref guard) = self.guard {
1286 tokens.append("if");
1287 guard.to_tokens(tokens);
1288 }
1289 tokens.append("=>");
1290 self.body.to_tokens(tokens);
1291 match *self.body {
David Tolnaydaaf7742016-10-03 11:11:43 -07001292 Expr::Block(_, _) => {
1293 // no comma
1294 }
David Tolnayb4ad3b52016-10-01 21:58:13 -07001295 _ => tokens.append(","),
1296 }
1297 }
1298 }
1299
1300 impl ToTokens for Pat {
1301 fn to_tokens(&self, tokens: &mut Tokens) {
1302 match *self {
1303 Pat::Wild => tokens.append("_"),
1304 Pat::Ident(mode, ref ident, ref subpat) => {
1305 mode.to_tokens(tokens);
1306 ident.to_tokens(tokens);
1307 if let Some(ref subpat) = *subpat {
1308 tokens.append("@");
1309 subpat.to_tokens(tokens);
1310 }
1311 }
David Tolnay8d9e81a2016-10-03 22:36:32 -07001312 Pat::Struct(ref path, ref fields, dots) => {
1313 path.to_tokens(tokens);
1314 tokens.append("{");
1315 tokens.append_separated(fields, ",");
1316 if dots {
1317 if !fields.is_empty() {
1318 tokens.append(",");
1319 }
1320 tokens.append("..");
1321 }
1322 tokens.append("}");
1323 }
David Tolnayaa610942016-10-03 22:22:49 -07001324 Pat::TupleStruct(ref path, ref pats, dotpos) => {
1325 path.to_tokens(tokens);
1326 tokens.append("(");
1327 match dotpos {
1328 Some(pos) => {
1329 if pos > 0 {
1330 tokens.append_separated(&pats[..pos], ",");
1331 tokens.append(",");
1332 }
1333 tokens.append("..");
1334 if pos < pats.len() {
1335 tokens.append(",");
1336 tokens.append_separated(&pats[pos..], ",");
1337 }
1338 }
1339 None => tokens.append_separated(pats, ","),
1340 }
1341 tokens.append(")");
1342 }
David Tolnay8b308c22016-10-03 01:24:10 -07001343 Pat::Path(None, ref path) => path.to_tokens(tokens),
1344 Pat::Path(Some(ref qself), ref path) => {
1345 tokens.append("<");
1346 qself.ty.to_tokens(tokens);
1347 if qself.position > 0 {
1348 tokens.append("as");
David Tolnaydaaf7742016-10-03 11:11:43 -07001349 for (i, segment) in path.segments
1350 .iter()
1351 .take(qself.position)
1352 .enumerate() {
David Tolnay8b308c22016-10-03 01:24:10 -07001353 if i > 0 || path.global {
1354 tokens.append("::");
1355 }
1356 segment.to_tokens(tokens);
1357 }
1358 }
1359 tokens.append(">");
1360 for segment in path.segments.iter().skip(qself.position) {
1361 tokens.append("::");
1362 segment.to_tokens(tokens);
1363 }
1364 }
David Tolnayfbb73232016-10-03 01:00:06 -07001365 Pat::Tuple(ref pats, dotpos) => {
1366 tokens.append("(");
1367 match dotpos {
1368 Some(pos) => {
1369 if pos > 0 {
1370 tokens.append_separated(&pats[..pos], ",");
1371 tokens.append(",");
1372 }
1373 tokens.append("..");
1374 if pos < pats.len() {
1375 tokens.append(",");
1376 tokens.append_separated(&pats[pos..], ",");
1377 }
1378 }
1379 None => tokens.append_separated(pats, ","),
1380 }
1381 tokens.append(")");
1382 }
1383 Pat::Box(ref inner) => {
1384 tokens.append("box");
1385 inner.to_tokens(tokens);
1386 }
David Tolnayffdb97f2016-10-03 01:28:33 -07001387 Pat::Ref(ref target, mutability) => {
1388 tokens.append("&");
1389 mutability.to_tokens(tokens);
1390 target.to_tokens(tokens);
1391 }
David Tolnay8b308c22016-10-03 01:24:10 -07001392 Pat::Lit(ref lit) => lit.to_tokens(tokens),
1393 Pat::Range(ref lo, ref hi) => {
1394 lo.to_tokens(tokens);
1395 tokens.append("...");
1396 hi.to_tokens(tokens);
1397 }
David Tolnay16709ba2016-10-05 23:11:32 -07001398 Pat::Slice(ref _before, ref _dots, ref _after) => unimplemented!(),
David Tolnaycc3d66e2016-10-02 23:36:05 -07001399 Pat::Mac(ref mac) => mac.to_tokens(tokens),
David Tolnayb4ad3b52016-10-01 21:58:13 -07001400 }
1401 }
1402 }
1403
David Tolnay8d9e81a2016-10-03 22:36:32 -07001404 impl ToTokens for FieldPat {
1405 fn to_tokens(&self, tokens: &mut Tokens) {
1406 if !self.is_shorthand {
1407 self.ident.to_tokens(tokens);
1408 tokens.append(":");
1409 }
1410 self.pat.to_tokens(tokens);
1411 }
1412 }
1413
David Tolnayb4ad3b52016-10-01 21:58:13 -07001414 impl ToTokens for BindingMode {
1415 fn to_tokens(&self, tokens: &mut Tokens) {
1416 match *self {
1417 BindingMode::ByRef(Mutability::Immutable) => {
1418 tokens.append("ref");
1419 }
1420 BindingMode::ByRef(Mutability::Mutable) => {
1421 tokens.append("ref");
1422 tokens.append("mut");
1423 }
1424 BindingMode::ByValue(Mutability::Immutable) => {}
1425 BindingMode::ByValue(Mutability::Mutable) => {
1426 tokens.append("mut");
1427 }
1428 }
1429 }
1430 }
David Tolnay42602292016-10-01 22:25:45 -07001431
David Tolnay89e05672016-10-02 14:39:42 -07001432 impl ToTokens for CaptureBy {
1433 fn to_tokens(&self, tokens: &mut Tokens) {
1434 match *self {
1435 CaptureBy::Value => tokens.append("move"),
David Tolnaydaaf7742016-10-03 11:11:43 -07001436 CaptureBy::Ref => {
1437 // nothing
1438 }
David Tolnay89e05672016-10-02 14:39:42 -07001439 }
1440 }
1441 }
1442
David Tolnay42602292016-10-01 22:25:45 -07001443 impl ToTokens for Block {
1444 fn to_tokens(&self, tokens: &mut Tokens) {
David Tolnay42602292016-10-01 22:25:45 -07001445 tokens.append("{");
1446 for stmt in &self.stmts {
1447 stmt.to_tokens(tokens);
1448 }
1449 tokens.append("}");
1450 }
1451 }
1452
1453 impl ToTokens for BlockCheckMode {
1454 fn to_tokens(&self, tokens: &mut Tokens) {
1455 match *self {
David Tolnaydaaf7742016-10-03 11:11:43 -07001456 BlockCheckMode::Default => {
1457 // nothing
1458 }
David Tolnay42602292016-10-01 22:25:45 -07001459 BlockCheckMode::Unsafe => tokens.append("unsafe"),
1460 }
1461 }
1462 }
1463
1464 impl ToTokens for Stmt {
1465 fn to_tokens(&self, tokens: &mut Tokens) {
1466 match *self {
David Tolnay191e0582016-10-02 18:31:09 -07001467 Stmt::Local(ref local) => local.to_tokens(tokens),
David Tolnay42602292016-10-01 22:25:45 -07001468 Stmt::Item(ref item) => item.to_tokens(tokens),
1469 Stmt::Expr(ref expr) => expr.to_tokens(tokens),
1470 Stmt::Semi(ref expr) => {
1471 expr.to_tokens(tokens);
1472 tokens.append(";");
1473 }
David Tolnay13b3d352016-10-03 00:31:15 -07001474 Stmt::Mac(ref mac) => {
1475 let (ref mac, style, ref attrs) = **mac;
1476 for attr in attrs.outer() {
1477 attr.to_tokens(tokens);
1478 }
1479 mac.to_tokens(tokens);
1480 match style {
1481 MacStmtStyle::Semicolon => tokens.append(";"),
David Tolnaydaaf7742016-10-03 11:11:43 -07001482 MacStmtStyle::Braces | MacStmtStyle::NoBraces => {
1483 // no semicolon
1484 }
David Tolnay13b3d352016-10-03 00:31:15 -07001485 }
1486 }
David Tolnay42602292016-10-01 22:25:45 -07001487 }
1488 }
1489 }
David Tolnay191e0582016-10-02 18:31:09 -07001490
1491 impl ToTokens for Local {
1492 fn to_tokens(&self, tokens: &mut Tokens) {
1493 tokens.append("let");
1494 self.pat.to_tokens(tokens);
1495 if let Some(ref ty) = self.ty {
1496 tokens.append(":");
1497 ty.to_tokens(tokens);
1498 }
1499 if let Some(ref init) = self.init {
1500 tokens.append("=");
1501 init.to_tokens(tokens);
1502 }
1503 tokens.append(";");
1504 }
1505 }
David Tolnayf4bbbd92016-09-23 14:41:55 -07001506}