Skip to content

Commit e19dfc8

Browse files
authored
Merge pull request #21388 from Veykril/push-uyrsywszqotk
Remove unnecessary `ConstLiteralRef` enum
2 parents 913fdb2 + 8ecf6fc commit e19dfc8

File tree

5 files changed

+130
-98
lines changed

5 files changed

+130
-98
lines changed

crates/hir-def/src/expr_store/lower.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2319,7 +2319,6 @@ impl<'db> ExprCollector<'db> {
23192319
ast::Pat::SlicePat(p) => {
23202320
let SlicePatComponents { prefix, slice, suffix } = p.components();
23212321

2322-
// FIXME properly handle `RestPat`
23232322
Pat::Slice {
23242323
prefix: prefix.into_iter().map(|p| self.collect_pat(p, binding_list)).collect(),
23252324
slice: slice.map(|p| self.collect_pat(p, binding_list)),

crates/hir-def/src/hir/type_ref.rs

Lines changed: 1 addition & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,18 @@
11
//! HIR for references to types. Paths in these are not yet resolved. They can
22
//! be directly created from an ast::TypeRef, without further queries.
33
4-
use std::fmt::Write;
5-
64
use hir_expand::name::Name;
75
use intern::Symbol;
86
use la_arena::Idx;
97
use thin_vec::ThinVec;
108

119
use crate::{
1210
LifetimeParamId, TypeParamId,
13-
builtin_type::{BuiltinInt, BuiltinType, BuiltinUint},
1411
expr_store::{
1512
ExpressionStore,
1613
path::{GenericArg, Path},
1714
},
18-
hir::{ExprId, Literal},
15+
hir::ExprId,
1916
};
2017

2118
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
@@ -275,56 +272,3 @@ impl TypeBound {
275272
pub struct ConstRef {
276273
pub expr: ExprId,
277274
}
278-
279-
/// A literal constant value
280-
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
281-
pub enum LiteralConstRef {
282-
Int(i128),
283-
UInt(u128),
284-
Bool(bool),
285-
Char(char),
286-
287-
/// Case of an unknown value that rustc might know but we don't
288-
// FIXME: this is a hack to get around chalk not being able to represent unevaluatable
289-
// constants
290-
// https://github.com/rust-lang/rust-analyzer/pull/8813#issuecomment-840679177
291-
// https://rust-lang.zulipchat.com/#narrow/stream/144729-wg-traits/topic/Handling.20non.20evaluatable.20constants'.20equality/near/238386348
292-
Unknown,
293-
}
294-
295-
impl LiteralConstRef {
296-
pub fn builtin_type(&self) -> BuiltinType {
297-
match self {
298-
LiteralConstRef::UInt(_) | LiteralConstRef::Unknown => {
299-
BuiltinType::Uint(BuiltinUint::U128)
300-
}
301-
LiteralConstRef::Int(_) => BuiltinType::Int(BuiltinInt::I128),
302-
LiteralConstRef::Char(_) => BuiltinType::Char,
303-
LiteralConstRef::Bool(_) => BuiltinType::Bool,
304-
}
305-
}
306-
}
307-
308-
impl From<Literal> for LiteralConstRef {
309-
fn from(literal: Literal) -> Self {
310-
match literal {
311-
Literal::Char(c) => Self::Char(c),
312-
Literal::Bool(flag) => Self::Bool(flag),
313-
Literal::Int(num, _) => Self::Int(num),
314-
Literal::Uint(num, _) => Self::UInt(num),
315-
_ => Self::Unknown,
316-
}
317-
}
318-
}
319-
320-
impl std::fmt::Display for LiteralConstRef {
321-
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
322-
match self {
323-
LiteralConstRef::Int(num) => num.fmt(f),
324-
LiteralConstRef::UInt(num) => num.fmt(f),
325-
LiteralConstRef::Bool(flag) => flag.fmt(f),
326-
LiteralConstRef::Char(c) => write!(f, "'{c}'"),
327-
LiteralConstRef::Unknown => f.write_char('_'),
328-
}
329-
}
330-
}

crates/hir-ty/src/consteval.rs

Lines changed: 105 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,9 @@ use base_db::Crate;
77
use hir_def::{
88
ConstId, EnumVariantId, GeneralConstId, HasModule, StaticId,
99
attrs::AttrFlags,
10+
builtin_type::{BuiltinInt, BuiltinType, BuiltinUint},
1011
expr_store::Body,
11-
hir::{Expr, ExprId},
12-
type_ref::LiteralConstRef,
12+
hir::{Expr, ExprId, Literal},
1313
};
1414
use hir_expand::Lookup;
1515
use rustc_type_ir::inherent::IntoKind;
@@ -23,7 +23,7 @@ use crate::{
2323
mir::{MirEvalError, MirLowerError},
2424
next_solver::{
2525
Const, ConstBytes, ConstKind, DbInterner, ErrorGuaranteed, GenericArg, GenericArgs,
26-
ParamEnv, StoredConst, StoredGenericArgs, Ty, ValueConst,
26+
StoredConst, StoredGenericArgs, Ty, ValueConst,
2727
},
2828
traits::StoredParamEnvAndCrate,
2929
};
@@ -81,47 +81,122 @@ impl From<MirEvalError> for ConstEvalError {
8181
/// Interns a constant scalar with the given type
8282
pub fn intern_const_ref<'a>(
8383
db: &'a dyn HirDatabase,
84-
value: &LiteralConstRef,
84+
value: &Literal,
8585
ty: Ty<'a>,
86-
krate: Crate,
86+
_krate: Crate,
8787
) -> Const<'a> {
8888
let interner = DbInterner::new_no_crate(db);
89-
let layout = db
90-
.layout_of_ty(ty.store(), ParamEnvAndCrate { param_env: ParamEnv::empty(), krate }.store());
9189
let kind = match value {
92-
LiteralConstRef::Int(i) => {
93-
// FIXME: We should handle failure of layout better.
94-
let size = layout.map(|it| it.size.bytes_usize()).unwrap_or(16);
90+
&Literal::Uint(i, builtin_ty)
91+
if builtin_ty.is_none() || ty.as_builtin() == builtin_ty.map(BuiltinType::Uint) =>
92+
{
93+
let memory = match ty.as_builtin() {
94+
Some(BuiltinType::Uint(builtin_uint)) => match builtin_uint {
95+
BuiltinUint::U8 => Box::new([i as u8]) as Box<[u8]>,
96+
BuiltinUint::U16 => Box::new((i as u16).to_le_bytes()),
97+
BuiltinUint::U32 => Box::new((i as u32).to_le_bytes()),
98+
BuiltinUint::U64 => Box::new((i as u64).to_le_bytes()),
99+
BuiltinUint::U128 => Box::new((i).to_le_bytes()),
100+
BuiltinUint::Usize => Box::new((i as usize).to_le_bytes()),
101+
},
102+
_ => return Const::new(interner, rustc_type_ir::ConstKind::Error(ErrorGuaranteed)),
103+
};
95104
rustc_type_ir::ConstKind::Value(ValueConst::new(
96105
ty,
97-
ConstBytes {
98-
memory: i.to_le_bytes()[0..size].into(),
99-
memory_map: MemoryMap::default(),
106+
ConstBytes { memory, memory_map: MemoryMap::default() },
107+
))
108+
}
109+
&Literal::Int(i, None)
110+
if ty
111+
.as_builtin()
112+
.is_some_and(|builtin_ty| matches!(builtin_ty, BuiltinType::Uint(_))) =>
113+
{
114+
let memory = match ty.as_builtin() {
115+
Some(BuiltinType::Uint(builtin_uint)) => match builtin_uint {
116+
BuiltinUint::U8 => Box::new([i as u8]) as Box<[u8]>,
117+
BuiltinUint::U16 => Box::new((i as u16).to_le_bytes()),
118+
BuiltinUint::U32 => Box::new((i as u32).to_le_bytes()),
119+
BuiltinUint::U64 => Box::new((i as u64).to_le_bytes()),
120+
BuiltinUint::U128 => Box::new((i as u128).to_le_bytes()),
121+
BuiltinUint::Usize => Box::new((i as usize).to_le_bytes()),
100122
},
123+
_ => return Const::new(interner, rustc_type_ir::ConstKind::Error(ErrorGuaranteed)),
124+
};
125+
rustc_type_ir::ConstKind::Value(ValueConst::new(
126+
ty,
127+
ConstBytes { memory, memory_map: MemoryMap::default() },
101128
))
102129
}
103-
LiteralConstRef::UInt(i) => {
104-
let size = layout.map(|it| it.size.bytes_usize()).unwrap_or(16);
130+
&Literal::Int(i, builtin_ty)
131+
if builtin_ty.is_none() || ty.as_builtin() == builtin_ty.map(BuiltinType::Int) =>
132+
{
133+
let memory = match ty.as_builtin() {
134+
Some(BuiltinType::Int(builtin_int)) => match builtin_int {
135+
BuiltinInt::I8 => Box::new([i as u8]) as Box<[u8]>,
136+
BuiltinInt::I16 => Box::new((i as i16).to_le_bytes()),
137+
BuiltinInt::I32 => Box::new((i as i32).to_le_bytes()),
138+
BuiltinInt::I64 => Box::new((i as i64).to_le_bytes()),
139+
BuiltinInt::I128 => Box::new((i).to_le_bytes()),
140+
BuiltinInt::Isize => Box::new((i as isize).to_le_bytes()),
141+
},
142+
_ => return Const::new(interner, rustc_type_ir::ConstKind::Error(ErrorGuaranteed)),
143+
};
105144
rustc_type_ir::ConstKind::Value(ValueConst::new(
106145
ty,
107-
ConstBytes {
108-
memory: i.to_le_bytes()[0..size].into(),
109-
memory_map: MemoryMap::default(),
146+
ConstBytes { memory, memory_map: MemoryMap::default() },
147+
))
148+
}
149+
Literal::Float(float_type_wrapper, builtin_float)
150+
if builtin_float.is_none()
151+
|| ty.as_builtin() == builtin_float.map(BuiltinType::Float) =>
152+
{
153+
let memory = match ty.as_builtin().unwrap() {
154+
BuiltinType::Float(builtin_float) => match builtin_float {
155+
// FIXME:
156+
hir_def::builtin_type::BuiltinFloat::F16 => Box::new([0u8; 2]) as Box<[u8]>,
157+
hir_def::builtin_type::BuiltinFloat::F32 => {
158+
Box::new(float_type_wrapper.to_f32().to_le_bytes())
159+
}
160+
hir_def::builtin_type::BuiltinFloat::F64 => {
161+
Box::new(float_type_wrapper.to_f64().to_le_bytes())
162+
}
163+
// FIXME:
164+
hir_def::builtin_type::BuiltinFloat::F128 => Box::new([0; 16]),
110165
},
166+
_ => unreachable!(),
167+
};
168+
rustc_type_ir::ConstKind::Value(ValueConst::new(
169+
ty,
170+
ConstBytes { memory, memory_map: MemoryMap::default() },
111171
))
112172
}
113-
LiteralConstRef::Bool(b) => rustc_type_ir::ConstKind::Value(ValueConst::new(
173+
Literal::Bool(b) if ty.is_bool() => rustc_type_ir::ConstKind::Value(ValueConst::new(
114174
ty,
115175
ConstBytes { memory: Box::new([*b as u8]), memory_map: MemoryMap::default() },
116176
)),
117-
LiteralConstRef::Char(c) => rustc_type_ir::ConstKind::Value(ValueConst::new(
177+
Literal::Char(c) if ty.is_char() => rustc_type_ir::ConstKind::Value(ValueConst::new(
118178
ty,
119179
ConstBytes {
120180
memory: (*c as u32).to_le_bytes().into(),
121181
memory_map: MemoryMap::default(),
122182
},
123183
)),
124-
LiteralConstRef::Unknown => rustc_type_ir::ConstKind::Error(ErrorGuaranteed),
184+
Literal::String(symbol) if ty.is_str() => rustc_type_ir::ConstKind::Value(ValueConst::new(
185+
ty,
186+
ConstBytes {
187+
memory: symbol.as_str().as_bytes().into(),
188+
memory_map: MemoryMap::default(),
189+
},
190+
)),
191+
Literal::ByteString(items) if ty.as_slice().is_some_and(|ty| ty.is_u8()) => {
192+
rustc_type_ir::ConstKind::Value(ValueConst::new(
193+
ty,
194+
ConstBytes { memory: items.clone(), memory_map: MemoryMap::default() },
195+
))
196+
}
197+
// FIXME
198+
Literal::CString(_items) => rustc_type_ir::ConstKind::Error(ErrorGuaranteed),
199+
_ => rustc_type_ir::ConstKind::Error(ErrorGuaranteed),
125200
};
126201
Const::new(interner, kind)
127202
}
@@ -130,7 +205,15 @@ pub fn intern_const_ref<'a>(
130205
pub fn usize_const<'db>(db: &'db dyn HirDatabase, value: Option<u128>, krate: Crate) -> Const<'db> {
131206
intern_const_ref(
132207
db,
133-
&value.map_or(LiteralConstRef::Unknown, LiteralConstRef::UInt),
208+
&match value {
209+
Some(value) => Literal::Uint(value, Some(BuiltinUint::Usize)),
210+
None => {
211+
return Const::new(
212+
DbInterner::new_no_crate(db),
213+
rustc_type_ir::ConstKind::Error(ErrorGuaranteed),
214+
);
215+
}
216+
},
134217
Ty::new_uint(DbInterner::new_no_crate(db), rustc_type_ir::UintTy::Usize),
135218
krate,
136219
)

crates/hir-ty/src/lower.rs

Lines changed: 6 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,8 @@ use hir_def::{
2727
resolver::{HasResolver, LifetimeNs, Resolver, TypeNs, ValueNs},
2828
signatures::{FunctionSignature, TraitFlags, TypeAliasFlags},
2929
type_ref::{
30-
ConstRef, LifetimeRefId, LiteralConstRef, PathId, TraitBoundModifier,
31-
TraitRef as HirTraitRef, TypeBound, TypeRef, TypeRefId,
30+
ConstRef, LifetimeRefId, PathId, TraitBoundModifier, TraitRef as HirTraitRef, TypeBound,
31+
TypeRef, TypeRefId,
3232
},
3333
};
3434
use hir_expand::name::Name;
@@ -281,21 +281,9 @@ impl<'db, 'a> TyLoweringContext<'db, 'a> {
281281
hir_def::hir::Expr::Path(path) => {
282282
self.path_to_const(path).unwrap_or_else(|| unknown_const(const_type))
283283
}
284-
hir_def::hir::Expr::Literal(literal) => intern_const_ref(
285-
self.db,
286-
&match *literal {
287-
hir_def::hir::Literal::Float(_, _)
288-
| hir_def::hir::Literal::String(_)
289-
| hir_def::hir::Literal::ByteString(_)
290-
| hir_def::hir::Literal::CString(_) => LiteralConstRef::Unknown,
291-
hir_def::hir::Literal::Char(c) => LiteralConstRef::Char(c),
292-
hir_def::hir::Literal::Bool(b) => LiteralConstRef::Bool(b),
293-
hir_def::hir::Literal::Int(val, _) => LiteralConstRef::Int(val),
294-
hir_def::hir::Literal::Uint(val, _) => LiteralConstRef::UInt(val),
295-
},
296-
const_type,
297-
self.resolver.krate(),
298-
),
284+
hir_def::hir::Expr::Literal(literal) => {
285+
intern_const_ref(self.db, literal, const_type, self.resolver.krate())
286+
}
299287
hir_def::hir::Expr::UnaryOp { expr: inner_expr, op: hir_def::hir::UnaryOp::Neg } => {
300288
if let hir_def::hir::Expr::Literal(literal) = &self.store[*inner_expr] {
301289
// Only handle negation for signed integers and floats
@@ -304,7 +292,7 @@ impl<'db, 'a> TyLoweringContext<'db, 'a> {
304292
if let Some(negated_literal) = literal.clone().negate() {
305293
intern_const_ref(
306294
self.db,
307-
&negated_literal.into(),
295+
&negated_literal,
308296
const_type,
309297
self.resolver.krate(),
310298
)

crates/hir-ty/src/next_solver/ty.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -383,6 +383,11 @@ impl<'db> Ty<'db> {
383383
matches!(self.kind(), TyKind::Bool)
384384
}
385385

386+
#[inline]
387+
pub fn is_char(self) -> bool {
388+
matches!(self.kind(), TyKind::Char)
389+
}
390+
386391
/// A scalar type is one that denotes an atomic datum, with no sub-components.
387392
/// (A RawPtr is scalar because it represents a non-managed pointer, so its
388393
/// contents are abstract to rustc.)
@@ -422,6 +427,11 @@ impl<'db> Ty<'db> {
422427
matches!(self.kind(), TyKind::Tuple(tys) if tys.is_empty())
423428
}
424429

430+
#[inline]
431+
pub fn is_u8(self) -> bool {
432+
matches!(self.kind(), TyKind::Uint(UintTy::U8))
433+
}
434+
425435
#[inline]
426436
pub fn is_raw_ptr(self) -> bool {
427437
matches!(self.kind(), TyKind::RawPtr(..))
@@ -456,6 +466,14 @@ impl<'db> Ty<'db> {
456466
}
457467
}
458468

469+
#[inline]
470+
pub fn as_slice(self) -> Option<Ty<'db>> {
471+
match self.kind() {
472+
TyKind::Slice(ty) => Some(ty),
473+
_ => None,
474+
}
475+
}
476+
459477
#[inline]
460478
pub fn ty_vid(self) -> Option<TyVid> {
461479
match self.kind() {

0 commit comments

Comments
 (0)