Skip to content
Open
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
2 changes: 2 additions & 0 deletions compiler/rustc_attr_ir/src/lang_items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,8 @@ language_item_table! {

// Experimental lang item for `Reflection and comptime`(https://goals.rust-lang.org/2025h2/reflection-and-comptime.html)
FnPtr, sym::FnPtr, fn_ptr, Target::Struct, GenericRequirement::None;
VariantId, sym::VariantId, variant_id, Target::Struct, GenericRequirement::None;
VariantGetter, sym::variant_getter, variant_getter, Target::Fn, GenericRequirement::Exact(1);
}

/// The requirement imposed on the generics of a lang item
Expand Down
72 changes: 46 additions & 26 deletions compiler/rustc_const_eval/src/const_eval/machine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,17 @@ use rustc_middle::mir::AssertMessage;
use rustc_middle::mir::interpret::ReportedErrorInfo;
use rustc_middle::query::TyCtxtAt;
use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv, TyAndLayout, ValidityRequirement};
use rustc_middle::ty::{self, FieldInfo, ScalarInt, Ty, TyCtxt};
use rustc_middle::ty::{self, FieldInfo, Instance, ScalarInt, Ty, TyCtxt};
use rustc_middle::{mir, throw_machine_stop};
use rustc_span::{Span, Symbol, bug, span_bug, sym};
use rustc_target::callconv::FnAbi;
use tracing::debug;

