Skip to content

Commit 20b854e

Browse files
authored
Merge pull request #12 from rbartlensky/fix-instruction-encoding-decoding
Fix instruction encoding and decoding.
2 parents ecb86b7 + c34d8d8 commit 20b854e

File tree

2 files changed

+30
-7
lines changed

2 files changed

+30
-7
lines changed

luacompiler/build.rs

+5-2
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,14 @@ extern crate lrlex;
22
extern crate lrpar;
33

44
use lrlex::LexerBuilder;
5+
use lrpar::ActionKind;
56
use lrpar::CTParserBuilder;
67

78
fn main() -> Result<(), Box<std::error::Error>> {
8-
let lex_rule_ids_map =
9-
CTParserBuilder::<u8>::new_with_storaget().process_file_in_src("lua5_3/lua5_3.y")?;
9+
let mut ct = CTParserBuilder::<u8>::new_with_storaget()
10+
.error_on_conflicts(false)
11+
.action_kind(ActionKind::GenericParseTree);
12+
let lex_rule_ids_map = ct.process_file_in_src("lua5_3/lua5_3.y")?;
1013
LexerBuilder::new()
1114
.rule_ids_map(lex_rule_ids_map)
1215
.process_file_in_src("lua5_3/lua5_3.l")?;

luacompiler/src/lib/bytecode/instructions.rs

+25-5
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
const MASK: u32 = 0x000F;
1+
const MASK: u32 = 0x000000FF;
22

33
/// Get the opcode of an instruction
44
pub fn opcode(instr: u32) -> u8 {
@@ -7,22 +7,22 @@ pub fn opcode(instr: u32) -> u8 {
77

88
/// Get the first argument of an instruction.
99
pub fn first_arg(instr: u32) -> u8 {
10-
((instr >> 4) & MASK) as u8
10+
((instr >> 8) & MASK) as u8
1111
}
1212

1313
/// Get the second argument of an instruction.
1414
pub fn second_arg(instr: u32) -> u8 {
15-
((instr >> 8) & MASK) as u8
15+
((instr >> 16) & MASK) as u8
1616
}
1717

1818
/// Get the third argument of an instruction.
1919
pub fn third_arg(instr: u32) -> u8 {
20-
((instr >> 12) & MASK) as u8
20+
((instr >> 24) & MASK) as u8
2121
}
2222

2323
/// Create an instruction with the given opcode and arguments.
2424
pub fn make_instr(opcode: Opcode, arg1: u8, arg2: u8, arg3: u8) -> u32 {
25-
opcode as u32 + ((arg1 as u32) << 4) + ((arg2 as u32) << 8) + ((arg3 as u32) << 12)
25+
opcode as u32 + ((arg1 as u32) << 8) + ((arg2 as u32) << 16) + ((arg3 as u32) << 24)
2626
}
2727

2828
/// Represents a high level instruction whose operands have a size of usize.
@@ -58,3 +58,23 @@ pub enum Opcode {
5858
FDIV = 9, // R(1) = R(2) // R(3)
5959
EXP = 10, // R(1) = R(2) ^ R(3)
6060
}
61+
62+
#[cfg(test)]
63+
mod tests {
64+
use super::*;
65+
66+
#[test]
67+
fn encoding_and_decoding_works() {
68+
for i in 0..=255 {
69+
for j in 0..=255 {
70+
for k in 0..=255 {
71+
let instr = make_instr(Opcode::MOV, i, j, k);
72+
assert_eq!(opcode(instr), Opcode::MOV as u8);
73+
assert_eq!(first_arg(instr), i);
74+
assert_eq!(second_arg(instr), j);
75+
assert_eq!(third_arg(instr), k);
76+
}
77+
}
78+
}
79+
}
80+
}

0 commit comments

Comments
 (0)