From 403e78f655d2a75502a99f3ccc933abc8781b3c7 Mon Sep 17 00:00:00 2001 From: Eduard Urbach Date: Sun, 7 Jul 2024 14:07:34 +0200 Subject: [PATCH] Improved branch code generation --- examples/hello/hello.q | 2 +- src/build/ast/Parse.go | 14 +++++++------- src/build/core/CompileIf.go | 4 +++- 3 files changed, 11 insertions(+), 9 deletions(-) diff --git a/examples/hello/hello.q b/examples/hello/hello.q index 53d906b..f6e8e26 100644 --- a/examples/hello/hello.q +++ b/examples/hello/hello.q @@ -1,7 +1,7 @@ main() { x := f(1) + f(2) + f(3) - if x != 9 { + if x != f(8) { exit(42) } diff --git a/src/build/ast/Parse.go b/src/build/ast/Parse.go index 4f00224..aa4eeef 100644 --- a/src/build/ast/Parse.go +++ b/src/build/ast/Parse.go @@ -33,7 +33,7 @@ func toASTNode(tokens token.List) (Node, error) { return &Return{Value: value}, nil case keyword.Loop: - blockStart := tokens.IndexKind(token.BlockStart) + 1 + blockStart := tokens.IndexKind(token.BlockStart) blockEnd := tokens.LastIndexKind(token.BlockEnd) if blockStart == -1 { @@ -44,11 +44,11 @@ func toASTNode(tokens token.List) (Node, error) { return nil, errors.New(errors.MissingBlockEnd, nil, tokens[len(tokens)-1].End()) } - tree, err := Parse(tokens[blockStart:blockEnd]) - return &Loop{Body: tree}, err + body, err := Parse(tokens[blockStart+1 : blockEnd]) + return &Loop{Body: body}, err case keyword.If: - blockStart := tokens.IndexKind(token.BlockStart) + 1 + blockStart := tokens.IndexKind(token.BlockStart) blockEnd := tokens.LastIndexKind(token.BlockEnd) if blockStart == -1 { @@ -59,9 +59,9 @@ func toASTNode(tokens token.List) (Node, error) { return nil, errors.New(errors.MissingBlockEnd, nil, tokens[len(tokens)-1].End()) } - condition := expression.Parse(tokens[1:token.BlockStart]) - tree, err := Parse(tokens[blockStart:blockEnd]) - return &If{Condition: condition, Body: tree}, err + condition := expression.Parse(tokens[1:blockStart]) + body, err := Parse(tokens[blockStart+1 : blockEnd]) + return &If{Condition: condition, Body: body}, err default: return nil, errors.New(&errors.KeywordNotImplemented{Keyword: tokens[0].Text()}, nil, tokens[0].Position) diff --git a/src/build/core/CompileIf.go b/src/build/core/CompileIf.go index 2f058e3..a38c76f 100644 --- a/src/build/core/CompileIf.go +++ b/src/build/core/CompileIf.go @@ -10,13 +10,14 @@ import ( // CompileIf compiles a branch instruction. func (f *Function) CompileIf(branch *ast.If) error { condition := branch.Condition - tmpRight := f.cpu.Input[1] + tmpRight := f.cpu.MustFindFree(f.cpu.General) err := f.ExpressionToRegister(condition.Children[1], tmpRight) if err != nil { return err } + f.cpu.Use(tmpRight) tmpLeft := f.cpu.Input[0] err = f.ExpressionToRegister(condition.Children[0], tmpLeft) @@ -25,6 +26,7 @@ func (f *Function) CompileIf(branch *ast.If) error { } f.assembler.RegisterRegister(asm.COMPARE, tmpLeft, tmpRight) + f.cpu.Free(tmpRight) elseLabel := fmt.Sprintf("%s_if_%d_else", f.Name, f.count.branch) switch condition.Token.Text() {