Skip to content
Closed
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
9 changes: 9 additions & 0 deletions compiler/rustc_attr_parsing/src/attributes/macro_attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -206,3 +206,12 @@ impl<S: Stage> SingleAttributeParser<S> for CollapseDebugInfoParser {
Some(AttributeKind::CollapseDebugInfo(info))
}
}

pub(crate) struct RustcProcMacroDeclsParser;

impl<S: Stage> NoArgsAttributeParser<S> for RustcProcMacroDeclsParser {
const PATH: &[Symbol] = &[sym::rustc_proc_macro_decls];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Static)]);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcProcMacroDecls;
}
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 @@ -300,6 +300,7 @@ attribute_parsers!(
Single<WithoutArgs<RustcOutlivesParser>>,
Single<WithoutArgs<RustcPassIndirectlyInNonRusticAbisParser>>,
Single<WithoutArgs<RustcPreserveUbChecksParser>>,
Single<WithoutArgs<RustcProcMacroDeclsParser>>,
Single<WithoutArgs<RustcReallocatorParser>>,
Single<WithoutArgs<RustcRegionsParser>>,
Single<WithoutArgs<RustcShouldNotBeCalledOnConstItems>>,
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_cranelift/src/codegen_f16_f128.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ pub(crate) fn codegen_cast(
let ret_ty = if to_ty.bits() < 32 { types::I32 } else { to_ty };
let name = format!(
"__fix{sign}tf{size}i",
sign = if from_signed { "" } else { "un" },
sign = if to_signed { "" } else { "uns" },
size = match ret_ty {
types::I32 => 's',
types::I64 => 'd',
Expand Down
27 changes: 3 additions & 24 deletions compiler/rustc_expand/src/proc_macro.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,32 +11,11 @@ use {rustc_ast as ast, rustc_proc_macro as pm};
use crate::base::{self, *};
use crate::{errors, proc_macro_server};

struct MessagePipe<T> {
tx: std::sync::mpsc::SyncSender<T>,
rx: std::sync::mpsc::Receiver<T>,
}

impl<T> pm::bridge::server::MessagePipe<T> for MessagePipe<T> {
fn new() -> (Self, Self) {
let (tx1, rx1) = std::sync::mpsc::sync_channel(1);
let (tx2, rx2) = std::sync::mpsc::sync_channel(1);
(MessagePipe { tx: tx1, rx: rx2 }, MessagePipe { tx: tx2, rx: rx1 })
}

fn send(&mut self, value: T) {
self.tx.send(value).unwrap();
}

fn recv(&mut self) -> Option<T> {
self.rx.recv().ok()
}
}

fn exec_strategy(sess: &Session) -> impl pm::bridge::server::ExecutionStrategy + 'static {
pm::bridge::server::MaybeCrossThread::<MessagePipe<_>>::new(
sess.opts.unstable_opts.proc_macro_execution_strategy
pm::bridge::server::MaybeCrossThread {
cross_thread: sess.opts.unstable_opts.proc_macro_execution_strategy
== ProcMacroExecutionStrategy::CrossThread,
)
}
}

pub struct BangProcMacro {
Expand Down
3 changes: 3 additions & 0 deletions compiler/rustc_hir/src/attrs/data_structures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1295,6 +1295,9 @@ pub enum AttributeKind {
/// Represents `#[rustc_preserve_ub_checks]`
RustcPreserveUbChecks,

/// Represents `#[rustc_proc_macro_decls]`
RustcProcMacroDecls,

/// Represents `#[rustc_pub_transparent]` (used by the `repr_transparent_external_private_fields` lint).
RustcPubTransparent(Span),

Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_hir/src/attrs/encode_cross_crate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@ impl AttributeKind {
RustcPassByValue(..) => Yes,
RustcPassIndirectlyInNonRusticAbis(..) => No,
RustcPreserveUbChecks => No,
RustcProcMacroDecls => No,
RustcPubTransparent(..) => Yes,
RustcReallocator => No,
RustcRegions => No,
Expand Down
30 changes: 21 additions & 9 deletions compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,10 @@ use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
use rustc_infer::traits::DynCompatibilityViolation;
use rustc_macros::{TypeFoldable, TypeVisitable};
use rustc_middle::middle::stability::AllowUnstable;
use rustc_middle::mir::interpret::LitToConstInput;
use rustc_middle::ty::print::PrintPolyTraitRefExt as _;
use rustc_middle::ty::{
self, Const, GenericArgKind, GenericArgsRef, GenericParamDefKind, Ty, TyCtxt,
TypeSuperFoldable, TypeVisitableExt, TypingMode, Upcast, fold_regions,
self, Const, GenericArgKind, GenericArgsRef, GenericParamDefKind, LitToConstInput, Ty, TyCtxt,
TypeSuperFoldable, TypeVisitableExt, TypingMode, Upcast, const_lit_matches_ty, fold_regions,
};
use rustc_middle::{bug, span_bug};
use rustc_session::lint::builtin::AMBIGUOUS_ASSOCIATED_ITEMS;
Expand Down Expand Up @@ -2809,8 +2808,17 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
span: Span,
) -> Const<'tcx> {
let tcx = self.tcx();
if let LitKind::Err(guar) = *kind {
return ty::Const::new_error(tcx, guar);
}
let input = LitToConstInput { lit: *kind, ty, neg };
tcx.at(span).lit_to_const(input)
match tcx.at(span).lit_to_const(input) {
Some(value) => ty::Const::new_value(tcx, value.valtree, value.ty),
None => {
let e = tcx.dcx().span_err(span, "type annotations needed for the literal");
ty::Const::new_error(tcx, e)
}
}
}

#[instrument(skip(self), level = "debug")]
Expand Down Expand Up @@ -2839,11 +2847,15 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
_ => None,
};

lit_input
// Allow the `ty` to be an alias type, though we cannot handle it here, we just go through
// the more expensive anon const code path.
.filter(|l| !l.ty.has_aliases())
.map(|l| tcx.at(expr.span).lit_to_const(l))
lit_input.and_then(|l| {
if const_lit_matches_ty(tcx, &l.lit, l.ty, l.neg) {
tcx.at(expr.span)
.lit_to_const(l)
.map(|value| ty::Const::new_value(tcx, value.valtree, value.ty))
} else {
None
}
})
}

fn require_type_const_attribute(
Expand Down
7 changes: 3 additions & 4 deletions compiler/rustc_interface/src/proc_macro_decls.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
use rustc_ast::attr;
use rustc_hir::attrs::AttributeKind;
use rustc_hir::def_id::LocalDefId;
use rustc_hir::find_attr;
use rustc_middle::query::Providers;
use rustc_middle::ty::TyCtxt;
use rustc_span::sym;

fn proc_macro_decls_static(tcx: TyCtxt<'_>, (): ()) -> Option<LocalDefId> {
let mut decls = None;

for id in tcx.hir_free_items() {
let attrs = tcx.hir_attrs(id.hir_id());
if attr::contains_name(attrs, sym::rustc_proc_macro_decls) {
if find_attr!(tcx.hir_attrs(id.hir_id()), AttributeKind::RustcProcMacroDecls) {
decls = Some(id.owner_id.def_id);
}
}
Expand Down
13 changes: 1 addition & 12 deletions compiler/rustc_middle/src/mir/interpret/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use std::num::NonZero;
use std::{fmt, io};

use rustc_abi::{AddressSpace, Align, Endian, HasDataLayout, Size};
use rustc_ast::{LitKind, Mutability};
use rustc_ast::Mutability;
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::sharded::ShardedHashMap;
use rustc_data_structures::sync::{AtomicU64, Lock};
Expand Down Expand Up @@ -73,17 +73,6 @@ impl<'tcx> GlobalId<'tcx> {
}
}

/// Input argument for `tcx.lit_to_const`.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, HashStable)]
pub struct LitToConstInput<'tcx> {
/// The absolute value of the resultant constant.
pub lit: LitKind,
/// The type of the constant.
pub ty: Ty<'tcx>,
/// If the constant is negative.
pub neg: bool,
}

#[derive(Copy, Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct AllocId(pub NonZero<u64>);

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 @@ -111,7 +111,7 @@ use crate::middle::resolve_bound_vars::{ObjectLifetimeDefault, ResolveBoundVars,
use crate::middle::stability::DeprecationEntry;
use crate::mir::interpret::{
EvalStaticInitializerRawResult, EvalToAllocationRawResult, EvalToConstValueResult,
EvalToValTreeResult, GlobalId, LitToConstInput,
EvalToValTreeResult, GlobalId,
};
use crate::mir::mono::{
CodegenUnit, CollectionMode, MonoItem, MonoItemPartitions, NormalizationErrorInMono,
Expand All @@ -134,8 +134,8 @@ use crate::ty::layout::ValidityRequirement;
use crate::ty::print::PrintTraitRefExt;
use crate::ty::util::AlwaysRequiresDrop;
use crate::ty::{
self, CrateInherentImpls, GenericArg, GenericArgsRef, PseudoCanonicalInput, SizedTraitKind, Ty,
TyCtxt, TyCtxtFeed,
self, CrateInherentImpls, GenericArg, GenericArgsRef, LitToConstInput, PseudoCanonicalInput,
SizedTraitKind, Ty, TyCtxt, TyCtxtFeed,
};
use crate::{dep_graph, mir, thir};

Expand Down Expand Up @@ -1411,7 +1411,7 @@ rustc_queries! {
// FIXME get rid of this with valtrees
query lit_to_const(
key: LitToConstInput<'tcx>
) -> ty::Const<'tcx> {
) -> Option<ty::Value<'tcx>> {
desc { "converting literal to const" }
}

Expand Down
6 changes: 5 additions & 1 deletion compiler/rustc_middle/src/query/erase.rs
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,10 @@ impl Erasable for Option<ty::EarlyBinder<'_, Ty<'_>>> {
type Storage = [u8; size_of::<Option<ty::EarlyBinder<'static, Ty<'static>>>>()];
}

impl Erasable for Option<ty::Value<'_>> {
type Storage = [u8; size_of::<Option<ty::Value<'static>>>()];
}

impl Erasable for rustc_hir::MaybeOwner<'_> {
type Storage = [u8; size_of::<rustc_hir::MaybeOwner<'static>>()];
}
Expand Down Expand Up @@ -441,7 +445,6 @@ impl_erasable_for_single_lifetime_types! {
rustc_middle::mir::DestructuredConstant,
rustc_middle::mir::ConstAlloc,
rustc_middle::mir::interpret::GlobalId,
rustc_middle::mir::interpret::LitToConstInput,
rustc_middle::mir::interpret::EvalStaticInitializerRawResult,
rustc_middle::mir::mono::MonoItemPartitions,
rustc_middle::traits::query::MethodAutoderefStepsResult,
Expand All @@ -466,6 +469,7 @@ impl_erasable_for_single_lifetime_types! {
rustc_middle::ty::InstanceKind,
rustc_middle::ty::layout::FnAbiError,
rustc_middle::ty::layout::LayoutError,
rustc_middle::ty::LitToConstInput,
rustc_middle::ty::ParamEnv,
rustc_middle::ty::TypingEnv,
rustc_middle::ty::Predicate,
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/query/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ impl<'tcx> Key for (Ty<'tcx>, Option<ty::ExistentialTraitRef<'tcx>>) {
}
}

impl<'tcx> Key for mir::interpret::LitToConstInput<'tcx> {
impl<'tcx> Key for ty::LitToConstInput<'tcx> {
fn default_span(&self, _tcx: TyCtxt<'_>) -> Span {
DUMMY_SP
}
Expand Down
2 changes: 2 additions & 0 deletions compiler/rustc_middle/src/ty/consts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,12 @@ use crate::ty::{self, Ty, TyCtxt};

mod int;
mod kind;
mod lit;
mod valtree;

pub use int::*;
pub use kind::*;
pub use lit::*;
use rustc_span::{DUMMY_SP, ErrorGuaranteed};
pub use valtree::*;

Expand Down
55 changes: 55 additions & 0 deletions compiler/rustc_middle/src/ty/consts/lit.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
use rustc_ast::LitKind;
use rustc_hir;
use rustc_macros::HashStable;

use crate::ty::{self, Ty, TyCtxt};

/// Input argument for `tcx.lit_to_const`.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, HashStable)]
pub struct LitToConstInput<'tcx> {
/// The absolute value of the resultant constant.
pub lit: LitKind,
/// The type of the constant.
pub ty: Ty<'tcx>,
/// If the constant is negative.
pub neg: bool,
}

/// Checks whether a literal can be interpreted as a const of the given type.
pub fn const_lit_matches_ty<'tcx>(
tcx: TyCtxt<'tcx>,
kind: &LitKind,
ty: Ty<'tcx>,
neg: bool,
) -> bool {
match (*kind, ty.kind()) {
(LitKind::Str(..), ty::Ref(_, inner_ty, _)) if inner_ty.is_str() => true,
(LitKind::Str(..), ty::Str) if tcx.features().deref_patterns() => true,
(LitKind::ByteStr(..), ty::Ref(_, inner_ty, _))
if let ty::Slice(ty) | ty::Array(ty, _) = inner_ty.kind()
&& matches!(ty.kind(), ty::Uint(ty::UintTy::U8)) =>
{
true
}
(LitKind::ByteStr(..), ty::Slice(inner_ty) | ty::Array(inner_ty, _))
if tcx.features().deref_patterns()
&& matches!(inner_ty.kind(), ty::Uint(ty::UintTy::U8)) =>
{
true
}
(LitKind::Byte(..), ty::Uint(ty::UintTy::U8)) => true,
(LitKind::CStr(..), ty::Ref(_, inner_ty, _))
if matches!(inner_ty.kind(), ty::Adt(def, _)
if tcx.is_lang_item(def.did(), rustc_hir::LangItem::CStr)) =>
{
true
}
(LitKind::Int(..), ty::Uint(_)) if !neg => true,
(LitKind::Int(..), ty::Int(_)) => true,
(LitKind::Bool(..), ty::Bool) => true,
(LitKind::Float(..), ty::Float(_)) => true,
(LitKind::Char(..), ty::Char) => true,
(LitKind::Err(..), _) => true,
_ => false,
}
}
5 changes: 3 additions & 2 deletions compiler/rustc_middle/src/ty/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,9 @@ pub use self::closure::{
place_to_string_for_capture,
};
pub use self::consts::{
AtomicOrdering, Const, ConstInt, ConstKind, ConstToValTreeResult, Expr, ExprKind, ScalarInt,
SimdAlign, UnevaluatedConst, ValTree, ValTreeKindExt, Value,
AtomicOrdering, Const, ConstInt, ConstKind, ConstToValTreeResult, Expr, ExprKind,
LitToConstInput, ScalarInt, SimdAlign, UnevaluatedConst, ValTree, ValTreeKindExt, Value,
const_lit_matches_ty,
};
pub use self::context::{
CtxtInterners, CurrentGcx, Feed, FreeRegionInfo, GlobalCtxt, Lift, TyCtxt, TyCtxtFeed, tls,
Expand Down
7 changes: 4 additions & 3 deletions compiler/rustc_middle/src/ty/vtable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,10 @@ pub(super) fn vtable_allocation_provider<'tcx>(
// This confirms that the layout computation for &dyn Trait has an accurate sizing.
assert!(vtable_entries.len() >= vtable_min_entries(tcx, poly_trait_ref));

let layout = tcx
.layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(ty))
.expect("failed to build vtable representation");
let layout = match tcx.layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(ty)) {
Ok(layout) => layout,
Err(e) => tcx.dcx().emit_fatal(e.into_diagnostic()),
};
assert!(layout.is_sized(), "can't create a vtable for an unsized type");
let size = layout.size.bytes();
let align = layout.align.bytes();
Expand Down
8 changes: 4 additions & 4 deletions compiler/rustc_mir_build/src/builder/expr/as_constant.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
//! See docs in build/expr/mod.rs
//! See docs in builder/expr/mod.rs

use rustc_abi::Size;
use rustc_ast::{self as ast};
use rustc_hir::LangItem;
use rustc_middle::mir::interpret::{CTFE_ALLOC_SALT, LitToConstInput, Scalar};
use rustc_middle::mir::interpret::{CTFE_ALLOC_SALT, Scalar};
use rustc_middle::mir::*;
use rustc_middle::thir::*;
use rustc_middle::ty::{
self, CanonicalUserType, CanonicalUserTypeAnnotation, Ty, TyCtxt, TypeVisitableExt as _,
UserTypeAnnotationIndex,
self, CanonicalUserType, CanonicalUserTypeAnnotation, LitToConstInput, Ty, TyCtxt,
TypeVisitableExt as _, UserTypeAnnotationIndex,
};
use rustc_middle::{bug, mir, span_bug};
use tracing::{instrument, trace};
Expand Down
Loading
Loading