blob: 8a41b428724839be083a11a14c1cb2170e6d72a4 [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 Tolnay438c9052016-10-07 23:24:48 -0700298 use lit::parsing::{digits, 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 Tolnay438c9052016-10-07 23:24:48 -0700301 use op::parsing::{assign_op, 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 |
David Tolnay438c9052016-10-07 23:24:48 -0700342 expr_range
343 |
David Tolnay89e05672016-10-02 14:39:42 -0700344 expr_path
David Tolnay3c2467c2016-10-02 17:55:08 -0700345 |
346 expr_addr_of
Gregory Katzfd6935d2016-09-30 22:51:25 -0400347 |
David Tolnay055a7042016-10-02 19:23:54 -0700348 expr_repeat
David Tolnayfa0edf22016-09-23 22:58:24 -0700349 ) >>
350 many0!(alt!(
David Tolnay939766a2016-09-23 23:48:12 -0700351 tap!(args: and_call => {
352 e = Expr::Call(Box::new(e), args);
David Tolnayfa0edf22016-09-23 22:58:24 -0700353 })
354 |
David Tolnay939766a2016-09-23 23:48:12 -0700355 tap!(more: and_method_call => {
356 let (method, ascript, mut args) = more;
David Tolnayfa0edf22016-09-23 22:58:24 -0700357 args.insert(0, e);
358 e = Expr::MethodCall(method, ascript, args);
359 })
360 |
David Tolnay939766a2016-09-23 23:48:12 -0700361 tap!(more: and_binary => {
362 let (op, other) = more;
David Tolnayfa0edf22016-09-23 22:58:24 -0700363 e = Expr::Binary(op, Box::new(e), Box::new(other));
364 })
David Tolnay939766a2016-09-23 23:48:12 -0700365 |
366 tap!(ty: and_cast => {
367 e = Expr::Cast(Box::new(e), Box::new(ty));
368 })
369 |
370 tap!(ty: and_ascription => {
371 e = Expr::Type(Box::new(e), Box::new(ty));
372 })
David Tolnay438c9052016-10-07 23:24:48 -0700373 |
374 tap!(v: and_assign => {
375 e = Expr::Assign(Box::new(e), Box::new(v));
376 })
377 |
378 tap!(more: and_assign_op => {
379 let (op, v) = more;
380 e = Expr::AssignOp(op, Box::new(e), Box::new(v));
381 })
382 |
383 tap!(field: and_field => {
384 e = Expr::Field(Box::new(e), field);
385 })
386 |
387 tap!(field: and_tup_field => {
388 e = Expr::TupField(Box::new(e), field as usize);
389 })
390 |
391 tap!(i: and_index => {
392 e = Expr::Index(Box::new(e), Box::new(i));
393 })
394 |
395 tap!(more: and_range => {
396 let (limits, hi) = more;
397 e = Expr::Range(Some(Box::new(e)), hi.map(Box::new), limits);
398 })
David Tolnay055a7042016-10-02 19:23:54 -0700399 |
400 tap!(_try: punct!("?") => {
401 e = Expr::Try(Box::new(e));
402 })
David Tolnayfa0edf22016-09-23 22:58:24 -0700403 )) >>
404 (e)
David Tolnayb9c8e322016-09-23 20:48:37 -0700405 ));
406
David Tolnay84aa0752016-10-02 23:01:13 -0700407 named!(expr_mac -> Expr, map!(mac, Expr::Mac));
408
David Tolnay89e05672016-10-02 14:39:42 -0700409 named!(expr_paren -> Expr, do_parse!(
410 punct!("(") >>
411 e: expr >>
412 punct!(")") >>
413 (Expr::Paren(Box::new(e)))
414 ));
415
David Tolnay939766a2016-09-23 23:48:12 -0700416 named!(expr_box -> Expr, do_parse!(
David Tolnay10413f02016-09-30 09:12:02 -0700417 keyword!("box") >>
David Tolnayb9c8e322016-09-23 20:48:37 -0700418 inner: expr >>
419 (Expr::Box(Box::new(inner)))
420 ));
David Tolnayfa0edf22016-09-23 22:58:24 -0700421
David Tolnay939766a2016-09-23 23:48:12 -0700422 named!(expr_vec -> Expr, do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700423 punct!("[") >>
424 elems: separated_list!(punct!(","), expr) >>
David Tolnayf6c74402016-10-08 02:31:26 -0700425 cond!(!elems.is_empty(), option!(punct!(","))) >>
David Tolnayfa0edf22016-09-23 22:58:24 -0700426 punct!("]") >>
427 (Expr::Vec(elems))
428 ));
429
David Tolnay939766a2016-09-23 23:48:12 -0700430 named!(and_call -> Vec<Expr>, do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700431 punct!("(") >>
432 args: separated_list!(punct!(","), expr) >>
David Tolnayf6c74402016-10-08 02:31:26 -0700433 cond!(!args.is_empty(), option!(punct!(","))) >>
David Tolnayfa0edf22016-09-23 22:58:24 -0700434 punct!(")") >>
435 (args)
436 ));
437
David Tolnay939766a2016-09-23 23:48:12 -0700438 named!(and_method_call -> (Ident, Vec<Ty>, Vec<Expr>), do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700439 punct!(".") >>
440 method: ident >>
David Tolnayf6c74402016-10-08 02:31:26 -0700441 ascript: opt_vec!(preceded!(
442 punct!("::"),
443 delimited!(
444 punct!("<"),
445 separated_list!(punct!(","), ty),
446 punct!(">")
447 )
David Tolnayfa0edf22016-09-23 22:58:24 -0700448 )) >>
449 punct!("(") >>
450 args: separated_list!(punct!(","), expr) >>
David Tolnayf6c74402016-10-08 02:31:26 -0700451 cond!(!args.is_empty(), option!(punct!(","))) >>
David Tolnayfa0edf22016-09-23 22:58:24 -0700452 punct!(")") >>
453 (method, ascript, args)
454 ));
455
David Tolnay939766a2016-09-23 23:48:12 -0700456 named!(expr_tup -> Expr, do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700457 punct!("(") >>
458 elems: separated_list!(punct!(","), expr) >>
David Tolnayf6c74402016-10-08 02:31:26 -0700459 cond!(!elems.is_empty(), option!(punct!(","))) >>
David Tolnayfa0edf22016-09-23 22:58:24 -0700460 punct!(")") >>
461 (Expr::Tup(elems))
462 ));
463
David Tolnay3cb23a92016-10-07 23:02:21 -0700464 named!(and_binary -> (BinOp, Expr), tuple!(binop, expr));
David Tolnayfa0edf22016-09-23 22:58:24 -0700465
David Tolnay939766a2016-09-23 23:48:12 -0700466 named!(expr_unary -> Expr, do_parse!(
David Tolnay3cb23a92016-10-07 23:02:21 -0700467 operator: unop >>
David Tolnayfa0edf22016-09-23 22:58:24 -0700468 operand: expr >>
469 (Expr::Unary(operator, Box::new(operand)))
470 ));
David Tolnay939766a2016-09-23 23:48:12 -0700471
472 named!(expr_lit -> Expr, map!(lit, Expr::Lit));
473
474 named!(and_cast -> Ty, do_parse!(
David Tolnay10413f02016-09-30 09:12:02 -0700475 keyword!("as") >>
David Tolnay939766a2016-09-23 23:48:12 -0700476 ty: ty >>
477 (ty)
478 ));
479
480 named!(and_ascription -> Ty, preceded!(punct!(":"), ty));
481
David Tolnaybb6feae2016-10-02 21:25:20 -0700482 enum Cond {
David Tolnay29f9ce12016-10-02 20:58:40 -0700483 Let(Pat, Expr),
484 Expr(Expr),
485 }
486
David Tolnaybb6feae2016-10-02 21:25:20 -0700487 named!(cond -> Cond, alt!(
488 do_parse!(
489 keyword!("let") >>
490 pat: pat >>
491 punct!("=") >>
492 value: expr >>
493 (Cond::Let(pat, value))
494 )
495 |
496 map!(expr, Cond::Expr)
497 ));
498
David Tolnay939766a2016-09-23 23:48:12 -0700499 named!(expr_if -> Expr, do_parse!(
David Tolnay10413f02016-09-30 09:12:02 -0700500 keyword!("if") >>
David Tolnaybb6feae2016-10-02 21:25:20 -0700501 cond: cond >>
David Tolnay939766a2016-09-23 23:48:12 -0700502 punct!("{") >>
503 then_block: within_block >>
504 punct!("}") >>
505 else_block: option!(preceded!(
David Tolnay10413f02016-09-30 09:12:02 -0700506 keyword!("else"),
David Tolnay939766a2016-09-23 23:48:12 -0700507 alt!(
508 expr_if
509 |
510 do_parse!(
511 punct!("{") >>
512 else_block: within_block >>
513 punct!("}") >>
David Tolnay89e05672016-10-02 14:39:42 -0700514 (Expr::Block(BlockCheckMode::Default, Block {
David Tolnay939766a2016-09-23 23:48:12 -0700515 stmts: else_block,
David Tolnay89e05672016-10-02 14:39:42 -0700516 }))
David Tolnay939766a2016-09-23 23:48:12 -0700517 )
518 )
519 )) >>
David Tolnay29f9ce12016-10-02 20:58:40 -0700520 (match cond {
David Tolnaybb6feae2016-10-02 21:25:20 -0700521 Cond::Let(pat, expr) => Expr::IfLet(
David Tolnay29f9ce12016-10-02 20:58:40 -0700522 Box::new(pat),
523 Box::new(expr),
524 Block {
525 stmts: then_block,
526 },
527 else_block.map(Box::new),
528 ),
David Tolnaybb6feae2016-10-02 21:25:20 -0700529 Cond::Expr(cond) => Expr::If(
David Tolnay29f9ce12016-10-02 20:58:40 -0700530 Box::new(cond),
531 Block {
532 stmts: then_block,
533 },
534 else_block.map(Box::new),
535 ),
536 })
David Tolnay939766a2016-09-23 23:48:12 -0700537 ));
538
David Tolnaybb6feae2016-10-02 21:25:20 -0700539 named!(expr_for_loop -> Expr, do_parse!(
540 lbl: option!(terminated!(label, punct!(":"))) >>
541 keyword!("for") >>
542 pat: pat >>
543 keyword!("in") >>
544 expr: expr >>
545 loop_block: block >>
546 (Expr::ForLoop(Box::new(pat), Box::new(expr), loop_block, lbl))
547 ));
548
Gregory Katze5f35682016-09-27 14:20:55 -0400549 named!(expr_loop -> Expr, do_parse!(
David Tolnay8b07f372016-09-30 10:28:40 -0700550 lbl: option!(terminated!(label, punct!(":"))) >>
David Tolnay10413f02016-09-30 09:12:02 -0700551 keyword!("loop") >>
Gregory Katze5f35682016-09-27 14:20:55 -0400552 loop_block: block >>
David Tolnay89e05672016-10-02 14:39:42 -0700553 (Expr::Loop(loop_block, lbl))
Gregory Katze5f35682016-09-27 14:20:55 -0400554 ));
555
David Tolnayb4ad3b52016-10-01 21:58:13 -0700556 named!(expr_match -> Expr, do_parse!(
557 keyword!("match") >>
558 obj: expr >>
559 punct!("{") >>
560 arms: many0!(do_parse!(
561 attrs: many0!(outer_attr) >>
562 pats: separated_nonempty_list!(punct!("|"), pat) >>
563 guard: option!(preceded!(keyword!("if"), expr)) >>
564 punct!("=>") >>
565 body: alt!(
David Tolnay89e05672016-10-02 14:39:42 -0700566 map!(block, |blk| Expr::Block(BlockCheckMode::Default, blk))
David Tolnayf6c74402016-10-08 02:31:26 -0700567 |
568 expr
David Tolnayb4ad3b52016-10-01 21:58:13 -0700569 ) >>
David Tolnayf6c74402016-10-08 02:31:26 -0700570 option!(punct!(",")) >>
David Tolnayb4ad3b52016-10-01 21:58:13 -0700571 (Arm {
572 attrs: attrs,
573 pats: pats,
574 guard: guard.map(Box::new),
575 body: Box::new(body),
576 })
577 )) >>
578 punct!("}") >>
579 (Expr::Match(Box::new(obj), arms))
580 ));
581
David Tolnay89e05672016-10-02 14:39:42 -0700582 named!(expr_closure -> Expr, do_parse!(
583 capture: capture_by >>
584 punct!("|") >>
585 inputs: separated_list!(punct!(","), closure_arg) >>
David Tolnayf6c74402016-10-08 02:31:26 -0700586 cond!(!inputs.is_empty(), option!(punct!(","))) >>
David Tolnay89e05672016-10-02 14:39:42 -0700587 punct!("|") >>
588 ret_and_body: alt!(
589 do_parse!(
590 punct!("->") >>
591 ty: ty >>
592 body: block >>
593 ((FunctionRetTy::Ty(ty), body))
594 )
595 |
596 map!(expr, |e| (
597 FunctionRetTy::Default,
598 Block {
599 stmts: vec![Stmt::Expr(Box::new(e))],
600 },
601 ))
602 ) >>
603 (Expr::Closure(
604 capture,
605 Box::new(FnDecl {
606 inputs: inputs,
607 output: ret_and_body.0,
608 }),
609 ret_and_body.1,
610 ))
611 ));
612
613 named!(closure_arg -> FnArg, do_parse!(
614 pat: pat >>
615 ty: option!(preceded!(punct!(":"), ty)) >>
David Tolnayca085422016-10-04 00:12:38 -0700616 (FnArg::Captured(pat, ty.unwrap_or(Ty::Infer)))
David Tolnay89e05672016-10-02 14:39:42 -0700617 ));
618
Gregory Katz3e562cc2016-09-28 18:33:02 -0400619 named!(expr_while -> Expr, do_parse!(
David Tolnay8b07f372016-09-30 10:28:40 -0700620 lbl: option!(terminated!(label, punct!(":"))) >>
David Tolnay57ffbde2016-09-30 09:38:04 -0700621 keyword!("while") >>
David Tolnaybb6feae2016-10-02 21:25:20 -0700622 cond: cond >>
Gregory Katz3e562cc2016-09-28 18:33:02 -0400623 while_block: block >>
David Tolnaybb6feae2016-10-02 21:25:20 -0700624 (match cond {
625 Cond::Let(pat, expr) => Expr::WhileLet(
626 Box::new(pat),
627 Box::new(expr),
628 while_block,
629 lbl,
630 ),
631 Cond::Expr(cond) => Expr::While(
632 Box::new(cond),
633 while_block,
634 lbl,
635 ),
636 })
Gregory Katz3e562cc2016-09-28 18:33:02 -0400637 ));
638
Gregory Katzfd6935d2016-09-30 22:51:25 -0400639 named!(expr_continue -> Expr, do_parse!(
640 keyword!("continue") >>
641 lbl: option!(label) >>
David Tolnay055a7042016-10-02 19:23:54 -0700642 (Expr::Continue(lbl))
Gregory Katzfd6935d2016-09-30 22:51:25 -0400643 ));
644
645 named!(expr_break -> Expr, do_parse!(
646 keyword!("break") >>
647 lbl: option!(label) >>
David Tolnay055a7042016-10-02 19:23:54 -0700648 (Expr::Break(lbl))
Gregory Katzfd6935d2016-09-30 22:51:25 -0400649 ));
650
651 named!(expr_ret -> Expr, do_parse!(
652 keyword!("return") >>
653 ret_value: option!(expr) >>
David Tolnay055a7042016-10-02 19:23:54 -0700654 (Expr::Ret(ret_value.map(Box::new)))
655 ));
656
657 named!(expr_struct -> Expr, do_parse!(
658 path: path >>
659 punct!("{") >>
660 fields: separated_list!(punct!(","), field_value) >>
661 base: option!(do_parse!(
662 cond!(!fields.is_empty(), punct!(",")) >>
663 punct!("..") >>
664 base: expr >>
665 (base)
666 )) >>
David Tolnayf6c74402016-10-08 02:31:26 -0700667 cond!(!fields.is_empty() && base.is_none(), option!(punct!(","))) >>
David Tolnay055a7042016-10-02 19:23:54 -0700668 punct!("}") >>
669 (Expr::Struct(path, fields, base.map(Box::new)))
670 ));
671
672 named!(field_value -> FieldValue, do_parse!(
673 name: ident >>
674 punct!(":") >>
675 value: expr >>
676 (FieldValue {
677 ident: name,
678 expr: value,
679 })
680 ));
681
682 named!(expr_repeat -> Expr, do_parse!(
683 punct!("[") >>
684 value: expr >>
685 punct!(";") >>
686 times: expr >>
687 punct!("]") >>
688 (Expr::Repeat(Box::new(value), Box::new(times)))
Gregory Katzfd6935d2016-09-30 22:51:25 -0400689 ));
690
David Tolnay42602292016-10-01 22:25:45 -0700691 named!(expr_block -> Expr, do_parse!(
David Tolnay939766a2016-09-23 23:48:12 -0700692 rules: block_check_mode >>
David Tolnay42602292016-10-01 22:25:45 -0700693 b: block >>
David Tolnay89e05672016-10-02 14:39:42 -0700694 (Expr::Block(rules, Block {
David Tolnay42602292016-10-01 22:25:45 -0700695 stmts: b.stmts,
David Tolnay89e05672016-10-02 14:39:42 -0700696 }))
697 ));
698
David Tolnay438c9052016-10-07 23:24:48 -0700699 named!(expr_range -> Expr, do_parse!(
700 limits: range_limits >>
701 hi: option!(expr) >>
702 (Expr::Range(None, hi.map(Box::new), limits))
703 ));
704
705 named!(range_limits -> RangeLimits, alt!(
706 punct!("...") => { |_| RangeLimits::Closed }
707 |
708 punct!("..") => { |_| RangeLimits::HalfOpen }
709 ));
710
David Tolnay9636c052016-10-02 17:11:17 -0700711 named!(expr_path -> Expr, map!(qpath, |(qself, path)| Expr::Path(qself, path)));
David Tolnay42602292016-10-01 22:25:45 -0700712
David Tolnay3c2467c2016-10-02 17:55:08 -0700713 named!(expr_addr_of -> Expr, do_parse!(
714 punct!("&") >>
715 mutability: mutability >>
716 expr: expr >>
717 (Expr::AddrOf(mutability, Box::new(expr)))
718 ));
719
David Tolnay438c9052016-10-07 23:24:48 -0700720 named!(and_assign -> Expr, preceded!(punct!("="), expr));
721
722 named!(and_assign_op -> (BinOp, Expr), tuple!(assign_op, expr));
723
724 named!(and_field -> Ident, preceded!(punct!("."), ident));
725
726 named!(and_tup_field -> u64, preceded!(punct!("."), digits));
727
728 named!(and_index -> Expr, delimited!(punct!("["), expr, punct!("]")));
729
730 named!(and_range -> (RangeLimits, Option<Expr>), tuple!(range_limits, option!(expr)));
731
David Tolnay42602292016-10-01 22:25:45 -0700732 named!(pub block -> Block, do_parse!(
David Tolnay939766a2016-09-23 23:48:12 -0700733 punct!("{") >>
734 stmts: within_block >>
735 punct!("}") >>
736 (Block {
737 stmts: stmts,
David Tolnay939766a2016-09-23 23:48:12 -0700738 })
739 ));
740
741 named!(block_check_mode -> BlockCheckMode, alt!(
David Tolnay10413f02016-09-30 09:12:02 -0700742 keyword!("unsafe") => { |_| BlockCheckMode::Unsafe }
David Tolnay939766a2016-09-23 23:48:12 -0700743 |
744 epsilon!() => { |_| BlockCheckMode::Default }
745 ));
746
747 named!(within_block -> Vec<Stmt>, do_parse!(
David Tolnaycfe55022016-10-02 22:02:27 -0700748 many0!(punct!(";")) >>
749 mut standalone: many0!(terminated!(standalone_stmt, many0!(punct!(";")))) >>
David Tolnay939766a2016-09-23 23:48:12 -0700750 last: option!(expr) >>
751 (match last {
David Tolnaycfe55022016-10-02 22:02:27 -0700752 None => standalone,
David Tolnay939766a2016-09-23 23:48:12 -0700753 Some(last) => {
David Tolnaycfe55022016-10-02 22:02:27 -0700754 standalone.push(Stmt::Expr(Box::new(last)));
755 standalone
David Tolnay939766a2016-09-23 23:48:12 -0700756 }
757 })
758 ));
759
760 named!(standalone_stmt -> Stmt, alt!(
David Tolnay13b3d352016-10-03 00:31:15 -0700761 stmt_mac
762 |
David Tolnay191e0582016-10-02 18:31:09 -0700763 stmt_local
764 |
765 stmt_item
766 |
David Tolnaycfe55022016-10-02 22:02:27 -0700767 stmt_expr
David Tolnay939766a2016-09-23 23:48:12 -0700768 ));
769
David Tolnay13b3d352016-10-03 00:31:15 -0700770 named!(stmt_mac -> Stmt, do_parse!(
771 attrs: many0!(outer_attr) >>
772 mac: mac >>
773 semi: option!(punct!(";")) >>
774 ({
775 let style = if semi.is_some() {
776 MacStmtStyle::Semicolon
777 } else if let Some(&TokenTree::Delimited(Delimited { delim, .. })) = mac.tts.last() {
778 match delim {
779 DelimToken::Paren | DelimToken::Bracket => MacStmtStyle::NoBraces,
780 DelimToken::Brace => MacStmtStyle::Braces,
781 }
782 } else {
783 MacStmtStyle::NoBraces
784 };
785 Stmt::Mac(Box::new((mac, style, attrs)))
786 })
787 ));
788
David Tolnay191e0582016-10-02 18:31:09 -0700789 named!(stmt_local -> Stmt, do_parse!(
790 attrs: many0!(outer_attr) >>
791 keyword!("let") >>
792 pat: pat >>
793 ty: option!(preceded!(punct!(":"), ty)) >>
794 init: option!(preceded!(punct!("="), expr)) >>
795 punct!(";") >>
796 (Stmt::Local(Box::new(Local {
797 pat: Box::new(pat),
798 ty: ty.map(Box::new),
799 init: init.map(Box::new),
800 attrs: attrs,
801 })))
802 ));
803
804 named!(stmt_item -> Stmt, map!(item, |i| Stmt::Item(Box::new(i))));
805
David Tolnaycfe55022016-10-02 22:02:27 -0700806 fn requires_semi(e: &Expr) -> bool {
807 match *e {
David Tolnaycfe55022016-10-02 22:02:27 -0700808 Expr::If(_, _, _) |
809 Expr::IfLet(_, _, _, _) |
810 Expr::While(_, _, _) |
811 Expr::WhileLet(_, _, _, _) |
812 Expr::ForLoop(_, _, _, _) |
813 Expr::Loop(_, _) |
814 Expr::Match(_, _) |
815 Expr::Block(_, _) => false,
816
817 _ => true,
818 }
819 }
820
821 named!(stmt_expr -> Stmt, do_parse!(
David Tolnay939766a2016-09-23 23:48:12 -0700822 e: expr >>
David Tolnaycfe55022016-10-02 22:02:27 -0700823 semi: option!(punct!(";")) >>
824 (if semi.is_some() {
825 Stmt::Semi(Box::new(e))
826 } else if requires_semi(&e) {
827 return Error;
828 } else {
829 Stmt::Expr(Box::new(e))
830 })
David Tolnay939766a2016-09-23 23:48:12 -0700831 ));
David Tolnay8b07f372016-09-30 10:28:40 -0700832
David Tolnay42602292016-10-01 22:25:45 -0700833 named!(pub pat -> Pat, alt!(
David Tolnayfbb73232016-10-03 01:00:06 -0700834 pat_wild // must be before pat_ident
835 |
836 pat_box // must be before pat_ident
David Tolnayb4ad3b52016-10-01 21:58:13 -0700837 |
David Tolnay8b308c22016-10-03 01:24:10 -0700838 pat_range // must be before pat_lit
839 |
David Tolnayaa610942016-10-03 22:22:49 -0700840 pat_tuple_struct // must be before pat_ident
841 |
David Tolnay8d9e81a2016-10-03 22:36:32 -0700842 pat_struct // must be before pat_ident
843 |
David Tolnayaa610942016-10-03 22:22:49 -0700844 pat_mac // must be before pat_ident
845 |
David Tolnay8b308c22016-10-03 01:24:10 -0700846 pat_ident // must be before pat_path
David Tolnay9636c052016-10-02 17:11:17 -0700847 |
848 pat_path
David Tolnayfbb73232016-10-03 01:00:06 -0700849 |
850 pat_tuple
David Tolnayffdb97f2016-10-03 01:28:33 -0700851 |
852 pat_ref
David Tolnay8b308c22016-10-03 01:24:10 -0700853 |
854 pat_lit
David Tolnaydaaf7742016-10-03 11:11:43 -0700855 // TODO: Vec
David Tolnayb4ad3b52016-10-01 21:58:13 -0700856 ));
857
David Tolnay84aa0752016-10-02 23:01:13 -0700858 named!(pat_mac -> Pat, map!(mac, Pat::Mac));
859
David Tolnayb4ad3b52016-10-01 21:58:13 -0700860 named!(pat_wild -> Pat, map!(keyword!("_"), |_| Pat::Wild));
861
David Tolnayfbb73232016-10-03 01:00:06 -0700862 named!(pat_box -> Pat, do_parse!(
863 keyword!("box") >>
864 pat: pat >>
865 (Pat::Box(Box::new(pat)))
866 ));
867
David Tolnayb4ad3b52016-10-01 21:58:13 -0700868 named!(pat_ident -> Pat, do_parse!(
869 mode: option!(keyword!("ref")) >>
870 mutability: mutability >>
871 name: ident >>
David Tolnay8b308c22016-10-03 01:24:10 -0700872 not!(peek!(punct!("<"))) >>
873 not!(peek!(punct!("::"))) >>
David Tolnayb4ad3b52016-10-01 21:58:13 -0700874 subpat: option!(preceded!(punct!("@"), pat)) >>
875 (Pat::Ident(
876 if mode.is_some() {
877 BindingMode::ByRef(mutability)
878 } else {
879 BindingMode::ByValue(mutability)
880 },
881 name,
882 subpat.map(Box::new),
883 ))
884 ));
885
David Tolnayaa610942016-10-03 22:22:49 -0700886 named!(pat_tuple_struct -> Pat, do_parse!(
887 path: path >>
888 tuple: pat_tuple_helper >>
889 (Pat::TupleStruct(path, tuple.0, tuple.1))
890 ));
891
David Tolnay8d9e81a2016-10-03 22:36:32 -0700892 named!(pat_struct -> Pat, do_parse!(
893 path: path >>
894 punct!("{") >>
895 fields: separated_list!(punct!(","), field_pat) >>
896 more: option!(preceded!(
897 cond!(!fields.is_empty(), punct!(",")),
898 punct!("..")
899 )) >>
900 punct!("}") >>
901 (Pat::Struct(path, fields, more.is_some()))
902 ));
903
904 named!(field_pat -> FieldPat, alt!(
905 do_parse!(
906 ident: ident >>
907 punct!(":") >>
908 pat: pat >>
909 (FieldPat {
910 ident: ident,
911 pat: Box::new(pat),
912 is_shorthand: false,
913 })
914 )
915 |
916 do_parse!(
917 mode: option!(keyword!("ref")) >>
918 mutability: mutability >>
919 ident: ident >>
920 (FieldPat {
921 ident: ident.clone(),
922 pat: Box::new(Pat::Ident(
923 if mode.is_some() {
924 BindingMode::ByRef(mutability)
925 } else {
926 BindingMode::ByValue(mutability)
927 },
928 ident,
929 None,
930 )),
931 is_shorthand: true,
932 })
933 )
934 ));
935
David Tolnay9636c052016-10-02 17:11:17 -0700936 named!(pat_path -> Pat, map!(qpath, |(qself, path)| Pat::Path(qself, path)));
937
David Tolnayaa610942016-10-03 22:22:49 -0700938 named!(pat_tuple -> Pat, map!(
939 pat_tuple_helper,
940 |(pats, dotdot)| Pat::Tuple(pats, dotdot)
941 ));
942
943 named!(pat_tuple_helper -> (Vec<Pat>, Option<usize>), do_parse!(
David Tolnayfbb73232016-10-03 01:00:06 -0700944 punct!("(") >>
945 mut elems: separated_list!(punct!(","), pat) >>
946 dotdot: option!(do_parse!(
947 cond!(!elems.is_empty(), punct!(",")) >>
948 punct!("..") >>
949 rest: many0!(preceded!(punct!(","), pat)) >>
950 cond!(!rest.is_empty(), option!(punct!(","))) >>
951 (rest)
952 )) >>
953 cond!(!elems.is_empty() && dotdot.is_none(), option!(punct!(","))) >>
954 punct!(")") >>
955 (match dotdot {
956 Some(rest) => {
957 let pos = elems.len();
958 elems.extend(rest);
David Tolnayaa610942016-10-03 22:22:49 -0700959 (elems, Some(pos))
David Tolnayfbb73232016-10-03 01:00:06 -0700960 }
David Tolnayaa610942016-10-03 22:22:49 -0700961 None => (elems, None),
David Tolnayfbb73232016-10-03 01:00:06 -0700962 })
963 ));
964
David Tolnayffdb97f2016-10-03 01:28:33 -0700965 named!(pat_ref -> Pat, do_parse!(
966 punct!("&") >>
967 mutability: mutability >>
968 pat: pat >>
969 (Pat::Ref(Box::new(pat), mutability))
970 ));
971
David Tolnay8b308c22016-10-03 01:24:10 -0700972 named!(pat_lit -> Pat, map!(lit, |lit| Pat::Lit(Box::new(lit))));
973
974 named!(pat_range -> Pat, do_parse!(
975 lo: lit >>
976 punct!("...") >>
977 hi: lit >>
978 (Pat::Range(Box::new(lo), Box::new(hi)))
979 ));
980
David Tolnay89e05672016-10-02 14:39:42 -0700981 named!(capture_by -> CaptureBy, alt!(
982 keyword!("move") => { |_| CaptureBy::Value }
983 |
984 epsilon!() => { |_| CaptureBy::Ref }
985 ));
986
David Tolnay8b07f372016-09-30 10:28:40 -0700987 named!(label -> Ident, map!(lifetime, |lt: Lifetime| lt.ident));
David Tolnayb9c8e322016-09-23 20:48:37 -0700988}
989
David Tolnayf4bbbd92016-09-23 14:41:55 -0700990#[cfg(feature = "printing")]
991mod printing {
992 use super::*;
David Tolnayca085422016-10-04 00:12:38 -0700993 use {FnArg, FunctionRetTy, Mutability, Ty};
David Tolnay13b3d352016-10-03 00:31:15 -0700994 use attr::FilterAttrs;
David Tolnayf4bbbd92016-09-23 14:41:55 -0700995 use quote::{Tokens, ToTokens};
996
997 impl ToTokens for Expr {
998 fn to_tokens(&self, tokens: &mut Tokens) {
999 match *self {
David Tolnaybb6feae2016-10-02 21:25:20 -07001000 Expr::Box(ref inner) => {
1001 tokens.append("box");
1002 inner.to_tokens(tokens);
1003 }
1004 Expr::Vec(ref tys) => {
1005 tokens.append("[");
1006 tokens.append_separated(tys, ",");
1007 tokens.append("]");
1008 }
David Tolnay9636c052016-10-02 17:11:17 -07001009 Expr::Call(ref func, ref args) => {
1010 func.to_tokens(tokens);
1011 tokens.append("(");
1012 tokens.append_separated(args, ",");
1013 tokens.append(")");
1014 }
1015 Expr::MethodCall(ref ident, ref ascript, ref args) => {
1016 args[0].to_tokens(tokens);
1017 tokens.append(".");
1018 ident.to_tokens(tokens);
1019 if ascript.len() > 0 {
1020 tokens.append("::");
1021 tokens.append("<");
1022 tokens.append_separated(ascript, ",");
1023 tokens.append(">");
1024 }
1025 tokens.append("(");
1026 tokens.append_separated(&args[1..], ",");
1027 tokens.append(")");
1028 }
David Tolnay47a877c2016-10-01 16:50:55 -07001029 Expr::Tup(ref fields) => {
1030 tokens.append("(");
1031 tokens.append_separated(fields, ",");
1032 if fields.len() == 1 {
1033 tokens.append(",");
1034 }
1035 tokens.append(")");
1036 }
David Tolnay89e05672016-10-02 14:39:42 -07001037 Expr::Binary(op, ref left, ref right) => {
1038 left.to_tokens(tokens);
1039 op.to_tokens(tokens);
1040 right.to_tokens(tokens);
1041 }
David Tolnay3c2467c2016-10-02 17:55:08 -07001042 Expr::Unary(op, ref expr) => {
1043 op.to_tokens(tokens);
1044 expr.to_tokens(tokens);
1045 }
David Tolnayf4bbbd92016-09-23 14:41:55 -07001046 Expr::Lit(ref lit) => lit.to_tokens(tokens),
David Tolnay3c2467c2016-10-02 17:55:08 -07001047 Expr::Cast(ref expr, ref ty) => {
1048 expr.to_tokens(tokens);
1049 tokens.append("as");
1050 ty.to_tokens(tokens);
1051 }
1052 Expr::Type(ref expr, ref ty) => {
1053 expr.to_tokens(tokens);
1054 tokens.append(":");
1055 ty.to_tokens(tokens);
1056 }
1057 Expr::If(ref cond, ref then_block, ref else_block) => {
1058 tokens.append("if");
1059 cond.to_tokens(tokens);
1060 then_block.to_tokens(tokens);
1061 if let Some(ref else_block) = *else_block {
1062 tokens.append("else");
1063 else_block.to_tokens(tokens);
1064 }
1065 }
David Tolnay29f9ce12016-10-02 20:58:40 -07001066 Expr::IfLet(ref pat, ref expr, ref then_block, ref else_block) => {
1067 tokens.append("if");
1068 tokens.append("let");
1069 pat.to_tokens(tokens);
1070 tokens.append("=");
1071 expr.to_tokens(tokens);
1072 then_block.to_tokens(tokens);
1073 if let Some(ref else_block) = *else_block {
1074 tokens.append("else");
1075 else_block.to_tokens(tokens);
1076 }
1077 }
David Tolnaybb6feae2016-10-02 21:25:20 -07001078 Expr::While(ref cond, ref body, ref label) => {
1079 if let Some(ref label) = *label {
1080 label.to_tokens(tokens);
1081 tokens.append(":");
1082 }
1083 tokens.append("while");
1084 cond.to_tokens(tokens);
1085 body.to_tokens(tokens);
1086 }
1087 Expr::WhileLet(ref pat, ref expr, ref body, ref label) => {
1088 if let Some(ref label) = *label {
1089 label.to_tokens(tokens);
1090 tokens.append(":");
1091 }
1092 tokens.append("while");
1093 tokens.append("let");
1094 pat.to_tokens(tokens);
1095 tokens.append("=");
1096 expr.to_tokens(tokens);
1097 body.to_tokens(tokens);
1098 }
1099 Expr::ForLoop(ref pat, ref expr, ref body, ref label) => {
1100 if let Some(ref label) = *label {
1101 label.to_tokens(tokens);
1102 tokens.append(":");
1103 }
1104 tokens.append("for");
1105 pat.to_tokens(tokens);
1106 tokens.append("in");
1107 expr.to_tokens(tokens);
1108 body.to_tokens(tokens);
1109 }
1110 Expr::Loop(ref body, ref label) => {
1111 if let Some(ref label) = *label {
1112 label.to_tokens(tokens);
1113 tokens.append(":");
1114 }
1115 tokens.append("loop");
1116 body.to_tokens(tokens);
1117 }
David Tolnayb4ad3b52016-10-01 21:58:13 -07001118 Expr::Match(ref expr, ref arms) => {
1119 tokens.append("match");
1120 expr.to_tokens(tokens);
1121 tokens.append("{");
1122 tokens.append_separated(arms, ",");
1123 tokens.append("}");
1124 }
David Tolnay89e05672016-10-02 14:39:42 -07001125 Expr::Closure(capture, ref decl, ref body) => {
1126 capture.to_tokens(tokens);
1127 tokens.append("|");
1128 for (i, input) in decl.inputs.iter().enumerate() {
1129 if i > 0 {
1130 tokens.append(",");
1131 }
David Tolnayca085422016-10-04 00:12:38 -07001132 match *input {
1133 FnArg::Captured(ref pat, Ty::Infer) => {
1134 pat.to_tokens(tokens);
David Tolnaydaaf7742016-10-03 11:11:43 -07001135 }
David Tolnayca085422016-10-04 00:12:38 -07001136 _ => input.to_tokens(tokens),
David Tolnay89e05672016-10-02 14:39:42 -07001137 }
1138 }
1139 tokens.append("|");
1140 match decl.output {
1141 FunctionRetTy::Default => {
1142 if body.stmts.len() == 1 {
1143 if let Stmt::Expr(ref expr) = body.stmts[0] {
1144 expr.to_tokens(tokens);
1145 } else {
1146 body.to_tokens(tokens);
1147 }
1148 } else {
1149 body.to_tokens(tokens);
1150 }
1151 }
1152 FunctionRetTy::Ty(ref ty) => {
1153 tokens.append("->");
1154 ty.to_tokens(tokens);
1155 body.to_tokens(tokens);
1156 }
1157 }
1158 }
1159 Expr::Block(rules, ref block) => {
1160 rules.to_tokens(tokens);
1161 block.to_tokens(tokens);
1162 }
David Tolnaybb6feae2016-10-02 21:25:20 -07001163 Expr::Assign(ref var, ref expr) => {
1164 var.to_tokens(tokens);
1165 tokens.append("=");
1166 expr.to_tokens(tokens);
1167 }
1168 Expr::AssignOp(op, ref var, ref expr) => {
1169 var.to_tokens(tokens);
David Tolnay3cb23a92016-10-07 23:02:21 -07001170 tokens.append(op.assign_op().unwrap());
David Tolnaybb6feae2016-10-02 21:25:20 -07001171 expr.to_tokens(tokens);
1172 }
1173 Expr::Field(ref expr, ref field) => {
1174 expr.to_tokens(tokens);
1175 tokens.append(".");
1176 field.to_tokens(tokens);
1177 }
1178 Expr::TupField(ref expr, field) => {
1179 expr.to_tokens(tokens);
1180 tokens.append(".");
1181 tokens.append(&field.to_string());
1182 }
1183 Expr::Index(ref expr, ref index) => {
1184 expr.to_tokens(tokens);
1185 tokens.append("[");
1186 index.to_tokens(tokens);
1187 tokens.append("]");
1188 }
1189 Expr::Range(ref from, ref to, limits) => {
1190 from.to_tokens(tokens);
1191 match limits {
1192 RangeLimits::HalfOpen => tokens.append(".."),
1193 RangeLimits::Closed => tokens.append("..."),
1194 }
1195 to.to_tokens(tokens);
1196 }
David Tolnay8b308c22016-10-03 01:24:10 -07001197 Expr::Path(None, ref path) => path.to_tokens(tokens),
David Tolnay89e05672016-10-02 14:39:42 -07001198 Expr::Path(Some(ref qself), ref path) => {
1199 tokens.append("<");
1200 qself.ty.to_tokens(tokens);
1201 if qself.position > 0 {
1202 tokens.append("as");
David Tolnaydaaf7742016-10-03 11:11:43 -07001203 for (i, segment) in path.segments
1204 .iter()
1205 .take(qself.position)
1206 .enumerate() {
David Tolnay89e05672016-10-02 14:39:42 -07001207 if i > 0 || path.global {
1208 tokens.append("::");
1209 }
1210 segment.to_tokens(tokens);
1211 }
1212 }
1213 tokens.append(">");
1214 for segment in path.segments.iter().skip(qself.position) {
1215 tokens.append("::");
1216 segment.to_tokens(tokens);
1217 }
1218 }
David Tolnay3c2467c2016-10-02 17:55:08 -07001219 Expr::AddrOf(mutability, ref expr) => {
1220 tokens.append("&");
1221 mutability.to_tokens(tokens);
1222 expr.to_tokens(tokens);
1223 }
1224 Expr::Break(ref opt_label) => {
1225 tokens.append("break");
1226 opt_label.to_tokens(tokens);
1227 }
1228 Expr::Continue(ref opt_label) => {
1229 tokens.append("continue");
1230 opt_label.to_tokens(tokens);
1231 }
David Tolnay42602292016-10-01 22:25:45 -07001232 Expr::Ret(ref opt_expr) => {
1233 tokens.append("return");
1234 opt_expr.to_tokens(tokens);
1235 }
David Tolnaycc3d66e2016-10-02 23:36:05 -07001236 Expr::Mac(ref mac) => mac.to_tokens(tokens),
David Tolnay055a7042016-10-02 19:23:54 -07001237 Expr::Struct(ref path, ref fields, ref base) => {
1238 path.to_tokens(tokens);
1239 tokens.append("{");
1240 tokens.append_separated(fields, ",");
1241 if let Some(ref base) = *base {
1242 if !fields.is_empty() {
1243 tokens.append(",");
1244 }
1245 tokens.append("..");
1246 base.to_tokens(tokens);
1247 }
1248 tokens.append("}");
1249 }
1250 Expr::Repeat(ref expr, ref times) => {
1251 tokens.append("[");
1252 expr.to_tokens(tokens);
1253 tokens.append(";");
1254 times.to_tokens(tokens);
1255 tokens.append("]");
1256 }
David Tolnay89e05672016-10-02 14:39:42 -07001257 Expr::Paren(ref expr) => {
1258 tokens.append("(");
1259 expr.to_tokens(tokens);
1260 tokens.append(")");
1261 }
David Tolnay3c2467c2016-10-02 17:55:08 -07001262 Expr::Try(ref expr) => {
1263 expr.to_tokens(tokens);
1264 tokens.append("?");
1265 }
David Tolnayf4bbbd92016-09-23 14:41:55 -07001266 }
1267 }
1268 }
David Tolnayb4ad3b52016-10-01 21:58:13 -07001269
David Tolnay055a7042016-10-02 19:23:54 -07001270 impl ToTokens for FieldValue {
1271 fn to_tokens(&self, tokens: &mut Tokens) {
1272 self.ident.to_tokens(tokens);
1273 tokens.append(":");
1274 self.expr.to_tokens(tokens);
1275 }
1276 }
1277
David Tolnayb4ad3b52016-10-01 21:58:13 -07001278 impl ToTokens for Arm {
1279 fn to_tokens(&self, tokens: &mut Tokens) {
1280 for attr in &self.attrs {
1281 attr.to_tokens(tokens);
1282 }
1283 tokens.append_separated(&self.pats, "|");
1284 if let Some(ref guard) = self.guard {
1285 tokens.append("if");
1286 guard.to_tokens(tokens);
1287 }
1288 tokens.append("=>");
1289 self.body.to_tokens(tokens);
1290 match *self.body {
David Tolnaydaaf7742016-10-03 11:11:43 -07001291 Expr::Block(_, _) => {
1292 // no comma
1293 }
David Tolnayb4ad3b52016-10-01 21:58:13 -07001294 _ => tokens.append(","),
1295 }
1296 }
1297 }
1298
1299 impl ToTokens for Pat {
1300 fn to_tokens(&self, tokens: &mut Tokens) {
1301 match *self {
1302 Pat::Wild => tokens.append("_"),
1303 Pat::Ident(mode, ref ident, ref subpat) => {
1304 mode.to_tokens(tokens);
1305 ident.to_tokens(tokens);
1306 if let Some(ref subpat) = *subpat {
1307 tokens.append("@");
1308 subpat.to_tokens(tokens);
1309 }
1310 }
David Tolnay8d9e81a2016-10-03 22:36:32 -07001311 Pat::Struct(ref path, ref fields, dots) => {
1312 path.to_tokens(tokens);
1313 tokens.append("{");
1314 tokens.append_separated(fields, ",");
1315 if dots {
1316 if !fields.is_empty() {
1317 tokens.append(",");
1318 }
1319 tokens.append("..");
1320 }
1321 tokens.append("}");
1322 }
David Tolnayaa610942016-10-03 22:22:49 -07001323 Pat::TupleStruct(ref path, ref pats, dotpos) => {
1324 path.to_tokens(tokens);
1325 tokens.append("(");
1326 match dotpos {
1327 Some(pos) => {
1328 if pos > 0 {
1329 tokens.append_separated(&pats[..pos], ",");
1330 tokens.append(",");
1331 }
1332 tokens.append("..");
1333 if pos < pats.len() {
1334 tokens.append(",");
1335 tokens.append_separated(&pats[pos..], ",");
1336 }
1337 }
1338 None => tokens.append_separated(pats, ","),
1339 }
1340 tokens.append(")");
1341 }
David Tolnay8b308c22016-10-03 01:24:10 -07001342 Pat::Path(None, ref path) => path.to_tokens(tokens),
1343 Pat::Path(Some(ref qself), ref path) => {
1344 tokens.append("<");
1345 qself.ty.to_tokens(tokens);
1346 if qself.position > 0 {
1347 tokens.append("as");
David Tolnaydaaf7742016-10-03 11:11:43 -07001348 for (i, segment) in path.segments
1349 .iter()
1350 .take(qself.position)
1351 .enumerate() {
David Tolnay8b308c22016-10-03 01:24:10 -07001352 if i > 0 || path.global {
1353 tokens.append("::");
1354 }
1355 segment.to_tokens(tokens);
1356 }
1357 }
1358 tokens.append(">");
1359 for segment in path.segments.iter().skip(qself.position) {
1360 tokens.append("::");
1361 segment.to_tokens(tokens);
1362 }
1363 }
David Tolnayfbb73232016-10-03 01:00:06 -07001364 Pat::Tuple(ref pats, dotpos) => {
1365 tokens.append("(");
1366 match dotpos {
1367 Some(pos) => {
1368 if pos > 0 {
1369 tokens.append_separated(&pats[..pos], ",");
1370 tokens.append(",");
1371 }
1372 tokens.append("..");
1373 if pos < pats.len() {
1374 tokens.append(",");
1375 tokens.append_separated(&pats[pos..], ",");
1376 }
1377 }
1378 None => tokens.append_separated(pats, ","),
1379 }
1380 tokens.append(")");
1381 }
1382 Pat::Box(ref inner) => {
1383 tokens.append("box");
1384 inner.to_tokens(tokens);
1385 }
David Tolnayffdb97f2016-10-03 01:28:33 -07001386 Pat::Ref(ref target, mutability) => {
1387 tokens.append("&");
1388 mutability.to_tokens(tokens);
1389 target.to_tokens(tokens);
1390 }
David Tolnay8b308c22016-10-03 01:24:10 -07001391 Pat::Lit(ref lit) => lit.to_tokens(tokens),
1392 Pat::Range(ref lo, ref hi) => {
1393 lo.to_tokens(tokens);
1394 tokens.append("...");
1395 hi.to_tokens(tokens);
1396 }
David Tolnay16709ba2016-10-05 23:11:32 -07001397 Pat::Slice(ref _before, ref _dots, ref _after) => unimplemented!(),
David Tolnaycc3d66e2016-10-02 23:36:05 -07001398 Pat::Mac(ref mac) => mac.to_tokens(tokens),
David Tolnayb4ad3b52016-10-01 21:58:13 -07001399 }
1400 }
1401 }
1402
David Tolnay8d9e81a2016-10-03 22:36:32 -07001403 impl ToTokens for FieldPat {
1404 fn to_tokens(&self, tokens: &mut Tokens) {
1405 if !self.is_shorthand {
1406 self.ident.to_tokens(tokens);
1407 tokens.append(":");
1408 }
1409 self.pat.to_tokens(tokens);
1410 }
1411 }
1412
David Tolnayb4ad3b52016-10-01 21:58:13 -07001413 impl ToTokens for BindingMode {
1414 fn to_tokens(&self, tokens: &mut Tokens) {
1415 match *self {
1416 BindingMode::ByRef(Mutability::Immutable) => {
1417 tokens.append("ref");
1418 }
1419 BindingMode::ByRef(Mutability::Mutable) => {
1420 tokens.append("ref");
1421 tokens.append("mut");
1422 }
1423 BindingMode::ByValue(Mutability::Immutable) => {}
1424 BindingMode::ByValue(Mutability::Mutable) => {
1425 tokens.append("mut");
1426 }
1427 }
1428 }
1429 }
David Tolnay42602292016-10-01 22:25:45 -07001430
David Tolnay89e05672016-10-02 14:39:42 -07001431 impl ToTokens for CaptureBy {
1432 fn to_tokens(&self, tokens: &mut Tokens) {
1433 match *self {
1434 CaptureBy::Value => tokens.append("move"),
David Tolnaydaaf7742016-10-03 11:11:43 -07001435 CaptureBy::Ref => {
1436 // nothing
1437 }
David Tolnay89e05672016-10-02 14:39:42 -07001438 }
1439 }
1440 }
1441
David Tolnay42602292016-10-01 22:25:45 -07001442 impl ToTokens for Block {
1443 fn to_tokens(&self, tokens: &mut Tokens) {
David Tolnay42602292016-10-01 22:25:45 -07001444 tokens.append("{");
1445 for stmt in &self.stmts {
1446 stmt.to_tokens(tokens);
1447 }
1448 tokens.append("}");
1449 }
1450 }
1451
1452 impl ToTokens for BlockCheckMode {
1453 fn to_tokens(&self, tokens: &mut Tokens) {
1454 match *self {
David Tolnaydaaf7742016-10-03 11:11:43 -07001455 BlockCheckMode::Default => {
1456 // nothing
1457 }
David Tolnay42602292016-10-01 22:25:45 -07001458 BlockCheckMode::Unsafe => tokens.append("unsafe"),
1459 }
1460 }
1461 }
1462
1463 impl ToTokens for Stmt {
1464 fn to_tokens(&self, tokens: &mut Tokens) {
1465 match *self {
David Tolnay191e0582016-10-02 18:31:09 -07001466 Stmt::Local(ref local) => local.to_tokens(tokens),
David Tolnay42602292016-10-01 22:25:45 -07001467 Stmt::Item(ref item) => item.to_tokens(tokens),
1468 Stmt::Expr(ref expr) => expr.to_tokens(tokens),
1469 Stmt::Semi(ref expr) => {
1470 expr.to_tokens(tokens);
1471 tokens.append(";");
1472 }
David Tolnay13b3d352016-10-03 00:31:15 -07001473 Stmt::Mac(ref mac) => {
1474 let (ref mac, style, ref attrs) = **mac;
1475 for attr in attrs.outer() {
1476 attr.to_tokens(tokens);
1477 }
1478 mac.to_tokens(tokens);
1479 match style {
1480 MacStmtStyle::Semicolon => tokens.append(";"),
David Tolnaydaaf7742016-10-03 11:11:43 -07001481 MacStmtStyle::Braces | MacStmtStyle::NoBraces => {
1482 // no semicolon
1483 }
David Tolnay13b3d352016-10-03 00:31:15 -07001484 }
1485 }
David Tolnay42602292016-10-01 22:25:45 -07001486 }
1487 }
1488 }
David Tolnay191e0582016-10-02 18:31:09 -07001489
1490 impl ToTokens for Local {
1491 fn to_tokens(&self, tokens: &mut Tokens) {
1492 tokens.append("let");
1493 self.pat.to_tokens(tokens);
1494 if let Some(ref ty) = self.ty {
1495 tokens.append(":");
1496 ty.to_tokens(tokens);
1497 }
1498 if let Some(ref init) = self.init {
1499 tokens.append("=");
1500 init.to_tokens(tokens);
1501 }
1502 tokens.append(";");
1503 }
1504 }
David Tolnayf4bbbd92016-09-23 14:41:55 -07001505}