diff --git a/src/ndspkg/compiler/scope.nim b/src/ndspkg/compiler/scope.nim index fa34c1a..4398a16 100644 --- a/src/ndspkg/compiler/scope.nim +++ b/src/ndspkg/compiler/scope.nim @@ -33,6 +33,14 @@ proc beginScope*(comp: Compiler, function: bool = false) = for label in scope.labels: comp.addLocal(&":{label}", delta = 0) +proc scopeRetIndex*(comp: Compiler): int = + let scope = comp.scopes[comp.scopes.high()] + when assertionsCompiler: + # this is an illegal operation for function scopes, as they work differently + if scope.function: + comp.error("Assertion failed, Internal error, scopeRetIndex calculation for a function scope.") + return scope.goalStackIndex + proc restore*(comp: Compiler, scope: Scope) = let delta = comp.stackIndex - scope.goalStackIndex comp.writePops(delta) diff --git a/src/ndspkg/compiler/statement.nim b/src/ndspkg/compiler/statement.nim index b2ab7c5..be16a6b 100644 --- a/src/ndspkg/compiler/statement.nim +++ b/src/ndspkg/compiler/statement.nim @@ -51,8 +51,13 @@ proc statement*(comp: Compiler) = comp.breakStatement() else: comp.expression() + if comp.current.tokenType == tkRightBrace: + # last expression in the block expression -> semicolon optional + comp.writeChunk(0, opSetLocal) + comp.writeChunk(0, comp.scopeRetIndex().toDU8()) + else: + comp.consume(tkSemicolon, "Semicolon expected after expression statement.") comp.writeChunk(-1, opPop) - comp.consume(tkSemicolon, "Semicolon expected after expression statement.") if comp.panicMode: comp.synchronize() \ No newline at end of file diff --git a/tests/closures.nds b/tests/closures.nds index 4728db3..41bf15c 100644 --- a/tests/closures.nds +++ b/tests/closures.nds @@ -1,27 +1,27 @@ // cascade -var f1 = funct() { @result +var f1 = funct() { var x = 1; var y = 5; - :result = funct() { @result + funct() { var z = 8; print (x); x = x + 1; - :result = funct() { @result + funct() { print (x); x = x + 1; - :result = funct() { @result + funct() { print (x); print (y); print (z); x = x + 1; - :result = funct() { + funct() { print (x); x = x + 1; - }; - }; - }; - }; + } + } + } + } }; f1()()()()(); //expect:1.0 @@ -33,13 +33,13 @@ f1()()()()(); // capturing closures in lists: -var f = funct() { @result +var f = funct() { var y = 5; var x = @[ funct() print (y), funct() y = y + 1 ]; - :result = x; + x }; var inst = f();