Skip to content

Commit

Permalink
allow local function definitions
Browse files Browse the repository at this point in the history
  • Loading branch information
musiKk committed Mar 12, 2024
1 parent 4300cd2 commit 944ee22
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 7 deletions.
22 changes: 15 additions & 7 deletions src/main/java/com/github/musiKk/Runner.java
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,9 @@ private Value execute(Statement expression, StackFrame frame) {
processTraitImplementation(ti, frame.scope);
yield null;
}
case FunctionDeclaration functionDeclaration -> {
yield registerFunction(functionDeclaration, frame.scope(), "");
}
default -> throw new RuntimeException("not yet implemented " + expression);
};
}
Expand Down Expand Up @@ -383,13 +386,7 @@ private RuntimeFile initRuntimeFile(String moduleName, Path path, StackFrame fra
processDataDefinition(dataDefinition, frame.scope);
});
processingResult.functionDeclarations().forEach((__, functionDeclaration) -> {
var functionName = functionDeclaration.signature().name();
var lookupName = switch (functionDeclaration.signature().receiver()) {
case FunctionReceiverVariable(String name) -> name + "." + functionName;
default -> functionName;
};
var function = Function.of(moduleName, functionDeclaration, runtimeFile.scope());
frame.putVariable(lookupName, new Variable(new FunctionType(functionName), function));
registerFunction(functionDeclaration, frame.scope, moduleName);
});
processingResult.variableDeclarations().forEach((name, variableDeclaration) -> {
execute(variableDeclaration, frame);
Expand Down Expand Up @@ -427,6 +424,17 @@ CompilationUnitProcessingResult addVariableDeclaration(VariableDeclaration varia
}
}

static Function registerFunction(FunctionDeclaration functionDeclaration, Scope scope, String moduleName) {
var functionName = functionDeclaration.signature().name();
var lookupName = switch (functionDeclaration.signature().receiver()) {
case FunctionReceiverVariable(String name) -> name + "." + functionName;
default -> functionName;
};
var function = Function.of(moduleName, functionDeclaration, scope);
scope.putVariable(lookupName, new Variable(new FunctionType(functionName), function));
return function;
}

static void processDataDefinition(DataDefinition dataDefinition, Scope scope) {
scope.putVariable(
dataDefinition.name(),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import io

def main() = {
var g1 = generator()
var g2 = generator()
print("g1: " + g1())
print("g1: " + g1())
print("g2: " + g2())
print("g1: " + g1())
print("g1: " + g1())
print("g2: " + g2())
print("g2: " + g2())
}

def generator() = {
var x = 0
def next() = {
var ret = x
x = x + 1
ret
}
}

// EXPECTED-OUTPUT
// g1: 0
// g1: 1
// g2: 0
// g1: 2
// g1: 3
// g2: 1
// g2: 2

0 comments on commit 944ee22

Please sign in to comment.