From ac0e27197fa304b928c2e9d331b467c5fe5176f9 Mon Sep 17 00:00:00 2001 From: Adam Eury Date: Sun, 21 Jan 2024 00:05:10 -0500 Subject: [PATCH] Terminate variables with string literals with a zero. --- examples/print.g | 12 +++++++----- gmachine.go | 2 +- gmachine_test.go | 12 +++++++++--- 3 files changed, 17 insertions(+), 9 deletions(-) diff --git a/examples/print.g b/examples/print.g index 89a2345..6484d18 100644 --- a/examples/print.g +++ b/examples/print.g @@ -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 diff --git a/gmachine.go b/gmachine.go index abcfca9..fd3978f 100644 --- a/gmachine.go +++ b/gmachine.go @@ -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) } diff --git a/gmachine_test.go b/gmachine_test.go index f231c70..8b53c3d 100644 --- a/gmachine_test.go +++ b/gmachine_test.go @@ -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)) }