Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Give real discriminant_type to chalk #15282

Merged
merged 2 commits into from
Jul 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/base-db/src/fixture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ pub trait WithFixture: Default + SourceDatabaseExt + 'static {
let fixture = ChangeFixture::parse(ra_fixture);
let mut db = Self::default();
fixture.change.apply(&mut db);
assert_eq!(fixture.files.len(), 1);
assert_eq!(fixture.files.len(), 1, "Multiple file found in the fixture");
(db, fixture.files[0])
}

Expand Down
38 changes: 38 additions & 0 deletions crates/hir-def/src/macro_expansion_tests/builtin_derive_macro.rs
Original file line number Diff line number Diff line change
Expand Up @@ -416,6 +416,44 @@ fn test_hash_expand() {
//- minicore: derive, hash
use core::hash::Hash;

#[derive(Hash)]
struct Foo {
x: i32,
y: u64,
z: (i32, u64),
}
"#,
expect![[r#"
use core::hash::Hash;

#[derive(Hash)]
struct Foo {
x: i32,
y: u64,
z: (i32, u64),
}

impl < > core::hash::Hash for Foo< > where {
fn hash<H: core::hash::Hasher>(&self , ra_expand_state: &mut H) {
match self {
Foo {
x: x, y: y, z: z,
}
=> {
x.hash(ra_expand_state);
y.hash(ra_expand_state);
z.hash(ra_expand_state);
}
,
}
}
}"#]],
);
check(
r#"
//- minicore: derive, hash
use core::hash::Hash;

#[derive(Hash)]
enum Command {
Move { x: i32, y: i32 },
Expand Down
32 changes: 17 additions & 15 deletions crates/hir-expand/src/builtin_derive_macro.rs
Original file line number Diff line number Diff line change
Expand Up @@ -624,9 +624,14 @@ fn hash_expand(
}
},
);
let check_discriminant = if matches!(&adt.shape, AdtShape::Enum { .. }) {
quote! { #krate::mem::discriminant(self).hash(ra_expand_state); }
} else {
quote! {}
};
quote! {
fn hash<H: #krate::hash::Hasher>(&self, ra_expand_state: &mut H) {
#krate::mem::discriminant(self).hash(ra_expand_state);
#check_discriminant
match self {
##arms
}
Expand Down Expand Up @@ -742,9 +747,6 @@ fn ord_expand(
// FIXME: Return expand error here
return quote!();
}
let left = quote!(#krate::intrinsics::discriminant_value(self));
let right = quote!(#krate::intrinsics::discriminant_value(other));

let (self_patterns, other_patterns) = self_and_other_patterns(adt, &adt.name);
let arms = izip!(self_patterns, other_patterns, adt.shape.field_names()).map(
|(pat1, pat2, fields)| {
Expand All @@ -759,17 +761,17 @@ fn ord_expand(
},
);
let fat_arrow = fat_arrow();
let body = compare(
krate,
left,
right,
quote! {
match (self, other) {
##arms
_unused #fat_arrow #krate::cmp::Ordering::Equal
}
},
);
let mut body = quote! {
match (self, other) {
##arms
_unused #fat_arrow #krate::cmp::Ordering::Equal
}
};
if matches!(&adt.shape, AdtShape::Enum { .. }) {
let left = quote!(#krate::intrinsics::discriminant_value(self));
let right = quote!(#krate::intrinsics::discriminant_value(other));
body = compare(krate, left, right, body);
}
quote! {
fn cmp(&self, other: &Self) -> #krate::cmp::Ordering {
#body
Expand Down
34 changes: 31 additions & 3 deletions crates/hir-ty/src/chalk_db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,37 @@ impl chalk_solve::RustIrDatabase<Interner> for ChalkContext<'_> {
// FIXME: keep track of these
Arc::new(rust_ir::AdtRepr { c: false, packed: false, int: None })
}
fn discriminant_type(&self, _ty: chalk_ir::Ty<Interner>) -> chalk_ir::Ty<Interner> {
// FIXME: keep track of this
chalk_ir::TyKind::Scalar(chalk_ir::Scalar::Uint(chalk_ir::UintTy::U32)).intern(Interner)
fn discriminant_type(&self, ty: chalk_ir::Ty<Interner>) -> chalk_ir::Ty<Interner> {
if let chalk_ir::TyKind::Adt(id, _) = ty.kind(Interner) {
if let hir_def::AdtId::EnumId(e) = id.0 {
let enum_data = self.db.enum_data(e);
let ty = enum_data.repr.unwrap_or_default().discr_type();
return chalk_ir::TyKind::Scalar(match ty {
hir_def::layout::IntegerType::Pointer(is_signed) => match is_signed {
true => chalk_ir::Scalar::Int(chalk_ir::IntTy::Isize),
false => chalk_ir::Scalar::Uint(chalk_ir::UintTy::Usize),
},
hir_def::layout::IntegerType::Fixed(size, is_signed) => match is_signed {
true => chalk_ir::Scalar::Int(match size {
hir_def::layout::Integer::I8 => chalk_ir::IntTy::I8,
hir_def::layout::Integer::I16 => chalk_ir::IntTy::I16,
hir_def::layout::Integer::I32 => chalk_ir::IntTy::I32,
hir_def::layout::Integer::I64 => chalk_ir::IntTy::I64,
hir_def::layout::Integer::I128 => chalk_ir::IntTy::I128,
}),
false => chalk_ir::Scalar::Uint(match size {
hir_def::layout::Integer::I8 => chalk_ir::UintTy::U8,
hir_def::layout::Integer::I16 => chalk_ir::UintTy::U16,
hir_def::layout::Integer::I32 => chalk_ir::UintTy::U32,
hir_def::layout::Integer::I64 => chalk_ir::UintTy::U64,
hir_def::layout::Integer::I128 => chalk_ir::UintTy::U128,
}),
},
})
.intern(Interner);
}
}
chalk_ir::TyKind::Scalar(chalk_ir::Scalar::Uint(chalk_ir::UintTy::U8)).intern(Interner)
}
fn impl_datum(&self, impl_id: ImplId) -> Arc<ImplDatum> {
self.db.impl_datum(self.krate, impl_id)
Expand Down
64 changes: 56 additions & 8 deletions crates/hir-ty/src/consteval/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use hir_def::db::DefDatabase;

use crate::{
consteval::try_const_usize, db::HirDatabase, mir::pad16, test_db::TestDB, Const, ConstScalar,
Interner,
Interner, MemoryMap,
};

use super::{
Expand Down Expand Up @@ -36,7 +36,7 @@ fn check_fail(ra_fixture: &str, error: impl FnOnce(ConstEvalError) -> bool) {

#[track_caller]
fn check_number(ra_fixture: &str, answer: i128) {
check_answer(ra_fixture, |b| {
check_answer(ra_fixture, |b, _| {
assert_eq!(
b,
&answer.to_le_bytes()[0..b.len()],
Expand All @@ -47,8 +47,26 @@ fn check_number(ra_fixture: &str, answer: i128) {
}

#[track_caller]
fn check_answer(ra_fixture: &str, check: impl FnOnce(&[u8])) {
let (db, file_id) = TestDB::with_single_file(ra_fixture);
fn check_str(ra_fixture: &str, answer: &str) {
check_answer(ra_fixture, |b, mm| {
let addr = usize::from_le_bytes(b[0..b.len() / 2].try_into().unwrap());
let size = usize::from_le_bytes(b[b.len() / 2..].try_into().unwrap());
let Some(bytes) = mm.get(addr, size) else {
panic!("string data missed in the memory map");
};
assert_eq!(
bytes,
answer.as_bytes(),
"Bytes differ. In string form: actual = {}, expected = {answer}",
String::from_utf8_lossy(bytes)
);
});
}

#[track_caller]
fn check_answer(ra_fixture: &str, check: impl FnOnce(&[u8], &MemoryMap)) {
let (db, file_ids) = TestDB::with_many_files(ra_fixture);
let file_id = *file_ids.last().unwrap();
let r = match eval_goal(&db, file_id) {
Ok(t) => t,
Err(e) => {
Expand All @@ -58,8 +76,8 @@ fn check_answer(ra_fixture: &str, check: impl FnOnce(&[u8])) {
};
match &r.data(Interner).value {
chalk_ir::ConstValue::Concrete(c) => match &c.interned {
ConstScalar::Bytes(b, _) => {
check(b);
ConstScalar::Bytes(b, mm) => {
check(b, mm);
}
x => panic!("Expected number but found {:?}", x),
},
Expand Down Expand Up @@ -224,7 +242,7 @@ const GOAL: usize = {
transmute(&x)
}
"#,
|b| assert_eq!(b[0] % 8, 0),
|b, _| assert_eq!(b[0] % 8, 0),
);
check_answer(
r#"
Expand All @@ -233,7 +251,7 @@ use core::mem::transmute;
static X: i64 = 12;
const GOAL: usize = transmute(&X);
"#,
|b| assert_eq!(b[0] % 8, 0),
|b, _| assert_eq!(b[0] % 8, 0),
);
}

Expand Down Expand Up @@ -2067,6 +2085,17 @@ fn array_and_index() {
);
}

#[test]
fn string() {
check_str(
r#"
//- minicore: coerce_unsized, index, slice
const GOAL: &str = "hello";
"#,
"hello",
);
}

#[test]
fn byte_string() {
check_number(
Expand Down Expand Up @@ -2443,6 +2472,25 @@ fn const_trait_assoc() {
"#,
32,
);
check_number(
r#"
//- /a/lib.rs crate:a
pub trait ToConst {
const VAL: usize;
}
pub const fn to_const<T: ToConst>() -> usize {
T::VAL
}
//- /main.rs crate:main deps:a
use a::{ToConst, to_const};
struct U0;
impl ToConst for U0 {
const VAL: usize = 5;
}
const GOAL: usize = to_const::<U0>();
"#,
5,
);
check_number(
r#"
struct S<T>(*mut T);
Expand Down
30 changes: 30 additions & 0 deletions crates/hir-ty/src/consteval/tests/intrinsics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,36 @@ fn min_align_of_val() {
);
}

#[test]
fn type_name() {
check_str(
r#"
extern "rust-intrinsic" {
pub fn type_name<T: ?Sized>() -> &'static str;
}

const GOAL: &str = type_name::<i32>();
"#,
"i32",
);
check_str(
r#"
extern "rust-intrinsic" {
pub fn type_name<T: ?Sized>() -> &'static str;
}

mod mod1 {
pub mod mod2 {
pub struct Ty;
}
}

const GOAL: &str = type_name::<mod1::mod2::Ty>();
"#,
"mod1::mod2::Ty",
);
}

#[test]
fn transmute() {
check_number(
Expand Down
38 changes: 38 additions & 0 deletions crates/hir-ty/src/layout/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -464,3 +464,41 @@ fn enums_with_discriminants() {
}
}
}

#[test]
fn core_mem_discriminant() {
size_and_align! {
minicore: discriminant;
struct S(i32, u64);
struct Goal(core::mem::Discriminant<S>);
}
size_and_align! {
minicore: discriminant;
#[repr(u32)]
enum S {
A,
B,
C,
}
struct Goal(core::mem::Discriminant<S>);
}
size_and_align! {
minicore: discriminant;
enum S {
A(i32),
B(i64),
C(u8),
}
struct Goal(core::mem::Discriminant<S>);
}
size_and_align! {
minicore: discriminant;
#[repr(C, u16)]
enum S {
A(i32),
B(i64) = 200,
C = 1000,
}
struct Goal(core::mem::Discriminant<S>);
}
}