]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/build.rs
Rollup merge of #64302 - nnethercote:shrink-ObligationCauseCode, r=zackmdavis
[rust.git] / src / libsyntax / ext / build.rs
1 use crate::ast::{self, Ident, Generics, Expr, BlockCheckMode, UnOp, PatKind};
2 use crate::attr;
3 use crate::source_map::{dummy_spanned, respan, Spanned};
4 use crate::ext::base::ExtCtxt;
5 use crate::ptr::P;
6 use crate::symbol::{kw, sym, Symbol};
7 use crate::ThinVec;
8
9 use rustc_target::spec::abi::Abi;
10 use syntax_pos::{Pos, Span};
11
12 // Left so that Cargo tests don't break, this can be removed once those no longer use it
13 pub trait AstBuilder {}
14
15 impl<'a> ExtCtxt<'a> {
16     pub fn path(&self, span: Span, strs: Vec<ast::Ident> ) -> ast::Path {
17         self.path_all(span, false, strs, vec![], vec![])
18     }
19     pub fn path_ident(&self, span: Span, id: ast::Ident) -> ast::Path {
20         self.path(span, vec![id])
21     }
22     pub fn path_global(&self, span: Span, strs: Vec<ast::Ident> ) -> ast::Path {
23         self.path_all(span, true, strs, vec![], vec![])
24     }
25     pub fn path_all(&self,
26                 span: Span,
27                 global: bool,
28                 mut idents: Vec<ast::Ident> ,
29                 args: Vec<ast::GenericArg>,
30                 constraints: Vec<ast::AssocTyConstraint> )
31                 -> ast::Path {
32         assert!(!idents.is_empty());
33         let add_root = global && !idents[0].is_path_segment_keyword();
34         let mut segments = Vec::with_capacity(idents.len() + add_root as usize);
35         if add_root {
36             segments.push(ast::PathSegment::path_root(span));
37         }
38         let last_ident = idents.pop().unwrap();
39         segments.extend(idents.into_iter().map(|ident| {
40             ast::PathSegment::from_ident(ident.with_span_pos(span))
41         }));
42         let args = if !args.is_empty() || !constraints.is_empty() {
43             ast::AngleBracketedArgs { args, constraints, span }.into()
44         } else {
45             None
46         };
47         segments.push(ast::PathSegment {
48             ident: last_ident.with_span_pos(span),
49             id: ast::DUMMY_NODE_ID,
50             args,
51         });
52         ast::Path { span, segments }
53     }
54
55     /// Constructs a qualified path.
56     ///
57     /// Constructs a path like `<self_type as trait_path>::ident`.
58     pub fn qpath(&self,
59              self_type: P<ast::Ty>,
60              trait_path: ast::Path,
61              ident: ast::Ident)
62              -> (ast::QSelf, ast::Path) {
63         self.qpath_all(self_type, trait_path, ident, vec![], vec![])
64     }
65
66     /// Constructs a qualified path.
67     ///
68     /// Constructs a path like `<self_type as trait_path>::ident<'a, T, A = Bar>`.
69     pub fn qpath_all(&self,
70                  self_type: P<ast::Ty>,
71                  trait_path: ast::Path,
72                  ident: ast::Ident,
73                  args: Vec<ast::GenericArg>,
74                  constraints: Vec<ast::AssocTyConstraint>)
75                  -> (ast::QSelf, ast::Path) {
76         let mut path = trait_path;
77         let args = if !args.is_empty() || !constraints.is_empty() {
78             ast::AngleBracketedArgs { args, constraints, span: ident.span }.into()
79         } else {
80             None
81         };
82         path.segments.push(ast::PathSegment { ident, id: ast::DUMMY_NODE_ID, args });
83
84         (ast::QSelf {
85             ty: self_type,
86             path_span: path.span,
87             position: path.segments.len() - 1
88         }, path)
89     }
90
91     pub fn ty_mt(&self, ty: P<ast::Ty>, mutbl: ast::Mutability) -> ast::MutTy {
92         ast::MutTy {
93             ty,
94             mutbl,
95         }
96     }
97
98     pub fn ty(&self, span: Span, ty: ast::TyKind) -> P<ast::Ty> {
99         P(ast::Ty {
100             id: ast::DUMMY_NODE_ID,
101             span,
102             node: ty
103         })
104     }
105
106     pub fn ty_path(&self, path: ast::Path) -> P<ast::Ty> {
107         self.ty(path.span, ast::TyKind::Path(None, path))
108     }
109
110     // Might need to take bounds as an argument in the future, if you ever want
111     // to generate a bounded existential trait type.
112     pub fn ty_ident(&self, span: Span, ident: ast::Ident)
113         -> P<ast::Ty> {
114         self.ty_path(self.path_ident(span, ident))
115     }
116
117     pub fn anon_const(&self, span: Span, expr: ast::ExprKind) -> ast::AnonConst {
118         ast::AnonConst {
119             id: ast::DUMMY_NODE_ID,
120             value: P(ast::Expr {
121                 id: ast::DUMMY_NODE_ID,
122                 node: expr,
123                 span,
124                 attrs: ThinVec::new(),
125             })
126         }
127     }
128
129     pub fn const_ident(&self, span: Span, ident: ast::Ident) -> ast::AnonConst {
130         self.anon_const(span, ast::ExprKind::Path(None, self.path_ident(span, ident)))
131     }
132
133     pub fn ty_rptr(&self,
134                span: Span,
135                ty: P<ast::Ty>,
136                lifetime: Option<ast::Lifetime>,
137                mutbl: ast::Mutability)
138         -> P<ast::Ty> {
139         self.ty(span,
140                 ast::TyKind::Rptr(lifetime, self.ty_mt(ty, mutbl)))
141     }
142
143     pub fn ty_ptr(&self,
144               span: Span,
145               ty: P<ast::Ty>,
146               mutbl: ast::Mutability)
147         -> P<ast::Ty> {
148         self.ty(span,
149                 ast::TyKind::Ptr(self.ty_mt(ty, mutbl)))
150     }
151
152     pub fn ty_infer(&self, span: Span) -> P<ast::Ty> {
153         self.ty(span, ast::TyKind::Infer)
154     }
155
156     pub fn typaram(&self,
157                span: Span,
158                ident: ast::Ident,
159                attrs: Vec<ast::Attribute>,
160                bounds: ast::GenericBounds,
161                default: Option<P<ast::Ty>>) -> ast::GenericParam {
162         ast::GenericParam {
163             ident: ident.with_span_pos(span),
164             id: ast::DUMMY_NODE_ID,
165             attrs: attrs.into(),
166             bounds,
167             kind: ast::GenericParamKind::Type {
168                 default,
169             },
170             is_placeholder: false
171         }
172     }
173
174     pub fn trait_ref(&self, path: ast::Path) -> ast::TraitRef {
175         ast::TraitRef {
176             path,
177             ref_id: ast::DUMMY_NODE_ID,
178         }
179     }
180
181     pub fn poly_trait_ref(&self, span: Span, path: ast::Path) -> ast::PolyTraitRef {
182         ast::PolyTraitRef {
183             bound_generic_params: Vec::new(),
184             trait_ref: self.trait_ref(path),
185             span,
186         }
187     }
188
189     pub fn trait_bound(&self, path: ast::Path) -> ast::GenericBound {
190         ast::GenericBound::Trait(self.poly_trait_ref(path.span, path),
191                                  ast::TraitBoundModifier::None)
192     }
193
194     pub fn lifetime(&self, span: Span, ident: ast::Ident) -> ast::Lifetime {
195         ast::Lifetime { id: ast::DUMMY_NODE_ID, ident: ident.with_span_pos(span) }
196     }
197
198     pub fn lifetime_def(&self,
199                     span: Span,
200                     ident: ast::Ident,
201                     attrs: Vec<ast::Attribute>,
202                     bounds: ast::GenericBounds)
203                     -> ast::GenericParam {
204         let lifetime = self.lifetime(span, ident);
205         ast::GenericParam {
206             ident: lifetime.ident,
207             id: lifetime.id,
208             attrs: attrs.into(),
209             bounds,
210             kind: ast::GenericParamKind::Lifetime,
211             is_placeholder: false
212         }
213     }
214
215     pub fn stmt_expr(&self, expr: P<ast::Expr>) -> ast::Stmt {
216         ast::Stmt {
217             id: ast::DUMMY_NODE_ID,
218             span: expr.span,
219             node: ast::StmtKind::Expr(expr),
220         }
221     }
222
223     pub fn stmt_semi(&self, expr: P<ast::Expr>) -> ast::Stmt {
224         ast::Stmt {
225             id: ast::DUMMY_NODE_ID,
226             span: expr.span,
227             node: ast::StmtKind::Semi(expr),
228         }
229     }
230
231     pub fn stmt_let(&self, sp: Span, mutbl: bool, ident: ast::Ident,
232                 ex: P<ast::Expr>) -> ast::Stmt {
233         let pat = if mutbl {
234             let binding_mode = ast::BindingMode::ByValue(ast::Mutability::Mutable);
235             self.pat_ident_binding_mode(sp, ident, binding_mode)
236         } else {
237             self.pat_ident(sp, ident)
238         };
239         let local = P(ast::Local {
240             pat,
241             ty: None,
242             init: Some(ex),
243             id: ast::DUMMY_NODE_ID,
244             span: sp,
245             attrs: ThinVec::new(),
246         });
247         ast::Stmt {
248             id: ast::DUMMY_NODE_ID,
249             node: ast::StmtKind::Local(local),
250             span: sp,
251         }
252     }
253
254     pub fn stmt_let_typed(&self,
255                       sp: Span,
256                       mutbl: bool,
257                       ident: ast::Ident,
258                       typ: P<ast::Ty>,
259                       ex: P<ast::Expr>)
260                       -> ast::Stmt {
261         let pat = if mutbl {
262             let binding_mode = ast::BindingMode::ByValue(ast::Mutability::Mutable);
263             self.pat_ident_binding_mode(sp, ident, binding_mode)
264         } else {
265             self.pat_ident(sp, ident)
266         };
267         let local = P(ast::Local {
268             pat,
269             ty: Some(typ),
270             init: Some(ex),
271             id: ast::DUMMY_NODE_ID,
272             span: sp,
273             attrs: ThinVec::new(),
274         });
275         ast::Stmt {
276             id: ast::DUMMY_NODE_ID,
277             node: ast::StmtKind::Local(local),
278             span: sp,
279         }
280     }
281
282     // Generates `let _: Type;`, which is usually used for type assertions.
283     pub fn stmt_let_type_only(&self, span: Span, ty: P<ast::Ty>) -> ast::Stmt {
284         let local = P(ast::Local {
285             pat: self.pat_wild(span),
286             ty: Some(ty),
287             init: None,
288             id: ast::DUMMY_NODE_ID,
289             span,
290             attrs: ThinVec::new(),
291         });
292         ast::Stmt {
293             id: ast::DUMMY_NODE_ID,
294             node: ast::StmtKind::Local(local),
295             span,
296         }
297     }
298
299     pub fn stmt_item(&self, sp: Span, item: P<ast::Item>) -> ast::Stmt {
300         ast::Stmt {
301             id: ast::DUMMY_NODE_ID,
302             node: ast::StmtKind::Item(item),
303             span: sp,
304         }
305     }
306
307     pub fn block_expr(&self, expr: P<ast::Expr>) -> P<ast::Block> {
308         self.block(expr.span, vec![ast::Stmt {
309             id: ast::DUMMY_NODE_ID,
310             span: expr.span,
311             node: ast::StmtKind::Expr(expr),
312         }])
313     }
314     pub fn block(&self, span: Span, stmts: Vec<ast::Stmt>) -> P<ast::Block> {
315         P(ast::Block {
316            stmts,
317            id: ast::DUMMY_NODE_ID,
318            rules: BlockCheckMode::Default,
319            span,
320         })
321     }
322
323     pub fn expr(&self, span: Span, node: ast::ExprKind) -> P<ast::Expr> {
324         P(ast::Expr {
325             id: ast::DUMMY_NODE_ID,
326             node,
327             span,
328             attrs: ThinVec::new(),
329         })
330     }
331
332     pub fn expr_path(&self, path: ast::Path) -> P<ast::Expr> {
333         self.expr(path.span, ast::ExprKind::Path(None, path))
334     }
335
336     /// Constructs a `QPath` expression.
337     pub fn expr_qpath(&self, span: Span, qself: ast::QSelf, path: ast::Path) -> P<ast::Expr> {
338         self.expr(span, ast::ExprKind::Path(Some(qself), path))
339     }
340
341     pub fn expr_ident(&self, span: Span, id: ast::Ident) -> P<ast::Expr> {
342         self.expr_path(self.path_ident(span, id))
343     }
344     pub fn expr_self(&self, span: Span) -> P<ast::Expr> {
345         self.expr_ident(span, Ident::with_dummy_span(kw::SelfLower))
346     }
347
348     pub fn expr_binary(&self, sp: Span, op: ast::BinOpKind,
349                    lhs: P<ast::Expr>, rhs: P<ast::Expr>) -> P<ast::Expr> {
350         self.expr(sp, ast::ExprKind::Binary(Spanned { node: op, span: sp }, lhs, rhs))
351     }
352
353     pub fn expr_deref(&self, sp: Span, e: P<ast::Expr>) -> P<ast::Expr> {
354         self.expr_unary(sp, UnOp::Deref, e)
355     }
356     pub fn expr_unary(&self, sp: Span, op: ast::UnOp, e: P<ast::Expr>) -> P<ast::Expr> {
357         self.expr(sp, ast::ExprKind::Unary(op, e))
358     }
359
360     pub fn expr_field_access(
361         &self, sp: Span, expr: P<ast::Expr>, ident: ast::Ident,
362     ) -> P<ast::Expr> {
363         self.expr(sp, ast::ExprKind::Field(expr, ident.with_span_pos(sp)))
364     }
365     pub fn expr_tup_field_access(&self, sp: Span, expr: P<ast::Expr>, idx: usize) -> P<ast::Expr> {
366         let ident = Ident::from_str(&idx.to_string()).with_span_pos(sp);
367         self.expr(sp, ast::ExprKind::Field(expr, ident))
368     }
369     pub fn expr_addr_of(&self, sp: Span, e: P<ast::Expr>) -> P<ast::Expr> {
370         self.expr(sp, ast::ExprKind::AddrOf(ast::Mutability::Immutable, e))
371     }
372     pub fn expr_mut_addr_of(&self, sp: Span, e: P<ast::Expr>) -> P<ast::Expr> {
373         self.expr(sp, ast::ExprKind::AddrOf(ast::Mutability::Mutable, e))
374     }
375
376     pub fn expr_call(
377         &self, span: Span, expr: P<ast::Expr>, args: Vec<P<ast::Expr>>,
378     ) -> P<ast::Expr> {
379         self.expr(span, ast::ExprKind::Call(expr, args))
380     }
381     pub fn expr_call_ident(&self, span: Span, id: ast::Ident,
382                        args: Vec<P<ast::Expr>>) -> P<ast::Expr> {
383         self.expr(span, ast::ExprKind::Call(self.expr_ident(span, id), args))
384     }
385     pub fn expr_call_global(&self, sp: Span, fn_path: Vec<ast::Ident> ,
386                       args: Vec<P<ast::Expr>> ) -> P<ast::Expr> {
387         let pathexpr = self.expr_path(self.path_global(sp, fn_path));
388         self.expr_call(sp, pathexpr, args)
389     }
390     pub fn expr_method_call(&self, span: Span,
391                         expr: P<ast::Expr>,
392                         ident: ast::Ident,
393                         mut args: Vec<P<ast::Expr>> ) -> P<ast::Expr> {
394         args.insert(0, expr);
395         let segment = ast::PathSegment::from_ident(ident.with_span_pos(span));
396         self.expr(span, ast::ExprKind::MethodCall(segment, args))
397     }
398     pub fn expr_block(&self, b: P<ast::Block>) -> P<ast::Expr> {
399         self.expr(b.span, ast::ExprKind::Block(b, None))
400     }
401     pub fn field_imm(&self, span: Span, ident: Ident, e: P<ast::Expr>) -> ast::Field {
402         ast::Field {
403             ident: ident.with_span_pos(span),
404             expr: e,
405             span,
406             is_shorthand: false,
407             attrs: ThinVec::new(),
408             id: ast::DUMMY_NODE_ID,
409             is_placeholder: false,
410         }
411     }
412     pub fn expr_struct(
413         &self, span: Span, path: ast::Path, fields: Vec<ast::Field>
414     ) -> P<ast::Expr> {
415         self.expr(span, ast::ExprKind::Struct(path, fields, None))
416     }
417     pub fn expr_struct_ident(&self, span: Span,
418                          id: ast::Ident, fields: Vec<ast::Field>) -> P<ast::Expr> {
419         self.expr_struct(span, self.path_ident(span, id), fields)
420     }
421
422     pub fn expr_lit(&self, span: Span, lit_kind: ast::LitKind) -> P<ast::Expr> {
423         let lit = ast::Lit::from_lit_kind(lit_kind, span);
424         self.expr(span, ast::ExprKind::Lit(lit))
425     }
426     pub fn expr_usize(&self, span: Span, i: usize) -> P<ast::Expr> {
427         self.expr_lit(span, ast::LitKind::Int(i as u128,
428                                               ast::LitIntType::Unsigned(ast::UintTy::Usize)))
429     }
430     pub fn expr_isize(&self, sp: Span, i: isize) -> P<ast::Expr> {
431         if i < 0 {
432             let i = (-i) as u128;
433             let lit_ty = ast::LitIntType::Signed(ast::IntTy::Isize);
434             let lit = self.expr_lit(sp, ast::LitKind::Int(i, lit_ty));
435             self.expr_unary(sp, ast::UnOp::Neg, lit)
436         } else {
437             self.expr_lit(sp, ast::LitKind::Int(i as u128,
438                                                 ast::LitIntType::Signed(ast::IntTy::Isize)))
439         }
440     }
441     pub fn expr_u32(&self, sp: Span, u: u32) -> P<ast::Expr> {
442         self.expr_lit(sp, ast::LitKind::Int(u as u128,
443                                             ast::LitIntType::Unsigned(ast::UintTy::U32)))
444     }
445     pub fn expr_u16(&self, sp: Span, u: u16) -> P<ast::Expr> {
446         self.expr_lit(sp, ast::LitKind::Int(u as u128,
447                                             ast::LitIntType::Unsigned(ast::UintTy::U16)))
448     }
449     pub fn expr_u8(&self, sp: Span, u: u8) -> P<ast::Expr> {
450         self.expr_lit(sp, ast::LitKind::Int(u as u128, ast::LitIntType::Unsigned(ast::UintTy::U8)))
451     }
452     pub fn expr_bool(&self, sp: Span, value: bool) -> P<ast::Expr> {
453         self.expr_lit(sp, ast::LitKind::Bool(value))
454     }
455
456     pub fn expr_vec(&self, sp: Span, exprs: Vec<P<ast::Expr>>) -> P<ast::Expr> {
457         self.expr(sp, ast::ExprKind::Array(exprs))
458     }
459     pub fn expr_vec_ng(&self, sp: Span) -> P<ast::Expr> {
460         self.expr_call_global(sp, self.std_path(&[sym::vec, sym::Vec, sym::new]),
461                               Vec::new())
462     }
463     pub fn expr_vec_slice(&self, sp: Span, exprs: Vec<P<ast::Expr>>) -> P<ast::Expr> {
464         self.expr_addr_of(sp, self.expr_vec(sp, exprs))
465     }
466     pub fn expr_str(&self, sp: Span, s: Symbol) -> P<ast::Expr> {
467         self.expr_lit(sp, ast::LitKind::Str(s, ast::StrStyle::Cooked))
468     }
469
470     pub fn expr_cast(&self, sp: Span, expr: P<ast::Expr>, ty: P<ast::Ty>) -> P<ast::Expr> {
471         self.expr(sp, ast::ExprKind::Cast(expr, ty))
472     }
473
474     pub fn expr_some(&self, sp: Span, expr: P<ast::Expr>) -> P<ast::Expr> {
475         let some = self.std_path(&[sym::option, sym::Option, sym::Some]);
476         self.expr_call_global(sp, some, vec![expr])
477     }
478
479     pub fn expr_none(&self, sp: Span) -> P<ast::Expr> {
480         let none = self.std_path(&[sym::option, sym::Option, sym::None]);
481         let none = self.path_global(sp, none);
482         self.expr_path(none)
483     }
484
485     pub fn expr_break(&self, sp: Span) -> P<ast::Expr> {
486         self.expr(sp, ast::ExprKind::Break(None, None))
487     }
488
489     pub fn expr_tuple(&self, sp: Span, exprs: Vec<P<ast::Expr>>) -> P<ast::Expr> {
490         self.expr(sp, ast::ExprKind::Tup(exprs))
491     }
492
493     pub fn expr_fail(&self, span: Span, msg: Symbol) -> P<ast::Expr> {
494         let loc = self.source_map().lookup_char_pos(span.lo());
495         let expr_file = self.expr_str(span, Symbol::intern(&loc.file.name.to_string()));
496         let expr_line = self.expr_u32(span, loc.line as u32);
497         let expr_col = self.expr_u32(span, loc.col.to_usize() as u32 + 1);
498         let expr_loc_tuple = self.expr_tuple(span, vec![expr_file, expr_line, expr_col]);
499         let expr_loc_ptr = self.expr_addr_of(span, expr_loc_tuple);
500         self.expr_call_global(
501             span,
502             [sym::std, sym::rt, sym::begin_panic].iter().map(|s| Ident::new(*s, span)).collect(),
503             vec![
504                 self.expr_str(span, msg),
505                 expr_loc_ptr])
506     }
507
508     pub fn expr_unreachable(&self, span: Span) -> P<ast::Expr> {
509         self.expr_fail(span, Symbol::intern("internal error: entered unreachable code"))
510     }
511
512     pub fn expr_ok(&self, sp: Span, expr: P<ast::Expr>) -> P<ast::Expr> {
513         let ok = self.std_path(&[sym::result, sym::Result, sym::Ok]);
514         self.expr_call_global(sp, ok, vec![expr])
515     }
516
517     pub fn expr_err(&self, sp: Span, expr: P<ast::Expr>) -> P<ast::Expr> {
518         let err = self.std_path(&[sym::result, sym::Result, sym::Err]);
519         self.expr_call_global(sp, err, vec![expr])
520     }
521
522     pub fn expr_try(&self, sp: Span, head: P<ast::Expr>) -> P<ast::Expr> {
523         let ok = self.std_path(&[sym::result, sym::Result, sym::Ok]);
524         let ok_path = self.path_global(sp, ok);
525         let err = self.std_path(&[sym::result, sym::Result, sym::Err]);
526         let err_path = self.path_global(sp, err);
527
528         let binding_variable = self.ident_of("__try_var");
529         let binding_pat = self.pat_ident(sp, binding_variable);
530         let binding_expr = self.expr_ident(sp, binding_variable);
531
532         // `Ok(__try_var)` pattern
533         let ok_pat = self.pat_tuple_struct(sp, ok_path, vec![binding_pat.clone()]);
534
535         // `Err(__try_var)` (pattern and expression respectively)
536         let err_pat = self.pat_tuple_struct(sp, err_path.clone(), vec![binding_pat]);
537         let err_inner_expr = self.expr_call(sp, self.expr_path(err_path),
538                                             vec![binding_expr.clone()]);
539         // `return Err(__try_var)`
540         let err_expr = self.expr(sp, ast::ExprKind::Ret(Some(err_inner_expr)));
541
542         // `Ok(__try_var) => __try_var`
543         let ok_arm = self.arm(sp, ok_pat, binding_expr);
544         // `Err(__try_var) => return Err(__try_var)`
545         let err_arm = self.arm(sp, err_pat, err_expr);
546
547         // `match head { Ok() => ..., Err() => ... }`
548         self.expr_match(sp, head, vec![ok_arm, err_arm])
549     }
550
551
552     pub fn pat(&self, span: Span, pat: PatKind) -> P<ast::Pat> {
553         P(ast::Pat { id: ast::DUMMY_NODE_ID, node: pat, span })
554     }
555     pub fn pat_wild(&self, span: Span) -> P<ast::Pat> {
556         self.pat(span, PatKind::Wild)
557     }
558     pub fn pat_lit(&self, span: Span, expr: P<ast::Expr>) -> P<ast::Pat> {
559         self.pat(span, PatKind::Lit(expr))
560     }
561     pub fn pat_ident(&self, span: Span, ident: ast::Ident) -> P<ast::Pat> {
562         let binding_mode = ast::BindingMode::ByValue(ast::Mutability::Immutable);
563         self.pat_ident_binding_mode(span, ident, binding_mode)
564     }
565
566     pub fn pat_ident_binding_mode(&self,
567                               span: Span,
568                               ident: ast::Ident,
569                               bm: ast::BindingMode) -> P<ast::Pat> {
570         let pat = PatKind::Ident(bm, ident.with_span_pos(span), None);
571         self.pat(span, pat)
572     }
573     pub fn pat_path(&self, span: Span, path: ast::Path) -> P<ast::Pat> {
574         self.pat(span, PatKind::Path(None, path))
575     }
576     pub fn pat_tuple_struct(&self, span: Span, path: ast::Path,
577                         subpats: Vec<P<ast::Pat>>) -> P<ast::Pat> {
578         self.pat(span, PatKind::TupleStruct(path, subpats))
579     }
580     pub fn pat_struct(&self, span: Span, path: ast::Path,
581                       field_pats: Vec<ast::FieldPat>) -> P<ast::Pat> {
582         self.pat(span, PatKind::Struct(path, field_pats, false))
583     }
584     pub fn pat_tuple(&self, span: Span, pats: Vec<P<ast::Pat>>) -> P<ast::Pat> {
585         self.pat(span, PatKind::Tuple(pats))
586     }
587
588     pub fn pat_some(&self, span: Span, pat: P<ast::Pat>) -> P<ast::Pat> {
589         let some = self.std_path(&[sym::option, sym::Option, sym::Some]);
590         let path = self.path_global(span, some);
591         self.pat_tuple_struct(span, path, vec![pat])
592     }
593
594     pub fn pat_none(&self, span: Span) -> P<ast::Pat> {
595         let some = self.std_path(&[sym::option, sym::Option, sym::None]);
596         let path = self.path_global(span, some);
597         self.pat_path(span, path)
598     }
599
600     pub fn pat_ok(&self, span: Span, pat: P<ast::Pat>) -> P<ast::Pat> {
601         let some = self.std_path(&[sym::result, sym::Result, sym::Ok]);
602         let path = self.path_global(span, some);
603         self.pat_tuple_struct(span, path, vec![pat])
604     }
605
606     pub fn pat_err(&self, span: Span, pat: P<ast::Pat>) -> P<ast::Pat> {
607         let some = self.std_path(&[sym::result, sym::Result, sym::Err]);
608         let path = self.path_global(span, some);
609         self.pat_tuple_struct(span, path, vec![pat])
610     }
611
612     pub fn arm(&self, span: Span, pat: P<ast::Pat>, expr: P<ast::Expr>) -> ast::Arm {
613         ast::Arm {
614             attrs: vec![],
615             pat,
616             guard: None,
617             body: expr,
618             span,
619             id: ast::DUMMY_NODE_ID,
620             is_placeholder: false,
621         }
622     }
623
624     pub fn arm_unreachable(&self, span: Span) -> ast::Arm {
625         self.arm(span, self.pat_wild(span), self.expr_unreachable(span))
626     }
627
628     pub fn expr_match(&self, span: Span, arg: P<ast::Expr>, arms: Vec<ast::Arm>) -> P<Expr> {
629         self.expr(span, ast::ExprKind::Match(arg, arms))
630     }
631
632     pub fn expr_if(&self, span: Span, cond: P<ast::Expr>,
633                then: P<ast::Expr>, els: Option<P<ast::Expr>>) -> P<ast::Expr> {
634         let els = els.map(|x| self.expr_block(self.block_expr(x)));
635         self.expr(span, ast::ExprKind::If(cond, self.block_expr(then), els))
636     }
637
638     pub fn expr_loop(&self, span: Span, block: P<ast::Block>) -> P<ast::Expr> {
639         self.expr(span, ast::ExprKind::Loop(block, None))
640     }
641
642     pub fn lambda_fn_decl(&self,
643                       span: Span,
644                       fn_decl: P<ast::FnDecl>,
645                       body: P<ast::Expr>,
646                       fn_decl_span: Span) // span of the `|...|` part
647                       -> P<ast::Expr> {
648         self.expr(span, ast::ExprKind::Closure(ast::CaptureBy::Ref,
649                                                ast::IsAsync::NotAsync,
650                                                ast::Movability::Movable,
651                                                fn_decl,
652                                                body,
653                                                fn_decl_span))
654     }
655
656     pub fn lambda(&self,
657               span: Span,
658               ids: Vec<ast::Ident>,
659               body: P<ast::Expr>)
660               -> P<ast::Expr> {
661         let fn_decl = self.fn_decl(
662             ids.iter().map(|id| self.param(span, *id, self.ty_infer(span))).collect(),
663             ast::FunctionRetTy::Default(span));
664
665         // FIXME -- We are using `span` as the span of the `|...|`
666         // part of the lambda, but it probably (maybe?) corresponds to
667         // the entire lambda body. Probably we should extend the API
668         // here, but that's not entirely clear.
669         self.expr(span, ast::ExprKind::Closure(ast::CaptureBy::Ref,
670                                                ast::IsAsync::NotAsync,
671                                                ast::Movability::Movable,
672                                                fn_decl,
673                                                body,
674                                                span))
675     }
676
677     pub fn lambda0(&self, span: Span, body: P<ast::Expr>) -> P<ast::Expr> {
678         self.lambda(span, Vec::new(), body)
679     }
680
681     pub fn lambda1(&self, span: Span, body: P<ast::Expr>, ident: ast::Ident) -> P<ast::Expr> {
682         self.lambda(span, vec![ident], body)
683     }
684
685     pub fn lambda_stmts(&self,
686                     span: Span,
687                     ids: Vec<ast::Ident>,
688                     stmts: Vec<ast::Stmt>)
689                     -> P<ast::Expr> {
690         self.lambda(span, ids, self.expr_block(self.block(span, stmts)))
691     }
692     pub fn lambda_stmts_0(&self, span: Span, stmts: Vec<ast::Stmt>) -> P<ast::Expr> {
693         self.lambda0(span, self.expr_block(self.block(span, stmts)))
694     }
695     pub fn lambda_stmts_1(&self, span: Span, stmts: Vec<ast::Stmt>,
696                       ident: ast::Ident) -> P<ast::Expr> {
697         self.lambda1(span, self.expr_block(self.block(span, stmts)), ident)
698     }
699
700     pub fn param(&self, span: Span, ident: ast::Ident, ty: P<ast::Ty>) -> ast::Param {
701         let arg_pat = self.pat_ident(span, ident);
702         ast::Param {
703             attrs: ThinVec::default(),
704             id: ast::DUMMY_NODE_ID,
705             pat: arg_pat,
706             span,
707             ty,
708             is_placeholder: false,
709         }
710     }
711
712     // FIXME: unused `self`
713     pub fn fn_decl(&self, inputs: Vec<ast::Param>, output: ast::FunctionRetTy) -> P<ast::FnDecl> {
714         P(ast::FnDecl {
715             inputs,
716             output,
717             c_variadic: false
718         })
719     }
720
721     pub fn item(&self, span: Span, name: Ident,
722             attrs: Vec<ast::Attribute>, node: ast::ItemKind) -> P<ast::Item> {
723         // FIXME: Would be nice if our generated code didn't violate
724         // Rust coding conventions
725         P(ast::Item {
726             ident: name,
727             attrs,
728             id: ast::DUMMY_NODE_ID,
729             node,
730             vis: respan(span.shrink_to_lo(), ast::VisibilityKind::Inherited),
731             span,
732             tokens: None,
733         })
734     }
735
736     pub fn item_fn_poly(&self,
737                     span: Span,
738                     name: Ident,
739                     inputs: Vec<ast::Param> ,
740                     output: P<ast::Ty>,
741                     generics: Generics,
742                     body: P<ast::Block>) -> P<ast::Item> {
743         self.item(span,
744                   name,
745                   Vec::new(),
746                   ast::ItemKind::Fn(self.fn_decl(inputs, ast::FunctionRetTy::Ty(output)),
747                               ast::FnHeader {
748                                   unsafety: ast::Unsafety::Normal,
749                                   asyncness: dummy_spanned(ast::IsAsync::NotAsync),
750                                   constness: dummy_spanned(ast::Constness::NotConst),
751                                   abi: Abi::Rust,
752                               },
753                               generics,
754                               body))
755     }
756
757     pub fn item_fn(&self,
758                span: Span,
759                name: Ident,
760                inputs: Vec<ast::Param> ,
761                output: P<ast::Ty>,
762                body: P<ast::Block>
763               ) -> P<ast::Item> {
764         self.item_fn_poly(
765             span,
766             name,
767             inputs,
768             output,
769             Generics::default(),
770             body)
771     }
772
773     pub fn variant(&self, span: Span, ident: Ident, tys: Vec<P<ast::Ty>> ) -> ast::Variant {
774         let fields: Vec<_> = tys.into_iter().map(|ty| {
775             ast::StructField {
776                 span: ty.span,
777                 ty,
778                 ident: None,
779                 vis: respan(span.shrink_to_lo(), ast::VisibilityKind::Inherited),
780                 attrs: Vec::new(),
781                 id: ast::DUMMY_NODE_ID,
782                 is_placeholder: false,
783             }
784         }).collect();
785
786         let vdata = if fields.is_empty() {
787             ast::VariantData::Unit(ast::DUMMY_NODE_ID)
788         } else {
789             ast::VariantData::Tuple(fields, ast::DUMMY_NODE_ID)
790         };
791
792         ast::Variant {
793             attrs: Vec::new(),
794             data: vdata,
795             disr_expr: None,
796             id: ast::DUMMY_NODE_ID,
797             ident,
798             span,
799             is_placeholder: false,
800         }
801     }
802
803     pub fn item_enum_poly(&self, span: Span, name: Ident,
804                       enum_definition: ast::EnumDef,
805                       generics: Generics) -> P<ast::Item> {
806         self.item(span, name, Vec::new(), ast::ItemKind::Enum(enum_definition, generics))
807     }
808
809     pub fn item_enum(&self, span: Span, name: Ident,
810                  enum_definition: ast::EnumDef) -> P<ast::Item> {
811         self.item_enum_poly(span, name, enum_definition,
812                             Generics::default())
813     }
814
815     pub fn item_struct(&self, span: Span, name: Ident,
816                    struct_def: ast::VariantData) -> P<ast::Item> {
817         self.item_struct_poly(
818             span,
819             name,
820             struct_def,
821             Generics::default()
822         )
823     }
824
825     pub fn item_struct_poly(&self, span: Span, name: Ident,
826         struct_def: ast::VariantData, generics: Generics) -> P<ast::Item> {
827         self.item(span, name, Vec::new(), ast::ItemKind::Struct(struct_def, generics))
828     }
829
830     pub fn item_mod(&self, span: Span, inner_span: Span, name: Ident,
831                 attrs: Vec<ast::Attribute>,
832                 items: Vec<P<ast::Item>>) -> P<ast::Item> {
833         self.item(
834             span,
835             name,
836             attrs,
837             ast::ItemKind::Mod(ast::Mod {
838                 inner: inner_span,
839                 items,
840                 inline: true
841             })
842         )
843     }
844
845     pub fn item_extern_crate(&self, span: Span, name: Ident) -> P<ast::Item> {
846         self.item(span, name, Vec::new(), ast::ItemKind::ExternCrate(None))
847     }
848
849     pub fn item_static(&self,
850                    span: Span,
851                    name: Ident,
852                    ty: P<ast::Ty>,
853                    mutbl: ast::Mutability,
854                    expr: P<ast::Expr>)
855                    -> P<ast::Item> {
856         self.item(span, name, Vec::new(), ast::ItemKind::Static(ty, mutbl, expr))
857     }
858
859     pub fn item_const(&self,
860                   span: Span,
861                   name: Ident,
862                   ty: P<ast::Ty>,
863                   expr: P<ast::Expr>)
864                   -> P<ast::Item> {
865         self.item(span, name, Vec::new(), ast::ItemKind::Const(ty, expr))
866     }
867
868     pub fn item_ty_poly(&self, span: Span, name: Ident, ty: P<ast::Ty>,
869                     generics: Generics) -> P<ast::Item> {
870         self.item(span, name, Vec::new(), ast::ItemKind::TyAlias(ty, generics))
871     }
872
873     pub fn item_ty(&self, span: Span, name: Ident, ty: P<ast::Ty>) -> P<ast::Item> {
874         self.item_ty_poly(span, name, ty, Generics::default())
875     }
876
877     pub fn attribute(&self, mi: ast::MetaItem) -> ast::Attribute {
878         attr::mk_attr_outer(mi)
879     }
880
881     pub fn meta_word(&self, sp: Span, w: ast::Name) -> ast::MetaItem {
882         attr::mk_word_item(Ident::new(w, sp))
883     }
884
885     pub fn meta_list_item_word(&self, sp: Span, w: ast::Name) -> ast::NestedMetaItem {
886         attr::mk_nested_word_item(Ident::new(w, sp))
887     }
888
889     pub fn meta_list(&self, sp: Span, name: ast::Name, mis: Vec<ast::NestedMetaItem>)
890                  -> ast::MetaItem {
891         attr::mk_list_item(Ident::new(name, sp), mis)
892     }
893
894     pub fn meta_name_value(&self, span: Span, name: ast::Name, lit_kind: ast::LitKind)
895                        -> ast::MetaItem {
896         attr::mk_name_value_item(Ident::new(name, span), lit_kind, span)
897     }
898
899     pub fn item_use(&self, sp: Span,
900                 vis: ast::Visibility, vp: P<ast::UseTree>) -> P<ast::Item> {
901         P(ast::Item {
902             id: ast::DUMMY_NODE_ID,
903             ident: Ident::invalid(),
904             attrs: vec![],
905             node: ast::ItemKind::Use(vp),
906             vis,
907             span: sp,
908             tokens: None,
909         })
910     }
911
912     pub fn item_use_simple(&self, sp: Span, vis: ast::Visibility, path: ast::Path) -> P<ast::Item> {
913         self.item_use_simple_(sp, vis, None, path)
914     }
915
916     pub fn item_use_simple_(&self, sp: Span, vis: ast::Visibility,
917                         rename: Option<ast::Ident>, path: ast::Path) -> P<ast::Item> {
918         self.item_use(sp, vis, P(ast::UseTree {
919             span: sp,
920             prefix: path,
921             kind: ast::UseTreeKind::Simple(rename, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID),
922         }))
923     }
924
925     pub fn item_use_list(&self, sp: Span, vis: ast::Visibility,
926                      path: Vec<ast::Ident>, imports: &[ast::Ident]) -> P<ast::Item> {
927         let imports = imports.iter().map(|id| {
928             (ast::UseTree {
929                 span: sp,
930                 prefix: self.path(sp, vec![*id]),
931                 kind: ast::UseTreeKind::Simple(None, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID),
932             }, ast::DUMMY_NODE_ID)
933         }).collect();
934
935         self.item_use(sp, vis, P(ast::UseTree {
936             span: sp,
937             prefix: self.path(sp, path),
938             kind: ast::UseTreeKind::Nested(imports),
939         }))
940     }
941
942     pub fn item_use_glob(&self, sp: Span,
943                      vis: ast::Visibility, path: Vec<ast::Ident>) -> P<ast::Item> {
944         self.item_use(sp, vis, P(ast::UseTree {
945             span: sp,
946             prefix: self.path(sp, path),
947             kind: ast::UseTreeKind::Glob,
948         }))
949     }
950 }