Fixed declarations without initial value

This commit is contained in:
2024-10-13 15:18:48 +11:00
parent 80734563b9
commit a51c5591ee
3 changed files with 51 additions and 2 deletions

View File

@@ -1,3 +1,7 @@
//declare a variable
var foobar = 42;
//defaults as null
var empty;

View File

@@ -551,7 +551,7 @@ static void makeVariableDeclarationStmt(Toy_Bucket** bucketHandle, Toy_Parser* p
makeExpr(bucketHandle, parser, &expr);
}
else {
Toy_private_emitAstValue(bucketHandle, rootHandle, TOY_VALUE_FROM_NULL());
Toy_private_emitAstValue(bucketHandle, &expr, TOY_VALUE_FROM_NULL());
}
//finally, emit the declaration as an Ast

View File

@@ -306,7 +306,7 @@ int test_keywords(Toy_Bucket** bucketHandle) {
}
int test_scope(Toy_Bucket** bucketHandle) {
//test execution
//test declaration with initial value
{
//generate bytecode for testing
const char* source = "var foobar = 42;";
@@ -353,6 +353,51 @@ int test_scope(Toy_Bucket** bucketHandle) {
Toy_freeVM(&vm);
}
//test declaration with absent value
{
//generate bytecode for testing
const char* source = "var foobar;";
Toy_Lexer lexer;
Toy_bindLexer(&lexer, source);
Toy_Parser parser;
Toy_bindParser(&parser, &lexer);
Toy_Ast* ast = Toy_scanParser(bucketHandle, &parser);
Toy_Bytecode bc = Toy_compileBytecode(ast);
//run the setup
Toy_VM vm;
Toy_initVM(&vm);
Toy_bindVM(&vm, bc.ptr);
//run
Toy_runVM(&vm);
//check the final state of the stack
Toy_String* key = Toy_createNameStringLength(bucketHandle, "foobar", 6, TOY_VALUE_NULL);
if (vm.stack == NULL ||
vm.stack->count != 0 ||
vm.scope == NULL ||
Toy_isDeclaredScope(vm.scope, key) == false ||
TOY_VALUE_IS_NULL(Toy_accessScope(vm.scope, key)) != true
)
{
fprintf(stderr, TOY_CC_ERROR "ERROR: Unexpected result in 'Toy_VM' when testing scope, source: %s\n" TOY_CC_RESET, source);
//cleanup and return
Toy_freeVM(&vm);
return -1;
}
//teadown
Toy_freeVM(&vm);
}
return 0;
}