rustc_expand/
build.rs

1use rustc_ast::token::Delimiter;
2use rustc_ast::tokenstream::TokenStream;
3use rustc_ast::util::literal;
4use rustc_ast::{
5    self as ast, AnonConst, AttrItem, AttrVec, BlockCheckMode, Expr, LocalKind, MatchKind,
6    MgcaDisambiguation, PatKind, UnOp, attr, token, tokenstream,
7};
8use rustc_span::source_map::Spanned;
9use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, sym};
10use thin_vec::{ThinVec, thin_vec};
11
12use crate::base::ExtCtxt;
13
14impl<'a> ExtCtxt<'a> {
15    pub fn path(&self, span: Span, strs: Vec<Ident>) -> ast::Path {
16        self.path_all(span, false, strs, vec![])
17    }
18    pub fn path_ident(&self, span: Span, id: Ident) -> ast::Path {
19        self.path(span, vec![id])
20    }
21    pub fn path_global(&self, span: Span, strs: Vec<Ident>) -> ast::Path {
22        self.path_all(span, true, strs, vec![])
23    }
24    pub fn path_all(
25        &self,
26        span: Span,
27        global: bool,
28        mut idents: Vec<Ident>,
29        args: Vec<ast::GenericArg>,
30    ) -> ast::Path {
31        assert!(!idents.is_empty());
32        let add_root = global && !idents[0].is_path_segment_keyword();
33        let mut segments = ThinVec::with_capacity(idents.len() + add_root as usize);
34        if add_root {
35            segments.push(ast::PathSegment::path_root(span));
36        }
37        let last_ident = idents.pop().unwrap();
38        segments.extend(
39            idents.into_iter().map(|ident| ast::PathSegment::from_ident(ident.with_span_pos(span))),
40        );
41        let args = if !args.is_empty() {
42            let args = args.into_iter().map(ast::AngleBracketedArg::Arg).collect();
43            Some(ast::AngleBracketedArgs { args, 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, tokens: None }
53    }
54
55    pub fn macro_call(
56        &self,
57        span: Span,
58        path: ast::Path,
59        delim: Delimiter,
60        tokens: TokenStream,
61    ) -> Box<ast::MacCall> {
62        Box::new(ast::MacCall {
63            path,
64            args: Box::new(ast::DelimArgs {
65                dspan: tokenstream::DelimSpan { open: span, close: span },
66                delim,
67                tokens,
68            }),
69        })
70    }
71
72    pub fn ty_mt(&self, ty: Box<ast::Ty>, mutbl: ast::Mutability) -> ast::MutTy {
73        ast::MutTy { ty, mutbl }
74    }
75
76    pub fn ty(&self, span: Span, kind: ast::TyKind) -> Box<ast::Ty> {
77        Box::new(ast::Ty { id: ast::DUMMY_NODE_ID, span, kind, tokens: None })
78    }
79
80    pub fn ty_infer(&self, span: Span) -> Box<ast::Ty> {
81        self.ty(span, ast::TyKind::Infer)
82    }
83
84    pub fn ty_path(&self, path: ast::Path) -> Box<ast::Ty> {
85        self.ty(path.span, ast::TyKind::Path(None, path))
86    }
87
88    // Might need to take bounds as an argument in the future, if you ever want
89    // to generate a bounded existential trait type.
90    pub fn ty_ident(&self, span: Span, ident: Ident) -> Box<ast::Ty> {
91        self.ty_path(self.path_ident(span, ident))
92    }
93
94    pub fn anon_const(&self, span: Span, kind: ast::ExprKind) -> ast::AnonConst {
95        ast::AnonConst {
96            id: ast::DUMMY_NODE_ID,
97            value: Box::new(ast::Expr {
98                id: ast::DUMMY_NODE_ID,
99                kind,
100                span,
101                attrs: AttrVec::new(),
102                tokens: None,
103            }),
104            mgca_disambiguation: MgcaDisambiguation::Direct,
105        }
106    }
107
108    pub fn anon_const_block(&self, b: Box<ast::Block>) -> Box<ast::AnonConst> {
109        Box::new(self.anon_const(b.span, ast::ExprKind::Block(b, None)))
110    }
111
112    pub fn const_ident(&self, span: Span, ident: Ident) -> ast::AnonConst {
113        self.anon_const(span, ast::ExprKind::Path(None, self.path_ident(span, ident)))
114    }
115
116    pub fn ty_ref(
117        &self,
118        span: Span,
119        ty: Box<ast::Ty>,
120        lifetime: Option<ast::Lifetime>,
121        mutbl: ast::Mutability,
122    ) -> Box<ast::Ty> {
123        self.ty(span, ast::TyKind::Ref(lifetime, self.ty_mt(ty, mutbl)))
124    }
125
126    pub fn ty_ptr(&self, span: Span, ty: Box<ast::Ty>, mutbl: ast::Mutability) -> Box<ast::Ty> {
127        self.ty(span, ast::TyKind::Ptr(self.ty_mt(ty, mutbl)))
128    }
129
130    pub fn typaram(
131        &self,
132        span: Span,
133        ident: Ident,
134        bounds: ast::GenericBounds,
135        default: Option<Box<ast::Ty>>,
136    ) -> ast::GenericParam {
137        ast::GenericParam {
138            ident: ident.with_span_pos(span),
139            id: ast::DUMMY_NODE_ID,
140            attrs: AttrVec::new(),
141            bounds,
142            kind: ast::GenericParamKind::Type { default },
143            is_placeholder: false,
144            colon_span: None,
145        }
146    }
147
148    pub fn lifetime_param(
149        &self,
150        span: Span,
151        ident: Ident,
152        bounds: ast::GenericBounds,
153    ) -> ast::GenericParam {
154        ast::GenericParam {
155            id: ast::DUMMY_NODE_ID,
156            ident: ident.with_span_pos(span),
157            attrs: AttrVec::new(),
158            bounds,
159            is_placeholder: false,
160            kind: ast::GenericParamKind::Lifetime,
161            colon_span: None,
162        }
163    }
164
165    pub fn const_param(
166        &self,
167        span: Span,
168        ident: Ident,
169        bounds: ast::GenericBounds,
170        ty: Box<ast::Ty>,
171        default: Option<AnonConst>,
172    ) -> ast::GenericParam {
173        ast::GenericParam {
174            id: ast::DUMMY_NODE_ID,
175            ident: ident.with_span_pos(span),
176            attrs: AttrVec::new(),
177            bounds,
178            is_placeholder: false,
179            kind: ast::GenericParamKind::Const { ty, span: DUMMY_SP, default },
180            colon_span: None,
181        }
182    }
183
184    pub fn trait_ref(&self, path: ast::Path) -> ast::TraitRef {
185        ast::TraitRef { path, ref_id: ast::DUMMY_NODE_ID }
186    }
187
188    pub fn poly_trait_ref(&self, span: Span, path: ast::Path, is_const: bool) -> ast::PolyTraitRef {
189        ast::PolyTraitRef {
190            bound_generic_params: ThinVec::new(),
191            modifiers: ast::TraitBoundModifiers {
192                polarity: ast::BoundPolarity::Positive,
193                constness: if is_const {
194                    ast::BoundConstness::Maybe(DUMMY_SP)
195                } else {
196                    ast::BoundConstness::Never
197                },
198                asyncness: ast::BoundAsyncness::Normal,
199            },
200            trait_ref: self.trait_ref(path),
201            span,
202            parens: ast::Parens::No,
203        }
204    }
205
206    pub fn trait_bound(&self, path: ast::Path, is_const: bool) -> ast::GenericBound {
207        ast::GenericBound::Trait(self.poly_trait_ref(path.span, path, is_const))
208    }
209
210    pub fn lifetime(&self, span: Span, ident: Ident) -> ast::Lifetime {
211        ast::Lifetime { id: ast::DUMMY_NODE_ID, ident: ident.with_span_pos(span) }
212    }
213
214    pub fn lifetime_static(&self, span: Span) -> ast::Lifetime {
215        self.lifetime(span, Ident::new(kw::StaticLifetime, span))
216    }
217
218    pub fn stmt_expr(&self, expr: Box<ast::Expr>) -> ast::Stmt {
219        ast::Stmt { id: ast::DUMMY_NODE_ID, span: expr.span, kind: ast::StmtKind::Expr(expr) }
220    }
221
222    pub fn stmt_let(&self, sp: Span, mutbl: bool, ident: Ident, ex: Box<ast::Expr>) -> ast::Stmt {
223        self.stmt_let_ty(sp, mutbl, ident, None, ex)
224    }
225
226    pub fn stmt_let_ty(
227        &self,
228        sp: Span,
229        mutbl: bool,
230        ident: Ident,
231        ty: Option<Box<ast::Ty>>,
232        ex: Box<ast::Expr>,
233    ) -> ast::Stmt {
234        let pat = if mutbl {
235            self.pat_ident_binding_mode(sp, ident, ast::BindingMode::MUT)
236        } else {
237            self.pat_ident(sp, ident)
238        };
239        let local = Box::new(ast::Local {
240            super_: None,
241            pat: Box::new(pat),
242            ty,
243            id: ast::DUMMY_NODE_ID,
244            kind: LocalKind::Init(ex),
245            span: sp,
246            colon_sp: None,
247            attrs: AttrVec::new(),
248            tokens: None,
249        });
250        self.stmt_local(local, sp)
251    }
252
253    /// Generates `let _: Type;`, which is usually used for type assertions.
254    pub fn stmt_let_type_only(&self, span: Span, ty: Box<ast::Ty>) -> ast::Stmt {
255        let local = Box::new(ast::Local {
256            super_: None,
257            pat: Box::new(self.pat_wild(span)),
258            ty: Some(ty),
259            id: ast::DUMMY_NODE_ID,
260            kind: LocalKind::Decl,
261            span,
262            colon_sp: None,
263            attrs: AttrVec::new(),
264            tokens: None,
265        });
266        self.stmt_local(local, span)
267    }
268
269    pub fn stmt_semi(&self, expr: Box<ast::Expr>) -> ast::Stmt {
270        ast::Stmt { id: ast::DUMMY_NODE_ID, span: expr.span, kind: ast::StmtKind::Semi(expr) }
271    }
272
273    pub fn stmt_local(&self, local: Box<ast::Local>, span: Span) -> ast::Stmt {
274        ast::Stmt { id: ast::DUMMY_NODE_ID, kind: ast::StmtKind::Let(local), span }
275    }
276
277    pub fn stmt_item(&self, sp: Span, item: Box<ast::Item>) -> ast::Stmt {
278        ast::Stmt { id: ast::DUMMY_NODE_ID, kind: ast::StmtKind::Item(item), span: sp }
279    }
280
281    pub fn block_expr(&self, expr: Box<ast::Expr>) -> Box<ast::Block> {
282        self.block(
283            expr.span,
284            thin_vec![ast::Stmt {
285                id: ast::DUMMY_NODE_ID,
286                span: expr.span,
287                kind: ast::StmtKind::Expr(expr),
288            }],
289        )
290    }
291    pub fn block(&self, span: Span, stmts: ThinVec<ast::Stmt>) -> Box<ast::Block> {
292        Box::new(ast::Block {
293            stmts,
294            id: ast::DUMMY_NODE_ID,
295            rules: BlockCheckMode::Default,
296            span,
297            tokens: None,
298        })
299    }
300
301    pub fn expr(&self, span: Span, kind: ast::ExprKind) -> Box<ast::Expr> {
302        Box::new(ast::Expr {
303            id: ast::DUMMY_NODE_ID,
304            kind,
305            span,
306            attrs: AttrVec::new(),
307            tokens: None,
308        })
309    }
310
311    pub fn expr_path(&self, path: ast::Path) -> Box<ast::Expr> {
312        self.expr(path.span, ast::ExprKind::Path(None, path))
313    }
314
315    pub fn expr_ident(&self, span: Span, id: Ident) -> Box<ast::Expr> {
316        self.expr_path(self.path_ident(span, id))
317    }
318    pub fn expr_self(&self, span: Span) -> Box<ast::Expr> {
319        self.expr_ident(span, Ident::with_dummy_span(kw::SelfLower))
320    }
321
322    pub fn expr_macro_call(&self, span: Span, call: Box<ast::MacCall>) -> Box<ast::Expr> {
323        self.expr(span, ast::ExprKind::MacCall(call))
324    }
325
326    pub fn expr_binary(
327        &self,
328        sp: Span,
329        op: ast::BinOpKind,
330        lhs: Box<ast::Expr>,
331        rhs: Box<ast::Expr>,
332    ) -> Box<ast::Expr> {
333        self.expr(sp, ast::ExprKind::Binary(Spanned { node: op, span: sp }, lhs, rhs))
334    }
335
336    pub fn expr_deref(&self, sp: Span, e: Box<ast::Expr>) -> Box<ast::Expr> {
337        self.expr(sp, ast::ExprKind::Unary(UnOp::Deref, e))
338    }
339
340    pub fn expr_addr_of(&self, sp: Span, e: Box<ast::Expr>) -> Box<ast::Expr> {
341        self.expr(sp, ast::ExprKind::AddrOf(ast::BorrowKind::Ref, ast::Mutability::Not, e))
342    }
343
344    pub fn expr_paren(&self, sp: Span, e: Box<ast::Expr>) -> Box<ast::Expr> {
345        self.expr(sp, ast::ExprKind::Paren(e))
346    }
347
348    pub fn expr_method_call(
349        &self,
350        span: Span,
351        expr: Box<ast::Expr>,
352        ident: Ident,
353        args: ThinVec<Box<ast::Expr>>,
354    ) -> Box<ast::Expr> {
355        let seg = ast::PathSegment::from_ident(ident);
356        self.expr(
357            span,
358            ast::ExprKind::MethodCall(Box::new(ast::MethodCall {
359                seg,
360                receiver: expr,
361                args,
362                span,
363            })),
364        )
365    }
366
367    pub fn expr_call(
368        &self,
369        span: Span,
370        expr: Box<ast::Expr>,
371        args: ThinVec<Box<ast::Expr>>,
372    ) -> Box<ast::Expr> {
373        self.expr(span, ast::ExprKind::Call(expr, args))
374    }
375    pub fn expr_loop(&self, sp: Span, block: Box<ast::Block>) -> Box<ast::Expr> {
376        self.expr(sp, ast::ExprKind::Loop(block, None, sp))
377    }
378    pub fn expr_asm(&self, sp: Span, expr: Box<ast::InlineAsm>) -> Box<ast::Expr> {
379        self.expr(sp, ast::ExprKind::InlineAsm(expr))
380    }
381    pub fn expr_call_ident(
382        &self,
383        span: Span,
384        id: Ident,
385        args: ThinVec<Box<ast::Expr>>,
386    ) -> Box<ast::Expr> {
387        self.expr(span, ast::ExprKind::Call(self.expr_ident(span, id), args))
388    }
389    pub fn expr_call_global(
390        &self,
391        sp: Span,
392        fn_path: Vec<Ident>,
393        args: ThinVec<Box<ast::Expr>>,
394    ) -> Box<ast::Expr> {
395        let pathexpr = self.expr_path(self.path_global(sp, fn_path));
396        self.expr_call(sp, pathexpr, args)
397    }
398    pub fn expr_block(&self, b: Box<ast::Block>) -> Box<ast::Expr> {
399        self.expr(b.span, ast::ExprKind::Block(b, None))
400    }
401    pub fn field_imm(&self, span: Span, ident: Ident, e: Box<ast::Expr>) -> ast::ExprField {
402        ast::ExprField {
403            ident: ident.with_span_pos(span),
404            expr: e,
405            span,
406            is_shorthand: false,
407            attrs: AttrVec::new(),
408            id: ast::DUMMY_NODE_ID,
409            is_placeholder: false,
410        }
411    }
412    pub fn expr_struct(
413        &self,
414        span: Span,
415        path: ast::Path,
416        fields: ThinVec<ast::ExprField>,
417    ) -> Box<ast::Expr> {
418        self.expr(
419            span,
420            ast::ExprKind::Struct(Box::new(ast::StructExpr {
421                qself: None,
422                path,
423                fields,
424                rest: ast::StructRest::None,
425            })),
426        )
427    }
428    pub fn expr_struct_ident(
429        &self,
430        span: Span,
431        id: Ident,
432        fields: ThinVec<ast::ExprField>,
433    ) -> Box<ast::Expr> {
434        self.expr_struct(span, self.path_ident(span, id), fields)
435    }
436
437    pub fn expr_usize(&self, span: Span, n: usize) -> Box<ast::Expr> {
438        let suffix = Some(ast::UintTy::Usize.name());
439        let lit = token::Lit::new(token::Integer, sym::integer(n), suffix);
440        self.expr(span, ast::ExprKind::Lit(lit))
441    }
442
443    pub fn expr_u32(&self, span: Span, n: u32) -> Box<ast::Expr> {
444        let suffix = Some(ast::UintTy::U32.name());
445        let lit = token::Lit::new(token::Integer, sym::integer(n), suffix);
446        self.expr(span, ast::ExprKind::Lit(lit))
447    }
448
449    pub fn expr_bool(&self, span: Span, value: bool) -> Box<ast::Expr> {
450        let lit = token::Lit::new(token::Bool, if value { kw::True } else { kw::False }, None);
451        self.expr(span, ast::ExprKind::Lit(lit))
452    }
453
454    pub fn expr_str(&self, span: Span, s: Symbol) -> Box<ast::Expr> {
455        let lit = token::Lit::new(token::Str, literal::escape_string_symbol(s), None);
456        self.expr(span, ast::ExprKind::Lit(lit))
457    }
458
459    pub fn expr_byte_str(&self, span: Span, bytes: Vec<u8>) -> Box<ast::Expr> {
460        let lit = token::Lit::new(token::ByteStr, literal::escape_byte_str_symbol(&bytes), None);
461        self.expr(span, ast::ExprKind::Lit(lit))
462    }
463
464    /// `[expr1, expr2, ...]`
465    pub fn expr_array(&self, sp: Span, exprs: ThinVec<Box<ast::Expr>>) -> Box<ast::Expr> {
466        self.expr(sp, ast::ExprKind::Array(exprs))
467    }
468
469    /// `&[expr1, expr2, ...]`
470    pub fn expr_array_ref(&self, sp: Span, exprs: ThinVec<Box<ast::Expr>>) -> Box<ast::Expr> {
471        self.expr_addr_of(sp, self.expr_array(sp, exprs))
472    }
473
474    pub fn expr_some(&self, sp: Span, expr: Box<ast::Expr>) -> Box<ast::Expr> {
475        let some = self.std_path(&[sym::option, sym::Option, sym::Some]);
476        self.expr_call_global(sp, some, thin_vec![expr])
477    }
478
479    pub fn expr_none(&self, sp: Span) -> Box<ast::Expr> {
480        let none = self.std_path(&[sym::option, sym::Option, sym::None]);
481        self.expr_path(self.path_global(sp, none))
482    }
483    pub fn expr_tuple(&self, sp: Span, exprs: ThinVec<Box<ast::Expr>>) -> Box<ast::Expr> {
484        self.expr(sp, ast::ExprKind::Tup(exprs))
485    }
486
487    pub fn expr_unreachable(&self, span: Span) -> Box<ast::Expr> {
488        self.expr_macro_call(
489            span,
490            self.macro_call(
491                span,
492                self.path_global(
493                    span,
494                    [sym::std, sym::unreachable].map(|s| Ident::new(s, span)).to_vec(),
495                ),
496                Delimiter::Parenthesis,
497                TokenStream::default(),
498            ),
499        )
500    }
501
502    pub fn expr_ok(&self, sp: Span, expr: Box<ast::Expr>) -> Box<ast::Expr> {
503        let ok = self.std_path(&[sym::result, sym::Result, sym::Ok]);
504        self.expr_call_global(sp, ok, thin_vec![expr])
505    }
506
507    pub fn expr_try(&self, sp: Span, head: Box<ast::Expr>) -> Box<ast::Expr> {
508        let ok = self.std_path(&[sym::result, sym::Result, sym::Ok]);
509        let ok_path = self.path_global(sp, ok);
510        let err = self.std_path(&[sym::result, sym::Result, sym::Err]);
511        let err_path = self.path_global(sp, err);
512
513        let binding_variable = Ident::new(sym::__try_var, sp);
514        let binding_pat = self.pat_ident(sp, binding_variable);
515        let binding_expr = self.expr_ident(sp, binding_variable);
516
517        // `Ok(__try_var)` pattern
518        let ok_pat = self.pat_tuple_struct(sp, ok_path, thin_vec![binding_pat.clone()]);
519
520        // `Err(__try_var)` (pattern and expression respectively)
521        let err_pat = self.pat_tuple_struct(sp, err_path.clone(), thin_vec![binding_pat]);
522        let err_inner_expr =
523            self.expr_call(sp, self.expr_path(err_path), thin_vec![binding_expr.clone()]);
524        // `return Err(__try_var)`
525        let err_expr = self.expr(sp, ast::ExprKind::Ret(Some(err_inner_expr)));
526
527        // `Ok(__try_var) => __try_var`
528        let ok_arm = self.arm(sp, ok_pat, binding_expr);
529        // `Err(__try_var) => return Err(__try_var)`
530        let err_arm = self.arm(sp, err_pat, err_expr);
531
532        // `match head { Ok() => ..., Err() => ... }`
533        self.expr_match(sp, head, thin_vec![ok_arm, err_arm])
534    }
535
536    pub fn pat(&self, span: Span, kind: PatKind) -> ast::Pat {
537        ast::Pat { id: ast::DUMMY_NODE_ID, kind, span, tokens: None }
538    }
539    pub fn pat_wild(&self, span: Span) -> ast::Pat {
540        self.pat(span, PatKind::Wild)
541    }
542    pub fn pat_lit(&self, span: Span, expr: Box<ast::Expr>) -> ast::Pat {
543        self.pat(span, PatKind::Expr(expr))
544    }
545    pub fn pat_ident(&self, span: Span, ident: Ident) -> ast::Pat {
546        self.pat_ident_binding_mode(span, ident, ast::BindingMode::NONE)
547    }
548
549    pub fn pat_ident_binding_mode(
550        &self,
551        span: Span,
552        ident: Ident,
553        ann: ast::BindingMode,
554    ) -> ast::Pat {
555        let pat = PatKind::Ident(ann, ident.with_span_pos(span), None);
556        self.pat(span, pat)
557    }
558    pub fn pat_path(&self, span: Span, path: ast::Path) -> ast::Pat {
559        self.pat(span, PatKind::Path(None, path))
560    }
561    pub fn pat_tuple_struct(
562        &self,
563        span: Span,
564        path: ast::Path,
565        subpats: ThinVec<ast::Pat>,
566    ) -> ast::Pat {
567        self.pat(span, PatKind::TupleStruct(None, path, subpats))
568    }
569    pub fn pat_struct(
570        &self,
571        span: Span,
572        path: ast::Path,
573        field_pats: ThinVec<ast::PatField>,
574    ) -> ast::Pat {
575        self.pat(span, PatKind::Struct(None, path, field_pats, ast::PatFieldsRest::None))
576    }
577    pub fn pat_tuple(&self, span: Span, pats: ThinVec<ast::Pat>) -> ast::Pat {
578        self.pat(span, PatKind::Tuple(pats))
579    }
580
581    pub fn pat_some(&self, span: Span, pat: ast::Pat) -> ast::Pat {
582        let some = self.std_path(&[sym::option, sym::Option, sym::Some]);
583        let path = self.path_global(span, some);
584        self.pat_tuple_struct(span, path, thin_vec![pat])
585    }
586
587    pub fn arm(&self, span: Span, pat: ast::Pat, expr: Box<ast::Expr>) -> ast::Arm {
588        ast::Arm {
589            attrs: AttrVec::new(),
590            pat: Box::new(pat),
591            guard: None,
592            body: Some(expr),
593            span,
594            id: ast::DUMMY_NODE_ID,
595            is_placeholder: false,
596        }
597    }
598
599    pub fn arm_unreachable(&self, span: Span) -> ast::Arm {
600        self.arm(span, self.pat_wild(span), self.expr_unreachable(span))
601    }
602
603    pub fn expr_match(
604        &self,
605        span: Span,
606        arg: Box<ast::Expr>,
607        arms: ThinVec<ast::Arm>,
608    ) -> Box<Expr> {
609        self.expr(span, ast::ExprKind::Match(arg, arms, MatchKind::Prefix))
610    }
611
612    pub fn expr_if(
613        &self,
614        span: Span,
615        cond: Box<ast::Expr>,
616        then: Box<ast::Expr>,
617        els: Option<Box<ast::Expr>>,
618    ) -> Box<ast::Expr> {
619        let els = els.map(|x| self.expr_block(self.block_expr(x)));
620        self.expr(span, ast::ExprKind::If(cond, self.block_expr(then), els))
621    }
622
623    pub fn lambda(&self, span: Span, ids: Vec<Ident>, body: Box<ast::Expr>) -> Box<ast::Expr> {
624        let fn_decl = self.fn_decl(
625            ids.iter().map(|id| self.param(span, *id, self.ty(span, ast::TyKind::Infer))).collect(),
626            ast::FnRetTy::Default(span),
627        );
628
629        // FIXME -- We are using `span` as the span of the `|...|`
630        // part of the lambda, but it probably (maybe?) corresponds to
631        // the entire lambda body. Probably we should extend the API
632        // here, but that's not entirely clear.
633        self.expr(
634            span,
635            ast::ExprKind::Closure(Box::new(ast::Closure {
636                binder: ast::ClosureBinder::NotPresent,
637                capture_clause: ast::CaptureBy::Ref,
638                constness: ast::Const::No,
639                coroutine_kind: None,
640                movability: ast::Movability::Movable,
641                fn_decl,
642                body,
643                fn_decl_span: span,
644                // FIXME(SarthakSingh31): This points to the start of the declaration block and
645                // not the span of the argument block.
646                fn_arg_span: span,
647            })),
648        )
649    }
650
651    pub fn lambda0(&self, span: Span, body: Box<ast::Expr>) -> Box<ast::Expr> {
652        self.lambda(span, Vec::new(), body)
653    }
654
655    pub fn lambda1(&self, span: Span, body: Box<ast::Expr>, ident: Ident) -> Box<ast::Expr> {
656        self.lambda(span, vec![ident], body)
657    }
658
659    pub fn lambda_stmts_1(
660        &self,
661        span: Span,
662        stmts: ThinVec<ast::Stmt>,
663        ident: Ident,
664    ) -> Box<ast::Expr> {
665        self.lambda1(span, self.expr_block(self.block(span, stmts)), ident)
666    }
667
668    pub fn param(&self, span: Span, ident: Ident, ty: Box<ast::Ty>) -> ast::Param {
669        let pat = Box::new(self.pat_ident(span, ident));
670        ast::Param {
671            attrs: AttrVec::default(),
672            id: ast::DUMMY_NODE_ID,
673            pat,
674            span,
675            ty,
676            is_placeholder: false,
677        }
678    }
679
680    // `self` is unused but keep it as method for the convenience use.
681    pub fn fn_decl(&self, inputs: ThinVec<ast::Param>, output: ast::FnRetTy) -> Box<ast::FnDecl> {
682        Box::new(ast::FnDecl { inputs, output })
683    }
684
685    pub fn item(&self, span: Span, attrs: ast::AttrVec, kind: ast::ItemKind) -> Box<ast::Item> {
686        Box::new(ast::Item {
687            attrs,
688            id: ast::DUMMY_NODE_ID,
689            kind,
690            vis: ast::Visibility {
691                span: span.shrink_to_lo(),
692                kind: ast::VisibilityKind::Inherited,
693                tokens: None,
694            },
695            span,
696            tokens: None,
697        })
698    }
699
700    pub fn item_static(
701        &self,
702        span: Span,
703        ident: Ident,
704        ty: Box<ast::Ty>,
705        mutability: ast::Mutability,
706        expr: Box<ast::Expr>,
707    ) -> Box<ast::Item> {
708        self.item(
709            span,
710            AttrVec::new(),
711            ast::ItemKind::Static(
712                ast::StaticItem {
713                    ident,
714                    ty,
715                    safety: ast::Safety::Default,
716                    mutability,
717                    expr: Some(expr),
718                    define_opaque: None,
719                }
720                .into(),
721            ),
722        )
723    }
724
725    pub fn item_const(
726        &self,
727        span: Span,
728        ident: Ident,
729        ty: Box<ast::Ty>,
730        rhs: ast::ConstItemRhs,
731    ) -> Box<ast::Item> {
732        let defaultness = ast::Defaultness::Final;
733        self.item(
734            span,
735            AttrVec::new(),
736            ast::ItemKind::Const(
737                ast::ConstItem {
738                    defaultness,
739                    ident,
740                    // FIXME(generic_const_items): Pass the generics as a parameter.
741                    generics: ast::Generics::default(),
742                    ty,
743                    rhs: Some(rhs),
744                    define_opaque: None,
745                }
746                .into(),
747            ),
748        )
749    }
750
751    // Builds `#[name]`.
752    pub fn attr_word(&self, name: Symbol, span: Span) -> ast::Attribute {
753        let g = &self.sess.psess.attr_id_generator;
754        attr::mk_attr_word(g, ast::AttrStyle::Outer, ast::Safety::Default, name, span)
755    }
756
757    // Builds `#[name = val]`.
758    //
759    // Note: `span` is used for both the identifier and the value.
760    pub fn attr_name_value_str(&self, name: Symbol, val: Symbol, span: Span) -> ast::Attribute {
761        let g = &self.sess.psess.attr_id_generator;
762        attr::mk_attr_name_value_str(
763            g,
764            ast::AttrStyle::Outer,
765            ast::Safety::Default,
766            name,
767            val,
768            span,
769        )
770    }
771
772    // Builds `#[outer(inner)]`.
773    pub fn attr_nested_word(&self, outer: Symbol, inner: Symbol, span: Span) -> ast::Attribute {
774        let g = &self.sess.psess.attr_id_generator;
775        attr::mk_attr_nested_word(
776            g,
777            ast::AttrStyle::Outer,
778            ast::Safety::Default,
779            outer,
780            inner,
781            span,
782        )
783    }
784
785    // Builds an attribute fully manually.
786    pub fn attr_nested(&self, inner: AttrItem, span: Span) -> ast::Attribute {
787        let g = &self.sess.psess.attr_id_generator;
788        attr::mk_attr_from_item(g, inner, None, ast::AttrStyle::Outer, span)
789    }
790}