1 use crate::base::ExtCtxt;
5 use rustc_ast::{self as ast, AttrVec, BlockCheckMode, Expr, LocalKind, PatKind, UnOp};
6 use rustc_span::source_map::Spanned;
7 use rustc_span::symbol::{kw, sym, Ident, Symbol};
11 impl<'a> ExtCtxt<'a> {
12 pub fn path(&self, span: Span, strs: Vec<Ident>) -> ast::Path {
13 self.path_all(span, false, strs, vec![])
15 pub fn path_ident(&self, span: Span, id: Ident) -> ast::Path {
16 self.path(span, vec![id])
18 pub fn path_global(&self, span: Span, strs: Vec<Ident>) -> ast::Path {
19 self.path_all(span, true, strs, vec![])
25 mut idents: Vec<Ident>,
26 args: Vec<ast::GenericArg>,
28 assert!(!idents.is_empty());
29 let add_root = global && !idents[0].is_path_segment_keyword();
30 let mut segments = Vec::with_capacity(idents.len() + add_root as usize);
32 segments.push(ast::PathSegment::path_root(span));
34 let last_ident = idents.pop().unwrap();
36 idents.into_iter().map(|ident| ast::PathSegment::from_ident(ident.with_span_pos(span))),
38 let args = if !args.is_empty() {
39 let args = args.into_iter().map(ast::AngleBracketedArg::Arg).collect();
40 ast::AngleBracketedArgs { args, span }.into()
44 segments.push(ast::PathSegment {
45 ident: last_ident.with_span_pos(span),
46 id: ast::DUMMY_NODE_ID,
49 ast::Path { span, segments, tokens: None }
52 pub fn ty_mt(&self, ty: P<ast::Ty>, mutbl: ast::Mutability) -> ast::MutTy {
53 ast::MutTy { ty, mutbl }
56 pub fn ty(&self, span: Span, kind: ast::TyKind) -> P<ast::Ty> {
57 P(ast::Ty { id: ast::DUMMY_NODE_ID, span, kind, tokens: None })
60 pub fn ty_path(&self, path: ast::Path) -> P<ast::Ty> {
61 self.ty(path.span, ast::TyKind::Path(None, path))
64 // Might need to take bounds as an argument in the future, if you ever want
65 // to generate a bounded existential trait type.
66 pub fn ty_ident(&self, span: Span, ident: Ident) -> P<ast::Ty> {
67 self.ty_path(self.path_ident(span, ident))
70 pub fn anon_const(&self, span: Span, kind: ast::ExprKind) -> ast::AnonConst {
72 id: ast::DUMMY_NODE_ID,
74 id: ast::DUMMY_NODE_ID,
77 attrs: AttrVec::new(),
83 pub fn const_ident(&self, span: Span, ident: Ident) -> ast::AnonConst {
84 self.anon_const(span, ast::ExprKind::Path(None, self.path_ident(span, ident)))
91 lifetime: Option<ast::Lifetime>,
92 mutbl: ast::Mutability,
94 self.ty(span, ast::TyKind::Rptr(lifetime, self.ty_mt(ty, mutbl)))
97 pub fn ty_ptr(&self, span: Span, ty: P<ast::Ty>, mutbl: ast::Mutability) -> P<ast::Ty> {
98 self.ty(span, ast::TyKind::Ptr(self.ty_mt(ty, mutbl)))
105 attrs: Vec<ast::Attribute>,
106 bounds: ast::GenericBounds,
107 default: Option<P<ast::Ty>>,
108 ) -> ast::GenericParam {
110 ident: ident.with_span_pos(span),
111 id: ast::DUMMY_NODE_ID,
114 kind: ast::GenericParamKind::Type { default },
115 is_placeholder: false,
120 pub fn trait_ref(&self, path: ast::Path) -> ast::TraitRef {
121 ast::TraitRef { path, ref_id: ast::DUMMY_NODE_ID }
124 pub fn poly_trait_ref(&self, span: Span, path: ast::Path) -> ast::PolyTraitRef {
126 bound_generic_params: Vec::new(),
127 trait_ref: self.trait_ref(path),
132 pub fn trait_bound(&self, path: ast::Path) -> ast::GenericBound {
133 ast::GenericBound::Trait(
134 self.poly_trait_ref(path.span, path),
135 ast::TraitBoundModifier::None,
139 pub fn lifetime(&self, span: Span, ident: Ident) -> ast::Lifetime {
140 ast::Lifetime { id: ast::DUMMY_NODE_ID, ident: ident.with_span_pos(span) }
143 pub fn stmt_expr(&self, expr: P<ast::Expr>) -> ast::Stmt {
144 ast::Stmt { id: ast::DUMMY_NODE_ID, span: expr.span, kind: ast::StmtKind::Expr(expr) }
147 pub fn stmt_let(&self, sp: Span, mutbl: bool, ident: Ident, ex: P<ast::Expr>) -> ast::Stmt {
149 let binding_mode = ast::BindingMode::ByValue(ast::Mutability::Mut);
150 self.pat_ident_binding_mode(sp, ident, binding_mode)
152 self.pat_ident(sp, ident)
154 let local = P(ast::Local {
157 id: ast::DUMMY_NODE_ID,
158 kind: LocalKind::Init(ex),
160 attrs: AttrVec::new(),
163 self.stmt_local(local, sp)
166 // Generates `let _: Type;`, which is usually used for type assertions.
167 pub fn stmt_let_type_only(&self, span: Span, ty: P<ast::Ty>) -> ast::Stmt {
168 let local = P(ast::Local {
169 pat: self.pat_wild(span),
171 id: ast::DUMMY_NODE_ID,
172 kind: LocalKind::Decl,
174 attrs: AttrVec::new(),
177 self.stmt_local(local, span)
180 pub fn stmt_local(&self, local: P<ast::Local>, span: Span) -> ast::Stmt {
181 ast::Stmt { id: ast::DUMMY_NODE_ID, kind: ast::StmtKind::Local(local), span }
184 pub fn stmt_item(&self, sp: Span, item: P<ast::Item>) -> ast::Stmt {
185 ast::Stmt { id: ast::DUMMY_NODE_ID, kind: ast::StmtKind::Item(item), span: sp }
188 pub fn block_expr(&self, expr: P<ast::Expr>) -> P<ast::Block> {
192 id: ast::DUMMY_NODE_ID,
194 kind: ast::StmtKind::Expr(expr),
198 pub fn block(&self, span: Span, stmts: Vec<ast::Stmt>) -> P<ast::Block> {
201 id: ast::DUMMY_NODE_ID,
202 rules: BlockCheckMode::Default,
205 could_be_bare_literal: false,
209 pub fn expr(&self, span: Span, kind: ast::ExprKind) -> P<ast::Expr> {
210 P(ast::Expr { id: ast::DUMMY_NODE_ID, kind, span, attrs: AttrVec::new(), tokens: None })
213 pub fn expr_path(&self, path: ast::Path) -> P<ast::Expr> {
214 self.expr(path.span, ast::ExprKind::Path(None, path))
217 pub fn expr_ident(&self, span: Span, id: Ident) -> P<ast::Expr> {
218 self.expr_path(self.path_ident(span, id))
220 pub fn expr_self(&self, span: Span) -> P<ast::Expr> {
221 self.expr_ident(span, Ident::with_dummy_span(kw::SelfLower))
231 self.expr(sp, ast::ExprKind::Binary(Spanned { node: op, span: sp }, lhs, rhs))
234 pub fn expr_deref(&self, sp: Span, e: P<ast::Expr>) -> P<ast::Expr> {
235 self.expr(sp, ast::ExprKind::Unary(UnOp::Deref, e))
238 pub fn expr_addr_of(&self, sp: Span, e: P<ast::Expr>) -> P<ast::Expr> {
239 self.expr(sp, ast::ExprKind::AddrOf(ast::BorrowKind::Ref, ast::Mutability::Not, e))
246 args: Vec<P<ast::Expr>>,
248 self.expr(span, ast::ExprKind::Call(expr, args))
250 pub fn expr_call_ident(&self, span: Span, id: Ident, args: Vec<P<ast::Expr>>) -> P<ast::Expr> {
251 self.expr(span, ast::ExprKind::Call(self.expr_ident(span, id), args))
253 pub fn expr_call_global(
257 args: Vec<P<ast::Expr>>,
259 let pathexpr = self.expr_path(self.path_global(sp, fn_path));
260 self.expr_call(sp, pathexpr, args)
262 pub fn expr_block(&self, b: P<ast::Block>) -> P<ast::Expr> {
263 self.expr(b.span, ast::ExprKind::Block(b, None))
265 pub fn field_imm(&self, span: Span, ident: Ident, e: P<ast::Expr>) -> ast::ExprField {
267 ident: ident.with_span_pos(span),
271 attrs: AttrVec::new(),
272 id: ast::DUMMY_NODE_ID,
273 is_placeholder: false,
280 fields: Vec<ast::ExprField>,
284 ast::ExprKind::Struct(P(ast::StructExpr {
288 rest: ast::StructRest::None,
292 pub fn expr_struct_ident(
296 fields: Vec<ast::ExprField>,
298 self.expr_struct(span, self.path_ident(span, id), fields)
301 pub fn expr_lit(&self, span: Span, lit_kind: ast::LitKind) -> P<ast::Expr> {
302 let lit = ast::Lit::from_lit_kind(lit_kind, span);
303 self.expr(span, ast::ExprKind::Lit(lit))
305 pub fn expr_usize(&self, span: Span, i: usize) -> P<ast::Expr> {
308 ast::LitKind::Int(i as u128, ast::LitIntType::Unsigned(ast::UintTy::Usize)),
311 pub fn expr_u32(&self, sp: Span, u: u32) -> P<ast::Expr> {
312 self.expr_lit(sp, ast::LitKind::Int(u as u128, ast::LitIntType::Unsigned(ast::UintTy::U32)))
314 pub fn expr_bool(&self, sp: Span, value: bool) -> P<ast::Expr> {
315 self.expr_lit(sp, ast::LitKind::Bool(value))
318 pub fn expr_vec(&self, sp: Span, exprs: Vec<P<ast::Expr>>) -> P<ast::Expr> {
319 self.expr(sp, ast::ExprKind::Array(exprs))
321 pub fn expr_vec_slice(&self, sp: Span, exprs: Vec<P<ast::Expr>>) -> P<ast::Expr> {
322 self.expr_addr_of(sp, self.expr_vec(sp, exprs))
324 pub fn expr_str(&self, sp: Span, s: Symbol) -> P<ast::Expr> {
325 self.expr_lit(sp, ast::LitKind::Str(s, ast::StrStyle::Cooked))
328 pub fn expr_cast(&self, sp: Span, expr: P<ast::Expr>, ty: P<ast::Ty>) -> P<ast::Expr> {
329 self.expr(sp, ast::ExprKind::Cast(expr, ty))
332 pub fn expr_some(&self, sp: Span, expr: P<ast::Expr>) -> P<ast::Expr> {
333 let some = self.std_path(&[sym::option, sym::Option, sym::Some]);
334 self.expr_call_global(sp, some, vec![expr])
337 pub fn expr_none(&self, sp: Span) -> P<ast::Expr> {
338 let none = self.std_path(&[sym::option, sym::Option, sym::None]);
339 self.expr_path(self.path_global(sp, none))
341 pub fn expr_tuple(&self, sp: Span, exprs: Vec<P<ast::Expr>>) -> P<ast::Expr> {
342 self.expr(sp, ast::ExprKind::Tup(exprs))
345 pub fn expr_fail(&self, span: Span, msg: Symbol) -> P<ast::Expr> {
346 self.expr_call_global(
348 [sym::std, sym::rt, sym::begin_panic].iter().map(|s| Ident::new(*s, span)).collect(),
349 vec![self.expr_str(span, msg)],
353 pub fn expr_unreachable(&self, span: Span) -> P<ast::Expr> {
354 self.expr_fail(span, Symbol::intern("internal error: entered unreachable code"))
357 pub fn expr_ok(&self, sp: Span, expr: P<ast::Expr>) -> P<ast::Expr> {
358 let ok = self.std_path(&[sym::result, sym::Result, sym::Ok]);
359 self.expr_call_global(sp, ok, vec![expr])
362 pub fn expr_try(&self, sp: Span, head: P<ast::Expr>) -> P<ast::Expr> {
363 let ok = self.std_path(&[sym::result, sym::Result, sym::Ok]);
364 let ok_path = self.path_global(sp, ok);
365 let err = self.std_path(&[sym::result, sym::Result, sym::Err]);
366 let err_path = self.path_global(sp, err);
368 let binding_variable = Ident::new(sym::__try_var, sp);
369 let binding_pat = self.pat_ident(sp, binding_variable);
370 let binding_expr = self.expr_ident(sp, binding_variable);
372 // `Ok(__try_var)` pattern
373 let ok_pat = self.pat_tuple_struct(sp, ok_path, vec![binding_pat.clone()]);
375 // `Err(__try_var)` (pattern and expression respectively)
376 let err_pat = self.pat_tuple_struct(sp, err_path.clone(), vec![binding_pat]);
378 self.expr_call(sp, self.expr_path(err_path), vec![binding_expr.clone()]);
379 // `return Err(__try_var)`
380 let err_expr = self.expr(sp, ast::ExprKind::Ret(Some(err_inner_expr)));
382 // `Ok(__try_var) => __try_var`
383 let ok_arm = self.arm(sp, ok_pat, binding_expr);
384 // `Err(__try_var) => return Err(__try_var)`
385 let err_arm = self.arm(sp, err_pat, err_expr);
387 // `match head { Ok() => ..., Err() => ... }`
388 self.expr_match(sp, head, vec![ok_arm, err_arm])
391 pub fn pat(&self, span: Span, kind: PatKind) -> P<ast::Pat> {
392 P(ast::Pat { id: ast::DUMMY_NODE_ID, kind, span, tokens: None })
394 pub fn pat_wild(&self, span: Span) -> P<ast::Pat> {
395 self.pat(span, PatKind::Wild)
397 pub fn pat_lit(&self, span: Span, expr: P<ast::Expr>) -> P<ast::Pat> {
398 self.pat(span, PatKind::Lit(expr))
400 pub fn pat_ident(&self, span: Span, ident: Ident) -> P<ast::Pat> {
401 let binding_mode = ast::BindingMode::ByValue(ast::Mutability::Not);
402 self.pat_ident_binding_mode(span, ident, binding_mode)
405 pub fn pat_ident_binding_mode(
409 bm: ast::BindingMode,
411 let pat = PatKind::Ident(bm, ident.with_span_pos(span), None);
414 pub fn pat_path(&self, span: Span, path: ast::Path) -> P<ast::Pat> {
415 self.pat(span, PatKind::Path(None, path))
417 pub fn pat_tuple_struct(
421 subpats: Vec<P<ast::Pat>>,
423 self.pat(span, PatKind::TupleStruct(None, path, subpats))
429 field_pats: Vec<ast::PatField>,
431 self.pat(span, PatKind::Struct(None, path, field_pats, false))
433 pub fn pat_tuple(&self, span: Span, pats: Vec<P<ast::Pat>>) -> P<ast::Pat> {
434 self.pat(span, PatKind::Tuple(pats))
437 pub fn pat_some(&self, span: Span, pat: P<ast::Pat>) -> P<ast::Pat> {
438 let some = self.std_path(&[sym::option, sym::Option, sym::Some]);
439 let path = self.path_global(span, some);
440 self.pat_tuple_struct(span, path, vec![pat])
443 pub fn arm(&self, span: Span, pat: P<ast::Pat>, expr: P<ast::Expr>) -> ast::Arm {
445 attrs: AttrVec::new(),
450 id: ast::DUMMY_NODE_ID,
451 is_placeholder: false,
455 pub fn arm_unreachable(&self, span: Span) -> ast::Arm {
456 self.arm(span, self.pat_wild(span), self.expr_unreachable(span))
459 pub fn expr_match(&self, span: Span, arg: P<ast::Expr>, arms: Vec<ast::Arm>) -> P<Expr> {
460 self.expr(span, ast::ExprKind::Match(arg, arms))
468 els: Option<P<ast::Expr>>,
470 let els = els.map(|x| self.expr_block(self.block_expr(x)));
471 self.expr(span, ast::ExprKind::If(cond, self.block_expr(then), els))
474 pub fn lambda(&self, span: Span, ids: Vec<Ident>, body: P<ast::Expr>) -> P<ast::Expr> {
475 let fn_decl = self.fn_decl(
476 ids.iter().map(|id| self.param(span, *id, self.ty(span, ast::TyKind::Infer))).collect(),
477 ast::FnRetTy::Default(span),
480 // FIXME -- We are using `span` as the span of the `|...|`
481 // part of the lambda, but it probably (maybe?) corresponds to
482 // the entire lambda body. Probably we should extend the API
483 // here, but that's not entirely clear.
486 ast::ExprKind::Closure(
489 ast::Movability::Movable,
497 pub fn lambda0(&self, span: Span, body: P<ast::Expr>) -> P<ast::Expr> {
498 self.lambda(span, Vec::new(), body)
501 pub fn lambda1(&self, span: Span, body: P<ast::Expr>, ident: Ident) -> P<ast::Expr> {
502 self.lambda(span, vec![ident], body)
505 pub fn lambda_stmts_1(&self, span: Span, stmts: Vec<ast::Stmt>, ident: Ident) -> P<ast::Expr> {
506 self.lambda1(span, self.expr_block(self.block(span, stmts)), ident)
509 pub fn param(&self, span: Span, ident: Ident, ty: P<ast::Ty>) -> ast::Param {
510 let arg_pat = self.pat_ident(span, ident);
512 attrs: AttrVec::default(),
513 id: ast::DUMMY_NODE_ID,
517 is_placeholder: false,
521 // `self` is unused but keep it as method for the convenience use.
522 pub fn fn_decl(&self, inputs: Vec<ast::Param>, output: ast::FnRetTy) -> P<ast::FnDecl> {
523 P(ast::FnDecl { inputs, output })
530 attrs: Vec<ast::Attribute>,
533 // FIXME: Would be nice if our generated code didn't violate
534 // Rust coding conventions
538 id: ast::DUMMY_NODE_ID,
540 vis: ast::Visibility {
541 span: span.shrink_to_lo(),
542 kind: ast::VisibilityKind::Inherited,
555 mutbl: ast::Mutability,
558 self.item(span, name, Vec::new(), ast::ItemKind::Static(ty, mutbl, Some(expr)))
568 let def = ast::Defaultness::Final;
569 self.item(span, name, Vec::new(), ast::ItemKind::Const(def, ty, Some(expr)))
572 pub fn attribute(&self, mi: ast::MetaItem) -> ast::Attribute {
573 attr::mk_attr_outer(mi)
576 pub fn meta_word(&self, sp: Span, w: Symbol) -> ast::MetaItem {
577 attr::mk_word_item(Ident::new(w, sp))