core/asm: Fix PC calculations when a label is pushed

Incrementing PC by 5 is only correct if the label appears after a jump,
in which case there is an implicit push. When it appears after an explicit
push, PC should only be incremented by 4.
This commit is contained in:
Michael Forney 2019-10-26 14:51:06 -07:00
parent 422067abb8
commit 7c353009d5
2 changed files with 13 additions and 1 deletions

View file

@ -57,6 +57,7 @@ func NewCompiler(debug bool) *Compiler {
// second stage to push labels and determine the right // second stage to push labels and determine the right
// position. // position.
func (c *Compiler) Feed(ch <-chan token) { func (c *Compiler) Feed(ch <-chan token) {
var prev token
for i := range ch { for i := range ch {
switch i.typ { switch i.typ {
case number: case number:
@ -73,10 +74,14 @@ func (c *Compiler) Feed(ch <-chan token) {
c.labels[i.text] = c.pc c.labels[i.text] = c.pc
c.pc++ c.pc++
case label: case label:
c.pc += 5 c.pc += 4
if prev.typ == element && isJump(prev.text) {
c.pc++
}
} }
c.tokens = append(c.tokens, i) c.tokens = append(c.tokens, i)
prev = i
} }
if c.debug { if c.debug {
fmt.Fprintln(os.Stderr, "found", len(c.labels), "labels") fmt.Fprintln(os.Stderr, "found", len(c.labels), "labels")

View file

@ -32,6 +32,13 @@ func TestCompiler(t *testing.T) {
`, `,
output: "5a5b6300000001", output: "5a5b6300000001",
}, },
{
input: `
PUSH @label
label:
`,
output: "63000000055b",
},
} }
for _, test := range tests { for _, test := range tests {
ch := Lex([]byte(test.input), false) ch := Lex([]byte(test.input), false)