Implement Index<Inst/StackSlot> for Function.

When Function serves as a container for IL entities, use the Index trait to
translate a reference class to a Data object.

Works for:

- StackSlot -> StackSlotData
- Inst -> InstructionData
This commit is contained in:
Jakob Stoklund Olesen
2016-04-29 17:23:34 -07:00
parent e414ce6315
commit e026b36db4

View File

@@ -261,6 +261,15 @@ impl Display for Inst {
} }
} }
/// Allow immutable access to instructions via function indexing.
impl Index<Inst> for Function {
type Output = InstructionData;
fn index<'a>(&'a self, inst: Inst) -> &'a InstructionData {
&self.instructions[inst.index()]
}
}
// ====--------------------------------------------------------------------------------------====// // ====--------------------------------------------------------------------------------------====//
// //
// Value implementation. // Value implementation.
@@ -402,11 +411,6 @@ impl Function {
} }
} }
/// Resolve an instruction reference.
pub fn inst(&self, i: Inst) -> &InstructionData {
&self.instructions[i.0 as usize]
}
/// Create a new instruction. /// Create a new instruction.
pub fn make_inst(&mut self, data: InstructionData) -> Inst { pub fn make_inst(&mut self, data: InstructionData) -> Inst {
let iref = Inst::new(self.instructions.len()); let iref = Inst::new(self.instructions.len());
@@ -427,7 +431,7 @@ impl Function {
use self::ExpandedValue::*; use self::ExpandedValue::*;
use self::ValueData::*; use self::ValueData::*;
match v.expand() { match v.expand() {
Direct(i) => self.inst(i).first_type(), Direct(i) => self[i].first_type(),
Table(i) => { Table(i) => {
match self.extended_values[i] { match self.extended_values[i] {
Unused => panic!("Can't get type of Unused value {}", v), Unused => panic!("Can't get type of Unused value {}", v),
@@ -457,7 +461,7 @@ mod tests {
assert_eq!(inst.to_string(), "inst0"); assert_eq!(inst.to_string(), "inst0");
// Immutable reference resolution. // Immutable reference resolution.
let ins = func.inst(inst); let ins = &func[inst];
assert_eq!(ins.opcode(), Opcode::Iconst); assert_eq!(ins.opcode(), Opcode::Iconst);
assert_eq!(ins.first_type(), types::I32); assert_eq!(ins.first_type(), types::I32);
} }