Skip to content

Commit

Permalink
Fix conversion to StaticDef and add test
Browse files Browse the repository at this point in the history
  • Loading branch information
celinval committed Dec 8, 2023
1 parent 4c9e842 commit 9cb6463
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
2 changes: 1 addition & 1 deletion compiler/stable_mir/src/compiler_interface.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ pub trait Context {
fn krate(&self, def_id: DefId) -> Crate;
fn instance_name(&self, def: InstanceDef, trimmed: bool) -> Symbol;

/// Return the number of bytes for a pointer size.
/// Return information about the target machine.
fn target_info(&self) -> MachineInfo;
}

Expand Down
2 changes: 1 addition & 1 deletion compiler/stable_mir/src/mir/mono.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ impl TryFrom<CrateItem> for StaticDef {
type Error = crate::Error;

fn try_from(value: CrateItem) -> Result<Self, Self::Error> {
if matches!(value.kind(), ItemKind::Static | ItemKind::Const) {
if matches!(value.kind(), ItemKind::Static) {
Ok(StaticDef(value.0))
} else {
Err(Error::new(format!("Expected a static item, but found: {value:?}")))
Expand Down
16 changes: 16 additions & 0 deletions tests/ui-fulldeps/stable-mir/check_allocation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ fn test_stable_mir(_tcx: TyCtxt<'_>) -> ControlFlow<()> {
let items = stable_mir::all_local_items();
check_foo(*get_item(&items, (ItemKind::Static, "FOO")).unwrap());
check_bar(*get_item(&items, (ItemKind::Static, "BAR")).unwrap());
check_len(*get_item(&items, (ItemKind::Static, "LEN")).unwrap());
ControlFlow::Continue(())
}

Expand Down Expand Up @@ -76,6 +77,19 @@ fn check_bar(item: CrateItem) {
assert_eq!(allocation.bytes[0].unwrap(), Char::CapitalB.to_u8());
assert_eq!(allocation.bytes[1].unwrap(), Char::SmallA.to_u8());
assert_eq!(allocation.bytes[2].unwrap(), Char::SmallR.to_u8());
assert_eq!(std::str::from_utf8(&allocation.raw_bytes().unwrap()), Ok("Bar"));
}

/// Check the allocation data for `LEN`.
///
/// ```no_run
/// static LEN: usize = 2;
/// ```
fn check_len(item: CrateItem) {
let def = StaticDef::try_from(item).unwrap();
let alloc = def.eval_initializer().unwrap();
assert!(alloc.provenance.ptrs.is_empty());
assert_eq!(alloc.read_uint(), Ok(2));
}

// Use internal API to find a function in a crate.
Expand Down Expand Up @@ -109,11 +123,13 @@ fn generate_input(path: &str) -> std::io::Result<()> {
write!(
file,
r#"
static LEN: usize = 2;
static FOO: [&str; 2] = ["hi", "there"];
static BAR: &str = "Bar";
pub fn main() {{
println!("{{FOO:?}}! {{BAR}}");
assert_eq!(FOO.len(), LEN);
}}"#
)?;
Ok(())
Expand Down

0 comments on commit 9cb6463

Please sign in to comment.