Skip to content
This repository was archived by the owner on Oct 3, 2021. It is now read-only.

Commit 39d1b51

Browse files
authored
Merge pull request #2 from looplanguage/feat_return
feat: early return
2 parents 8cdcfd2 + e476a50 commit 39d1b51

1 file changed

Lines changed: 22 additions & 1 deletion

File tree

compiler/compile.go

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ import (
88
"sort"
99
)
1010

11+
var jumpReturns []*int
12+
1113
func (c *Compiler) Compile(node ast.Node) error {
1214
switch node := node.(type) {
1315
case *ast.Program:
@@ -99,7 +101,8 @@ func (c *Compiler) Compile(node ast.Node) error {
99101
}
100102

101103
c.emit(code.OpJump, startPos)
102-
c.changeOperand(jumpPos, len(c.currentInstructions()))
104+
afterPos := len(c.currentInstructions())
105+
c.changeOperand(jumpPos, afterPos)
103106
case *ast.ConditionalStatement:
104107
err := c.Compile(node.Condition)
105108
if err != nil {
@@ -151,6 +154,15 @@ func (c *Compiler) Compile(node ast.Node) error {
151154
}
152155
}
153156
c.currentScope = c.currentScope.Outer
157+
158+
if c.currentScope.Outer == nil {
159+
skipTo := len(c.currentInstructions())
160+
for _, jumpReturn := range jumpReturns {
161+
c.changeOperand(*jumpReturn, skipTo)
162+
}
163+
164+
jumpReturns = []*int{}
165+
}
154166
case *ast.VariableDeclaration:
155167
index := c.variables
156168

@@ -273,12 +285,21 @@ func (c *Compiler) Compile(node ast.Node) error {
273285

274286
c.emit(code.OpClosure, c.addConstant(compiledFunc), len(freeSymbols))
275287
case *ast.Return:
288+
if c.currentScope.Outer == nil {
289+
return fmt.Errorf("cannot have return statement in root scope")
290+
}
291+
276292
err := c.Compile(node.Value)
277293
if err != nil {
278294
return err
279295
}
280296

281297
c.emit(code.OpReturnValue)
298+
299+
if c.scopeIndex == 0 {
300+
val := c.emit(code.OpJump, 9999)
301+
jumpReturns = append(jumpReturns, &val)
302+
}
282303
case *ast.CallExpression:
283304
err := c.Compile(node.Function)
284305
if err != nil {

0 commit comments

Comments
 (0)