Skip to content

Commit

Permalink
assembler: parse negative values in Offset properly
Browse files Browse the repository at this point in the history
Fixes #186
  • Loading branch information
quasilyte committed Jan 24, 2024
1 parent 06dca18 commit 6b042a2
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 2 deletions.
5 changes: 4 additions & 1 deletion pkg/assembler/assembler.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@ var parser *participle.Parser[CasmProgram] = participle.MustBuild[CasmProgram](
// also required for:
// instr -> jmp rel <expr> and
// instr -> jmp rel <expr> if <val> != 0
participle.UseLookahead(7),
//
// an extra +1 (7->8) step is required for an optionally negative offset (see #186):
// jmp rel [fp + -111]; without lookahead=8, it won't be parsed sucessfully
participle.UseLookahead(8),
)

// Given a CASM program it returns its encoded bytecode
Expand Down
38 changes: 38 additions & 0 deletions pkg/assembler/assembler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,44 @@ import (
"github.com/stretchr/testify/assert"
)

func TestCondJumpNegativeImmediate(t *testing.T) {
// See #186
instrList := parseSingleInstructionToInstrList("jmp rel [ap+5] if [fp + -3] != 0;")

expected := Instruction{
OffDest: -3,
OffOp0: -1,
OffOp1: 5,
DstRegister: Fp,
Op0Register: Fp,
Op1Source: ApPlusOffOp1,
Res: Op1,
PcUpdate: PcUpdateJnz,
ApUpdate: SameAp,
Opcode: OpCodeNop,
}
assert.Equal(t, expected, instrList[0])
}

func TestJumpNegativeImmediate(t *testing.T) {
// See #186
instrList := parseSingleInstructionToInstrList("jmp rel [fp + -111];")

expected := Instruction{
OffDest: -1,
OffOp0: -1,
OffOp1: -111,
DstRegister: Fp,
Op0Register: Fp,
Op1Source: FpPlusOffOp1,
Res: Op1,
PcUpdate: PcUpdateJumpRel,
ApUpdate: SameAp,
Opcode: OpCodeNop,
}
assert.Equal(t, expected, instrList[0])
}

func TestAssertEqRegisterToInstrList(t *testing.T) {
instrList := parseSingleInstructionToInstrList("[ap] = [fp], ap++;")

Expand Down
2 changes: 1 addition & 1 deletion pkg/assembler/grammar.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ type DoubleDeref struct {

type Offset struct {
Sign string `@("+" | "-")`
Value *int `@Int`
Value *int `@("-"? Int)`
}

type MathOperation struct {
Expand Down

0 comments on commit 6b042a2

Please sign in to comment.