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

Type entity #57

Closed
wants to merge 1 commit into from
Closed
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
65 changes: 64 additions & 1 deletion crates/ir/src/types.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! This module contains Sonatina IR types definitions.
use std::{cmp, fmt};

use cranelift_entity::PrimaryMap;
use cranelift_entity::{EntityRef, PrimaryMap};
use indexmap::IndexMap;
use rustc_hash::FxHashMap;

Expand Down Expand Up @@ -135,6 +135,46 @@ pub enum Type {
Void,
}

impl EntityRef for Type {
fn new(i: usize) -> Self {
if i == 0 {
Type::Void
} else if i == 1 {
Type::I1
} else if i == 8 {
Type::I8
} else if i == 16 {
Type::I16
} else if i == 32 {
Type::I32
} else if i == 64 {
Type::I64
} else if i == 128 {
Type::I128
} else if i == 256 {
Type::I256
} else if i > 256 {
Type::Compound(CompoundType::new(i - 256))
} else {
unreachable!()
}
}

fn index(self) -> usize {
match self {
Type::Void => 0,
Type::I1 => 1,
Type::I8 => 8,
Type::I16 => 16,
Type::I32 => 32,
Type::I64 => 64,
Type::I128 => 128,
Type::I256 => 256,
Type::Compound(cmpd_ty) => 256 + cmpd_ty.index(),
}
}
}

/// An opaque reference to [`CompoundTypeData`].
#[derive(Debug, Clone, PartialEq, Eq, Copy, Hash, PartialOrd, Ord)]
pub struct CompoundType(u32);
Expand Down Expand Up @@ -267,3 +307,26 @@ impl cmp::PartialOrd for Type {
}
}
}

#[cfg(test)]
mod tests {
use cranelift_entity::SecondaryMap;

use super::*;

#[test]
fn type_as_entity() {
let mut map = SecondaryMap::new();
assert_eq!(map.capacity(), 0);

map[Type::I1] = 1;
map[Type::I32] = 32;

let cmpd_ty = CompoundType(1);
map[Type::Compound(cmpd_ty)] = 257;

assert_eq!(map[Type::Void], 0);
assert_eq!(map[Type::I32], 32);
assert_eq!(map[Type::Compound(cmpd_ty)], 257);
}
}