Fixed some issues in scope

This commit is contained in:
2022-08-15 10:15:24 +01:00
parent 6b834ca6d1
commit 7e01ead6ff
3 changed files with 16 additions and 6 deletions

View File

@@ -2,3 +2,4 @@
var dict : [string, int] = ["hello" : 1, "world" : 2];

View File

@@ -304,7 +304,7 @@ static bool execVarDecl(Interpreter* interpreter, bool lng) {
Literal type = interpreter->literalCache.literals[typeIndex]; Literal type = interpreter->literalCache.literals[typeIndex];
if (!declareScopeVariable(interpreter->scope, identifier, type)) { if (!declareScopeVariable(interpreter->scope, identifier, type)) {
printf("Can't redefine the variable \"");; printf("Can't redefine the variable \"");
printLiteral(identifier); printLiteral(identifier);
printf("\"\n"); printf("\"\n");
return false; return false;
@@ -325,14 +325,14 @@ static bool execVarAssign(Interpreter* interpreter) {
Literal lhs = popLiteralArray(&interpreter->stack); Literal lhs = popLiteralArray(&interpreter->stack);
if (!IS_IDENTIFIER(lhs)) { if (!IS_IDENTIFIER(lhs)) {
printf("Can't assign to a non-variable \"");; printf("Can't assign to a non-variable \"");
printLiteral(lhs); printLiteral(lhs);
printf("\"\n"); printf("\"\n");
return false; return false;
} }
if (!isDelcaredScopeVariable(interpreter->scope, lhs)) { if (!isDelcaredScopeVariable(interpreter->scope, lhs)) {
printf("Undeclared variable \"");; printf("Undeclared variable \"");
printLiteral(lhs); printLiteral(lhs);
printf("\"\n"); printf("\"\n");
return false; return false;

View File

@@ -59,11 +59,11 @@ static bool checkType(Literal typeLiteral, Literal value) {
for (int i = 0; i < AS_DICTIONARY(value)->capacity; i++) { for (int i = 0; i < AS_DICTIONARY(value)->capacity; i++) {
//only assigned and non-tombstoned keys //only assigned and non-tombstoned keys
if (!IS_NULL(AS_DICTIONARY(value)->entries[i].key)) { if (!IS_NULL(AS_DICTIONARY(value)->entries[i].key)) {
if (checkType(((Literal*)(AS_TYPE(typeLiteral).subtypes))[0], AS_DICTIONARY(value)->entries[i].key)) { if (!checkType(((Literal*)(AS_TYPE(typeLiteral).subtypes))[0], AS_DICTIONARY(value)->entries[i].key)) {
return false; return false;
} }
if (checkType(((Literal*)(AS_TYPE(typeLiteral).subtypes))[1], AS_DICTIONARY(value)->entries[i].value)) { if (!checkType(((Literal*)(AS_TYPE(typeLiteral).subtypes))[1], AS_DICTIONARY(value)->entries[i].value)) {
return false; return false;
} }
} }
@@ -112,7 +112,16 @@ bool declareScopeVariable(Scope* scope, Literal key, Literal type) {
} }
bool isDelcaredScopeVariable(Scope* scope, Literal key) { bool isDelcaredScopeVariable(Scope* scope, Literal key) {
return existsLiteralDictionary(&scope->variables, key); if (scope == NULL) {
return false;
}
//if it's not in this scope, keep searching up the chain
if (!existsLiteralDictionary(&scope->variables, key)) {
return isDelcaredScopeVariable(scope->ancestor, key);
}
return true;
} }
//return false if undefined, or can't be assigned //return false if undefined, or can't be assigned