Skip to content

Commit

Permalink
Terminate variables with string literals with a zero.
Browse files Browse the repository at this point in the history
  • Loading branch information
aleury committed Jan 21, 2024
1 parent 5262115 commit ac0e271
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 9 deletions.
12 changes: 7 additions & 5 deletions examples/print.g
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
JUMP run
VARB msg "hello world"

.run
SETX msg ; set X register to the address of msg
SETX msg ; set X register to the address of msg
JUMP print

.print
MOVE *X -> A ; move the value of address in X to A
OUTA ; print A
INCX ; increment address stored in X
JANZ print ; jump to label 'done' if A = 0
MOVE *X -> A ; move the value at address in X to A
OUTA ; print A
INCX ; increment address stored in X
JANZ print ; jump to label 'done' if A = 0
HALT

2 changes: 1 addition & 1 deletion gmachine.go
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,7 @@ func Assemble(reader io.Reader) ([]Word, error) {
case ast.IntegerLiteral:
program = append(program, Word(operand.Value))
case ast.StringLiteral:
strSlice := make([]Word, len(operand.Value))
strSlice := make([]Word, len(operand.Value)+1)
for i, c := range operand.Value {
strSlice[i] = Word(c)
}
Expand Down
12 changes: 9 additions & 3 deletions gmachine_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -914,12 +914,18 @@ HALT
func TestVARB_DeclaresAStringVariableInMemory(t *testing.T) {
t.Parallel()
g := gmachine.New(nil)
err := assembleAndRunFromString(g, `VARB msg "hello world"`)
err := assembleAndRunFromString(g, `
JUMP start
VARB msg "hello world"
.start
HALT
`)
if err != nil {
t.Fatal("didn't expect an error:", err)
}
want := []gmachine.Word{'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'}
got := g.Memory[int(g.MemOffset) : int(g.MemOffset)+len(want)]
want := []gmachine.Word{'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', 0}
offsetStart := int(g.MemOffset) + 2
got := g.Memory[offsetStart : offsetStart+len(want)]
if !cmp.Equal(want, got) {
t.Error(cmp.Diff(want, got))
}
Expand Down

0 comments on commit ac0e271

Please sign in to comment.