blob: e31e2ad6ad41ee09bb4674c43008a543225484ec [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
276 Lit(Box<Expr>),
277 /// A range pattern, e.g. `1...2`
278 Range(Box<Expr>, Box<Expr>),
279 /// `[a, b, ..i, y, z]` is represented as:
David Tolnay432afc02016-09-24 07:37:13 -0700280 /// `Pat::Vec(box [a, b], Some(i), box [y, z])`
David Tolnayf4bbbd92016-09-23 14:41:55 -0700281 Vec(Vec<Pat>, Option<Box<Pat>>, Vec<Pat>),
282 /// 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 Tolnay055a7042016-10-02 19:23:54 -0700355 expr_lit // needs to be before expr_struct
356 |
357 expr_struct // needs to be before expr_path
358 |
359 expr_paren // needs to be before expr_tup
David Tolnay89e05672016-10-02 14:39:42 -0700360 |
David Tolnay939766a2016-09-23 23:48:12 -0700361 expr_box
David Tolnayfa0edf22016-09-23 22:58:24 -0700362 |
David Tolnay939766a2016-09-23 23:48:12 -0700363 expr_vec
David Tolnayfa0edf22016-09-23 22:58:24 -0700364 |
David Tolnay939766a2016-09-23 23:48:12 -0700365 expr_tup
David Tolnayfa0edf22016-09-23 22:58:24 -0700366 |
David Tolnay939766a2016-09-23 23:48:12 -0700367 expr_unary
David Tolnayfa0edf22016-09-23 22:58:24 -0700368 |
David Tolnay939766a2016-09-23 23:48:12 -0700369 expr_if
Gregory Katz3e562cc2016-09-28 18:33:02 -0400370 |
371 expr_while
David Tolnaybb6feae2016-10-02 21:25:20 -0700372 |
373 expr_for_loop
Gregory Katze5f35682016-09-27 14:20:55 -0400374 |
375 expr_loop
David Tolnayb4ad3b52016-10-01 21:58:13 -0700376 |
377 expr_match
David Tolnay89e05672016-10-02 14:39:42 -0700378 |
379 expr_closure
David Tolnay939766a2016-09-23 23:48:12 -0700380 |
381 expr_block
David Tolnay89e05672016-10-02 14:39:42 -0700382 |
383 expr_path
David Tolnay3c2467c2016-10-02 17:55:08 -0700384 |
385 expr_addr_of
Gregory Katzfd6935d2016-09-30 22:51:25 -0400386 |
387 expr_break
388 |
389 expr_continue
390 |
391 expr_ret
David Tolnay84aa0752016-10-02 23:01:13 -0700392 |
393 expr_mac
David Tolnay055a7042016-10-02 19:23:54 -0700394 |
395 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 Tolnaya96a3fa2016-09-24 07:17:42 -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)) >>
680 (FnArg {
681 pat: pat,
682 ty: ty.unwrap_or(Ty::Infer),
683 })
684 ));
685
Gregory Katz3e562cc2016-09-28 18:33:02 -0400686 named!(expr_while -> Expr, do_parse!(
David Tolnay8b07f372016-09-30 10:28:40 -0700687 lbl: option!(terminated!(label, punct!(":"))) >>
David Tolnay57ffbde2016-09-30 09:38:04 -0700688 keyword!("while") >>
David Tolnaybb6feae2016-10-02 21:25:20 -0700689 cond: cond >>
Gregory Katz3e562cc2016-09-28 18:33:02 -0400690 while_block: block >>
David Tolnaybb6feae2016-10-02 21:25:20 -0700691 (match cond {
692 Cond::Let(pat, expr) => Expr::WhileLet(
693 Box::new(pat),
694 Box::new(expr),
695 while_block,
696 lbl,
697 ),
698 Cond::Expr(cond) => Expr::While(
699 Box::new(cond),
700 while_block,
701 lbl,
702 ),
703 })
Gregory Katz3e562cc2016-09-28 18:33:02 -0400704 ));
705
Gregory Katzfd6935d2016-09-30 22:51:25 -0400706 named!(expr_continue -> Expr, do_parse!(
707 keyword!("continue") >>
708 lbl: option!(label) >>
David Tolnay055a7042016-10-02 19:23:54 -0700709 (Expr::Continue(lbl))
Gregory Katzfd6935d2016-09-30 22:51:25 -0400710 ));
711
712 named!(expr_break -> Expr, do_parse!(
713 keyword!("break") >>
714 lbl: option!(label) >>
David Tolnay055a7042016-10-02 19:23:54 -0700715 (Expr::Break(lbl))
Gregory Katzfd6935d2016-09-30 22:51:25 -0400716 ));
717
718 named!(expr_ret -> Expr, do_parse!(
719 keyword!("return") >>
720 ret_value: option!(expr) >>
David Tolnay055a7042016-10-02 19:23:54 -0700721 (Expr::Ret(ret_value.map(Box::new)))
722 ));
723
724 named!(expr_struct -> Expr, do_parse!(
725 path: path >>
726 punct!("{") >>
727 fields: separated_list!(punct!(","), field_value) >>
728 base: option!(do_parse!(
729 cond!(!fields.is_empty(), punct!(",")) >>
730 punct!("..") >>
731 base: expr >>
732 (base)
733 )) >>
734 punct!("}") >>
735 (Expr::Struct(path, fields, base.map(Box::new)))
736 ));
737
738 named!(field_value -> FieldValue, do_parse!(
739 name: ident >>
740 punct!(":") >>
741 value: expr >>
742 (FieldValue {
743 ident: name,
744 expr: value,
745 })
746 ));
747
748 named!(expr_repeat -> Expr, do_parse!(
749 punct!("[") >>
750 value: expr >>
751 punct!(";") >>
752 times: expr >>
753 punct!("]") >>
754 (Expr::Repeat(Box::new(value), Box::new(times)))
Gregory Katzfd6935d2016-09-30 22:51:25 -0400755 ));
756
David Tolnay42602292016-10-01 22:25:45 -0700757 named!(expr_block -> Expr, do_parse!(
David Tolnay939766a2016-09-23 23:48:12 -0700758 rules: block_check_mode >>
David Tolnay42602292016-10-01 22:25:45 -0700759 b: block >>
David Tolnay89e05672016-10-02 14:39:42 -0700760 (Expr::Block(rules, Block {
David Tolnay42602292016-10-01 22:25:45 -0700761 stmts: b.stmts,
David Tolnay89e05672016-10-02 14:39:42 -0700762 }))
763 ));
764
David Tolnay9636c052016-10-02 17:11:17 -0700765 named!(expr_path -> Expr, map!(qpath, |(qself, path)| Expr::Path(qself, path)));
David Tolnay42602292016-10-01 22:25:45 -0700766
David Tolnay3c2467c2016-10-02 17:55:08 -0700767 named!(expr_addr_of -> Expr, do_parse!(
768 punct!("&") >>
769 mutability: mutability >>
770 expr: expr >>
771 (Expr::AddrOf(mutability, Box::new(expr)))
772 ));
773
David Tolnay42602292016-10-01 22:25:45 -0700774 named!(pub block -> Block, do_parse!(
David Tolnay939766a2016-09-23 23:48:12 -0700775 punct!("{") >>
776 stmts: within_block >>
777 punct!("}") >>
778 (Block {
779 stmts: stmts,
David Tolnay939766a2016-09-23 23:48:12 -0700780 })
781 ));
782
783 named!(block_check_mode -> BlockCheckMode, alt!(
David Tolnay10413f02016-09-30 09:12:02 -0700784 keyword!("unsafe") => { |_| BlockCheckMode::Unsafe }
David Tolnay939766a2016-09-23 23:48:12 -0700785 |
786 epsilon!() => { |_| BlockCheckMode::Default }
787 ));
788
789 named!(within_block -> Vec<Stmt>, do_parse!(
David Tolnaycfe55022016-10-02 22:02:27 -0700790 many0!(punct!(";")) >>
791 mut standalone: many0!(terminated!(standalone_stmt, many0!(punct!(";")))) >>
David Tolnay939766a2016-09-23 23:48:12 -0700792 last: option!(expr) >>
793 (match last {
David Tolnaycfe55022016-10-02 22:02:27 -0700794 None => standalone,
David Tolnay939766a2016-09-23 23:48:12 -0700795 Some(last) => {
David Tolnaycfe55022016-10-02 22:02:27 -0700796 standalone.push(Stmt::Expr(Box::new(last)));
797 standalone
David Tolnay939766a2016-09-23 23:48:12 -0700798 }
799 })
800 ));
801
802 named!(standalone_stmt -> Stmt, alt!(
David Tolnay191e0582016-10-02 18:31:09 -0700803 stmt_local
804 |
805 stmt_item
806 |
David Tolnaycfe55022016-10-02 22:02:27 -0700807 stmt_expr
David Tolnay939766a2016-09-23 23:48:12 -0700808 ));
809
David Tolnay191e0582016-10-02 18:31:09 -0700810 named!(stmt_local -> Stmt, do_parse!(
811 attrs: many0!(outer_attr) >>
812 keyword!("let") >>
813 pat: pat >>
814 ty: option!(preceded!(punct!(":"), ty)) >>
815 init: option!(preceded!(punct!("="), expr)) >>
816 punct!(";") >>
817 (Stmt::Local(Box::new(Local {
818 pat: Box::new(pat),
819 ty: ty.map(Box::new),
820 init: init.map(Box::new),
821 attrs: attrs,
822 })))
823 ));
824
825 named!(stmt_item -> Stmt, map!(item, |i| Stmt::Item(Box::new(i))));
826
David Tolnaycfe55022016-10-02 22:02:27 -0700827 fn requires_semi(e: &Expr) -> bool {
828 match *e {
David Tolnaycc3d66e2016-10-02 23:36:05 -0700829 Expr::Mac(ref mac) => match mac.tts.last() {
830 Some(&TokenTree::Delimited(
831 Delimited { delim: DelimToken::Brace, .. }
832 )) => false,
833 _ => true,
834 },
David Tolnaycfe55022016-10-02 22:02:27 -0700835
836 Expr::If(_, _, _) |
837 Expr::IfLet(_, _, _, _) |
838 Expr::While(_, _, _) |
839 Expr::WhileLet(_, _, _, _) |
840 Expr::ForLoop(_, _, _, _) |
841 Expr::Loop(_, _) |
842 Expr::Match(_, _) |
843 Expr::Block(_, _) => false,
844
845 _ => true,
846 }
847 }
848
849 named!(stmt_expr -> Stmt, do_parse!(
David Tolnay939766a2016-09-23 23:48:12 -0700850 e: expr >>
David Tolnaycfe55022016-10-02 22:02:27 -0700851 semi: option!(punct!(";")) >>
852 (if semi.is_some() {
853 Stmt::Semi(Box::new(e))
854 } else if requires_semi(&e) {
855 return Error;
856 } else {
857 Stmt::Expr(Box::new(e))
858 })
David Tolnay939766a2016-09-23 23:48:12 -0700859 ));
David Tolnay8b07f372016-09-30 10:28:40 -0700860
David Tolnay42602292016-10-01 22:25:45 -0700861 named!(pub pat -> Pat, alt!(
David Tolnayb4ad3b52016-10-01 21:58:13 -0700862 pat_wild
863 |
864 pat_ident
865 // TODO: Struct
866 // TODO: TupleStruct
David Tolnay9636c052016-10-02 17:11:17 -0700867 |
868 pat_path
David Tolnayb4ad3b52016-10-01 21:58:13 -0700869 // TODO: Tuple
870 // TODO: Box
871 // TODO: Ref
872 // TODO: Lit
873 // TODO: Range
874 // TODO: Vec
David Tolnay84aa0752016-10-02 23:01:13 -0700875 |
876 pat_mac
David Tolnayb4ad3b52016-10-01 21:58:13 -0700877 ));
878
David Tolnay84aa0752016-10-02 23:01:13 -0700879 named!(pat_mac -> Pat, map!(mac, Pat::Mac));
880
David Tolnayb4ad3b52016-10-01 21:58:13 -0700881 named!(pat_wild -> Pat, map!(keyword!("_"), |_| Pat::Wild));
882
883 named!(pat_ident -> Pat, do_parse!(
884 mode: option!(keyword!("ref")) >>
885 mutability: mutability >>
886 name: ident >>
887 subpat: option!(preceded!(punct!("@"), pat)) >>
888 (Pat::Ident(
889 if mode.is_some() {
890 BindingMode::ByRef(mutability)
891 } else {
892 BindingMode::ByValue(mutability)
893 },
894 name,
895 subpat.map(Box::new),
896 ))
897 ));
898
David Tolnay9636c052016-10-02 17:11:17 -0700899 named!(pat_path -> Pat, map!(qpath, |(qself, path)| Pat::Path(qself, path)));
900
David Tolnay89e05672016-10-02 14:39:42 -0700901 named!(capture_by -> CaptureBy, alt!(
902 keyword!("move") => { |_| CaptureBy::Value }
903 |
904 epsilon!() => { |_| CaptureBy::Ref }
905 ));
906
David Tolnay8b07f372016-09-30 10:28:40 -0700907 named!(label -> Ident, map!(lifetime, |lt: Lifetime| lt.ident));
David Tolnayb9c8e322016-09-23 20:48:37 -0700908}
909
David Tolnayf4bbbd92016-09-23 14:41:55 -0700910#[cfg(feature = "printing")]
911mod printing {
912 use super::*;
David Tolnay89e05672016-10-02 14:39:42 -0700913 use {FunctionRetTy, Mutability, Ty};
David Tolnayf4bbbd92016-09-23 14:41:55 -0700914 use quote::{Tokens, ToTokens};
915
916 impl ToTokens for Expr {
917 fn to_tokens(&self, tokens: &mut Tokens) {
918 match *self {
David Tolnaybb6feae2016-10-02 21:25:20 -0700919 Expr::Box(ref inner) => {
920 tokens.append("box");
921 inner.to_tokens(tokens);
922 }
923 Expr::Vec(ref tys) => {
924 tokens.append("[");
925 tokens.append_separated(tys, ",");
926 tokens.append("]");
927 }
David Tolnay9636c052016-10-02 17:11:17 -0700928 Expr::Call(ref func, ref args) => {
929 func.to_tokens(tokens);
930 tokens.append("(");
931 tokens.append_separated(args, ",");
932 tokens.append(")");
933 }
934 Expr::MethodCall(ref ident, ref ascript, ref args) => {
935 args[0].to_tokens(tokens);
936 tokens.append(".");
937 ident.to_tokens(tokens);
938 if ascript.len() > 0 {
939 tokens.append("::");
940 tokens.append("<");
941 tokens.append_separated(ascript, ",");
942 tokens.append(">");
943 }
944 tokens.append("(");
945 tokens.append_separated(&args[1..], ",");
946 tokens.append(")");
947 }
David Tolnay47a877c2016-10-01 16:50:55 -0700948 Expr::Tup(ref fields) => {
949 tokens.append("(");
950 tokens.append_separated(fields, ",");
951 if fields.len() == 1 {
952 tokens.append(",");
953 }
954 tokens.append(")");
955 }
David Tolnay89e05672016-10-02 14:39:42 -0700956 Expr::Binary(op, ref left, ref right) => {
957 left.to_tokens(tokens);
958 op.to_tokens(tokens);
959 right.to_tokens(tokens);
960 }
David Tolnay3c2467c2016-10-02 17:55:08 -0700961 Expr::Unary(op, ref expr) => {
962 op.to_tokens(tokens);
963 expr.to_tokens(tokens);
964 }
David Tolnayf4bbbd92016-09-23 14:41:55 -0700965 Expr::Lit(ref lit) => lit.to_tokens(tokens),
David Tolnay3c2467c2016-10-02 17:55:08 -0700966 Expr::Cast(ref expr, ref ty) => {
967 expr.to_tokens(tokens);
968 tokens.append("as");
969 ty.to_tokens(tokens);
970 }
971 Expr::Type(ref expr, ref ty) => {
972 expr.to_tokens(tokens);
973 tokens.append(":");
974 ty.to_tokens(tokens);
975 }
976 Expr::If(ref cond, ref then_block, ref else_block) => {
977 tokens.append("if");
978 cond.to_tokens(tokens);
979 then_block.to_tokens(tokens);
980 if let Some(ref else_block) = *else_block {
981 tokens.append("else");
982 else_block.to_tokens(tokens);
983 }
984 }
David Tolnay29f9ce12016-10-02 20:58:40 -0700985 Expr::IfLet(ref pat, ref expr, ref then_block, ref else_block) => {
986 tokens.append("if");
987 tokens.append("let");
988 pat.to_tokens(tokens);
989 tokens.append("=");
990 expr.to_tokens(tokens);
991 then_block.to_tokens(tokens);
992 if let Some(ref else_block) = *else_block {
993 tokens.append("else");
994 else_block.to_tokens(tokens);
995 }
996 }
David Tolnaybb6feae2016-10-02 21:25:20 -0700997 Expr::While(ref cond, ref body, ref label) => {
998 if let Some(ref label) = *label {
999 label.to_tokens(tokens);
1000 tokens.append(":");
1001 }
1002 tokens.append("while");
1003 cond.to_tokens(tokens);
1004 body.to_tokens(tokens);
1005 }
1006 Expr::WhileLet(ref pat, ref expr, ref body, ref label) => {
1007 if let Some(ref label) = *label {
1008 label.to_tokens(tokens);
1009 tokens.append(":");
1010 }
1011 tokens.append("while");
1012 tokens.append("let");
1013 pat.to_tokens(tokens);
1014 tokens.append("=");
1015 expr.to_tokens(tokens);
1016 body.to_tokens(tokens);
1017 }
1018 Expr::ForLoop(ref pat, ref expr, ref body, ref label) => {
1019 if let Some(ref label) = *label {
1020 label.to_tokens(tokens);
1021 tokens.append(":");
1022 }
1023 tokens.append("for");
1024 pat.to_tokens(tokens);
1025 tokens.append("in");
1026 expr.to_tokens(tokens);
1027 body.to_tokens(tokens);
1028 }
1029 Expr::Loop(ref body, ref label) => {
1030 if let Some(ref label) = *label {
1031 label.to_tokens(tokens);
1032 tokens.append(":");
1033 }
1034 tokens.append("loop");
1035 body.to_tokens(tokens);
1036 }
David Tolnayb4ad3b52016-10-01 21:58:13 -07001037 Expr::Match(ref expr, ref arms) => {
1038 tokens.append("match");
1039 expr.to_tokens(tokens);
1040 tokens.append("{");
1041 tokens.append_separated(arms, ",");
1042 tokens.append("}");
1043 }
David Tolnay89e05672016-10-02 14:39:42 -07001044 Expr::Closure(capture, ref decl, ref body) => {
1045 capture.to_tokens(tokens);
1046 tokens.append("|");
1047 for (i, input) in decl.inputs.iter().enumerate() {
1048 if i > 0 {
1049 tokens.append(",");
1050 }
1051 input.pat.to_tokens(tokens);
1052 match input.ty {
1053 Ty::Infer => { /* nothing */ }
1054 _ => {
1055 tokens.append(":");
1056 input.ty.to_tokens(tokens);
1057 }
1058 }
1059 }
1060 tokens.append("|");
1061 match decl.output {
1062 FunctionRetTy::Default => {
1063 if body.stmts.len() == 1 {
1064 if let Stmt::Expr(ref expr) = body.stmts[0] {
1065 expr.to_tokens(tokens);
1066 } else {
1067 body.to_tokens(tokens);
1068 }
1069 } else {
1070 body.to_tokens(tokens);
1071 }
1072 }
1073 FunctionRetTy::Ty(ref ty) => {
1074 tokens.append("->");
1075 ty.to_tokens(tokens);
1076 body.to_tokens(tokens);
1077 }
1078 }
1079 }
1080 Expr::Block(rules, ref block) => {
1081 rules.to_tokens(tokens);
1082 block.to_tokens(tokens);
1083 }
David Tolnaybb6feae2016-10-02 21:25:20 -07001084 Expr::Assign(ref var, ref expr) => {
1085 var.to_tokens(tokens);
1086 tokens.append("=");
1087 expr.to_tokens(tokens);
1088 }
1089 Expr::AssignOp(op, ref var, ref expr) => {
1090 var.to_tokens(tokens);
1091 tokens.append(op.assign_op());
1092 expr.to_tokens(tokens);
1093 }
1094 Expr::Field(ref expr, ref field) => {
1095 expr.to_tokens(tokens);
1096 tokens.append(".");
1097 field.to_tokens(tokens);
1098 }
1099 Expr::TupField(ref expr, field) => {
1100 expr.to_tokens(tokens);
1101 tokens.append(".");
1102 tokens.append(&field.to_string());
1103 }
1104 Expr::Index(ref expr, ref index) => {
1105 expr.to_tokens(tokens);
1106 tokens.append("[");
1107 index.to_tokens(tokens);
1108 tokens.append("]");
1109 }
1110 Expr::Range(ref from, ref to, limits) => {
1111 from.to_tokens(tokens);
1112 match limits {
1113 RangeLimits::HalfOpen => tokens.append(".."),
1114 RangeLimits::Closed => tokens.append("..."),
1115 }
1116 to.to_tokens(tokens);
1117 }
David Tolnay89e05672016-10-02 14:39:42 -07001118 Expr::Path(None, ref path) => {
1119 path.to_tokens(tokens);
1120 }
1121 Expr::Path(Some(ref qself), ref path) => {
1122 tokens.append("<");
1123 qself.ty.to_tokens(tokens);
1124 if qself.position > 0 {
1125 tokens.append("as");
1126 for (i, segment) in path.segments.iter()
1127 .take(qself.position)
1128 .enumerate()
1129 {
1130 if i > 0 || path.global {
1131 tokens.append("::");
1132 }
1133 segment.to_tokens(tokens);
1134 }
1135 }
1136 tokens.append(">");
1137 for segment in path.segments.iter().skip(qself.position) {
1138 tokens.append("::");
1139 segment.to_tokens(tokens);
1140 }
1141 }
David Tolnay3c2467c2016-10-02 17:55:08 -07001142 Expr::AddrOf(mutability, ref expr) => {
1143 tokens.append("&");
1144 mutability.to_tokens(tokens);
1145 expr.to_tokens(tokens);
1146 }
1147 Expr::Break(ref opt_label) => {
1148 tokens.append("break");
1149 opt_label.to_tokens(tokens);
1150 }
1151 Expr::Continue(ref opt_label) => {
1152 tokens.append("continue");
1153 opt_label.to_tokens(tokens);
1154 }
David Tolnay42602292016-10-01 22:25:45 -07001155 Expr::Ret(ref opt_expr) => {
1156 tokens.append("return");
1157 opt_expr.to_tokens(tokens);
1158 }
David Tolnaycc3d66e2016-10-02 23:36:05 -07001159 Expr::Mac(ref mac) => mac.to_tokens(tokens),
David Tolnay055a7042016-10-02 19:23:54 -07001160 Expr::Struct(ref path, ref fields, ref base) => {
1161 path.to_tokens(tokens);
1162 tokens.append("{");
1163 tokens.append_separated(fields, ",");
1164 if let Some(ref base) = *base {
1165 if !fields.is_empty() {
1166 tokens.append(",");
1167 }
1168 tokens.append("..");
1169 base.to_tokens(tokens);
1170 }
1171 tokens.append("}");
1172 }
1173 Expr::Repeat(ref expr, ref times) => {
1174 tokens.append("[");
1175 expr.to_tokens(tokens);
1176 tokens.append(";");
1177 times.to_tokens(tokens);
1178 tokens.append("]");
1179 }
David Tolnay89e05672016-10-02 14:39:42 -07001180 Expr::Paren(ref expr) => {
1181 tokens.append("(");
1182 expr.to_tokens(tokens);
1183 tokens.append(")");
1184 }
David Tolnay3c2467c2016-10-02 17:55:08 -07001185 Expr::Try(ref expr) => {
1186 expr.to_tokens(tokens);
1187 tokens.append("?");
1188 }
David Tolnayf4bbbd92016-09-23 14:41:55 -07001189 }
1190 }
1191 }
David Tolnayb4ad3b52016-10-01 21:58:13 -07001192
David Tolnaybb6feae2016-10-02 21:25:20 -07001193 impl BinOp {
1194 fn op(&self) -> &'static str {
1195 match *self {
1196 BinOp::Add => "+",
1197 BinOp::Sub => "-",
1198 BinOp::Mul => "*",
1199 BinOp::Div => "/",
1200 BinOp::Rem => "%",
1201 BinOp::And => "&&",
1202 BinOp::Or => "||",
1203 BinOp::BitXor => "^",
1204 BinOp::BitAnd => "&",
1205 BinOp::BitOr => "|",
1206 BinOp::Shl => "<<",
1207 BinOp::Shr => ">>",
1208 BinOp::Eq => "==",
1209 BinOp::Lt => "<",
1210 BinOp::Le => "<=",
1211 BinOp::Ne => "!=",
1212 BinOp::Ge => ">=",
1213 BinOp::Gt => ">",
1214 }
1215 }
1216
1217 fn assign_op(&self) -> &'static str {
1218 match *self {
1219 BinOp::Add => "+=",
1220 BinOp::Sub => "-=",
1221 BinOp::Mul => "*=",
1222 BinOp::Div => "/=",
1223 BinOp::Rem => "%=",
1224 BinOp::BitXor => "^=",
1225 BinOp::BitAnd => "&=",
1226 BinOp::BitOr => "|=",
1227 BinOp::Shl => "<<=",
1228 BinOp::Shr => ">>=",
1229 _ => panic!("bad assignment operator"),
1230 }
1231 }
1232 }
1233
David Tolnay89e05672016-10-02 14:39:42 -07001234 impl ToTokens for BinOp {
1235 fn to_tokens(&self, tokens: &mut Tokens) {
David Tolnaybb6feae2016-10-02 21:25:20 -07001236 tokens.append(self.op());
1237 }
1238 }
1239
1240 impl UnOp {
1241 fn op(&self) -> &'static str {
David Tolnay89e05672016-10-02 14:39:42 -07001242 match *self {
David Tolnaybb6feae2016-10-02 21:25:20 -07001243 UnOp::Deref => "*",
1244 UnOp::Not => "!",
1245 UnOp::Neg => "-",
David Tolnay89e05672016-10-02 14:39:42 -07001246 }
1247 }
1248 }
1249
David Tolnay3c2467c2016-10-02 17:55:08 -07001250 impl ToTokens for UnOp {
1251 fn to_tokens(&self, tokens: &mut Tokens) {
David Tolnaybb6feae2016-10-02 21:25:20 -07001252 tokens.append(self.op());
David Tolnay3c2467c2016-10-02 17:55:08 -07001253 }
1254 }
1255
David Tolnay055a7042016-10-02 19:23:54 -07001256 impl ToTokens for FieldValue {
1257 fn to_tokens(&self, tokens: &mut Tokens) {
1258 self.ident.to_tokens(tokens);
1259 tokens.append(":");
1260 self.expr.to_tokens(tokens);
1261 }
1262 }
1263
David Tolnayb4ad3b52016-10-01 21:58:13 -07001264 impl ToTokens for Arm {
1265 fn to_tokens(&self, tokens: &mut Tokens) {
1266 for attr in &self.attrs {
1267 attr.to_tokens(tokens);
1268 }
1269 tokens.append_separated(&self.pats, "|");
1270 if let Some(ref guard) = self.guard {
1271 tokens.append("if");
1272 guard.to_tokens(tokens);
1273 }
1274 tokens.append("=>");
1275 self.body.to_tokens(tokens);
1276 match *self.body {
David Tolnay89e05672016-10-02 14:39:42 -07001277 Expr::Block(_, _) => { /* no comma */ }
David Tolnayb4ad3b52016-10-01 21:58:13 -07001278 _ => tokens.append(","),
1279 }
1280 }
1281 }
1282
1283 impl ToTokens for Pat {
1284 fn to_tokens(&self, tokens: &mut Tokens) {
1285 match *self {
1286 Pat::Wild => tokens.append("_"),
1287 Pat::Ident(mode, ref ident, ref subpat) => {
1288 mode.to_tokens(tokens);
1289 ident.to_tokens(tokens);
1290 if let Some(ref subpat) = *subpat {
1291 tokens.append("@");
1292 subpat.to_tokens(tokens);
1293 }
1294 }
1295 Pat::Struct(ref _path, ref _fields, _dots) => unimplemented!(),
1296 Pat::TupleStruct(ref _path, ref _pats, _dotpos) => unimplemented!(),
1297 Pat::Path(ref _qself, ref _path) => unimplemented!(),
1298 Pat::Tuple(ref _pats, _dotpos) => unimplemented!(),
1299 Pat::Box(ref _inner) => unimplemented!(),
1300 Pat::Ref(ref _target, _mutability) => unimplemented!(),
1301 Pat::Lit(ref _expr) => unimplemented!(),
1302 Pat::Range(ref _lower, ref _upper) => unimplemented!(),
1303 Pat::Vec(ref _before, ref _dots, ref _after) => unimplemented!(),
David Tolnaycc3d66e2016-10-02 23:36:05 -07001304 Pat::Mac(ref mac) => mac.to_tokens(tokens),
David Tolnayb4ad3b52016-10-01 21:58:13 -07001305 }
1306 }
1307 }
1308
1309 impl ToTokens for BindingMode {
1310 fn to_tokens(&self, tokens: &mut Tokens) {
1311 match *self {
1312 BindingMode::ByRef(Mutability::Immutable) => {
1313 tokens.append("ref");
1314 }
1315 BindingMode::ByRef(Mutability::Mutable) => {
1316 tokens.append("ref");
1317 tokens.append("mut");
1318 }
1319 BindingMode::ByValue(Mutability::Immutable) => {}
1320 BindingMode::ByValue(Mutability::Mutable) => {
1321 tokens.append("mut");
1322 }
1323 }
1324 }
1325 }
David Tolnay42602292016-10-01 22:25:45 -07001326
David Tolnay89e05672016-10-02 14:39:42 -07001327 impl ToTokens for CaptureBy {
1328 fn to_tokens(&self, tokens: &mut Tokens) {
1329 match *self {
1330 CaptureBy::Value => tokens.append("move"),
1331 CaptureBy::Ref => { /* nothing */ }
1332 }
1333 }
1334 }
1335
David Tolnay42602292016-10-01 22:25:45 -07001336 impl ToTokens for Block {
1337 fn to_tokens(&self, tokens: &mut Tokens) {
David Tolnay42602292016-10-01 22:25:45 -07001338 tokens.append("{");
1339 for stmt in &self.stmts {
1340 stmt.to_tokens(tokens);
1341 }
1342 tokens.append("}");
1343 }
1344 }
1345
1346 impl ToTokens for BlockCheckMode {
1347 fn to_tokens(&self, tokens: &mut Tokens) {
1348 match *self {
David Tolnay89e05672016-10-02 14:39:42 -07001349 BlockCheckMode::Default => { /* nothing */ }
David Tolnay42602292016-10-01 22:25:45 -07001350 BlockCheckMode::Unsafe => tokens.append("unsafe"),
1351 }
1352 }
1353 }
1354
1355 impl ToTokens for Stmt {
1356 fn to_tokens(&self, tokens: &mut Tokens) {
1357 match *self {
David Tolnay191e0582016-10-02 18:31:09 -07001358 Stmt::Local(ref local) => local.to_tokens(tokens),
David Tolnay42602292016-10-01 22:25:45 -07001359 Stmt::Item(ref item) => item.to_tokens(tokens),
1360 Stmt::Expr(ref expr) => expr.to_tokens(tokens),
1361 Stmt::Semi(ref expr) => {
1362 expr.to_tokens(tokens);
1363 tokens.append(";");
1364 }
1365 Stmt::Mac(ref _mac) => unimplemented!(),
1366 }
1367 }
1368 }
David Tolnay191e0582016-10-02 18:31:09 -07001369
1370 impl ToTokens for Local {
1371 fn to_tokens(&self, tokens: &mut Tokens) {
1372 tokens.append("let");
1373 self.pat.to_tokens(tokens);
1374 if let Some(ref ty) = self.ty {
1375 tokens.append(":");
1376 ty.to_tokens(tokens);
1377 }
1378 if let Some(ref init) = self.init {
1379 tokens.append("=");
1380 init.to_tokens(tokens);
1381 }
1382 tokens.append(";");
1383 }
1384 }
David Tolnayf4bbbd92016-09-23 14:41:55 -07001385}