Initial work on closures. Seems to be working

This commit is contained in:
Mattia Giambirtone 2022-07-10 14:50:08 +02:00
parent 6116c127c6
commit 13cc641e7b
1 changed files with 6 additions and 5 deletions

View File

@ -379,13 +379,13 @@ proc getStackPos(self: Compiler, name: IdentExpr, depth: int = self.scopeDepth):
var found = false var found = false
result = 2 result = 2
for variable in self.names: for variable in self.names:
if variable.valueType.kind == Function: if variable.isFunDecl:
continue continue
inc(result) inc(result)
if name.name.lexeme == variable.name.name.lexeme: if name.name.lexeme == variable.name.name.lexeme:
if variable.isPrivate and variable.owner != self.currentModule: if variable.isPrivate and variable.owner != self.currentModule:
continue continue
elif variable.depth == depth: else:
found = true found = true
dec(result) dec(result)
break break
@ -1223,7 +1223,7 @@ proc endScope(self: Compiler) =
dec(self.scopeDepth) dec(self.scopeDepth)
var names: seq[Name] = @[] var names: seq[Name] = @[]
for name in self.names: for name in self.names:
if name.depth > self.scopeDepth and name.valueType.kind notin {Generic, CustomType, Function}: if name.depth > self.scopeDepth and name.valueType.kind notin {Generic, CustomType} and not name.isFunDecl:
names.add(name) names.add(name)
if len(names) > 1: if len(names) > 1:
# If we're popping less than 65535 variables, then # If we're popping less than 65535 variables, then
@ -1435,7 +1435,7 @@ proc endFunctionBeforeReturn(self: Compiler) =
## its return instruction ## its return instruction
var popped = 0 var popped = 0
for name in self.names: for name in self.names:
if name.depth == self.scopeDepth and name.valueType.kind notin {Function, Generic, CustomType}: if name.depth == self.scopeDepth and name.valueType.kind notin {Generic, CustomType} and not name.isFunDecl:
inc(popped) inc(popped)
if popped > 1: if popped > 1:
self.emitByte(PopN) self.emitByte(PopN)
@ -1849,6 +1849,7 @@ proc compile*(self: Compiler, ast: seq[Declaration], file: string): Chunk =
args: @[]), args: @[]),
codePos: 13, # Jump address is hardcoded codePos: 13, # Jump address is hardcoded
name: newIdentExpr(Token(lexeme: "", kind: Identifier)), name: newIdentExpr(Token(lexeme: "", kind: Identifier)),
isFunDecl: true,
line: -1) line: -1)
self.names.add(main) self.names.add(main)
self.emitByte(LoadFunction) self.emitByte(LoadFunction)
@ -1860,7 +1861,7 @@ proc compile*(self: Compiler, ast: seq[Declaration], file: string): Chunk =
self.emitBytes(0.toTriple()) self.emitBytes(0.toTriple())
while not self.done(): while not self.done():
self.declaration(Declaration(self.step())) self.declaration(Declaration(self.step()))
self.endFunctionBeforeReturn() self.endScope()
self.patchReturnAddress(pos) self.patchReturnAddress(pos)
self.emitByte(OpCode.Return) self.emitByte(OpCode.Return)
self.emitByte(0) # Entry point has no return value self.emitByte(0) # Entry point has no return value