Skip to main content

rustc_expand/
build.rs

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