From 8d12db7dbeb6518d5a3ea3a268e703fbf92dfb44 Mon Sep 17 00:00:00 2001 From: Kayne Ruse Date: Mon, 15 Aug 2022 03:12:10 +0100 Subject: [PATCH] Some declaration guards --- source/interpreter.c | 17 ++++++++++++++++- source/parser.c | 6 ++++-- source/scope.c | 6 +++++- source/scope.h | 1 + 4 files changed, 26 insertions(+), 4 deletions(-) diff --git a/source/interpreter.c b/source/interpreter.c index 2322820..b191fd8 100644 --- a/source/interpreter.c +++ b/source/interpreter.c @@ -311,6 +311,9 @@ static bool execVarDecl(Interpreter* interpreter, bool lng) { } if (!setScopeVariable(interpreter->scope, identifier, parseIdentifierToValue(interpreter, popLiteralArray(&interpreter->stack)) )) { + printf("Incorrect type assigned to variable \""); + printLiteral(identifier); + printf("\"\n"); return false; } @@ -328,7 +331,19 @@ static bool execVarAssign(Interpreter* interpreter) { return false; } - setScopeVariable(interpreter->scope, lhs, rhs); + if (!isDelcaredScopeVariable(interpreter->scope, lhs)) { + printf("Undeclared variable \"");; + printLiteral(lhs); + printf("\"\n"); + return false; + } + + if (!setScopeVariable(interpreter->scope, lhs, rhs)) { + printf("Incorrect type assigned to variable \""); + printLiteral(lhs); + printf("\"\n"); + return false; + } return true; } diff --git a/source/parser.c b/source/parser.c index 7e8ef66..88edf13 100644 --- a/source/parser.c +++ b/source/parser.c @@ -763,8 +763,10 @@ static void expressionStmt(Parser* parser, Node** nodeHandle) { Node* ptr = NULL; expression(parser, &ptr); - **nodeHandle = *ptr; - FREE(Node, ptr); //BUGFIX: this thread of execution is nuts + if (ptr != NULL) { + **nodeHandle = *ptr; + FREE(Node, ptr); //BUGFIX: this thread of execution is nuts + } consume(parser, TOKEN_SEMICOLON, "Expected ';' at the end of expression statement"); } diff --git a/source/scope.c b/source/scope.c index 9f5a455..90ccb46 100644 --- a/source/scope.c +++ b/source/scope.c @@ -59,7 +59,11 @@ bool declareScopeVariable(Scope* scope, Literal key, Literal type) { return true; } -//return false if undefined +bool isDelcaredScopeVariable(Scope* scope, Literal key) { + return existsLiteralDictionary(&scope->variables, key); +} + +//return false if undefined, or can't be assigned bool setScopeVariable(Scope* scope, Literal key, Literal value) { //dead end if (scope == NULL) { diff --git a/source/scope.h b/source/scope.h index 8e7afec..3d9bd65 100644 --- a/source/scope.h +++ b/source/scope.h @@ -14,6 +14,7 @@ Scope* popScope(Scope* scope); //returns false if error bool declareScopeVariable(Scope* scope, Literal key, Literal type); +bool isDelcaredScopeVariable(Scope* scope, Literal key); //return false if undefined bool setScopeVariable(Scope* scope, Literal key, Literal value);