blob: 4f5c73f113fabad9e98e9cbb7f84f93aff65a534 [file] [log] [blame]
David Tolnayf4bbbd92016-09-23 14:41:55 -07001use super::*;
2
3#[derive(Debug, Clone, Eq, PartialEq)]
4pub enum Expr {
5 /// A `box x` expression.
6 Box(Box<Expr>),
David Tolnayf4bbbd92016-09-23 14:41:55 -07007 /// An array (`[a, b, c, d]`)
8 Vec(Vec<Expr>),
9 /// A function call
10 ///
11 /// The first field resolves to the function itself,
12 /// and the second field is the list of arguments
13 Call(Box<Expr>, Vec<Expr>),
14 /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
15 ///
16 /// The `Ident` is the identifier for the method name.
17 /// The vector of `Ty`s are the ascripted type parameters for the method
18 /// (within the angle brackets).
19 ///
20 /// The first element of the vector of `Expr`s is the expression that evaluates
21 /// to the object on which the method is being called on (the receiver),
22 /// and the remaining elements are the rest of the arguments.
23 ///
24 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
25 /// `ExprKind::MethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
26 MethodCall(Ident, Vec<Ty>, Vec<Expr>),
27 /// A tuple (`(a, b, c, d)`)
28 Tup(Vec<Expr>),
29 /// A binary operation (For example: `a + b`, `a * b`)
30 Binary(BinOp, Box<Expr>, Box<Expr>),
31 /// A unary operation (For example: `!x`, `*x`)
32 Unary(UnOp, Box<Expr>),
33 /// A literal (For example: `1`, `"foo"`)
34 Lit(Lit),
35 /// A cast (`foo as f64`)
36 Cast(Box<Expr>, Box<Ty>),
David Tolnay939766a2016-09-23 23:48:12 -070037 /// Type ascription (`foo: f64`)
David Tolnayf4bbbd92016-09-23 14:41:55 -070038 Type(Box<Expr>, Box<Ty>),
39 /// An `if` block, with an optional else block
40 ///
41 /// `if expr { block } else { expr }`
David Tolnay89e05672016-10-02 14:39:42 -070042 If(Box<Expr>, Block, Option<Box<Expr>>),
David Tolnayf4bbbd92016-09-23 14:41:55 -070043 /// An `if let` expression with an optional else block
44 ///
45 /// `if let pat = expr { block } else { expr }`
46 ///
47 /// This is desugared to a `match` expression.
David Tolnay89e05672016-10-02 14:39:42 -070048 IfLet(Box<Pat>, Box<Expr>, Block, Option<Box<Expr>>),
David Tolnayf4bbbd92016-09-23 14:41:55 -070049 /// A while loop, with an optional label
50 ///
51 /// `'label: while expr { block }`
David Tolnay89e05672016-10-02 14:39:42 -070052 While(Box<Expr>, Block, Option<Ident>),
David Tolnayf4bbbd92016-09-23 14:41:55 -070053 /// A while-let loop, with an optional label
54 ///
55 /// `'label: while let pat = expr { block }`
56 ///
57 /// This is desugared to a combination of `loop` and `match` expressions.
David Tolnay89e05672016-10-02 14:39:42 -070058 WhileLet(Box<Pat>, Box<Expr>, Block, Option<Ident>),
David Tolnayf4bbbd92016-09-23 14:41:55 -070059 /// A for loop, with an optional label
60 ///
61 /// `'label: for pat in expr { block }`
62 ///
63 /// This is desugared to a combination of `loop` and `match` expressions.
David Tolnay89e05672016-10-02 14:39:42 -070064 ForLoop(Box<Pat>, Box<Expr>, Block, Option<Ident>),
David Tolnayf4bbbd92016-09-23 14:41:55 -070065 /// Conditionless loop (can be exited with break, continue, or return)
66 ///
67 /// `'label: loop { block }`
David Tolnay89e05672016-10-02 14:39:42 -070068 Loop(Block, Option<Ident>),
David Tolnayf4bbbd92016-09-23 14:41:55 -070069 /// A `match` block.
70 Match(Box<Expr>, Vec<Arm>),
71 /// A closure (for example, `move |a, b, c| {a + b + c}`)
David Tolnay89e05672016-10-02 14:39:42 -070072 Closure(CaptureBy, Box<FnDecl>, Block),
73 /// A block (`{ ... }` or `unsafe { ... }`)
74 Block(BlockCheckMode, Block),
David Tolnayf4bbbd92016-09-23 14:41:55 -070075
76 /// An assignment (`a = foo()`)
77 Assign(Box<Expr>, Box<Expr>),
78 /// An assignment with an operator
79 ///
80 /// For example, `a += 1`.
81 AssignOp(BinOp, Box<Expr>, Box<Expr>),
82 /// Access of a named struct field (`obj.foo`)
83 Field(Box<Expr>, Ident),
84 /// Access of an unnamed field of a struct or tuple-struct
85 ///
86 /// For example, `foo.0`.
87 TupField(Box<Expr>, usize),
88 /// An indexing operation (`foo[2]`)
89 Index(Box<Expr>, Box<Expr>),
90 /// A range (`1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`)
91 Range(Option<Box<Expr>>, Option<Box<Expr>>, RangeLimits),
92
93 /// Variable reference, possibly containing `::` and/or type
94 /// parameters, e.g. foo::bar::<baz>.
95 ///
96 /// Optionally "qualified",
97 /// E.g. `<Vec<T> as SomeTrait>::SomeType`.
98 Path(Option<QSelf>, Path),
99
100 /// A referencing operation (`&a` or `&mut a`)
101 AddrOf(Mutability, Box<Expr>),
102 /// A `break`, with an optional label to break
103 Break(Option<Ident>),
104 /// A `continue`, with an optional label
105 Continue(Option<Ident>),
106 /// A `return`, with an optional value to be returned
107 Ret(Option<Box<Expr>>),
108
109 /// A macro invocation; pre-expansion
110 Mac(Mac),
111
112 /// A struct literal expression.
113 ///
114 /// For example, `Foo {x: 1, y: 2}`, or
115 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
David Tolnay055a7042016-10-02 19:23:54 -0700116 Struct(Path, Vec<FieldValue>, Option<Box<Expr>>),
David Tolnayf4bbbd92016-09-23 14:41:55 -0700117
118 /// An array literal constructed from one repeated element.
119 ///
120 /// For example, `[1; 5]`. The first expression is the element
121 /// to be repeated; the second is the number of times to repeat it.
122 Repeat(Box<Expr>, Box<Expr>),
123
124 /// No-op: used solely so we can pretty-print faithfully
125 Paren(Box<Expr>),
126
127 /// `expr?`
128 Try(Box<Expr>),
129}
130
David Tolnay055a7042016-10-02 19:23:54 -0700131#[derive(Debug, Clone, Eq, PartialEq)]
132pub struct FieldValue {
133 pub ident: Ident,
134 pub expr: Expr,
135}
136
David Tolnayf4bbbd92016-09-23 14:41:55 -0700137/// A Block (`{ .. }`).
138///
139/// E.g. `{ .. }` as in `fn foo() { .. }`
140#[derive(Debug, Clone, Eq, PartialEq)]
141pub struct Block {
142 /// Statements in a block
143 pub stmts: Vec<Stmt>,
David Tolnayf4bbbd92016-09-23 14:41:55 -0700144}
145
146#[derive(Debug, Copy, Clone, Eq, PartialEq)]
147pub enum BlockCheckMode {
148 Default,
149 Unsafe,
150}
151
152#[derive(Debug, Clone, Eq, PartialEq)]
153pub enum Stmt {
154 /// A local (let) binding.
155 Local(Box<Local>),
156
157 /// An item definition.
158 Item(Box<Item>),
159
160 /// Expr without trailing semi-colon.
161 Expr(Box<Expr>),
162
163 Semi(Box<Expr>),
164
165 Mac(Box<(Mac, MacStmtStyle, Vec<Attribute>)>),
166}
167
168#[derive(Debug, Copy, Clone, Eq, PartialEq)]
169pub enum MacStmtStyle {
170 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
171 /// `foo!(...);`, `foo![...];`
172 Semicolon,
173 /// The macro statement had braces; e.g. foo! { ... }
174 Braces,
175 /// The macro statement had parentheses or brackets and no semicolon; e.g.
176 /// `foo!(...)`. All of these will end up being converted into macro
177 /// expressions.
178 NoBraces,
179}
180
181/// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
182#[derive(Debug, Clone, Eq, PartialEq)]
183pub struct Local {
184 pub pat: Box<Pat>,
185 pub ty: Option<Box<Ty>>,
186 /// Initializer expression to set the value, if any
187 pub init: Option<Box<Expr>>,
188 pub attrs: Vec<Attribute>,
189}
190
David Tolnayf4bbbd92016-09-23 14:41:55 -0700191#[derive(Debug, Clone, Eq, PartialEq)]
192pub enum Pat {
193 /// Represents a wildcard pattern (`_`)
194 Wild,
195
David Tolnay432afc02016-09-24 07:37:13 -0700196 /// A `Pat::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
David Tolnayf4bbbd92016-09-23 14:41:55 -0700197 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
198 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
199 /// during name resolution.
200 Ident(BindingMode, Ident, Option<Box<Pat>>),
201
202 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
203 /// The `bool` is `true` in the presence of a `..`.
204 Struct(Path, Vec<FieldPat>, bool),
205
206 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
207 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
208 /// 0 <= position <= subpats.len()
209 TupleStruct(Path, Vec<Pat>, Option<usize>),
210
211 /// A possibly qualified path pattern.
212 /// Unquailfied path patterns `A::B::C` can legally refer to variants, structs, constants
213 /// or associated constants. Quailfied path patterns `<A>::B::C`/`<A as Trait>::B::C` can
214 /// only legally refer to associated constants.
215 Path(Option<QSelf>, Path),
216
217 /// A tuple pattern `(a, b)`.
218 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
219 /// 0 <= position <= subpats.len()
220 Tuple(Vec<Pat>, Option<usize>),
221 /// A `box` pattern
222 Box(Box<Pat>),
223 /// A reference pattern, e.g. `&mut (a, b)`
224 Ref(Box<Pat>, Mutability),
225 /// A literal
David Tolnay8b308c22016-10-03 01:24:10 -0700226 Lit(Box<Lit>),
David Tolnayf4bbbd92016-09-23 14:41:55 -0700227 /// A range pattern, e.g. `1...2`
David Tolnay8b308c22016-10-03 01:24:10 -0700228 Range(Box<Lit>, Box<Lit>),
David Tolnayf4bbbd92016-09-23 14:41:55 -0700229 /// `[a, b, ..i, y, z]` is represented as:
David Tolnay16709ba2016-10-05 23:11:32 -0700230 /// `Pat::Slice(box [a, b], Some(i), box [y, z])`
231 Slice(Vec<Pat>, Option<Box<Pat>>, Vec<Pat>),
David Tolnayf4bbbd92016-09-23 14:41:55 -0700232 /// A macro pattern; pre-expansion
233 Mac(Mac),
234}
235
David Tolnay771ecf42016-09-23 19:26:37 -0700236/// An arm of a 'match'.
237///
238/// E.g. `0...10 => { println!("match!") }` as in
239///
240/// ```rust,ignore
241/// match n {
242/// 0...10 => { println!("match!") },
243/// // ..
244/// }
245/// ```
David Tolnayf4bbbd92016-09-23 14:41:55 -0700246#[derive(Debug, Clone, Eq, PartialEq)]
247pub struct Arm {
248 pub attrs: Vec<Attribute>,
249 pub pats: Vec<Pat>,
250 pub guard: Option<Box<Expr>>,
251 pub body: Box<Expr>,
252}
253
254/// A capture clause
255#[derive(Debug, Copy, Clone, Eq, PartialEq)]
256pub enum CaptureBy {
257 Value,
258 Ref,
259}
260
261/// Limit types of a range (inclusive or exclusive)
262#[derive(Debug, Copy, Clone, Eq, PartialEq)]
263pub enum RangeLimits {
264 /// Inclusive at the beginning, exclusive at the end
265 HalfOpen,
266 /// Inclusive at the beginning and end
267 Closed,
268}
269
270/// A single field in a struct pattern
271///
272/// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
David Tolnay181bac52016-09-24 00:10:05 -0700273/// are treated the same as `x: x, y: ref y, z: ref mut z`,
David Tolnayaed77b02016-09-23 20:50:31 -0700274/// except `is_shorthand` is true
David Tolnayf4bbbd92016-09-23 14:41:55 -0700275#[derive(Debug, Clone, Eq, PartialEq)]
276pub struct FieldPat {
277 /// The identifier for the field
278 pub ident: Ident,
279 /// The pattern the field is destructured to
280 pub pat: Box<Pat>,
281 pub is_shorthand: bool,
282}
283
284#[derive(Debug, Copy, Clone, Eq, PartialEq)]
285pub enum BindingMode {
286 ByRef(Mutability),
287 ByValue(Mutability),
288}
289
David Tolnayb9c8e322016-09-23 20:48:37 -0700290#[cfg(feature = "parsing")]
291pub mod parsing {
292 use super::*;
David Tolnay3bcfb722016-10-08 11:58:36 -0700293 use {BinOp, Delimited, DelimToken, FnArg, FnDecl, FunctionRetTy, Ident, Lifetime, TokenTree,
294 Ty};
David Tolnayb4ad3b52016-10-01 21:58:13 -0700295 use attr::parsing::outer_attr;
Gregory Katz1b69f682016-09-27 21:06:09 -0400296 use generics::parsing::lifetime;
David Tolnayfa0edf22016-09-23 22:58:24 -0700297 use ident::parsing::ident;
David Tolnay191e0582016-10-02 18:31:09 -0700298 use item::parsing::item;
David Tolnay438c9052016-10-07 23:24:48 -0700299 use lit::parsing::{digits, lit};
David Tolnay84aa0752016-10-02 23:01:13 -0700300 use mac::parsing::mac;
David Tolnaycfe55022016-10-02 22:02:27 -0700301 use nom::IResult::Error;
David Tolnay438c9052016-10-07 23:24:48 -0700302 use op::parsing::{assign_op, binop, unop};
David Tolnay055a7042016-10-02 19:23:54 -0700303 use ty::parsing::{mutability, path, qpath, ty};
David Tolnayb9c8e322016-09-23 20:48:37 -0700304
David Tolnayfa0edf22016-09-23 22:58:24 -0700305 named!(pub expr -> Expr, do_parse!(
306 mut e: alt!(
David Tolnayfa94b6f2016-10-05 23:26:11 -0700307 expr_lit // must be before expr_struct
David Tolnay055a7042016-10-02 19:23:54 -0700308 |
David Tolnayfa94b6f2016-10-05 23:26:11 -0700309 expr_struct // must be before expr_path
David Tolnay055a7042016-10-02 19:23:54 -0700310 |
David Tolnayfa94b6f2016-10-05 23:26:11 -0700311 expr_paren // must be before expr_tup
312 |
313 expr_mac // must be before expr_path
David Tolnay89e05672016-10-02 14:39:42 -0700314 |
David Tolnay4c9be372016-10-06 00:47:37 -0700315 expr_break // must be before expr_path
316 |
317 expr_continue // must be before expr_path
318 |
319 expr_ret // must be before expr_path
320 |
David Tolnay939766a2016-09-23 23:48:12 -0700321 expr_box
David Tolnayfa0edf22016-09-23 22:58:24 -0700322 |
David Tolnay939766a2016-09-23 23:48:12 -0700323 expr_vec
David Tolnayfa0edf22016-09-23 22:58:24 -0700324 |
David Tolnay939766a2016-09-23 23:48:12 -0700325 expr_tup
David Tolnayfa0edf22016-09-23 22:58:24 -0700326 |
David Tolnay939766a2016-09-23 23:48:12 -0700327 expr_unary
David Tolnayfa0edf22016-09-23 22:58:24 -0700328 |
David Tolnay939766a2016-09-23 23:48:12 -0700329 expr_if
Gregory Katz3e562cc2016-09-28 18:33:02 -0400330 |
331 expr_while
David Tolnaybb6feae2016-10-02 21:25:20 -0700332 |
333 expr_for_loop
Gregory Katze5f35682016-09-27 14:20:55 -0400334 |
335 expr_loop
David Tolnayb4ad3b52016-10-01 21:58:13 -0700336 |
337 expr_match
David Tolnay89e05672016-10-02 14:39:42 -0700338 |
339 expr_closure
David Tolnay939766a2016-09-23 23:48:12 -0700340 |
341 expr_block
David Tolnay89e05672016-10-02 14:39:42 -0700342 |
David Tolnay438c9052016-10-07 23:24:48 -0700343 expr_range
344 |
David Tolnay89e05672016-10-02 14:39:42 -0700345 expr_path
David Tolnay3c2467c2016-10-02 17:55:08 -0700346 |
347 expr_addr_of
Gregory Katzfd6935d2016-09-30 22:51:25 -0400348 |
David Tolnay055a7042016-10-02 19:23:54 -0700349 expr_repeat
David Tolnayfa0edf22016-09-23 22:58:24 -0700350 ) >>
351 many0!(alt!(
David Tolnay939766a2016-09-23 23:48:12 -0700352 tap!(args: and_call => {
353 e = Expr::Call(Box::new(e), args);
David Tolnayfa0edf22016-09-23 22:58:24 -0700354 })
355 |
David Tolnay939766a2016-09-23 23:48:12 -0700356 tap!(more: and_method_call => {
357 let (method, ascript, mut args) = more;
David Tolnayfa0edf22016-09-23 22:58:24 -0700358 args.insert(0, e);
359 e = Expr::MethodCall(method, ascript, args);
360 })
361 |
David Tolnay939766a2016-09-23 23:48:12 -0700362 tap!(more: and_binary => {
363 let (op, other) = more;
David Tolnayfa0edf22016-09-23 22:58:24 -0700364 e = Expr::Binary(op, Box::new(e), Box::new(other));
365 })
David Tolnay939766a2016-09-23 23:48:12 -0700366 |
367 tap!(ty: and_cast => {
368 e = Expr::Cast(Box::new(e), Box::new(ty));
369 })
370 |
371 tap!(ty: and_ascription => {
372 e = Expr::Type(Box::new(e), Box::new(ty));
373 })
David Tolnay438c9052016-10-07 23:24:48 -0700374 |
375 tap!(v: and_assign => {
376 e = Expr::Assign(Box::new(e), Box::new(v));
377 })
378 |
379 tap!(more: and_assign_op => {
380 let (op, v) = more;
381 e = Expr::AssignOp(op, Box::new(e), Box::new(v));
382 })
383 |
384 tap!(field: and_field => {
385 e = Expr::Field(Box::new(e), field);
386 })
387 |
388 tap!(field: and_tup_field => {
389 e = Expr::TupField(Box::new(e), field as usize);
390 })
391 |
392 tap!(i: and_index => {
393 e = Expr::Index(Box::new(e), Box::new(i));
394 })
395 |
396 tap!(more: and_range => {
397 let (limits, hi) = more;
398 e = Expr::Range(Some(Box::new(e)), hi.map(Box::new), limits);
399 })
David Tolnay055a7042016-10-02 19:23:54 -0700400 |
401 tap!(_try: punct!("?") => {
402 e = Expr::Try(Box::new(e));
403 })
David Tolnayfa0edf22016-09-23 22:58:24 -0700404 )) >>
405 (e)
David Tolnayb9c8e322016-09-23 20:48:37 -0700406 ));
407
David Tolnay84aa0752016-10-02 23:01:13 -0700408 named!(expr_mac -> Expr, map!(mac, Expr::Mac));
409
David Tolnay89e05672016-10-02 14:39:42 -0700410 named!(expr_paren -> Expr, do_parse!(
411 punct!("(") >>
412 e: expr >>
413 punct!(")") >>
414 (Expr::Paren(Box::new(e)))
415 ));
416
David Tolnay939766a2016-09-23 23:48:12 -0700417 named!(expr_box -> Expr, do_parse!(
David Tolnay10413f02016-09-30 09:12:02 -0700418 keyword!("box") >>
David Tolnayb9c8e322016-09-23 20:48:37 -0700419 inner: expr >>
420 (Expr::Box(Box::new(inner)))
421 ));
David Tolnayfa0edf22016-09-23 22:58:24 -0700422
David Tolnay939766a2016-09-23 23:48:12 -0700423 named!(expr_vec -> Expr, do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700424 punct!("[") >>
David Tolnayff46fd22016-10-08 13:53:28 -0700425 elems: terminated_list!(punct!(","), expr) >>
David Tolnayfa0edf22016-09-23 22:58:24 -0700426 punct!("]") >>
427 (Expr::Vec(elems))
428 ));
429
David Tolnay939766a2016-09-23 23:48:12 -0700430 named!(and_call -> Vec<Expr>, do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700431 punct!("(") >>
David Tolnayff46fd22016-10-08 13:53:28 -0700432 args: terminated_list!(punct!(","), expr) >>
David Tolnayfa0edf22016-09-23 22:58:24 -0700433 punct!(")") >>
434 (args)
435 ));
436
David Tolnay939766a2016-09-23 23:48:12 -0700437 named!(and_method_call -> (Ident, Vec<Ty>, Vec<Expr>), do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700438 punct!(".") >>
439 method: ident >>
David Tolnayf6c74402016-10-08 02:31:26 -0700440 ascript: opt_vec!(preceded!(
441 punct!("::"),
442 delimited!(
443 punct!("<"),
David Tolnayff46fd22016-10-08 13:53:28 -0700444 terminated_list!(punct!(","), ty),
David Tolnayf6c74402016-10-08 02:31:26 -0700445 punct!(">")
446 )
David Tolnayfa0edf22016-09-23 22:58:24 -0700447 )) >>
448 punct!("(") >>
David Tolnayff46fd22016-10-08 13:53:28 -0700449 args: terminated_list!(punct!(","), expr) >>
David Tolnayfa0edf22016-09-23 22:58:24 -0700450 punct!(")") >>
451 (method, ascript, args)
452 ));
453
David Tolnay939766a2016-09-23 23:48:12 -0700454 named!(expr_tup -> Expr, do_parse!(
David Tolnayfa0edf22016-09-23 22:58:24 -0700455 punct!("(") >>
David Tolnayff46fd22016-10-08 13:53:28 -0700456 elems: terminated_list!(punct!(","), expr) >>
David Tolnayfa0edf22016-09-23 22:58:24 -0700457 punct!(")") >>
458 (Expr::Tup(elems))
459 ));
460
David Tolnay3cb23a92016-10-07 23:02:21 -0700461 named!(and_binary -> (BinOp, Expr), tuple!(binop, expr));
David Tolnayfa0edf22016-09-23 22:58:24 -0700462
David Tolnay939766a2016-09-23 23:48:12 -0700463 named!(expr_unary -> Expr, do_parse!(
David Tolnay3cb23a92016-10-07 23:02:21 -0700464 operator: unop >>
David Tolnayfa0edf22016-09-23 22:58:24 -0700465 operand: expr >>
466 (Expr::Unary(operator, Box::new(operand)))
467 ));
David Tolnay939766a2016-09-23 23:48:12 -0700468
469 named!(expr_lit -> Expr, map!(lit, Expr::Lit));
470
471 named!(and_cast -> Ty, do_parse!(
David Tolnay10413f02016-09-30 09:12:02 -0700472 keyword!("as") >>
David Tolnay939766a2016-09-23 23:48:12 -0700473 ty: ty >>
474 (ty)
475 ));
476
477 named!(and_ascription -> Ty, preceded!(punct!(":"), ty));
478
David Tolnaybb6feae2016-10-02 21:25:20 -0700479 enum Cond {
David Tolnay29f9ce12016-10-02 20:58:40 -0700480 Let(Pat, Expr),
481 Expr(Expr),
482 }
483
David Tolnaybb6feae2016-10-02 21:25:20 -0700484 named!(cond -> Cond, alt!(
485 do_parse!(
486 keyword!("let") >>
487 pat: pat >>
488 punct!("=") >>
489 value: expr >>
490 (Cond::Let(pat, value))
491 )
492 |
493 map!(expr, Cond::Expr)
494 ));
495
David Tolnay939766a2016-09-23 23:48:12 -0700496 named!(expr_if -> Expr, do_parse!(
David Tolnay10413f02016-09-30 09:12:02 -0700497 keyword!("if") >>
David Tolnaybb6feae2016-10-02 21:25:20 -0700498 cond: cond >>
David Tolnay939766a2016-09-23 23:48:12 -0700499 punct!("{") >>
500 then_block: within_block >>
501 punct!("}") >>
502 else_block: option!(preceded!(
David Tolnay10413f02016-09-30 09:12:02 -0700503 keyword!("else"),
David Tolnay939766a2016-09-23 23:48:12 -0700504 alt!(
505 expr_if
506 |
507 do_parse!(
508 punct!("{") >>
509 else_block: within_block >>
510 punct!("}") >>
David Tolnay89e05672016-10-02 14:39:42 -0700511 (Expr::Block(BlockCheckMode::Default, Block {
David Tolnay939766a2016-09-23 23:48:12 -0700512 stmts: else_block,
David Tolnay89e05672016-10-02 14:39:42 -0700513 }))
David Tolnay939766a2016-09-23 23:48:12 -0700514 )
515 )
516 )) >>
David Tolnay29f9ce12016-10-02 20:58:40 -0700517 (match cond {
David Tolnaybb6feae2016-10-02 21:25:20 -0700518 Cond::Let(pat, expr) => Expr::IfLet(
David Tolnay29f9ce12016-10-02 20:58:40 -0700519 Box::new(pat),
520 Box::new(expr),
521 Block {
522 stmts: then_block,
523 },
524 else_block.map(Box::new),
525 ),
David Tolnaybb6feae2016-10-02 21:25:20 -0700526 Cond::Expr(cond) => Expr::If(
David Tolnay29f9ce12016-10-02 20:58:40 -0700527 Box::new(cond),
528 Block {
529 stmts: then_block,
530 },
531 else_block.map(Box::new),
532 ),
533 })
David Tolnay939766a2016-09-23 23:48:12 -0700534 ));
535
David Tolnaybb6feae2016-10-02 21:25:20 -0700536 named!(expr_for_loop -> Expr, do_parse!(
537 lbl: option!(terminated!(label, punct!(":"))) >>
538 keyword!("for") >>
539 pat: pat >>
540 keyword!("in") >>
541 expr: expr >>
542 loop_block: block >>
543 (Expr::ForLoop(Box::new(pat), Box::new(expr), loop_block, lbl))
544 ));
545
Gregory Katze5f35682016-09-27 14:20:55 -0400546 named!(expr_loop -> Expr, do_parse!(
David Tolnay8b07f372016-09-30 10:28:40 -0700547 lbl: option!(terminated!(label, punct!(":"))) >>
David Tolnay10413f02016-09-30 09:12:02 -0700548 keyword!("loop") >>
Gregory Katze5f35682016-09-27 14:20:55 -0400549 loop_block: block >>
David Tolnay89e05672016-10-02 14:39:42 -0700550 (Expr::Loop(loop_block, lbl))
Gregory Katze5f35682016-09-27 14:20:55 -0400551 ));
552
David Tolnayb4ad3b52016-10-01 21:58:13 -0700553 named!(expr_match -> Expr, do_parse!(
554 keyword!("match") >>
555 obj: expr >>
556 punct!("{") >>
557 arms: many0!(do_parse!(
558 attrs: many0!(outer_attr) >>
559 pats: separated_nonempty_list!(punct!("|"), pat) >>
560 guard: option!(preceded!(keyword!("if"), expr)) >>
561 punct!("=>") >>
562 body: alt!(
David Tolnay89e05672016-10-02 14:39:42 -0700563 map!(block, |blk| Expr::Block(BlockCheckMode::Default, blk))
David Tolnayf6c74402016-10-08 02:31:26 -0700564 |
565 expr
David Tolnayb4ad3b52016-10-01 21:58:13 -0700566 ) >>
David Tolnayf6c74402016-10-08 02:31:26 -0700567 option!(punct!(",")) >>
David Tolnayb4ad3b52016-10-01 21:58:13 -0700568 (Arm {
569 attrs: attrs,
570 pats: pats,
571 guard: guard.map(Box::new),
572 body: Box::new(body),
573 })
574 )) >>
575 punct!("}") >>
576 (Expr::Match(Box::new(obj), arms))
577 ));
578
David Tolnay89e05672016-10-02 14:39:42 -0700579 named!(expr_closure -> Expr, do_parse!(
580 capture: capture_by >>
581 punct!("|") >>
David Tolnayff46fd22016-10-08 13:53:28 -0700582 inputs: terminated_list!(punct!(","), closure_arg) >>
David Tolnay89e05672016-10-02 14:39:42 -0700583 punct!("|") >>
584 ret_and_body: alt!(
585 do_parse!(
586 punct!("->") >>
587 ty: ty >>
588 body: block >>
589 ((FunctionRetTy::Ty(ty), body))
590 )
591 |
592 map!(expr, |e| (
593 FunctionRetTy::Default,
594 Block {
595 stmts: vec![Stmt::Expr(Box::new(e))],
596 },
597 ))
598 ) >>
599 (Expr::Closure(
600 capture,
601 Box::new(FnDecl {
602 inputs: inputs,
603 output: ret_and_body.0,
604 }),
605 ret_and_body.1,
606 ))
607 ));
608
609 named!(closure_arg -> FnArg, do_parse!(
610 pat: pat >>
611 ty: option!(preceded!(punct!(":"), ty)) >>
David Tolnayca085422016-10-04 00:12:38 -0700612 (FnArg::Captured(pat, ty.unwrap_or(Ty::Infer)))
David Tolnay89e05672016-10-02 14:39:42 -0700613 ));
614
Gregory Katz3e562cc2016-09-28 18:33:02 -0400615 named!(expr_while -> Expr, do_parse!(
David Tolnay8b07f372016-09-30 10:28:40 -0700616 lbl: option!(terminated!(label, punct!(":"))) >>
David Tolnay57ffbde2016-09-30 09:38:04 -0700617 keyword!("while") >>
David Tolnaybb6feae2016-10-02 21:25:20 -0700618 cond: cond >>
Gregory Katz3e562cc2016-09-28 18:33:02 -0400619 while_block: block >>
David Tolnaybb6feae2016-10-02 21:25:20 -0700620 (match cond {
621 Cond::Let(pat, expr) => Expr::WhileLet(
622 Box::new(pat),
623 Box::new(expr),
624 while_block,
625 lbl,
626 ),
627 Cond::Expr(cond) => Expr::While(
628 Box::new(cond),
629 while_block,
630 lbl,
631 ),
632 })
Gregory Katz3e562cc2016-09-28 18:33:02 -0400633 ));
634
Gregory Katzfd6935d2016-09-30 22:51:25 -0400635 named!(expr_continue -> Expr, do_parse!(
636 keyword!("continue") >>
637 lbl: option!(label) >>
David Tolnay055a7042016-10-02 19:23:54 -0700638 (Expr::Continue(lbl))
Gregory Katzfd6935d2016-09-30 22:51:25 -0400639 ));
640
641 named!(expr_break -> Expr, do_parse!(
642 keyword!("break") >>
643 lbl: option!(label) >>
David Tolnay055a7042016-10-02 19:23:54 -0700644 (Expr::Break(lbl))
Gregory Katzfd6935d2016-09-30 22:51:25 -0400645 ));
646
647 named!(expr_ret -> Expr, do_parse!(
648 keyword!("return") >>
649 ret_value: option!(expr) >>
David Tolnay055a7042016-10-02 19:23:54 -0700650 (Expr::Ret(ret_value.map(Box::new)))
651 ));
652
653 named!(expr_struct -> Expr, do_parse!(
654 path: path >>
655 punct!("{") >>
656 fields: separated_list!(punct!(","), field_value) >>
657 base: option!(do_parse!(
658 cond!(!fields.is_empty(), punct!(",")) >>
659 punct!("..") >>
660 base: expr >>
661 (base)
662 )) >>
David Tolnayf6c74402016-10-08 02:31:26 -0700663 cond!(!fields.is_empty() && base.is_none(), option!(punct!(","))) >>
David Tolnay055a7042016-10-02 19:23:54 -0700664 punct!("}") >>
665 (Expr::Struct(path, fields, base.map(Box::new)))
666 ));
667
668 named!(field_value -> FieldValue, do_parse!(
669 name: ident >>
670 punct!(":") >>
671 value: expr >>
672 (FieldValue {
673 ident: name,
674 expr: value,
675 })
676 ));
677
678 named!(expr_repeat -> Expr, do_parse!(
679 punct!("[") >>
680 value: expr >>
681 punct!(";") >>
682 times: expr >>
683 punct!("]") >>
684 (Expr::Repeat(Box::new(value), Box::new(times)))
Gregory Katzfd6935d2016-09-30 22:51:25 -0400685 ));
686
David Tolnay42602292016-10-01 22:25:45 -0700687 named!(expr_block -> Expr, do_parse!(
David Tolnay939766a2016-09-23 23:48:12 -0700688 rules: block_check_mode >>
David Tolnay42602292016-10-01 22:25:45 -0700689 b: block >>
David Tolnay89e05672016-10-02 14:39:42 -0700690 (Expr::Block(rules, Block {
David Tolnay42602292016-10-01 22:25:45 -0700691 stmts: b.stmts,
David Tolnay89e05672016-10-02 14:39:42 -0700692 }))
693 ));
694
David Tolnay438c9052016-10-07 23:24:48 -0700695 named!(expr_range -> Expr, do_parse!(
696 limits: range_limits >>
697 hi: option!(expr) >>
698 (Expr::Range(None, hi.map(Box::new), limits))
699 ));
700
701 named!(range_limits -> RangeLimits, alt!(
702 punct!("...") => { |_| RangeLimits::Closed }
703 |
704 punct!("..") => { |_| RangeLimits::HalfOpen }
705 ));
706
David Tolnay9636c052016-10-02 17:11:17 -0700707 named!(expr_path -> Expr, map!(qpath, |(qself, path)| Expr::Path(qself, path)));
David Tolnay42602292016-10-01 22:25:45 -0700708
David Tolnay3c2467c2016-10-02 17:55:08 -0700709 named!(expr_addr_of -> Expr, do_parse!(
710 punct!("&") >>
711 mutability: mutability >>
712 expr: expr >>
713 (Expr::AddrOf(mutability, Box::new(expr)))
714 ));
715
David Tolnay438c9052016-10-07 23:24:48 -0700716 named!(and_assign -> Expr, preceded!(punct!("="), expr));
717
718 named!(and_assign_op -> (BinOp, Expr), tuple!(assign_op, expr));
719
720 named!(and_field -> Ident, preceded!(punct!("."), ident));
721
722 named!(and_tup_field -> u64, preceded!(punct!("."), digits));
723
724 named!(and_index -> Expr, delimited!(punct!("["), expr, punct!("]")));
725
726 named!(and_range -> (RangeLimits, Option<Expr>), tuple!(range_limits, option!(expr)));
727
David Tolnay42602292016-10-01 22:25:45 -0700728 named!(pub block -> Block, do_parse!(
David Tolnay939766a2016-09-23 23:48:12 -0700729 punct!("{") >>
730 stmts: within_block >>
731 punct!("}") >>
732 (Block {
733 stmts: stmts,
David Tolnay939766a2016-09-23 23:48:12 -0700734 })
735 ));
736
737 named!(block_check_mode -> BlockCheckMode, alt!(
David Tolnay10413f02016-09-30 09:12:02 -0700738 keyword!("unsafe") => { |_| BlockCheckMode::Unsafe }
David Tolnay939766a2016-09-23 23:48:12 -0700739 |
740 epsilon!() => { |_| BlockCheckMode::Default }
741 ));
742
743 named!(within_block -> Vec<Stmt>, do_parse!(
David Tolnaycfe55022016-10-02 22:02:27 -0700744 many0!(punct!(";")) >>
745 mut standalone: many0!(terminated!(standalone_stmt, many0!(punct!(";")))) >>
David Tolnay939766a2016-09-23 23:48:12 -0700746 last: option!(expr) >>
747 (match last {
David Tolnaycfe55022016-10-02 22:02:27 -0700748 None => standalone,
David Tolnay939766a2016-09-23 23:48:12 -0700749 Some(last) => {
David Tolnaycfe55022016-10-02 22:02:27 -0700750 standalone.push(Stmt::Expr(Box::new(last)));
751 standalone
David Tolnay939766a2016-09-23 23:48:12 -0700752 }
753 })
754 ));
755
756 named!(standalone_stmt -> Stmt, alt!(
David Tolnay13b3d352016-10-03 00:31:15 -0700757 stmt_mac
758 |
David Tolnay191e0582016-10-02 18:31:09 -0700759 stmt_local
760 |
761 stmt_item
762 |
David Tolnaycfe55022016-10-02 22:02:27 -0700763 stmt_expr
David Tolnay939766a2016-09-23 23:48:12 -0700764 ));
765
David Tolnay13b3d352016-10-03 00:31:15 -0700766 named!(stmt_mac -> Stmt, do_parse!(
767 attrs: many0!(outer_attr) >>
768 mac: mac >>
769 semi: option!(punct!(";")) >>
770 ({
771 let style = if semi.is_some() {
772 MacStmtStyle::Semicolon
773 } else if let Some(&TokenTree::Delimited(Delimited { delim, .. })) = mac.tts.last() {
774 match delim {
775 DelimToken::Paren | DelimToken::Bracket => MacStmtStyle::NoBraces,
776 DelimToken::Brace => MacStmtStyle::Braces,
777 }
778 } else {
779 MacStmtStyle::NoBraces
780 };
781 Stmt::Mac(Box::new((mac, style, attrs)))
782 })
783 ));
784
David Tolnay191e0582016-10-02 18:31:09 -0700785 named!(stmt_local -> Stmt, do_parse!(
786 attrs: many0!(outer_attr) >>
787 keyword!("let") >>
788 pat: pat >>
789 ty: option!(preceded!(punct!(":"), ty)) >>
790 init: option!(preceded!(punct!("="), expr)) >>
791 punct!(";") >>
792 (Stmt::Local(Box::new(Local {
793 pat: Box::new(pat),
794 ty: ty.map(Box::new),
795 init: init.map(Box::new),
796 attrs: attrs,
797 })))
798 ));
799
800 named!(stmt_item -> Stmt, map!(item, |i| Stmt::Item(Box::new(i))));
801
David Tolnaycfe55022016-10-02 22:02:27 -0700802 fn requires_semi(e: &Expr) -> bool {
803 match *e {
David Tolnaycfe55022016-10-02 22:02:27 -0700804 Expr::If(_, _, _) |
805 Expr::IfLet(_, _, _, _) |
806 Expr::While(_, _, _) |
807 Expr::WhileLet(_, _, _, _) |
808 Expr::ForLoop(_, _, _, _) |
809 Expr::Loop(_, _) |
810 Expr::Match(_, _) |
811 Expr::Block(_, _) => false,
812
813 _ => true,
814 }
815 }
816
817 named!(stmt_expr -> Stmt, do_parse!(
David Tolnay939766a2016-09-23 23:48:12 -0700818 e: expr >>
David Tolnaycfe55022016-10-02 22:02:27 -0700819 semi: option!(punct!(";")) >>
820 (if semi.is_some() {
821 Stmt::Semi(Box::new(e))
822 } else if requires_semi(&e) {
823 return Error;
824 } else {
825 Stmt::Expr(Box::new(e))
826 })
David Tolnay939766a2016-09-23 23:48:12 -0700827 ));
David Tolnay8b07f372016-09-30 10:28:40 -0700828
David Tolnay42602292016-10-01 22:25:45 -0700829 named!(pub pat -> Pat, alt!(
David Tolnayfbb73232016-10-03 01:00:06 -0700830 pat_wild // must be before pat_ident
831 |
832 pat_box // must be before pat_ident
David Tolnayb4ad3b52016-10-01 21:58:13 -0700833 |
David Tolnay8b308c22016-10-03 01:24:10 -0700834 pat_range // must be before pat_lit
835 |
David Tolnayaa610942016-10-03 22:22:49 -0700836 pat_tuple_struct // must be before pat_ident
837 |
David Tolnay8d9e81a2016-10-03 22:36:32 -0700838 pat_struct // must be before pat_ident
839 |
David Tolnayaa610942016-10-03 22:22:49 -0700840 pat_mac // must be before pat_ident
841 |
David Tolnay8b308c22016-10-03 01:24:10 -0700842 pat_ident // must be before pat_path
David Tolnay9636c052016-10-02 17:11:17 -0700843 |
844 pat_path
David Tolnayfbb73232016-10-03 01:00:06 -0700845 |
846 pat_tuple
David Tolnayffdb97f2016-10-03 01:28:33 -0700847 |
848 pat_ref
David Tolnay8b308c22016-10-03 01:24:10 -0700849 |
850 pat_lit
David Tolnaydaaf7742016-10-03 11:11:43 -0700851 // TODO: Vec
David Tolnayb4ad3b52016-10-01 21:58:13 -0700852 ));
853
David Tolnay84aa0752016-10-02 23:01:13 -0700854 named!(pat_mac -> Pat, map!(mac, Pat::Mac));
855
David Tolnayb4ad3b52016-10-01 21:58:13 -0700856 named!(pat_wild -> Pat, map!(keyword!("_"), |_| Pat::Wild));
857
David Tolnayfbb73232016-10-03 01:00:06 -0700858 named!(pat_box -> Pat, do_parse!(
859 keyword!("box") >>
860 pat: pat >>
861 (Pat::Box(Box::new(pat)))
862 ));
863
David Tolnayb4ad3b52016-10-01 21:58:13 -0700864 named!(pat_ident -> Pat, do_parse!(
865 mode: option!(keyword!("ref")) >>
866 mutability: mutability >>
867 name: ident >>
David Tolnay8b308c22016-10-03 01:24:10 -0700868 not!(peek!(punct!("<"))) >>
869 not!(peek!(punct!("::"))) >>
David Tolnayb4ad3b52016-10-01 21:58:13 -0700870 subpat: option!(preceded!(punct!("@"), pat)) >>
871 (Pat::Ident(
872 if mode.is_some() {
873 BindingMode::ByRef(mutability)
874 } else {
875 BindingMode::ByValue(mutability)
876 },
877 name,
878 subpat.map(Box::new),
879 ))
880 ));
881
David Tolnayaa610942016-10-03 22:22:49 -0700882 named!(pat_tuple_struct -> Pat, do_parse!(
883 path: path >>
884 tuple: pat_tuple_helper >>
885 (Pat::TupleStruct(path, tuple.0, tuple.1))
886 ));
887
David Tolnay8d9e81a2016-10-03 22:36:32 -0700888 named!(pat_struct -> Pat, do_parse!(
889 path: path >>
890 punct!("{") >>
891 fields: separated_list!(punct!(","), field_pat) >>
892 more: option!(preceded!(
893 cond!(!fields.is_empty(), punct!(",")),
894 punct!("..")
895 )) >>
David Tolnayff46fd22016-10-08 13:53:28 -0700896 cond!(!fields.is_empty() && more.is_none(), option!(punct!(","))) >>
David Tolnay8d9e81a2016-10-03 22:36:32 -0700897 punct!("}") >>
898 (Pat::Struct(path, fields, more.is_some()))
899 ));
900
901 named!(field_pat -> FieldPat, alt!(
902 do_parse!(
903 ident: ident >>
904 punct!(":") >>
905 pat: pat >>
906 (FieldPat {
907 ident: ident,
908 pat: Box::new(pat),
909 is_shorthand: false,
910 })
911 )
912 |
913 do_parse!(
914 mode: option!(keyword!("ref")) >>
915 mutability: mutability >>
916 ident: ident >>
917 (FieldPat {
918 ident: ident.clone(),
919 pat: Box::new(Pat::Ident(
920 if mode.is_some() {
921 BindingMode::ByRef(mutability)
922 } else {
923 BindingMode::ByValue(mutability)
924 },
925 ident,
926 None,
927 )),
928 is_shorthand: true,
929 })
930 )
931 ));
932
David Tolnay9636c052016-10-02 17:11:17 -0700933 named!(pat_path -> Pat, map!(qpath, |(qself, path)| Pat::Path(qself, path)));
934
David Tolnayaa610942016-10-03 22:22:49 -0700935 named!(pat_tuple -> Pat, map!(
936 pat_tuple_helper,
937 |(pats, dotdot)| Pat::Tuple(pats, dotdot)
938 ));
939
940 named!(pat_tuple_helper -> (Vec<Pat>, Option<usize>), do_parse!(
David Tolnayfbb73232016-10-03 01:00:06 -0700941 punct!("(") >>
942 mut elems: separated_list!(punct!(","), pat) >>
943 dotdot: option!(do_parse!(
944 cond!(!elems.is_empty(), punct!(",")) >>
945 punct!("..") >>
946 rest: many0!(preceded!(punct!(","), pat)) >>
947 cond!(!rest.is_empty(), option!(punct!(","))) >>
948 (rest)
949 )) >>
950 cond!(!elems.is_empty() && dotdot.is_none(), option!(punct!(","))) >>
951 punct!(")") >>
952 (match dotdot {
953 Some(rest) => {
954 let pos = elems.len();
955 elems.extend(rest);
David Tolnayaa610942016-10-03 22:22:49 -0700956 (elems, Some(pos))
David Tolnayfbb73232016-10-03 01:00:06 -0700957 }
David Tolnayaa610942016-10-03 22:22:49 -0700958 None => (elems, None),
David Tolnayfbb73232016-10-03 01:00:06 -0700959 })
960 ));
961
David Tolnayffdb97f2016-10-03 01:28:33 -0700962 named!(pat_ref -> Pat, do_parse!(
963 punct!("&") >>
964 mutability: mutability >>
965 pat: pat >>
966 (Pat::Ref(Box::new(pat), mutability))
967 ));
968
David Tolnay8b308c22016-10-03 01:24:10 -0700969 named!(pat_lit -> Pat, map!(lit, |lit| Pat::Lit(Box::new(lit))));
970
971 named!(pat_range -> Pat, do_parse!(
972 lo: lit >>
973 punct!("...") >>
974 hi: lit >>
975 (Pat::Range(Box::new(lo), Box::new(hi)))
976 ));
977
David Tolnay89e05672016-10-02 14:39:42 -0700978 named!(capture_by -> CaptureBy, alt!(
979 keyword!("move") => { |_| CaptureBy::Value }
980 |
981 epsilon!() => { |_| CaptureBy::Ref }
982 ));
983
David Tolnay8b07f372016-09-30 10:28:40 -0700984 named!(label -> Ident, map!(lifetime, |lt: Lifetime| lt.ident));
David Tolnayb9c8e322016-09-23 20:48:37 -0700985}
986
David Tolnayf4bbbd92016-09-23 14:41:55 -0700987#[cfg(feature = "printing")]
988mod printing {
989 use super::*;
David Tolnayca085422016-10-04 00:12:38 -0700990 use {FnArg, FunctionRetTy, Mutability, Ty};
David Tolnay13b3d352016-10-03 00:31:15 -0700991 use attr::FilterAttrs;
David Tolnayf4bbbd92016-09-23 14:41:55 -0700992 use quote::{Tokens, ToTokens};
993
994 impl ToTokens for Expr {
995 fn to_tokens(&self, tokens: &mut Tokens) {
996 match *self {
David Tolnaybb6feae2016-10-02 21:25:20 -0700997 Expr::Box(ref inner) => {
998 tokens.append("box");
999 inner.to_tokens(tokens);
1000 }
1001 Expr::Vec(ref tys) => {
1002 tokens.append("[");
1003 tokens.append_separated(tys, ",");
1004 tokens.append("]");
1005 }
David Tolnay9636c052016-10-02 17:11:17 -07001006 Expr::Call(ref func, ref args) => {
1007 func.to_tokens(tokens);
1008 tokens.append("(");
1009 tokens.append_separated(args, ",");
1010 tokens.append(")");
1011 }
1012 Expr::MethodCall(ref ident, ref ascript, ref args) => {
1013 args[0].to_tokens(tokens);
1014 tokens.append(".");
1015 ident.to_tokens(tokens);
1016 if ascript.len() > 0 {
1017 tokens.append("::");
1018 tokens.append("<");
1019 tokens.append_separated(ascript, ",");
1020 tokens.append(">");
1021 }
1022 tokens.append("(");
1023 tokens.append_separated(&args[1..], ",");
1024 tokens.append(")");
1025 }
David Tolnay47a877c2016-10-01 16:50:55 -07001026 Expr::Tup(ref fields) => {
1027 tokens.append("(");
1028 tokens.append_separated(fields, ",");
1029 if fields.len() == 1 {
1030 tokens.append(",");
1031 }
1032 tokens.append(")");
1033 }
David Tolnay89e05672016-10-02 14:39:42 -07001034 Expr::Binary(op, ref left, ref right) => {
1035 left.to_tokens(tokens);
1036 op.to_tokens(tokens);
1037 right.to_tokens(tokens);
1038 }
David Tolnay3c2467c2016-10-02 17:55:08 -07001039 Expr::Unary(op, ref expr) => {
1040 op.to_tokens(tokens);
1041 expr.to_tokens(tokens);
1042 }
David Tolnayf4bbbd92016-09-23 14:41:55 -07001043 Expr::Lit(ref lit) => lit.to_tokens(tokens),
David Tolnay3c2467c2016-10-02 17:55:08 -07001044 Expr::Cast(ref expr, ref ty) => {
1045 expr.to_tokens(tokens);
1046 tokens.append("as");
1047 ty.to_tokens(tokens);
1048 }
1049 Expr::Type(ref expr, ref ty) => {
1050 expr.to_tokens(tokens);
1051 tokens.append(":");
1052 ty.to_tokens(tokens);
1053 }
1054 Expr::If(ref cond, ref then_block, ref else_block) => {
1055 tokens.append("if");
1056 cond.to_tokens(tokens);
1057 then_block.to_tokens(tokens);
1058 if let Some(ref else_block) = *else_block {
1059 tokens.append("else");
1060 else_block.to_tokens(tokens);
1061 }
1062 }
David Tolnay29f9ce12016-10-02 20:58:40 -07001063 Expr::IfLet(ref pat, ref expr, ref then_block, ref else_block) => {
1064 tokens.append("if");
1065 tokens.append("let");
1066 pat.to_tokens(tokens);
1067 tokens.append("=");
1068 expr.to_tokens(tokens);
1069 then_block.to_tokens(tokens);
1070 if let Some(ref else_block) = *else_block {
1071 tokens.append("else");
1072 else_block.to_tokens(tokens);
1073 }
1074 }
David Tolnaybb6feae2016-10-02 21:25:20 -07001075 Expr::While(ref cond, ref body, ref label) => {
1076 if let Some(ref label) = *label {
1077 label.to_tokens(tokens);
1078 tokens.append(":");
1079 }
1080 tokens.append("while");
1081 cond.to_tokens(tokens);
1082 body.to_tokens(tokens);
1083 }
1084 Expr::WhileLet(ref pat, ref expr, ref body, ref label) => {
1085 if let Some(ref label) = *label {
1086 label.to_tokens(tokens);
1087 tokens.append(":");
1088 }
1089 tokens.append("while");
1090 tokens.append("let");
1091 pat.to_tokens(tokens);
1092 tokens.append("=");
1093 expr.to_tokens(tokens);
1094 body.to_tokens(tokens);
1095 }
1096 Expr::ForLoop(ref pat, ref expr, ref body, ref label) => {
1097 if let Some(ref label) = *label {
1098 label.to_tokens(tokens);
1099 tokens.append(":");
1100 }
1101 tokens.append("for");
1102 pat.to_tokens(tokens);
1103 tokens.append("in");
1104 expr.to_tokens(tokens);
1105 body.to_tokens(tokens);
1106 }
1107 Expr::Loop(ref body, ref label) => {
1108 if let Some(ref label) = *label {
1109 label.to_tokens(tokens);
1110 tokens.append(":");
1111 }
1112 tokens.append("loop");
1113 body.to_tokens(tokens);
1114 }
David Tolnayb4ad3b52016-10-01 21:58:13 -07001115 Expr::Match(ref expr, ref arms) => {
1116 tokens.append("match");
1117 expr.to_tokens(tokens);
1118 tokens.append("{");
David Tolnay2165b042016-10-08 00:04:23 -07001119 tokens.append_all(arms);
David Tolnayb4ad3b52016-10-01 21:58:13 -07001120 tokens.append("}");
1121 }
David Tolnay89e05672016-10-02 14:39:42 -07001122 Expr::Closure(capture, ref decl, ref body) => {
1123 capture.to_tokens(tokens);
1124 tokens.append("|");
1125 for (i, input) in decl.inputs.iter().enumerate() {
1126 if i > 0 {
1127 tokens.append(",");
1128 }
David Tolnayca085422016-10-04 00:12:38 -07001129 match *input {
1130 FnArg::Captured(ref pat, Ty::Infer) => {
1131 pat.to_tokens(tokens);
David Tolnaydaaf7742016-10-03 11:11:43 -07001132 }
David Tolnayca085422016-10-04 00:12:38 -07001133 _ => input.to_tokens(tokens),
David Tolnay89e05672016-10-02 14:39:42 -07001134 }
1135 }
1136 tokens.append("|");
1137 match decl.output {
1138 FunctionRetTy::Default => {
1139 if body.stmts.len() == 1 {
1140 if let Stmt::Expr(ref expr) = body.stmts[0] {
1141 expr.to_tokens(tokens);
1142 } else {
1143 body.to_tokens(tokens);
1144 }
1145 } else {
1146 body.to_tokens(tokens);
1147 }
1148 }
1149 FunctionRetTy::Ty(ref ty) => {
1150 tokens.append("->");
1151 ty.to_tokens(tokens);
1152 body.to_tokens(tokens);
1153 }
1154 }
1155 }
1156 Expr::Block(rules, ref block) => {
1157 rules.to_tokens(tokens);
1158 block.to_tokens(tokens);
1159 }
David Tolnaybb6feae2016-10-02 21:25:20 -07001160 Expr::Assign(ref var, ref expr) => {
1161 var.to_tokens(tokens);
1162 tokens.append("=");
1163 expr.to_tokens(tokens);
1164 }
1165 Expr::AssignOp(op, ref var, ref expr) => {
1166 var.to_tokens(tokens);
David Tolnay3cb23a92016-10-07 23:02:21 -07001167 tokens.append(op.assign_op().unwrap());
David Tolnaybb6feae2016-10-02 21:25:20 -07001168 expr.to_tokens(tokens);
1169 }
1170 Expr::Field(ref expr, ref field) => {
1171 expr.to_tokens(tokens);
1172 tokens.append(".");
1173 field.to_tokens(tokens);
1174 }
1175 Expr::TupField(ref expr, field) => {
1176 expr.to_tokens(tokens);
1177 tokens.append(".");
1178 tokens.append(&field.to_string());
1179 }
1180 Expr::Index(ref expr, ref index) => {
1181 expr.to_tokens(tokens);
1182 tokens.append("[");
1183 index.to_tokens(tokens);
1184 tokens.append("]");
1185 }
1186 Expr::Range(ref from, ref to, limits) => {
1187 from.to_tokens(tokens);
1188 match limits {
1189 RangeLimits::HalfOpen => tokens.append(".."),
1190 RangeLimits::Closed => tokens.append("..."),
1191 }
1192 to.to_tokens(tokens);
1193 }
David Tolnay8b308c22016-10-03 01:24:10 -07001194 Expr::Path(None, ref path) => path.to_tokens(tokens),
David Tolnay89e05672016-10-02 14:39:42 -07001195 Expr::Path(Some(ref qself), ref path) => {
1196 tokens.append("<");
1197 qself.ty.to_tokens(tokens);
1198 if qself.position > 0 {
1199 tokens.append("as");
David Tolnaydaaf7742016-10-03 11:11:43 -07001200 for (i, segment) in path.segments
1201 .iter()
1202 .take(qself.position)
1203 .enumerate() {
David Tolnay89e05672016-10-02 14:39:42 -07001204 if i > 0 || path.global {
1205 tokens.append("::");
1206 }
1207 segment.to_tokens(tokens);
1208 }
1209 }
1210 tokens.append(">");
1211 for segment in path.segments.iter().skip(qself.position) {
1212 tokens.append("::");
1213 segment.to_tokens(tokens);
1214 }
1215 }
David Tolnay3c2467c2016-10-02 17:55:08 -07001216 Expr::AddrOf(mutability, ref expr) => {
1217 tokens.append("&");
1218 mutability.to_tokens(tokens);
1219 expr.to_tokens(tokens);
1220 }
1221 Expr::Break(ref opt_label) => {
1222 tokens.append("break");
1223 opt_label.to_tokens(tokens);
1224 }
1225 Expr::Continue(ref opt_label) => {
1226 tokens.append("continue");
1227 opt_label.to_tokens(tokens);
1228 }
David Tolnay42602292016-10-01 22:25:45 -07001229 Expr::Ret(ref opt_expr) => {
1230 tokens.append("return");
1231 opt_expr.to_tokens(tokens);
1232 }
David Tolnaycc3d66e2016-10-02 23:36:05 -07001233 Expr::Mac(ref mac) => mac.to_tokens(tokens),
David Tolnay055a7042016-10-02 19:23:54 -07001234 Expr::Struct(ref path, ref fields, ref base) => {
1235 path.to_tokens(tokens);
1236 tokens.append("{");
1237 tokens.append_separated(fields, ",");
1238 if let Some(ref base) = *base {
1239 if !fields.is_empty() {
1240 tokens.append(",");
1241 }
1242 tokens.append("..");
1243 base.to_tokens(tokens);
1244 }
1245 tokens.append("}");
1246 }
1247 Expr::Repeat(ref expr, ref times) => {
1248 tokens.append("[");
1249 expr.to_tokens(tokens);
1250 tokens.append(";");
1251 times.to_tokens(tokens);
1252 tokens.append("]");
1253 }
David Tolnay89e05672016-10-02 14:39:42 -07001254 Expr::Paren(ref expr) => {
1255 tokens.append("(");
1256 expr.to_tokens(tokens);
1257 tokens.append(")");
1258 }
David Tolnay3c2467c2016-10-02 17:55:08 -07001259 Expr::Try(ref expr) => {
1260 expr.to_tokens(tokens);
1261 tokens.append("?");
1262 }
David Tolnayf4bbbd92016-09-23 14:41:55 -07001263 }
1264 }
1265 }
David Tolnayb4ad3b52016-10-01 21:58:13 -07001266
David Tolnay055a7042016-10-02 19:23:54 -07001267 impl ToTokens for FieldValue {
1268 fn to_tokens(&self, tokens: &mut Tokens) {
1269 self.ident.to_tokens(tokens);
1270 tokens.append(":");
1271 self.expr.to_tokens(tokens);
1272 }
1273 }
1274
David Tolnayb4ad3b52016-10-01 21:58:13 -07001275 impl ToTokens for Arm {
1276 fn to_tokens(&self, tokens: &mut Tokens) {
1277 for attr in &self.attrs {
1278 attr.to_tokens(tokens);
1279 }
1280 tokens.append_separated(&self.pats, "|");
1281 if let Some(ref guard) = self.guard {
1282 tokens.append("if");
1283 guard.to_tokens(tokens);
1284 }
1285 tokens.append("=>");
1286 self.body.to_tokens(tokens);
1287 match *self.body {
David Tolnaydaaf7742016-10-03 11:11:43 -07001288 Expr::Block(_, _) => {
1289 // no comma
1290 }
David Tolnayb4ad3b52016-10-01 21:58:13 -07001291 _ => tokens.append(","),
1292 }
1293 }
1294 }
1295
1296 impl ToTokens for Pat {
1297 fn to_tokens(&self, tokens: &mut Tokens) {
1298 match *self {
1299 Pat::Wild => tokens.append("_"),
1300 Pat::Ident(mode, ref ident, ref subpat) => {
1301 mode.to_tokens(tokens);
1302 ident.to_tokens(tokens);
1303 if let Some(ref subpat) = *subpat {
1304 tokens.append("@");
1305 subpat.to_tokens(tokens);
1306 }
1307 }
David Tolnay8d9e81a2016-10-03 22:36:32 -07001308 Pat::Struct(ref path, ref fields, dots) => {
1309 path.to_tokens(tokens);
1310 tokens.append("{");
1311 tokens.append_separated(fields, ",");
1312 if dots {
1313 if !fields.is_empty() {
1314 tokens.append(",");
1315 }
1316 tokens.append("..");
1317 }
1318 tokens.append("}");
1319 }
David Tolnayaa610942016-10-03 22:22:49 -07001320 Pat::TupleStruct(ref path, ref pats, dotpos) => {
1321 path.to_tokens(tokens);
1322 tokens.append("(");
1323 match dotpos {
1324 Some(pos) => {
1325 if pos > 0 {
1326 tokens.append_separated(&pats[..pos], ",");
1327 tokens.append(",");
1328 }
1329 tokens.append("..");
1330 if pos < pats.len() {
1331 tokens.append(",");
1332 tokens.append_separated(&pats[pos..], ",");
1333 }
1334 }
1335 None => tokens.append_separated(pats, ","),
1336 }
1337 tokens.append(")");
1338 }
David Tolnay8b308c22016-10-03 01:24:10 -07001339 Pat::Path(None, ref path) => path.to_tokens(tokens),
1340 Pat::Path(Some(ref qself), ref path) => {
1341 tokens.append("<");
1342 qself.ty.to_tokens(tokens);
1343 if qself.position > 0 {
1344 tokens.append("as");
David Tolnaydaaf7742016-10-03 11:11:43 -07001345 for (i, segment) in path.segments
1346 .iter()
1347 .take(qself.position)
1348 .enumerate() {
David Tolnay8b308c22016-10-03 01:24:10 -07001349 if i > 0 || path.global {
1350 tokens.append("::");
1351 }
1352 segment.to_tokens(tokens);
1353 }
1354 }
1355 tokens.append(">");
1356 for segment in path.segments.iter().skip(qself.position) {
1357 tokens.append("::");
1358 segment.to_tokens(tokens);
1359 }
1360 }
David Tolnayfbb73232016-10-03 01:00:06 -07001361 Pat::Tuple(ref pats, dotpos) => {
1362 tokens.append("(");
1363 match dotpos {
1364 Some(pos) => {
1365 if pos > 0 {
1366 tokens.append_separated(&pats[..pos], ",");
1367 tokens.append(",");
1368 }
1369 tokens.append("..");
1370 if pos < pats.len() {
1371 tokens.append(",");
1372 tokens.append_separated(&pats[pos..], ",");
1373 }
1374 }
1375 None => tokens.append_separated(pats, ","),
1376 }
1377 tokens.append(")");
1378 }
1379 Pat::Box(ref inner) => {
1380 tokens.append("box");
1381 inner.to_tokens(tokens);
1382 }
David Tolnayffdb97f2016-10-03 01:28:33 -07001383 Pat::Ref(ref target, mutability) => {
1384 tokens.append("&");
1385 mutability.to_tokens(tokens);
1386 target.to_tokens(tokens);
1387 }
David Tolnay8b308c22016-10-03 01:24:10 -07001388 Pat::Lit(ref lit) => lit.to_tokens(tokens),
1389 Pat::Range(ref lo, ref hi) => {
1390 lo.to_tokens(tokens);
1391 tokens.append("...");
1392 hi.to_tokens(tokens);
1393 }
David Tolnay16709ba2016-10-05 23:11:32 -07001394 Pat::Slice(ref _before, ref _dots, ref _after) => unimplemented!(),
David Tolnaycc3d66e2016-10-02 23:36:05 -07001395 Pat::Mac(ref mac) => mac.to_tokens(tokens),
David Tolnayb4ad3b52016-10-01 21:58:13 -07001396 }
1397 }
1398 }
1399
David Tolnay8d9e81a2016-10-03 22:36:32 -07001400 impl ToTokens for FieldPat {
1401 fn to_tokens(&self, tokens: &mut Tokens) {
1402 if !self.is_shorthand {
1403 self.ident.to_tokens(tokens);
1404 tokens.append(":");
1405 }
1406 self.pat.to_tokens(tokens);
1407 }
1408 }
1409
David Tolnayb4ad3b52016-10-01 21:58:13 -07001410 impl ToTokens for BindingMode {
1411 fn to_tokens(&self, tokens: &mut Tokens) {
1412 match *self {
1413 BindingMode::ByRef(Mutability::Immutable) => {
1414 tokens.append("ref");
1415 }
1416 BindingMode::ByRef(Mutability::Mutable) => {
1417 tokens.append("ref");
1418 tokens.append("mut");
1419 }
1420 BindingMode::ByValue(Mutability::Immutable) => {}
1421 BindingMode::ByValue(Mutability::Mutable) => {
1422 tokens.append("mut");
1423 }
1424 }
1425 }
1426 }
David Tolnay42602292016-10-01 22:25:45 -07001427
David Tolnay89e05672016-10-02 14:39:42 -07001428 impl ToTokens for CaptureBy {
1429 fn to_tokens(&self, tokens: &mut Tokens) {
1430 match *self {
1431 CaptureBy::Value => tokens.append("move"),
David Tolnaydaaf7742016-10-03 11:11:43 -07001432 CaptureBy::Ref => {
1433 // nothing
1434 }
David Tolnay89e05672016-10-02 14:39:42 -07001435 }
1436 }
1437 }
1438
David Tolnay42602292016-10-01 22:25:45 -07001439 impl ToTokens for Block {
1440 fn to_tokens(&self, tokens: &mut Tokens) {
David Tolnay42602292016-10-01 22:25:45 -07001441 tokens.append("{");
1442 for stmt in &self.stmts {
1443 stmt.to_tokens(tokens);
1444 }
1445 tokens.append("}");
1446 }
1447 }
1448
1449 impl ToTokens for BlockCheckMode {
1450 fn to_tokens(&self, tokens: &mut Tokens) {
1451 match *self {
David Tolnaydaaf7742016-10-03 11:11:43 -07001452 BlockCheckMode::Default => {
1453 // nothing
1454 }
David Tolnay42602292016-10-01 22:25:45 -07001455 BlockCheckMode::Unsafe => tokens.append("unsafe"),
1456 }
1457 }
1458 }
1459
1460 impl ToTokens for Stmt {
1461 fn to_tokens(&self, tokens: &mut Tokens) {
1462 match *self {
David Tolnay191e0582016-10-02 18:31:09 -07001463 Stmt::Local(ref local) => local.to_tokens(tokens),
David Tolnay42602292016-10-01 22:25:45 -07001464 Stmt::Item(ref item) => item.to_tokens(tokens),
1465 Stmt::Expr(ref expr) => expr.to_tokens(tokens),
1466 Stmt::Semi(ref expr) => {
1467 expr.to_tokens(tokens);
1468 tokens.append(";");
1469 }
David Tolnay13b3d352016-10-03 00:31:15 -07001470 Stmt::Mac(ref mac) => {
1471 let (ref mac, style, ref attrs) = **mac;
1472 for attr in attrs.outer() {
1473 attr.to_tokens(tokens);
1474 }
1475 mac.to_tokens(tokens);
1476 match style {
1477 MacStmtStyle::Semicolon => tokens.append(";"),
David Tolnaydaaf7742016-10-03 11:11:43 -07001478 MacStmtStyle::Braces | MacStmtStyle::NoBraces => {
1479 // no semicolon
1480 }
David Tolnay13b3d352016-10-03 00:31:15 -07001481 }
1482 }
David Tolnay42602292016-10-01 22:25:45 -07001483 }
1484 }
1485 }
David Tolnay191e0582016-10-02 18:31:09 -07001486
1487 impl ToTokens for Local {
1488 fn to_tokens(&self, tokens: &mut Tokens) {
1489 tokens.append("let");
1490 self.pat.to_tokens(tokens);
1491 if let Some(ref ty) = self.ty {
1492 tokens.append(":");
1493 ty.to_tokens(tokens);
1494 }
1495 if let Some(ref init) = self.init {
1496 tokens.append("=");
1497 init.to_tokens(tokens);
1498 }
1499 tokens.append(";");
1500 }
1501 }
David Tolnayf4bbbd92016-09-23 14:41:55 -07001502}