Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 8086647

Browse files
committedNov 25, 2022
use rustc crates instead of copy paste
1 parent 08e71fa commit 8086647

File tree

16 files changed

+270
-2063
lines changed

16 files changed

+270
-2063
lines changed
 

‎Cargo.lock

Lines changed: 26 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ exclude = ["crates/proc-macro-test/imp"]
55
[profile.dev]
66
# Disabling debug info speeds up builds a bunch,
77
# and we don't rely on it for debugging that much.
8-
debug = 0
8+
# debug = 0
99

1010
[profile.dev.package]
1111
# These speed up local tests.

‎crates/hir-def/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ base-db = { path = "../base-db", version = "0.0.0" }
3333
syntax = { path = "../syntax", version = "0.0.0" }
3434
profile = { path = "../profile", version = "0.0.0" }
3535
hir-expand = { path = "../hir-expand", version = "0.0.0" }
36+
rustc_abi = { version = "0.0.20221125", package = "hkalbasi-rustc-ap-rustc_abi", default-features = false }
3637
mbe = { path = "../mbe", version = "0.0.0" }
3738
cfg = { path = "../cfg", version = "0.0.0" }
3839
tt = { path = "../tt", version = "0.0.0" }

‎crates/hir-def/src/adt.rs

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ use hir_expand::{
99
HirFileId, InFile,
1010
};
1111
use la_arena::{Arena, ArenaMap};
12+
use rustc_abi::{Integer, IntegerType};
1213
use syntax::ast::{self, HasName, HasVisibility};
1314
use tt::{Delimiter, DelimiterKind, Leaf, Subtree, TokenTree};
1415

@@ -127,15 +128,32 @@ fn parse_repr_tt(tt: &Subtree) -> Option<ReprOptions> {
127128
.map(Either::Left)
128129
.or_else(|| BuiltinUint::from_suffix(repr).map(Either::Right))
129130
{
130-
int = Some(builtin);
131+
int = Some(match builtin {
132+
Either::Left(bi) => match bi {
133+
BuiltinInt::Isize => IntegerType::Pointer(true),
134+
BuiltinInt::I8 => IntegerType::Fixed(Integer::I8, true),
135+
BuiltinInt::I16 => IntegerType::Fixed(Integer::I16, true),
136+
BuiltinInt::I32 => IntegerType::Fixed(Integer::I32, true),
137+
BuiltinInt::I64 => IntegerType::Fixed(Integer::I64, true),
138+
BuiltinInt::I128 => IntegerType::Fixed(Integer::I128, true),
139+
},
140+
Either::Right(bu) => match bu {
141+
BuiltinUint::Usize => IntegerType::Pointer(false),
142+
BuiltinUint::U8 => IntegerType::Fixed(Integer::I8, false),
143+
BuiltinUint::U16 => IntegerType::Fixed(Integer::I16, false),
144+
BuiltinUint::U32 => IntegerType::Fixed(Integer::I32, false),
145+
BuiltinUint::U64 => IntegerType::Fixed(Integer::I64, false),
146+
BuiltinUint::U128 => IntegerType::Fixed(Integer::I128, false),
147+
},
148+
});
131149
}
132150
ReprFlags::empty()
133151
}
134152
})
135153
}
136154
}
137155

138-
Some(ReprOptions { int, align: max_align, pack: min_pack, flags })
156+
Some(ReprOptions { int, align: max_align, pack: min_pack, flags, field_shuffle_seed: 0 })
139157
}
140158

