Fixed the for loop bug and scoping issues

This commit is contained in:
nocturn9x 2020-07-31 11:28:46 +02:00
parent a5106cc5e9
commit 0c05b24c3d
8 changed files with 38 additions and 32 deletions

View File

@ -136,7 +136,6 @@ class While(Statement):
body: Statement
def accept(self, visitor):
print("porcodio")
visitor.visit_while(self)

View File

@ -105,7 +105,7 @@ class Resolver(object):
def visit_var_expr(self, expr):
"""Visits a var expression node"""
if self.scopes and self.scopes[-1].get(expr.name.lexeme) == False:
if self.scopes and self.scopes[-1].get(expr.name.lexeme) is False:
raise JAPLError(expr.name, f"Cannot read local variable in its own initializer")
self.resolve_local(expr, expr.name)
@ -114,7 +114,7 @@ class Resolver(object):
i = 0
for scope in reversed(self.scopes):
if name.lexeme in self.scopes:
if name.lexeme in scope:
self.interpreter.resolve(expr, i)
i += 1

View File

@ -32,7 +32,7 @@ class JAPL(object):
print(f"Error' '{file}', permission denied")
except JAPLError as err:
if len(err.args) == 2:
message, token = err.args
token, message = err.args
print(f"An exception occurred at line {token.line}, file '{file}' at '{token.lexeme}': {message}")
else:
print(f"An exception occurred, details below\n\n{err}")

View File

@ -20,7 +20,7 @@ Even though that books treats the implementation of a basic language named Lox,
- A decent standard library (__Work in progress__)
Other than that, JAPL features closures, function definitions, classes and static scoping. You can check
the provided example `.jpl` files in this repo to find out more about JAPL.
the provided example `.jpl` files in the repo to find out more about JAPL.
### Disclaimer

View File

@ -1,13 +0,0 @@
fun makeCounter() {
var i = 0;
fun count() {
i = i + 1;
print i;
}
return count;
}
var counter = makeCounter();
counter(); // "1".
counter(); // "2".

View File

@ -1,10 +0,0 @@
var a = "global";
{
fun showA() {
print a;
}
showA();
var a = "block";
showA();
}

View File

@ -39,6 +39,11 @@ while (n <= 10) { // While loops
n = n + 1;
}
for (var i = 0; i < 10; i = i + 1) { // For loops
print i;
}
// Functions
print clock(); // Function calls
@ -49,3 +54,32 @@ fun count(n) { // Function definitions
}
count(3);
// Closures work too!
var a = "global";
{
fun showA() {
print a;
}
showA();
var a = "block";
showA();
}
// Nested functions
fun makeCounter() {
var i = 0;
fun count() {
i = i + 1;
print i;
}
return count;
}
var counter = makeCounter();
counter(); // "1".
counter(); // "2".

View File

@ -1,4 +0,0 @@
for (var i = 0; i < 10; i = i + 1) { // For loops
print i;
}