-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompiler.hpp
More file actions
79 lines (67 loc) · 2 KB
/
compiler.hpp
File metadata and controls
79 lines (67 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#pragma once
#include "ast.hpp"
#include <string>
#include <unordered_map>
#include <vector>
#include <cstdint>
struct Value {
enum class Type { Int, Bool, String, Void };
Type type;
std::int64_t i;
bool b;
std::string s;
Value() : type(Type::Void), i(0), b(false) {}
static Value makeInt(std::int64_t v) {
Value r;
r.type = Type::Int;
r.i = v;
return r;
}
static Value makeBool(bool v) {
Value r;
r.type = Type::Bool;
r.b = v;
return r;
}
static Value makeString(const std::string& v) {
Value r;
r.type = Type::String;
r.s = v;
return r;
}
static Value makeVoid() {
return Value();
}
std::string toString() const {
if (type == Type::Int) return std::to_string(i);
if (type == Type::Bool) return b ? "true" : "false";
if (type == Type::String) return s;
return "";
}
};
class Interpreter {
public:
explicit Interpreter(AST::Program* p);
void run();
private:
struct Instance {
AST::ClassDecl* cls;
std::unordered_map<std::string, Value> fields;
explicit Instance(AST::ClassDecl* c) : cls(c) {}
};
struct Frame {
Instance* self;
std::unordered_map<std::string, Value> locals;
Frame() : self(nullptr) {}
};
AST::Program* program;
std::unordered_map<std::string, AST::ClassDecl*> classes;
Instance* mainInstance;
void indexClasses();
Value evalExpr(AST::Expr* e, Frame& frame);
void execStmt(AST::Stmt* s, Frame& frame, bool& returned, Value& retVal);
void execBlock(AST::Block* b, Frame& frame, bool& returned, Value& retVal);
AST::MethodDecl* findMethod(AST::ClassDecl* c, const std::string& name);
Value callMethod(Instance* inst, AST::MethodDecl* m, const std::vector<Value>& args);
Value defaultValueForType(const std::string& typeName);
};