Skip to content

Commit

Permalink
VM: add support for type deduction
Browse files Browse the repository at this point in the history
  • Loading branch information
mrunix00 committed Jul 9, 2024
1 parent 260498e commit cc1247d
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/ast.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,17 @@ bool Declaration::operator==(const AbstractSyntaxTree &other) const {
}

void Declaration::compile(Program &program, Segment &segment) const {
if (!type.has_value())
throw std::runtime_error("[Declaration::compile] Type deduction is not implemented!");
if (!type.has_value()) {
if (value.has_value()) {
auto varType = deduceType(program, segment, value.value());
value.value()->compile(program, segment);
segment.declare_variable(identifier.token.value, varType);
emitStore(program, segment, identifier.token.value);
} else {
throw std::runtime_error("[Declaration::compile] Cannot deduce the variable type!");
}
return;
}
switch (type.value()->nodeType) {
case AbstractSyntaxTree::Type::Node: {
Node *initNode = (Node *) value.value();
Expand Down
9 changes: 9 additions & 0 deletions tests/vm_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,15 @@ TEST(VM, SimpleVariableDeclaration) {
ASSERT_EQ(*static_cast<int32_t *>(vm.topStack(sizeof(int32_t))), 42);
}

TEST(VM, TypeDeduction) {
const char *input = "define a = 42;"
"a;";
VM vm;
auto program = compile(input);
vm.run(program);
ASSERT_EQ(*static_cast<int32_t *>(vm.topStack(sizeof(int32_t))), 42);
}

TEST(VM, SimpleI64VariableDeclaration) {
const char *input = "define a : i64 = 42;"
"a;";
Expand Down

0 comments on commit cc1247d

Please sign in to comment.