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