1 use crate::base::ExtCtxt;
5 use rustc_ast::{self as ast, AttrVec, BlockCheckMode, Expr, LocalKind, PatKind, UnOp};
6 use rustc_data_structures::sync::Lrc;
7 use rustc_span::source_map::Spanned;
8 use rustc_span::symbol::{kw, sym, Ident, Symbol};
12 impl<'a> ExtCtxt<'a> {
13 pub fn path(&self, span: Span, strs: Vec<Ident>) -> ast::Path {
14 self.path_all(span, false, strs, vec![])
16 pub fn path_ident(&self, span: Span, id: Ident) -> ast::Path {
17 self.path(span, vec![id])
19 pub fn path_global(&self, span: Span, strs: Vec<Ident>) -> ast::Path {
20 self.path_all(span, true, strs, vec![])
26 mut idents: Vec<Ident>,
27 args: Vec<ast::GenericArg>,
29 assert!(!idents.is_empty());
30 let add_root = global && !idents[0].is_path_segment_keyword();
31 let mut segments = Vec::with_capacity(idents.len() + add_root as usize);
33 segments.push(ast::PathSegment::path_root(span));
35 let last_ident = idents.pop().unwrap();
37 idents.into_iter().map(|ident| ast::PathSegment::from_ident(ident.with_span_pos(span))),
39 let args = if !args.is_empty() {
40 let args = args.into_iter().map(ast::AngleBracketedArg::Arg).collect();
41 ast::AngleBracketedArgs { args, span }.into()
45 segments.push(ast::PathSegment {
46 ident: last_ident.with_span_pos(span),
47 id: ast::DUMMY_NODE_ID,
50 ast::Path { span, segments, tokens: None }
53 pub fn ty_mt(&self, ty: P<ast::Ty>, mutbl: ast::Mutability) -> ast::MutTy {
54 ast::MutTy { ty, mutbl }
57 pub fn ty(&self, span: Span, kind: ast::TyKind) -> P<ast::Ty> {
58 P(ast::Ty { id: ast::DUMMY_NODE_ID, span, kind, tokens: None })
61 pub fn ty_infer(&self, span: Span) -> P<ast::Ty> {
62 self.ty(span, ast::TyKind::Infer)
65 pub fn ty_path(&self, path: ast::Path) -> P<ast::Ty> {
66 self.ty(path.span, ast::TyKind::Path(None, path))
69 // Might need to take bounds as an argument in the future, if you ever want
70 // to generate a bounded existential trait type.
71 pub fn ty_ident(&self, span: Span, ident: Ident) -> P<ast::Ty> {
72 self.ty_path(self.path_ident(span, ident))
75 pub fn anon_const(&self, span: Span, kind: ast::ExprKind) -> ast::AnonConst {
77 id: ast::DUMMY_NODE_ID,
79 id: ast::DUMMY_NODE_ID,
82 attrs: AttrVec::new(),
88 pub fn const_ident(&self, span: Span, ident: Ident) -> ast::AnonConst {
89 self.anon_const(span, ast::ExprKind::Path(None, self.path_ident(span, ident)))
96 lifetime: Option<ast::Lifetime>,
97 mutbl: ast::Mutability,
99 self.ty(span, ast::TyKind::Rptr(lifetime, self.ty_mt(ty, mutbl)))
102 pub fn ty_ptr(&self, span: Span, ty: P<ast::Ty>, mutbl: ast::Mutability) -> P<ast::Ty> {
103 self.ty(span, ast::TyKind::Ptr(self.ty_mt(ty, mutbl)))
110 bounds: ast::GenericBounds,
111 default: Option<P<ast::Ty>>,
112 ) -> ast::GenericParam {
114 ident: ident.with_span_pos(span),
115 id: ast::DUMMY_NODE_ID,
116 attrs: AttrVec::new(),
118 kind: ast::GenericParamKind::Type { default },
119 is_placeholder: false,
124 pub fn trait_ref(&self, path: ast::Path) -> ast::TraitRef {
125 ast::TraitRef { path, ref_id: ast::DUMMY_NODE_ID }
128 pub fn poly_trait_ref(&self, span: Span, path: ast::Path) -> ast::PolyTraitRef {
130 bound_generic_params: Vec::new(),
131 trait_ref: self.trait_ref(path),
136 pub fn trait_bound(&self, path: ast::Path) -> ast::GenericBound {
137 ast::GenericBound::Trait(
138 self.poly_trait_ref(path.span, path),
139 ast::TraitBoundModifier::None,
143 pub fn lifetime(&self, span: Span, ident: Ident) -> ast::Lifetime {
144 ast::Lifetime { id: ast::DUMMY_NODE_ID, ident: ident.with_span_pos(span) }
147 pub fn lifetime_static(&self, span: Span) -> ast::Lifetime {
148 self.lifetime(span, Ident::new(kw::StaticLifetime, span))
151 pub fn stmt_expr(&self, expr: P<ast::Expr>) -> ast::Stmt {
152 ast::Stmt { id: ast::DUMMY_NODE_ID, span: expr.span, kind: ast::StmtKind::Expr(expr) }
155 pub fn stmt_let_pat(&self, sp: Span, pat: P<ast::Pat>, ex: P<ast::Expr>) -> ast::Stmt {
156 let local = P(ast::Local {
159 id: ast::DUMMY_NODE_ID,
160 kind: LocalKind::Init(ex),
162 attrs: AttrVec::new(),
165 self.stmt_local(local, sp)
168 pub fn stmt_let(&self, sp: Span, mutbl: bool, ident: Ident, ex: P<ast::Expr>) -> ast::Stmt {
169 self.stmt_let_ty(sp, mutbl, ident, None, ex)
177 ty: Option<P<ast::Ty>>,
181 self.pat_ident_binding_mode(sp, ident, ast::BindingAnnotation::MUT)
183 self.pat_ident(sp, ident)
185 let local = P(ast::Local {
188 id: ast::DUMMY_NODE_ID,
189 kind: LocalKind::Init(ex),
191 attrs: AttrVec::new(),
194 self.stmt_local(local, sp)
197 // Generates `let _: Type;`, which is usually used for type assertions.
198 pub fn stmt_let_type_only(&self, span: Span, ty: P<ast::Ty>) -> ast::Stmt {
199 let local = P(ast::Local {
200 pat: self.pat_wild(span),
202 id: ast::DUMMY_NODE_ID,
203 kind: LocalKind::Decl,
205 attrs: AttrVec::new(),
208 self.stmt_local(local, span)
211 pub fn stmt_local(&self, local: P<ast::Local>, span: Span) -> ast::Stmt {
212 ast::Stmt { id: ast::DUMMY_NODE_ID, kind: ast::StmtKind::Local(local), span }
215 pub fn stmt_item(&self, sp: Span, item: P<ast::Item>) -> ast::Stmt {
216 ast::Stmt { id: ast::DUMMY_NODE_ID, kind: ast::StmtKind::Item(item), span: sp }
219 pub fn block_expr(&self, expr: P<ast::Expr>) -> P<ast::Block> {
223 id: ast::DUMMY_NODE_ID,
225 kind: ast::StmtKind::Expr(expr),
229 pub fn block(&self, span: Span, stmts: Vec<ast::Stmt>) -> P<ast::Block> {
232 id: ast::DUMMY_NODE_ID,
233 rules: BlockCheckMode::Default,
236 could_be_bare_literal: false,
240 pub fn expr(&self, span: Span, kind: ast::ExprKind) -> P<ast::Expr> {
241 P(ast::Expr { id: ast::DUMMY_NODE_ID, kind, span, attrs: AttrVec::new(), tokens: None })
244 pub fn expr_path(&self, path: ast::Path) -> P<ast::Expr> {
245 self.expr(path.span, ast::ExprKind::Path(None, path))
248 pub fn expr_ident(&self, span: Span, id: Ident) -> P<ast::Expr> {
249 self.expr_path(self.path_ident(span, id))
251 pub fn expr_self(&self, span: Span) -> P<ast::Expr> {
252 self.expr_ident(span, Ident::with_dummy_span(kw::SelfLower))
262 self.expr(sp, ast::ExprKind::Binary(Spanned { node: op, span: sp }, lhs, rhs))
265 pub fn expr_deref(&self, sp: Span, e: P<ast::Expr>) -> P<ast::Expr> {
266 self.expr(sp, ast::ExprKind::Unary(UnOp::Deref, e))
269 pub fn expr_addr_of(&self, sp: Span, e: P<ast::Expr>) -> P<ast::Expr> {
270 self.expr(sp, ast::ExprKind::AddrOf(ast::BorrowKind::Ref, ast::Mutability::Not, e))
277 args: Vec<P<ast::Expr>>,
279 self.expr(span, ast::ExprKind::Call(expr, args))
281 pub fn expr_call_ident(&self, span: Span, id: Ident, args: Vec<P<ast::Expr>>) -> P<ast::Expr> {
282 self.expr(span, ast::ExprKind::Call(self.expr_ident(span, id), args))
284 pub fn expr_call_global(
288 args: Vec<P<ast::Expr>>,
290 let pathexpr = self.expr_path(self.path_global(sp, fn_path));
291 self.expr_call(sp, pathexpr, args)
293 pub fn expr_block(&self, b: P<ast::Block>) -> P<ast::Expr> {
294 self.expr(b.span, ast::ExprKind::Block(b, None))
296 pub fn field_imm(&self, span: Span, ident: Ident, e: P<ast::Expr>) -> ast::ExprField {
298 ident: ident.with_span_pos(span),
302 attrs: AttrVec::new(),
303 id: ast::DUMMY_NODE_ID,
304 is_placeholder: false,
311 fields: Vec<ast::ExprField>,
315 ast::ExprKind::Struct(P(ast::StructExpr {
319 rest: ast::StructRest::None,
323 pub fn expr_struct_ident(
327 fields: Vec<ast::ExprField>,
329 self.expr_struct(span, self.path_ident(span, id), fields)
332 fn expr_lit(&self, span: Span, lit_kind: ast::LitKind) -> P<ast::Expr> {
333 let lit = ast::Lit::from_lit_kind(lit_kind, span);
334 self.expr(span, ast::ExprKind::Lit(lit))
337 pub fn expr_usize(&self, span: Span, i: usize) -> P<ast::Expr> {
340 ast::LitKind::Int(i as u128, ast::LitIntType::Unsigned(ast::UintTy::Usize)),
344 pub fn expr_u32(&self, sp: Span, u: u32) -> P<ast::Expr> {
345 self.expr_lit(sp, ast::LitKind::Int(u as u128, ast::LitIntType::Unsigned(ast::UintTy::U32)))
348 pub fn expr_bool(&self, sp: Span, value: bool) -> P<ast::Expr> {
349 self.expr_lit(sp, ast::LitKind::Bool(value))
352 pub fn expr_str(&self, sp: Span, s: Symbol) -> P<ast::Expr> {
353 self.expr_lit(sp, ast::LitKind::Str(s, ast::StrStyle::Cooked))
356 pub fn expr_char(&self, sp: Span, ch: char) -> P<ast::Expr> {
357 self.expr_lit(sp, ast::LitKind::Char(ch))
360 pub fn expr_byte_str(&self, sp: Span, bytes: Vec<u8>) -> P<ast::Expr> {
361 self.expr_lit(sp, ast::LitKind::ByteStr(Lrc::from(bytes)))
364 /// `[expr1, expr2, ...]`
365 pub fn expr_array(&self, sp: Span, exprs: Vec<P<ast::Expr>>) -> P<ast::Expr> {
366 self.expr(sp, ast::ExprKind::Array(exprs))
369 /// `&[expr1, expr2, ...]`
370 pub fn expr_array_ref(&self, sp: Span, exprs: Vec<P<ast::Expr>>) -> P<ast::Expr> {
371 self.expr_addr_of(sp, self.expr_array(sp, exprs))
374 pub fn expr_cast(&self, sp: Span, expr: P<ast::Expr>, ty: P<ast::Ty>) -> P<ast::Expr> {
375 self.expr(sp, ast::ExprKind::Cast(expr, ty))
378 pub fn expr_some(&self, sp: Span, expr: P<ast::Expr>) -> P<ast::Expr> {
379 let some = self.std_path(&[sym::option, sym::Option, sym::Some]);
380 self.expr_call_global(sp, some, vec![expr])
383 pub fn expr_none(&self, sp: Span) -> P<ast::Expr> {
384 let none = self.std_path(&[sym::option, sym::Option, sym::None]);
385 self.expr_path(self.path_global(sp, none))
387 pub fn expr_tuple(&self, sp: Span, exprs: Vec<P<ast::Expr>>) -> P<ast::Expr> {
388 self.expr(sp, ast::ExprKind::Tup(exprs))
391 pub fn expr_fail(&self, span: Span, msg: Symbol) -> P<ast::Expr> {
392 self.expr_call_global(
394 [sym::std, sym::rt, sym::begin_panic].iter().map(|s| Ident::new(*s, span)).collect(),
395 vec![self.expr_str(span, msg)],
399 pub fn expr_unreachable(&self, span: Span) -> P<ast::Expr> {
400 self.expr_fail(span, Symbol::intern("internal error: entered unreachable code"))
403 pub fn expr_ok(&self, sp: Span, expr: P<ast::Expr>) -> P<ast::Expr> {
404 let ok = self.std_path(&[sym::result, sym::Result, sym::Ok]);
405 self.expr_call_global(sp, ok, vec![expr])
408 pub fn expr_try(&self, sp: Span, head: P<ast::Expr>) -> P<ast::Expr> {
409 let ok = self.std_path(&[sym::result, sym::Result, sym::Ok]);
410 let ok_path = self.path_global(sp, ok);
411 let err = self.std_path(&[sym::result, sym::Result, sym::Err]);
412 let err_path = self.path_global(sp, err);
414 let binding_variable = Ident::new(sym::__try_var, sp);
415 let binding_pat = self.pat_ident(sp, binding_variable);
416 let binding_expr = self.expr_ident(sp, binding_variable);
418 // `Ok(__try_var)` pattern
419 let ok_pat = self.pat_tuple_struct(sp, ok_path, vec![binding_pat.clone()]);
421 // `Err(__try_var)` (pattern and expression respectively)
422 let err_pat = self.pat_tuple_struct(sp, err_path.clone(), vec![binding_pat]);
424 self.expr_call(sp, self.expr_path(err_path), vec![binding_expr.clone()]);
425 // `return Err(__try_var)`
426 let err_expr = self.expr(sp, ast::ExprKind::Ret(Some(err_inner_expr)));
428 // `Ok(__try_var) => __try_var`
429 let ok_arm = self.arm(sp, ok_pat, binding_expr);
430 // `Err(__try_var) => return Err(__try_var)`
431 let err_arm = self.arm(sp, err_pat, err_expr);
433 // `match head { Ok() => ..., Err() => ... }`
434 self.expr_match(sp, head, vec![ok_arm, err_arm])
437 pub fn pat(&self, span: Span, kind: PatKind) -> P<ast::Pat> {
438 P(ast::Pat { id: ast::DUMMY_NODE_ID, kind, span, tokens: None })
440 pub fn pat_wild(&self, span: Span) -> P<ast::Pat> {
441 self.pat(span, PatKind::Wild)
443 pub fn pat_lit(&self, span: Span, expr: P<ast::Expr>) -> P<ast::Pat> {
444 self.pat(span, PatKind::Lit(expr))
446 pub fn pat_ident(&self, span: Span, ident: Ident) -> P<ast::Pat> {
447 self.pat_ident_binding_mode(span, ident, ast::BindingAnnotation::NONE)
450 pub fn pat_ident_binding_mode(
454 ann: ast::BindingAnnotation,
456 let pat = PatKind::Ident(ann, ident.with_span_pos(span), None);
459 pub fn pat_path(&self, span: Span, path: ast::Path) -> P<ast::Pat> {
460 self.pat(span, PatKind::Path(None, path))
462 pub fn pat_tuple_struct(
466 subpats: Vec<P<ast::Pat>>,
468 self.pat(span, PatKind::TupleStruct(None, path, subpats))
474 field_pats: Vec<ast::PatField>,
476 self.pat(span, PatKind::Struct(None, path, field_pats, false))
478 pub fn pat_tuple(&self, span: Span, pats: Vec<P<ast::Pat>>) -> P<ast::Pat> {
479 self.pat(span, PatKind::Tuple(pats))
482 pub fn pat_some(&self, span: Span, pat: P<ast::Pat>) -> P<ast::Pat> {
483 let some = self.std_path(&[sym::option, sym::Option, sym::Some]);
484 let path = self.path_global(span, some);
485 self.pat_tuple_struct(span, path, vec![pat])
488 pub fn arm(&self, span: Span, pat: P<ast::Pat>, expr: P<ast::Expr>) -> ast::Arm {
490 attrs: AttrVec::new(),
495 id: ast::DUMMY_NODE_ID,
496 is_placeholder: false,
500 pub fn arm_unreachable(&self, span: Span) -> ast::Arm {
501 self.arm(span, self.pat_wild(span), self.expr_unreachable(span))
504 pub fn expr_match(&self, span: Span, arg: P<ast::Expr>, arms: Vec<ast::Arm>) -> P<Expr> {
505 self.expr(span, ast::ExprKind::Match(arg, arms))
513 els: Option<P<ast::Expr>>,
515 let els = els.map(|x| self.expr_block(self.block_expr(x)));
516 self.expr(span, ast::ExprKind::If(cond, self.block_expr(then), els))
519 pub fn lambda(&self, span: Span, ids: Vec<Ident>, body: P<ast::Expr>) -> P<ast::Expr> {
520 let fn_decl = self.fn_decl(
521 ids.iter().map(|id| self.param(span, *id, self.ty(span, ast::TyKind::Infer))).collect(),
522 ast::FnRetTy::Default(span),
525 // FIXME -- We are using `span` as the span of the `|...|`
526 // part of the lambda, but it probably (maybe?) corresponds to
527 // the entire lambda body. Probably we should extend the API
528 // here, but that's not entirely clear.
531 ast::ExprKind::Closure(
532 ast::ClosureBinder::NotPresent,
535 ast::Movability::Movable,
543 pub fn lambda0(&self, span: Span, body: P<ast::Expr>) -> P<ast::Expr> {
544 self.lambda(span, Vec::new(), body)
547 pub fn lambda1(&self, span: Span, body: P<ast::Expr>, ident: Ident) -> P<ast::Expr> {
548 self.lambda(span, vec![ident], body)
551 pub fn lambda_stmts_1(&self, span: Span, stmts: Vec<ast::Stmt>, ident: Ident) -> P<ast::Expr> {
552 self.lambda1(span, self.expr_block(self.block(span, stmts)), ident)
555 pub fn param(&self, span: Span, ident: Ident, ty: P<ast::Ty>) -> ast::Param {
556 let arg_pat = self.pat_ident(span, ident);
558 attrs: AttrVec::default(),
559 id: ast::DUMMY_NODE_ID,
563 is_placeholder: false,
567 // `self` is unused but keep it as method for the convenience use.
568 pub fn fn_decl(&self, inputs: Vec<ast::Param>, output: ast::FnRetTy) -> P<ast::FnDecl> {
569 P(ast::FnDecl { inputs, output })
579 // FIXME: Would be nice if our generated code didn't violate
580 // Rust coding conventions
584 id: ast::DUMMY_NODE_ID,
586 vis: ast::Visibility {
587 span: span.shrink_to_lo(),
588 kind: ast::VisibilityKind::Inherited,
601 mutbl: ast::Mutability,
604 self.item(span, name, AttrVec::new(), ast::ItemKind::Static(ty, mutbl, Some(expr)))
614 let def = ast::Defaultness::Final;
615 self.item(span, name, AttrVec::new(), ast::ItemKind::Const(def, ty, Some(expr)))
618 pub fn attribute(&self, mi: ast::MetaItem) -> ast::Attribute {
619 attr::mk_attr_outer(&self.sess.parse_sess.attr_id_generator, mi)
622 pub fn meta_word(&self, sp: Span, w: Symbol) -> ast::MetaItem {
623 attr::mk_word_item(Ident::new(w, sp))