141159
impl StructData {
@@ -276,10 +294,10 @@ impl EnumData {
276294
Some(id)
277295
}
278296

279-
pub fn variant_body_type(&self) -> Either<BuiltinInt, BuiltinUint> {
297+
pub fn variant_body_type(&self) -> IntegerType {
280298
match self.repr {
281299
Some(ReprOptions { int: Some(builtin), .. }) => builtin,
282-
_ => Either::Left(BuiltinInt::Isize),
300+
_ => IntegerType::Pointer(true),
283301
}
284302
}
285303
}

‎crates/hir-def/src/layout.rs

Lines changed: 22 additions & 1113 deletions
Large diffs are not rendered by default.

‎crates/hir-ty/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ chalk-derive = "0.86.0"
2525
la-arena = { version = "0.3.0", path = "../../lib/la-arena" }
2626
once_cell = "1.15.0"
2727
typed-arena = "2.0.1"
28+
rustc_index = { version = "0.0.20221125", package = "hkalbasi-rustc-ap-rustc_index", default-features = false }
2829

2930
stdx = { path = "../stdx", version = "0.0.0" }
3031
hir-def = { path = "../hir-def", version = "0.0.0" }

‎crates/hir-ty/src/infer.rs

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,11 @@ use std::sync::Arc;
1919
use chalk_ir::{cast::Cast, ConstValue, DebruijnIndex, Mutability, Safety, Scalar, TypeFlags};
2020
use hir_def::{
2121
body::Body,
22-
builtin_type::BuiltinType,
22+
builtin_type::{BuiltinInt, BuiltinType, BuiltinUint},
2323
data::{ConstData, StaticData},
2424
expr::{BindingAnnotation, ExprId, PatId},
2525
lang_item::LangItemTarget,
26+
layout::Integer,
2627
path::{path, Path},
2728
resolver::{HasResolver, ResolveValueResult, Resolver, TypeNs, ValueNs},
2829
type_ref::TypeRef,
@@ -70,8 +71,26 @@ pub(crate) fn infer_query(db: &dyn HirDatabase, def: DefWithBodyId) -> Arc<Infer
7071
DefWithBodyId::StaticId(s) => ctx.collect_static(&db.static_data(s)),
7172
DefWithBodyId::VariantId(v) => {
7273
ctx.return_ty = TyBuilder::builtin(match db.enum_data(v.parent).variant_body_type() {
73-
Either::Left(builtin) => BuiltinType::Int(builtin),
74-
Either::Right(builtin) => BuiltinType::Uint(builtin),
74+
hir_def::layout::IntegerType::Pointer(signed) => match signed {
75+
true => BuiltinType::Int(BuiltinInt::Isize),
76+
false => BuiltinType::Uint(BuiltinUint::Usize),
77+
},
78+
hir_def::layout::IntegerType::Fixed(size, signed) => match signed {
79+
true => BuiltinType::Int(match size {
80+
Integer::I8 => BuiltinInt::I8,
81+
Integer::I16 => BuiltinInt::I16,
82+
Integer::I32 => BuiltinInt::I32,
83+
Integer::I64 => BuiltinInt::I64,
84+
Integer::I128 => BuiltinInt::I128,
85+
}),
86+
false => BuiltinType::Uint(match size {
87+
Integer::I8 => BuiltinUint::U8,
88+
Integer::I16 => BuiltinUint::U16,
89+
Integer::I32 => BuiltinUint::U32,
90+
Integer::I64 => BuiltinUint::U64,
91+
Integer::I128 => BuiltinUint::U128,
92+
}),
93+
},
7594
});
7695
}
7796
}

‎crates/hir-ty/src/layout.rs

Lines changed: 46 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,15 @@
11
//! Compute the binary representation of a type
22
3+
use std::sync::Arc;
4+
35
use chalk_ir::{AdtId, TyKind};
46
pub(self) use hir_def::layout::*;
5-
use hir_def::LocalFieldId;
7+
use hir_def::{LocalEnumVariantId, LocalFieldId};
8+
use stdx::never;
69

710
use crate::{db::HirDatabase, Interner, Substitution, Ty};
811

9-
use self::adt::univariant;
12+
use self::adt::struct_variant_idx;
1013
pub use self::{
1114
adt::{layout_of_adt_query, layout_of_adt_recover},
1215
target::current_target_data_layout_query,
@@ -21,6 +24,22 @@ macro_rules! user_error {
2124
mod adt;
2225
mod target;
2326

27+
struct LayoutCx<'a> {
28+
db: &'a dyn HirDatabase,
29+
}
30+
31+
impl LayoutCalculator for LayoutCx<'_> {
32+
type TargetDataLayoutRef = Arc<TargetDataLayout>;
33+
34+
fn delay_bug(&self, txt: &str) {
35+
never!("{}", txt);
36+
}
37+
38+
fn current_data_layout(&self) -> Arc<TargetDataLayout> {
39+
self.db.current_target_data_layout()
40+
}
41+
}
42+
2443
fn scalar_unit(dl: &TargetDataLayout, value: Primitive) -> Scalar {
2544
Scalar::Initialized { value, valid_range: WrappingRange::full(value.size(dl)) }
2645
}
@@ -29,34 +48,9 @@ fn scalar(dl: &TargetDataLayout, value: Primitive) -> Layout {
2948
Layout::scalar(dl, scalar_unit(dl, value))
3049
}
3150

32-
fn scalar_pair(dl: &TargetDataLayout, a: Scalar, b: Scalar) -> Layout {
33-
let b_align = b.align(dl);
34-
let align = a.align(dl).max(b_align).max(dl.aggregate_align);
35-
let b_offset = a.size(dl).align_to(b_align.abi);
36-
let size = b_offset.checked_add(b.size(dl), dl).unwrap().align_to(align.abi);
37-
38-
// HACK(nox): We iter on `b` and then `a` because `max_by_key`
39-
// returns the last maximum.
40-
let largest_niche = Niche::from_scalar(dl, b_offset, b)
41-
.into_iter()
42-
.chain(Niche::from_scalar(dl, Size::ZERO, a))
43-
.max_by_key(|niche| niche.available(dl));
44-
45-
Layout {
46-
variants: Variants::Single,
47-
fields: FieldsShape::Arbitrary {
48-
offsets: vec![Size::ZERO, b_offset],
49-
memory_index: vec![0, 1],
50-
},
51-
abi: Abi::ScalarPair(a, b),
52-
largest_niche,
53-
align,
54-
size,
55-
}
56-
}
57-
5851
pub fn layout_of_ty(db: &dyn HirDatabase, ty: &Ty) -> Result<Layout, LayoutError> {
5952
let dl = &*db.current_target_data_layout();
53+
let cx = LayoutCx { db };
6054
Ok(match ty.kind(Interner) {
6155
TyKind::Adt(AdtId(def), subst) => db.layout_of_adt(*def, subst.clone())?,
6256
TyKind::Scalar(s) => match s {
@@ -113,14 +107,13 @@ pub fn layout_of_ty(db: &dyn HirDatabase, ty: &Ty) -> Result<Layout, LayoutError
113107
TyKind::Tuple(len, tys) => {
114108
let kind = if *len == 0 { StructKind::AlwaysSized } else { StructKind::MaybeUnsized };
115109

116-
univariant(
117-
dl,
118-
&tys.iter(Interner)
119-
.map(|k| layout_of_ty(db, k.assert_ty_ref(Interner)))
120-
.collect::<Result<Vec<_>, _>>()?,
121-
&ReprOptions::default(),
122-
kind,
123-
)?
110+
let fields = tys
111+
.iter(Interner)
112+
.map(|k| layout_of_ty(db, k.assert_ty_ref(Interner)))
113+
.collect::<Result<Vec<_>, _>>()?;
114+
let fields = fields.iter().collect::<Vec<_>>();
115+
let fields = fields.iter().collect::<Vec<_>>();
116+
cx.univariant(dl, &fields, &ReprOptions::default(), kind).ok_or(LayoutError::Unknown)?
124117
}
125118
TyKind::Array(element, count) => {
126119
let count = match count.data(Interner).value {
@@ -146,7 +139,7 @@ pub fn layout_of_ty(db: &dyn HirDatabase, ty: &Ty) -> Result<Layout, LayoutError
146139
let largest_niche = if count != 0 { element.largest_niche } else { None };
147140

148141
Layout {
149-
variants: Variants::Single,
142+
variants: Variants::Single { index: struct_variant_idx() },
150143
fields: FieldsShape::Array { stride: element.size, count },
151144
abi,
152145
largest_niche,
@@ -157,7 +150,7 @@ pub fn layout_of_ty(db: &dyn HirDatabase, ty: &Ty) -> Result<Layout, LayoutError
157150
TyKind::Slice(element) => {
158151
let element = layout_of_ty(db, element)?;
159152
Layout {
160-
variants: Variants::Single,
153+
variants: Variants::Single { index: struct_variant_idx() },
161154
fields: FieldsShape::Array { stride: element.size, count: 0 },
162155
abi: Abi::Aggregate { sized: false },
163156
largest_niche: None,
@@ -194,29 +187,27 @@ pub fn layout_of_ty(db: &dyn HirDatabase, ty: &Ty) -> Result<Layout, LayoutError
194187
};
195188

196189
// Effectively a (ptr, meta) tuple.
197-
scalar_pair(dl, data_ptr, metadata)
198-
}
199-
TyKind::FnDef(_, _) => {
200-
univariant(dl, &[], &ReprOptions::default(), StructKind::AlwaysSized)?
190+
cx.scalar_pair(data_ptr, metadata)
201191
}
192+
TyKind::FnDef(_, _) => layout_of_unit(&cx, dl)?,
202193
TyKind::Str => Layout {
203-
variants: Variants::Single,
194+
variants: Variants::Single { index: struct_variant_idx() },
204195
fields: FieldsShape::Array { stride: Size::from_bytes(1), count: 0 },
205196
abi: Abi::Aggregate { sized: false },
206197
largest_niche: None,
207198
align: dl.i8_align,
208199
size: Size::ZERO,
209200
},
210201
TyKind::Never => Layout {
211-
variants: Variants::Single,
202+
variants: Variants::Single { index: struct_variant_idx() },
212203
fields: FieldsShape::Primitive,
213204
abi: Abi::Uninhabited,
214205
largest_niche: None,
215206
align: dl.i8_align,
216207
size: Size::ZERO,
217208
},
218209
TyKind::Dyn(_) | TyKind::Foreign(_) => {
219-
let mut unit = univariant(dl, &[], &ReprOptions::default(), StructKind::AlwaysSized)?;
210+
let mut unit = layout_of_unit(&cx, dl)?;
220211
match unit.abi {
221212
Abi::Aggregate { ref mut sized } => *sized = false,
222213
_ => user_error!("bug"),
@@ -241,6 +232,16 @@ pub fn layout_of_ty(db: &dyn HirDatabase, ty: &Ty) -> Result<Layout, LayoutError
241232
})
242233
}
243234

235+
fn layout_of_unit(cx: &LayoutCx<'_>, dl: &TargetDataLayout) -> Result<Layout, LayoutError> {
236+
cx.univariant::<LocalEnumVariantId, &&Layout>(
237+
&dl,
238+
&[],
239+
&ReprOptions::default(),
240+
StructKind::AlwaysSized,
241+
)
242+
.ok_or(LayoutError::Unknown)
243+
}
244+
244245
fn struct_tail_erasing_lifetimes(db: &dyn HirDatabase, pointee: Ty) -> Ty {
245246
match pointee.kind(Interner) {
246247
TyKind::Adt(AdtId(adt), subst) => match adt {

‎crates/hir-ty/src/layout/adt.rs

Lines changed: 70 additions & 889 deletions
Large diffs are not rendered by default.

‎crates/hir-ty/src/layout/target.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ pub fn current_target_data_layout_query(db: &dyn HirDatabase) -> Arc<TargetDataL
3535
f32_align: AbiAndPrefAlign::new(Align::from_bytes(4).unwrap()),
3636
f64_align: AbiAndPrefAlign::new(Align::from_bytes(8).unwrap()),
3737
pointer_size,
38-
pointer_align: AbiAndPrefAlign::new(Align::from_bytes(8).unwrap()),
38+
pointer_align: AbiAndPrefAlign::new(Align::from_bytes(pointer_size.bytes()).unwrap()),
3939
aggregate_align: AbiAndPrefAlign::new(Align::from_bytes(1).unwrap()),
4040
vector_align: vec![],
4141
instruction_address_space: AddressSpace(0),

‎crates/hir-ty/src/layout/tests.rs

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,6 @@ fn hello_world() {
6767
size_and_align! {
6868
struct Goal(i32);
6969
}
70-
//check_size_and_align(r#"struct Goal(i32)"#, 4, 4);
7170
}
7271

7372
#[test]
@@ -178,3 +177,21 @@ fn niche_optimization() {
178177
1,
179178
);
180179
}
180+
181+
#[test]
182+
fn enums_with_discriminants() {
183+
size_and_align! {
184+
enum Goal {
185+
A = 1000,
186+
B = 2000,
187+
C = 3000,
188+
}
189+
}
190+
size_and_align! {
191+
enum Goal {
192+
A = 254,
193+
B,
194+
C, // implicitly becomes 256, so we need two bytes
195+
}
196+
}
197+
}

‎crates/hir/src/lib.rs

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -994,8 +994,30 @@ impl Enum {
994994
Type::new_for_crate(
995995
self.id.lookup(db.upcast()).container.krate(),
996996
TyBuilder::builtin(match db.enum_data(self.id).variant_body_type() {
997-
Either::Left(builtin) => hir_def::builtin_type::BuiltinType::Int(builtin),
998-
Either::Right(builtin) => hir_def::builtin_type::BuiltinType::Uint(builtin),
997+
hir_def::layout::IntegerType::Pointer(sign) => match sign {
998+
true => hir_def::builtin_type::BuiltinType::Int(
999+
hir_def::builtin_type::BuiltinInt::Isize,
1000+
),
1001+
false => hir_def::builtin_type::BuiltinType::Uint(
1002+
hir_def::builtin_type::BuiltinUint::Usize,
1003+
),
1004+
},
1005+
hir_def::layout::IntegerType::Fixed(i, sign) => match sign {
1006+
true => hir_def::builtin_type::BuiltinType::Int(match i {
1007+
hir_def::layout::Integer::I8 => hir_def::builtin_type::BuiltinInt::I8,
1008+
hir_def::layout::Integer::I16 => hir_def::builtin_type::BuiltinInt::I16,
1009+
hir_def::layout::Integer::I32 => hir_def::builtin_type::BuiltinInt::I32,
1010+
hir_def::layout::Integer::I64 => hir_def::builtin_type::BuiltinInt::I64,
1011+
hir_def::layout::Integer::I128 => hir_def::builtin_type::BuiltinInt::I128,
1012+
}),
1013+
false => hir_def::builtin_type::BuiltinType::Uint(match i {
1014+
hir_def::layout::Integer::I8 => hir_def::builtin_type::BuiltinUint::U8,
1015+
hir_def::layout::Integer::I16 => hir_def::builtin_type::BuiltinUint::U16,
1016+
hir_def::layout::Integer::I32 => hir_def::builtin_type::BuiltinUint::U32,
1017+
hir_def::layout::Integer::I64 => hir_def::builtin_type::BuiltinUint::U64,
1018+
hir_def::layout::Integer::I128 => hir_def::builtin_type::BuiltinUint::U128,
1019+
}),
1020+
},
9991021
}),
10001022
)
10011023
}

‎crates/ide/src/hover/render.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,7 @@ use std::fmt::Display;
33

44
use either::Either;
55
use hir::{
6-
db::HirDatabase, Adt, AsAssocItem, AttributeTemplate, HasAttrs, HasSource, HirDisplay,
7-
Semantics, TypeInfo,
6+
Adt, AsAssocItem, AttributeTemplate, HasAttrs, HasSource, HirDisplay, Semantics, TypeInfo,
87
};
98
use ide_db::{
109
base_db::SourceDatabase,
@@ -352,7 +351,7 @@ pub(super) fn definition(
352351
let offset = match var_def {
353352
hir::VariantDef::Struct(s) => {
354353
let layout = Adt::from(s).layout(db).ok()?;
355-
layout.fields.offset(id, &db.current_target_data_layout())
354+
layout.fields.offset(id)
356355
}
357356
_ => return None,
358357
};

‎crates/ide/src/hover/tests.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -537,7 +537,7 @@ struct Foo { fiel$0d_a: u8, field_b: i32, field_c: i16 }
537537
```
538538
539539
```rust
540-
field_a: u8 // size = 1, align = 1, offset = 6
540+
field_a: u8 // size = 1, align = 1, offset = 4
541541
```
542542
"#]],
543543
);

‎lib/la-arena/Cargo.toml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,6 @@ documentation = "https://docs.rs/la-arena"
88
categories = ["data-structures", "memory-management", "rust-patterns"]
99
edition = "2021"
1010
rust-version = "1.56"
11+
12+
[dependencies]
13+
rustc_index = { version = "0.0.20221125", package = "hkalbasi-rustc-ap-rustc_index", default-features = false }

‎lib/la-arena/src/lib.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,16 @@ impl<T> fmt::Debug for Idx<T> {
7777
}
7878
}
7979

80+
impl<T: 'static> rustc_index::vec::Idx for Idx<T> {
81+
fn new(idx: usize) -> Self {
82+
Idx::from_raw(RawIdx(idx as u32))
83+
}
84+
85+
fn index(self) -> usize {
86+
self.raw.0 as usize
87+
}
88+
}
89+
8090
impl<T> Idx<T> {
8191
/// Creates a new index from a [`RawIdx`].
8292
pub fn from_raw(raw: RawIdx) -> Self {

0 commit comments

Comments
 (0)
Please sign in to comment.