diff --git a/compiler/rustc_ast_lowering/src/block.rs b/compiler/rustc_ast_lowering/src/block.rs index b2cb1718b86a3..dbed9093fc29b 100644 --- a/compiler/rustc_ast_lowering/src/block.rs +++ b/compiler/rustc_ast_lowering/src/block.rs @@ -1,5 +1,5 @@ use rustc_ast::{Block, BlockCheckMode, Local, LocalKind, Stmt, StmtKind}; -use rustc_attr_ir::target::Target; +use rustc_attr_ir::target::{AstTarget, Target}; use rustc_hir as hir; use rustc_span::sym; use smallvec::SmallVec; @@ -37,7 +37,7 @@ impl<'hir> LoweringContext<'_, 'hir> { match &s.kind { StmtKind::Let(local) => { let hir_id = self.lower_node_id(s.id); - let local = self.lower_local(local); + let local = self.lower_local(local, &s); self.alias_attrs(hir_id, local.hir_id); let kind = hir::StmtKind::Let(local); let span = self.lower_span(s.span); @@ -88,7 +88,7 @@ impl<'hir> LoweringContext<'_, 'hir> { } } - fn lower_local(&mut self, l: &Local) -> &'hir hir::LetStmt<'hir> { + fn lower_local(&mut self, l: &Local, s: &Stmt) -> &'hir hir::LetStmt<'hir> { // Let statements are allowed to have impl trait in bindings. let super_ = l.super_.map(|span| self.lower_span(span)); let ty = l.ty.as_ref().map(|t| { @@ -104,7 +104,7 @@ impl<'hir> LoweringContext<'_, 'hir> { }; let span = self.lower_span(l.span); let source = hir::LocalSource::Normal; - self.lower_attrs(hir_id, &l.attrs, l.span, Target::Statement); + self.lower_attrs(hir_id, &l.attrs, l.span, Target::Statement, AstTarget::Statement(s)); self.arena.alloc(hir::LetStmt { hir_id, super_, ty, pat, init, els, span, source }) } diff --git a/compiler/rustc_ast_lowering/src/contract.rs b/compiler/rustc_ast_lowering/src/contract.rs index cbfeda33040e7..66c007813698d 100644 --- a/compiler/rustc_ast_lowering/src/contract.rs +++ b/compiler/rustc_ast_lowering/src/contract.rs @@ -1,7 +1,7 @@ use std::sync::Arc; use rustc_attr_ir::lang_items::LangItem; -use rustc_attr_ir::target::Target; +use rustc_attr_ir::target::{AstTarget, Target}; use rustc_span::sym; use thin_vec::thin_vec; @@ -62,8 +62,12 @@ impl<'hir> LoweringContext<'_, 'hir> { postcond_checker, ); - let wrapped_body = - self.wrap_body_with_contract_check(body, contract_check, postcond_checker.span); + let wrapped_body = self.wrap_body_with_contract_check( + body, + contract_check, + postcond_checker.span, + ens, + ); self.expr_block(wrapped_body) } (None, Some(ens)) => { @@ -92,8 +96,12 @@ impl<'hir> LoweringContext<'_, 'hir> { let contract_check = self.lower_contract_check_with_postcond(contract_decls, None, postcond_checker); - let wrapped_body = - self.wrap_body_with_contract_check(body, contract_check, postcond_checker.span); + let wrapped_body = self.wrap_body_with_contract_check( + body, + contract_check, + postcond_checker.span, + ens, + ); self.expr_block(wrapped_body) } (Some(req), None) => { @@ -238,6 +246,7 @@ impl<'hir> LoweringContext<'_, 'hir> { body: impl FnOnce(&mut Self) -> rustc_hir::Expr<'hir>, contract_check: &'hir rustc_hir::Expr<'hir>, postcond_span: rustc_span::Span, + ast_expr: &rustc_ast::Expr, ) -> &'hir rustc_hir::Block<'hir> { let check_ident: rustc_span::Ident = rustc_span::Ident::new(sym::__ensures_checker, postcond_span); @@ -266,7 +275,8 @@ impl<'hir> LoweringContext<'_, 'hir> { let body = self.arena.alloc(body(self)); // Finally, inject an ensures check on the implicit return of the body. - let body = self.inject_ensures_check(body, postcond_span, check_ident, check_hir_id); + let body = + self.inject_ensures_check(body, postcond_span, check_ident, check_hir_id, ast_expr); // Flatten the body into precond, then postcond, then wrapped body. let wrapped_body = self.block_all( @@ -282,14 +292,16 @@ impl<'hir> LoweringContext<'_, 'hir> { pub(super) fn checked_return( &mut self, opt_expr: Option<&'hir rustc_hir::Expr<'hir>>, + ast_expr: &rustc_ast::Expr, ) -> rustc_hir::ExprKind<'hir> { - let checked_ret = - if let Some((check_span, check_ident, check_hir_id)) = self.contract_ensures { - let expr = opt_expr.unwrap_or_else(|| self.expr_unit(check_span)); - Some(self.inject_ensures_check(expr, check_span, check_ident, check_hir_id)) - } else { - opt_expr - }; + let checked_ret = if let Some((check_span, check_ident, check_hir_id)) = + self.contract_ensures + { + let expr = opt_expr.unwrap_or_else(|| self.expr_unit(check_span)); + Some(self.inject_ensures_check(expr, check_span, check_ident, check_hir_id, ast_expr)) + } else { + opt_expr + }; rustc_hir::ExprKind::Ret(checked_ret) } @@ -300,6 +312,7 @@ impl<'hir> LoweringContext<'_, 'hir> { span: rustc_span::Span, cond_ident: rustc_span::Ident, cond_hir_id: rustc_hir::HirId, + ast_expr: &rustc_ast::Expr, ) -> &'hir rustc_hir::Expr<'hir> { // { // let ret = { body }; @@ -352,7 +365,13 @@ impl<'hir> LoweringContext<'_, 'hir> { )); let attrs: rustc_ast::AttrVec = thin_vec![self.unreachable_code_attr(span)]; - self.lower_attrs(contract_check.hir_id, &attrs, span, Target::Expression); + self.lower_attrs( + contract_check.hir_id, + &attrs, + span, + Target::Expression, + AstTarget::Expression(ast_expr), + ); let ret_block = self.block_all(span, arena_vec![self; ret_stmt], Some(contract_check)); self.arena.alloc(self.expr_block(self.arena.alloc(ret_block))) diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index f4bfec24e3b1b..42c4f451e4a8d 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -6,7 +6,7 @@ use rustc_ast::node_id::NodeMap; use rustc_ast::visit::{Visitor, walk_expr}; use rustc_ast::*; use rustc_attr_ir::lang_items::LangItem; -use rustc_attr_ir::target::Target; +use rustc_attr_ir::target::{AstTarget, Target}; use rustc_errors::msg; use rustc_hir as hir; use rustc_hir::HirId; @@ -231,7 +231,13 @@ impl<'hir> LoweringContext<'_, 'hir> { let old_attrs = self.curr_owner.attrs.get(&ex.hir_id.local_id).copied().unwrap_or(&[]); let new_attrs = self - .lower_attrs_vec(&e.attrs, e.span, ex.hir_id, Target::from_expr(e), None) + .lower_attrs_vec( + &e.attrs, + e.span, + ex.hir_id, + Target::from_expr(e), + AstTarget::Expression(e), + ) .into_iter() .chain(old_attrs.iter().cloned()); let new_attrs = &*self.arena.alloc_from_iter(new_attrs); @@ -255,7 +261,13 @@ impl<'hir> LoweringContext<'_, 'hir> { } let expr_hir_id = self.lower_node_id(e.id); - self.lower_attrs(expr_hir_id, &e.attrs, e.span, Target::from_expr(e)); + self.lower_attrs( + expr_hir_id, + &e.attrs, + e.span, + Target::from_expr(e), + AstTarget::Expression(e), + ); let kind = match &e.kind { ExprKind::Array(exprs) => hir::ExprKind::Array(self.lower_exprs(exprs)), @@ -480,11 +492,11 @@ impl<'hir> LoweringContext<'_, 'hir> { ExprKind::Continue(opt_label) => { hir::ExprKind::Continue(self.lower_jump_destination(e.id, *opt_label)) } - ExprKind::Ret(e) => { - let expr = e.as_ref().map(|x| self.lower_expr(x)); - self.checked_return(expr) + ExprKind::Ret(box_e) => { + let expr = box_e.as_ref().map(|x| self.lower_expr(x)); + self.checked_return(expr, e) } - ExprKind::Yeet(sub_expr) => self.lower_expr_yeet(e.span, sub_expr.as_deref()), + ExprKind::Yeet(sub_expr) => self.lower_expr_yeet(e.span, sub_expr.as_deref(), e), ExprKind::Become(sub_expr) => { let sub_expr = self.lower_expr(sub_expr); hir::ExprKind::Become(sub_expr) @@ -795,7 +807,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let guard = arm.guard.as_ref().map(|guard| self.lower_expr(&guard.cond)); let hir_id = self.next_id(); let span = self.lower_span(arm.span); - self.lower_attrs(hir_id, &arm.attrs, arm.span, Target::Arm); + self.lower_attrs(hir_id, &arm.attrs, arm.span, Target::Arm, AstTarget::Arm(arm)); let is_never_pattern = pat.is_never_pattern(); // We need to lower the body even if it's unneeded for never pattern in match, // ensure that we can get HirId for DefId if need (issue #137708). @@ -1659,7 +1671,7 @@ impl<'hir> LoweringContext<'_, 'hir> { fn lower_expr_field(&mut self, f: &ExprField) -> hir::ExprField<'hir> { let hir_id = self.lower_node_id(f.id); - self.lower_attrs(hir_id, &f.attrs, f.span, Target::ExprField); + self.lower_attrs(hir_id, &f.attrs, f.span, Target::ExprField, AstTarget::ExprField(f)); hir::ExprField { hir_id, ident: self.lower_ident(f.ident), @@ -1926,7 +1938,13 @@ impl<'hir> LoweringContext<'_, 'hir> { // // Also, add the attributes to the outer returned expr node. let expr = self.expr_drop_temps_mut(for_span, match_expr); - self.lower_attrs(expr.hir_id, &e.attrs, e.span, Target::from_expr(e)); + self.lower_attrs( + expr.hir_id, + &e.attrs, + e.span, + Target::from_expr(e), + AstTarget::Expression(e), + ); expr } @@ -1974,7 +1992,13 @@ impl<'hir> LoweringContext<'_, 'hir> { let val_ident = Ident::with_dummy_span(sym::val); let (val_pat, val_pat_nid) = self.pat_ident(span, val_ident); let val_expr = self.expr_ident(span, val_ident, val_pat_nid); - self.lower_attrs(val_expr.hir_id, &attrs, span, Target::Expression); + self.lower_attrs( + val_expr.hir_id, + &attrs, + span, + Target::Expression, + AstTarget::Expression(sub_expr), + ); let continue_pat = self.pat_cf_continue(unstable_span, val_pat); self.arm(continue_pat, val_expr, try_span) }; @@ -2013,10 +2037,16 @@ impl<'hir> LoweringContext<'_, 'hir> { ), )) } else { - let ret_expr = self.checked_return(Some(from_residual_expr)); + let ret_expr = self.checked_return(Some(from_residual_expr), sub_expr); self.arena.alloc(self.expr(try_span, ret_expr)) }; - self.lower_attrs(ret_expr.hir_id, &attrs, span, Target::Expression); + self.lower_attrs( + ret_expr.hir_id, + &attrs, + span, + Target::Expression, + AstTarget::Expression(sub_expr), + ); let break_pat = self.pat_cf_break(try_span, residual_local); self.arm(break_pat, ret_expr, try_span) @@ -2038,7 +2068,12 @@ impl<'hir> LoweringContext<'_, 'hir> { /// ``` /// But to simplify this, there's a `from_yeet` lang item function which /// handles the combined `FromResidual::from_residual(Yeet(residual))`. - fn lower_expr_yeet(&mut self, span: Span, sub_expr: Option<&Expr>) -> hir::ExprKind<'hir> { + fn lower_expr_yeet( + &mut self, + span: Span, + sub_expr: Option<&Expr>, + ast_expr: &rustc_ast::Expr, + ) -> hir::ExprKind<'hir> { // The expression (if present) or `()` otherwise. let (yeeted_span, yeeted_expr) = if let Some(sub_expr) = sub_expr { (sub_expr.span, self.lower_expr(sub_expr)) @@ -2066,7 +2101,7 @@ impl<'hir> LoweringContext<'_, 'hir> { Some(from_yeet_expr), ) } - TryBlockScope::Function => self.checked_return(Some(from_yeet_expr)), + TryBlockScope::Function => self.checked_return(Some(from_yeet_expr), ast_expr), } } diff --git a/compiler/rustc_ast_lowering/src/expr/closure.rs b/compiler/rustc_ast_lowering/src/expr/closure.rs index 5924d53dd11e4..808248db3204e 100644 --- a/compiler/rustc_ast_lowering/src/expr/closure.rs +++ b/compiler/rustc_ast_lowering/src/expr/closure.rs @@ -1,6 +1,6 @@ use rustc_ast::*; use rustc_attr_ir::find_attr; -use rustc_attr_ir::target::Target; +use rustc_attr_ir::target::{AstTarget, Target}; use rustc_hir as hir; use rustc_hir::HirId; use rustc_span::{Span, span_bug}; @@ -20,7 +20,13 @@ impl<'hir> LoweringContext<'_, 'hir> { closure: &Closure, ) -> hir::Expr<'hir> { let expr_hir_id = self.lower_node_id(e.id); - let attrs = self.lower_attrs(expr_hir_id, &e.attrs, e.span, Target::from_expr(e)); + let attrs = self.lower_attrs( + expr_hir_id, + &e.attrs, + e.span, + Target::from_expr(e), + AstTarget::Closure(closure), + ); match closure.coroutine_marker { Some(coroutine_marker) => self.lower_expr_coroutine_closure_with_move_exprs( diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index 9698ab0aedb83..3a871e85daa24 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -1,7 +1,7 @@ use rustc_abi::ExternAbi; use rustc_ast::visit::AssocCtxt; use rustc_ast::*; -use rustc_attr_ir::target::Target; +use rustc_attr_ir::target::{AstTarget, Target}; use rustc_attr_ir::{AttributeKind, EiiImplResolution, find_attr}; use rustc_errors::{E0570, ErrorGuaranteed, struct_span_code_err}; use rustc_hir::def::{DefKind, Res}; @@ -165,7 +165,7 @@ impl<'hir> LoweringContext<'_, 'hir> { &i.attrs, i.span, Target::from_ast_item(i), - Some(i), + AstTarget::from_ast_item(&i.kind), &extra_hir_attributes, ); @@ -614,8 +614,13 @@ impl<'hir> LoweringContext<'_, 'hir> { pub(super) fn lower_foreign_item(&mut self, i: &ForeignItem) -> &'hir hir::ForeignItem<'hir> { let owner_id = self.curr_owner.owner_id(); let hir_id: HirId = owner_id.into(); - let attrs = - self.lower_attrs(hir_id, &i.attrs, i.span, Target::from_foreign_item_kind(&i.kind)); + let attrs = self.lower_attrs( + hir_id, + &i.attrs, + i.span, + Target::from_foreign_item_kind(&i.kind), + AstTarget::from_foreign_item_kind(&i.kind), + ); let (ident, kind) = match &i.kind { ForeignItemKind::Fn(Fn { sig, ident, generics, define_opaque, .. }) => { let fdec = &sig.decl; @@ -693,7 +698,7 @@ impl<'hir> LoweringContext<'_, 'hir> { self.dcx().span_fatal(v.span, "unnamed enum variants are not yet implemented"); } let hir_id = self.lower_node_id(v.id); - self.lower_attrs(hir_id, &v.attrs, v.span, Target::Variant); + self.lower_attrs(hir_id, &v.attrs, v.span, Target::Variant, AstTarget::Variant(v)); hir::Variant { hir_id, def_id: self.local_def_id(v.id), @@ -780,7 +785,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let ty = self.lower_ty_alloc(&f.ty, ImplTraitContext::Disallowed(ImplTraitPosition::FieldTy)); let hir_id = self.lower_node_id(f.id); - self.lower_attrs(hir_id, &f.attrs, f.span, Target::Field); + self.lower_attrs(hir_id, &f.attrs, f.span, Target::Field, AstTarget::Field(f)); hir::FieldDef { span: self.lower_span(f.span), hir_id, @@ -808,6 +813,7 @@ impl<'hir> LoweringContext<'_, 'hir> { &i.attrs, i.span, Target::from_assoc_item_kind(&i.kind, AssocCtxt::Trait), + AstTarget::from_assoc_item_kind(&i.kind), ); let (ident, generics, kind, has_value) = match &i.kind { @@ -1070,6 +1076,7 @@ impl<'hir> LoweringContext<'_, 'hir> { &i.attrs, i.span, Target::from_assoc_item_kind(&i.kind, AssocCtxt::Impl { of_trait: is_in_trait_impl }), + AstTarget::from_assoc_item_kind(&i.kind), ); let (ident, (generics, kind)) = match &i.kind { @@ -1238,7 +1245,7 @@ impl<'hir> LoweringContext<'_, 'hir> { fn lower_param(&mut self, param: &Param) -> hir::Param<'hir> { let hir_id = self.lower_node_id(param.id); - self.lower_attrs(hir_id, ¶m.attrs, param.span, Target::Param); + self.lower_attrs(hir_id, ¶m.attrs, param.span, Target::Param, AstTarget::Param(param)); hir::Param { hir_id, pat: self.lower_pat(¶m.pat), @@ -1938,7 +1945,13 @@ impl<'hir> LoweringContext<'_, 'hir> { ) -> hir::WherePredicate<'hir> { let hir_id = self.lower_node_id(pred.id); let span = self.lower_span(pred.span); - self.lower_attrs(hir_id, &pred.attrs, span, Target::WherePredicate); + self.lower_attrs( + hir_id, + &pred.attrs, + span, + Target::WherePredicate, + AstTarget::WherePredicate(pred), + ); let kind = self.arena.alloc(match &pred.kind { WherePredicateKind::BoundPredicate(WhereBoundPredicate { bound_generic_params, diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index b6d1017665ec6..eac871388cce5 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -47,7 +47,7 @@ use rustc_ast::visit::{self, Visitor}; use rustc_ast::{self as ast, *}; use rustc_attr_ir::find_attr; use rustc_attr_ir::lang_items::LangItem; -use rustc_attr_ir::target::Target; +use rustc_attr_ir::target::{AstTarget, Target}; use rustc_attr_parsing::{AttributeParser, Recovery, ShouldEmit}; use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::sorted_map::SortedMap; @@ -755,7 +755,13 @@ fn lower_to_hir(tcx: TyCtxt<'_>, def_id: LocalDefId) -> hir::MaybeOwner<'_> { AstOwner::Crate(c) => with_lctx(tcx, &*resolver, CRATE_NODE_ID, |lctx| { debug_assert_eq!(lctx.curr_owner.owner_id(), CRATE_OWNER_ID); let module = lctx.lower_mod(&c.items, &c.spans); - lctx.lower_attrs(hir::CRATE_HIR_ID, &c.attrs, c.spans.inner_span, Target::Crate); + lctx.lower_attrs( + hir::CRATE_HIR_ID, + &c.attrs, + c.spans.inner_span, + Target::Crate, + AstTarget::Crate(c), + ); hir::OwnerNode::Crate(module) }), AstOwner::Item(item) => { @@ -1145,8 +1151,9 @@ impl<'hir> LoweringContext<'_, 'hir> { attrs: &[Attribute], target_span: Span, target: Target, + ast_target: AstTarget<'_>, ) -> &'hir [rustc_attr_ir::Attribute] { - self.lower_attrs_with_extra(id, attrs, target_span, target, None, &[]) + self.lower_attrs_with_extra(id, attrs, target_span, target, ast_target, &[]) } fn lower_attrs_with_extra( @@ -1155,14 +1162,14 @@ impl<'hir> LoweringContext<'_, 'hir> { attrs: &[Attribute], target_span: Span, target: Target, - target_item: Option<&ast::Item>, + ast_target: AstTarget<'_>, extra_hir_attributes: &[rustc_attr_ir::Attribute], ) -> &'hir [rustc_attr_ir::Attribute] { if attrs.is_empty() && extra_hir_attributes.is_empty() { &[] } else { let mut lowered_attrs = - self.lower_attrs_vec(attrs, self.lower_span(target_span), id, target, target_item); + self.lower_attrs_vec(attrs, self.lower_span(target_span), id, target, ast_target); lowered_attrs.extend(extra_hir_attributes.iter().cloned()); assert_eq!(id.owner, self.curr_owner.owner_id()); @@ -1189,14 +1196,14 @@ impl<'hir> LoweringContext<'_, 'hir> { target_span: Span, target_hir_id: HirId, target: Target, - target_item: Option<&ast::Item>, + ast_target: AstTarget<'_>, ) -> Vec { let l = self.span_lowerer(); self.attribute_parser.parse_attribute_list( attrs, target_span, target, - target_item, + ast_target, |s| l.lower(s), |lint_id, span, kind| { self.curr_owner.delayed_lints.push(DelayedLint { @@ -1955,7 +1962,13 @@ impl<'hir> LoweringContext<'_, 'hir> { // FIXME This uses `fn_hir_id`, which is not correct, it should use the parameter hir id instead // The parameter is currently not lowered for functions without bodies, so there is no place to store the lowered hir id // This should be fixed by storing function parameters in the `hir::FnSig` instead of `hir::Body` - self.lower_attrs(fn_hir_id, ¶m.attrs, param.span, Target::Param); + self.lower_attrs( + fn_hir_id, + ¶m.attrs, + param.span, + Target::Param, + AstTarget::Param(param), + ); } let itctx = match kind { FnDeclKind::Fn | FnDeclKind::Inherent | FnDeclKind::Impl | FnDeclKind::Trait => { @@ -2272,7 +2285,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let hir_id = self.lower_node_id(param.id); let param_attrs = ¶m.attrs; let param_span = param.span(); - let param = hir::GenericParam { + let param_hir = hir::GenericParam { hir_id, def_id: self.local_def_id(param.id), name, @@ -2282,8 +2295,14 @@ impl<'hir> LoweringContext<'_, 'hir> { colon_span: param.colon_span.map(|s| self.lower_span(s)), source, }; - self.lower_attrs(hir_id, param_attrs, param_span, Target::from(¶m)); - param + self.lower_attrs( + hir_id, + param_attrs, + param_span, + Target::from(¶m_hir), + AstTarget::GenericParam(param), + ); + param_hir } fn lower_generic_param_kind( @@ -2888,7 +2907,13 @@ impl<'hir> LoweringContext<'_, 'hir> { // FIXME(mgca): This might result in lowering attributes that // then go unused as the `Target::ExprField` is not actually // corresponding to `Node::ExprField`. - self.lower_attrs(hir_id, &f.attrs, f.span, Target::ExprField); + self.lower_attrs( + hir_id, + &f.attrs, + f.span, + Target::ExprField, + AstTarget::ExprField(f), + ); let expr = self.lower_expr_to_const_arg_direct(&f.expr, None); &*self.arena.alloc(hir::ConstArgExprField { diff --git a/compiler/rustc_ast_lowering/src/pat.rs b/compiler/rustc_ast_lowering/src/pat.rs index df3d7b1a3c0a6..cce1b7039e7b2 100644 --- a/compiler/rustc_ast_lowering/src/pat.rs +++ b/compiler/rustc_ast_lowering/src/pat.rs @@ -2,7 +2,7 @@ use std::sync::Arc; use rustc_ast::*; use rustc_attr_ir::lang_items::LangItem; -use rustc_attr_ir::target::Target; +use rustc_attr_ir::target::{AstTarget, Target}; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_span::{DesugaringKind, Ident, Span, Spanned, respan, span_bug}; @@ -92,7 +92,13 @@ impl<'hir> LoweringContext<'_, 'hir> { let fs = self.arena.alloc_from_iter(fields.iter().map(|f| { let hir_id = self.lower_node_id(f.id); - self.lower_attrs(hir_id, &f.attrs, f.span, Target::PatField); + self.lower_attrs( + hir_id, + &f.attrs, + f.span, + Target::PatField, + AstTarget::Pat(pattern), + ); hir::PatField { hir_id, diff --git a/compiler/rustc_attr_ir/src/target.rs b/compiler/rustc_attr_ir/src/target.rs index c41e78c4a96e0..180f03f60fc85 100644 --- a/compiler/rustc_attr_ir/src/target.rs +++ b/compiler/rustc_attr_ir/src/target.rs @@ -2,9 +2,76 @@ use std::fmt::{self, Display}; +use rustc_abi::ExternAbi; pub use rustc_ast::visit::AssocCtxt; -use rustc_ast::{AssocItemKind, ForeignItemKind, ast}; +use rustc_ast::{ + Arm, AssocItemKind, Closure, ConstBlockItem, ConstItem, Crate, EnumDef, Expr, ExprField, + FieldDef, Fn, ForeignItemKind, ForeignMod, GenericParam, Generics, Impl, InlineAsm, MacroDef, + ModKind, Param, Pat, Safety, StaticItem, Stmt, Trait, TraitAlias, TyAlias, UseTree, Variant, + VariantData, WherePredicate, ast, +}; use rustc_macros::StableHash; +use rustc_span::{Ident, Symbol}; + +/// This enum lists all possible types of AST items. +#[derive(Clone, Copy, Debug)] +pub enum AstTarget<'a> { + // Target types that may correspond to different kinds of items. + Delegation, + MacroCall, + + // Target types that correspond exclusively to `AssocItem` kind. Mapping is obtained from `Target::from_assoc_item_kind`. + AssocConst(&'a ConstItem), + Method(&'a Fn), + AssocTy(&'a TyAlias), + + // Target types that correspond exclusively to `ForeignItem` kind. Mapping is obtained from `Target::from_foreign_item_kind`. + ForeignStatic(&'a StaticItem), + ForeignFn(&'a Fn), + ForeignTy(&'a TyAlias), + + // Target types that correspond exclusively to `Item` kind. Mapping is obtained from `Target::from_ast_item`. + ExternCrate(&'a Option, &'a Ident), + Use(&'a UseTree), + Static(&'a StaticItem), + Const(ConstTypeAstTarget<'a>), + Fn(&'a Fn), + Mod(&'a Safety, &'a Ident, &'a ModKind), + ForeignMod(&'a ForeignMod), + GlobalAsm(&'a InlineAsm), + TyAlias(&'a TyAlias), + Enum(&'a Ident, &'a Generics, &'a EnumDef), + Struct(&'a Ident, &'a Generics, &'a VariantData), + Union(&'a Ident, &'a Generics, &'a VariantData), + Trait(&'a Trait), + TraitAlias(&'a TraitAlias), + Impl(&'a Impl), + MacroDef(&'a Ident, &'a MacroDef), + + // Target types that correspond exclusively to `Expr` kind. Mapping is obtained from `Target::from_expr`. + Closure(&'a Closure), + Expression(&'a Expr), + + Arm(&'a Arm), + Crate(&'a Crate), + ExprField(&'a ExprField), + Field(&'a FieldDef), + GenericParam(&'a GenericParam), + Param(&'a Param), + Pat(&'a Pat), + Statement(&'a Stmt), + Variant(&'a Variant), + WherePredicate(&'a WherePredicate), + + // Only reserved for cases when it is not possible to obtain detailed Ast Target + None, +} + +#[derive(Clone, Copy, Debug)] +pub enum ConstTypeAstTarget<'a> { + ConstItem(&'a ConstItem), + ConstBlockItem(&'a ConstBlockItem), +} #[derive(Copy, Clone, PartialEq, Debug, Eq, StableHash)] pub enum MethodKind { @@ -19,6 +86,8 @@ pub enum MethodKind { Inherent, } +// FIXME(rtjkro): `AstTarget` has nearly one-to-one mapping with `Target`, barring the extra fields from `AssocConst`, `Method`, and `AssocTy`. +// In the future, remove `Target` and use `AstTarget` instead. #[derive(Copy, Clone, PartialEq, Debug, Eq, StableHash)] pub enum Target { ExternCrate, @@ -65,6 +134,82 @@ pub enum Target { Break, } +impl<'a> AstTarget<'a> { + pub fn get_abi(&self) -> Option { + let ext = match self { + AstTarget::Method(fn_item) => fn_item.sig.header.ext, + AstTarget::Fn(fn_item) => fn_item.sig.header.ext, + AstTarget::ForeignFn(fn_item) => fn_item.sig.header.ext, + _ => return None, + }; + + match ext { + ast::Extern::None => Some(ExternAbi::Rust), + ast::Extern::Implicit(_) => Some(ExternAbi::FALLBACK), + ast::Extern::Explicit(abi, _) => Some(abi.symbol_unescaped.as_str().parse().ok()?), + } + } + + pub fn get_fn_sig(&self) -> Option<&rustc_ast::ast::FnSig> { + match self { + AstTarget::Method(fn_item) => Some(&fn_item.sig), + AstTarget::Fn(fn_item) => Some(&fn_item.sig), + AstTarget::ForeignFn(fn_item) => Some(&fn_item.sig), + _ => None, + } + } + + pub fn from_foreign_item_kind(kind: &'a ast::ForeignItemKind) -> Self { + match kind { + ForeignItemKind::Static(static_item) => AstTarget::ForeignStatic(static_item), + ForeignItemKind::Fn(f) => AstTarget::ForeignFn(f), + ForeignItemKind::TyAlias(ty_alias) => AstTarget::ForeignTy(ty_alias), + ForeignItemKind::MacCall(_) => AstTarget::MacroCall, + } + } + + pub fn from_assoc_item_kind(kind: &'a ast::AssocItemKind) -> Self { + match kind { + AssocItemKind::Const(const_item) => AstTarget::AssocConst(const_item), + AssocItemKind::Fn(f) => AstTarget::Method(f), + AssocItemKind::Type(type_alias) => AstTarget::AssocTy(type_alias), + AssocItemKind::Delegation(_) => AstTarget::Delegation, + AssocItemKind::DelegationMac(_) => AstTarget::Delegation, + AssocItemKind::MacCall(_) => AstTarget::MacroCall, + } + } + + pub fn from_ast_item(kind: &'a ast::ItemKind) -> Self { + match kind { + ast::ItemKind::ExternCrate(symbol, ident) => AstTarget::ExternCrate(symbol, ident), + ast::ItemKind::Use(use_tree) => AstTarget::Use(use_tree), + ast::ItemKind::Static(static_item) => AstTarget::Static(static_item), + ast::ItemKind::Const(const_item) => { + AstTarget::Const(ConstTypeAstTarget::ConstItem(const_item)) + } + ast::ItemKind::ConstBlock(const_block_item) => { + AstTarget::Const(ConstTypeAstTarget::ConstBlockItem(const_block_item)) + } + ast::ItemKind::Fn(f) => AstTarget::Fn(f), + ast::ItemKind::Mod(s, i, mk) => AstTarget::Mod(s, i, mk), + ast::ItemKind::ForeignMod(foreign_mod) => AstTarget::ForeignMod(foreign_mod), + ast::ItemKind::GlobalAsm(inline_asm) => AstTarget::GlobalAsm(inline_asm), + ast::ItemKind::TyAlias(ty_alias) => AstTarget::TyAlias(ty_alias), + ast::ItemKind::Enum(i, g, ed) => AstTarget::Enum(i, g, ed), + ast::ItemKind::Struct(i, g, vd) => AstTarget::Struct(i, g, vd), + ast::ItemKind::Union(i, g, vd) => AstTarget::Union(i, g, vd), + ast::ItemKind::Trait(trait_kind) => AstTarget::Trait(trait_kind), + ast::ItemKind::TraitAlias(trait_alias) => AstTarget::TraitAlias(trait_alias), + ast::ItemKind::Impl(i) => AstTarget::Impl(i), + ast::ItemKind::MacCall(..) => AstTarget::MacroCall, + ast::ItemKind::MacroDef(ident, macro_def) => AstTarget::MacroDef(ident, macro_def), + ast::ItemKind::Delegation(..) => AstTarget::Delegation, + ast::ItemKind::DelegationMac(..) => AstTarget::Delegation, + ast::ItemKind::TestBinderConstraints(..) => AstTarget::MacroCall, + } + } +} + impl Display for Target { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", Self::name(*self)) diff --git a/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs b/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs index 2553829f8c5ce..234e217d9f2c8 100644 --- a/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs +++ b/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs @@ -8,6 +8,7 @@ use rustc_structures::SanitizerSet; use super::prelude::*; use crate::attributes::AttributeSafety; +use crate::context::FinalizeCheckFn; use crate::diagnostics::{ EmptyExportName, EmptySection, NakedFunctionIncompatibleAttribute, NullOnExport, NullOnObjcClass, NullOnObjcSelector, NullOnSection, ObjcClassExpectedStringLiteral, @@ -327,6 +328,40 @@ impl AttributeParser for NakedParser { Some(AttributeKind::Naked(span)) } + + fn deferred_finalize_check(&self) -> Option<(FinalizeCheckFn, Span)> { + // FIXME(rtjkro): Currently, we're enum matching on `cx.target` instead of `cx.ast_target` + // because `AstTarget::Method` doesn't contain `MethodKind` yet. In the future, when this field is available to `AstTarget::Method`, + // update this check to use `cx.ast_target` instead of `cx.target`. + Some(( + |cx, _| match cx.target { + Target::Fn + | Target::Method( + MethodKind::Trait { body: true } | MethodKind::TraitImpl | MethodKind::Inherent, + ) => { + let fn_sig = + cx.ast_target.get_fn_sig().expect("missing fn signature for AST target"); + let Some(abi) = cx.ast_target.get_abi() else { + return; + }; + + if abi.is_rustic_abi() && !cx.features().naked_functions_rustic_abi() { + feature_err( + cx.sess(), + sym::naked_functions_rustic_abi, + fn_sig.span, + format!( + "`#[naked]` is currently unstable on `extern {abi}` functions", + ), + ) + .emit(); + } + } + _ => {} + }, + self.span?, + )) + } } pub(crate) struct TrackCallerParser; diff --git a/compiler/rustc_attr_parsing/src/attributes/link_attrs.rs b/compiler/rustc_attr_parsing/src/attributes/link_attrs.rs index ed911a63eb7fe..d5b2f7accb621 100644 --- a/compiler/rustc_attr_parsing/src/attributes/link_attrs.rs +++ b/compiler/rustc_attr_parsing/src/attributes/link_attrs.rs @@ -1,6 +1,6 @@ use rustc_abi::ExternAbi; -use rustc_ast::ItemKind; use rustc_attr_ir::AttributeKind::{LinkName, LinkOrdinal, LinkSection}; +use rustc_attr_ir::target::AstTarget; use rustc_attr_ir::*; use rustc_errors::msg; use rustc_feature::{AttributeStability, Features}; @@ -262,14 +262,10 @@ impl CombineAttributeParser for LinkParser { } fn finalize_check(cx: &mut FinalizeCheckContext<'_, '_>, attr_span: Span) { - if cx.target != Target::ForeignMod { + let AstTarget::ForeignMod(fm) = cx.ast_target else { return; - } - - let item = cx.target_item.expect("missing AST target item for Target::ForeignMod"); - let ItemKind::ForeignMod(fm) = &item.kind else { - panic!("expected foreign module AST target item for Target::ForeignMod"); }; + let abi = fm.abi.map_or(ExternAbi::FALLBACK, |abi| { abi.symbol_unescaped.as_str().parse().unwrap_or_else(|_| { cx.dcx().span_delayed_bug( diff --git a/compiler/rustc_attr_parsing/src/attributes/macro_attrs.rs b/compiler/rustc_attr_parsing/src/attributes/macro_attrs.rs index 8bb5e6b7fc270..8a0c31400b100 100644 --- a/compiler/rustc_attr_parsing/src/attributes/macro_attrs.rs +++ b/compiler/rustc_attr_parsing/src/attributes/macro_attrs.rs @@ -1,4 +1,4 @@ -use rustc_ast::ItemKind; +use rustc_attr_ir::target::AstTarget; use rustc_attr_ir::{MacroUseArgs, find_attr}; use rustc_feature::AttributeStability; use rustc_lint_defs::builtin::{INVALID_MACRO_EXPORT_ARGUMENTS, UNUSED_ATTRIBUTES}; @@ -181,14 +181,11 @@ impl SingleAttributeParser for MacroExportParser { } fn finalize_check(cx: &mut FinalizeCheckContext<'_, '_>, attr_span: Span) { - if cx.target != Target::MacroDef { + let AstTarget::MacroDef(_, macro_def) = cx.ast_target else { return; - } + }; - let item = cx.target_item.unwrap(); - if let ItemKind::MacroDef(_, macro_def) = &item.kind - && !macro_def.macro_rules - { + if !macro_def.macro_rules { cx.emit_lint(UNUSED_ATTRIBUTES, MacroExport::OnDeclMacro, attr_span); } } diff --git a/compiler/rustc_attr_parsing/src/attributes/non_exhaustive.rs b/compiler/rustc_attr_parsing/src/attributes/non_exhaustive.rs index 2acba84956e67..c2f8875e440e7 100644 --- a/compiler/rustc_attr_parsing/src/attributes/non_exhaustive.rs +++ b/compiler/rustc_attr_parsing/src/attributes/non_exhaustive.rs @@ -1,4 +1,5 @@ -use rustc_ast::{ItemKind, VariantData}; +use rustc_ast::VariantData; +use rustc_attr_ir::target::AstTarget; use rustc_feature::AttributeStability; use super::prelude::*; @@ -22,13 +23,8 @@ impl NoArgsAttributeParser for NonExhaustiveParser { const CREATE: fn(Span) -> AttributeKind = AttributeKind::NonExhaustive; fn finalize_check(cx: &mut FinalizeCheckContext<'_, '_>, attr_span: Span) { - if cx.target != Target::Struct { + let AstTarget::Struct(_, _, data) = cx.ast_target else { return; - } - - let item = cx.target_item.expect("missing AST target item for Target::Struct"); - let ItemKind::Struct(_, _, data) = &item.kind else { - panic!("expected struct AST target item for Target::Struct"); }; if let VariantData::Struct { fields, .. } = data && fields.iter().any(|f| f.default_value().is_some()) diff --git a/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs b/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs index b9c03883d7c0b..73f376bd39301 100644 --- a/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs +++ b/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs @@ -1,7 +1,8 @@ use std::path::PathBuf; -use rustc_ast::{GenericParamKind, ItemKind, LitIntType, LitKind, MetaItemLit}; +use rustc_ast::{GenericParamKind, LitIntType, LitKind, MetaItemLit}; use rustc_attr_ir::lang_items::LangItem; +use rustc_attr_ir::target::AstTarget; use rustc_attr_ir::{ BorrowckGraphvizFormatKind, CguFields, CguKind, RustcCleanAttribute, RustcCleanQueries, RustcMirKind, @@ -171,13 +172,8 @@ impl SingleAttributeParser for RustcLegacyConstGenericsParser { } fn finalize_check(cx: &mut FinalizeCheckContext<'_, '_>, attr_span: Span) { - if cx.target != Target::Fn { - // Invalid targets are already diagnosed by target checking. + let AstTarget::Fn(function) = cx.ast_target else { return; - } - let item = cx.target_item.expect("missing AST target item for Target::Fn"); - let ItemKind::Fn(function) = &item.kind else { - panic!("expected fn AST target item for Target::Fn"); }; let index_list = rustc_attr_ir::find_attr!(cx.parsed_attrs, RustcLegacyConstGenerics { fn_indexes, .. } => fn_indexes) .expect("missing parsed RustcLegacyConstGenerics attribute in finalize_check"); diff --git a/compiler/rustc_attr_parsing/src/context.rs b/compiler/rustc_attr_parsing/src/context.rs index 060fd74c1db21..f439193138261 100644 --- a/compiler/rustc_attr_parsing/src/context.rs +++ b/compiler/rustc_attr_parsing/src/context.rs @@ -855,9 +855,8 @@ pub(crate) struct FinalizeCheckContext<'p, 'sess> { /// Unlike [`all_attrs`](Self::all_attrs), this contains the fully parsed attributes. pub(crate) parsed_attrs: &'p [Attribute], - /// The AST item these attributes were applied to, when the target is an item. - /// Used by `finalize_check` to inspect item structure that is not encoded in [`Target`]. - pub(crate) target_item: Option<&'p rustc_ast::ast::Item>, + /// The AST item these attributes were applied to. + pub(crate) ast_target: rustc_attr_ir::target::AstTarget<'p>, } impl<'p, 'sess: 'p> Deref for FinalizeCheckContext<'p, 'sess> { diff --git a/compiler/rustc_attr_parsing/src/interface.rs b/compiler/rustc_attr_parsing/src/interface.rs index 4ce284a0a9d5a..42cd5a4190dfa 100644 --- a/compiler/rustc_attr_parsing/src/interface.rs +++ b/compiler/rustc_attr_parsing/src/interface.rs @@ -6,7 +6,7 @@ use std::sync::atomic::{AtomicBool, Ordering}; use rustc_ast as ast; use rustc_ast::token::DocFragmentKind; use rustc_ast::{AttrStyle, CRATE_NODE_ID, NodeId, Safety}; -use rustc_attr_ir::target::Target; +use rustc_attr_ir::target::{AstTarget, Target}; use rustc_attr_ir::{AttrArgs, AttrItem, AttrPath, Attribute, AttributeKind, HashIgnoredAttrId}; use rustc_data_structures::sync::{DynSend, DynSync}; use rustc_errors::{Diag, DiagCtxtHandle, Diagnostic, Level, MultiSpan}; @@ -161,7 +161,7 @@ impl<'sess> AttributeParser<'sess> { attrs, target_span, target, - None, + AstTarget::None, std::convert::identity, |lint_id, span, kind| { sess.psess.dyn_buffer_lint_sess(lint_id.lint, span, target_node_id, kind.0) @@ -317,7 +317,7 @@ impl<'sess> AttributeParser<'sess> { attrs: &[ast::Attribute], target_span: Span, target: Target, - target_item: Option<&ast::Item>, + ast_target: AstTarget<'_>, lower_span: impl Copy + Fn(Span) -> Span, mut emit_lint: impl FnMut(LintId, MultiSpan, EmitAttribute), ) -> Vec { @@ -525,7 +525,7 @@ impl<'sess> AttributeParser<'sess> { }, all_attrs: &attr_paths, parsed_attrs: &attributes, - target_item, + ast_target, }, attr_span, ); diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 3eb6892177b05..c5cd132573273 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -38,7 +38,6 @@ use rustc_middle::query::Providers; use rustc_middle::traits::ObligationCause; use rustc_middle::ty::error::{ExpectedFound, TypeError}; use rustc_middle::ty::{self, TyCtxt, TypingMode, Unnormalized}; -use rustc_session::diagnostics::feature_err; use rustc_span::edition::Edition; use rustc_span::{DUMMY_SP, Ident, Span, Symbol, bug, kw, span_bug, sym}; use rustc_structures::CrateType; @@ -201,7 +200,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> { AttributeKind::RustcAllowConstFnUnstable(_, first_span) => { self.check_rustc_allow_const_fn_unstable(hir_id, *first_span, span, target) } - AttributeKind::Naked(..) => self.check_naked(hir_id, target), AttributeKind::MayDangle(attr_span) => self.check_may_dangle(hir_id, *attr_span), AttributeKind::Doc(attr) => self.check_doc_attrs(attr, hir_id, target), AttributeKind::EiiImpl(eii_impl) => self.check_eii_impl(eii_impl), @@ -272,6 +270,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { AttributeKind::MoveSizeLimit { .. } => (), AttributeKind::MustNotSupend { .. } => (), AttributeKind::MustUse { .. } => (), + AttributeKind::Naked(..) => (), AttributeKind::NeedsAllocator => (), AttributeKind::NeedsPanicRuntime => (), AttributeKind::NoBuiltins => (), @@ -732,32 +731,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> { } } - /// Checks if `#[naked]` is applied to a function definition. - fn check_naked(&self, hir_id: HirId, target: Target) { - match target { - Target::Fn - | Target::Method( - MethodKind::Trait { body: true } | MethodKind::TraitImpl | MethodKind::Inherent, - ) => { - let fn_sig = self.tcx.hir_node(hir_id).fn_sig().unwrap(); - let abi = fn_sig.header.abi; - if abi.is_rustic_abi() && !self.tcx.features().naked_functions_rustic_abi() { - feature_err( - &self.tcx.sess, - sym::naked_functions_rustic_abi, - fn_sig.span, - format!( - "`#[naked]` is currently unstable on `extern \"{}\"` functions", - abi.as_str() - ), - ) - .emit(); - } - } - _ => {} - } - } - fn check_doc_alias_value(&self, span: Span, hir_id: HirId, target: Target, alias: Symbol) { if let Some(location) = match target { Target::AssocTy(_) => { diff --git a/compiler/rustc_resolve/src/def_collector.rs b/compiler/rustc_resolve/src/def_collector.rs index f3329c3d0398e..b55a3534bb28f 100644 --- a/compiler/rustc_resolve/src/def_collector.rs +++ b/compiler/rustc_resolve/src/def_collector.rs @@ -2,7 +2,7 @@ use std::mem; use rustc_ast::visit::FnKind; use rustc_ast::*; -use rustc_attr_ir::target::Target; +use rustc_attr_ir::target::{AstTarget, Target}; use rustc_attr_parsing::{AttributeParser, ShouldEmit}; use rustc_expand::expand::AstFragment; use rustc_hir as hir; @@ -183,7 +183,7 @@ impl<'a, 'ra, 'tcx> visit::Visitor<'a> for DefCollector<'a, 'ra, 'tcx> { &i.attrs, i.span, Target::MacroDef, - None, + AstTarget::from_ast_item(&i.kind), std::convert::identity, |_lint_id, _span, _kind| { // FIXME(jdonszelmann): emit lints here properly