Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions compiler/rustc_attr_ir/src/data_structures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1296,6 +1296,9 @@ pub enum AttributeKind {
/// Represents `#[rustc_intrinsic_const_stable_indirect]`
RustcIntrinsicConstStableIndirect,

/// Represents `#[rustc_isolated_const]`
RustcIsolatedConst,

/// Represents `#[rustc_legacy_const_generics]`
RustcLegacyConstGenerics {
fn_indexes: ThinVec<(usize, Span)>,
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_attr_ir/src/encode_cross_crate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@ impl AttributeKind {
RustcInsignificantDtor => Yes,
RustcIntrinsic => Yes,
RustcIntrinsicConstStableIndirect => No,
RustcIsolatedConst => Yes,
RustcLegacyConstGenerics { .. } => Yes,
RustcLintOptDenyFieldAccess { .. } => Yes,
RustcLintOptTy => Yes,
Expand Down
9 changes: 9 additions & 0 deletions compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1114,3 +1114,12 @@ impl NoArgsAttributeParser for RustcCanonicalSymbolParser {
);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcCanonicalSymbol;
}

pub(crate) struct RustcIsolatedConstParser;

impl NoArgsAttributeParser for RustcIsolatedConstParser {
const PATH: &[Symbol] = &[sym::rustc_isolated_const];
const ALLOWED_TARGETS: AllowedTargets<'_> = AllowedTargets::AllowList(&[Allow(Target::Const)]);
const STABILITY: AttributeStability = unstable!(rustc_attrs);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcIsolatedConst;
}
1 change: 1 addition & 0 deletions compiler/rustc_attr_parsing/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,7 @@ attribute_parsers!(
Single<WithoutArgs<RustcInsignificantDtorParser>>,
Single<WithoutArgs<RustcIntrinsicConstStableIndirectParser>>,
Single<WithoutArgs<RustcIntrinsicParser>>,
Single<WithoutArgs<RustcIsolatedConstParser>>,
Single<WithoutArgs<RustcLintOptTyParser>>,
Single<WithoutArgs<RustcLintQueryInstabilityParser>>,
Single<WithoutArgs<RustcLintUntrackedQueryInformationParser>>,
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1380,6 +1380,7 @@ impl<'diag, 'tcx> MirBorrowckCtxt<'_, 'diag, 'tcx> {
self.infcx.tcx.for_each_relevant_impl(
self.infcx.tcx.lang_items().clone_trait().unwrap(),
ty,
ty::IncludeLocalImpls::Yes,
|def_id| {
if self.infcx.tcx.is_automatically_derived(def_id) {
derive_clone = true;
Expand Down
15 changes: 12 additions & 3 deletions compiler/rustc_const_eval/src/const_eval/eval_queries.rs

@RalfJung RalfJung Sep 22, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't actually check that the functions invoked during CTFE are all from the current crate, does it?

View changes since the review

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's not important in practice for the end goal. Either the resolver doesn't even let you call that function, or you get a cycle error, or you can call that function. All the work here is to avoid cycle errors, and we'll see how far we can take this

Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ fn retry_codegen_mode_with_postanalysis<'tcx, K: TypeVisitable<TyCtxt<'tcx>>, V>
| ty::TypingMode::PostTypeckUntilBorrowck { .. }
| ty::TypingMode::PostBorrowck { .. }
| ty::TypingMode::Reflection
| ty::TypingMode::PostAnalysis => {}
| ty::TypingMode::PostAnalysis
| ty::TypingMode::IsolatedConst => {}
}

None
Expand Down Expand Up @@ -357,11 +358,19 @@ pub(crate) fn turn_into_const_value<'tcx>(
#[instrument(skip(tcx), level = "debug")]
pub fn eval_to_const_value_raw_provider<'tcx>(
tcx: TyCtxt<'tcx>,
key: ty::PseudoCanonicalInput<'tcx, GlobalId<'tcx>>,
mut key: ty::PseudoCanonicalInput<'tcx, GlobalId<'tcx>>,
) -> ::rustc_middle::mir::interpret::EvalToConstValueResult<'tcx> {
crate::assert_typing_mode(key.typing_env.typing_mode());

if let Some((value, _ty)) = tcx.trivial_const(key.value.instance.def_id()) {
let def_id = key.value.instance.def_id();

if matches!(tcx.def_kind(def_id), DefKind::Const { .. })
&& rustc_hir::find_attr!(tcx, def_id, RustcIsolatedConst)
{
key.typing_env = ty::TypingEnv::isolated_const(tcx, key.value.instance.def_id());
}

if let Some((value, _ty)) = tcx.trivial_const(def_id) {
return Ok(value);
}

Expand Down
4 changes: 3 additions & 1 deletion compiler/rustc_const_eval/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ use rustc_span::bug;
fn assert_typing_mode(typing_mode: ty::TypingMode<'_>) {
if cfg!(debug_assertions) {
match typing_mode.assert_not_erased() {
ty::TypingMode::PostAnalysis | ty::TypingMode::Codegen => {}
ty::TypingMode::PostAnalysis
| ty::TypingMode::Codegen
| ty::TypingMode::IsolatedConst => {}
// Const eval always happens in PostAnalysis or Codegen mode. See the comment in
// `InterpCx::new` for more details.
ty::TypingMode::Coherence
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_feature/src/builtin_attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,7 @@ pub static BUILTIN_ATTRIBUTES: &[Symbol] = &[
sym::rustc_const_stable_indirect,
sym::rustc_intrinsic_const_stable_indirect,
sym::rustc_allow_const_fn_unstable,
sym::rustc_isolated_const,

// ==========================================================================
// Internal attributes, Layout related:
Expand Down
4 changes: 3 additions & 1 deletion compiler/rustc_hir_analysis/src/coherence/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ use rustc_infer::traits::{Obligation, TraitErrors};
use rustc_middle::ty::adjustment::CoerceUnsizedInfo;
use rustc_middle::ty::print::PrintTraitRefExt as _;
use rustc_middle::ty::{
self, Ty, TyCtxt, TypeVisitableExt, TypingMode, Unnormalized, suggest_constraining_type_params,
self, IncludeLocalImpls, Ty, TyCtxt, TypeVisitableExt, TypingMode, Unnormalized,
suggest_constraining_type_params,
};
use rustc_span::{DUMMY_SP, Ident, Span, Symbol, sym};
use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
Expand Down Expand Up @@ -302,6 +303,7 @@ fn visit_implementation_of_dispatch_from_dyn(checker: &Checker<'_>) -> Result<()
tcx.for_each_relevant_impl(
tcx.require_lang_item(LangItem::CoerceUnsized, span),
source,
IncludeLocalImpls::Yes,
|impl_def_id| {
res = res.and(tcx.ensure_result().coerce_unsized_info(impl_def_id));
},
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -563,7 +563,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
vec!["Self".to_string()]
} else {
// Find all the types that have an `impl` for the trait.
tcx.all_impls(trait_def_id)
tcx.all_impls(trait_def_id, ty::IncludeLocalImpls::Yes)
.map(|impl_def_id| tcx.impl_trait_header(impl_def_id))
.filter(|header| {
// Consider only accessible traits
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1883,7 +1883,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
// Consider only accessible traits
&& tcx.visibility(*trait_def_id)
.is_accessible_from(self.mod_id(), tcx)
&& tcx.all_impls(*trait_def_id)
&& tcx.all_impls(*trait_def_id, ty::IncludeLocalImpls::Yes)
.any(|impl_def_id| {
let header = tcx.impl_trait_header(impl_def_id);
let trait_ref = header.trait_ref.instantiate(tcx, infcx.fresh_args_for_item(DUMMY_SP, impl_def_id)).skip_norm_wip();
Expand Down
11 changes: 8 additions & 3 deletions compiler/rustc_hir_typeck/src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3546,9 +3546,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let index_trait_output_def_id = self.tcx.get_diagnostic_item(sym::IndexOutput)?;

let mut relevant_impls = vec![];
self.tcx.for_each_relevant_impl(index_trait_def_id, base_ty, |impl_def_id| {
relevant_impls.push(impl_def_id);
});
self.tcx.for_each_relevant_impl(
index_trait_def_id,
base_ty,
self.typing_mode().include_local_impls(),
|impl_def_id| {
relevant_impls.push(impl_def_id);
},
);
let [impl_def_id] = relevant_impls[..] else {
// Only report unsatisfied impl predicates if there's one impl
return None;
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -695,6 +695,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
ty::TypingMode::Typeck { defining_opaque_types_and_generators } => {
defining_opaque_types_and_generators
}
ty::TypingMode::IsolatedConst => ty::List::empty(),

@lcnr lcnr Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

XD I was thinking I should add a comment here... typeck needs to know about IsolatedConst as well, but that would mean essentially adding a new dimension typing mode, where everything can be an isolated const, but also have the normal typingmode.

Instead this MVP just forbids having opaque types at all, even if we could make RPITs work. TAITs won't work as they require access to other items from the current crate

ty::TypingMode::Coherence
| ty::TypingMode::Reflection
| ty::TypingMode::PostTypeckUntilBorrowck { .. }
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir_typeck/src/method/suggest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4696,7 +4696,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// Check if there's a negative impl of `candidate` for `rcvr_ty`
if self
.tcx
.all_impls(candidate.def_id)
.all_impls(candidate.def_id, self.typing_mode().include_local_impls())

@lcnr lcnr Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

when do we use all_impls without specifying the typing mode? because if so, there should maybe just be an infcx.all_impls wrapper which considers the typing mode

View changes since the review

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should never use all_impls without specifying the mode, and always use the mode of the infcx if available

.map(|imp_did| self.tcx.impl_trait_header(imp_did))
.filter(|header| header.polarity != ty::ImplPolarity::Positive)
.any(|header| {
Expand Down
3 changes: 2 additions & 1 deletion compiler/rustc_hir_typeck/src/opaque_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,8 @@ impl<'tcx> FnCtxt<'_, 'tcx> {
| ty::TypingMode::PostTypeckUntilBorrowck { .. }
| ty::TypingMode::PostBorrowck { .. }
| ty::TypingMode::PostAnalysis
| ty::TypingMode::Codegen => {
| ty::TypingMode::Codegen
| ty::TypingMode::IsolatedConst => {
bug!()
}
};
Expand Down
9 changes: 6 additions & 3 deletions compiler/rustc_infer/src/infer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -373,7 +373,8 @@ impl<'tcx> Drop for InferCtxt<'tcx> {
| TypingMode::PostBorrowck { .. }
| TypingMode::Reflection
| TypingMode::PostAnalysis
| TypingMode::Codegen => {}
| TypingMode::Codegen
| TypingMode::IsolatedConst => {}
// In erased mode, the opaque type storage is always empty
TypingMode::ErasedNotCoherence(..) => {}
TypingMode::PostTypeckUntilBorrowck { .. } => {
Expand Down Expand Up @@ -1201,7 +1202,8 @@ impl<'tcx> InferCtxt<'tcx> {
| TypingMode::Reflection
| TypingMode::PostBorrowck { .. }
| TypingMode::PostAnalysis
| TypingMode::Codegen => false,
| TypingMode::Codegen
| TypingMode::IsolatedConst => false,
}
}

Expand Down Expand Up @@ -1689,7 +1691,8 @@ impl<'tcx> InferCtxt<'tcx> {
| ty::TypingMode::PostBorrowck { .. }
| ty::TypingMode::PostAnalysis
| ty::TypingMode::Reflection
| ty::TypingMode::Codegen) => mode,
| ty::TypingMode::Codegen
| ty::TypingMode::IsolatedConst) => mode,
ty::TypingMode::ErasedNotCoherence(MayBeErased) => unreachable!(),
};
ty::TypingEnv::new(param_env, typing_mode)
Expand Down
3 changes: 2 additions & 1 deletion compiler/rustc_infer/src/infer/opaque_types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,8 @@ impl<'tcx> InferCtxt<'tcx> {
mode @ (ty::TypingMode::PostBorrowck { .. }
| ty::TypingMode::PostAnalysis
| ty::TypingMode::Codegen
| ty::TypingMode::Reflection) => {
| ty::TypingMode::Reflection
| ty::TypingMode::IsolatedConst) => {
bug!("insert hidden type in {mode:?}")
}
}
Expand Down
8 changes: 4 additions & 4 deletions compiler/rustc_middle/src/queries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,8 @@ use crate::ty::layout::ValidityRequirement;
use crate::ty::print::PrintTraitRefExt;
use crate::ty::util::AlwaysRequiresDrop;
use crate::ty::{
self, CrateInherentImpls, GenericArg, GenericArgsRef, LitToConstInput, PseudoCanonicalInput,
RequiredDepth, SizedTraitKind, Ty, TyCtxt, TyCtxtFeed,
self, CrateInherentImpls, GenericArg, GenericArgsRef, IncludeLocalImpls, LitToConstInput,
PseudoCanonicalInput, RequiredDepth, SizedTraitKind, Ty, TyCtxt, TyCtxtFeed,
};
use crate::{mir, thir};

Expand Down Expand Up @@ -1643,9 +1643,9 @@ rustc_queries! {
}

/// Given a trait `trait_id`, return all known `impl` blocks.
query trait_impls_of(trait_id: DefId) -> &'tcx ty::trait_def::TraitImpls {
query trait_impls_of(key: (DefId, IncludeLocalImpls)) -> &'tcx ty::trait_def::TraitImpls {
arena_cache
desc { "finding trait impls of `{}`", tcx.def_path_str(trait_id) }
desc { "finding trait impls of `{}`", tcx.def_path_str(key.0) }
}

query specialization_graph_of(trait_id: DefId) -> Result<&'tcx specialization_graph::Graph, ErrorGuaranteed> {
Expand Down
7 changes: 7 additions & 0 deletions compiler/rustc_middle/src/query/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use rustc_hir::OwnerId;
use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE, LocalDefId, LocalModId};
use rustc_span::def_id::ModId;
use rustc_span::{DUMMY_SP, Ident, LocalExpnId, Span, Symbol};
use rustc_type_ir::IncludeLocalImpls;

use crate::dep_graph::DepNodeIndex;
use crate::infer::canonical::CanonicalQueryInput;
Expand Down Expand Up @@ -414,6 +415,12 @@ impl<'tcx> QueryKey for (ty::Instance<'tcx>, CollectionMode) {
}
}

impl QueryKey for (DefId, IncludeLocalImpls) {
fn default_span(&self, tcx: TyCtxt<'_>) -> Span {
self.0.default_span(tcx)
}
}

/// Gets a `DefId` associated with a type
///
/// Visited set is needed to avoid full iteration over
Expand Down
14 changes: 10 additions & 4 deletions compiler/rustc_middle/src/ty/context/impl_interner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ use rustc_span::{DUMMY_SP, Span, Symbol, bug};
use rustc_type_ir::lang_items::{SolverAdtLangItem, SolverProjectionLangItem, SolverTraitLangItem};
use rustc_type_ir::solve::CanonicalInputData;
use rustc_type_ir::{
BoundVar, CollectAndApply, DebruijnIndex, Interner, RegionVid, TypeFoldable, Unnormalized,
VisitorResult, search_graph, try_visit,
BoundVar, CollectAndApply, DebruijnIndex, IncludeLocalImpls, Interner, RegionVid, TypeFoldable,
Unnormalized, VisitorResult, search_graph, try_visit,
};

use crate::dep_graph::{DepKind, DepNodeIndex};
Expand Down Expand Up @@ -195,6 +195,10 @@ impl<'tcx> Interner for TyCtxt<'tcx> {
ty::AliasConstKind::Anon { .. } => false,
}
}
fn is_isolated_const(self, def_id: LocalDefId) -> bool {
matches!(self.def_kind(def_id), DefKind::Const { .. })
&& rustc_hir::find_attr!(self, def_id, RustcIsolatedConst)
}
fn const_of_item(
self,
alias: ty::AliasConstKind<'tcx>,
Expand Down Expand Up @@ -526,21 +530,23 @@ impl<'tcx> Interner for TyCtxt<'tcx> {
fn for_each_relevant_impl<R: VisitorResult>(
self,
trait_ref: ty::TraitRef<'tcx>,
include_local_impls: IncludeLocalImpls,
f: impl FnMut(DefId) -> R,
) -> R {
let self_ty = trait_ref.args.type_at(0);
debug_assert!(
!matches!(self_ty.kind(), ty::Infer(ty::TyVar(_)) | ty::Param(_) | ty::Bound(_, _)),
"we should not have them as self ty in the next solver"
);
TyCtxt::for_each_relevant_impl(self, trait_ref.def_id, self_ty, f)
TyCtxt::for_each_relevant_impl(self, trait_ref.def_id, self_ty, include_local_impls, f)
}
fn for_each_blanket_impl<R: VisitorResult>(
self,
trait_def_id: DefId,
include_local_impls: IncludeLocalImpls,
mut f: impl FnMut(DefId) -> R,
) -> R {
let trait_impls = self.trait_impls_of(trait_def_id);
let trait_impls = self.trait_impls_of((trait_def_id, include_local_impls));
for &impl_def_id in trait_impls.blanket_impls() {
try_visit!(f(impl_def_id));
}
Expand Down
13 changes: 11 additions & 2 deletions compiler/rustc_middle/src/ty/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1173,6 +1173,13 @@ impl<'tcx> TypingEnv<'tcx> {
TypingEnv::new(tcx.param_env_normalized_for_post_analysis(def_id), TypingMode::Codegen)
}

pub fn isolated_const(tcx: TyCtxt<'tcx>, def_id: impl IntoQueryKey<DefId>) -> TypingEnv<'tcx> {
TypingEnv::new(
tcx.param_env_normalized_for_post_analysis(def_id),
TypingMode::IsolatedConst,
)
}

/// Modify the `typing_mode` to `PostAnalysis` or `Codegen` and eagerly reveal all opaque types
/// in the `param_env`.
pub fn with_post_analysis_normalized(self, tcx: TyCtxt<'tcx>) -> TypingEnv<'tcx> {
Expand All @@ -1182,7 +1189,8 @@ impl<'tcx> TypingEnv<'tcx> {
| TypingMode::Reflection
| TypingMode::Typeck { .. }
| TypingMode::PostTypeckUntilBorrowck { .. }
| TypingMode::PostBorrowck { .. } => {}
| TypingMode::PostBorrowck { .. }
| TypingMode::IsolatedConst => {}
TypingMode::PostAnalysis | TypingMode::Codegen => return self,
}

Expand All @@ -1200,7 +1208,8 @@ impl<'tcx> TypingEnv<'tcx> {
| TypingMode::Typeck { .. }
| TypingMode::PostTypeckUntilBorrowck { .. }
| TypingMode::PostBorrowck { .. }
| TypingMode::PostAnalysis => {}
| TypingMode::PostAnalysis
| TypingMode::IsolatedConst => {}
TypingMode::Codegen => return self,
}

Expand Down
Loading
Loading