rustc_expand/
build.rs

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