use super::error::*;
use crate::diagnostics::{LongRunning, LongRunningWarn};
use crate::interpret::Immediate::ScalarPair;
use crate::interpret::{
self, AllocId, AllocInit, AllocRange, ConstAllocation, CtfeProvenance, FnArg, Frame,
self, AllocId, AllocInit, AllocRange, ConstAllocation, CtfeProvenance, FnArg, FnVal, Frame,
GlobalAlloc, ImmTy, Immediate, InterpCx, InterpResult, OpTy, PlaceTy, Pointer, RangeSet,
RetagMode, Scalar, compile_time_machine, ensure_monomorphic_enough, err_inval, interp_ok,
throw_exhaust, throw_inval, throw_ub, throw_ub_format, throw_unsup, throw_unsup_format,
Expand Down Expand Up @@ -699,7 +700,7 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> {
ecx.write_scalar(Scalar::from_target_usize(fields_num as u64, ecx), dest)?;
}

sym::type_id_field_representing_type => {
sym::type_id_field_representing => {
let ty = ecx.read_type_id(&args[0])?;
let variant_idx = ecx.read_target_usize(&args[1])? as usize;
let field_idx = ecx.read_target_usize(&args[2])? as usize;
Expand Down Expand Up @@ -770,6 +771,32 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> {
ecx.write_scalar(Scalar::from_target_usize(variants_num as u64, ecx), dest)?;
}

sym::type_id_variant_getter => {
let ty = ecx.read_type_id(&args[0])?;
let getter_def_id =
ecx.tcx().require_lang_item(LangItem::VariantGetter, rustc_span::DUMMY_SP);
let generic_arg = ecx.tcx().mk_args(&[ty.into()]);
let instance = Instance::expect_resolve(
ecx.tcx(),
ecx.typing_env(),
getter_def_id,
generic_arg,
rustc_span::DUMMY_SP,
);
let fn_ptr = ecx.fn_ptr(FnVal::Instance(instance));
ecx.write_pointer(fn_ptr, dest)?;
}

sym::type_id_variant_lookup_table => {
let ty = instance
.args
.first()
.expect("has one generic")
.as_type()
.expect("the generic arg is a Ty");
ecx.write_slice_of_discriminant(dest, ty)?;
}

sym::type_id_variant_name => {
let base = ecx.read_type_id(&args[0])?;

Expand All @@ -796,6 +823,20 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> {
)?;
}

sym::type_id_name => {
let ty = ecx.read_type_id(&args[0])?;
ensure_monomorphic_enough(ty)?;
let name = crate::util::type_name(ecx.tcx(), ty);
let ptr = ecx.allocate_bytes_dedup(name.as_str().as_bytes())?;
ecx.write_immediate(
ScalarPair(
Scalar::from_pointer(ptr, ecx),
Scalar::from_target_usize(name.as_str().len() as u64, ecx),
),
dest,
)?;
}

sym::type_id_variant_non_exhaustive => {
let base = ecx.read_type_id(&args[0])?;

Expand Down Expand Up @@ -836,28 +877,7 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> {
ecx.write_scalar(Scalar::from_target_usize(offset, ecx), dest)?;
}

sym::field_representing_type_name => {
let frt_ty = ecx.read_type_id(&args[0])?;

let field_name = if let ty::Adt(def, args) = frt_ty.kind()
&& let Some(FieldInfo { name, .. }) =
def.field_representing_type_info(ecx.tcx.tcx, args)
{
name
} else {
span_bug!(ecx.cur_span(), "expected field representing type, got {frt_ty}")
};
let ptr = ecx.allocate_bytes_dedup(field_name.as_str().as_bytes())?;
ecx.write_immediate(
Immediate::ScalarPair(
Scalar::from_pointer(ptr, ecx),
Scalar::from_target_usize(field_name.as_str().len() as u64, ecx),
),
dest,
)?;
}

sym::field_representing_type_offset => {
sym::type_id_field_representing_field_offset => {
let frt_ty = ecx.read_type_id(&args[0])?;

let (ty, variant, field) = if let ty::Adt(def, args) = frt_ty.kind()
Expand All @@ -877,7 +897,7 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> {
ecx.write_scalar(Scalar::from_target_usize(offset, ecx), dest)?;
}

sym::field_representing_type_actual_type_id => {
sym::type_id_field_representing_outer_type_id => {
let frt_ty = ecx.read_type_id(&args[0])?;

let field_ty = if let ty::Adt(def, args) = frt_ty.kind()
Expand Down
28 changes: 27 additions & 1 deletion compiler/rustc_const_eval/src/const_eval/type_info/adt.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use rustc_abi::{FieldIdx, VariantIdx};
use rustc_middle::ty::{
AdtDef, AdtKind, Const, ConstKind, GenericArgKind, GenericArgs, Region, Ty,
self, AdtDef, AdtKind, Const, ConstKind, GenericArgKind, GenericArgs, Region, ScalarInt, Ty,
};
use rustc_span::{bug, span_bug, sym};

Expand All @@ -10,6 +10,32 @@ use crate::interpret::{
};

impl<'tcx> InterpCx<'tcx, CompileTimeMachine<'tcx>> {
pub(crate) fn write_slice_of_discriminant(
&mut self,
place: &impl Writeable<'tcx, CtfeProvenance>,
ty: Ty<'tcx>,
) -> InterpResult<'tcx, ()> {
let cast_to = ty.discriminant_ty(*self.tcx);
let discriminant_size = cast_to.primitive_size(*self.tcx);

let num_variants = if let ty::Adt(def, _) = ty.kind()
&& def.is_enum()
{
def.variants().len() as u64
} else {
0
};
self.allocate_fill_and_write_slice_ptr(place, num_variants, |this, i, place| {
let discriminant = ty
.discriminant_for_variant(*this.tcx, VariantIdx::from_usize(i as usize))
.expect("i is in range")
.val;
let discriminant = ScalarInt::try_from_uint(discriminant, discriminant_size)
.expect("discriminant ty fits the current value");
this.write_scalar(discriminant, &place)
})
}

// FIXME(type_info): No semver considerations for now
pub(crate) fn write_adt_type_info(
&mut self,
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_const_eval/src/interpret/intrinsics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ pub enum VarArgCompatible {

/// Directly returns an `Allocation` containing an absolute path representation of the given type.
pub(crate) fn alloc_type_name<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> (AllocId, u64) {
let path = crate::util::type_name(tcx, ty);
let path = crate::util::type_name_and_path(tcx, ty);
let bytes = path.into_bytes();
let len = bytes.len().try_into().unwrap();
(tcx.allocate_bytes_dedup(bytes, CTFE_ALLOC_SALT), len)
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_const_eval/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#![feature(deref_patterns)]
#![feature(slice_ptr_get)]
#![feature(trait_alias)]
#![feature(try_blocks)]
#![feature(unqualified_local_imports)]
#![feature(yeet_expr)]
#![warn(unqualified_local_imports)]
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_const_eval/src/util/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ pub use self::alignment::{most_packed_projection, place_unalignment};
pub use self::check_validity_requirement::check_validity_requirement;
pub(crate) use self::check_validity_requirement::validate_scalar_in_layout;
pub use self::compare_types::{relate_types, sub_types};
pub use self::type_name::type_name;
pub use self::type_name::{type_name, type_name_and_path};

/// Classify whether an operator is "left-homogeneous", i.e., the LHS has the
/// same type as the result.
Expand Down
36 changes: 34 additions & 2 deletions compiler/rustc_const_eval/src/util/type_name.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use rustc_data_structures::intern::Interned;
use rustc_hir::def_id::{CrateNum, DefId};
use rustc_hir::definitions::DisambiguatedDefPathData;
use rustc_middle::ty::print::{PrettyPrinter, PrintError, Printer};
use rustc_middle::ty::{self, GenericArg, Ty, TyCtxt};
use rustc_middle::ty::{self, FieldInfo, GenericArg, Ty, TyCtxt};
use rustc_span::bug;

struct TypeNamePrinter<'tcx> {
Expand Down Expand Up @@ -213,8 +213,40 @@ impl Write for TypeNamePrinter<'_> {
}
}

pub fn type_name<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> String {
pub fn type_name_and_path<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> String {
let mut p = TypeNamePrinter { tcx, path: String::new() };
p.print_type(ty).unwrap();
p.path
}

pub fn type_name<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> String {
let mut s = String::new();

try {
match *ty.kind() {
ty::Adt(def, args)
if let Some(FieldInfo { name, .. }) =
def.field_representing_type_info(tcx, args) =>
{
write!(s, "{name}")?
}
ty::Adt(def, _) => write!(s, "{}", tcx.item_name(def.did()))?,
ty::Dynamic(data, _) => {
let trait_def_id = data
.iter()
.map(|b| b.skip_binder())
.find_map(|pred| match pred {
ty::ExistentialPredicate::Trait(tr) => Some(tr.def_id),
ty::ExistentialPredicate::AutoTrait(def_id) => Some(def_id),
_ => None,
})
.expect("There should be a principal trait");
write!(s, "{}", tcx.item_name(trait_def_id))?;
}
_ => (),
}
}
.unwrap();

s
}
39 changes: 31 additions & 8 deletions compiler/rustc_hir_analysis/src/check/intrinsic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,9 +104,6 @@ fn intrinsic_operation_unsafety(tcx: TyCtxt<'_>, intrinsic_id: LocalDefId) -> hi
| sym::fadd_algebraic
| sym::fdiv_algebraic
| sym::field_offset
| sym::field_representing_type_actual_type_id
| sym::field_representing_type_name
| sym::field_representing_type_offset
| sym::floor
| sym::fma
| sym::fmul_algebraic
Expand Down Expand Up @@ -173,16 +170,21 @@ fn intrinsic_operation_unsafety(tcx: TyCtxt<'_>, intrinsic_id: LocalDefId) -> hi
| sym::type_id_array_len
| sym::type_id_element_ty
| sym::type_id_eq
| sym::type_id_field_representing_type
| sym::type_id_field_representing
| sym::type_id_field_representing_field_offset
| sym::type_id_field_representing_outer_type_id
| sym::type_id_fields
| sym::type_id_function_ptr
| sym::type_id_generics
| sym::type_id_is_signed
| sym::type_id_name
| sym::type_id_non_exhaustive
| sym::type_id_points_mutably
| sym::type_id_points_to
| sym::type_id_size_of
| sym::type_id_type_of
| sym::type_id_variant_getter
| sym::type_id_variant_lookup_table
| sym::type_id_variant_name
| sym::type_id_variant_non_exhaustive
| sym::type_id_variants
Expand Down Expand Up @@ -294,7 +296,7 @@ pub(crate) fn check_intrinsic_type(
sym::type_id_array_len => (0, 0, vec![type_id_ty()], tcx.types.usize),
sym::type_id_element_ty => (0, 0, vec![type_id_ty()], Ty::new_option(tcx, type_id_ty())),
sym::type_id_eq => (0, 0, vec![type_id_ty(), type_id_ty()], tcx.types.bool),
sym::type_id_field_representing_type => {
sym::type_id_field_representing => {
(0, 0, vec![type_id_ty(), tcx.types.usize, tcx.types.usize], type_id_ty())
}
sym::type_id_fields => (0, 0, vec![type_id_ty(), tcx.types.usize], tcx.types.usize),
Expand All @@ -313,6 +315,27 @@ pub(crate) fn check_intrinsic_type(
sym::type_id_points_mutably => (0, 0, vec![type_id_ty()], tcx.types.bool),
sym::type_id_points_to => (0, 0, vec![type_id_ty()], Ty::new_option(tcx, type_id_ty())),
sym::type_id_variants => (0, 0, vec![type_id_ty()], tcx.types.usize),
sym::type_id_variant_getter => {
let variant_id =
tcx.type_of(tcx.lang_items().variant_id().unwrap()).no_bound_vars().unwrap();
let unit_ptr = Ty::new_ptr(tcx, tcx.types.unit, ty::Mutability::Not);
let fn_ty = ty::Binder::dummy(tcx.mk_fn_sig_unsafe_rust_abi([unit_ptr], variant_id));
(0, 0, vec![type_id_ty()], Ty::new_fn_ptr(tcx, fn_ty))
}
sym::type_id_variant_lookup_table => {
let assoc_items = tcx
.associated_item_def_ids(tcx.require_lang_item(LangItem::DiscriminantKind, span));
let discriminant_def_id = assoc_items[0];
let discriminant_ty = Ty::new_projection_from_args(
tcx,
ty::IsRigid::No,
discriminant_def_id,
tcx.mk_args(&[param(0).into()]),
);
let slice = Ty::new_slice(tcx, discriminant_ty);
let slice = Ty::new_imm_ref(tcx, tcx.lifetimes.re_static, slice);
(1, 0, vec![], slice)
}
sym::type_id_variant_name => {
(0, 0, vec![type_id_ty(), tcx.types.usize], Ty::new_static_str(tcx))
}
Expand All @@ -339,9 +362,9 @@ pub(crate) fn check_intrinsic_type(
vec![type_id_ty()],
tcx.type_of(tcx.lang_items().type_struct().unwrap()).no_bound_vars().unwrap(),
),
sym::field_representing_type_actual_type_id => (0, 0, vec![type_id_ty()], type_id_ty()),
sym::field_representing_type_name => (0, 0, vec![type_id_ty()], Ty::new_static_str(tcx)),
sym::field_representing_type_offset => (0, 0, vec![type_id_ty()], tcx.types.usize),
sym::type_id_field_representing_outer_type_id => (0, 0, vec![type_id_ty()], type_id_ty()),
sym::type_id_field_representing_field_offset => (0, 0, vec![type_id_ty()], tcx.types.usize),
sym::type_id_name => (0, 0, vec![type_id_ty()], Ty::new_static_str(tcx)),
sym::type_id_non_exhaustive => (0, 0, vec![type_id_ty()], tcx.types.bool),
sym::type_id_generics => (
0,
Expand Down
12 changes: 8 additions & 4 deletions compiler/rustc_span/src/symbol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,7 @@ symbols! {
UnsafeFnPointer,
Unsize,
UnsizePointee,
VariantId,
Vec,
Wrapper,
_DECLS,
Expand Down Expand Up @@ -994,9 +995,6 @@ symbols! {
field_offset,
field_projections,
field_representing_type,
field_representing_type_actual_type_id,
field_representing_type_name,
field_representing_type_offset,
field_representing_type_raw,
field_type,
fields,
Expand Down Expand Up @@ -2209,16 +2207,21 @@ symbols! {
type_id_array_len,
type_id_element_ty,
type_id_eq,
type_id_field_representing_type,
type_id_field_representing,
type_id_field_representing_field_offset,
type_id_field_representing_outer_type_id,
type_id_fields,
type_id_function_ptr,
type_id_generics,
type_id_is_signed,
type_id_name,
type_id_non_exhaustive,
type_id_points_mutably,
type_id_points_to,
type_id_size_of,
type_id_type_of,
type_id_variant_getter,
type_id_variant_lookup_table,
type_id_variant_name,
type_id_variant_non_exhaustive,
type_id_variants,
Expand Down Expand Up @@ -2361,6 +2364,7 @@ symbols! {
var,
variadic,
variant_count,
variant_getter,
vec,
vector,
verbatim,
Expand Down
Loading
Loading