-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor(register): reorganize stuff
- Loading branch information
1 parent
d1aa332
commit 3319292
Showing
3 changed files
with
123 additions
and
84 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,5 @@ | ||
mod codegen; | ||
mod register; | ||
|
||
pub use codegen::CodeGen; | ||
pub use register::{Register, RegisterAllocator}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
#[derive(Clone, PartialEq)] | ||
pub struct Register { | ||
byte: &'static str, | ||
dword: &'static str, | ||
} | ||
|
||
impl Register { | ||
pub fn new(byte: &'static str, dword: &'static str) -> Self { | ||
return Self { byte, dword }; | ||
} | ||
|
||
pub fn byte(&self) -> &'static str { | ||
self.byte | ||
} | ||
|
||
pub fn dword(&self) -> &'static str { | ||
self.dword | ||
} | ||
} | ||
|
||
#[derive(Debug)] | ||
pub enum AllocatorError { | ||
DoubleFree, | ||
RanOutOfRegisters, | ||
} | ||
|
||
pub struct RegisterAllocator { | ||
registers: Vec<Register>, | ||
used: Vec<u8>, | ||
} | ||
|
||
impl RegisterAllocator { | ||
pub fn new(registers: Vec<Register>) -> Self { | ||
return Self { | ||
used: Vec::with_capacity(registers.len()), | ||
registers, | ||
}; | ||
} | ||
|
||
pub fn alloc(&mut self) -> Result<Register, AllocatorError> { | ||
for (i, reg) in self.registers.iter().enumerate() { | ||
if !self.used.contains(&i.try_into().unwrap()) { | ||
self.used.push(i.try_into().unwrap()); | ||
|
||
return Ok(reg.clone()); | ||
} | ||
} | ||
|
||
Err(AllocatorError::RanOutOfRegisters) | ||
} | ||
|
||
pub fn free(&mut self, r: Register) -> Result<(), AllocatorError> { | ||
for (i, register) in self.registers.iter().enumerate() { | ||
if r == *register { | ||
if self.used.contains(&i.try_into().unwrap()) { | ||
self.used.remove(i); | ||
|
||
return Ok(()); | ||
} else { | ||
return Err(AllocatorError::DoubleFree); | ||
} | ||
} | ||
} | ||
|
||
Ok(()) | ||
} | ||
} |