Skip to content

Commit

Permalink
REPL: add support for printing arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
mrunix00 committed Jul 30, 2024
1 parent c805192 commit f2974ac
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 3 deletions.
6 changes: 3 additions & 3 deletions include/vm.h
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,8 @@ struct FunctionType : public VariableType {
struct Object {
enum class Type {
Invalid = 0,
String
String,
Array,
} objType;
Object() : objType(Type::Invalid){};
explicit Object(Type type) : objType(type){};
Expand All @@ -81,7 +82,6 @@ struct StringObject : public Object {
char *chars;
StringObject(size_t length, char *chars) : Object(Type::String), length(length), chars(chars){};
inline bool operator==(StringObject &other) const {
if (objType != other.objType) return false;
if (length != other.length) return false;
return std::memcmp(chars, other.chars, length) == 0;
}
Expand All @@ -93,7 +93,7 @@ struct StringObject : public Object {
struct ArrayObject : public Object {
uint64_t *data;
size_t size;
ArrayObject(size_t size, uint64_t *data) : size(size), data(data) {}
ArrayObject(size_t size, uint64_t *data) : Object(Object::Type::Array), size(size), data(data) {}
inline bool operator==(ArrayObject &other) const {
if (size != other.size) return false;
for (size_t i = 0; i < size; i++) {
Expand Down
8 changes: 8 additions & 0 deletions main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,14 @@ void printTopStack(const VM &vm, const Program &program) {
auto obj = std::bit_cast<Object *>(vm.topStack());
if (obj->objType == Object::Type::String) {
std::cout << static_cast<StringObject *>(obj)->chars << std::endl;
} else if (obj->objType == Object::Type::Array) {
auto array = static_cast<ArrayObject *>(obj);
std::cout << "[";
for (size_t i = 0; i < array->size; i++) {
std::cout << array->data[i];
if (i != array->size - 1) std::cout << ", ";
}
std::cout << "]" << std::endl;
}
}
default:
Expand Down
3 changes: 3 additions & 0 deletions src/utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,9 @@ VariableType::Type getInstructionType(const Program &program, const Instruction
case Instruction::InstructionType::LoadGlobalObject:
case Instruction::InstructionType::MakeArray:
return VariableType::Object;
case Instruction::InstructionType::LoadArrayElement:
// TODO: Handle other types
return VariableType::I64;
case Instruction::InstructionType::Call: {
auto func_index = instruction.params.index;
auto function = program.segments[func_index];
Expand Down

0 comments on commit f2974ac

Please sign in to comment.