Skip to content

feat: Add layout info for enum variant and locals #14845

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

Merged
merged 1 commit into from
May 18, 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 36 additions & 14 deletions crates/hir/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ use hir_def::{
hir::{BindingAnnotation, BindingId, ExprOrPatId, LabelId, Pat},
item_tree::ItemTreeNode,
lang_item::LangItemTarget,
layout::ReprOptions,
layout::{self, ReprOptions},
macro_id_to_def_id,
nameres::{self, diagnostics::DefDiagnostic, ModuleOrigin},
per_ns::PerNs,
Expand All @@ -62,7 +62,7 @@ use hir_ty::{
consteval::{try_const_usize, unknown_const_as_generic, ConstEvalError, ConstExt},
diagnostics::BodyValidationDiagnostic,
display::HexifiedConst,
layout::{layout_of_ty, Layout, LayoutError},
layout::{layout_of_ty, Layout, LayoutError, RustcEnumVariantIdx, TagEncoding},
method_resolution::{self, TyFingerprint},
mir::{self, interpret_mir},
primitive::UintTy,
Expand Down Expand Up @@ -1089,28 +1089,28 @@ impl Enum {
Type::new_for_crate(
self.id.lookup(db.upcast()).container.krate(),
TyBuilder::builtin(match db.enum_data(self.id).variant_body_type() {
hir_def::layout::IntegerType::Pointer(sign) => match sign {
layout::IntegerType::Pointer(sign) => match sign {
true => hir_def::builtin_type::BuiltinType::Int(
hir_def::builtin_type::BuiltinInt::Isize,
),
false => hir_def::builtin_type::BuiltinType::Uint(
hir_def::builtin_type::BuiltinUint::Usize,
),
},
hir_def::layout::IntegerType::Fixed(i, sign) => match sign {
layout::IntegerType::Fixed(i, sign) => match sign {
true => hir_def::builtin_type::BuiltinType::Int(match i {
hir_def::layout::Integer::I8 => hir_def::builtin_type::BuiltinInt::I8,
hir_def::layout::Integer::I16 => hir_def::builtin_type::BuiltinInt::I16,
hir_def::layout::Integer::I32 => hir_def::builtin_type::BuiltinInt::I32,
hir_def::layout::Integer::I64 => hir_def::builtin_type::BuiltinInt::I64,
hir_def::layout::Integer::I128 => hir_def::builtin_type::BuiltinInt::I128,
layout::Integer::I8 => hir_def::builtin_type::BuiltinInt::I8,
layout::Integer::I16 => hir_def::builtin_type::BuiltinInt::I16,
layout::Integer::I32 => hir_def::builtin_type::BuiltinInt::I32,
layout::Integer::I64 => hir_def::builtin_type::BuiltinInt::I64,
layout::Integer::I128 => hir_def::builtin_type::BuiltinInt::I128,
}),
false => hir_def::builtin_type::BuiltinType::Uint(match i {
hir_def::layout::Integer::I8 => hir_def::builtin_type::BuiltinUint::U8,
hir_def::layout::Integer::I16 => hir_def::builtin_type::BuiltinUint::U16,
hir_def::layout::Integer::I32 => hir_def::builtin_type::BuiltinUint::U32,
hir_def::layout::Integer::I64 => hir_def::builtin_type::BuiltinUint::U64,
hir_def::layout::Integer::I128 => hir_def::builtin_type::BuiltinUint::U128,
layout::Integer::I8 => hir_def::builtin_type::BuiltinUint::U8,
layout::Integer::I16 => hir_def::builtin_type::BuiltinUint::U16,
layout::Integer::I32 => hir_def::builtin_type::BuiltinUint::U32,
layout::Integer::I64 => hir_def::builtin_type::BuiltinUint::U64,
layout::Integer::I128 => hir_def::builtin_type::BuiltinUint::U128,
}),
},
}),
Expand Down Expand Up @@ -1177,6 +1177,28 @@ impl Variant {
pub fn eval(self, db: &dyn HirDatabase) -> Result<i128, ConstEvalError> {
db.const_eval_discriminant(self.into())
}

/// Return layout of the variant and tag size of the parent enum.
pub fn layout(&self, db: &dyn HirDatabase) -> Result<(Layout, usize), LayoutError> {
let parent_enum = self.parent_enum(db);
let parent_layout = Adt::from(parent_enum).layout(db)?;
if let layout::Variants::Multiple { variants, tag, tag_encoding, tag_field: _ } =
parent_layout.variants
{
let tag_size = match tag_encoding {
TagEncoding::Direct => {
let target_data_layout = db
.target_data_layout(parent_enum.module(db).krate().id)
.ok_or(LayoutError::TargetLayoutNotAvailable)?;
tag.size(&*target_data_layout).bytes_usize()
}
TagEncoding::Niche { .. } => 0,
};
Ok((variants[RustcEnumVariantIdx(self.id)].clone(), tag_size))
} else {
Ok((parent_layout, 0))
}
}
}

/// Variants inherit visibility from the parent enum.
Expand Down
58 changes: 52 additions & 6 deletions crates/ide/src/hover/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -417,15 +417,25 @@ pub(super) fn definition(
let layout = it.layout(db).ok()?;
Some(format!("size = {}, align = {}", layout.size.bytes(), layout.align.abi.bytes()))
}),
Definition::Variant(it) => label_value_and_docs(db, it, |&it| {
if !it.parent_enum(db).is_data_carrying(db) {
Definition::Variant(it) => label_value_and_layout_info_and_docs(db, it, config, |&it| {
let layout = (|| {
let (layout, tag_size) = it.layout(db).ok()?;
let size = layout.size.bytes_usize() - tag_size;
if size == 0 {
// There is no value in showing layout info for fieldless variants
return None;
}
Some(format!("size = {}", layout.size.bytes()))
})();
let value = if !it.parent_enum(db).is_data_carrying(db) {
match it.eval(db) {
Ok(x) => Some(if x >= 10 { format!("{x} ({x:#X})") } else { format!("{x}") }),
Err(_) => it.value(db).map(|x| format!("{x:?}")),
}
} else {
None
}
};
(value, layout)
}),
Definition::Const(it) => label_value_and_docs(db, it, |it| {
let body = it.render_eval(db);
Expand Down Expand Up @@ -460,7 +470,7 @@ pub(super) fn definition(
.and_then(|fd| builtin(fd, it))
.or_else(|| Some(Markup::fenced_block(&it.name())))
}
Definition::Local(it) => return local(db, it),
Definition::Local(it) => return local(db, it, config),
Definition::SelfType(impl_def) => {
impl_def.self_ty(db).as_adt().map(|adt| label_and_docs(db, adt))?
}
Expand Down Expand Up @@ -637,6 +647,32 @@ where
(label, docs)
}

fn label_value_and_layout_info_and_docs<D, E, V, L>(
db: &RootDatabase,
def: D,
config: &HoverConfig,
value_extractor: E,
) -> (String, Option<hir::Documentation>)
where
D: HasAttrs + HirDisplay,
E: Fn(&D) -> (Option<V>, Option<L>),
V: Display,
L: Display,
{
let (value, layout) = value_extractor(&def);
let label = if let Some(value) = value {
format!("{} = {value}", def.display(db))
} else {
def.display(db).to_string()
};
let label = match layout {
Some(layout) if config.memory_layout => format!("{} // {layout}", label),
_ => label,
};
let docs = def.attrs(db).docs();
(label, docs)
}

fn label_value_and_docs<D, E, V>(
db: &RootDatabase,
def: D,
Expand Down Expand Up @@ -696,11 +732,11 @@ fn find_std_module(famous_defs: &FamousDefs<'_, '_>, name: &str) -> Option<hir::
.find(|module| module.name(db).map_or(false, |module| module.to_string() == name))
}

fn local(db: &RootDatabase, it: hir::Local) -> Option<Markup> {
fn local(db: &RootDatabase, it: hir::Local, config: &HoverConfig) -> Option<Markup> {
let ty = it.ty(db);
let ty = ty.display_truncated(db, None);
let is_mut = if it.is_mut(db) { "mut " } else { "" };
let desc = match it.primary_source(db).into_ident_pat() {
let mut desc = match it.primary_source(db).into_ident_pat() {
Some(ident) => {
let name = it.name(db);
let let_kw = if ident
Expand All @@ -716,6 +752,16 @@ fn local(db: &RootDatabase, it: hir::Local) -> Option<Markup> {
}
None => format!("{is_mut}self: {ty}"),
};
if config.memory_layout {
if let Ok(layout) = it.ty(db).layout(db) {
format_to!(
desc,
" // size = {}, align = {}",
layout.size.bytes(),
layout.align.abi.bytes()
);
}
}
markup(None, desc, None)
}

Expand Down
Loading