diff --git a/compiler/rustc_builtin_macros/src/asm.rs b/compiler/rustc_builtin_macros/src/asm.rs index 975b2c49b292d..845dc8ab544fc 100644 --- a/compiler/rustc_builtin_macros/src/asm.rs +++ b/compiler/rustc_builtin_macros/src/asm.rs @@ -588,13 +588,7 @@ pub(super) fn expand_asm<'cx>( return ExpandResult::Retry(()); }; let expr = match mac { - Ok(inline_asm) => Box::new(ast::Expr { - id: ast::DUMMY_NODE_ID, - kind: ast::ExprKind::InlineAsm(Box::new(inline_asm)), - span: sp, - attrs: ast::AttrVec::new(), - tokens: None, - }), + Ok(inline_asm) => ecx.expr(sp, ast::ExprKind::InlineAsm(Box::new(inline_asm))), Err(guar) => DummyResult::raw_expr(sp, Some(guar)), }; MacEager::expr(expr) @@ -618,13 +612,7 @@ pub(super) fn expand_naked_asm<'cx>( return ExpandResult::Retry(()); }; let expr = match mac { - Ok(inline_asm) => Box::new(ast::Expr { - id: ast::DUMMY_NODE_ID, - kind: ast::ExprKind::InlineAsm(Box::new(inline_asm)), - span: sp, - attrs: ast::AttrVec::new(), - tokens: None, - }), + Ok(inline_asm) => ecx.expr(sp, ast::ExprKind::InlineAsm(Box::new(inline_asm))), Err(guar) => DummyResult::raw_expr(sp, Some(guar)), }; MacEager::expr(expr) @@ -648,17 +636,11 @@ pub(super) fn expand_global_asm<'cx>( return ExpandResult::Retry(()); }; match mac { - Ok(inline_asm) => MacEager::items(smallvec![Box::new(ast::Item { - attrs: ast::AttrVec::new(), - id: ast::DUMMY_NODE_ID, - kind: ast::ItemKind::GlobalAsm(Box::new(inline_asm)), - vis: ast::Visibility { - span: sp.shrink_to_lo(), - kind: ast::VisibilityKind::Inherited, - }, - span: sp, - tokens: None, - })]), + Ok(inline_asm) => MacEager::items(smallvec![ecx.item( + sp, + ast::AttrVec::new(), + ast::ItemKind::GlobalAsm(Box::new(inline_asm)) + )]), Err(guar) => DummyResult::any(sp, guar), } } diff --git a/compiler/rustc_builtin_macros/src/assert.rs b/compiler/rustc_builtin_macros/src/assert.rs index 5f71e02d1350b..f5a582ddffcc5 100644 --- a/compiler/rustc_builtin_macros/src/assert.rs +++ b/compiler/rustc_builtin_macros/src/assert.rs @@ -1,8 +1,8 @@ mod context; use rustc_ast::token::Delimiter; -use rustc_ast::tokenstream::{DelimSpan, TokenStream}; -use rustc_ast::{DelimArgs, Expr, ExprKind, MacCall, Path, PathSegment, UnOp, token}; +use rustc_ast::tokenstream::TokenStream; +use rustc_ast::{Expr, ExprKind, Path, UnOp, token}; use rustc_ast_pretty::pprust; use rustc_errors::PResult; use rustc_expand::base::{DummyResult, ExpandResult, ExtCtxt, MacEager, MacroExpanderResult}; @@ -34,14 +34,7 @@ pub(crate) fn expand_assert<'cx>( let panic_path = || { if use_panic_2021(span) { // On edition 2021, we always call `$crate::panic::panic_2021!()`. - Path { - span: call_site_span, - segments: cx - .std_path(&[sym::panic, sym::panic_2021]) - .into_iter() - .map(PathSegment::from_ident) - .collect(), - } + cx.path(call_site_span, cx.std_path(&[sym::panic, sym::panic_2021])) } else { // Before edition 2021, we call `panic!()` unqualified, // such that it calls either `std::panic!()` or `core::panic!()`. @@ -51,16 +44,9 @@ pub(crate) fn expand_assert<'cx>( // Simply uses the user provided message instead of generating custom outputs let expr = if let Some(tokens) = custom_message { - let then = cx.expr( + let then = cx.expr_macro_call( call_site_span, - ExprKind::MacCall(Box::new(MacCall { - path: panic_path(), - args: Box::new(DelimArgs { - dspan: DelimSpan::from_single(call_site_span), - delim: Delimiter::Parenthesis, - tokens, - }), - })), + cx.macro_call(call_site_span, panic_path(), Delimiter::Parenthesis, tokens), ); expr_if_not(cx, call_site_span, cond_expr, then, None) } diff --git a/compiler/rustc_builtin_macros/src/assert/context.rs b/compiler/rustc_builtin_macros/src/assert/context.rs index cb3ea2475721e..11c97da0db5ad 100644 --- a/compiler/rustc_builtin_macros/src/assert/context.rs +++ b/compiler/rustc_builtin_macros/src/assert/context.rs @@ -1,8 +1,8 @@ use rustc_ast::token::{self, Delimiter, IdentKind}; use rustc_ast::tokenstream::{DelimSpan, TokenStream, TokenTree}; use rustc_ast::{ - BinOpKind, BorrowKind, DUMMY_NODE_ID, DelimArgs, Expr, ExprKind, ItemKind, MacCall, MethodCall, - Mutability, Path, PathSegment, Stmt, StructRest, UnOp, UseTree, UseTreeAndId, UseTreeKind, + BinOpKind, BorrowKind, DUMMY_NODE_ID, DelimArgs, Expr, ExprKind, ItemKind, MacCall, Mutability, + Path, Stmt, StructRest, UnOp, UseTree, UseTreeAndId, UseTreeKind, }; use rustc_ast_pretty::pprust; use rustc_data_structures::fx::FxHashSet; @@ -382,20 +382,15 @@ impl<'cx, 'a> Context<'cx, 'a> { ); let try_capture_call = self .cx - .stmt_expr(expr_method_call( - self.cx, - PathSegment { - args: None, - id: DUMMY_NODE_ID, - ident: Ident::new(sym::try_capture, self.span), - }, - expr_paren(self.cx, self.span, self.cx.expr_addr_of(self.span, wrapper)), + .stmt_expr(self.cx.expr_method_call( + self.span, + self.cx.expr_paren(self.span, self.cx.expr_addr_of(self.span, wrapper)), + Ident::new(sym::try_capture, self.span), thin_vec![expr_addr_of_mut( self.cx, self.span, self.cx.expr_path(Path::from_ident(capture)), )], - self.span, )) .add_trailing_semicolon(); let local_bind_path = self.cx.expr_path(Path::from_ident(local_bind)); @@ -448,17 +443,3 @@ fn escape_to_fmt(s: &str) -> String { fn expr_addr_of_mut(cx: &ExtCtxt<'_>, sp: Span, e: Box) -> Box { cx.expr(sp, ExprKind::AddrOf(BorrowKind::Ref, Mutability::Mut, e)) } - -fn expr_method_call( - cx: &ExtCtxt<'_>, - seg: PathSegment, - receiver: Box, - args: ThinVec>, - span: Span, -) -> Box { - cx.expr(span, ExprKind::MethodCall(Box::new(MethodCall { seg, receiver, args, span }))) -} - -fn expr_paren(cx: &ExtCtxt<'_>, sp: Span, e: Box) -> Box { - cx.expr(sp, ExprKind::Paren(e)) -} diff --git a/compiler/rustc_builtin_macros/src/autodiff.rs b/compiler/rustc_builtin_macros/src/autodiff.rs index 0c81b9080c6cf..083d05d03a070 100644 --- a/compiler/rustc_builtin_macros/src/autodiff.rs +++ b/compiler/rustc_builtin_macros/src/autodiff.rs @@ -14,9 +14,8 @@ mod llvm_enzyme { use rustc_ast::tokenstream::*; use rustc_ast::visit::AssocCtxt::*; use rustc_ast::{ - self as ast, AngleBracketedArg, AngleBracketedArgs, AnonConst, AssocItemKind, BindingMode, - FnRetTy, FnSig, GenericArg, GenericArgs, GenericParamKind, Generics, ItemKind, - MetaItemInner, PatKind, Path, PathSegment, TyKind, Visibility, + self as ast, AnonConst, FnRetTy, FnSig, GenericArg, GenericParamKind, Generics, ItemKind, + MetaItemInner, PatKind, TyKind, Visibility, }; use rustc_attr_ir::RustcAutodiff; use rustc_expand::base::{Annotatable, ExtCtxt}; @@ -154,7 +153,7 @@ mod llvm_enzyme { } fn meta_item_inner_to_ts(t: &MetaItemInner, ts: &mut Vec) { - let comma: Token = Token::new(TokenKind::Comma, Span::default()); + let comma = Token::new(TokenKind::Comma, Span::default()); let val = first_ident(t); let t = Token::from_ast_ident(val); ts.push(TokenTree::Token(t, Spacing::Joint)); @@ -275,7 +274,7 @@ mod llvm_enzyme { // Now, if the user gave a width (vector aka batch-mode ad), then we copy it. // If it is not given, we default to 1 (scalar mode). let start_position; - let kind: LitKind = LitKind::Integer; + let kind = LitKind::Integer; let symbol; if meta_item_vec.len() >= 2 && let Some(width) = width(&meta_item_vec[1]) @@ -287,7 +286,7 @@ mod llvm_enzyme { symbol = sym::integer(1); } - let l: Lit = Lit { kind, symbol, suffix: None }; + let l = Lit { kind, symbol, suffix: None }; let t = Token::new(TokenKind::Literal(l), Span::default()); let comma = Token::new(TokenKind::Comma, Span::default()); ts.push(TokenTree::Token(t, Spacing::Joint)); @@ -306,9 +305,9 @@ mod llvm_enzyme { } // We remove the last, trailing comma. ts.pop(); - let ts: TokenStream = TokenStream::from_iter(ts); + let ts = TokenStream::from_iter(ts); - let x: RustcAutodiff = from_ast(ecx, &meta_item_vec, has_ret, mode); + let x = from_ast(ecx, &meta_item_vec, has_ret, mode); if !x.is_active() { // We encountered an error, so we return the original item. // This allows us to potentially parse other attributes. @@ -346,7 +345,7 @@ mod llvm_enzyme { let mut rustc_ad_attr = Box::new(ast::NormalAttr::from_ident(Ident::with_dummy_span(sym::rustc_autodiff))); - let ts2: Vec = vec![TokenTree::Token( + let ts2 = vec![TokenTree::Token( Token::new(TokenKind::Ident(sym::never, IdentKind::Normal), span), Spacing::Joint, )]; @@ -382,7 +381,7 @@ mod llvm_enzyme { let mut has_inline_never = false; // Don't add it multiple times: - let orig_annotatable: Annotatable = match item { + let orig_annotatable = match item { Annotatable::Item(ref mut iitem) => { if !iitem.attrs.iter().any(|a| same_attribute(&a.kind, &attr.kind)) { iitem.attrs.push(attr); @@ -439,7 +438,7 @@ mod llvm_enzyme { let d_annotatable = match &item { Annotatable::AssocItem(_, ctxt) => { - let assoc_item: AssocItemKind = ast::AssocItemKind::Fn(d_fn); + let assoc_item = ast::AssocItemKind::Fn(d_fn); let d_fn = Box::new(ast::AssocItem { attrs: d_attrs, id: ast::DUMMY_NODE_ID, @@ -459,12 +458,7 @@ mod llvm_enzyme { Annotatable::Stmt(_) => { let mut d_fn = ecx.item(span, d_attrs, ItemKind::Fn(d_fn)); d_fn.vis = vis; - - Annotatable::Stmt(Box::new(ast::Stmt { - id: ast::DUMMY_NODE_ID, - kind: ast::StmtKind::Item(d_fn), - span, - })) + Annotatable::Stmt(Box::new(ecx.stmt_item(span, d_fn))) } _ => { unreachable!("item kind checked previously") @@ -568,7 +562,7 @@ mod llvm_enzyme { let call_expr = ecx.expr_call( span, ecx.expr_path(enzyme_path), - vec![primal_fn_ptr, diff_path_expr, tuple_expr].into(), + thin_vec![primal_fn_ptr, diff_path_expr, tuple_expr], ); ecx.stmt_expr(call_expr) @@ -591,35 +585,20 @@ mod llvm_enzyme { GenericParamKind::Type { .. } => { let path = ast::Path::from_ident(p.ident); let ty = ecx.ty_path(path); - Some(AngleBracketedArg::Arg(GenericArg::Type(ty))) + Some(GenericArg::Type(ty)) } GenericParamKind::Const { .. } => { let expr = ecx.expr_path(ast::Path::from_ident(p.ident)); let anon_const = AnonConst { id: ast::DUMMY_NODE_ID, value: expr }; - Some(AngleBracketedArg::Arg(GenericArg::Const(anon_const))) + Some(GenericArg::Const(anon_const)) } GenericParamKind::Lifetime => None, }) - .collect::>(); - - let args: AngleBracketedArgs = AngleBracketedArgs { span, args: generic_args }; - - let segment = PathSegment { - ident, - id: ast::DUMMY_NODE_ID, - args: Some(Box::new(GenericArgs::AngleBracketed(args))), - }; - - let segments = if is_impl { - thin_vec![ - PathSegment { ident: Ident::from_str("Self"), id: ast::DUMMY_NODE_ID, args: None }, - segment, - ] - } else { - thin_vec![segment] - }; + .collect::>(); - let path = Path { span, segments }; + let idents = + if is_impl { vec![Ident::new(kw::SelfUpper, span), ident] } else { vec![ident] }; + let path = ecx.path_all(span, false, idents, generic_args); ecx.expr_path(path) } @@ -657,9 +636,7 @@ mod llvm_enzyme { assert!(sig.decl.inputs.len() == x.input_activity.len()); assert!(has_ret == x.has_ret_activity()); let mut d_decl = sig.decl.clone(); - let mut d_inputs = Vec::new(); - let mut new_inputs = Vec::new(); - let mut idents = Vec::new(); + let mut d_inputs = ThinVec::new(); let mut act_ret = ThinVec::new(); // We have two loops, a first one just to check the activities and types and possibly report @@ -724,15 +701,10 @@ mod llvm_enzyme { debug!("{:#?}", &shadow_arg.pat); panic!("not an ident?"); }; - let name: String = format!("d{}_{}", old_name, i); - new_inputs.push(name.clone()); + let name = format!("d{}_{}", old_name, i); let ident = Ident::from_str_and_span(&name, shadow_arg.pat.span); - *shadow_arg.pat = ast::Pat { - id: ast::DUMMY_NODE_ID, - kind: PatKind::Ident(BindingMode::NONE, ident, None), - span: shadow_arg.pat.span, - }; - d_inputs.push(shadow_arg.clone()); + *shadow_arg.pat = ecx.pat_ident(shadow_arg.pat.span, ident); + d_inputs.push(shadow_arg); } } DiffActivity::Dual @@ -755,15 +727,11 @@ mod llvm_enzyme { debug!("{:#?}", &shadow_arg.pat); panic!("not an ident?"); }; - let name: String = format!("b{}_{}", old_name, i); - new_inputs.push(name.clone()); + let name = format!("b{}_{}", old_name, i); let ident = Ident::from_str_and_span(&name, shadow_arg.pat.span); - *shadow_arg.pat = ast::Pat { - id: ast::DUMMY_NODE_ID, - kind: PatKind::Ident(BindingMode::NONE, ident, None), - span: shadow_arg.pat.span, - }; - d_inputs.push(shadow_arg.clone()); + + *shadow_arg.pat = ecx.pat_ident(shadow_arg.pat.span, ident); + d_inputs.push(shadow_arg); } } DiffActivity::Const => { @@ -773,11 +741,6 @@ mod llvm_enzyme { panic!("Should not happen"); } } - if let PatKind::Ident(_, ident, _) = arg.pat.kind { - idents.push(ident); - } else { - panic!("not an ident?"); - } } let active_only_ret = x.ret_activity == DiffActivity::ActiveOnly; @@ -798,33 +761,20 @@ mod llvm_enzyme { }; let name = "dret".to_string(); let ident = Ident::from_str_and_span(&name, ty.span); - let shadow_arg = ast::Param { - attrs: ThinVec::new(), - ty: ty.clone(), - pat: Box::new(ast::Pat { - id: ast::DUMMY_NODE_ID, - kind: PatKind::Ident(BindingMode::NONE, ident, None), - span: ty.span, - }), - id: ast::DUMMY_NODE_ID, - span: ty.span, - is_placeholder: false, - }; + let shadow_arg = ecx.param(ty.span, ident, ty); d_inputs.push(shadow_arg); - new_inputs.push(name); } _ => {} } } - d_decl.inputs = d_inputs.into(); + d_decl.inputs = d_inputs; if x.mode.is_fwd() { let ty = match d_decl.output { FnRetTy::Ty(ref ty) => ty.clone(), FnRetTy::Default(span) => { // We want to return std::hint::black_box(()). - let kind = TyKind::Tup(ThinVec::new()); - let ty = Box::new(rustc_ast::Ty { kind, id: ast::DUMMY_NODE_ID, span }); + let ty = ecx.ty_unit(span); d_decl.output = FnRetTy::Ty(ty.clone()); assert!(matches!(x.ret_activity, DiffActivity::None)); // this won't be used below, so any type would be fine. diff --git a/compiler/rustc_builtin_macros/src/deriving/coerce_pointee.rs b/compiler/rustc_builtin_macros/src/deriving/coerce_pointee.rs index ab9037331050e..7d0db12a450d6 100644 --- a/compiler/rustc_builtin_macros/src/deriving/coerce_pointee.rs +++ b/compiler/rustc_builtin_macros/src/deriving/coerce_pointee.rs @@ -2,8 +2,8 @@ use ast::HasAttrs; use rustc_ast::mut_visit::MutVisitor; use rustc_ast::visit::{BoundKind, Visitor}; use rustc_ast::{ - self as ast, GenericArg, GenericBound, GenericParamKind, Generics, ItemKind, - TraitBoundModifiers, VariantData, WherePredicate, + self as ast, GenericArg, GenericBound, GenericParamKind, ItemKind, TraitBoundModifiers, + VariantData, WherePredicate, }; use rustc_data_structures::flat_map_in_place::FlatMapInPlace; use rustc_errors::E0802; @@ -12,12 +12,10 @@ use rustc_macros::Diagnostic; use rustc_span::{Ident, Span, Symbol, sym}; use thin_vec::{ThinVec, thin_vec}; +use crate::deriving::generic::*; +use crate::deriving::{new_path, path_std}; use crate::diagnostics; -macro_rules! path { - ($span:expr, $($part:ident)::*) => { vec![$(Ident::new(sym::$part, $span),)*] } -} - pub(crate) fn expand_deriving_coerce_pointee( cx: &ExtCtxt<'_>, span: Span, @@ -43,15 +41,8 @@ pub(crate) fn expand_deriving_coerce_pointee( }; // Convert generic parameters (from the struct) into generic args. - let self_params: Vec<_> = generics - .params - .iter() - .map(|p| match p.kind { - GenericParamKind::Lifetime => GenericArg::Lifetime(cx.lifetime(p.span(), p.ident)), - GenericParamKind::Type { .. } => GenericArg::Type(cx.ty_ident(p.span(), p.ident)), - GenericParamKind::Const { .. } => GenericArg::Const(cx.const_ident(p.span(), p.ident)), - }) - .collect(); + let self_params: Vec<_> = + generics.params.iter().map(|p| generic_param_to_arg(cx, p, p.span())).collect(); let type_params: Vec<_> = generics .params .iter() @@ -98,71 +89,30 @@ pub(crate) fn expand_deriving_coerce_pointee( let attrs = thin_vec![cx.attr_word(sym::automatically_derived, span),]; // # Validity assertion which will be checked later in `rustc_hir_analysis::coherence::builtins`. { - let trait_path = - cx.path_all(span, true, path!(span, core::marker::CoercePointeeValidated), vec![]); - let trait_ref = cx.trait_ref(trait_path); - push( - cx.item( - span, - attrs.clone(), - ast::ItemKind::Impl(ast::Impl { - generics: Generics { - params: generics - .params - .iter() - .map(|p| match &p.kind { - GenericParamKind::Lifetime => { - cx.lifetime_param(p.span(), p.ident, p.bounds.clone()) - } - GenericParamKind::Type { default: _ } => { - cx.typaram(p.span(), p.ident, p.bounds.clone(), None) - } - GenericParamKind::Const { ty, span: _, default: _ } => cx - .const_param( - p.span(), - p.ident, - p.bounds.clone(), - ty.clone(), - None, - ), - }) - .collect(), - where_clause: generics.where_clause.clone(), - span: generics.span, - }, - of_trait: Some(Box::new(ast::TraitImplHeader { - safety: ast::Safety::Default, - polarity: ast::ImplPolarity::Positive, - defaultness: ast::Defaultness::Implicit, - trait_ref, - })), - constness: ast::Const::No, - self_ty: self_type.clone(), - items: ThinVec::new(), - }), - ), - ); + let trait_path = path_std!(cx, span, marker::CoercePointeeValidated); + push(cx.item_trait_impl( + span, + attrs.clone(), + generics_without_defaults(generics), + ast::Safety::Default, + false, + cx.trait_ref(trait_path), + self_type.clone(), + ThinVec::new(), + )); } let mut add_impl_block = |generics, trait_symbol, trait_args| { - let mut parts = path!(span, core::ops); - parts.push(Ident::new(trait_symbol, span)); - let trait_path = cx.path_all(span, true, parts, trait_args); + let trait_path = new_path(cx, span, &[sym::ops, trait_symbol], trait_args); let trait_ref = cx.trait_ref(trait_path); - let item = cx.item( + let item = cx.item_trait_impl( span, attrs.clone(), - ast::ItemKind::Impl(ast::Impl { - generics, - of_trait: Some(Box::new(ast::TraitImplHeader { - safety: ast::Safety::Default, - polarity: ast::ImplPolarity::Positive, - defaultness: ast::Defaultness::Implicit, - trait_ref, - })), - constness: ast::Const::No, - self_ty: self_type.clone(), - items: ThinVec::new(), - }), + generics, + ast::Safety::Default, + false, + trait_ref, + self_type.clone(), + ThinVec::new(), ); push(item); }; @@ -196,7 +146,7 @@ pub(crate) fn expand_deriving_coerce_pointee( return; } let arg = GenericArg::Type(s_ty.clone()); - let unsize = cx.path_all(span, true, path!(span, core::marker::Unsize), vec![arg]); + let unsize = cx.path_all(span, true, cx.std_path(&[sym::marker, sym::Unsize]), vec![arg]); pointee.bounds.push(cx.trait_bound(unsize, false)); // Drop `#[pointee]` attribute since it should not be recognized outside `derive(CoercePointee)` pointee.attrs.retain(|attr| !attr.has_name(sym::pointee)); @@ -313,11 +263,11 @@ pub(crate) fn expand_deriving_coerce_pointee( } } - let extra_param = cx.typaram(span, Ident::new(sym::__S, span), self_bounds, None); + let extra_param = cx.typaram(Ident::new(sym::__S, span), self_bounds, None); impl_generics.params.insert(pointee_param_idx + 1, extra_param); // Add the impl blocks for `DispatchFromDyn` and `CoerceUnsized`. - let gen_args = vec![GenericArg::Type(alt_self_type)]; + let gen_args = vec![alt_self_type]; add_impl_block(impl_generics.clone(), sym::DispatchFromDyn, gen_args.clone()); add_impl_block(impl_generics, sym::CoerceUnsized, gen_args); } diff --git a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs index 71329da76c481..8b15920511aca 100644 --- a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs +++ b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs @@ -182,13 +182,13 @@ pub(crate) use rustc_ast as ast; use rustc_ast::token::{IdentKind, LitKind, Token, TokenKind}; use rustc_ast::tokenstream::{DelimSpan, Spacing, TokenTree}; use rustc_ast::{ - AttrArgs, DelimArgs, EnumDef, Expr, GenericArg, GenericParamKind, Generics, Safety, SelfKind, - VariantData, + AttrArgs, DelimArgs, EnumDef, Expr, GenericArg, GenericParam, GenericParamKind, Generics, + Safety, SelfKind, VariantData, }; use rustc_attr_ir::{Attribute, AttributeKind, ReprPacked}; use rustc_attr_parsing::AttributeParser; use rustc_expand::base::ExtCtxt; -use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, respan, sym}; +use rustc_span::{Ident, Span, Symbol, kw, respan, sym}; pub(crate) use smallvec::{SmallVec, smallvec}; use thin_vec::{ThinVec, thin_vec}; @@ -610,7 +610,7 @@ impl<'a> TraitDef<'a> { ) .collect(); - cx.typaram(span, param.ident, bounds, None) + cx.typaram(param.ident, bounds, None) } GenericParamKind::Const { ty, span, .. } => { let const_nodefault_kind = GenericParamKind::Const { @@ -708,17 +708,7 @@ impl<'a> TraitDef<'a> { let self_params: Vec<_> = generics .params .iter() - .map(|param| match param.kind { - GenericParamKind::Lifetime => { - GenericArg::Lifetime(cx.lifetime(param.ident.span.with_ctxt(ctxt), param.ident)) - } - GenericParamKind::Type { .. } => { - GenericArg::Type(cx.ty_ident(param.ident.span.with_ctxt(ctxt), param.ident)) - } - GenericParamKind::Const { .. } => { - GenericArg::Const(cx.const_ident(param.ident.span.with_ctxt(ctxt), param.ident)) - } - }) + .map(|param| generic_param_to_arg(cx, param, param.ident.span.with_ctxt(ctxt))) .collect(); // Create the type of `self`. @@ -770,21 +760,15 @@ impl<'a> TraitDef<'a> { attrs.push(cx.attr_nested_word(sym::doc, sym::hidden, self.span)); } - cx.item( + cx.item_trait_impl( self.span, attrs, - ast::ItemKind::Impl(ast::Impl { - generics: trait_generics, - of_trait: Some(Box::new(ast::TraitImplHeader { - safety: self.safety, - polarity: ast::ImplPolarity::Positive, - defaultness: ast::Defaultness::Implicit, - trait_ref, - })), - constness: if self.is_const { ast::Const::Yes(DUMMY_SP) } else { ast::Const::No }, - self_ty: self_type, - items: methods.collect(), - }), + trait_generics, + self.safety, + self.is_const, + trait_ref, + self_type, + methods.collect(), ) } } @@ -1239,3 +1223,32 @@ fn create_struct_field_access_fields( .collect() }) } + +pub(crate) fn generic_param_to_arg(cx: &ExtCtxt<'_>, p: &GenericParam, span: Span) -> GenericArg { + match p.kind { + GenericParamKind::Lifetime => GenericArg::Lifetime(cx.lifetime(span, p.ident)), + GenericParamKind::Type { .. } => GenericArg::Type(cx.ty_ident(span, p.ident)), + GenericParamKind::Const { .. } => GenericArg::Const(cx.const_ident(span, p.ident)), + } +} + +pub(crate) fn generics_without_defaults(g: &Generics) -> Generics { + Generics { + params: g + .params + .iter() + .map(|p| { + let mut p = p.clone(); + match &mut p.kind { + ast::GenericParamKind::Const { default, .. } => *default = None, + ast::GenericParamKind::Type { default } => *default = None, + ast::GenericParamKind::Lifetime => {} + }; + p.attrs.clear(); + p + }) + .collect(), + where_clause: g.where_clause.clone(), + span: g.span, + } +} diff --git a/compiler/rustc_builtin_macros/src/deriving/hash.rs b/compiler/rustc_builtin_macros/src/deriving/hash.rs index 3d3023b39955d..3e0722988155c 100644 --- a/compiler/rustc_builtin_macros/src/deriving/hash.rs +++ b/compiler/rustc_builtin_macros/src/deriving/hash.rs @@ -21,7 +21,7 @@ pub(crate) fn expand_deriving_hash( let param = { let path = path_std!(cx, span, hash::Hasher); - cx.typaram(span, typaram, thin_vec![cx.trait_bound(path, false)], None) + cx.typaram(typaram, thin_vec![cx.trait_bound(path, false)], None) }; let generics = ast::Generics { diff --git a/compiler/rustc_builtin_macros/src/deriving/reborrow.rs b/compiler/rustc_builtin_macros/src/deriving/reborrow.rs index dc45b1a896bc9..05ad76dbd1ff9 100644 --- a/compiler/rustc_builtin_macros/src/deriving/reborrow.rs +++ b/compiler/rustc_builtin_macros/src/deriving/reborrow.rs @@ -1,13 +1,12 @@ -use rustc_ast::{self as ast, AttrArgs, GenericArg, GenericParamKind, Generics, ItemKind, token}; +use rustc_ast::{self as ast, AttrArgs, Generics, ItemKind, token}; use rustc_errors::E0802; use rustc_expand::base::ExtCtxt; use rustc_macros::Diagnostic; use rustc_span::{Ident, Span, Symbol, sym}; use thin_vec::ThinVec; -macro_rules! path { - ($span:expr, $($part:ident)::*) => { vec![$(Ident::new(sym::$part, $span),)*] } -} +use crate::deriving::generic::*; +use crate::deriving::new_path; pub(crate) fn expand_deriving_reborrow( cx: &ExtCtxt<'_>, @@ -37,15 +36,7 @@ pub(crate) fn expand_deriving_coerce_shared( return; }; - push_marker_impl( - cx, - span, - ident, - generics, - sym::CoerceShared, - vec![GenericArg::Type(target)], - push, - ); + push_marker_impl(cx, span, ident, generics, sym::CoerceShared, vec![target], push); } fn struct_def<'a>( @@ -114,78 +105,28 @@ fn push_marker_impl( ident: Ident, generics: &Generics, trait_name: Symbol, - trait_args: Vec, + trait_args: Vec>, push: &mut dyn FnMut(Box), ) { - let mut trait_parts = path!(span, core::marker); - trait_parts.push(Ident::new(trait_name, span)); - let trait_path = cx.path_all(span, true, trait_parts, trait_args); + let trait_path = new_path(cx, span, &[sym::core, sym::marker, trait_name], trait_args); let trait_ref = cx.trait_ref(trait_path); - let self_params: Vec<_> = generics - .params - .iter() - .map(|param| match param.kind { - GenericParamKind::Lifetime => { - GenericArg::Lifetime(cx.lifetime(param.span(), param.ident)) - } - GenericParamKind::Type { .. } => { - GenericArg::Type(cx.ty_ident(param.span(), param.ident)) - } - GenericParamKind::Const { .. } => { - GenericArg::Const(cx.const_ident(param.span(), param.ident)) - } - }) - .collect(); + let self_params: Vec<_> = + generics.params.iter().map(|p| generic_param_to_arg(cx, p, p.span())).collect(); let self_ty = cx.ty_path(cx.path_all(span, false, vec![ident], self_params)); - push(cx.item( + push(cx.item_trait_impl( span, thin_vec::thin_vec![cx.attr_word(sym::automatically_derived, span)], - ast::ItemKind::Impl(ast::Impl { - generics: impl_generics(cx, generics), - of_trait: Some(Box::new(ast::TraitImplHeader { - safety: ast::Safety::Default, - polarity: ast::ImplPolarity::Positive, - defaultness: ast::Defaultness::Implicit, - trait_ref, - })), - constness: ast::Const::No, - self_ty, - items: ThinVec::new(), - }), + generics_without_defaults(generics), + ast::Safety::Default, + false, + trait_ref, + self_ty, + ThinVec::new(), )); } -fn impl_generics(cx: &ExtCtxt<'_>, generics: &Generics) -> Generics { - // Rebuild the generic parameter declarations because defaults are allowed on structs but - // rejected on impls. Preserve lifetime, type, and const parameters and their bounds, const - // parameter types, and the where-clause, while omitting type and const defaults. - Generics { - params: generics - .params - .iter() - .map(|param| match ¶m.kind { - GenericParamKind::Lifetime => { - cx.lifetime_param(param.span(), param.ident, param.bounds.clone()) - } - GenericParamKind::Type { default: _ } => { - cx.typaram(param.span(), param.ident, param.bounds.clone(), None) - } - GenericParamKind::Const { ty, span: _, default: _ } => cx.const_param( - param.span(), - param.ident, - param.bounds.clone(), - ty.clone(), - None, - ), - }) - .collect(), - where_clause: generics.where_clause.clone(), - span: generics.span, - } -} - #[derive(Diagnostic)] #[diag("`derive({$trait_name})` is only supported for structs, not {$kind}s", code = E0802)] struct UnsupportedItem { diff --git a/compiler/rustc_builtin_macros/src/edition_panic.rs b/compiler/rustc_builtin_macros/src/edition_panic.rs index ac5c43c660088..4c99ef9a9da26 100644 --- a/compiler/rustc_builtin_macros/src/edition_panic.rs +++ b/compiler/rustc_builtin_macros/src/edition_panic.rs @@ -1,6 +1,5 @@ use rustc_ast::token::Delimiter; -use rustc_ast::tokenstream::{DelimSpan, TokenStream}; -use rustc_ast::*; +use rustc_ast::tokenstream::TokenStream; use rustc_expand::base::*; use rustc_span::edition::Edition; use rustc_span::{Span, sym}; @@ -44,26 +43,15 @@ fn expand<'cx>( ) -> MacroExpanderResult<'cx> { let sp = cx.with_call_site_ctxt(sp); - ExpandResult::Ready(MacEager::expr( - cx.expr( + ExpandResult::Ready(MacEager::expr(cx.expr_macro_call( + sp, + cx.macro_call( sp, - ExprKind::MacCall(Box::new(MacCall { - path: Path { - span: sp, - segments: cx - .std_path(&[sym::panic, mac]) - .into_iter() - .map(PathSegment::from_ident) - .collect(), - }, - args: Box::new(DelimArgs { - dspan: DelimSpan::from_single(sp), - delim: Delimiter::Parenthesis, - tokens: tts, - }), - })), + cx.path(sp, cx.std_path(&[sym::panic, mac])), + Delimiter::Parenthesis, + tts, ), - )) + ))) } pub(crate) fn use_panic_2021(mut span: Span) -> bool { diff --git a/compiler/rustc_builtin_macros/src/format.rs b/compiler/rustc_builtin_macros/src/format.rs index e23c057f8a651..e52da1136dd64 100644 --- a/compiler/rustc_builtin_macros/src/format.rs +++ b/compiler/rustc_builtin_macros/src/format.rs @@ -1107,7 +1107,7 @@ fn report_invalid_references( // for `println!("{7:7$}", 1);` indexes.sort(); indexes.dedup(); - let span: MultiSpan = if !parser.is_source_literal || parser.arg_places.is_empty() { + let span = if !parser.is_source_literal || parser.arg_places.is_empty() { MultiSpan::from_span(fmt_span) } else { MultiSpan::from_spans(invalid_refs.iter().filter_map(|&(_, span, _, _)| span).collect()) diff --git a/compiler/rustc_builtin_macros/src/gca.rs b/compiler/rustc_builtin_macros/src/gca.rs index ba26b16d06be5..9e117e06ea9fd 100644 --- a/compiler/rustc_builtin_macros/src/gca.rs +++ b/compiler/rustc_builtin_macros/src/gca.rs @@ -18,16 +18,9 @@ pub(crate) fn expand<'cx>( Err(err) => return ExpandResult::Ready(DummyResult::any(span, err)), }; - let id = ast::DUMMY_NODE_ID; ExpandResult::Ready(Box::new(base::MacEager { - expr: Some(Box::new(ast::Expr { - id, - kind: ast::ExprKind::GcaMacro(expr.clone()), - span, - attrs: Default::default(), - tokens: None, - })), - ty: Some(Box::new(ast::Ty { id, kind: ast::TyKind::GcaMacro(expr), span })), + expr: Some(cx.expr(span, ast::ExprKind::GcaMacro(expr.clone()))), + ty: Some(cx.ty(span, ast::TyKind::GcaMacro(expr))), ..Default::default() })) } diff --git a/compiler/rustc_builtin_macros/src/offload.rs b/compiler/rustc_builtin_macros/src/offload.rs index 53bf0f4ca6b86..4da4ce4e4a505 100644 --- a/compiler/rustc_builtin_macros/src/offload.rs +++ b/compiler/rustc_builtin_macros/src/offload.rs @@ -148,7 +148,7 @@ pub(crate) fn expand_kernel( } // inline(never) attr - let ts: Vec = vec![TokenTree::Token( + let ts = vec![TokenTree::Token( Token::new(TokenKind::Ident(sym::never, IdentKind::Normal), span), Spacing::Joint, )]; diff --git a/compiler/rustc_builtin_macros/src/proc_macro_harness.rs b/compiler/rustc_builtin_macros/src/proc_macro_harness.rs index 2fbce3638e021..ecf4f7e7fb1af 100644 --- a/compiler/rustc_builtin_macros/src/proc_macro_harness.rs +++ b/compiler/rustc_builtin_macros/src/proc_macro_harness.rs @@ -339,6 +339,7 @@ fn mk_decls(cx: &mut ExtCtxt<'_>, macros: &[ProcMacro]) -> Box { let mut decls_static = cx.item_static( span, + ast::AttrVec::new(), Ident::new(sym::_DECLS, span), cx.ty_ref( span, diff --git a/compiler/rustc_builtin_macros/src/test.rs b/compiler/rustc_builtin_macros/src/test.rs index 42dbc801bfb5a..f2a9dd4f05be3 100644 --- a/compiler/rustc_builtin_macros/src/test.rs +++ b/compiler/rustc_builtin_macros/src/test.rs @@ -3,7 +3,7 @@ use std::{assert_matches, iter}; -use rustc_ast::{self as ast, GenericParamKind, Mutability, Safety, attr, join_path_idents}; +use rustc_ast::{self as ast, GenericParamKind, Mutability, attr, join_path_idents}; use rustc_ast_pretty::pprust; use rustc_attr_ir::{Attribute, AttributeKind}; use rustc_attr_parsing::AttributeParser; @@ -210,8 +210,9 @@ pub(crate) fn expand_test_or_bench( thin_vec![ // #[coverage(off)] // |__bench_fn_name| self::test::assert_test_result( - coverage_off(cx.lambda1( + coverage_off(cx.closure( sp, + vec![bencher_param], cx.expr_call( sp, cx.expr_path(test_path("assert_test_result")), @@ -224,7 +225,6 @@ pub(crate) fn expand_test_or_bench( ), ], ), - bencher_param, )), // ) ], ) @@ -235,8 +235,9 @@ pub(crate) fn expand_test_or_bench( thin_vec![ // #[coverage(off)] // || { - coverage_off(cx.lambda0( + coverage_off(cx.closure( sp, + vec![], // test::assert_test_result( cx.expr_call( sp, @@ -263,76 +264,74 @@ pub(crate) fn expand_test_or_bench( let location_info = get_location_info(cx, fn_); - let mut test_const = - cx.item( + // static $ident: test::TestDescAndFn = + // We use a static because these things only exist to have references taken + // to them for the test case array. No reason to introduce tons of promoteds for that. + // Promoteds have the advantage that they can be merged to save space, but every one + // of these points to a different function so that will not happen. + let mut test_const = cx.item_static( + sp, + thin_vec![ + // #[cfg(test)] + cx.attr_nested_word(sym::cfg, sym::test, attr_sp), + // #[rustc_test_marker = "test_case_sort_key"] + cx.attr_name_value_str(sym::rustc_test_marker, test_path_symbol, attr_sp), + // #[doc(hidden)] + cx.attr_nested_word(sym::doc, sym::hidden, attr_sp), + ], + Ident::new(fn_.ident.name, sp), + cx.ty(sp, ast::TyKind::Path(None, test_path("TestDescAndFn"))), + Mutability::Not, + // test::TestDescAndFn { + cx.expr_struct( sp, + test_path("TestDescAndFn"), thin_vec![ - // #[cfg(test)] - cx.attr_nested_word(sym::cfg, sym::test, attr_sp), - // #[rustc_test_marker = "test_case_sort_key"] - cx.attr_name_value_str(sym::rustc_test_marker, test_path_symbol, attr_sp), - // #[doc(hidden)] - cx.attr_nested_word(sym::doc, sym::hidden, attr_sp), - ], - // static $ident: test::TestDescAndFn = - // We use a static because these things only exist to have references taken - // to them for the test case array. No reason to introduce tons of promoteds for that. - // Promoteds have the advantage that they can be merged to save space, but every one - // of these points to a different function so that will not happen. - ast::ItemKind::Static( - ast::StaticItem { - ident: Ident::new(fn_.ident.name, sp), - ty: cx.ty(sp, ast::TyKind::Path(None, test_path("TestDescAndFn"))), - safety: Safety::Default, - mutability: Mutability::Not, - define_opaque: None, - eii_impl: None, - // test::TestDescAndFn { - expr: Some( - cx.expr_struct( - sp, - test_path("TestDescAndFn"), - thin_vec![ - // desc: test::TestDesc { - field( - "desc", - cx.expr_struct(sp, test_path("TestDesc"), thin_vec![ - // name: "path::to::test" - field( - "name", - cx.expr_call( - sp, - cx.expr_path(test_path("StaticTestName")), - thin_vec![cx.expr_str(sp, test_path_symbol)], - ), - ), - // ignore: true | false - field("ignore", cx.expr_bool(sp, should_ignore(&item)),), - // ignore_message: Some("...") | None - field( - "ignore_message", - if let Some(msg) = should_ignore_message(&item) { - cx.expr_some(sp, cx.expr_str(sp, msg)) - } else { - cx.expr_none(sp) - }, + // desc: test::TestDesc { + field( + "desc", + cx.expr_struct( + sp, + test_path("TestDesc"), + thin_vec![ + // name: "path::to::test" + field( + "name", + cx.expr_call( + sp, + cx.expr_path(test_path("StaticTestName")), + thin_vec![cx.expr_str(sp, test_path_symbol)], ), - // source_file: - field("source_file", cx.expr_str(sp, location_info.0)), - // start_line: start line of the test fn identifier. - field("start_line", cx.expr_usize(sp, location_info.1)), - // start_col: start column of the test fn identifier. - field("start_col", cx.expr_usize(sp, location_info.2)), - // end_line: end line of the test fn identifier. - field("end_line", cx.expr_usize(sp, location_info.3)), - // end_col: end column of the test fn identifier. - field("end_col", cx.expr_usize(sp, location_info.4)), - // compile_fail: true | false - field("compile_fail", cx.expr_bool(sp, false)), - // no_run: true | false - field("no_run", cx.expr_bool(sp, false)), - // should_panic: ... - field("should_panic", match should_panic(cx, &item) { + ), + // ignore: true | false + field("ignore", cx.expr_bool(sp, should_ignore(&item)),), + // ignore_message: Some("...") | None + field( + "ignore_message", + if let Some(msg) = should_ignore_message(&item) { + cx.expr_some(sp, cx.expr_str(sp, msg)) + } else { + cx.expr_none(sp) + }, + ), + // source_file: + field("source_file", cx.expr_str(sp, location_info.0)), + // start_line: start line of the test fn identifier. + field("start_line", cx.expr_usize(sp, location_info.1)), + // start_col: start column of the test fn identifier. + field("start_col", cx.expr_usize(sp, location_info.2)), + // end_line: end line of the test fn identifier. + field("end_line", cx.expr_usize(sp, location_info.3)), + // end_col: end column of the test fn identifier. + field("end_col", cx.expr_usize(sp, location_info.4)), + // compile_fail: true | false + field("compile_fail", cx.expr_bool(sp, false)), + // no_run: true | false + field("no_run", cx.expr_bool(sp, false)), + // should_panic: ... + field( + "should_panic", + match should_panic(cx, &item) { // test::ShouldPanic::No ShouldPanic::No => { cx.expr_path(should_panic_path("No")) @@ -347,9 +346,12 @@ pub(crate) fn expand_test_or_bench( cx.expr_path(should_panic_path("YesWithMessage")), thin_vec![cx.expr_str(sp, sym)], ), - },), - // test_type: ... - field("test_type", match test_type(cx) { + }, + ), + // test_type: ... + field( + "test_type", + match test_type(cx) { // test::TestType::UnitTest TestType::UnitTest => { cx.expr_path(test_type_path("UnitTest")) @@ -362,19 +364,18 @@ pub(crate) fn expand_test_or_bench( TestType::Unknown => { cx.expr_path(test_type_path("Unknown")) } - },), - // }, - ],), - ), - // testfn: test::StaticTestFn(...) | test::StaticBenchFn(...) - field("testfn", test_fn), // } - ], - ), // } + }, + ), + // }, + ], ), - } - .into(), - ), - ); + ), + // testfn: test::StaticTestFn(...) | test::StaticBenchFn(...) + field("testfn", test_fn), // } + ], + // } + ), + ); test_const.vis.kind = ast::VisibilityKind::Public; // extern crate test diff --git a/compiler/rustc_builtin_macros/src/test_binder_constraints.rs b/compiler/rustc_builtin_macros/src/test_binder_constraints.rs index d6a3649500c29..3e70e83bb0762 100644 --- a/compiler/rustc_builtin_macros/src/test_binder_constraints.rs +++ b/compiler/rustc_builtin_macros/src/test_binder_constraints.rs @@ -1,5 +1,5 @@ use rustc_ast::tokenstream::TokenStream; -use rustc_ast::{AttrVec, VisibilityKind, ast, token}; +use rustc_ast::{AttrVec, ast, token}; use rustc_expand::base::{DummyResult, ExpandResult, ExtCtxt, MacEager, MacroExpanderResult}; use rustc_span::Span; use smallvec::SmallVec; @@ -26,15 +26,8 @@ pub(crate) fn expand<'cx>( if p.token != token::Eof { cx.dcx().emit_err(diagnostics::OnlyOneArgument { span: p.token.span, name }); } - let item = Box::new(ast::Item { - attrs: AttrVec::default(), - id: ast::DUMMY_NODE_ID, - span, - vis: ast::Visibility { kind: VisibilityKind::Inherited, span: span.shrink_to_lo() }, - kind: ast::ItemKind::TestBinderConstraints(item), - tokens: None, - }); - rustc_expand::base::ExpandResult::Ready(Box::new(MacEager { + let item = cx.item(span, AttrVec::default(), ast::ItemKind::TestBinderConstraints(item)); + ExpandResult::Ready(Box::new(MacEager { expr: None, items: Some(SmallVec::from_buf([item])), ty: None, diff --git a/compiler/rustc_expand/src/base.rs b/compiler/rustc_expand/src/base.rs index fda75319b087b..01e8cef49e445 100644 --- a/compiler/rustc_expand/src/base.rs +++ b/compiler/rustc_expand/src/base.rs @@ -1,6 +1,5 @@ use std::any::Any; use std::default::Default; -use std::iter; use std::path::PathBuf; use std::rc::Rc; use std::sync::Arc; @@ -24,7 +23,7 @@ use rustc_span::def_id::{CrateNum, DefId, LocalDefId, ModId}; use rustc_span::edition::Edition; use rustc_span::hygiene::{AstPass, ExpnData, ExpnKind, LocalExpnId, MacroKind}; use rustc_span::source_map::SourceMap; -use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw}; +use rustc_span::{DUMMY_SP, Ident, Span, Symbol}; use rustc_structures::{CollapseMacroDebuginfo, Limit}; use smallvec::{SmallVec, smallvec}; use thin_vec::ThinVec; @@ -1324,16 +1323,6 @@ impl<'a> ExtCtxt<'a> { pub fn set_trace_macros(&mut self, x: bool) { self.ecfg.trace_mac = x } - pub fn std_path(&self, components: &[Symbol]) -> Vec { - let def_site = self.with_def_site_ctxt(DUMMY_SP); - iter::once(Ident::new(kw::DollarCrate, def_site)) - .chain(components.iter().map(|&s| Ident::new(s, def_site))) - .collect() - } - pub fn def_site_path(&self, components: &[Symbol]) -> Vec { - let def_site = self.with_def_site_ctxt(DUMMY_SP); - components.iter().map(|&s| Ident::new(s, def_site)).collect() - } pub fn check_unused_macros(&mut self) { self.resolver.check_unused_macros(); diff --git a/compiler/rustc_expand/src/build.rs b/compiler/rustc_expand/src/build.rs index 9a93d82a4fe4c..34d4343ba9ba0 100644 --- a/compiler/rustc_expand/src/build.rs +++ b/compiler/rustc_expand/src/build.rs @@ -1,3 +1,5 @@ +use std::iter; + use rustc_ast::token::Delimiter; use rustc_ast::tokenstream::TokenStream; use rustc_ast::util::literal; @@ -11,6 +13,13 @@ use thin_vec::{ThinVec, thin_vec}; use crate::base::ExtCtxt; impl<'a> ExtCtxt<'a> { + pub fn std_path(&self, components: &[Symbol]) -> Vec { + let def_site = self.with_def_site_ctxt(DUMMY_SP); + iter::once(Ident::new(kw::DollarCrate, def_site)) + .chain(components.iter().map(|&s| Ident::new(s, def_site))) + .collect() + } + pub fn path(&self, span: Span, strs: Vec) -> ast::Path { self.path_all(span, false, strs, vec![]) } @@ -138,13 +147,12 @@ impl<'a> ExtCtxt<'a> { pub fn typaram( &self, - span: Span, ident: Ident, bounds: ast::GenericBounds, default: Option>, ) -> ast::GenericParam { ast::GenericParam { - ident: ident.with_span_pos(span), + ident, id: ast::DUMMY_NODE_ID, attrs: AttrVec::new(), bounds, @@ -154,15 +162,10 @@ impl<'a> ExtCtxt<'a> { } } - pub fn lifetime_param( - &self, - span: Span, - ident: Ident, - bounds: ast::GenericBounds, - ) -> ast::GenericParam { + pub fn lifetime_param(&self, ident: Ident, bounds: ast::GenericBounds) -> ast::GenericParam { ast::GenericParam { id: ast::DUMMY_NODE_ID, - ident: ident.with_span_pos(span), + ident, attrs: AttrVec::new(), bounds, is_placeholder: false, @@ -173,7 +176,6 @@ impl<'a> ExtCtxt<'a> { pub fn const_param( &self, - span: Span, ident: Ident, bounds: ast::GenericBounds, ty: Box, @@ -181,7 +183,7 @@ impl<'a> ExtCtxt<'a> { ) -> ast::GenericParam { ast::GenericParam { id: ast::DUMMY_NODE_ID, - ident: ident.with_span_pos(span), + ident, attrs: AttrVec::new(), bounds, is_placeholder: false, @@ -275,10 +277,6 @@ impl<'a> ExtCtxt<'a> { self.stmt_local(local, span) } - pub fn stmt_semi(&self, expr: Box) -> ast::Stmt { - ast::Stmt { id: ast::DUMMY_NODE_ID, span: expr.span, kind: ast::StmtKind::Semi(expr) } - } - pub fn stmt_local(&self, local: Box, span: Span) -> ast::Stmt { ast::Stmt { id: ast::DUMMY_NODE_ID, kind: ast::StmtKind::Let(local), span } } @@ -378,12 +376,6 @@ impl<'a> ExtCtxt<'a> { ) -> Box { self.expr(span, ast::ExprKind::Call(expr, args)) } - pub fn expr_loop(&self, sp: Span, block: Box) -> Box { - self.expr(sp, ast::ExprKind::Loop(block, None, sp)) - } - pub fn expr_asm(&self, sp: Span, expr: Box) -> Box { - self.expr(sp, ast::ExprKind::InlineAsm(expr)) - } pub fn expr_call_ident( &self, span: Span, @@ -490,64 +482,17 @@ impl<'a> ExtCtxt<'a> { self.expr(sp, ast::ExprKind::Tup(exprs)) } - pub fn expr_unreachable(&self, span: Span) -> Box { - self.expr_macro_call( - span, - self.macro_call( - span, - self.path_global( - span, - [sym::std, sym::unreachable].map(|s| Ident::new(s, span)).to_vec(), - ), - Delimiter::Parenthesis, - TokenStream::default(), - ), - ) - } - pub fn expr_ok(&self, sp: Span, expr: Box) -> Box { let ok = self.std_path(&[sym::result, sym::Result, sym::Ok]); self.expr_call_global(sp, ok, thin_vec![expr]) } - pub fn expr_try(&self, sp: Span, head: Box) -> Box { - let ok = self.std_path(&[sym::result, sym::Result, sym::Ok]); - let ok_path = self.path_global(sp, ok); - let err = self.std_path(&[sym::result, sym::Result, sym::Err]); - let err_path = self.path_global(sp, err); - - let binding_variable = Ident::new(sym::__try_var, sp); - let binding_pat = self.pat_ident(sp, binding_variable); - let binding_expr = self.expr_ident(sp, binding_variable); - - // `Ok(__try_var)` pattern - let ok_pat = self.pat_tuple_struct(sp, ok_path, thin_vec![binding_pat.clone()]); - - // `Err(__try_var)` (pattern and expression respectively) - let err_pat = self.pat_tuple_struct(sp, err_path.clone(), thin_vec![binding_pat]); - let err_inner_expr = - self.expr_call(sp, self.expr_path(err_path), thin_vec![binding_expr.clone()]); - // `return Err(__try_var)` - let err_expr = self.expr(sp, ast::ExprKind::Ret(Some(err_inner_expr))); - - // `Ok(__try_var) => __try_var` - let ok_arm = self.arm(sp, ok_pat, binding_expr); - // `Err(__try_var) => return Err(__try_var)` - let err_arm = self.arm(sp, err_pat, err_expr); - - // `match head { Ok() => ..., Err() => ... }` - self.expr_match(sp, head, thin_vec![ok_arm, err_arm]) - } - pub fn pat(&self, span: Span, kind: PatKind) -> ast::Pat { ast::Pat { id: ast::DUMMY_NODE_ID, kind, span } } pub fn pat_wild(&self, span: Span) -> ast::Pat { self.pat(span, PatKind::Wild) } - pub fn pat_lit(&self, span: Span, expr: Box) -> ast::Pat { - self.pat(span, PatKind::Expr(expr)) - } pub fn pat_ident(&self, span: Span, ident: Ident) -> ast::Pat { self.pat_ident_binding_mode(span, ident, ast::BindingMode::NONE) } @@ -602,10 +547,6 @@ impl<'a> ExtCtxt<'a> { } } - pub fn arm_unreachable(&self, span: Span) -> ast::Arm { - self.arm(span, self.pat_wild(span), self.expr_unreachable(span)) - } - pub fn expr_match( &self, span: Span, @@ -626,15 +567,15 @@ impl<'a> ExtCtxt<'a> { self.expr(span, ast::ExprKind::If(cond, self.block_expr(then), els)) } - pub fn lambda(&self, span: Span, ids: Vec, body: Box) -> Box { + pub fn closure(&self, span: Span, ids: Vec, body: Box) -> Box { let fn_decl = self.fn_decl( ids.iter().map(|id| self.param(span, *id, self.ty(span, ast::TyKind::Infer))).collect(), ast::FnRetTy::Default(span), ); // FIXME -- We are using `span` as the span of the `|...|` - // part of the lambda, but it probably (maybe?) corresponds to - // the entire lambda body. Probably we should extend the API + // part of the closure, but it probably (maybe?) corresponds to + // the entire closure body. Probably we should extend the API // here, but that's not entirely clear. self.expr( span, @@ -654,23 +595,6 @@ impl<'a> ExtCtxt<'a> { ) } - pub fn lambda0(&self, span: Span, body: Box) -> Box { - self.lambda(span, Vec::new(), body) - } - - pub fn lambda1(&self, span: Span, body: Box, ident: Ident) -> Box { - self.lambda(span, vec![ident], body) - } - - pub fn lambda_stmts_1( - &self, - span: Span, - stmts: ThinVec, - ident: Ident, - ) -> Box { - self.lambda1(span, self.expr_block(self.block(span, stmts)), ident) - } - pub fn param(&self, span: Span, ident: Ident, ty: Box) -> ast::Param { let pat = Box::new(self.pat_ident(span, ident)); ast::Param { @@ -702,9 +626,39 @@ impl<'a> ExtCtxt<'a> { }) } + pub fn item_trait_impl( + &self, + span: Span, + attrs: ast::AttrVec, + generics: ast::Generics, + safety: ast::Safety, + is_const: bool, + trait_ref: ast::TraitRef, + self_ty: Box, + items: ThinVec>, + ) -> Box { + self.item( + span, + attrs, + ast::ItemKind::Impl(ast::Impl { + generics, + of_trait: Some(Box::new(ast::TraitImplHeader { + safety, + polarity: ast::ImplPolarity::Positive, + defaultness: ast::Defaultness::Implicit, + trait_ref, + })), + constness: if is_const { ast::Const::Yes(DUMMY_SP) } else { ast::Const::No }, + self_ty, + items, + }), + ) + } + pub fn item_static( &self, span: Span, + attrs: ast::AttrVec, ident: Ident, ty: Box, mutability: ast::Mutability, @@ -712,7 +666,7 @@ impl<'a> ExtCtxt<'a> { ) -> Box { self.item( span, - AttrVec::new(), + attrs, ast::ItemKind::Static( ast::StaticItem { ident, diff --git a/tests/pretty/autodiff/autodiff_forward.pp b/tests/pretty/autodiff/autodiff_forward.pp index 746754637f5cd..0fb60061f6982 100644 --- a/tests/pretty/autodiff/autodiff_forward.pp +++ b/tests/pretty/autodiff/autodiff_forward.pp @@ -35,8 +35,8 @@ } #[rustc_autodiff(Forward, 1, Dual, Const, Dual)] pub fn df1(x: &[f64], bx_0: &[f64], y: f64) -> (f64, f64) { - ::core::intrinsics::autodiff(f1::<> as fn(_: &[f64], _: f64) -> f64, - df1::<>, (x, bx_0, y)) + ::core::intrinsics::autodiff(f1 as fn(_: &[f64], _: f64) -> f64, df1, + (x, bx_0, y)) } #[rustc_autodiff] pub fn f2(x: &[f64], y: f64) -> f64 { @@ -44,8 +44,8 @@ } #[rustc_autodiff(Forward, 1, Dual, Const, Const)] pub fn df2(x: &[f64], bx_0: &[f64], y: f64) -> f64 { - ::core::intrinsics::autodiff(f2::<> as fn(_: &[f64], _: f64) -> f64, - df2::<>, (x, bx_0, y)) + ::core::intrinsics::autodiff(f2 as fn(_: &[f64], _: f64) -> f64, df2, + (x, bx_0, y)) } #[rustc_autodiff] pub fn f3(x: &[f64], y: f64) -> f64 { @@ -53,33 +53,31 @@ } #[rustc_autodiff(Forward, 1, Dual, Const, Const)] pub fn df3(x: &[f64], bx_0: &[f64], y: f64) -> f64 { - ::core::intrinsics::autodiff(f3::<> as fn(_: &[f64], _: f64) -> f64, - df3::<>, (x, bx_0, y)) + ::core::intrinsics::autodiff(f3 as fn(_: &[f64], _: f64) -> f64, df3, + (x, bx_0, y)) } #[rustc_autodiff] pub fn f4() {} #[rustc_autodiff(Forward, 1, None)] -pub fn df4() -> () { - ::core::intrinsics::autodiff(f4::<> as fn(), df4::<>, ()) -} +pub fn df4() -> () { ::core::intrinsics::autodiff(f4 as fn(), df4, ()) } #[rustc_autodiff] pub fn f5(x: &[f64], y: f64) -> f64 { ::core::panicking::panic("not implemented") } #[rustc_autodiff(Forward, 1, Const, Dual, Const)] pub fn df5_y(x: &[f64], y: f64, by_0: f64) -> f64 { - ::core::intrinsics::autodiff(f5::<> as fn(_: &[f64], _: f64) -> f64, - df5_y::<>, (x, y, by_0)) + ::core::intrinsics::autodiff(f5 as fn(_: &[f64], _: f64) -> f64, df5_y, + (x, y, by_0)) } #[rustc_autodiff(Forward, 1, Dual, Const, Const)] pub fn df5_x(x: &[f64], bx_0: &[f64], y: f64) -> f64 { - ::core::intrinsics::autodiff(f5::<> as fn(_: &[f64], _: f64) -> f64, - df5_x::<>, (x, bx_0, y)) + ::core::intrinsics::autodiff(f5 as fn(_: &[f64], _: f64) -> f64, df5_x, + (x, bx_0, y)) } #[rustc_autodiff(Reverse, 1, Duplicated, Const, Active)] pub fn df5_rev(x: &[f64], dx_0: &mut [f64], y: f64, dret: f64) -> f64 { - ::core::intrinsics::autodiff(f5::<> as fn(_: &[f64], _: f64) -> f64, - df5_rev::<>, (x, dx_0, y, dret)) + ::core::intrinsics::autodiff(f5 as fn(_: &[f64], _: f64) -> f64, df5_rev, + (x, dx_0, y, dret)) } struct DoesNotImplDefault; #[rustc_autodiff] @@ -88,14 +86,13 @@ } #[rustc_autodiff(Forward, 1, Const)] pub fn df6() -> DoesNotImplDefault { - ::core::intrinsics::autodiff(f6::<> as fn() -> DoesNotImplDefault, - df6::<>, ()) + ::core::intrinsics::autodiff(f6 as fn() -> DoesNotImplDefault, df6, ()) } #[rustc_autodiff] pub fn f7(x: f32) -> () {} #[rustc_autodiff(Forward, 1, Const, None)] pub fn df7(x: f32) -> () { - ::core::intrinsics::autodiff(f7::<> as fn(_: f32) -> (), df7::<>, (x,)) + ::core::intrinsics::autodiff(f7 as fn(_: f32) -> (), df7, (x,)) } #[no_mangle] #[rustc_autodiff] @@ -103,32 +100,31 @@ #[rustc_autodiff(Forward, 4, Dual, Dual)] fn f8_3(x: &f32, bx_0: &f32, bx_1: &f32, bx_2: &f32, bx_3: &f32) -> [f32; 5usize] { - ::core::intrinsics::autodiff(f8::<> as fn(_: &f32) -> f32, f8_3::<>, + ::core::intrinsics::autodiff(f8 as fn(_: &f32) -> f32, f8_3, (x, bx_0, bx_1, bx_2, bx_3)) } #[rustc_autodiff(Forward, 4, Dual, DualOnly)] fn f8_2(x: &f32, bx_0: &f32, bx_1: &f32, bx_2: &f32, bx_3: &f32) -> [f32; 4usize] { - ::core::intrinsics::autodiff(f8::<> as fn(_: &f32) -> f32, f8_2::<>, + ::core::intrinsics::autodiff(f8 as fn(_: &f32) -> f32, f8_2, (x, bx_0, bx_1, bx_2, bx_3)) } #[rustc_autodiff(Forward, 1, Dual, DualOnly)] fn f8_1(x: &f32, bx_0: &f32) -> f32 { - ::core::intrinsics::autodiff(f8::<> as fn(_: &f32) -> f32, f8_1::<>, - (x, bx_0)) + ::core::intrinsics::autodiff(f8 as fn(_: &f32) -> f32, f8_1, (x, bx_0)) } pub fn f9() { #[rustc_autodiff] fn inner(x: f32) -> f32 { x * x } #[rustc_autodiff(Forward, 1, Dual, Dual)] fn d_inner_2(x: f32, bx_0: f32) -> (f32, f32) { - ::core::intrinsics::autodiff(inner::<> as fn(_: f32) -> f32, - d_inner_2::<>, (x, bx_0)) + ::core::intrinsics::autodiff(inner as fn(_: f32) -> f32, d_inner_2, + (x, bx_0)) } #[rustc_autodiff(Forward, 1, Dual, DualOnly)] fn d_inner_1(x: f32, bx_0: f32) -> f32 { - ::core::intrinsics::autodiff(inner::<> as fn(_: f32) -> f32, - d_inner_1::<>, (x, bx_0)) + ::core::intrinsics::autodiff(inner as fn(_: f32) -> f32, d_inner_1, + (x, bx_0)) } } #[rustc_autodiff] diff --git a/tests/pretty/autodiff/autodiff_reverse.pp b/tests/pretty/autodiff/autodiff_reverse.pp index e2088e0ac13db..01ac5a5888cfc 100644 --- a/tests/pretty/autodiff/autodiff_reverse.pp +++ b/tests/pretty/autodiff/autodiff_reverse.pp @@ -28,21 +28,21 @@ } #[rustc_autodiff(Reverse, 1, Duplicated, Const, Active)] pub fn df1(x: &[f64], dx_0: &mut [f64], y: f64, dret: f64) -> f64 { - ::core::intrinsics::autodiff(f1::<> as fn(_: &[f64], _: f64) -> f64, - df1::<>, (x, dx_0, y, dret)) + ::core::intrinsics::autodiff(f1 as fn(_: &[f64], _: f64) -> f64, df1, + (x, dx_0, y, dret)) } #[rustc_autodiff] pub fn f2() {} #[rustc_autodiff(Reverse, 1, None)] -pub fn df2() { ::core::intrinsics::autodiff(f2::<> as fn(), df2::<>, ()) } +pub fn df2() { ::core::intrinsics::autodiff(f2 as fn(), df2, ()) } #[rustc_autodiff] pub fn f3(x: &[f64], y: f64) -> f64 { ::core::panicking::panic("not implemented") } #[rustc_autodiff(Reverse, 1, Duplicated, Const, Active)] pub fn df3(x: &[f64], dx_0: &mut [f64], y: f64, dret: f64) -> f64 { - ::core::intrinsics::autodiff(f3::<> as fn(_: &[f64], _: f64) -> f64, - df3::<>, (x, dx_0, y, dret)) + ::core::intrinsics::autodiff(f3 as fn(_: &[f64], _: f64) -> f64, df3, + (x, dx_0, y, dret)) } enum Foo { Reverse, } use Foo::Reverse; @@ -50,7 +50,7 @@ pub fn f4(x: f32) { ::core::panicking::panic("not implemented") } #[rustc_autodiff(Reverse, 1, Const, None)] pub fn df4(x: f32) { - ::core::intrinsics::autodiff(f4::<> as fn(_: f32), df4::<>, (x,)) + ::core::intrinsics::autodiff(f4 as fn(_: f32), df4, (x,)) } #[rustc_autodiff] pub fn f5(x: *const f32, y: &f32) { @@ -58,7 +58,7 @@ } #[rustc_autodiff(Reverse, 1, DuplicatedOnly, Duplicated, None)] pub unsafe fn df5(x: *const f32, dx_0: *mut f32, y: &f32, dy_0: &mut f32) { - ::core::intrinsics::autodiff(f5::<> as fn(_: *const f32, _: &f32), - df5::<>, (x, dx_0, y, dy_0)) + ::core::intrinsics::autodiff(f5 as fn(_: *const f32, _: &f32), df5, + (x, dx_0, y, dy_0)) } fn main() {} diff --git a/tests/pretty/autodiff/inherent_impl.pp b/tests/pretty/autodiff/inherent_impl.pp index d3a5a71b8bcbf..d175fbdecf1e0 100644 --- a/tests/pretty/autodiff/inherent_impl.pp +++ b/tests/pretty/autodiff/inherent_impl.pp @@ -30,7 +30,7 @@ } #[rustc_autodiff(Reverse, 1, Const, Active, Active)] fn df(&self, x: f64, dret: f64) -> (f64, f64) { - ::core::intrinsics::autodiff(Self::f::<> as - fn(_: &Self, _: f64) -> f64, Self::df::<>, (self, x, dret)) + ::core::intrinsics::autodiff(Self::f as fn(_: &Self, _: f64) -> f64, + Self::df, (self, x, dret)) } }