Skip to content

Commit

Permalink
Add SETX instruction.
Browse files Browse the repository at this point in the history
  • Loading branch information
aleury committed Jan 15, 2024
1 parent 9d2dda7 commit d7485a4
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 2 deletions.
2 changes: 1 addition & 1 deletion examples/factorial.g
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
; Tasks:
; 1. Implement MULA
; 1. Implement MULA - done
; 2. Implement SETX
; 3. Implement DECX (and DECA, DECY)
; 4. Implement JXNZ
Expand Down
6 changes: 5 additions & 1 deletion gmachine.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ const (
OpMULA
OpMOVA
OpSETA
OpSETX
OpPSHA
OpPOPA
OpJUMP
Expand Down Expand Up @@ -68,6 +69,7 @@ var opcodes = map[string]Word{
"MULA": OpMULA,
"MOVA": OpMOVA,
"SETA": OpSETA,
"SETX": OpSETX,
"PSHA": OpPSHA,
"POPA": OpPOPA,
"JUMP": OpJUMP,
Expand Down Expand Up @@ -149,6 +151,8 @@ func (g *Machine) Run() {
}
case OpSETA:
g.A = g.Next()
case OpSETX:
g.X = g.Next()
case OpPSHA:
g.Memory[g.S] = g.A
g.S++
Expand Down Expand Up @@ -289,7 +293,7 @@ func assembleOpcodeStatement(stmt *ast.OpcodeStatement, program []Word, refs []R
refs = append(refs, ref)
program = append(program, Word(0))
case *ast.IntegerLiteral:
if !slices.Contains([]Word{OpSETA, OpJUMP}, opcode) {
if !slices.Contains([]Word{OpSETA, OpSETX, OpJUMP}, opcode) {
return nil, nil, fmt.Errorf("%w: %s at line %d", ErrInvalidOperand, stmt.TokenLiteral(), stmt.Token.Line)
}
program = append(program, Word(operand.Value))
Expand Down
13 changes: 13 additions & 0 deletions gmachine_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,19 @@ func TestSETA(t *testing.T) {
}
}

func TestSETX(t *testing.T) {
t.Parallel()
g := gmachine.New(nil)
var wantX gmachine.Word = 5
err := assembleAndRunFromString(g, "SETX 5")
if err != nil {
t.Fatal("didn't expect an error", err)
}
if wantX != g.X {
t.Errorf("want X value %d, got %d", wantX, g.X)
}
}

func TestAssemble(t *testing.T) {
t.Parallel()
want := []gmachine.Word{gmachine.OpINCA, gmachine.OpHALT}
Expand Down
1 change: 1 addition & 0 deletions token/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ var opcodes = map[string]TokenType{
"MULA": OPCODE,
"MOVA": OPCODE,
"SETA": OPCODE,
"SETX": OPCODE,
"PSHA": OPCODE,
"POPA": OPCODE,
"JUMP": OPCODE,
Expand Down

0 comments on commit d7485a4

Please sign in to comment.