blob: f2f96d0551ff5fb49dfce1e459eb8dc540ba38bf [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
191#[derive(Debug, Copy, Clone, Eq, PartialEq)]
192pub enum BinOp {
193 /// The `+` operator (addition)
194 Add,
195 /// The `-` operator (subtraction)
196 Sub,
197 /// The `*` operator (multiplication)
198 Mul,
199 /// The `/` operator (division)
200 Div,
201 /// The `%` operator (modulus)
202 Rem,
203 /// The `&&` operator (logical and)
204 And,
205 /// The `||` operator (logical or)
206 Or,
207 /// The `^` operator (bitwise xor)
208 BitXor,
209 /// The `&` operator (bitwise and)
210 BitAnd,
211 /// The `|` operator (bitwise or)
212 BitOr,
213 /// The `<<` operator (shift left)
214 Shl,
215 /// The `>>` operator (shift right)
216 Shr,
217 /// The `==` operator (equality)
218 Eq,
219 /// The `<` operator (less than)
220 Lt,
221 /// The `<=` operator (less than or equal to)
222 Le,
223 /// The `!=` operator (not equal to)
224 Ne,
225 /// The `>=` operator (greater than or equal to)
226 Ge,
227 /// The `>` operator (greater than)
228 Gt,
229}
230
231#[derive(Debug, Copy, Clone, Eq, PartialEq)]
232pub enum UnOp {
233 /// The `*` operator for dereferencing
234 Deref,
235 /// The `!` operator for logical inversion
236 Not,
237 /// The `-` operator for negation
238 Neg,
239}
240
241#[derive(Debug, Clone, Eq, PartialEq)]
242pub enum Pat {
243 /// Represents a wildcard pattern (`_`)
244 Wild,
245
David Tolnay432afc02016-09-24 07:37:13 -0700246 /// A `Pat::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
David Tolnayf4bbbd92016-09-23 14:41:55 -0700247 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
248 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
249 /// during name resolution.
250 Ident(BindingMode, Ident, Option<Box<Pat>>),
251
252 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
253 /// The `bool` is `true` in the presence of a `..`.
254 Struct(Path, Vec<FieldPat>, bool),
255
256 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
257 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
258 /// 0 <= position <= subpats.len()
259 TupleStruct(Path, Vec<Pat>, Option<usize>),
260
261 /// A possibly qualified path pattern.
262 /// Unquailfied path patterns `A::B::C` can legally refer to variants, structs, constants
263 /// or associated constants. Quailfied path patterns `<A>::B::C`/`<A as Trait>::B::C` can
264 /// only legally refer to associated constants.
265 Path(Option<QSelf>, Path),
266
267 /// A tuple pattern `(a, b)`.
268 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
269 /// 0 <= position <= subpats.len()
270 Tuple(Vec<Pat>, Option<usize>),
271 /// A `box` pattern
272 Box(Box<Pat>),
273 /// A reference pattern, e.g. `&mut (a, b)`
274 Ref(Box<Pat>, Mutability),
275 /// A literal
David Tolnay8b308c22016-10-03 01:24:10 -0700276 Lit(Box<Lit>),
David Tolnayf4bbbd92016-09-23 14:41:55 -0700277 /// A range pattern, e.g. `1...2`
David Tolnay8b308c22016-10-03 01:24:10 -0700278 Range(Box<Lit>, Box<Lit>),
David Tolnayf4bbbd92016-09-23 14:41:55 -0700279 /// `[a, b, ..i, y, z]` is represented as:
David Tolnay16709ba2016-10-05 23:11:32 -0700280 /// `Pat::Slice(box [a, b], Some(i), box [y, z])`
281 Slice(Vec<Pat>, Option<Box<Pat>>, Vec<Pat>),
David Tolnayf4bbbd92016-09-23 14:41:55 -0700282 /// A macro pattern; pre-expansion
283 Mac(Mac),
284}
285
David Tolnay771ecf42016-09-23 19:26:37 -0700286/// An arm of a 'match'.
287///
288/// E.g. `0...10 => { println!("match!") }` as in
289///
290/// ```rust,ignore
291/// match n {
292/// 0...10 => { println!("match!") },
293/// // ..
294/// }
295/// ```
David Tolnayf4bbbd92016-09-23 14:41:55 -0700296#[derive(Debug, Clone, Eq, PartialEq)]
297pub struct Arm {
298 pub attrs: Vec<Attribute>,
299 pub pats: Vec<Pat>,
300 pub guard: Option<Box<Expr>>,
301 pub body: Box<Expr>,
302}
303
304/// A capture clause
305#[derive(Debug, Copy, Clone, Eq, PartialEq)]
306pub enum CaptureBy {
307 Value,
308 Ref,
309}
310
311/// Limit types of a range (inclusive or exclusive)
312#[derive(Debug, Copy, Clone, Eq, PartialEq)]
313pub enum RangeLimits {
314 /// Inclusive at the beginning, exclusive at the end
315 HalfOpen,
316 /// Inclusive at the beginning and end
317 Closed,
318}
319
320/// A single field in a struct pattern
321///
322/// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
David Tolnay181bac52016-09-24 00:10:05 -0700323/// are treated the same as `x: x, y: ref y, z: ref mut z`,
David Tolnayaed77b02016-09-23 20:50:31 -0700324/// except `is_shorthand` is true
David Tolnayf4bbbd92016-09-23 14:41:55 -0700325#[derive(Debug, Clone, Eq, PartialEq)]
326pub struct FieldPat {
327 /// The identifier for the field
328 pub ident: Ident,
329 /// The pattern the field is destructured to
330 pub pat: Box<Pat>,
331 pub is_shorthand: bool,
332}
333
334#[derive(Debug, Copy, Clone, Eq, PartialEq)]
335pub enum BindingMode {
336 ByRef(Mutability),
337 ByValue(Mutability),
338}
339
David Tolnayb9c8e322016-09-23 20:48:37 -0700340#[cfg(feature = "parsing")]
341pub mod parsing {
342 use super::*;
David Tolnaycfe55022016-10-02 22:02:27 -0700343 use {Delimited, DelimToken, FnArg, FnDecl, FunctionRetTy, Ident, Lifetime, TokenTree, Ty};
David Tolnayb4ad3b52016-10-01 21:58:13 -0700344 use attr::parsing::outer_attr;
Gregory Katz1b69f682016-09-27 21:06:09 -0400345 use generics::parsing::lifetime;
David Tolnayfa0edf22016-09-23 22:58:24 -0700346 use ident::parsing::ident;
David Tolnay191e0582016-10-02 18:31:09 -0700347 use item::parsing::item;
David Tolnayfa0edf22016-09-23 22:58:24 -0700348 use lit::parsing::lit;
David Tolnay84aa0752016-10-02 23:01:13 -0700349 use mac::parsing::mac;
David Tolnaycfe55022016-10-02 22:02:27 -0700350 use nom::IResult::Error;
David Tolnay055a7042016-10-02 19:23:54 -0700351 use ty::parsing::{mutability, path, qpath, ty};
David Tolnayb9c8e322016-09-23 20:48:37 -0700352
David Tolnayfa0edf22016-09-23 22:58:24 -0700353 named!(pub expr -> Expr, do_parse!(
354 mut e: alt!(
David Tolnayfa94b6f2016-10-05 23:26:11 -0700355 expr_lit // must be before expr_struct
David Tolnay055a7042016-10-02 19:23:54 -0700356 |
David Tolnayfa94b6f2016-10-05 23:26:11 -0700357 expr_struct // must be before expr_path
David Tolnay055a7042016-10-02 19:23:54 -0700358 |
David Tolnayfa94b6f2016-10-05 23:26:11 -0700359 expr_paren // must be before expr_tup
360 |
361 expr_mac // must be before expr_path
David Tolnay89e05672016-10-02 14:39:42 -0700362 |
David Tolnay4c9be372016-10-06 00:47:37 -0700363 expr_break // must be before expr_path
364 |
365 expr_continue // must be before expr_path
366 |
367 expr_ret // must be before expr_path
368 |
David Tolnay939766a2016-09-23 23:48:12 -0700369 expr_box
David Tolnayfa0edf22016-09-23 22:58:24 -0700370 |
David Tolnay939766a2016-09-23 23:48:12 -0700371 expr_vec
David Tolnayfa0edf22016-09-23 22:58:24 -0700372 |
David Tolnay939766a2016-09-23 23:48:12 -0700373 expr_tup
David Tolnayfa0edf22016-09-23 22:58:24 -0700374 |
David Tolnay939766a2016-09-23 23:48:12 -0700375 expr_unary
David Tolnayfa0edf22016-09-23 22:58:24 -0700376 |
David Tolnay939766a2016-09-23 23:48:12 -0700377 expr_if
Gregory Katz3e562cc2016-09-28 18:33:02 -0400378 |
379 expr_while
David Tolnaybb6feae2016-10-02 21:25:20 -0700380 |
381 expr_for_loop
Gregory Katze5f35682016-09-27 14:20:55 -0400382 |
383 expr_loop
David Tolnayb4ad3b52016-10-01 21:58:13 -0700384 |
385 expr_match
David Tolnay89e05672016-10-02 14:39:42 -0700386 |
387 expr_closure
David Tolnay939766a2016-09-23 23:48:12 -0700388 |
389 expr_block
David Tolnay89e05672016-10-02 14:39:42 -0700390 |
391 expr_path
David Tolnay3c2467c2016-10-02 17:55:08 -0700392 |
393 expr_addr_of
Gregory Katzfd6935d2016-09-30 22:51:25 -0400394 |
David Tolnay055a7042016-10-02 19:23:54 -0700395 expr_repeat
David Tolnayfa0edf22016-09-23 22:58:24 -0700396 ) >>
397 many0!(alt!(
David Tolnay939766a2016-09-23 23:48:12 -0700398 tap!(args: and_call => {
399 e = Expr::Call(Box::new(e), args);
David Tolnayfa0edf22016-09-23 22:58:24 -0700400 })
401 |
David Tolnay939766a2016-09-23 23:48:12 -0700402 tap!(more: and_method_call => {
403 let (method, ascript, mut args) = more;
David Tolnayfa0edf22016-09-23 22:58:24 -0700404 args.insert(0, e);
405 e = Expr::MethodCall(method, ascript, args);
406 })
407 |
David Tolnay939766a2016-09-23 23:48:12 -0700408 tap!(more: and_binary => {
409 let (op, other) = more;
David Tolnayfa0edf22016-09-23 22:58:24 -0700410 e = Expr::Binary(op, Box::new(e), Box::new(other));
411 })
David Tolnay939766a2016-09-23 23:48:12 -0700412 |
413 tap!(ty: and_cast => {
414 e = Expr::Cast(Box::new(e), Box::new(ty));
415 })
416 |
417 tap!(ty: and_ascription => {
418 e = Expr::Type(Box::new(e), Box::new(ty));
419 })
David Tolnaydaaf7742016-10-03 11:11:43 -0700420 // TODO: Assign
421 // TODO: AssignOp
422 // TODO: Field
423 // TODO: TupField
424 // TODO: Index
425 // TODO: Range
David Tolnay055a7042016-10-02 19:23:54 -0700426 |
427 tap!(_try: punct!("?") => {
428 e = Expr::Try(Box::new(e));
429 })
David Tolnayfa0edf22016-09-23 22:58:24 -0700430 )) >>
431 (e)
David Tolnayb9c8e322016-09-23 20:48:37 -0700432 ));
433
David Tolnay84aa0752016-10-02 23:01:13 -0700434 named!(expr_mac -> Expr, map!(mac, Expr::Mac));
435
David Tolnay89e05672016-10-02 14:39:42 -0700436 named!(expr_paren -> Expr, do_parse!(
437 punct!("(") >>
438 e: expr >>
439 punct!(")") >>
440 (Expr::Paren(Box::new(e)))
441 ));
442
David Tolnay939766a2016-09-23 23:48:12 -0700443 named!(expr_box -> Expr, do_parse!(
David Tolnay10413f02016-09-30 09:12:02 -0700444 keyword!("box") >>
David Tolnayb9c8e322016-09-23 20:48:37 -0700445 inner: expr >>
446 (Expr::Box(Box::new(inner)))
447 ));
David Tolnayfa0edf22016-09-23 22:58:24 -0700448
David Tolnay939766a2016-09-23 23:48:12 -0700449 named!(expr_vec -> Expr, do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700450 punct!("[") >>
451 elems: separated_list!(punct!(","), expr) >>
452 punct!("]") >>
453 (Expr::Vec(elems))
454 ));
455
David Tolnay939766a2016-09-23 23:48:12 -0700456 named!(and_call -> Vec<Expr>, do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700457 punct!("(") >>
458 args: separated_list!(punct!(","), expr) >>
459 punct!(")") >>
460 (args)
461 ));
462
David Tolnay939766a2016-09-23 23:48:12 -0700463 named!(and_method_call -> (Ident, Vec<Ty>, Vec<Expr>), do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700464 punct!(".") >>
465 method: ident >>
466 ascript: opt_vec!(delimited!(
467 punct!("<"),
468 separated_list!(punct!(","), ty),
469 punct!(">")
470 )) >>
471 punct!("(") >>
472 args: separated_list!(punct!(","), expr) >>
473 punct!(")") >>
474 (method, ascript, args)
475 ));
476
David Tolnay939766a2016-09-23 23:48:12 -0700477 named!(expr_tup -> Expr, do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700478 punct!("(") >>
479 elems: separated_list!(punct!(","), expr) >>
David Tolnay89e05672016-10-02 14:39:42 -0700480 option!(punct!(",")) >>
David Tolnayfa0edf22016-09-23 22:58:24 -0700481 punct!(")") >>
482 (Expr::Tup(elems))
483 ));
484
David Tolnay939766a2016-09-23 23:48:12 -0700485 named!(and_binary -> (BinOp, Expr), tuple!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700486 alt!(
487 punct!("&&") => { |_| BinOp::And }
488 |
489 punct!("||") => { |_| BinOp::Or }
490 |
491 punct!("<<") => { |_| BinOp::Shl }
492 |
493 punct!(">>") => { |_| BinOp::Shr }
494 |
495 punct!("==") => { |_| BinOp::Eq }
496 |
497 punct!("<=") => { |_| BinOp::Le }
498 |
499 punct!("!=") => { |_| BinOp::Ne }
500 |
501 punct!(">=") => { |_| BinOp::Ge }
502 |
503 punct!("+") => { |_| BinOp::Add }
504 |
505 punct!("-") => { |_| BinOp::Sub }
506 |
507 punct!("*") => { |_| BinOp::Mul }
508 |
509 punct!("/") => { |_| BinOp::Div }
510 |
511 punct!("%") => { |_| BinOp::Rem }
512 |
513 punct!("^") => { |_| BinOp::BitXor }
514 |
515 punct!("&") => { |_| BinOp::BitAnd }
516 |
517 punct!("|") => { |_| BinOp::BitOr }
518 |
519 punct!("<") => { |_| BinOp::Lt }
520 |
521 punct!(">") => { |_| BinOp::Gt }
522 ),
523 expr
524 ));
525
David Tolnay939766a2016-09-23 23:48:12 -0700526 named!(expr_unary -> Expr, do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700527 operator: alt!(
528 punct!("*") => { |_| UnOp::Deref }
529 |
530 punct!("!") => { |_| UnOp::Not }
531 |
532 punct!("-") => { |_| UnOp::Neg }
533 ) >>
534 operand: expr >>
535 (Expr::Unary(operator, Box::new(operand)))
536 ));
David Tolnay939766a2016-09-23 23:48:12 -0700537
538 named!(expr_lit -> Expr, map!(lit, Expr::Lit));
539
540 named!(and_cast -> Ty, do_parse!(
David Tolnay10413f02016-09-30 09:12:02 -0700541 keyword!("as") >>
David Tolnay939766a2016-09-23 23:48:12 -0700542 ty: ty >>
543 (ty)
544 ));
545
546 named!(and_ascription -> Ty, preceded!(punct!(":"), ty));
547
David Tolnaybb6feae2016-10-02 21:25:20 -0700548 enum Cond {
David Tolnay29f9ce12016-10-02 20:58:40 -0700549 Let(Pat, Expr),
550 Expr(Expr),
551 }
552
David Tolnaybb6feae2016-10-02 21:25:20 -0700553 named!(cond -> Cond, alt!(
554 do_parse!(
555 keyword!("let") >>
556 pat: pat >>
557 punct!("=") >>
558 value: expr >>
559 (Cond::Let(pat, value))
560 )
561 |
562 map!(expr, Cond::Expr)
563 ));
564
David Tolnay939766a2016-09-23 23:48:12 -0700565 named!(expr_if -> Expr, do_parse!(
David Tolnay10413f02016-09-30 09:12:02 -0700566 keyword!("if") >>
David Tolnaybb6feae2016-10-02 21:25:20 -0700567 cond: cond >>
David Tolnay939766a2016-09-23 23:48:12 -0700568 punct!("{") >>
569 then_block: within_block >>
570 punct!("}") >>
571 else_block: option!(preceded!(
David Tolnay10413f02016-09-30 09:12:02 -0700572 keyword!("else"),
David Tolnay939766a2016-09-23 23:48:12 -0700573 alt!(
574 expr_if
575 |
576 do_parse!(
577 punct!("{") >>
578 else_block: within_block >>
579 punct!("}") >>
David Tolnay89e05672016-10-02 14:39:42 -0700580 (Expr::Block(BlockCheckMode::Default, Block {
David Tolnay939766a2016-09-23 23:48:12 -0700581 stmts: else_block,
David Tolnay89e05672016-10-02 14:39:42 -0700582 }))
David Tolnay939766a2016-09-23 23:48:12 -0700583 )
584 )
585 )) >>
David Tolnay29f9ce12016-10-02 20:58:40 -0700586 (match cond {
David Tolnaybb6feae2016-10-02 21:25:20 -0700587 Cond::Let(pat, expr) => Expr::IfLet(
David Tolnay29f9ce12016-10-02 20:58:40 -0700588 Box::new(pat),
589 Box::new(expr),
590 Block {
591 stmts: then_block,
592 },
593 else_block.map(Box::new),
594 ),
David Tolnaybb6feae2016-10-02 21:25:20 -0700595 Cond::Expr(cond) => Expr::If(
David Tolnay29f9ce12016-10-02 20:58:40 -0700596 Box::new(cond),
597 Block {
598 stmts: then_block,
599 },
600 else_block.map(Box::new),
601 ),
602 })
David Tolnay939766a2016-09-23 23:48:12 -0700603 ));
604
David Tolnaybb6feae2016-10-02 21:25:20 -0700605 named!(expr_for_loop -> Expr, do_parse!(
606 lbl: option!(terminated!(label, punct!(":"))) >>
607 keyword!("for") >>
608 pat: pat >>
609 keyword!("in") >>
610 expr: expr >>
611 loop_block: block >>
612 (Expr::ForLoop(Box::new(pat), Box::new(expr), loop_block, lbl))
613 ));
614
Gregory Katze5f35682016-09-27 14:20:55 -0400615 named!(expr_loop -> Expr, do_parse!(
David Tolnay8b07f372016-09-30 10:28:40 -0700616 lbl: option!(terminated!(label, punct!(":"))) >>
David Tolnay10413f02016-09-30 09:12:02 -0700617 keyword!("loop") >>
Gregory Katze5f35682016-09-27 14:20:55 -0400618 loop_block: block >>
David Tolnay89e05672016-10-02 14:39:42 -0700619 (Expr::Loop(loop_block, lbl))
Gregory Katze5f35682016-09-27 14:20:55 -0400620 ));
621
David Tolnayb4ad3b52016-10-01 21:58:13 -0700622 named!(expr_match -> Expr, do_parse!(
623 keyword!("match") >>
624 obj: expr >>
625 punct!("{") >>
626 arms: many0!(do_parse!(
627 attrs: many0!(outer_attr) >>
628 pats: separated_nonempty_list!(punct!("|"), pat) >>
629 guard: option!(preceded!(keyword!("if"), expr)) >>
630 punct!("=>") >>
631 body: alt!(
632 terminated!(expr, punct!(","))
633 |
David Tolnay89e05672016-10-02 14:39:42 -0700634 map!(block, |blk| Expr::Block(BlockCheckMode::Default, blk))
David Tolnayb4ad3b52016-10-01 21:58:13 -0700635 ) >>
636 (Arm {
637 attrs: attrs,
638 pats: pats,
639 guard: guard.map(Box::new),
640 body: Box::new(body),
641 })
642 )) >>
643 punct!("}") >>
644 (Expr::Match(Box::new(obj), arms))
645 ));
646
David Tolnay89e05672016-10-02 14:39:42 -0700647 named!(expr_closure -> Expr, do_parse!(
648 capture: capture_by >>
649 punct!("|") >>
650 inputs: separated_list!(punct!(","), closure_arg) >>
651 punct!("|") >>
652 ret_and_body: alt!(
653 do_parse!(
654 punct!("->") >>
655 ty: ty >>
656 body: block >>
657 ((FunctionRetTy::Ty(ty), body))
658 )
659 |
660 map!(expr, |e| (
661 FunctionRetTy::Default,
662 Block {
663 stmts: vec![Stmt::Expr(Box::new(e))],
664 },
665 ))
666 ) >>
667 (Expr::Closure(
668 capture,
669 Box::new(FnDecl {
670 inputs: inputs,
671 output: ret_and_body.0,
672 }),
673 ret_and_body.1,
674 ))
675 ));
676
677 named!(closure_arg -> FnArg, do_parse!(
678 pat: pat >>
679 ty: option!(preceded!(punct!(":"), ty)) >>
David Tolnayca085422016-10-04 00:12:38 -0700680 (FnArg::Captured(pat, ty.unwrap_or(Ty::Infer)))
David Tolnay89e05672016-10-02 14:39:42 -0700681 ));
682
Gregory Katz3e562cc2016-09-28 18:33:02 -0400683 named!(expr_while -> Expr, do_parse!(
David Tolnay8b07f372016-09-30 10:28:40 -0700684 lbl: option!(terminated!(label, punct!(":"))) >>
David Tolnay57ffbde2016-09-30 09:38:04 -0700685 keyword!("while") >>
David Tolnaybb6feae2016-10-02 21:25:20 -0700686 cond: cond >>
Gregory Katz3e562cc2016-09-28 18:33:02 -0400687 while_block: block >>
David Tolnaybb6feae2016-10-02 21:25:20 -0700688 (match cond {
689 Cond::Let(pat, expr) => Expr::WhileLet(
690 Box::new(pat),
691 Box::new(expr),
692 while_block,
693 lbl,
694 ),
695 Cond::Expr(cond) => Expr::While(
696 Box::new(cond),
697 while_block,
698 lbl,
699 ),
700 })
Gregory Katz3e562cc2016-09-28 18:33:02 -0400701 ));
702
Gregory Katzfd6935d2016-09-30 22:51:25 -0400703 named!(expr_continue -> Expr, do_parse!(
704 keyword!("continue") >>
705 lbl: option!(label) >>
David Tolnay055a7042016-10-02 19:23:54 -0700706 (Expr::Continue(lbl))
Gregory Katzfd6935d2016-09-30 22:51:25 -0400707 ));
708
709 named!(expr_break -> Expr, do_parse!(
710 keyword!("break") >>
711 lbl: option!(label) >>
David Tolnay055a7042016-10-02 19:23:54 -0700712 (Expr::Break(lbl))
Gregory Katzfd6935d2016-09-30 22:51:25 -0400713 ));
714
715 named!(expr_ret -> Expr, do_parse!(
716 keyword!("return") >>
717 ret_value: option!(expr) >>
David Tolnay055a7042016-10-02 19:23:54 -0700718 (Expr::Ret(ret_value.map(Box::new)))
719 ));
720
721 named!(expr_struct -> Expr, do_parse!(
722 path: path >>
723 punct!("{") >>
724 fields: separated_list!(punct!(","), field_value) >>
725 base: option!(do_parse!(
726 cond!(!fields.is_empty(), punct!(",")) >>
727 punct!("..") >>
728 base: expr >>
729 (base)
730 )) >>
731 punct!("}") >>
732 (Expr::Struct(path, fields, base.map(Box::new)))
733 ));
734
735 named!(field_value -> FieldValue, do_parse!(
736 name: ident >>
737 punct!(":") >>
738 value: expr >>
739 (FieldValue {
740 ident: name,
741 expr: value,
742 })
743 ));
744
745 named!(expr_repeat -> Expr, do_parse!(
746 punct!("[") >>
747 value: expr >>
748 punct!(";") >>
749 times: expr >>
750 punct!("]") >>
751 (Expr::Repeat(Box::new(value), Box::new(times)))
Gregory Katzfd6935d2016-09-30 22:51:25 -0400752 ));
753
David Tolnay42602292016-10-01 22:25:45 -0700754 named!(expr_block -> Expr, do_parse!(
David Tolnay939766a2016-09-23 23:48:12 -0700755 rules: block_check_mode >>
David Tolnay42602292016-10-01 22:25:45 -0700756 b: block >>
David Tolnay89e05672016-10-02 14:39:42 -0700757 (Expr::Block(rules, Block {
David Tolnay42602292016-10-01 22:25:45 -0700758 stmts: b.stmts,
David Tolnay89e05672016-10-02 14:39:42 -0700759 }))
760 ));
761
David Tolnay9636c052016-10-02 17:11:17 -0700762 named!(expr_path -> Expr, map!(qpath, |(qself, path)| Expr::Path(qself, path)));
David Tolnay42602292016-10-01 22:25:45 -0700763
David Tolnay3c2467c2016-10-02 17:55:08 -0700764 named!(expr_addr_of -> Expr, do_parse!(
765 punct!("&") >>
766 mutability: mutability >>
767 expr: expr >>
768 (Expr::AddrOf(mutability, Box::new(expr)))
769 ));
770
David Tolnay42602292016-10-01 22:25:45 -0700771 named!(pub block -> Block, do_parse!(
David Tolnay939766a2016-09-23 23:48:12 -0700772 punct!("{") >>
773 stmts: within_block >>
774 punct!("}") >>
775 (Block {
776 stmts: stmts,
David Tolnay939766a2016-09-23 23:48:12 -0700777 })
778 ));
779
780 named!(block_check_mode -> BlockCheckMode, alt!(
David Tolnay10413f02016-09-30 09:12:02 -0700781 keyword!("unsafe") => { |_| BlockCheckMode::Unsafe }
David Tolnay939766a2016-09-23 23:48:12 -0700782 |
783 epsilon!() => { |_| BlockCheckMode::Default }
784 ));
785
786 named!(within_block -> Vec<Stmt>, do_parse!(
David Tolnaycfe55022016-10-02 22:02:27 -0700787 many0!(punct!(";")) >>
788 mut standalone: many0!(terminated!(standalone_stmt, many0!(punct!(";")))) >>
David Tolnay939766a2016-09-23 23:48:12 -0700789 last: option!(expr) >>
790 (match last {
David Tolnaycfe55022016-10-02 22:02:27 -0700791 None => standalone,
David Tolnay939766a2016-09-23 23:48:12 -0700792 Some(last) => {
David Tolnaycfe55022016-10-02 22:02:27 -0700793 standalone.push(Stmt::Expr(Box::new(last)));
794 standalone
David Tolnay939766a2016-09-23 23:48:12 -0700795 }
796 })
797 ));
798
799 named!(standalone_stmt -> Stmt, alt!(
David Tolnay13b3d352016-10-03 00:31:15 -0700800 stmt_mac
801 |
David Tolnay191e0582016-10-02 18:31:09 -0700802 stmt_local
803 |
804 stmt_item
805 |
David Tolnaycfe55022016-10-02 22:02:27 -0700806 stmt_expr
David Tolnay939766a2016-09-23 23:48:12 -0700807 ));
808
David Tolnay13b3d352016-10-03 00:31:15 -0700809 named!(stmt_mac -> Stmt, do_parse!(
810 attrs: many0!(outer_attr) >>
811 mac: mac >>
812 semi: option!(punct!(";")) >>
813 ({
814 let style = if semi.is_some() {
815 MacStmtStyle::Semicolon
816 } else if let Some(&TokenTree::Delimited(Delimited { delim, .. })) = mac.tts.last() {
817 match delim {
818 DelimToken::Paren | DelimToken::Bracket => MacStmtStyle::NoBraces,
819 DelimToken::Brace => MacStmtStyle::Braces,
820 }
821 } else {
822 MacStmtStyle::NoBraces
823 };
824 Stmt::Mac(Box::new((mac, style, attrs)))
825 })
826 ));
827
David Tolnay191e0582016-10-02 18:31:09 -0700828 named!(stmt_local -> Stmt, do_parse!(
829 attrs: many0!(outer_attr) >>
830 keyword!("let") >>
831 pat: pat >>
832 ty: option!(preceded!(punct!(":"), ty)) >>
833 init: option!(preceded!(punct!("="), expr)) >>
834 punct!(";") >>
835 (Stmt::Local(Box::new(Local {
836 pat: Box::new(pat),
837 ty: ty.map(Box::new),
838 init: init.map(Box::new),
839 attrs: attrs,
840 })))
841 ));
842
843 named!(stmt_item -> Stmt, map!(item, |i| Stmt::Item(Box::new(i))));
844
David Tolnaycfe55022016-10-02 22:02:27 -0700845 fn requires_semi(e: &Expr) -> bool {
846 match *e {
David Tolnaycfe55022016-10-02 22:02:27 -0700847 Expr::If(_, _, _) |
848 Expr::IfLet(_, _, _, _) |
849 Expr::While(_, _, _) |
850 Expr::WhileLet(_, _, _, _) |
851 Expr::ForLoop(_, _, _, _) |
852 Expr::Loop(_, _) |
853 Expr::Match(_, _) |
854 Expr::Block(_, _) => false,
855
856 _ => true,
857 }
858 }
859
860 named!(stmt_expr -> Stmt, do_parse!(
David Tolnay939766a2016-09-23 23:48:12 -0700861 e: expr >>
David Tolnaycfe55022016-10-02 22:02:27 -0700862 semi: option!(punct!(";")) >>
863 (if semi.is_some() {
864 Stmt::Semi(Box::new(e))
865 } else if requires_semi(&e) {
866 return Error;
867 } else {
868 Stmt::Expr(Box::new(e))
869 })
David Tolnay939766a2016-09-23 23:48:12 -0700870 ));
David Tolnay8b07f372016-09-30 10:28:40 -0700871
David Tolnay42602292016-10-01 22:25:45 -0700872 named!(pub pat -> Pat, alt!(
David Tolnayfbb73232016-10-03 01:00:06 -0700873 pat_wild // must be before pat_ident
874 |
875 pat_box // must be before pat_ident
David Tolnayb4ad3b52016-10-01 21:58:13 -0700876 |
David Tolnay8b308c22016-10-03 01:24:10 -0700877 pat_range // must be before pat_lit
878 |
David Tolnayaa610942016-10-03 22:22:49 -0700879 pat_tuple_struct // must be before pat_ident
880 |
David Tolnay8d9e81a2016-10-03 22:36:32 -0700881 pat_struct // must be before pat_ident
882 |
David Tolnayaa610942016-10-03 22:22:49 -0700883 pat_mac // must be before pat_ident
884 |
David Tolnay8b308c22016-10-03 01:24:10 -0700885 pat_ident // must be before pat_path
David Tolnay9636c052016-10-02 17:11:17 -0700886 |
887 pat_path
David Tolnayfbb73232016-10-03 01:00:06 -0700888 |
889 pat_tuple
David Tolnayffdb97f2016-10-03 01:28:33 -0700890 |
891 pat_ref
David Tolnay8b308c22016-10-03 01:24:10 -0700892 |
893 pat_lit
David Tolnaydaaf7742016-10-03 11:11:43 -0700894 // TODO: Vec
David Tolnayb4ad3b52016-10-01 21:58:13 -0700895 ));
896
David Tolnay84aa0752016-10-02 23:01:13 -0700897 named!(pat_mac -> Pat, map!(mac, Pat::Mac));
898
David Tolnayb4ad3b52016-10-01 21:58:13 -0700899 named!(pat_wild -> Pat, map!(keyword!("_"), |_| Pat::Wild));
900
David Tolnayfbb73232016-10-03 01:00:06 -0700901 named!(pat_box -> Pat, do_parse!(
902 keyword!("box") >>
903 pat: pat >>
904 (Pat::Box(Box::new(pat)))
905 ));
906
David Tolnayb4ad3b52016-10-01 21:58:13 -0700907 named!(pat_ident -> Pat, do_parse!(
908 mode: option!(keyword!("ref")) >>
909 mutability: mutability >>
910 name: ident >>
David Tolnay8b308c22016-10-03 01:24:10 -0700911 not!(peek!(punct!("<"))) >>
912 not!(peek!(punct!("::"))) >>
David Tolnayb4ad3b52016-10-01 21:58:13 -0700913 subpat: option!(preceded!(punct!("@"), pat)) >>
914 (Pat::Ident(
915 if mode.is_some() {
916 BindingMode::ByRef(mutability)
917 } else {
918 BindingMode::ByValue(mutability)
919 },
920 name,
921 subpat.map(Box::new),
922 ))
923 ));
924
David Tolnayaa610942016-10-03 22:22:49 -0700925 named!(pat_tuple_struct -> Pat, do_parse!(
926 path: path >>
927 tuple: pat_tuple_helper >>
928 (Pat::TupleStruct(path, tuple.0, tuple.1))
929 ));
930
David Tolnay8d9e81a2016-10-03 22:36:32 -0700931 named!(pat_struct -> Pat, do_parse!(
932 path: path >>
933 punct!("{") >>
934 fields: separated_list!(punct!(","), field_pat) >>
935 more: option!(preceded!(
936 cond!(!fields.is_empty(), punct!(",")),
937 punct!("..")
938 )) >>
939 punct!("}") >>
940 (Pat::Struct(path, fields, more.is_some()))
941 ));
942
943 named!(field_pat -> FieldPat, alt!(
944 do_parse!(
945 ident: ident >>
946 punct!(":") >>
947 pat: pat >>
948 (FieldPat {
949 ident: ident,
950 pat: Box::new(pat),
951 is_shorthand: false,
952 })
953 )
954 |
955 do_parse!(
956 mode: option!(keyword!("ref")) >>
957 mutability: mutability >>
958 ident: ident >>
959 (FieldPat {
960 ident: ident.clone(),
961 pat: Box::new(Pat::Ident(
962 if mode.is_some() {
963 BindingMode::ByRef(mutability)
964 } else {
965 BindingMode::ByValue(mutability)
966 },
967 ident,
968 None,
969 )),
970 is_shorthand: true,
971 })
972 )
973 ));
974
David Tolnay9636c052016-10-02 17:11:17 -0700975 named!(pat_path -> Pat, map!(qpath, |(qself, path)| Pat::Path(qself, path)));
976
David Tolnayaa610942016-10-03 22:22:49 -0700977 named!(pat_tuple -> Pat, map!(
978 pat_tuple_helper,
979 |(pats, dotdot)| Pat::Tuple(pats, dotdot)
980 ));
981
982 named!(pat_tuple_helper -> (Vec<Pat>, Option<usize>), do_parse!(
David Tolnayfbb73232016-10-03 01:00:06 -0700983 punct!("(") >>
984 mut elems: separated_list!(punct!(","), pat) >>
985 dotdot: option!(do_parse!(
986 cond!(!elems.is_empty(), punct!(",")) >>
987 punct!("..") >>
988 rest: many0!(preceded!(punct!(","), pat)) >>
989 cond!(!rest.is_empty(), option!(punct!(","))) >>
990 (rest)
991 )) >>
992 cond!(!elems.is_empty() && dotdot.is_none(), option!(punct!(","))) >>
993 punct!(")") >>
994 (match dotdot {
995 Some(rest) => {
996 let pos = elems.len();
997 elems.extend(rest);
David Tolnayaa610942016-10-03 22:22:49 -0700998 (elems, Some(pos))
David Tolnayfbb73232016-10-03 01:00:06 -0700999 }
David Tolnayaa610942016-10-03 22:22:49 -07001000 None => (elems, None),
David Tolnayfbb73232016-10-03 01:00:06 -07001001 })
1002 ));
1003
David Tolnayffdb97f2016-10-03 01:28:33 -07001004 named!(pat_ref -> Pat, do_parse!(
1005 punct!("&") >>
1006 mutability: mutability >>
1007 pat: pat >>
1008 (Pat::Ref(Box::new(pat), mutability))
1009 ));
1010
David Tolnay8b308c22016-10-03 01:24:10 -07001011 named!(pat_lit -> Pat, map!(lit, |lit| Pat::Lit(Box::new(lit))));
1012
1013 named!(pat_range -> Pat, do_parse!(
1014 lo: lit >>
1015 punct!("...") >>
1016 hi: lit >>
1017 (Pat::Range(Box::new(lo), Box::new(hi)))
1018 ));
1019
David Tolnay89e05672016-10-02 14:39:42 -07001020 named!(capture_by -> CaptureBy, alt!(
1021 keyword!("move") => { |_| CaptureBy::Value }
1022 |
1023 epsilon!() => { |_| CaptureBy::Ref }
1024 ));
1025
David Tolnay8b07f372016-09-30 10:28:40 -07001026 named!(label -> Ident, map!(lifetime, |lt: Lifetime| lt.ident));
David Tolnayb9c8e322016-09-23 20:48:37 -07001027}
1028
David Tolnayf4bbbd92016-09-23 14:41:55 -07001029#[cfg(feature = "printing")]
1030mod printing {
1031 use super::*;
David Tolnayca085422016-10-04 00:12:38 -07001032 use {FnArg, FunctionRetTy, Mutability, Ty};
David Tolnay13b3d352016-10-03 00:31:15 -07001033 use attr::FilterAttrs;
David Tolnayf4bbbd92016-09-23 14:41:55 -07001034 use quote::{Tokens, ToTokens};
1035
1036 impl ToTokens for Expr {
1037 fn to_tokens(&self, tokens: &mut Tokens) {
1038 match *self {
David Tolnaybb6feae2016-10-02 21:25:20 -07001039 Expr::Box(ref inner) => {
1040 tokens.append("box");
1041 inner.to_tokens(tokens);
1042 }
1043 Expr::Vec(ref tys) => {
1044 tokens.append("[");
1045 tokens.append_separated(tys, ",");
1046 tokens.append("]");
1047 }
David Tolnay9636c052016-10-02 17:11:17 -07001048 Expr::Call(ref func, ref args) => {
1049 func.to_tokens(tokens);
1050 tokens.append("(");
1051 tokens.append_separated(args, ",");
1052 tokens.append(")");
1053 }
1054 Expr::MethodCall(ref ident, ref ascript, ref args) => {
1055 args[0].to_tokens(tokens);
1056 tokens.append(".");
1057 ident.to_tokens(tokens);
1058 if ascript.len() > 0 {
1059 tokens.append("::");
1060 tokens.append("<");
1061 tokens.append_separated(ascript, ",");
1062 tokens.append(">");
1063 }
1064 tokens.append("(");
1065 tokens.append_separated(&args[1..], ",");
1066 tokens.append(")");
1067 }
David Tolnay47a877c2016-10-01 16:50:55 -07001068 Expr::Tup(ref fields) => {
1069 tokens.append("(");
1070 tokens.append_separated(fields, ",");
1071 if fields.len() == 1 {
1072 tokens.append(",");
1073 }
1074 tokens.append(")");
1075 }
David Tolnay89e05672016-10-02 14:39:42 -07001076 Expr::Binary(op, ref left, ref right) => {
1077 left.to_tokens(tokens);
1078 op.to_tokens(tokens);
1079 right.to_tokens(tokens);
1080 }
David Tolnay3c2467c2016-10-02 17:55:08 -07001081 Expr::Unary(op, ref expr) => {
1082 op.to_tokens(tokens);
1083 expr.to_tokens(tokens);
1084 }
David Tolnayf4bbbd92016-09-23 14:41:55 -07001085 Expr::Lit(ref lit) => lit.to_tokens(tokens),
David Tolnay3c2467c2016-10-02 17:55:08 -07001086 Expr::Cast(ref expr, ref ty) => {
1087 expr.to_tokens(tokens);
1088 tokens.append("as");
1089 ty.to_tokens(tokens);
1090 }
1091 Expr::Type(ref expr, ref ty) => {
1092 expr.to_tokens(tokens);
1093 tokens.append(":");
1094 ty.to_tokens(tokens);
1095 }
1096 Expr::If(ref cond, ref then_block, ref else_block) => {
1097 tokens.append("if");
1098 cond.to_tokens(tokens);
1099 then_block.to_tokens(tokens);
1100 if let Some(ref else_block) = *else_block {
1101 tokens.append("else");
1102 else_block.to_tokens(tokens);
1103 }
1104 }
David Tolnay29f9ce12016-10-02 20:58:40 -07001105 Expr::IfLet(ref pat, ref expr, ref then_block, ref else_block) => {
1106 tokens.append("if");
1107 tokens.append("let");
1108 pat.to_tokens(tokens);
1109 tokens.append("=");
1110 expr.to_tokens(tokens);
1111 then_block.to_tokens(tokens);
1112 if let Some(ref else_block) = *else_block {
1113 tokens.append("else");
1114 else_block.to_tokens(tokens);
1115 }
1116 }
David Tolnaybb6feae2016-10-02 21:25:20 -07001117 Expr::While(ref cond, ref body, ref label) => {
1118 if let Some(ref label) = *label {
1119 label.to_tokens(tokens);
1120 tokens.append(":");
1121 }
1122 tokens.append("while");
1123 cond.to_tokens(tokens);
1124 body.to_tokens(tokens);
1125 }
1126 Expr::WhileLet(ref pat, ref expr, ref body, ref label) => {
1127 if let Some(ref label) = *label {
1128 label.to_tokens(tokens);
1129 tokens.append(":");
1130 }
1131 tokens.append("while");
1132 tokens.append("let");
1133 pat.to_tokens(tokens);
1134 tokens.append("=");
1135 expr.to_tokens(tokens);
1136 body.to_tokens(tokens);
1137 }
1138 Expr::ForLoop(ref pat, ref expr, ref body, ref label) => {
1139 if let Some(ref label) = *label {
1140 label.to_tokens(tokens);
1141 tokens.append(":");
1142 }
1143 tokens.append("for");
1144 pat.to_tokens(tokens);
1145 tokens.append("in");
1146 expr.to_tokens(tokens);
1147 body.to_tokens(tokens);
1148 }
1149 Expr::Loop(ref body, ref label) => {
1150 if let Some(ref label) = *label {
1151 label.to_tokens(tokens);
1152 tokens.append(":");
1153 }
1154 tokens.append("loop");
1155 body.to_tokens(tokens);
1156 }
David Tolnayb4ad3b52016-10-01 21:58:13 -07001157 Expr::Match(ref expr, ref arms) => {
1158 tokens.append("match");
1159 expr.to_tokens(tokens);
1160 tokens.append("{");
1161 tokens.append_separated(arms, ",");
1162 tokens.append("}");
1163 }
David Tolnay89e05672016-10-02 14:39:42 -07001164 Expr::Closure(capture, ref decl, ref body) => {
1165 capture.to_tokens(tokens);
1166 tokens.append("|");
1167 for (i, input) in decl.inputs.iter().enumerate() {
1168 if i > 0 {
1169 tokens.append(",");
1170 }
David Tolnayca085422016-10-04 00:12:38 -07001171 match *input {
1172 FnArg::Captured(ref pat, Ty::Infer) => {
1173 pat.to_tokens(tokens);
David Tolnaydaaf7742016-10-03 11:11:43 -07001174 }
David Tolnayca085422016-10-04 00:12:38 -07001175 _ => input.to_tokens(tokens),
David Tolnay89e05672016-10-02 14:39:42 -07001176 }
1177 }
1178 tokens.append("|");
1179 match decl.output {
1180 FunctionRetTy::Default => {
1181 if body.stmts.len() == 1 {
1182 if let Stmt::Expr(ref expr) = body.stmts[0] {
1183 expr.to_tokens(tokens);
1184 } else {
1185 body.to_tokens(tokens);
1186 }
1187 } else {
1188 body.to_tokens(tokens);
1189 }
1190 }
1191 FunctionRetTy::Ty(ref ty) => {
1192 tokens.append("->");
1193 ty.to_tokens(tokens);
1194 body.to_tokens(tokens);
1195 }
1196 }
1197 }
1198 Expr::Block(rules, ref block) => {
1199 rules.to_tokens(tokens);
1200 block.to_tokens(tokens);
1201 }
David Tolnaybb6feae2016-10-02 21:25:20 -07001202 Expr::Assign(ref var, ref expr) => {
1203 var.to_tokens(tokens);
1204 tokens.append("=");
1205 expr.to_tokens(tokens);
1206 }
1207 Expr::AssignOp(op, ref var, ref expr) => {
1208 var.to_tokens(tokens);
1209 tokens.append(op.assign_op());
1210 expr.to_tokens(tokens);
1211 }
1212 Expr::Field(ref expr, ref field) => {
1213 expr.to_tokens(tokens);
1214 tokens.append(".");
1215 field.to_tokens(tokens);
1216 }
1217 Expr::TupField(ref expr, field) => {
1218 expr.to_tokens(tokens);
1219 tokens.append(".");
1220 tokens.append(&field.to_string());
1221 }
1222 Expr::Index(ref expr, ref index) => {
1223 expr.to_tokens(tokens);
1224 tokens.append("[");
1225 index.to_tokens(tokens);
1226 tokens.append("]");
1227 }
1228 Expr::Range(ref from, ref to, limits) => {
1229 from.to_tokens(tokens);
1230 match limits {
1231 RangeLimits::HalfOpen => tokens.append(".."),
1232 RangeLimits::Closed => tokens.append("..."),
1233 }
1234 to.to_tokens(tokens);
1235 }
David Tolnay8b308c22016-10-03 01:24:10 -07001236 Expr::Path(None, ref path) => path.to_tokens(tokens),
David Tolnay89e05672016-10-02 14:39:42 -07001237 Expr::Path(Some(ref qself), ref path) => {
1238 tokens.append("<");
1239 qself.ty.to_tokens(tokens);
1240 if qself.position > 0 {
1241 tokens.append("as");
David Tolnaydaaf7742016-10-03 11:11:43 -07001242 for (i, segment) in path.segments
1243 .iter()
1244 .take(qself.position)
1245 .enumerate() {
David Tolnay89e05672016-10-02 14:39:42 -07001246 if i > 0 || path.global {
1247 tokens.append("::");
1248 }
1249 segment.to_tokens(tokens);
1250 }
1251 }
1252 tokens.append(">");
1253 for segment in path.segments.iter().skip(qself.position) {
1254 tokens.append("::");
1255 segment.to_tokens(tokens);
1256 }
1257 }
David Tolnay3c2467c2016-10-02 17:55:08 -07001258 Expr::AddrOf(mutability, ref expr) => {
1259 tokens.append("&");
1260 mutability.to_tokens(tokens);
1261 expr.to_tokens(tokens);
1262 }
1263 Expr::Break(ref opt_label) => {
1264 tokens.append("break");
1265 opt_label.to_tokens(tokens);
1266 }
1267 Expr::Continue(ref opt_label) => {
1268 tokens.append("continue");
1269 opt_label.to_tokens(tokens);
1270 }
David Tolnay42602292016-10-01 22:25:45 -07001271 Expr::Ret(ref opt_expr) => {
1272 tokens.append("return");
1273 opt_expr.to_tokens(tokens);
1274 }
David Tolnaycc3d66e2016-10-02 23:36:05 -07001275 Expr::Mac(ref mac) => mac.to_tokens(tokens),
David Tolnay055a7042016-10-02 19:23:54 -07001276 Expr::Struct(ref path, ref fields, ref base) => {
1277 path.to_tokens(tokens);
1278 tokens.append("{");
1279 tokens.append_separated(fields, ",");
1280 if let Some(ref base) = *base {
1281 if !fields.is_empty() {
1282 tokens.append(",");
1283 }
1284 tokens.append("..");
1285 base.to_tokens(tokens);
1286 }
1287 tokens.append("}");
1288 }
1289 Expr::Repeat(ref expr, ref times) => {
1290 tokens.append("[");
1291 expr.to_tokens(tokens);
1292 tokens.append(";");
1293 times.to_tokens(tokens);
1294 tokens.append("]");
1295 }
David Tolnay89e05672016-10-02 14:39:42 -07001296 Expr::Paren(ref expr) => {
1297 tokens.append("(");
1298 expr.to_tokens(tokens);
1299 tokens.append(")");
1300 }
David Tolnay3c2467c2016-10-02 17:55:08 -07001301 Expr::Try(ref expr) => {
1302 expr.to_tokens(tokens);
1303 tokens.append("?");
1304 }
David Tolnayf4bbbd92016-09-23 14:41:55 -07001305 }
1306 }
1307 }
David Tolnayb4ad3b52016-10-01 21:58:13 -07001308
David Tolnaybb6feae2016-10-02 21:25:20 -07001309 impl BinOp {
1310 fn op(&self) -> &'static str {
1311 match *self {
1312 BinOp::Add => "+",
1313 BinOp::Sub => "-",
1314 BinOp::Mul => "*",
1315 BinOp::Div => "/",
1316 BinOp::Rem => "%",
1317 BinOp::And => "&&",
1318 BinOp::Or => "||",
1319 BinOp::BitXor => "^",
1320 BinOp::BitAnd => "&",
1321 BinOp::BitOr => "|",
1322 BinOp::Shl => "<<",
1323 BinOp::Shr => ">>",
1324 BinOp::Eq => "==",
1325 BinOp::Lt => "<",
1326 BinOp::Le => "<=",
1327 BinOp::Ne => "!=",
1328 BinOp::Ge => ">=",
1329 BinOp::Gt => ">",
1330 }
1331 }
1332
1333 fn assign_op(&self) -> &'static str {
1334 match *self {
1335 BinOp::Add => "+=",
1336 BinOp::Sub => "-=",
1337 BinOp::Mul => "*=",
1338 BinOp::Div => "/=",
1339 BinOp::Rem => "%=",
1340 BinOp::BitXor => "^=",
1341 BinOp::BitAnd => "&=",
1342 BinOp::BitOr => "|=",
1343 BinOp::Shl => "<<=",
1344 BinOp::Shr => ">>=",
1345 _ => panic!("bad assignment operator"),
1346 }
1347 }
1348 }
1349
David Tolnay89e05672016-10-02 14:39:42 -07001350 impl ToTokens for BinOp {
1351 fn to_tokens(&self, tokens: &mut Tokens) {
David Tolnaybb6feae2016-10-02 21:25:20 -07001352 tokens.append(self.op());
1353 }
1354 }
1355
1356 impl UnOp {
1357 fn op(&self) -> &'static str {
David Tolnay89e05672016-10-02 14:39:42 -07001358 match *self {
David Tolnaybb6feae2016-10-02 21:25:20 -07001359 UnOp::Deref => "*",
1360 UnOp::Not => "!",
1361 UnOp::Neg => "-",
David Tolnay89e05672016-10-02 14:39:42 -07001362 }
1363 }
1364 }
1365
David Tolnay3c2467c2016-10-02 17:55:08 -07001366 impl ToTokens for UnOp {
1367 fn to_tokens(&self, tokens: &mut Tokens) {
David Tolnaybb6feae2016-10-02 21:25:20 -07001368 tokens.append(self.op());
David Tolnay3c2467c2016-10-02 17:55:08 -07001369 }
1370 }
1371
David Tolnay055a7042016-10-02 19:23:54 -07001372 impl ToTokens for FieldValue {
1373 fn to_tokens(&self, tokens: &mut Tokens) {
1374 self.ident.to_tokens(tokens);
1375 tokens.append(":");
1376 self.expr.to_tokens(tokens);
1377 }
1378 }
1379
David Tolnayb4ad3b52016-10-01 21:58:13 -07001380 impl ToTokens for Arm {
1381 fn to_tokens(&self, tokens: &mut Tokens) {
1382 for attr in &self.attrs {
1383 attr.to_tokens(tokens);
1384 }
1385 tokens.append_separated(&self.pats, "|");
1386 if let Some(ref guard) = self.guard {
1387 tokens.append("if");
1388 guard.to_tokens(tokens);
1389 }
1390 tokens.append("=>");
1391 self.body.to_tokens(tokens);
1392 match *self.body {
David Tolnaydaaf7742016-10-03 11:11:43 -07001393 Expr::Block(_, _) => {
1394 // no comma
1395 }
David Tolnayb4ad3b52016-10-01 21:58:13 -07001396 _ => tokens.append(","),
1397 }
1398 }
1399 }
1400
1401 impl ToTokens for Pat {
1402 fn to_tokens(&self, tokens: &mut Tokens) {
1403 match *self {
1404 Pat::Wild => tokens.append("_"),
1405 Pat::Ident(mode, ref ident, ref subpat) => {
1406 mode.to_tokens(tokens);
1407 ident.to_tokens(tokens);
1408 if let Some(ref subpat) = *subpat {
1409 tokens.append("@");
1410 subpat.to_tokens(tokens);
1411 }
1412 }
David Tolnay8d9e81a2016-10-03 22:36:32 -07001413 Pat::Struct(ref path, ref fields, dots) => {
1414 path.to_tokens(tokens);
1415 tokens.append("{");
1416 tokens.append_separated(fields, ",");
1417 if dots {
1418 if !fields.is_empty() {
1419 tokens.append(",");
1420 }
1421 tokens.append("..");
1422 }
1423 tokens.append("}");
1424 }
David Tolnayaa610942016-10-03 22:22:49 -07001425 Pat::TupleStruct(ref path, ref pats, dotpos) => {
1426 path.to_tokens(tokens);
1427 tokens.append("(");
1428 match dotpos {
1429 Some(pos) => {
1430 if pos > 0 {
1431 tokens.append_separated(&pats[..pos], ",");
1432 tokens.append(",");
1433 }
1434 tokens.append("..");
1435 if pos < pats.len() {
1436 tokens.append(",");
1437 tokens.append_separated(&pats[pos..], ",");
1438 }
1439 }
1440 None => tokens.append_separated(pats, ","),
1441 }
1442 tokens.append(")");
1443 }
David Tolnay8b308c22016-10-03 01:24:10 -07001444 Pat::Path(None, ref path) => path.to_tokens(tokens),
1445 Pat::Path(Some(ref qself), ref path) => {
1446 tokens.append("<");
1447 qself.ty.to_tokens(tokens);
1448 if qself.position > 0 {
1449 tokens.append("as");
David Tolnaydaaf7742016-10-03 11:11:43 -07001450 for (i, segment) in path.segments
1451 .iter()
1452 .take(qself.position)
1453 .enumerate() {
David Tolnay8b308c22016-10-03 01:24:10 -07001454 if i > 0 || path.global {
1455 tokens.append("::");
1456 }
1457 segment.to_tokens(tokens);
1458 }
1459 }
1460 tokens.append(">");
1461 for segment in path.segments.iter().skip(qself.position) {
1462 tokens.append("::");
1463 segment.to_tokens(tokens);
1464 }
1465 }
David Tolnayfbb73232016-10-03 01:00:06 -07001466 Pat::Tuple(ref pats, dotpos) => {
1467 tokens.append("(");
1468 match dotpos {
1469 Some(pos) => {
1470 if pos > 0 {
1471 tokens.append_separated(&pats[..pos], ",");
1472 tokens.append(",");
1473 }
1474 tokens.append("..");
1475 if pos < pats.len() {
1476 tokens.append(",");
1477 tokens.append_separated(&pats[pos..], ",");
1478 }
1479 }
1480 None => tokens.append_separated(pats, ","),
1481 }
1482 tokens.append(")");
1483 }
1484 Pat::Box(ref inner) => {
1485 tokens.append("box");
1486 inner.to_tokens(tokens);
1487 }
David Tolnayffdb97f2016-10-03 01:28:33 -07001488 Pat::Ref(ref target, mutability) => {
1489 tokens.append("&");
1490 mutability.to_tokens(tokens);
1491 target.to_tokens(tokens);
1492 }
David Tolnay8b308c22016-10-03 01:24:10 -07001493 Pat::Lit(ref lit) => lit.to_tokens(tokens),
1494 Pat::Range(ref lo, ref hi) => {
1495 lo.to_tokens(tokens);
1496 tokens.append("...");
1497 hi.to_tokens(tokens);
1498 }
David Tolnay16709ba2016-10-05 23:11:32 -07001499 Pat::Slice(ref _before, ref _dots, ref _after) => unimplemented!(),
David Tolnaycc3d66e2016-10-02 23:36:05 -07001500 Pat::Mac(ref mac) => mac.to_tokens(tokens),
David Tolnayb4ad3b52016-10-01 21:58:13 -07001501 }
1502 }
1503 }
1504
David Tolnay8d9e81a2016-10-03 22:36:32 -07001505 impl ToTokens for FieldPat {
1506 fn to_tokens(&self, tokens: &mut Tokens) {
1507 if !self.is_shorthand {
1508 self.ident.to_tokens(tokens);
1509 tokens.append(":");
1510 }
1511 self.pat.to_tokens(tokens);
1512 }
1513 }
1514
David Tolnayb4ad3b52016-10-01 21:58:13 -07001515 impl ToTokens for BindingMode {
1516 fn to_tokens(&self, tokens: &mut Tokens) {
1517 match *self {
1518 BindingMode::ByRef(Mutability::Immutable) => {
1519 tokens.append("ref");
1520 }
1521 BindingMode::ByRef(Mutability::Mutable) => {
1522 tokens.append("ref");
1523 tokens.append("mut");
1524 }
1525 BindingMode::ByValue(Mutability::Immutable) => {}
1526 BindingMode::ByValue(Mutability::Mutable) => {
1527 tokens.append("mut");
1528 }
1529 }
1530 }
1531 }
David Tolnay42602292016-10-01 22:25:45 -07001532
David Tolnay89e05672016-10-02 14:39:42 -07001533 impl ToTokens for CaptureBy {
1534 fn to_tokens(&self, tokens: &mut Tokens) {
1535 match *self {
1536 CaptureBy::Value => tokens.append("move"),
David Tolnaydaaf7742016-10-03 11:11:43 -07001537 CaptureBy::Ref => {
1538 // nothing
1539 }
David Tolnay89e05672016-10-02 14:39:42 -07001540 }
1541 }
1542 }
1543
David Tolnay42602292016-10-01 22:25:45 -07001544 impl ToTokens for Block {
1545 fn to_tokens(&self, tokens: &mut Tokens) {
David Tolnay42602292016-10-01 22:25:45 -07001546 tokens.append("{");
1547 for stmt in &self.stmts {
1548 stmt.to_tokens(tokens);
1549 }
1550 tokens.append("}");
1551 }
1552 }
1553
1554 impl ToTokens for BlockCheckMode {
1555 fn to_tokens(&self, tokens: &mut Tokens) {
1556 match *self {
David Tolnaydaaf7742016-10-03 11:11:43 -07001557 BlockCheckMode::Default => {
1558 // nothing
1559 }
David Tolnay42602292016-10-01 22:25:45 -07001560 BlockCheckMode::Unsafe => tokens.append("unsafe"),
1561 }
1562 }
1563 }
1564
1565 impl ToTokens for Stmt {
1566 fn to_tokens(&self, tokens: &mut Tokens) {
1567 match *self {
David Tolnay191e0582016-10-02 18:31:09 -07001568 Stmt::Local(ref local) => local.to_tokens(tokens),
David Tolnay42602292016-10-01 22:25:45 -07001569 Stmt::Item(ref item) => item.to_tokens(tokens),
1570 Stmt::Expr(ref expr) => expr.to_tokens(tokens),
1571 Stmt::Semi(ref expr) => {
1572 expr.to_tokens(tokens);
1573 tokens.append(";");
1574 }
David Tolnay13b3d352016-10-03 00:31:15 -07001575 Stmt::Mac(ref mac) => {
1576 let (ref mac, style, ref attrs) = **mac;
1577 for attr in attrs.outer() {
1578 attr.to_tokens(tokens);
1579 }
1580 mac.to_tokens(tokens);
1581 match style {
1582 MacStmtStyle::Semicolon => tokens.append(";"),
David Tolnaydaaf7742016-10-03 11:11:43 -07001583 MacStmtStyle::Braces | MacStmtStyle::NoBraces => {
1584 // no semicolon
1585 }
David Tolnay13b3d352016-10-03 00:31:15 -07001586 }
1587 }
David Tolnay42602292016-10-01 22:25:45 -07001588 }
1589 }
1590 }
David Tolnay191e0582016-10-02 18:31:09 -07001591
1592 impl ToTokens for Local {
1593 fn to_tokens(&self, tokens: &mut Tokens) {
1594 tokens.append("let");
1595 self.pat.to_tokens(tokens);
1596 if let Some(ref ty) = self.ty {
1597 tokens.append(":");
1598 ty.to_tokens(tokens);
1599 }
1600 if let Some(ref init) = self.init {
1601 tokens.append("=");
1602 init.to_tokens(tokens);
1603 }
1604 tokens.append(";");
1605 }
1606 }
David Tolnayf4bbbd92016-09-23 14:41:55 -07001607}