From c3de4b3aad6a2be86d4711086267e21660bf2b23 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sun, 2 Jun 2024 12:40:07 +0000 Subject: [PATCH 01/17] Handle all GVN binops in a single place. --- compiler/rustc_mir_transform/src/gvn.rs | 70 ++++++++++++++----------- 1 file changed, 40 insertions(+), 30 deletions(-) diff --git a/compiler/rustc_mir_transform/src/gvn.rs b/compiler/rustc_mir_transform/src/gvn.rs index fadb5edefdfb1..548e4e309360e 100644 --- a/compiler/rustc_mir_transform/src/gvn.rs +++ b/compiler/rustc_mir_transform/src/gvn.rs @@ -223,7 +223,6 @@ enum Value<'tcx> { NullaryOp(NullOp<'tcx>, Ty<'tcx>), UnaryOp(UnOp, VnIndex), BinaryOp(BinOp, VnIndex, VnIndex), - CheckedBinaryOp(BinOp, VnIndex, VnIndex), // FIXME get rid of this, work like MIR instead Cast { kind: CastKind, value: VnIndex, @@ -508,17 +507,6 @@ impl<'body, 'tcx> VnState<'body, 'tcx> { let val = self.ecx.binary_op(bin_op, &lhs, &rhs).ok()?; val.into() } - CheckedBinaryOp(bin_op, lhs, rhs) => { - let lhs = self.evaluated[lhs].as_ref()?; - let lhs = self.ecx.read_immediate(lhs).ok()?; - let rhs = self.evaluated[rhs].as_ref()?; - let rhs = self.ecx.read_immediate(rhs).ok()?; - let val = self - .ecx - .binary_op(bin_op.wrapping_to_overflowing().unwrap(), &lhs, &rhs) - .ok()?; - val.into() - } Cast { kind, value, from: _, to } => match kind { CastKind::IntToInt | CastKind::IntToFloat => { let value = self.evaluated[value].as_ref()?; @@ -829,17 +817,10 @@ impl<'body, 'tcx> VnState<'body, 'tcx> { let lhs = lhs?; let rhs = rhs?; - if let Some(op) = op.overflowing_to_wrapping() { - if let Some(value) = self.simplify_binary(op, true, ty, lhs, rhs) { - return Some(value); - } - Value::CheckedBinaryOp(op, lhs, rhs) - } else { - if let Some(value) = self.simplify_binary(op, false, ty, lhs, rhs) { - return Some(value); - } - Value::BinaryOp(op, lhs, rhs) + if let Some(value) = self.simplify_binary(op, ty, lhs, rhs) { + return Some(value); } + Value::BinaryOp(op, lhs, rhs) } Rvalue::UnaryOp(op, ref mut arg) => { let arg = self.simplify_operand(arg, location)?; @@ -970,7 +951,6 @@ impl<'body, 'tcx> VnState<'body, 'tcx> { fn simplify_binary( &mut self, op: BinOp, - checked: bool, lhs_ty: Ty<'tcx>, lhs: VnIndex, rhs: VnIndex, @@ -999,22 +979,39 @@ impl<'body, 'tcx> VnState<'body, 'tcx> { use Either::{Left, Right}; let a = as_bits(lhs).map_or(Right(lhs), Left); let b = as_bits(rhs).map_or(Right(rhs), Left); + let result = match (op, a, b) { // Neutral elements. - (BinOp::Add | BinOp::BitOr | BinOp::BitXor, Left(0), Right(p)) + ( + BinOp::Add + | BinOp::AddWithOverflow + | BinOp::AddUnchecked + | BinOp::BitOr + | BinOp::BitXor, + Left(0), + Right(p), + ) | ( BinOp::Add + | BinOp::AddWithOverflow + | BinOp::AddUnchecked | BinOp::BitOr | BinOp::BitXor | BinOp::Sub + | BinOp::SubWithOverflow + | BinOp::SubUnchecked | BinOp::Offset | BinOp::Shl | BinOp::Shr, Right(p), Left(0), ) - | (BinOp::Mul, Left(1), Right(p)) - | (BinOp::Mul | BinOp::Div, Right(p), Left(1)) => p, + | (BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked, Left(1), Right(p)) + | ( + BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked | BinOp::Div, + Right(p), + Left(1), + ) => p, // Attempt to simplify `x & ALL_ONES` to `x`, with `ALL_ONES` depending on type size. (BinOp::BitAnd, Right(p), Left(ones)) | (BinOp::BitAnd, Left(ones), Right(p)) if ones == layout.size.truncate(u128::MAX) @@ -1023,10 +1020,21 @@ impl<'body, 'tcx> VnState<'body, 'tcx> { p } // Absorbing elements. - (BinOp::Mul | BinOp::BitAnd, _, Left(0)) + ( + BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked | BinOp::BitAnd, + _, + Left(0), + ) | (BinOp::Rem, _, Left(1)) | ( - BinOp::Mul | BinOp::Div | BinOp::Rem | BinOp::BitAnd | BinOp::Shl | BinOp::Shr, + BinOp::Mul + | BinOp::MulWithOverflow + | BinOp::MulUnchecked + | BinOp::Div + | BinOp::Rem + | BinOp::BitAnd + | BinOp::Shl + | BinOp::Shr, Left(0), _, ) => self.insert_scalar(Scalar::from_uint(0u128, layout.size), lhs_ty), @@ -1038,7 +1046,9 @@ impl<'body, 'tcx> VnState<'body, 'tcx> { self.insert_scalar(Scalar::from_uint(ones, layout.size), lhs_ty) } // Sub/Xor with itself. - (BinOp::Sub | BinOp::BitXor, a, b) if a == b => { + (BinOp::Sub | BinOp::SubWithOverflow | BinOp::SubUnchecked | BinOp::BitXor, a, b) + if a == b => + { self.insert_scalar(Scalar::from_uint(0u128, layout.size), lhs_ty) } // Comparison: @@ -1052,7 +1062,7 @@ impl<'body, 'tcx> VnState<'body, 'tcx> { _ => return None, }; - if checked { + if op.is_overflowing() { let false_val = self.insert_bool(false); Some(self.insert_tuple(vec![result, false_val])) } else { From 92f85f12a82ac23b794dcdd58a76b0ae7519951c Mon Sep 17 00:00:00 2001 From: onur-ozkan Date: Mon, 3 Jun 2024 06:58:30 +0300 Subject: [PATCH 02/17] wipe bootstrap build before switching to bumped rustc Technically, wiping bootstrap builds can increase the build time. But in practice, trying to manually resolve post-bump issues and even accidentally removing the entire build directory will result in a much greater loss of time. After all, the bootstrap build process is not a particularly lengthy operation. Signed-off-by: onur-ozkan --- src/bootstrap/bootstrap.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/src/bootstrap/bootstrap.py b/src/bootstrap/bootstrap.py index e60e8f0aa1f70..9861121aac0a3 100644 --- a/src/bootstrap/bootstrap.py +++ b/src/bootstrap/bootstrap.py @@ -599,6 +599,12 @@ def download_toolchain(self): print('Choosing a pool size of', pool_size, 'for the unpacking of the tarballs') p = Pool(pool_size) try: + # FIXME: A cheap workaround for https://github.com/rust-lang/rust/issues/125578, + # remove this once the issue is closed. + bootstrap_out = self.bootstrap_out() + if os.path.exists(bootstrap_out): + shutil.rmtree(bootstrap_out) + p.map(unpack_component, tarballs_download_info) finally: p.close() @@ -864,6 +870,16 @@ def get_string(line): return line[start + 1:end] return None + def bootstrap_out(self): + """Return the path of the bootstrap build artifacts + + >>> rb = RustBuild() + >>> rb.build_dir = "build" + >>> rb.bootstrap_binary() == os.path.join("build", "bootstrap") + True + """ + return os.path.join(self.build_dir, "bootstrap") + def bootstrap_binary(self): """Return the path of the bootstrap binary @@ -873,7 +889,7 @@ def bootstrap_binary(self): ... "debug", "bootstrap") True """ - return os.path.join(self.build_dir, "bootstrap", "debug", "bootstrap") + return os.path.join(self.bootstrap_out(), "debug", "bootstrap") def build_bootstrap(self): """Build bootstrap""" From f152e2cc3f76d8876263f3b7f1f03ba0d145d20a Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Mon, 3 Jun 2024 08:38:40 +0000 Subject: [PATCH 03/17] Revert "Cache whether a body has inline consts" This reverts commit eae5031ecbda434e92966099e0dc93917de03eff. --- compiler/rustc_ast_lowering/src/expr.rs | 5 +---- compiler/rustc_ast_lowering/src/lib.rs | 8 +------- compiler/rustc_hir/src/hir.rs | 3 --- compiler/rustc_hir/src/stable_hash_impls.rs | 3 +-- compiler/rustc_middle/src/ty/context.rs | 1 - compiler/rustc_mir_transform/src/lib.rs | 6 +----- 6 files changed, 4 insertions(+), 22 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index eb206a09be313..c0a424115aadf 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -74,10 +74,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let kind = match &e.kind { ExprKind::Array(exprs) => hir::ExprKind::Array(self.lower_exprs(exprs)), - ExprKind::ConstBlock(c) => { - self.has_inline_consts = true; - hir::ExprKind::ConstBlock(self.lower_expr(c)) - } + ExprKind::ConstBlock(c) => hir::ExprKind::ConstBlock(self.lower_expr(c)), ExprKind::Repeat(expr, count) => { let expr = self.lower_expr(expr); let count = self.lower_array_length(count); diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 5a80fa803f840..201dffb629a16 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -96,8 +96,6 @@ struct LoweringContext<'a, 'hir> { /// Bodies inside the owner being lowered. bodies: Vec<(hir::ItemLocalId, &'hir hir::Body<'hir>)>, - /// Whether there were inline consts that typeck will split out into bodies - has_inline_consts: bool, /// Attributes inside the owner being lowered. attrs: SortedMap, /// Collect items that were created by lowering the current owner. @@ -160,7 +158,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { item_local_id_counter: hir::ItemLocalId::ZERO, node_id_to_local_id: Default::default(), trait_map: Default::default(), - has_inline_consts: false, // Lowering state. catch_scope: None, @@ -570,7 +567,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let current_attrs = std::mem::take(&mut self.attrs); let current_bodies = std::mem::take(&mut self.bodies); - let current_has_inline_consts = std::mem::take(&mut self.has_inline_consts); let current_node_ids = std::mem::take(&mut self.node_id_to_local_id); let current_trait_map = std::mem::take(&mut self.trait_map); let current_owner = @@ -597,7 +593,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { self.attrs = current_attrs; self.bodies = current_bodies; - self.has_inline_consts = current_has_inline_consts; self.node_id_to_local_id = current_node_ids; self.trait_map = current_trait_map; self.current_hir_id_owner = current_owner; @@ -634,7 +629,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let attrs = std::mem::take(&mut self.attrs); let mut bodies = std::mem::take(&mut self.bodies); let trait_map = std::mem::take(&mut self.trait_map); - let has_inline_consts = std::mem::take(&mut self.has_inline_consts); #[cfg(debug_assertions)] for (id, attrs) in attrs.iter() { @@ -652,7 +646,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { self.tcx.hash_owner_nodes(node, &bodies, &attrs); let num_nodes = self.item_local_id_counter.as_usize(); let (nodes, parenting) = index::index_hir(self.tcx, node, &bodies, num_nodes); - let nodes = hir::OwnerNodes { opt_hash_including_bodies, nodes, bodies, has_inline_consts }; + let nodes = hir::OwnerNodes { opt_hash_including_bodies, nodes, bodies }; let attrs = hir::AttributeMap { map: attrs, opt_hash: attrs_hash }; self.arena.alloc(hir::OwnerInfo { nodes, parenting, attrs, trait_map }) diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index e971d0e3c1435..a5c666dfac41c 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -907,9 +907,6 @@ pub struct OwnerNodes<'tcx> { pub nodes: IndexVec>, /// Content of local bodies. pub bodies: SortedMap>, - /// Whether the body contains inline constants that are created for the query system during typeck - /// of the body. - pub has_inline_consts: bool, } impl<'tcx> OwnerNodes<'tcx> { diff --git a/compiler/rustc_hir/src/stable_hash_impls.rs b/compiler/rustc_hir/src/stable_hash_impls.rs index 1ebd4b80e1835..baa1635f7313f 100644 --- a/compiler/rustc_hir/src/stable_hash_impls.rs +++ b/compiler/rustc_hir/src/stable_hash_impls.rs @@ -93,8 +93,7 @@ impl<'tcx, HirCtx: crate::HashStableContext> HashStable for OwnerNodes<' // `local_id_to_def_id` is also ignored because is dependent on the body, then just hashing // the body satisfies the condition of two nodes being different have different // `hash_stable` results. - let OwnerNodes { opt_hash_including_bodies, nodes: _, bodies: _, has_inline_consts: _ } = - *self; + let OwnerNodes { opt_hash_including_bodies, nodes: _, bodies: _ } = *self; opt_hash_including_bodies.unwrap().hash_stable(hcx, hasher); } } diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 47f66c6440627..86d2a230f305c 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -743,7 +743,6 @@ impl<'tcx> TyCtxtFeed<'tcx, LocalDefId> { 1, ), bodies, - has_inline_consts: false, }))); self.feed_owner_id().hir_attrs(attrs); } diff --git a/compiler/rustc_mir_transform/src/lib.rs b/compiler/rustc_mir_transform/src/lib.rs index a8741254ffbf7..b66e3d66f4d3e 100644 --- a/compiler/rustc_mir_transform/src/lib.rs +++ b/compiler/rustc_mir_transform/src/lib.rs @@ -225,11 +225,7 @@ fn mir_keys(tcx: TyCtxt<'_>, (): ()) -> FxIndexSet { // Inline consts' bodies are created in // typeck instead of during ast lowering, like all other bodies so far. for def_id in tcx.hir().body_owners() { - // Incremental performance optimization: only load typeck results for things that actually have inline consts - if tcx.hir_owner_nodes(tcx.hir().body_owned_by(def_id).id().hir_id.owner).has_inline_consts - { - set.extend(tcx.typeck(def_id).inline_consts.values()) - } + set.extend(tcx.typeck(def_id).inline_consts.values()) } // Additionally, tuple struct/variant constructors have MIR, but From c9e50ae7a1fecefa11e16feb48c93dd8a18431dd Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Mon, 3 Jun 2024 09:11:58 +0000 Subject: [PATCH 04/17] Revert "Create const block DefIds in typeck instead of ast lowering" This reverts commit ddc5f9b6c1f21da5d4596bf7980185a00984ac42. --- compiler/rustc_ast/src/ast.rs | 2 +- compiler/rustc_ast/src/mut_visit.rs | 2 +- compiler/rustc_ast/src/visit.rs | 2 +- compiler/rustc_ast_lowering/src/expr.rs | 9 +++- compiler/rustc_ast_lowering/src/index.rs | 8 ++++ .../rustc_ast_pretty/src/pprust/state/expr.rs | 5 +-- .../src/const_eval/fn_queries.rs | 2 +- compiler/rustc_hir/src/hir.rs | 14 ++++++- compiler/rustc_hir/src/intravisit.rs | 13 +++++- .../rustc_hir_analysis/src/check/region.rs | 7 +--- .../src/collect/generics_of.rs | 10 ++--- .../rustc_hir_analysis/src/collect/type_of.rs | 3 +- compiler/rustc_hir_analysis/src/lib.rs | 8 ++-- compiler/rustc_hir_pretty/src/lib.rs | 5 ++- compiler/rustc_hir_typeck/src/expr.rs | 21 +++++++++- .../src/fn_ctxt/suggestions.rs | 4 -- compiler/rustc_hir_typeck/src/upvar.rs | 4 ++ compiler/rustc_hir_typeck/src/writeback.rs | 13 +++--- compiler/rustc_middle/src/hir/map/mod.rs | 42 ++++++------------- .../rustc_middle/src/ty/typeck_results.rs | 5 --- compiler/rustc_mir_build/src/build/mod.rs | 7 +++- compiler/rustc_mir_build/src/thir/cx/expr.rs | 6 +-- compiler/rustc_mir_build/src/thir/cx/mod.rs | 2 +- .../rustc_mir_build/src/thir/pattern/mod.rs | 8 ++-- compiler/rustc_mir_transform/src/lib.rs | 6 --- compiler/rustc_parse/src/parser/mod.rs | 13 +++--- compiler/rustc_passes/src/check_const.rs | 10 ++--- compiler/rustc_passes/src/dead.rs | 21 +++++----- compiler/rustc_passes/src/liveness.rs | 8 +--- compiler/rustc_passes/src/loops.rs | 7 ++-- compiler/rustc_resolve/src/def_collector.rs | 10 +++++ compiler/rustc_resolve/src/late.rs | 6 +-- src/tools/clippy/clippy_utils/src/consts.rs | 6 +-- .../clippy/clippy_utils/src/hir_utils.rs | 6 +-- .../tests/ui/arithmetic_side_effects.stderr | 32 ++------------ .../custom/consts.consts.built.after.mir | 2 +- tests/pretty/stmt_expr_attributes.rs | 7 +++- tests/ui/lint/non-local-defs/consts.stderr | 19 +++++---- tests/ui/unpretty/expanded-exhaustive.stdout | 3 +- 39 files changed, 190 insertions(+), 168 deletions(-) diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index 7a45d909d0779..8e801ebc2f912 100644 --- a/compiler/rustc_ast/src/ast.rs +++ b/compiler/rustc_ast/src/ast.rs @@ -1392,7 +1392,7 @@ pub enum ExprKind { /// An array (e.g, `[a, b, c, d]`). Array(ThinVec>), /// Allow anonymous constants from an inline `const` block - ConstBlock(P), + ConstBlock(AnonConst), /// A function call /// /// The first field resolves to the function itself, diff --git a/compiler/rustc_ast/src/mut_visit.rs b/compiler/rustc_ast/src/mut_visit.rs index 5c581c270e498..635f0f0345039 100644 --- a/compiler/rustc_ast/src/mut_visit.rs +++ b/compiler/rustc_ast/src/mut_visit.rs @@ -1411,7 +1411,7 @@ pub fn noop_visit_expr( match kind { ExprKind::Array(exprs) => visit_thin_exprs(exprs, vis), ExprKind::ConstBlock(anon_const) => { - vis.visit_expr(anon_const); + vis.visit_anon_const(anon_const); } ExprKind::Repeat(expr, count) => { vis.visit_expr(expr); diff --git a/compiler/rustc_ast/src/visit.rs b/compiler/rustc_ast/src/visit.rs index b2f3b27c77e90..247053550d286 100644 --- a/compiler/rustc_ast/src/visit.rs +++ b/compiler/rustc_ast/src/visit.rs @@ -954,7 +954,7 @@ pub fn walk_expr<'a, V: Visitor<'a>>(visitor: &mut V, expression: &'a Expr) -> V ExprKind::Array(subexpressions) => { walk_list!(visitor, visit_expr, subexpressions); } - ExprKind::ConstBlock(anon_const) => try_visit!(visitor.visit_expr(anon_const)), + ExprKind::ConstBlock(anon_const) => try_visit!(visitor.visit_anon_const(anon_const)), ExprKind::Repeat(element, count) => { try_visit!(visitor.visit_expr(element)); try_visit!(visitor.visit_anon_const(count)); diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index c0a424115aadf..a553109092842 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -74,7 +74,14 @@ impl<'hir> LoweringContext<'_, 'hir> { let kind = match &e.kind { ExprKind::Array(exprs) => hir::ExprKind::Array(self.lower_exprs(exprs)), - ExprKind::ConstBlock(c) => hir::ExprKind::ConstBlock(self.lower_expr(c)), + ExprKind::ConstBlock(c) => { + let c = self.with_new_scopes(c.value.span, |this| hir::ConstBlock { + def_id: this.local_def_id(c.id), + hir_id: this.lower_node_id(c.id), + body: this.lower_const_body(c.value.span, Some(&c.value)), + }); + hir::ExprKind::ConstBlock(c) + } ExprKind::Repeat(expr, count) => { let expr = self.lower_expr(expr); let count = self.lower_array_length(count); diff --git a/compiler/rustc_ast_lowering/src/index.rs b/compiler/rustc_ast_lowering/src/index.rs index 741a44eb0c523..44f37b5533a67 100644 --- a/compiler/rustc_ast_lowering/src/index.rs +++ b/compiler/rustc_ast_lowering/src/index.rs @@ -236,6 +236,14 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { }); } + fn visit_inline_const(&mut self, constant: &'hir ConstBlock) { + self.insert(DUMMY_SP, constant.hir_id, Node::ConstBlock(constant)); + + self.with_parent(constant.hir_id, |this| { + intravisit::walk_inline_const(this, constant); + }); + } + fn visit_expr(&mut self, expr: &'hir Expr<'hir>) { self.insert(expr.span, expr.hir_id, Node::Expr(expr)); diff --git a/compiler/rustc_ast_pretty/src/pprust/state/expr.rs b/compiler/rustc_ast_pretty/src/pprust/state/expr.rs index 993ccc5b95609..1e117c46b6e29 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state/expr.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state/expr.rs @@ -380,9 +380,8 @@ impl<'a> State<'a> { ast::ExprKind::Array(exprs) => { self.print_expr_vec(exprs); } - ast::ExprKind::ConstBlock(expr) => { - self.word_space("const"); - self.print_expr(expr, FixupContext::default()); + ast::ExprKind::ConstBlock(anon_const) => { + self.print_expr_anon_const(anon_const, attrs); } ast::ExprKind::Repeat(element, count) => { self.print_expr_repeat(element, count); diff --git a/compiler/rustc_const_eval/src/const_eval/fn_queries.rs b/compiler/rustc_const_eval/src/const_eval/fn_queries.rs index 3c11d67e74890..8c66888d1007e 100644 --- a/compiler/rustc_const_eval/src/const_eval/fn_queries.rs +++ b/compiler/rustc_const_eval/src/const_eval/fn_queries.rs @@ -38,6 +38,7 @@ fn constness(tcx: TyCtxt<'_>, def_id: LocalDefId) -> hir::Constness { match node { hir::Node::Ctor(_) | hir::Node::AnonConst(_) + | hir::Node::ConstBlock(_) | hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Const(..), .. }) => { hir::Constness::Const } @@ -56,7 +57,6 @@ fn constness(tcx: TyCtxt<'_>, def_id: LocalDefId) -> hir::Constness { if is_const { hir::Constness::Const } else { hir::Constness::NotConst } } hir::Node::Expr(e) if let hir::ExprKind::Closure(c) = e.kind => c.constness, - hir::Node::Expr(e) if let hir::ExprKind::ConstBlock(_) = e.kind => hir::Constness::Const, _ => { if let Some(fn_kind) = node.fn_kind() { if fn_kind.constness() == hir::Constness::Const { diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index a5c666dfac41c..ed344255a5eda 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -1623,6 +1623,14 @@ pub struct AnonConst { pub span: Span, } +/// An inline constant expression `const { something }`. +#[derive(Copy, Clone, Debug, HashStable_Generic)] +pub struct ConstBlock { + pub hir_id: HirId, + pub def_id: LocalDefId, + pub body: BodyId, +} + /// An expression. #[derive(Debug, Clone, Copy, HashStable_Generic)] pub struct Expr<'hir> { @@ -1909,7 +1917,7 @@ pub fn is_range_literal(expr: &Expr<'_>) -> bool { #[derive(Debug, Clone, Copy, HashStable_Generic)] pub enum ExprKind<'hir> { /// Allow anonymous constants from an inline `const` block - ConstBlock(&'hir Expr<'hir>), + ConstBlock(ConstBlock), /// An array (e.g., `[a, b, c, d]`). Array(&'hir [Expr<'hir>]), /// A function call. @@ -3641,6 +3649,7 @@ pub enum Node<'hir> { Variant(&'hir Variant<'hir>), Field(&'hir FieldDef<'hir>), AnonConst(&'hir AnonConst), + ConstBlock(&'hir ConstBlock), Expr(&'hir Expr<'hir>), ExprField(&'hir ExprField<'hir>), Stmt(&'hir Stmt<'hir>), @@ -3701,6 +3710,7 @@ impl<'hir> Node<'hir> { Node::PreciseCapturingNonLifetimeArg(a) => Some(a.ident), Node::Param(..) | Node::AnonConst(..) + | Node::ConstBlock(..) | Node::Expr(..) | Node::Stmt(..) | Node::Block(..) @@ -3798,6 +3808,7 @@ impl<'hir> Node<'hir> { } Node::AnonConst(constant) => Some((constant.def_id, constant.body)), + Node::ConstBlock(constant) => Some((constant.def_id, constant.body)), _ => None, } @@ -3866,6 +3877,7 @@ impl<'hir> Node<'hir> { expect_variant, &'hir Variant<'hir>, Node::Variant(n), n; expect_field, &'hir FieldDef<'hir>, Node::Field(n), n; expect_anon_const, &'hir AnonConst, Node::AnonConst(n), n; + expect_inline_const, &'hir ConstBlock, Node::ConstBlock(n), n; expect_expr, &'hir Expr<'hir>, Node::Expr(n), n; expect_expr_field, &'hir ExprField<'hir>, Node::ExprField(n), n; expect_stmt, &'hir Stmt<'hir>, Node::Stmt(n), n; diff --git a/compiler/rustc_hir/src/intravisit.rs b/compiler/rustc_hir/src/intravisit.rs index 9bc2bbe0c6471..4cadb899615b9 100644 --- a/compiler/rustc_hir/src/intravisit.rs +++ b/compiler/rustc_hir/src/intravisit.rs @@ -344,6 +344,9 @@ pub trait Visitor<'v>: Sized { fn visit_anon_const(&mut self, c: &'v AnonConst) -> Self::Result { walk_anon_const(self, c) } + fn visit_inline_const(&mut self, c: &'v ConstBlock) -> Self::Result { + walk_inline_const(self, c) + } fn visit_expr(&mut self, ex: &'v Expr<'v>) -> Self::Result { walk_expr(self, ex) } @@ -716,6 +719,14 @@ pub fn walk_anon_const<'v, V: Visitor<'v>>(visitor: &mut V, constant: &'v AnonCo visitor.visit_nested_body(constant.body) } +pub fn walk_inline_const<'v, V: Visitor<'v>>( + visitor: &mut V, + constant: &'v ConstBlock, +) -> V::Result { + try_visit!(visitor.visit_id(constant.hir_id)); + visitor.visit_nested_body(constant.body) +} + pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr<'v>) -> V::Result { try_visit!(visitor.visit_id(expression.hir_id)); match expression.kind { @@ -723,7 +734,7 @@ pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr<'v>) walk_list!(visitor, visit_expr, subexpressions); } ExprKind::ConstBlock(ref const_block) => { - try_visit!(visitor.visit_expr(const_block)) + try_visit!(visitor.visit_inline_const(const_block)) } ExprKind::Repeat(ref element, ref count) => { try_visit!(visitor.visit_expr(element)); diff --git a/compiler/rustc_hir_analysis/src/check/region.rs b/compiler/rustc_hir_analysis/src/check/region.rs index 30b03b43872a6..72e431926ca32 100644 --- a/compiler/rustc_hir_analysis/src/check/region.rs +++ b/compiler/rustc_hir_analysis/src/check/region.rs @@ -407,14 +407,11 @@ fn resolve_expr<'tcx>(visitor: &mut RegionResolutionVisitor<'tcx>, expr: &'tcx h match expr.kind { // Manually recurse over closures and inline consts, because they are the only // case of nested bodies that share the parent environment. - hir::ExprKind::Closure(&hir::Closure { body, .. }) => { + hir::ExprKind::Closure(&hir::Closure { body, .. }) + | hir::ExprKind::ConstBlock(hir::ConstBlock { body, .. }) => { let body = visitor.tcx.hir().body(body); visitor.visit_body(body); } - hir::ExprKind::ConstBlock(expr) => visitor.enter_body(expr.hir_id, |this| { - this.cx.var_parent = None; - resolve_local(this, None, Some(expr)); - }), hir::ExprKind::AssignOp(_, left_expr, right_expr) => { debug!( "resolve_expr - enabling pessimistic_yield, was previously {}", diff --git a/compiler/rustc_hir_analysis/src/collect/generics_of.rs b/compiler/rustc_hir_analysis/src/collect/generics_of.rs index 9af959681fbfa..abdf85ad707bc 100644 --- a/compiler/rustc_hir_analysis/src/collect/generics_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/generics_of.rs @@ -177,10 +177,10 @@ pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Generics { } } } - Node::Expr(&hir::Expr { - kind: hir::ExprKind::Closure { .. } | hir::ExprKind::ConstBlock { .. }, - .. - }) => Some(tcx.typeck_root_def_id(def_id.to_def_id())), + Node::ConstBlock(_) + | Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure { .. }, .. }) => { + Some(tcx.typeck_root_def_id(def_id.to_def_id())) + } Node::Item(item) => match item.kind { ItemKind::OpaqueTy(&hir::OpaqueTy { origin: @@ -415,7 +415,7 @@ pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Generics { } // provide junk type parameter defs for const blocks. - if let Node::Expr(Expr { kind: ExprKind::ConstBlock(..), .. }) = node { + if let Node::ConstBlock(_) = node { own_params.push(ty::GenericParamDef { index: next_index(), name: Symbol::intern(""), diff --git a/compiler/rustc_hir_analysis/src/collect/type_of.rs b/compiler/rustc_hir_analysis/src/collect/type_of.rs index c677fa9226160..505240d869c2d 100644 --- a/compiler/rustc_hir_analysis/src/collect/type_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/type_of.rs @@ -485,7 +485,8 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder<'_ } Node::AnonConst(_) => anon_const_type_of(tcx, def_id), - Node::Expr(&Expr { kind: ExprKind::ConstBlock(..), .. }) => { + + Node::ConstBlock(_) => { let args = ty::GenericArgs::identity_for_item(tcx, def_id.to_def_id()); args.as_inline_const().ty() } diff --git a/compiler/rustc_hir_analysis/src/lib.rs b/compiler/rustc_hir_analysis/src/lib.rs index 65b02a2ec5653..8fe81851f9327 100644 --- a/compiler/rustc_hir_analysis/src/lib.rs +++ b/compiler/rustc_hir_analysis/src/lib.rs @@ -190,6 +190,10 @@ pub fn check_crate(tcx: TyCtxt<'_>) { } }); + // Freeze definitions as we don't add new ones at this point. This improves performance by + // allowing lock-free access to them. + tcx.untracked().definitions.freeze(); + // FIXME: Remove this when we implement creating `DefId`s // for anon constants during their parents' typeck. // Typeck all body owners in parallel will produce queries @@ -201,10 +205,6 @@ pub fn check_crate(tcx: TyCtxt<'_>) { } }); - // Freeze definitions as we don't add new ones at this point. This improves performance by - // allowing lock-free access to them. - tcx.untracked().definitions.freeze(); - tcx.ensure().check_unused_traits(()); } diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs index a8e0b3fc0793d..413d50dff514c 100644 --- a/compiler/rustc_hir_pretty/src/lib.rs +++ b/compiler/rustc_hir_pretty/src/lib.rs @@ -84,6 +84,7 @@ impl<'a> State<'a> { Node::ImplItem(a) => self.print_impl_item(a), Node::Variant(a) => self.print_variant(a), Node::AnonConst(a) => self.print_anon_const(a), + Node::ConstBlock(a) => self.print_inline_const(a), Node::Expr(a) => self.print_expr(a), Node::ExprField(a) => self.print_expr_field(a), Node::Stmt(a) => self.print_stmt(a), @@ -1048,10 +1049,10 @@ impl<'a> State<'a> { self.end() } - fn print_inline_const(&mut self, constant: &hir::Expr<'_>) { + fn print_inline_const(&mut self, constant: &hir::ConstBlock) { self.ibox(INDENT_UNIT); self.word_space("const"); - self.print_expr(constant); + self.ann.nested(self, Nested::Body(constant.body)); self.end() } diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 2f92a304bf037..592c1a6f0e234 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -32,6 +32,7 @@ use rustc_errors::{ use rustc_hir as hir; use rustc_hir::def::{CtorKind, DefKind, Res}; use rustc_hir::def_id::DefId; +use rustc_hir::intravisit::Visitor; use rustc_hir::lang_items::LangItem; use rustc_hir::{ExprKind, HirId, QPath}; use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer as _; @@ -335,7 +336,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } ExprKind::DropTemps(e) => self.check_expr_with_expectation(e, expected), ExprKind::Array(args) => self.check_expr_array(args, expected, expr), - ExprKind::ConstBlock(ref block) => self.check_expr_with_expectation(block, expected), + ExprKind::ConstBlock(ref block) => self.check_expr_const_block(block, expected), ExprKind::Repeat(element, ref count) => { self.check_expr_repeat(element, count, expected, expr) } @@ -1459,6 +1460,24 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } + fn check_expr_const_block( + &self, + block: &'tcx hir::ConstBlock, + expected: Expectation<'tcx>, + ) -> Ty<'tcx> { + let body = self.tcx.hir().body(block.body); + + // Create a new function context. + let def_id = block.def_id; + let fcx = FnCtxt::new(self, self.param_env, def_id); + crate::GatherLocalsVisitor::new(&fcx).visit_body(body); + + let ty = fcx.check_expr_with_expectation(body.value, expected); + fcx.require_type_is_sized(ty, body.value.span, ObligationCauseCode::ConstSized); + fcx.write_ty(block.hir_id, ty); + ty + } + fn check_expr_repeat( &self, element: &'tcx hir::Expr<'tcx>, diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs index 5723b73a328ad..45494528dd2b8 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs @@ -1051,10 +1051,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .take_while(|(_, node)| { // look at parents until we find the first body owner node.body_id().is_none() - && !matches!( - node, - Node::Expr(Expr { kind: ExprKind::ConstBlock { .. }, .. }) - ) }) .any(|(parent_id, _)| self.is_loop(parent_id)); diff --git a/compiler/rustc_hir_typeck/src/upvar.rs b/compiler/rustc_hir_typeck/src/upvar.rs index 4386e68ce8674..466397817dae1 100644 --- a/compiler/rustc_hir_typeck/src/upvar.rs +++ b/compiler/rustc_hir_typeck/src/upvar.rs @@ -149,6 +149,10 @@ impl<'a, 'tcx> Visitor<'tcx> for InferBorrowKindVisitor<'a, 'tcx> { self.visit_body(body); self.fcx.analyze_closure(expr.hir_id, expr.span, body_id, body, capture_clause); } + hir::ExprKind::ConstBlock(anon_const) => { + let body = self.fcx.tcx.hir().body(anon_const.body); + self.visit_body(body); + } _ => {} } diff --git a/compiler/rustc_hir_typeck/src/writeback.rs b/compiler/rustc_hir_typeck/src/writeback.rs index e337105f01104..8546ae6170c8b 100644 --- a/compiler/rustc_hir_typeck/src/writeback.rs +++ b/compiler/rustc_hir_typeck/src/writeback.rs @@ -3,7 +3,6 @@ // generic parameters. use crate::FnCtxt; -use hir::def::DefKind; use rustc_data_structures::unord::ExtendUnord; use rustc_errors::{ErrorGuaranteed, StashKey}; use rustc_hir as hir; @@ -17,7 +16,7 @@ use rustc_middle::ty::fold::{TypeFoldable, TypeFolder}; use rustc_middle::ty::visit::TypeVisitableExt; use rustc_middle::ty::TypeSuperFoldable; use rustc_middle::ty::{self, Ty, TyCtxt}; -use rustc_span::symbol::{kw, sym}; +use rustc_span::symbol::sym; use rustc_span::Span; use rustc_trait_selection::solve; use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt; @@ -296,11 +295,11 @@ impl<'cx, 'tcx> Visitor<'tcx> for WritebackCx<'cx, 'tcx> { hir::ExprKind::Field(..) | hir::ExprKind::OffsetOf(..) => { self.visit_field_id(e.hir_id); } - hir::ExprKind::ConstBlock(_) => { - let feed = self.tcx().create_def(self.fcx.body_id, kw::Empty, DefKind::InlineConst); - feed.def_span(e.span); - feed.local_def_id_to_hir_id(e.hir_id); - self.typeck_results.inline_consts.insert(e.hir_id.local_id, feed.def_id()); + hir::ExprKind::ConstBlock(anon_const) => { + self.visit_node_id(e.span, anon_const.hir_id); + + let body = self.tcx().hir().body(anon_const.body); + self.visit_body(body); } _ => {} } diff --git a/compiler/rustc_middle/src/hir/map/mod.rs b/compiler/rustc_middle/src/hir/map/mod.rs index 639c98155e705..28371f2666097 100644 --- a/compiler/rustc_middle/src/hir/map/mod.rs +++ b/compiler/rustc_middle/src/hir/map/mod.rs @@ -1,5 +1,3 @@ -use std::borrow::Cow; - use crate::hir::ModuleItems; use crate::middle::debugger_visualizer::DebuggerVisualizerFile; use crate::query::LocalCrate; @@ -256,26 +254,13 @@ impl<'hir> Map<'hir> { /// Given a `LocalDefId`, returns the `BodyId` associated with it, /// if the node is a body owner, otherwise returns `None`. - pub fn maybe_body_owned_by(self, id: LocalDefId) -> Option>> { - Some(match self.tcx.def_kind(id) { - // Inline consts do not have bodies of their own, so create one to make the follow-up logic simpler. - DefKind::InlineConst => { - let e = self.expect_expr(self.tcx.local_def_id_to_hir_id(id)); - Cow::Owned(Body { - params: &[], - value: match e.kind { - ExprKind::ConstBlock(body) => body, - _ => span_bug!(e.span, "InlineConst was not a ConstBlock: {e:#?}"), - }, - }) - } - _ => Cow::Borrowed(self.body(self.tcx.hir_node_by_def_id(id).body_id()?)), - }) + pub fn maybe_body_owned_by(self, id: LocalDefId) -> Option<&'hir Body<'hir>> { + Some(self.body(self.tcx.hir_node_by_def_id(id).body_id()?)) } /// Given a body owner's id, returns the `BodyId` associated with it. #[track_caller] - pub fn body_owned_by(self, id: LocalDefId) -> Cow<'hir, Body<'hir>> { + pub fn body_owned_by(self, id: LocalDefId) -> &'hir Body<'hir> { self.maybe_body_owned_by(id).unwrap_or_else(|| { let hir_id = self.tcx.local_def_id_to_hir_id(id); span_bug!( @@ -336,7 +321,7 @@ impl<'hir> Map<'hir> { /// Returns an iterator of the `DefId`s for all body-owners in this /// crate. If you would prefer to iterate over the bodies - /// themselves, you can do `self.hir().krate().owners.iter()`. + /// themselves, you can do `self.hir().krate().body_ids.iter()`. #[inline] pub fn body_owners(self) -> impl Iterator + 'hir { self.tcx.hir_crate_items(()).body_owners.iter().copied() @@ -523,17 +508,7 @@ impl<'hir> Map<'hir> { /// Whether the expression pointed at by `hir_id` belongs to a `const` evaluation context. /// Used exclusively for diagnostics, to avoid suggestion function calls. pub fn is_inside_const_context(self, hir_id: HirId) -> bool { - for (_, node) in self.parent_iter(hir_id) { - if let Some((def_id, _)) = node.associated_body() { - return self.body_const_context(def_id).is_some(); - } - if let Node::Expr(e) = node { - if let ExprKind::ConstBlock(_) = e.kind { - return true; - } - } - } - false + self.body_const_context(self.enclosing_body_owner(hir_id)).is_some() } /// Retrieves the `HirId` for `id`'s enclosing function *if* the `id` block or return is @@ -916,6 +891,7 @@ impl<'hir> Map<'hir> { Node::Variant(variant) => variant.span, Node::Field(field) => field.span, Node::AnonConst(constant) => constant.span, + Node::ConstBlock(constant) => self.body(constant.body).value.span, Node::Expr(expr) => expr.span, Node::ExprField(field) => field.span, Node::Stmt(stmt) => stmt.span, @@ -1185,6 +1161,7 @@ fn hir_id_to_string(map: Map<'_>, id: HirId) -> String { format!("{id} (field `{}` in {})", field.ident, path_str(field.def_id)) } Node::AnonConst(_) => node_str("const"), + Node::ConstBlock(_) => node_str("const"), Node::Expr(_) => node_str("expr"), Node::ExprField(_) => node_str("expr field"), Node::Stmt(_) => node_str("stmt"), @@ -1334,6 +1311,11 @@ impl<'hir> Visitor<'hir> for ItemCollector<'hir> { intravisit::walk_anon_const(self, c) } + fn visit_inline_const(&mut self, c: &'hir ConstBlock) { + self.body_owners.push(c.def_id); + intravisit::walk_inline_const(self, c) + } + fn visit_expr(&mut self, ex: &'hir Expr<'hir>) { if let ExprKind::Closure(closure) = ex.kind { self.body_owners.push(closure.def_id); diff --git a/compiler/rustc_middle/src/ty/typeck_results.rs b/compiler/rustc_middle/src/ty/typeck_results.rs index 69ea9c9843a08..24e3e623ff274 100644 --- a/compiler/rustc_middle/src/ty/typeck_results.rs +++ b/compiler/rustc_middle/src/ty/typeck_results.rs @@ -217,10 +217,6 @@ pub struct TypeckResults<'tcx> { /// Container types and field indices of `offset_of!` expressions offset_of_data: ItemLocalMap<(Ty<'tcx>, Vec<(VariantIdx, FieldIdx)>)>, - - /// Maps from `HirId`s of const blocks (the `ExprKind::ConstBlock`, not the inner expression's) - /// to the `DefId` of the corresponding inline const. - pub inline_consts: FxIndexMap, } impl<'tcx> TypeckResults<'tcx> { @@ -253,7 +249,6 @@ impl<'tcx> TypeckResults<'tcx> { treat_byte_string_as_slice: Default::default(), closure_size_eval: Default::default(), offset_of_data: Default::default(), - inline_consts: Default::default(), } } diff --git a/compiler/rustc_mir_build/src/build/mod.rs b/compiler/rustc_mir_build/src/build/mod.rs index 14d1b502474fd..193f0d124bb80 100644 --- a/compiler/rustc_mir_build/src/build/mod.rs +++ b/compiler/rustc_mir_build/src/build/mod.rs @@ -568,8 +568,11 @@ fn construct_const<'a, 'tcx>( .. }) => (*span, ty.span), Node::AnonConst(ct) => (ct.span, ct.span), - Node::Expr(&hir::Expr { span, kind: hir::ExprKind::ConstBlock(_), .. }) => (span, span), - node => span_bug!(tcx.def_span(def), "can't build MIR for {def:?}: {node:#?}"), + Node::ConstBlock(_) => { + let span = tcx.def_span(def); + (span, span) + } + _ => span_bug!(tcx.def_span(def), "can't build MIR for {:?}", def), }; let infcx = tcx.infer_ctxt().build(); diff --git a/compiler/rustc_mir_build/src/thir/cx/expr.rs b/compiler/rustc_mir_build/src/thir/cx/expr.rs index bd66257e6b687..28f9300b97a88 100644 --- a/compiler/rustc_mir_build/src/thir/cx/expr.rs +++ b/compiler/rustc_mir_build/src/thir/cx/expr.rs @@ -671,9 +671,9 @@ impl<'tcx> Cx<'tcx> { ExprKind::OffsetOf { container, fields } } - hir::ExprKind::ConstBlock(body) => { - let ty = self.typeck_results().node_type(body.hir_id); - let did = self.typeck_results().inline_consts[&expr.hir_id.local_id].into(); + hir::ExprKind::ConstBlock(ref anon_const) => { + let ty = self.typeck_results().node_type(anon_const.hir_id); + let did = anon_const.def_id.to_def_id(); let typeck_root_def_id = tcx.typeck_root_def_id(did); let parent_args = tcx.erase_regions(GenericArgs::identity_for_item(tcx, typeck_root_def_id)); diff --git a/compiler/rustc_mir_build/src/thir/cx/mod.rs b/compiler/rustc_mir_build/src/thir/cx/mod.rs index bd9e34ae80fc4..244ac409fd381 100644 --- a/compiler/rustc_mir_build/src/thir/cx/mod.rs +++ b/compiler/rustc_mir_build/src/thir/cx/mod.rs @@ -165,7 +165,7 @@ impl<'tcx> Cx<'tcx> { &'a mut self, owner_id: HirId, fn_decl: &'tcx hir::FnDecl<'tcx>, - body: &hir::Body<'tcx>, + body: &'tcx hir::Body<'tcx>, ) -> impl Iterator> + 'a { let fn_sig = self.typeck_results.liberated_fn_sigs()[owner_id]; diff --git a/compiler/rustc_mir_build/src/thir/pattern/mod.rs b/compiler/rustc_mir_build/src/thir/pattern/mod.rs index 33401cad631a1..7408c679f00b1 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/mod.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/mod.rs @@ -637,13 +637,15 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { /// Converts inline const patterns. fn lower_inline_const( &mut self, - expr: &'tcx hir::Expr<'tcx>, + block: &'tcx hir::ConstBlock, id: hir::HirId, span: Span, ) -> PatKind<'tcx> { let tcx = self.tcx; - let def_id = self.typeck_results.inline_consts[&id.local_id]; - let ty = tcx.typeck(def_id).node_type(expr.hir_id); + let def_id = block.def_id; + let body_id = block.body; + let expr = &tcx.hir().body(body_id).value; + let ty = tcx.typeck(def_id).node_type(block.hir_id); // Special case inline consts that are just literals. This is solely // a performance optimization, as we could also just go through the regular diff --git a/compiler/rustc_mir_transform/src/lib.rs b/compiler/rustc_mir_transform/src/lib.rs index b66e3d66f4d3e..9d88f8bf9bec7 100644 --- a/compiler/rustc_mir_transform/src/lib.rs +++ b/compiler/rustc_mir_transform/src/lib.rs @@ -222,12 +222,6 @@ fn mir_keys(tcx: TyCtxt<'_>, (): ()) -> FxIndexSet { // All body-owners have MIR associated with them. set.extend(tcx.hir().body_owners()); - // Inline consts' bodies are created in - // typeck instead of during ast lowering, like all other bodies so far. - for def_id in tcx.hir().body_owners() { - set.extend(tcx.typeck(def_id).inline_consts.values()) - } - // Additionally, tuple struct/variant constructors have MIR, but // they don't have a BodyId, so we need to build them separately. struct GatherCtors<'a> { diff --git a/compiler/rustc_parse/src/parser/mod.rs b/compiler/rustc_parse/src/parser/mod.rs index bab8b6c06ebee..c2183258eef14 100644 --- a/compiler/rustc_parse/src/parser/mod.rs +++ b/compiler/rustc_parse/src/parser/mod.rs @@ -25,8 +25,8 @@ use rustc_ast::tokenstream::{AttributesData, DelimSpacing, DelimSpan, Spacing}; use rustc_ast::tokenstream::{TokenStream, TokenTree, TokenTreeCursor}; use rustc_ast::util::case::Case; use rustc_ast::{ - self as ast, AttrArgs, AttrArgsEq, AttrId, ByRef, Const, CoroutineKind, DelimArgs, Expr, - ExprKind, Extern, HasAttrs, HasTokens, Mutability, Recovered, Safety, StrLit, Visibility, + self as ast, AnonConst, AttrArgs, AttrArgsEq, AttrId, ByRef, Const, CoroutineKind, DelimArgs, + Expr, ExprKind, Extern, HasAttrs, HasTokens, Mutability, Recovered, Safety, StrLit, Visibility, VisibilityKind, DUMMY_NODE_ID, }; use rustc_ast_pretty::pprust; @@ -1260,9 +1260,12 @@ impl<'a> Parser<'a> { } self.eat_keyword(kw::Const); let (attrs, blk) = self.parse_inner_attrs_and_block()?; - let expr = self.mk_expr(blk.span, ExprKind::Block(blk, None)); - let blk_span = expr.span; - Ok(self.mk_expr_with_attrs(span.to(blk_span), ExprKind::ConstBlock(expr), attrs)) + let anon_const = AnonConst { + id: DUMMY_NODE_ID, + value: self.mk_expr(blk.span, ExprKind::Block(blk, None)), + }; + let blk_span = anon_const.value.span; + Ok(self.mk_expr_with_attrs(span.to(blk_span), ExprKind::ConstBlock(anon_const), attrs)) } /// Parses mutability (`mut` or nothing). diff --git a/compiler/rustc_passes/src/check_const.rs b/compiler/rustc_passes/src/check_const.rs index 71f3e8b7b5d9c..3f6eccbd5a523 100644 --- a/compiler/rustc_passes/src/check_const.rs +++ b/compiler/rustc_passes/src/check_const.rs @@ -196,6 +196,11 @@ impl<'tcx> Visitor<'tcx> for CheckConstVisitor<'tcx> { self.recurse_into(kind, None, |this| intravisit::walk_anon_const(this, anon)); } + fn visit_inline_const(&mut self, block: &'tcx hir::ConstBlock) { + let kind = Some(hir::ConstContext::Const { inline: true }); + self.recurse_into(kind, None, |this| intravisit::walk_inline_const(this, block)); + } + fn visit_body(&mut self, body: &hir::Body<'tcx>) { let owner = self.tcx.hir().body_owner_def_id(body.id()); let kind = self.tcx.hir().body_const_context(owner); @@ -223,11 +228,6 @@ impl<'tcx> Visitor<'tcx> for CheckConstVisitor<'tcx> { self.const_check_violated(expr, e.span); } } - hir::ExprKind::ConstBlock(expr) => { - let kind = Some(hir::ConstContext::Const { inline: true }); - self.recurse_into(kind, None, |this| intravisit::walk_expr(this, expr)); - return; - } _ => {} } diff --git a/compiler/rustc_passes/src/dead.rs b/compiler/rustc_passes/src/dead.rs index 0049afff528ca..ddc50e2b811a2 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -587,16 +587,6 @@ impl<'tcx> Visitor<'tcx> for MarkSymbolVisitor<'tcx> { hir::ExprKind::OffsetOf(..) => { self.handle_offset_of(expr); } - hir::ExprKind::ConstBlock(expr) => { - // When inline const blocks are used in pattern position, paths - // referenced by it should be considered as used. - let in_pat = mem::replace(&mut self.in_pat, false); - - intravisit::walk_expr(self, expr); - - self.in_pat = in_pat; - return; - } _ => (), } @@ -658,6 +648,17 @@ impl<'tcx> Visitor<'tcx> for MarkSymbolVisitor<'tcx> { self.in_pat = in_pat; } + + fn visit_inline_const(&mut self, c: &'tcx hir::ConstBlock) { + // When inline const blocks are used in pattern position, paths + // referenced by it should be considered as used. + let in_pat = mem::replace(&mut self.in_pat, false); + + self.live_symbols.insert(c.def_id); + intravisit::walk_inline_const(self, c); + + self.in_pat = in_pat; + } } fn has_allow_dead_code_or_lang_attr( diff --git a/compiler/rustc_passes/src/liveness.rs b/compiler/rustc_passes/src/liveness.rs index 698f15015c48c..dfa7dfa339817 100644 --- a/compiler/rustc_passes/src/liveness.rs +++ b/compiler/rustc_passes/src/liveness.rs @@ -147,11 +147,6 @@ fn check_liveness(tcx: TyCtxt<'_>, def_id: LocalDefId) { return; } - // Don't run for inline consts, they are collected together with their parent - if let DefKind::InlineConst = tcx.def_kind(def_id) { - return; - } - // Don't run unused pass for #[naked] if tcx.has_attr(def_id.to_def_id(), sym::naked) { return; @@ -1148,13 +1143,12 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { } hir::ExprKind::Lit(..) + | hir::ExprKind::ConstBlock(..) | hir::ExprKind::Err(_) | hir::ExprKind::Path(hir::QPath::TypeRelative(..)) | hir::ExprKind::Path(hir::QPath::LangItem(..)) | hir::ExprKind::OffsetOf(..) => succ, - hir::ExprKind::ConstBlock(expr) => self.propagate_through_expr(expr, succ), - // Note that labels have been resolved, so we don't need to look // at the label ident hir::ExprKind::Block(ref blk, _) => self.propagate_through_block(blk, succ), diff --git a/compiler/rustc_passes/src/loops.rs b/compiler/rustc_passes/src/loops.rs index 737310e5c04a3..2587a18b8c897 100644 --- a/compiler/rustc_passes/src/loops.rs +++ b/compiler/rustc_passes/src/loops.rs @@ -93,6 +93,10 @@ impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> { self.with_context(Constant, |v| intravisit::walk_anon_const(v, c)); } + fn visit_inline_const(&mut self, c: &'hir hir::ConstBlock) { + self.with_context(Constant, |v| intravisit::walk_inline_const(v, c)); + } + fn visit_fn( &mut self, fk: hir::intravisit::FnKind<'hir>, @@ -285,9 +289,6 @@ impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> { self.cx_stack.len() - 1, ) } - hir::ExprKind::ConstBlock(expr) => { - self.with_context(Constant, |v| intravisit::walk_expr(v, expr)); - } _ => intravisit::walk_expr(self, e), } } diff --git a/compiler/rustc_resolve/src/def_collector.rs b/compiler/rustc_resolve/src/def_collector.rs index cad10571afe62..bd0622428569c 100644 --- a/compiler/rustc_resolve/src/def_collector.rs +++ b/compiler/rustc_resolve/src/def_collector.rs @@ -325,6 +325,16 @@ impl<'a, 'b, 'tcx> visit::Visitor<'a> for DefCollector<'a, 'b, 'tcx> { ExprKind::Gen(_, _, _) => { self.create_def(expr.id, kw::Empty, DefKind::Closure, expr.span) } + ExprKind::ConstBlock(ref constant) => { + let def = self.create_def( + constant.id, + kw::Empty, + DefKind::InlineConst, + constant.value.span, + ); + self.with_parent(def, |this| visit::walk_anon_const(this, constant)); + return; + } _ => self.parent_def, }; diff --git a/compiler/rustc_resolve/src/late.rs b/compiler/rustc_resolve/src/late.rs index bcf2c9a920610..8b3af5093e5f9 100644 --- a/compiler/rustc_resolve/src/late.rs +++ b/compiler/rustc_resolve/src/late.rs @@ -4505,10 +4505,8 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> { self.visit_expr(elem); self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::Yes)); } - ExprKind::ConstBlock(ref expr) => { - self.resolve_anon_const_manual(false, AnonConstKind::InlineConst, |this| { - this.visit_expr(expr) - }); + ExprKind::ConstBlock(ref ct) => { + self.resolve_anon_const(ct, AnonConstKind::InlineConst); } ExprKind::Index(ref elem, ref idx, _) => { self.resolve_expr(elem, Some(expr)); diff --git a/src/tools/clippy/clippy_utils/src/consts.rs b/src/tools/clippy/clippy_utils/src/consts.rs index cd88ccd87cf0a..5c9cad2b45d4a 100644 --- a/src/tools/clippy/clippy_utils/src/consts.rs +++ b/src/tools/clippy/clippy_utils/src/consts.rs @@ -6,7 +6,7 @@ use crate::{clip, is_direct_expn_of, sext, unsext}; use rustc_ast::ast::{self, LitFloatType, LitKind}; use rustc_data_structures::sync::Lrc; use rustc_hir::def::{DefKind, Res}; -use rustc_hir::{BinOp, BinOpKind, Block, Expr, ExprKind, HirId, Item, ItemKind, Node, QPath, UnOp}; +use rustc_hir::{BinOp, BinOpKind, Block, ConstBlock, Expr, ExprKind, HirId, Item, ItemKind, Node, QPath, UnOp}; use rustc_lexer::tokenize; use rustc_lint::LateContext; use rustc_middle::mir::interpret::{alloc_range, Scalar}; @@ -412,7 +412,7 @@ impl<'a, 'tcx> ConstEvalLateContext<'a, 'tcx> { /// Simple constant folding: Insert an expression, get a constant or none. pub fn expr(&mut self, e: &Expr<'_>) -> Option> { match e.kind { - ExprKind::ConstBlock(e) | ExprKind::DropTemps(e) => self.expr(e), + ExprKind::ConstBlock(ConstBlock { body, .. }) => self.expr(self.lcx.tcx.hir().body(body).value), ExprKind::DropTemps(e) => self.expr(e), ExprKind::Path(ref qpath) => { self.fetch_path_and_apply(qpath, e.hir_id, self.typeck_results.expr_ty(e), |this, result| { let result = mir_to_const(this.lcx, result)?; @@ -490,7 +490,7 @@ impl<'a, 'tcx> ConstEvalLateContext<'a, 'tcx> { /// leaves the local crate. pub fn expr_is_empty(&mut self, e: &Expr<'_>) -> Option { match e.kind { - ExprKind::ConstBlock(e) | ExprKind::DropTemps(e) => self.expr_is_empty(e), + ExprKind::ConstBlock(ConstBlock { body, .. }) => self.expr_is_empty(self.lcx.tcx.hir().body(body).value), ExprKind::DropTemps(e) => self.expr_is_empty(e), ExprKind::Path(ref qpath) => { if !self .typeck_results diff --git a/src/tools/clippy/clippy_utils/src/hir_utils.rs b/src/tools/clippy/clippy_utils/src/hir_utils.rs index c649c17946843..36634817fc91e 100644 --- a/src/tools/clippy/clippy_utils/src/hir_utils.rs +++ b/src/tools/clippy/clippy_utils/src/hir_utils.rs @@ -295,7 +295,7 @@ impl HirEqInterExpr<'_, '_, '_> { self.eq_expr(lx, rx) && self.eq_ty(lt, rt) }, (&ExprKind::Closure(_l), &ExprKind::Closure(_r)) => false, - (&ExprKind::ConstBlock(lb), &ExprKind::ConstBlock(rb)) => self.eq_expr(lb, rb), + (&ExprKind::ConstBlock(lb), &ExprKind::ConstBlock(rb)) => self.eq_body(lb.body, rb.body), (&ExprKind::Continue(li), &ExprKind::Continue(ri)) => { both(&li.label, &ri.label, |l, r| l.ident.name == r.ident.name) }, @@ -769,8 +769,8 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> { // closures inherit TypeckResults self.hash_expr(self.cx.tcx.hir().body(body).value); }, - ExprKind::ConstBlock(l_id) => { - self.hash_expr(l_id); + ExprKind::ConstBlock(ref l_id) => { + self.hash_body(l_id.body); }, ExprKind::DropTemps(e) | ExprKind::Yield(e, _) => { self.hash_expr(e); diff --git a/src/tools/clippy/tests/ui/arithmetic_side_effects.stderr b/src/tools/clippy/tests/ui/arithmetic_side_effects.stderr index df14ff396f6cf..8039c0bfa2484 100644 --- a/src/tools/clippy/tests/ui/arithmetic_side_effects.stderr +++ b/src/tools/clippy/tests/ui/arithmetic_side_effects.stderr @@ -1,35 +1,11 @@ -error: arithmetic operation that can potentially result in unexpected side-effects - --> tests/ui/arithmetic_side_effects.rs:188:36 - | -LL | let _ = const { let mut n = 1; n += 1; n }; - | ^^^^^^ - | - = note: `-D clippy::arithmetic-side-effects` implied by `-D warnings` - = help: to override `-D warnings` add `#[allow(clippy::arithmetic_side_effects)]` - -error: arithmetic operation that can potentially result in unexpected side-effects - --> tests/ui/arithmetic_side_effects.rs:191:40 - | -LL | let _ = const { let mut n = 1; n = n + 1; n }; - | ^^^^^ - -error: arithmetic operation that can potentially result in unexpected side-effects - --> tests/ui/arithmetic_side_effects.rs:194:40 - | -LL | let _ = const { let mut n = 1; n = 1 + n; n }; - | ^^^^^ - -error: arithmetic operation that can potentially result in unexpected side-effects - --> tests/ui/arithmetic_side_effects.rs:200:59 - | -LL | let _ = const { let mut n = 1; n = -1; n = -(-1); n = -n; n }; - | ^^ - error: arithmetic operation that can potentially result in unexpected side-effects --> tests/ui/arithmetic_side_effects.rs:304:5 | LL | _n += 1; | ^^^^^^^ + | + = note: `-D clippy::arithmetic-side-effects` implied by `-D warnings` + = help: to override `-D warnings` add `#[allow(clippy::arithmetic_side_effects)]` error: arithmetic operation that can potentially result in unexpected side-effects --> tests/ui/arithmetic_side_effects.rs:305:5 @@ -751,5 +727,5 @@ error: arithmetic operation that can potentially result in unexpected side-effec LL | one.sub_assign(1); | ^^^^^^^^^^^^^^^^^ -error: aborting due to 125 previous errors +error: aborting due to 121 previous errors diff --git a/tests/mir-opt/building/custom/consts.consts.built.after.mir b/tests/mir-opt/building/custom/consts.consts.built.after.mir index 7b6964849d4b3..a011fadcef116 100644 --- a/tests/mir-opt/building/custom/consts.consts.built.after.mir +++ b/tests/mir-opt/building/custom/consts.consts.built.after.mir @@ -10,7 +10,7 @@ fn consts() -> () { bb0: { _1 = const 5_u8; - _2 = const consts::::{constant#1}; + _2 = const consts::::{constant#0}; _3 = const C; _4 = const D; _5 = consts::<10>; diff --git a/tests/pretty/stmt_expr_attributes.rs b/tests/pretty/stmt_expr_attributes.rs index f904126821103..5eb7d2fcae36a 100644 --- a/tests/pretty/stmt_expr_attributes.rs +++ b/tests/pretty/stmt_expr_attributes.rs @@ -206,7 +206,12 @@ fn _11() { let _ = (); () }; - let const {} = #[rustc_dummy] const {}; + let const { + #![rustc_dummy] + } = + #[rustc_dummy] const { + #![rustc_dummy] + }; let mut x = 0; let _ = (#[rustc_dummy] x) = 15; let _ = (#[rustc_dummy] x) += 15; diff --git a/tests/ui/lint/non-local-defs/consts.stderr b/tests/ui/lint/non-local-defs/consts.stderr index 48bdaa60823f8..2756ea4013877 100644 --- a/tests/ui/lint/non-local-defs/consts.stderr +++ b/tests/ui/lint/non-local-defs/consts.stderr @@ -67,13 +67,18 @@ LL | impl Test { warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item --> $DIR/consts.rs:50:9 | -LL | fn main() { - | --------- move the `impl` block outside of this function `main` -... -LL | impl Test { - | ^^^^^---- - | | - | `Test` is not local +LL | const { + | ___________- +LL | | impl Test { + | | ^^^^^---- + | | | + | | `Test` is not local +LL | | +LL | | fn hoo() {} +... | +LL | | 1 +LL | | }; + | |_____- move the `impl` block outside of this inline constant `` and up 2 bodies | = note: methods and associated constants are still usable outside the current expression, only `impl Local` and `impl dyn Local` can ever be private, and only if the type is nested in the same item as the `impl` = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue diff --git a/tests/ui/unpretty/expanded-exhaustive.stdout b/tests/ui/unpretty/expanded-exhaustive.stdout index 8737063bf3cc7..325bace7b5624 100644 --- a/tests/ui/unpretty/expanded-exhaustive.stdout +++ b/tests/ui/unpretty/expanded-exhaustive.stdout @@ -82,8 +82,7 @@ mod expressions { fn expr_const_block() { const {}; const { 1 }; - const - { + const { struct S; }; } From 0d88bf29bcd267f2d1a7fcd3cfa1be69b1a4b397 Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Mon, 3 Jun 2024 09:39:26 +0000 Subject: [PATCH 05/17] Add regression test --- .../inline-const/const_block_pat_liveness.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 tests/ui/inline-const/const_block_pat_liveness.rs diff --git a/tests/ui/inline-const/const_block_pat_liveness.rs b/tests/ui/inline-const/const_block_pat_liveness.rs new file mode 100644 index 0000000000000..26393a4f65b84 --- /dev/null +++ b/tests/ui/inline-const/const_block_pat_liveness.rs @@ -0,0 +1,18 @@ +//! This test used to ICE because const blocks didn't have a body +//! anymore, making a lot of logic very fragile around handling the +//! HIR of a const block. +//! https://github.com/rust-lang/rust/issues/125846 + +//@ check-pass + +#![feature(inline_const_pat)] + +fn main() { + match 0 { + const { + let a = 10_usize; + *&a + } + | _ => {} + } +} From 4c95b887feb74a5e617bc76c614ad642ec3dbc56 Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Fri, 8 Mar 2024 06:36:37 +0000 Subject: [PATCH 06/17] Add regression test --- .../const_check_false_cycle.current.stderr | 34 +++++++++++++++++++ .../rpit/const_check_false_cycle.rs | 15 ++++++++ 2 files changed, 49 insertions(+) create mode 100644 tests/ui/impl-trait/rpit/const_check_false_cycle.current.stderr create mode 100644 tests/ui/impl-trait/rpit/const_check_false_cycle.rs diff --git a/tests/ui/impl-trait/rpit/const_check_false_cycle.current.stderr b/tests/ui/impl-trait/rpit/const_check_false_cycle.current.stderr new file mode 100644 index 0000000000000..78c7c164f590e --- /dev/null +++ b/tests/ui/impl-trait/rpit/const_check_false_cycle.current.stderr @@ -0,0 +1,34 @@ +error[E0391]: cycle detected when computing type of opaque `f::{opaque#0}` + --> $DIR/const_check_false_cycle.rs:9:17 + | +LL | const fn f() -> impl Eq { + | ^^^^^^^ + | +note: ...which requires borrow-checking `f`... + --> $DIR/const_check_false_cycle.rs:9:1 + | +LL | const fn f() -> impl Eq { + | ^^^^^^^^^^^^^^^^^^^^^^^ +note: ...which requires promoting constants in MIR for `f`... + --> $DIR/const_check_false_cycle.rs:9:1 + | +LL | const fn f() -> impl Eq { + | ^^^^^^^^^^^^^^^^^^^^^^^ +note: ...which requires const checking `f`... + --> $DIR/const_check_false_cycle.rs:9:1 + | +LL | const fn f() -> impl Eq { + | ^^^^^^^^^^^^^^^^^^^^^^^ + = note: ...which requires computing whether `f::{opaque#0}` is freeze... + = note: ...which requires evaluating trait selection obligation `f::{opaque#0}: core::marker::Freeze`... + = note: ...which again requires computing type of opaque `f::{opaque#0}`, completing the cycle +note: cycle used when computing type of `f::{opaque#0}` + --> $DIR/const_check_false_cycle.rs:9:17 + | +LL | const fn f() -> impl Eq { + | ^^^^^^^ + = note: see https://rustc-dev-guide.rust-lang.org/overview.html#queries and https://rustc-dev-guide.rust-lang.org/query.html for more information + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0391`. diff --git a/tests/ui/impl-trait/rpit/const_check_false_cycle.rs b/tests/ui/impl-trait/rpit/const_check_false_cycle.rs new file mode 100644 index 0000000000000..5b6b667e1faf6 --- /dev/null +++ b/tests/ui/impl-trait/rpit/const_check_false_cycle.rs @@ -0,0 +1,15 @@ +//! This test causes a cycle error when checking whether the +//! return type is `Freeze` during const checking, even though +//! the information is readily available. + +//@ revisions: current next +//@[next] compile-flags: -Znext-solver +//@[next] check-pass + +const fn f() -> impl Eq { + //[current]~^ ERROR cycle detected + g() +} +const fn g() {} + +fn main() {} From ff5b2a4117bae609449b8ce2ed020b4d93934981 Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Fri, 8 Mar 2024 12:39:26 +0000 Subject: [PATCH 07/17] Do not try to reveal hidden types when trying to prove Freeze in the defining scope --- .../src/check_consts/qualifs.rs | 28 ++++++++++++- compiler/rustc_middle/src/ty/util.rs | 2 +- .../src/traits/select/mod.rs | 19 +++++---- tests/ui/const-generics/opaque_types.stderr | 2 - .../const_check_false_cycle.current.stderr | 34 ---------------- .../rpit/const_check_false_cycle.rs | 5 +-- .../ice-112822-expected-type-for-param.rs | 1 - .../ice-112822-expected-type-for-param.stderr | 39 ++----------------- .../type-alias-impl-trait/in-where-clause.rs | 1 - .../in-where-clause.stderr | 24 +----------- 10 files changed, 48 insertions(+), 107 deletions(-) delete mode 100644 tests/ui/impl-trait/rpit/const_check_false_cycle.current.stderr diff --git a/compiler/rustc_const_eval/src/check_consts/qualifs.rs b/compiler/rustc_const_eval/src/check_consts/qualifs.rs index 5949444e599a0..8bd3a8907d3cf 100644 --- a/compiler/rustc_const_eval/src/check_consts/qualifs.rs +++ b/compiler/rustc_const_eval/src/check_consts/qualifs.rs @@ -100,7 +100,33 @@ impl Qualif for HasMutInterior { } fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool { - !ty.is_freeze(cx.tcx, cx.param_env) + // Avoid selecting for simple cases, such as builtin types. + if ty.is_trivially_freeze() { + return false; + } + + // We do not use `ty.is_freeze` here, because that requires revealing opaque types, which + // requires borrowck, which in turn will invoke mir_const_qualifs again, causing a cycle error. + // Instead we invoke an obligation context manually, and provide the opaque type inference settings + // that allow the trait solver to just error out instead of cycling. + let freeze_def_id = cx.tcx.require_lang_item(LangItem::Freeze, Some(cx.body.span)); + + let obligation = Obligation::new( + cx.tcx, + ObligationCause::dummy_with_span(cx.body.span), + cx.param_env, + ty::TraitRef::new(cx.tcx, freeze_def_id, [ty::GenericArg::from(ty)]), + ); + + let infcx = cx + .tcx + .infer_ctxt() + .with_opaque_type_inference(cx.body.source.def_id().expect_local()) + .build(); + let ocx = ObligationCtxt::new(&infcx); + ocx.register_obligation(obligation); + let errors = ocx.select_all_or_error(); + !errors.is_empty() } fn in_adt_inherently<'tcx>( diff --git a/compiler/rustc_middle/src/ty/util.rs b/compiler/rustc_middle/src/ty/util.rs index 52a0e72e17e28..0843f21128f9b 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -1302,7 +1302,7 @@ impl<'tcx> Ty<'tcx> { /// /// Returning true means the type is known to be `Freeze`. Returning /// `false` means nothing -- could be `Freeze`, might not be. - fn is_trivially_freeze(self) -> bool { + pub fn is_trivially_freeze(self) -> bool { match self.kind() { ty::Int(_) | ty::Uint(_) diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index dcb0875639fc7..6dffd874d9b6e 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -2417,13 +2417,18 @@ impl<'tcx> SelectionContext<'_, 'tcx> { } ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => { - // We can resolve the `impl Trait` to its concrete type, - // which enforces a DAG between the functions requiring - // the auto trait bounds in question. - match self.tcx().type_of_opaque(def_id) { - Ok(ty) => t.rebind(vec![ty.instantiate(self.tcx(), args)]), - Err(_) => { - return Err(SelectionError::OpaqueTypeAutoTraitLeakageUnknown(def_id)); + if self.infcx.can_define_opaque_ty(def_id) { + // We cannot possibly resolve this opaque type, because we are currently computing its hidden type. + return Err(SelectionError::OpaqueTypeAutoTraitLeakageUnknown(def_id)); + } else { + // We can resolve the `impl Trait` to its concrete type, + // which enforces a DAG between the functions requiring + // the auto trait bounds in question. + match self.tcx().type_of_opaque(def_id) { + Ok(ty) => t.rebind(vec![ty.instantiate(self.tcx(), args)]), + Err(_) => { + return Err(SelectionError::OpaqueTypeAutoTraitLeakageUnknown(def_id)); + } } } } diff --git a/tests/ui/const-generics/opaque_types.stderr b/tests/ui/const-generics/opaque_types.stderr index f03bca69a8bbf..c98e89121f6e4 100644 --- a/tests/ui/const-generics/opaque_types.stderr +++ b/tests/ui/const-generics/opaque_types.stderr @@ -109,8 +109,6 @@ note: ...which requires const checking `main::{constant#0}`... | LL | foo::<42>(); | ^^ - = note: ...which requires computing whether `Foo` is freeze... - = note: ...which requires evaluating trait selection obligation `Foo: core::marker::Freeze`... = note: ...which again requires computing type of opaque `Foo::{opaque#0}`, completing the cycle note: cycle used when computing type of `Foo::{opaque#0}` --> $DIR/opaque_types.rs:3:12 diff --git a/tests/ui/impl-trait/rpit/const_check_false_cycle.current.stderr b/tests/ui/impl-trait/rpit/const_check_false_cycle.current.stderr deleted file mode 100644 index 78c7c164f590e..0000000000000 --- a/tests/ui/impl-trait/rpit/const_check_false_cycle.current.stderr +++ /dev/null @@ -1,34 +0,0 @@ -error[E0391]: cycle detected when computing type of opaque `f::{opaque#0}` - --> $DIR/const_check_false_cycle.rs:9:17 - | -LL | const fn f() -> impl Eq { - | ^^^^^^^ - | -note: ...which requires borrow-checking `f`... - --> $DIR/const_check_false_cycle.rs:9:1 - | -LL | const fn f() -> impl Eq { - | ^^^^^^^^^^^^^^^^^^^^^^^ -note: ...which requires promoting constants in MIR for `f`... - --> $DIR/const_check_false_cycle.rs:9:1 - | -LL | const fn f() -> impl Eq { - | ^^^^^^^^^^^^^^^^^^^^^^^ -note: ...which requires const checking `f`... - --> $DIR/const_check_false_cycle.rs:9:1 - | -LL | const fn f() -> impl Eq { - | ^^^^^^^^^^^^^^^^^^^^^^^ - = note: ...which requires computing whether `f::{opaque#0}` is freeze... - = note: ...which requires evaluating trait selection obligation `f::{opaque#0}: core::marker::Freeze`... - = note: ...which again requires computing type of opaque `f::{opaque#0}`, completing the cycle -note: cycle used when computing type of `f::{opaque#0}` - --> $DIR/const_check_false_cycle.rs:9:17 - | -LL | const fn f() -> impl Eq { - | ^^^^^^^ - = note: see https://rustc-dev-guide.rust-lang.org/overview.html#queries and https://rustc-dev-guide.rust-lang.org/query.html for more information - -error: aborting due to 1 previous error - -For more information about this error, try `rustc --explain E0391`. diff --git a/tests/ui/impl-trait/rpit/const_check_false_cycle.rs b/tests/ui/impl-trait/rpit/const_check_false_cycle.rs index 5b6b667e1faf6..d4ea0e3b14785 100644 --- a/tests/ui/impl-trait/rpit/const_check_false_cycle.rs +++ b/tests/ui/impl-trait/rpit/const_check_false_cycle.rs @@ -1,13 +1,12 @@ -//! This test causes a cycle error when checking whether the +//! This test caused a cycle error when checking whether the //! return type is `Freeze` during const checking, even though //! the information is readily available. //@ revisions: current next //@[next] compile-flags: -Znext-solver -//@[next] check-pass +//@ check-pass const fn f() -> impl Eq { - //[current]~^ ERROR cycle detected g() } const fn g() {} diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/ice-112822-expected-type-for-param.rs b/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/ice-112822-expected-type-for-param.rs index 21197fcaa273a..d78c7cada3385 100644 --- a/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/ice-112822-expected-type-for-param.rs +++ b/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/ice-112822-expected-type-for-param.rs @@ -3,7 +3,6 @@ const fn test() -> impl ~const Fn() { //~^ ERROR `~const` can only be applied to `#[const_trait]` traits //~| ERROR `~const` can only be applied to `#[const_trait]` traits - //~| ERROR cycle detected const move || { //~ ERROR const closures are experimental let sl: &[u8] = b"foo"; diff --git a/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/ice-112822-expected-type-for-param.stderr b/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/ice-112822-expected-type-for-param.stderr index 2f8051109173d..1512029f0adef 100644 --- a/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/ice-112822-expected-type-for-param.stderr +++ b/tests/ui/rfcs/rfc-2632-const-trait-impl/effects/ice-112822-expected-type-for-param.stderr @@ -1,5 +1,5 @@ error[E0658]: const closures are experimental - --> $DIR/ice-112822-expected-type-for-param.rs:7:5 + --> $DIR/ice-112822-expected-type-for-param.rs:6:5 | LL | const move || { | ^^^^^ @@ -23,7 +23,7 @@ LL | const fn test() -> impl ~const Fn() { = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error[E0277]: can't compare `&u8` with `&u8` - --> $DIR/ice-112822-expected-type-for-param.rs:12:17 + --> $DIR/ice-112822-expected-type-for-param.rs:11:17 | LL | assert_eq!(first, &b'f'); | ^^^^^^^^^^^^^^^^^^^^^^^^ no implementation for `&u8 == &u8` @@ -31,38 +31,7 @@ LL | assert_eq!(first, &b'f'); = help: the trait `~const PartialEq<&u8>` is not implemented for `&u8` = note: this error originates in the macro `assert_eq` (in Nightly builds, run with -Z macro-backtrace for more info) -error[E0391]: cycle detected when computing type of opaque `test::{opaque#0}` - --> $DIR/ice-112822-expected-type-for-param.rs:3:20 - | -LL | const fn test() -> impl ~const Fn() { - | ^^^^^^^^^^^^^^^^ - | -note: ...which requires borrow-checking `test`... - --> $DIR/ice-112822-expected-type-for-param.rs:3:1 - | -LL | const fn test() -> impl ~const Fn() { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -note: ...which requires promoting constants in MIR for `test`... - --> $DIR/ice-112822-expected-type-for-param.rs:3:1 - | -LL | const fn test() -> impl ~const Fn() { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -note: ...which requires const checking `test`... - --> $DIR/ice-112822-expected-type-for-param.rs:3:1 - | -LL | const fn test() -> impl ~const Fn() { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - = note: ...which requires computing whether `test::{opaque#0}` is freeze... - = note: ...which requires evaluating trait selection obligation `test::{opaque#0}: core::marker::Freeze`... - = note: ...which again requires computing type of opaque `test::{opaque#0}`, completing the cycle -note: cycle used when computing type of `test::{opaque#0}` - --> $DIR/ice-112822-expected-type-for-param.rs:3:20 - | -LL | const fn test() -> impl ~const Fn() { - | ^^^^^^^^^^^^^^^^ - = note: see https://rustc-dev-guide.rust-lang.org/overview.html#queries and https://rustc-dev-guide.rust-lang.org/query.html for more information - -error: aborting due to 5 previous errors +error: aborting due to 4 previous errors -Some errors have detailed explanations: E0277, E0391, E0658. +Some errors have detailed explanations: E0277, E0658. For more information about an error, try `rustc --explain E0277`. diff --git a/tests/ui/type-alias-impl-trait/in-where-clause.rs b/tests/ui/type-alias-impl-trait/in-where-clause.rs index 7c0de39c7c91c..6e104781d84f3 100644 --- a/tests/ui/type-alias-impl-trait/in-where-clause.rs +++ b/tests/ui/type-alias-impl-trait/in-where-clause.rs @@ -4,7 +4,6 @@ #![feature(type_alias_impl_trait)] type Bar = impl Sized; //~^ ERROR: cycle -//~| ERROR: cycle fn foo() -> Bar where diff --git a/tests/ui/type-alias-impl-trait/in-where-clause.stderr b/tests/ui/type-alias-impl-trait/in-where-clause.stderr index 9c08b8f127d27..c486013f8874a 100644 --- a/tests/ui/type-alias-impl-trait/in-where-clause.stderr +++ b/tests/ui/type-alias-impl-trait/in-where-clause.stderr @@ -10,7 +10,7 @@ note: ...which requires computing type of opaque `Bar::{opaque#0}`... LL | type Bar = impl Sized; | ^^^^^^^^^^ note: ...which requires type-checking `foo`... - --> $DIR/in-where-clause.rs:9:1 + --> $DIR/in-where-clause.rs:8:1 | LL | / fn foo() -> Bar LL | | where @@ -25,26 +25,6 @@ LL | type Bar = impl Sized; | ^^^^^^^^^^ = note: see https://rustc-dev-guide.rust-lang.org/overview.html#queries and https://rustc-dev-guide.rust-lang.org/query.html for more information -error[E0391]: cycle detected when computing type of opaque `Bar::{opaque#0}` - --> $DIR/in-where-clause.rs:5:12 - | -LL | type Bar = impl Sized; - | ^^^^^^^^^^ - | -note: ...which requires type-checking `foo`... - --> $DIR/in-where-clause.rs:13:9 - | -LL | [0; 1 + 2] - | ^^^^^ - = note: ...which requires evaluating trait selection obligation `Bar: core::marker::Send`... - = note: ...which again requires computing type of opaque `Bar::{opaque#0}`, completing the cycle -note: cycle used when computing type of `Bar::{opaque#0}` - --> $DIR/in-where-clause.rs:5:12 - | -LL | type Bar = impl Sized; - | ^^^^^^^^^^ - = note: see https://rustc-dev-guide.rust-lang.org/overview.html#queries and https://rustc-dev-guide.rust-lang.org/query.html for more information - -error: aborting due to 2 previous errors +error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0391`. From f67a0eb2b72294f108051381cbc833c295aadad9 Mon Sep 17 00:00:00 2001 From: bohan Date: Tue, 4 Jun 2024 12:40:41 +0800 Subject: [PATCH 08/17] resolve: mark it undetermined if single import is not has any bindings --- compiler/rustc_resolve/src/ident.rs | 29 +++++++++++++++++-- compiler/rustc_resolve/src/imports.rs | 4 +-- tests/crashes/124490.rs | 16 ---------- tests/crashes/125013-1.rs | 5 ---- tests/crashes/125013-2.rs | 16 ---------- .../imports/cycle-import-in-diff-module-0.rs | 14 +++++++++ .../imports/cycle-import-in-diff-module-1.rs | 14 +++++++++ .../shadow-glob-module-resolution-1.rs | 17 +++++++++++ .../shadow-glob-module-resolution-1.stderr | 23 +++++++++++++++ .../shadow-glob-module-resolution-2.rs | 19 ++++++++++++ .../shadow-glob-module-resolution-2.stderr | 26 +++++++++++++++++ 11 files changed, 142 insertions(+), 41 deletions(-) delete mode 100644 tests/crashes/124490.rs delete mode 100644 tests/crashes/125013-1.rs delete mode 100644 tests/crashes/125013-2.rs create mode 100644 tests/ui/imports/cycle-import-in-diff-module-0.rs create mode 100644 tests/ui/imports/cycle-import-in-diff-module-1.rs create mode 100644 tests/ui/imports/shadow-glob-module-resolution-1.rs create mode 100644 tests/ui/imports/shadow-glob-module-resolution-1.stderr create mode 100644 tests/ui/imports/shadow-glob-module-resolution-2.rs create mode 100644 tests/ui/imports/shadow-glob-module-resolution-2.stderr diff --git a/compiler/rustc_resolve/src/ident.rs b/compiler/rustc_resolve/src/ident.rs index 57db765c07e55..78bd3c4e49f2e 100644 --- a/compiler/rustc_resolve/src/ident.rs +++ b/compiler/rustc_resolve/src/ident.rs @@ -965,6 +965,21 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { // if it can then our result is not determined and can be invalidated. for single_import in &resolution.single_imports { let Some(import_vis) = single_import.vis.get() else { + // This branch handles a cycle in single imports, which occurs + // when we've previously captured the `vis` value during an import + // process. + // + // For example: + // ``` + // use a::b; + // use b as a; + // ``` + // 1. Steal the `vis` in `use a::b` and attempt to locate `a` in the + // current module. + // 2. Encounter the import `use b as a`, which is a `single_import` for `a`, + // and try to find `b` in the current module. + // 3. Re-encounter the `use a::b` import since it's a `single_import` of `b`. + // This leads to entering this branch. continue; }; if !self.is_accessible_from(import_vis, parent_scope.module) { @@ -979,15 +994,25 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { // named imports. continue; } + let Some(module) = single_import.imported_module.get() else { return Err((Undetermined, Weak::No)); }; - let ImportKind::Single { source: ident, .. } = single_import.kind else { + let ImportKind::Single { source: ident, source_bindings, .. } = &single_import.kind + else { unreachable!(); }; + if binding.map_or(false, |binding| binding.module().is_some()) + && source_bindings.iter().all(|binding| matches!(binding.get(), Err(Undetermined))) + { + // This branch allows the binding to be defined or updated later, + // avoiding module inconsistency between the resolve process and the finalize process. + // See more details in #124840 + return Err((Undetermined, Weak::No)); + } match self.resolve_ident_in_module( module, - ident, + *ident, ns, &single_import.parent_scope, None, diff --git a/compiler/rustc_resolve/src/imports.rs b/compiler/rustc_resolve/src/imports.rs index 6bbde26db3443..27ea7760f5893 100644 --- a/compiler/rustc_resolve/src/imports.rs +++ b/compiler/rustc_resolve/src/imports.rs @@ -352,9 +352,9 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { (old_glob @ true, false) | (old_glob @ false, true) => { let (glob_binding, nonglob_binding) = if old_glob { (old_binding, binding) } else { (binding, old_binding) }; - if glob_binding.res() != nonglob_binding.res() - && key.ns == MacroNS + if key.ns == MacroNS && nonglob_binding.expansion != LocalExpnId::ROOT + && glob_binding.res() != nonglob_binding.res() { resolution.binding = Some(this.ambiguity( AmbiguityKind::GlobVsExpanded, diff --git a/tests/crashes/124490.rs b/tests/crashes/124490.rs deleted file mode 100644 index 9f605c32cf261..0000000000000 --- a/tests/crashes/124490.rs +++ /dev/null @@ -1,16 +0,0 @@ -//@ known-bug: rust-lang/rust#124490 -use io::{self as std}; -use std::collections::{self as io}; - -mod a { - pub mod b { - pub mod c {} - } -} - -use a::*; - -use b::c; -use c as b; - -fn main() {} diff --git a/tests/crashes/125013-1.rs b/tests/crashes/125013-1.rs deleted file mode 100644 index ae66d7a146698..0000000000000 --- a/tests/crashes/125013-1.rs +++ /dev/null @@ -1,5 +0,0 @@ -//@ known-bug: rust-lang/rust#125013 -//@ edition:2021 -use io::{self as std}; -use std::ops::Deref::{self as io}; -pub fn main() {} diff --git a/tests/crashes/125013-2.rs b/tests/crashes/125013-2.rs deleted file mode 100644 index a14c8a76b63ee..0000000000000 --- a/tests/crashes/125013-2.rs +++ /dev/null @@ -1,16 +0,0 @@ -//@ known-bug: rust-lang/rust#125013 -//@ edition:2021 -mod a { - pub mod b { - pub mod c { - pub trait D {} - } - } -} - -use a::*; - -use e as b; -use b::c::D as e; - -fn main() { } diff --git a/tests/ui/imports/cycle-import-in-diff-module-0.rs b/tests/ui/imports/cycle-import-in-diff-module-0.rs new file mode 100644 index 0000000000000..962603a89716c --- /dev/null +++ b/tests/ui/imports/cycle-import-in-diff-module-0.rs @@ -0,0 +1,14 @@ +//@ check-pass + +// https://github.com/rust-lang/rust/pull/124840#issuecomment-2098148587 + +mod a { + pub(crate) use crate::S; +} +mod b { + pub struct S; +} +use self::a::S; +use self::b::*; + +fn main() {} diff --git a/tests/ui/imports/cycle-import-in-diff-module-1.rs b/tests/ui/imports/cycle-import-in-diff-module-1.rs new file mode 100644 index 0000000000000..8c67df376c3f9 --- /dev/null +++ b/tests/ui/imports/cycle-import-in-diff-module-1.rs @@ -0,0 +1,14 @@ +//@ check-pass + +// similar `cycle-import-in-diff-module-0.rs` + +mod a { + pub(crate) use crate::s; +} +mod b { + pub mod s {} +} +use self::b::*; +use self::a::s; + +fn main() {} diff --git a/tests/ui/imports/shadow-glob-module-resolution-1.rs b/tests/ui/imports/shadow-glob-module-resolution-1.rs new file mode 100644 index 0000000000000..ba1e65cddc652 --- /dev/null +++ b/tests/ui/imports/shadow-glob-module-resolution-1.rs @@ -0,0 +1,17 @@ +// https://github.com/rust-lang/rust/issues/124490 + +mod a { + pub mod b { + pub mod c {} + } +} + +use a::*; + +use b::c; +//~^ ERROR: cannot determine resolution for the import +//~| ERROR: cannot determine resolution for the import +//~| ERROR: unresolved import `b::c` +use c as b; + +fn main() {} diff --git a/tests/ui/imports/shadow-glob-module-resolution-1.stderr b/tests/ui/imports/shadow-glob-module-resolution-1.stderr new file mode 100644 index 0000000000000..f9135963fe99e --- /dev/null +++ b/tests/ui/imports/shadow-glob-module-resolution-1.stderr @@ -0,0 +1,23 @@ +error: cannot determine resolution for the import + --> $DIR/shadow-glob-module-resolution-1.rs:11:5 + | +LL | use b::c; + | ^^^^ + +error: cannot determine resolution for the import + --> $DIR/shadow-glob-module-resolution-1.rs:11:5 + | +LL | use b::c; + | ^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + +error[E0432]: unresolved import `b::c` + --> $DIR/shadow-glob-module-resolution-1.rs:11:5 + | +LL | use b::c; + | ^^^^ + +error: aborting due to 3 previous errors + +For more information about this error, try `rustc --explain E0432`. diff --git a/tests/ui/imports/shadow-glob-module-resolution-2.rs b/tests/ui/imports/shadow-glob-module-resolution-2.rs new file mode 100644 index 0000000000000..36bd72658ae84 --- /dev/null +++ b/tests/ui/imports/shadow-glob-module-resolution-2.rs @@ -0,0 +1,19 @@ +// https://github.com/rust-lang/rust/issues/125013 + +mod a { + pub mod b { + pub mod c { + pub trait D {} + } + } +} + +use a::*; + +use e as b; +//~^ ERROR: unresolved import `e` +use b::c::D as e; +//~^ ERROR: cannot determine resolution for the import +//~| ERROR: cannot determine resolution for the import + +fn main() { } diff --git a/tests/ui/imports/shadow-glob-module-resolution-2.stderr b/tests/ui/imports/shadow-glob-module-resolution-2.stderr new file mode 100644 index 0000000000000..644fcb8416289 --- /dev/null +++ b/tests/ui/imports/shadow-glob-module-resolution-2.stderr @@ -0,0 +1,26 @@ +error: cannot determine resolution for the import + --> $DIR/shadow-glob-module-resolution-2.rs:15:5 + | +LL | use b::c::D as e; + | ^^^^^^^^^^^^ + +error: cannot determine resolution for the import + --> $DIR/shadow-glob-module-resolution-2.rs:15:5 + | +LL | use b::c::D as e; + | ^^^^^^^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + +error[E0432]: unresolved import `e` + --> $DIR/shadow-glob-module-resolution-2.rs:13:5 + | +LL | use e as b; + | -^^^^^ + | | + | no `e` in the root + | help: a similar name exists in the module: `a` + +error: aborting due to 3 previous errors + +For more information about this error, try `rustc --explain E0432`. From 4f473422a93eff8e2c9919a67e16543090961f8b Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Tue, 4 Jun 2024 13:55:15 +0000 Subject: [PATCH 09/17] Add regression tests --- .../auto-trait-selection-freeze.next.stderr | 22 +++++++++++++++++ .../impl-trait/auto-trait-selection-freeze.rs | 24 +++++++++++++++++++ .../auto-trait-selection.next.stderr | 22 +++++++++++++++++ tests/ui/impl-trait/auto-trait-selection.rs | 20 ++++++++++++++++ 4 files changed, 88 insertions(+) create mode 100644 tests/ui/impl-trait/auto-trait-selection-freeze.next.stderr create mode 100644 tests/ui/impl-trait/auto-trait-selection-freeze.rs create mode 100644 tests/ui/impl-trait/auto-trait-selection.next.stderr create mode 100644 tests/ui/impl-trait/auto-trait-selection.rs diff --git a/tests/ui/impl-trait/auto-trait-selection-freeze.next.stderr b/tests/ui/impl-trait/auto-trait-selection-freeze.next.stderr new file mode 100644 index 0000000000000..d9192e854971f --- /dev/null +++ b/tests/ui/impl-trait/auto-trait-selection-freeze.next.stderr @@ -0,0 +1,22 @@ +error[E0283]: type annotations needed + --> $DIR/auto-trait-selection-freeze.rs:20:16 + | +LL | if false { is_trait(foo()) } else { Default::default() } + | ^^^^^^^^ ----- type must be known at this point + | | + | cannot infer type of the type parameter `T` declared on the function `is_trait` + | + = note: cannot satisfy `_: Trait<_>` +note: required by a bound in `is_trait` + --> $DIR/auto-trait-selection-freeze.rs:12:16 + | +LL | fn is_trait, U: Default>(_: T) -> U { + | ^^^^^^^^ required by this bound in `is_trait` +help: consider specifying the generic arguments + | +LL | if false { is_trait::(foo()) } else { Default::default() } + | ++++++++ + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0283`. diff --git a/tests/ui/impl-trait/auto-trait-selection-freeze.rs b/tests/ui/impl-trait/auto-trait-selection-freeze.rs new file mode 100644 index 0000000000000..72c24c5196221 --- /dev/null +++ b/tests/ui/impl-trait/auto-trait-selection-freeze.rs @@ -0,0 +1,24 @@ +//! This test shows how we fail selection in a way that can influence +//! selection in a code path that succeeds. + +//@ revisions: next old +//@[next] compile-flags: -Znext-solver +//@[old]check-pass + +#![feature(freeze)] + +use std::marker::Freeze; + +fn is_trait, U: Default>(_: T) -> U { + Default::default() +} + +trait Trait {} +impl Trait for T {} +impl Trait for T {} +fn foo() -> impl Sized { + if false { is_trait(foo()) } else { Default::default() } + //[next]~^ ERROR: type annotations needed +} + +fn main() {} diff --git a/tests/ui/impl-trait/auto-trait-selection.next.stderr b/tests/ui/impl-trait/auto-trait-selection.next.stderr new file mode 100644 index 0000000000000..2e8d7ad99b290 --- /dev/null +++ b/tests/ui/impl-trait/auto-trait-selection.next.stderr @@ -0,0 +1,22 @@ +error[E0283]: type annotations needed + --> $DIR/auto-trait-selection.rs:16:16 + | +LL | if false { is_trait(foo()) } else { Default::default() } + | ^^^^^^^^ ----- type must be known at this point + | | + | cannot infer type of the type parameter `T` declared on the function `is_trait` + | + = note: cannot satisfy `_: Trait<_>` +note: required by a bound in `is_trait` + --> $DIR/auto-trait-selection.rs:8:16 + | +LL | fn is_trait, U: Default>(_: T) -> U { + | ^^^^^^^^ required by this bound in `is_trait` +help: consider specifying the generic arguments + | +LL | if false { is_trait::(foo()) } else { Default::default() } + | ++++++++ + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0283`. diff --git a/tests/ui/impl-trait/auto-trait-selection.rs b/tests/ui/impl-trait/auto-trait-selection.rs new file mode 100644 index 0000000000000..beb0b189fd7f7 --- /dev/null +++ b/tests/ui/impl-trait/auto-trait-selection.rs @@ -0,0 +1,20 @@ +//! This test shows how we fail selection in a way that can influence +//! selection in a code path that succeeds. + +//@ revisions: next old +//@[next] compile-flags: -Znext-solver +//@[old]check-pass + +fn is_trait, U: Default>(_: T) -> U { + Default::default() +} + +trait Trait {} +impl Trait for T {} +impl Trait for T {} +fn foo() -> impl Sized { + if false { is_trait(foo()) } else { Default::default() } + //[next]~^ ERROR: type annotations needed +} + +fn main() {} From 5e8df95dbb445b2891610a9e46ce31c2b615bc09 Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Mon, 27 May 2024 13:01:16 +0000 Subject: [PATCH 10/17] Manual rustfmt --- compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs index 58eb0c2817987..5f73b3b618f5f 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs @@ -1419,8 +1419,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.dcx().span_delayed_bug( span, format!( - "instantiate_value_path: (UFCS) {self_ty:?} was a subtype of {impl_ty:?} but now is not?", - ), + "instantiate_value_path: (UFCS) {self_ty:?} was a subtype of {impl_ty:?} but now is not?", + ), ); } } From 14f9c63759b67ad725dbecb003bcb7752fc92d69 Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Tue, 28 May 2024 06:32:35 +0000 Subject: [PATCH 11/17] Show that it will pick up the entirely wrong function as a private candidate --- src/tools/tidy/src/ui_tests.rs | 2 +- ...3498.stderr => issue-53498.different_name.stderr} | 2 +- tests/ui/issues/issue-53498.rs | 9 ++++++++- tests/ui/issues/issue-53498.same_name.stderr | 12 ++++++++++++ 4 files changed, 22 insertions(+), 3 deletions(-) rename tests/ui/issues/{issue-53498.stderr => issue-53498.different_name.stderr} (91%) create mode 100644 tests/ui/issues/issue-53498.same_name.stderr diff --git a/src/tools/tidy/src/ui_tests.rs b/src/tools/tidy/src/ui_tests.rs index cce0fb2c1a25b..37ce335c9a3dd 100644 --- a/src/tools/tidy/src/ui_tests.rs +++ b/src/tools/tidy/src/ui_tests.rs @@ -15,7 +15,7 @@ use std::path::{Path, PathBuf}; const ENTRY_LIMIT: u32 = 900; // FIXME: The following limits should be reduced eventually. -const ISSUES_ENTRY_LIMIT: u32 = 1674; +const ISSUES_ENTRY_LIMIT: u32 = 1675; const EXPECTED_TEST_FILE_EXTENSIONS: &[&str] = &[ "rs", // test source files diff --git a/tests/ui/issues/issue-53498.stderr b/tests/ui/issues/issue-53498.different_name.stderr similarity index 91% rename from tests/ui/issues/issue-53498.stderr rename to tests/ui/issues/issue-53498.different_name.stderr index 61a1aedf50821..45ee858ac9215 100644 --- a/tests/ui/issues/issue-53498.stderr +++ b/tests/ui/issues/issue-53498.different_name.stderr @@ -1,5 +1,5 @@ error[E0624]: associated function `foo` is private - --> $DIR/issue-53498.rs:16:27 + --> $DIR/issue-53498.rs:21:27 | LL | fn foo() {} | -------- private associated function defined here diff --git a/tests/ui/issues/issue-53498.rs b/tests/ui/issues/issue-53498.rs index 9e0437c46f4bd..816d3f9e448fa 100644 --- a/tests/ui/issues/issue-53498.rs +++ b/tests/ui/issues/issue-53498.rs @@ -1,3 +1,5 @@ +//@ revisions: same_name different_name + pub mod test { pub struct A; pub struct B; @@ -8,10 +10,15 @@ pub mod test { } impl Foo { + #[cfg(same_name)] fn foo() {} + #[cfg(different_name)] + fn bar() {} } } fn main() { - test::Foo::::foo(); //~ ERROR associated function `foo` is private + test::Foo::::foo(); + //[same_name]~^ ERROR associated function `foo` is private + //[different_name]~^^ ERROR associated function `foo` is private } diff --git a/tests/ui/issues/issue-53498.same_name.stderr b/tests/ui/issues/issue-53498.same_name.stderr new file mode 100644 index 0000000000000..45ee858ac9215 --- /dev/null +++ b/tests/ui/issues/issue-53498.same_name.stderr @@ -0,0 +1,12 @@ +error[E0624]: associated function `foo` is private + --> $DIR/issue-53498.rs:21:27 + | +LL | fn foo() {} + | -------- private associated function defined here +... +LL | test::Foo::::foo(); + | ^^^ private associated function + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0624`. From 7d151fa3b015ad1dbac18933c58db3413a964534 Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Mon, 27 May 2024 15:51:21 +0000 Subject: [PATCH 12/17] Turn a delayed bug back into a normal bug by winnowing private method candidates instead of assuming any candidate of the right name will apply. --- .../rustc_hir_typeck/src/fn_ctxt/_impl.rs | 4 +-- compiler/rustc_hir_typeck/src/method/probe.rs | 28 ++++++++++++++----- .../issues/issue-53498.different_name.stderr | 13 +++++---- tests/ui/issues/issue-53498.rs | 2 +- 4 files changed, 32 insertions(+), 15 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs index 5f73b3b618f5f..4bd73dc6c9425 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs @@ -1072,7 +1072,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ty::ImplContainer => { if segments.len() == 1 { // `::assoc` will end up here, and so - // can `T::assoc`. It this came from an + // can `T::assoc`. If this came from an // inherent impl, we need to record the // `T` for posterity (see `UserSelfTy` for // details). @@ -1416,7 +1416,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) { Ok(ok) => self.register_infer_ok_obligations(ok), Err(_) => { - self.dcx().span_delayed_bug( + self.dcx().span_bug( span, format!( "instantiate_value_path: (UFCS) {self_ty:?} was a subtype of {impl_ty:?} but now is not?", diff --git a/compiler/rustc_hir_typeck/src/method/probe.rs b/compiler/rustc_hir_typeck/src/method/probe.rs index 12ced49f92ff7..ab0f16bd87d07 100644 --- a/compiler/rustc_hir_typeck/src/method/probe.rs +++ b/compiler/rustc_hir_typeck/src/method/probe.rs @@ -41,6 +41,7 @@ use rustc_trait_selection::traits::query::method_autoderef::{ use rustc_trait_selection::traits::query::CanonicalTyGoal; use rustc_trait_selection::traits::ObligationCtxt; use rustc_trait_selection::traits::{self, ObligationCause}; +use std::cell::Cell; use std::cell::RefCell; use std::cmp::max; use std::iter; @@ -76,8 +77,12 @@ pub(crate) struct ProbeContext<'a, 'tcx> { /// requested name (by edit distance) allow_similar_names: bool, + /// List of potential private candidates. Will be trimmed to ones that + /// actually apply and then the result inserted into `private_candidate` + private_candidates: Vec>, + /// Some(candidate) if there is a private candidate - private_candidate: Option<(DefKind, DefId)>, + private_candidate: Cell>, /// Collects near misses when the candidate functions are missing a `self` keyword and is only /// used for error reporting @@ -581,7 +586,8 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { orig_steps_var_values, steps, allow_similar_names: false, - private_candidate: None, + private_candidates: Vec::new(), + private_candidate: Cell::new(None), static_candidates: RefCell::new(Vec::new()), unsatisfied_predicates: RefCell::new(Vec::new()), scope_expr_id, @@ -593,7 +599,8 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { self.inherent_candidates.clear(); self.extension_candidates.clear(); self.impl_dups.clear(); - self.private_candidate = None; + self.private_candidates.clear(); + self.private_candidate.set(None); self.static_candidates.borrow_mut().clear(); self.unsatisfied_predicates.borrow_mut().clear(); } @@ -617,9 +624,8 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { } else { self.extension_candidates.push(candidate); } - } else if self.private_candidate.is_none() { - self.private_candidate = - Some((candidate.item.kind.as_def_kind(), candidate.item.def_id)); + } else { + self.private_candidates.push(candidate); } } @@ -1171,7 +1177,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { let mut possibly_unsatisfied_predicates = Vec::new(); for (kind, candidates) in - &[("inherent", &self.inherent_candidates), ("extension", &self.extension_candidates)] + [("inherent", &self.inherent_candidates), ("extension", &self.extension_candidates)] { debug!("searching {} candidates", kind); let res = self.consider_candidates( @@ -1185,6 +1191,14 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { } } + if self.private_candidate.get().is_none() { + if let Some(Ok(pick)) = + self.consider_candidates(self_ty, &self.private_candidates, &mut vec![], None) + { + self.private_candidate.set(Some((pick.item.kind.as_def_kind(), pick.item.def_id))); + } + } + // `pick_method` may be called twice for the same self_ty if no stable methods // match. Only extend once. if unstable_candidates.is_some() { diff --git a/tests/ui/issues/issue-53498.different_name.stderr b/tests/ui/issues/issue-53498.different_name.stderr index 45ee858ac9215..fc765f2e75d3f 100644 --- a/tests/ui/issues/issue-53498.different_name.stderr +++ b/tests/ui/issues/issue-53498.different_name.stderr @@ -1,12 +1,15 @@ -error[E0624]: associated function `foo` is private +error[E0599]: no function or associated item named `foo` found for struct `Foo` in the current scope --> $DIR/issue-53498.rs:21:27 | -LL | fn foo() {} - | -------- private associated function defined here +LL | pub struct Foo(T); + | ----------------- function or associated item `foo` not found for this struct ... LL | test::Foo::::foo(); - | ^^^ private associated function + | ^^^ function or associated item not found in `Foo` + | + = note: the function or associated item was found for + - `Foo` error: aborting due to 1 previous error -For more information about this error, try `rustc --explain E0624`. +For more information about this error, try `rustc --explain E0599`. diff --git a/tests/ui/issues/issue-53498.rs b/tests/ui/issues/issue-53498.rs index 816d3f9e448fa..64eb3a0c5fd4e 100644 --- a/tests/ui/issues/issue-53498.rs +++ b/tests/ui/issues/issue-53498.rs @@ -20,5 +20,5 @@ pub mod test { fn main() { test::Foo::::foo(); //[same_name]~^ ERROR associated function `foo` is private - //[different_name]~^^ ERROR associated function `foo` is private + //[different_name]~^^ ERROR no function or associated item named `foo` found for struct `Foo` } From 7894a1148371e4d0fa665c183615a76f9e2ec656 Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Tue, 28 May 2024 09:26:40 +0000 Subject: [PATCH 13/17] Move tests to a more appropriate directory --- src/tools/tidy/src/ui_tests.rs | 2 +- tests/ui/{issues => privacy}/issue-53498.different_name.stderr | 0 tests/ui/{issues => privacy}/issue-53498.rs | 0 tests/ui/{issues => privacy}/issue-53498.same_name.stderr | 0 4 files changed, 1 insertion(+), 1 deletion(-) rename tests/ui/{issues => privacy}/issue-53498.different_name.stderr (100%) rename tests/ui/{issues => privacy}/issue-53498.rs (100%) rename tests/ui/{issues => privacy}/issue-53498.same_name.stderr (100%) diff --git a/src/tools/tidy/src/ui_tests.rs b/src/tools/tidy/src/ui_tests.rs index 37ce335c9a3dd..f2eeda339d80e 100644 --- a/src/tools/tidy/src/ui_tests.rs +++ b/src/tools/tidy/src/ui_tests.rs @@ -15,7 +15,7 @@ use std::path::{Path, PathBuf}; const ENTRY_LIMIT: u32 = 900; // FIXME: The following limits should be reduced eventually. -const ISSUES_ENTRY_LIMIT: u32 = 1675; +const ISSUES_ENTRY_LIMIT: u32 = 1672; const EXPECTED_TEST_FILE_EXTENSIONS: &[&str] = &[ "rs", // test source files diff --git a/tests/ui/issues/issue-53498.different_name.stderr b/tests/ui/privacy/issue-53498.different_name.stderr similarity index 100% rename from tests/ui/issues/issue-53498.different_name.stderr rename to tests/ui/privacy/issue-53498.different_name.stderr diff --git a/tests/ui/issues/issue-53498.rs b/tests/ui/privacy/issue-53498.rs similarity index 100% rename from tests/ui/issues/issue-53498.rs rename to tests/ui/privacy/issue-53498.rs diff --git a/tests/ui/issues/issue-53498.same_name.stderr b/tests/ui/privacy/issue-53498.same_name.stderr similarity index 100% rename from tests/ui/issues/issue-53498.same_name.stderr rename to tests/ui/privacy/issue-53498.same_name.stderr From 81895065bb541b9e79f402d2446c1c83243b37d0 Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Tue, 28 May 2024 09:32:53 +0000 Subject: [PATCH 14/17] Give test a more useful name --- src/tools/tidy/src/issues.txt | 1 - ...ferent_name.stderr => ufc-method-call.different_name.stderr} | 2 +- tests/ui/privacy/{issue-53498.rs => ufc-method-call.rs} | 0 ...-53498.same_name.stderr => ufc-method-call.same_name.stderr} | 2 +- 4 files changed, 2 insertions(+), 3 deletions(-) rename tests/ui/privacy/{issue-53498.different_name.stderr => ufc-method-call.different_name.stderr} (93%) rename tests/ui/privacy/{issue-53498.rs => ufc-method-call.rs} (100%) rename tests/ui/privacy/{issue-53498.same_name.stderr => ufc-method-call.same_name.stderr} (90%) diff --git a/src/tools/tidy/src/issues.txt b/src/tools/tidy/src/issues.txt index 398a6fd0fbaaa..a6ba8959f0c5d 100644 --- a/src/tools/tidy/src/issues.txt +++ b/src/tools/tidy/src/issues.txt @@ -2445,7 +2445,6 @@ ui/issues/issue-53300.rs ui/issues/issue-53333.rs ui/issues/issue-53348.rs ui/issues/issue-53419.rs -ui/issues/issue-53498.rs ui/issues/issue-53568.rs ui/issues/issue-5358-1.rs ui/issues/issue-53728.rs diff --git a/tests/ui/privacy/issue-53498.different_name.stderr b/tests/ui/privacy/ufc-method-call.different_name.stderr similarity index 93% rename from tests/ui/privacy/issue-53498.different_name.stderr rename to tests/ui/privacy/ufc-method-call.different_name.stderr index fc765f2e75d3f..80321b1c11cb4 100644 --- a/tests/ui/privacy/issue-53498.different_name.stderr +++ b/tests/ui/privacy/ufc-method-call.different_name.stderr @@ -1,5 +1,5 @@ error[E0599]: no function or associated item named `foo` found for struct `Foo` in the current scope - --> $DIR/issue-53498.rs:21:27 + --> $DIR/ufc-method-call.rs:21:27 | LL | pub struct Foo(T); | ----------------- function or associated item `foo` not found for this struct diff --git a/tests/ui/privacy/issue-53498.rs b/tests/ui/privacy/ufc-method-call.rs similarity index 100% rename from tests/ui/privacy/issue-53498.rs rename to tests/ui/privacy/ufc-method-call.rs diff --git a/tests/ui/privacy/issue-53498.same_name.stderr b/tests/ui/privacy/ufc-method-call.same_name.stderr similarity index 90% rename from tests/ui/privacy/issue-53498.same_name.stderr rename to tests/ui/privacy/ufc-method-call.same_name.stderr index 45ee858ac9215..c66ae0a6b2527 100644 --- a/tests/ui/privacy/issue-53498.same_name.stderr +++ b/tests/ui/privacy/ufc-method-call.same_name.stderr @@ -1,5 +1,5 @@ error[E0624]: associated function `foo` is private - --> $DIR/issue-53498.rs:21:27 + --> $DIR/ufc-method-call.rs:21:27 | LL | fn foo() {} | -------- private associated function defined here From ffb1b2c14809ae5d15a078a9cce5299865d7dd73 Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Tue, 28 May 2024 09:34:16 +0000 Subject: [PATCH 15/17] Add test description --- tests/ui/privacy/ufc-method-call.different_name.stderr | 2 +- tests/ui/privacy/ufc-method-call.rs | 6 ++++++ tests/ui/privacy/ufc-method-call.same_name.stderr | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/tests/ui/privacy/ufc-method-call.different_name.stderr b/tests/ui/privacy/ufc-method-call.different_name.stderr index 80321b1c11cb4..16496c480dd12 100644 --- a/tests/ui/privacy/ufc-method-call.different_name.stderr +++ b/tests/ui/privacy/ufc-method-call.different_name.stderr @@ -1,5 +1,5 @@ error[E0599]: no function or associated item named `foo` found for struct `Foo` in the current scope - --> $DIR/ufc-method-call.rs:21:27 + --> $DIR/ufc-method-call.rs:27:27 | LL | pub struct Foo(T); | ----------------- function or associated item `foo` not found for this struct diff --git a/tests/ui/privacy/ufc-method-call.rs b/tests/ui/privacy/ufc-method-call.rs index 64eb3a0c5fd4e..525d9a9eee904 100644 --- a/tests/ui/privacy/ufc-method-call.rs +++ b/tests/ui/privacy/ufc-method-call.rs @@ -1,3 +1,9 @@ +//! This test used to report that the method call cannot +//! call the private method `Foo::foo`, even though the user +//! explicitly selected `Foo::foo`. This is because we only +//! looked for methods of the right name, without properly checking +//! the `Self` type + //@ revisions: same_name different_name pub mod test { diff --git a/tests/ui/privacy/ufc-method-call.same_name.stderr b/tests/ui/privacy/ufc-method-call.same_name.stderr index c66ae0a6b2527..194ba42cbf985 100644 --- a/tests/ui/privacy/ufc-method-call.same_name.stderr +++ b/tests/ui/privacy/ufc-method-call.same_name.stderr @@ -1,5 +1,5 @@ error[E0624]: associated function `foo` is private - --> $DIR/ufc-method-call.rs:21:27 + --> $DIR/ufc-method-call.rs:27:27 | LL | fn foo() {} | -------- private associated function defined here From ad6e85be316b72e85ed46f21e3a32908fb2cbc1b Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Tue, 4 Jun 2024 16:20:01 +0000 Subject: [PATCH 16/17] Do not assemble candidates for auto traits of opaque types in their defining scope --- .../src/traits/select/candidate_assembly.rs | 7 ++++- .../auto-trait-selection-freeze.next.stderr | 4 +-- .../auto-trait-selection-freeze.old.stderr | 26 +++++++++++++++++++ .../impl-trait/auto-trait-selection-freeze.rs | 3 +-- .../auto-trait-selection.next.stderr | 4 +-- .../auto-trait-selection.old.stderr | 26 +++++++++++++++++++ tests/ui/impl-trait/auto-trait-selection.rs | 3 +-- .../type-alias-impl-trait/in-where-clause.rs | 1 + .../in-where-clause.stderr | 13 ++++++++-- 9 files changed, 76 insertions(+), 11 deletions(-) create mode 100644 tests/ui/impl-trait/auto-trait-selection-freeze.old.stderr create mode 100644 tests/ui/impl-trait/auto-trait-selection.old.stderr diff --git a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs index d513a5d2996c6..98a569d87de21 100644 --- a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs +++ b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs @@ -777,7 +777,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { ); } - ty::Alias(ty::Opaque, _) => { + ty::Alias(ty::Opaque, alias) => { if candidates.vec.iter().any(|c| matches!(c, ProjectionCandidate(_))) { // We do not generate an auto impl candidate for `impl Trait`s which already // reference our auto trait. @@ -792,6 +792,11 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { // We do not emit auto trait candidates for opaque types in coherence. // Doing so can result in weird dependency cycles. candidates.ambiguous = true; + } else if self.infcx.can_define_opaque_ty(alias.def_id) { + // We do not emit auto trait candidates for opaque types in their defining scope, as + // we need to know the hidden type first, which we can't reliably know within the defining + // scope. + candidates.ambiguous = true; } else { candidates.vec.push(AutoImplCandidate) } diff --git a/tests/ui/impl-trait/auto-trait-selection-freeze.next.stderr b/tests/ui/impl-trait/auto-trait-selection-freeze.next.stderr index d9192e854971f..5caf0eb2fd4e3 100644 --- a/tests/ui/impl-trait/auto-trait-selection-freeze.next.stderr +++ b/tests/ui/impl-trait/auto-trait-selection-freeze.next.stderr @@ -1,5 +1,5 @@ error[E0283]: type annotations needed - --> $DIR/auto-trait-selection-freeze.rs:20:16 + --> $DIR/auto-trait-selection-freeze.rs:19:16 | LL | if false { is_trait(foo()) } else { Default::default() } | ^^^^^^^^ ----- type must be known at this point @@ -8,7 +8,7 @@ LL | if false { is_trait(foo()) } else { Default::default() } | = note: cannot satisfy `_: Trait<_>` note: required by a bound in `is_trait` - --> $DIR/auto-trait-selection-freeze.rs:12:16 + --> $DIR/auto-trait-selection-freeze.rs:11:16 | LL | fn is_trait, U: Default>(_: T) -> U { | ^^^^^^^^ required by this bound in `is_trait` diff --git a/tests/ui/impl-trait/auto-trait-selection-freeze.old.stderr b/tests/ui/impl-trait/auto-trait-selection-freeze.old.stderr new file mode 100644 index 0000000000000..b4d2229d408d2 --- /dev/null +++ b/tests/ui/impl-trait/auto-trait-selection-freeze.old.stderr @@ -0,0 +1,26 @@ +error[E0283]: type annotations needed + --> $DIR/auto-trait-selection-freeze.rs:19:16 + | +LL | if false { is_trait(foo()) } else { Default::default() } + | ^^^^^^^^ cannot infer type of the type parameter `U` declared on the function `is_trait` + | +note: multiple `impl`s satisfying `impl Sized: Trait<_>` found + --> $DIR/auto-trait-selection-freeze.rs:16:1 + | +LL | impl Trait for T {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | impl Trait for T {} + | ^^^^^^^^^^^^^^^^^^^^^^^^ +note: required by a bound in `is_trait` + --> $DIR/auto-trait-selection-freeze.rs:11:16 + | +LL | fn is_trait, U: Default>(_: T) -> U { + | ^^^^^^^^ required by this bound in `is_trait` +help: consider specifying the generic arguments + | +LL | if false { is_trait::<_, U>(foo()) } else { Default::default() } + | ++++++++ + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0283`. diff --git a/tests/ui/impl-trait/auto-trait-selection-freeze.rs b/tests/ui/impl-trait/auto-trait-selection-freeze.rs index 72c24c5196221..7306a1c41f746 100644 --- a/tests/ui/impl-trait/auto-trait-selection-freeze.rs +++ b/tests/ui/impl-trait/auto-trait-selection-freeze.rs @@ -3,7 +3,6 @@ //@ revisions: next old //@[next] compile-flags: -Znext-solver -//@[old]check-pass #![feature(freeze)] @@ -18,7 +17,7 @@ impl Trait for T {} impl Trait for T {} fn foo() -> impl Sized { if false { is_trait(foo()) } else { Default::default() } - //[next]~^ ERROR: type annotations needed + //~^ ERROR: type annotations needed } fn main() {} diff --git a/tests/ui/impl-trait/auto-trait-selection.next.stderr b/tests/ui/impl-trait/auto-trait-selection.next.stderr index 2e8d7ad99b290..d34fdcc44967f 100644 --- a/tests/ui/impl-trait/auto-trait-selection.next.stderr +++ b/tests/ui/impl-trait/auto-trait-selection.next.stderr @@ -1,5 +1,5 @@ error[E0283]: type annotations needed - --> $DIR/auto-trait-selection.rs:16:16 + --> $DIR/auto-trait-selection.rs:15:16 | LL | if false { is_trait(foo()) } else { Default::default() } | ^^^^^^^^ ----- type must be known at this point @@ -8,7 +8,7 @@ LL | if false { is_trait(foo()) } else { Default::default() } | = note: cannot satisfy `_: Trait<_>` note: required by a bound in `is_trait` - --> $DIR/auto-trait-selection.rs:8:16 + --> $DIR/auto-trait-selection.rs:7:16 | LL | fn is_trait, U: Default>(_: T) -> U { | ^^^^^^^^ required by this bound in `is_trait` diff --git a/tests/ui/impl-trait/auto-trait-selection.old.stderr b/tests/ui/impl-trait/auto-trait-selection.old.stderr new file mode 100644 index 0000000000000..1b5fd95fdf903 --- /dev/null +++ b/tests/ui/impl-trait/auto-trait-selection.old.stderr @@ -0,0 +1,26 @@ +error[E0283]: type annotations needed + --> $DIR/auto-trait-selection.rs:15:16 + | +LL | if false { is_trait(foo()) } else { Default::default() } + | ^^^^^^^^ cannot infer type of the type parameter `U` declared on the function `is_trait` + | +note: multiple `impl`s satisfying `impl Sized: Trait<_>` found + --> $DIR/auto-trait-selection.rs:12:1 + | +LL | impl Trait for T {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | impl Trait for T {} + | ^^^^^^^^^^^^^^^^^^^^^^^^ +note: required by a bound in `is_trait` + --> $DIR/auto-trait-selection.rs:7:16 + | +LL | fn is_trait, U: Default>(_: T) -> U { + | ^^^^^^^^ required by this bound in `is_trait` +help: consider specifying the generic arguments + | +LL | if false { is_trait::<_, U>(foo()) } else { Default::default() } + | ++++++++ + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0283`. diff --git a/tests/ui/impl-trait/auto-trait-selection.rs b/tests/ui/impl-trait/auto-trait-selection.rs index beb0b189fd7f7..ee5612459c257 100644 --- a/tests/ui/impl-trait/auto-trait-selection.rs +++ b/tests/ui/impl-trait/auto-trait-selection.rs @@ -3,7 +3,6 @@ //@ revisions: next old //@[next] compile-flags: -Znext-solver -//@[old]check-pass fn is_trait, U: Default>(_: T) -> U { Default::default() @@ -14,7 +13,7 @@ impl Trait for T {} impl Trait for T {} fn foo() -> impl Sized { if false { is_trait(foo()) } else { Default::default() } - //[next]~^ ERROR: type annotations needed + //~^ ERROR: type annotations needed } fn main() {} diff --git a/tests/ui/type-alias-impl-trait/in-where-clause.rs b/tests/ui/type-alias-impl-trait/in-where-clause.rs index 6e104781d84f3..8fc05023147fd 100644 --- a/tests/ui/type-alias-impl-trait/in-where-clause.rs +++ b/tests/ui/type-alias-impl-trait/in-where-clause.rs @@ -8,6 +8,7 @@ type Bar = impl Sized; fn foo() -> Bar where Bar: Send, + //~^ ERROR: type annotations needed { [0; 1 + 2] } diff --git a/tests/ui/type-alias-impl-trait/in-where-clause.stderr b/tests/ui/type-alias-impl-trait/in-where-clause.stderr index c486013f8874a..197e0fc2c79ec 100644 --- a/tests/ui/type-alias-impl-trait/in-where-clause.stderr +++ b/tests/ui/type-alias-impl-trait/in-where-clause.stderr @@ -25,6 +25,15 @@ LL | type Bar = impl Sized; | ^^^^^^^^^^ = note: see https://rustc-dev-guide.rust-lang.org/overview.html#queries and https://rustc-dev-guide.rust-lang.org/query.html for more information -error: aborting due to 1 previous error +error[E0283]: type annotations needed: cannot satisfy `Bar: Send` + --> $DIR/in-where-clause.rs:10:10 + | +LL | Bar: Send, + | ^^^^ + | + = note: cannot satisfy `Bar: Send` + +error: aborting due to 2 previous errors -For more information about this error, try `rustc --explain E0391`. +Some errors have detailed explanations: E0283, E0391. +For more information about an error, try `rustc --explain E0283`. From 874670399c43c58a6e21d46662979fb4fb8a0b8d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Le=C3=B3n=20Orell=20Valerian=20Liehr?= Date: Sat, 1 Jun 2024 23:44:59 +0200 Subject: [PATCH 17/17] Orphanck: Consider opaque types to never cover type parameters --- .../src/traits/coherence.rs | 59 ++++++++----------- ...k-opaque-types-not-covering.classic.stderr | 21 +++++++ ...heck-opaque-types-not-covering.next.stderr | 21 +++++++ .../orphan-check-opaque-types-not-covering.rs | 31 ++++++++++ ...erence.stderr => coherence.classic.stderr} | 2 +- .../coherence.next.stderr | 14 +++++ tests/ui/type-alias-impl-trait/coherence.rs | 2 + 7 files changed, 114 insertions(+), 36 deletions(-) create mode 100644 tests/ui/coherence/orphan-check-opaque-types-not-covering.classic.stderr create mode 100644 tests/ui/coherence/orphan-check-opaque-types-not-covering.next.stderr create mode 100644 tests/ui/coherence/orphan-check-opaque-types-not-covering.rs rename tests/ui/type-alias-impl-trait/{coherence.stderr => coherence.classic.stderr} (95%) create mode 100644 tests/ui/type-alias-impl-trait/coherence.next.stderr diff --git a/compiler/rustc_trait_selection/src/traits/coherence.rs b/compiler/rustc_trait_selection/src/traits/coherence.rs index ebdb032dc0e25..c81f5ac6e6efb 100644 --- a/compiler/rustc_trait_selection/src/traits/coherence.rs +++ b/compiler/rustc_trait_selection/src/traits/coherence.rs @@ -924,11 +924,12 @@ where } } - ty::Alias(kind @ (ty::Projection | ty::Inherent | ty::Weak), ..) => { - if ty.has_type_flags(ty::TypeFlags::HAS_TY_PARAM) { - bug!("unexpected ty param in alias ty"); - } - + // A rigid alias may normalize to anything. + // * If it references an infer var, placeholder or bound ty, it may + // normalize to that, so we have to treat it as an uncovered ty param. + // * Otherwise it may normalize to any non-type-generic type + // be it local or non-local. + ty::Alias(kind, _) => { if ty.has_type_flags( ty::TypeFlags::HAS_TY_PLACEHOLDER | ty::TypeFlags::HAS_TY_BOUND @@ -948,7 +949,24 @@ where } } } else { - ControlFlow::Continue(()) + // Regarding *opaque types* specifically, we choose to treat them as non-local, + // even those that appear within the same crate. This seems somewhat surprising + // at first, but makes sense when you consider that opaque types are supposed + // to hide the underlying type *within the same crate*. When an opaque type is + // used from outside the module where it is declared, it should be impossible to + // observe anything about it other than the traits that it implements. + // + // The alternative would be to look at the underlying type to determine whether + // or not the opaque type itself should be considered local. + // + // However, this could make it a breaking change to switch the underlying hidden + // type from a local type to a remote type. This would violate the rule that + // opaque types should be completely opaque apart from the traits that they + // implement, so we don't use this behavior. + // Addendum: Moreover, revealing the underlying type is likely to cause cycle + // errors as we rely on coherence / the specialization graph during typeck. + + self.found_non_local_ty(ty) } } @@ -990,35 +1008,6 @@ where // auto trait impl applies. There will never be multiple impls, so we can just // act as if it were a local type here. ty::CoroutineWitness(..) => ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty)), - ty::Alias(ty::Opaque, ..) => { - // This merits some explanation. - // Normally, opaque types are not involved when performing - // coherence checking, since it is illegal to directly - // implement a trait on an opaque type. However, we might - // end up looking at an opaque type during coherence checking - // if an opaque type gets used within another type (e.g. as - // the type of a field) when checking for auto trait or `Sized` - // impls. This requires us to decide whether or not an opaque - // type should be considered 'local' or not. - // - // We choose to treat all opaque types as non-local, even - // those that appear within the same crate. This seems - // somewhat surprising at first, but makes sense when - // you consider that opaque types are supposed to hide - // the underlying type *within the same crate*. When an - // opaque type is used from outside the module - // where it is declared, it should be impossible to observe - // anything about it other than the traits that it implements. - // - // The alternative would be to look at the underlying type - // to determine whether or not the opaque type itself should - // be considered local. However, this could make it a breaking change - // to switch the underlying ('defining') type from a local type - // to a remote type. This would violate the rule that opaque - // types should be completely opaque apart from the traits - // that they implement, so we don't use this behavior. - self.found_non_local_ty(ty) - } }; // A bit of a hack, the `OrphanChecker` is only used to visit a `TraitRef`, so // the first type we visit is always the self type. diff --git a/tests/ui/coherence/orphan-check-opaque-types-not-covering.classic.stderr b/tests/ui/coherence/orphan-check-opaque-types-not-covering.classic.stderr new file mode 100644 index 0000000000000..44f76f321cf10 --- /dev/null +++ b/tests/ui/coherence/orphan-check-opaque-types-not-covering.classic.stderr @@ -0,0 +1,21 @@ +error[E0210]: type parameter `T` must be covered by another type when it appears before the first local type (`Local`) + --> $DIR/orphan-check-opaque-types-not-covering.rs:17:6 + | +LL | impl foreign::Trait0 for Identity {} + | ^ type parameter `T` must be covered by another type when it appears before the first local type (`Local`) + | + = note: implementing a foreign trait is only possible if at least one of the types for which it is implemented is local, and no uncovered type parameters appear before that first local type + = note: in this case, 'before' refers to the following order: `impl<..> ForeignTrait for T0`, where `T0` is the first and `Tn` is the last + +error[E0210]: type parameter `T` must be covered by another type when it appears before the first local type (`Local`) + --> $DIR/orphan-check-opaque-types-not-covering.rs:26:6 + | +LL | impl foreign::Trait1 for Opaque {} + | ^ type parameter `T` must be covered by another type when it appears before the first local type (`Local`) + | + = note: implementing a foreign trait is only possible if at least one of the types for which it is implemented is local, and no uncovered type parameters appear before that first local type + = note: in this case, 'before' refers to the following order: `impl<..> ForeignTrait for T0`, where `T0` is the first and `Tn` is the last + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0210`. diff --git a/tests/ui/coherence/orphan-check-opaque-types-not-covering.next.stderr b/tests/ui/coherence/orphan-check-opaque-types-not-covering.next.stderr new file mode 100644 index 0000000000000..44f76f321cf10 --- /dev/null +++ b/tests/ui/coherence/orphan-check-opaque-types-not-covering.next.stderr @@ -0,0 +1,21 @@ +error[E0210]: type parameter `T` must be covered by another type when it appears before the first local type (`Local`) + --> $DIR/orphan-check-opaque-types-not-covering.rs:17:6 + | +LL | impl foreign::Trait0 for Identity {} + | ^ type parameter `T` must be covered by another type when it appears before the first local type (`Local`) + | + = note: implementing a foreign trait is only possible if at least one of the types for which it is implemented is local, and no uncovered type parameters appear before that first local type + = note: in this case, 'before' refers to the following order: `impl<..> ForeignTrait for T0`, where `T0` is the first and `Tn` is the last + +error[E0210]: type parameter `T` must be covered by another type when it appears before the first local type (`Local`) + --> $DIR/orphan-check-opaque-types-not-covering.rs:26:6 + | +LL | impl foreign::Trait1 for Opaque {} + | ^ type parameter `T` must be covered by another type when it appears before the first local type (`Local`) + | + = note: implementing a foreign trait is only possible if at least one of the types for which it is implemented is local, and no uncovered type parameters appear before that first local type + = note: in this case, 'before' refers to the following order: `impl<..> ForeignTrait for T0`, where `T0` is the first and `Tn` is the last + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0210`. diff --git a/tests/ui/coherence/orphan-check-opaque-types-not-covering.rs b/tests/ui/coherence/orphan-check-opaque-types-not-covering.rs new file mode 100644 index 0000000000000..8dc02b081c51d --- /dev/null +++ b/tests/ui/coherence/orphan-check-opaque-types-not-covering.rs @@ -0,0 +1,31 @@ +// Opaque types never cover type parameters. + +//@ revisions: classic next +//@[next] compile-flags: -Znext-solver + +//@ aux-crate:foreign=parametrized-trait.rs +//@ edition:2021 + +#![feature(type_alias_impl_trait)] + +type Identity = impl Sized; + +fn define_identity(x: T) -> Identity { + x +} + +impl foreign::Trait0 for Identity {} +//~^ ERROR type parameter `T` must be covered by another type + +type Opaque = impl Sized; + +fn define_local() -> Opaque { + Local +} + +impl foreign::Trait1 for Opaque {} +//~^ ERROR type parameter `T` must be covered by another type + +struct Local; + +fn main() {} diff --git a/tests/ui/type-alias-impl-trait/coherence.stderr b/tests/ui/type-alias-impl-trait/coherence.classic.stderr similarity index 95% rename from tests/ui/type-alias-impl-trait/coherence.stderr rename to tests/ui/type-alias-impl-trait/coherence.classic.stderr index 266a532a1db19..ff059bc5806de 100644 --- a/tests/ui/type-alias-impl-trait/coherence.stderr +++ b/tests/ui/type-alias-impl-trait/coherence.classic.stderr @@ -1,5 +1,5 @@ error[E0117]: only traits defined in the current crate can be implemented for arbitrary types - --> $DIR/coherence.rs:14:1 + --> $DIR/coherence.rs:16:1 | LL | impl foreign_crate::ForeignTrait for AliasOfForeignType<()> {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^---------------------- diff --git a/tests/ui/type-alias-impl-trait/coherence.next.stderr b/tests/ui/type-alias-impl-trait/coherence.next.stderr new file mode 100644 index 0000000000000..dab2786c1f0fb --- /dev/null +++ b/tests/ui/type-alias-impl-trait/coherence.next.stderr @@ -0,0 +1,14 @@ +error[E0117]: only traits defined in the current crate can be implemented for arbitrary types + --> $DIR/coherence.rs:16:1 + | +LL | impl foreign_crate::ForeignTrait for AliasOfForeignType<()> {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^---------------------- + | | | + | | `AliasOfForeignType<()>` is not defined in the current crate + | impl doesn't use only types from inside the current crate + | + = note: define and implement a trait or new type instead + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0117`. diff --git a/tests/ui/type-alias-impl-trait/coherence.rs b/tests/ui/type-alias-impl-trait/coherence.rs index 641c0fac17a64..760e5210c5b7a 100644 --- a/tests/ui/type-alias-impl-trait/coherence.rs +++ b/tests/ui/type-alias-impl-trait/coherence.rs @@ -1,4 +1,6 @@ //@ aux-build:foreign-crate.rs +//@ revisions: classic next +//@[next] compile-flags: -Znext-solver #![feature(type_alias_impl_trait)] extern crate foreign_crate;