-
Notifications
You must be signed in to change notification settings - Fork 0
/
scheme.cpp
59 lines (56 loc) · 1.43 KB
/
scheme.cpp
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
#include "scheme.h"
#include "parser.h"
#include <sstream>
std::string Interpreter::Run(const std::string& input) {
visited_.clear();
std::stringstream in;
in << input;
Tokenizer tokenizer(&in);
std::string ans;
auto root = Read(&tokenizer);
while (!tokenizer.IsEnd()) {
Read(&tokenizer);
}
if (scope_ == nullptr) {
scope_ = std::make_shared<Scope>();
scope_->CreateGlobalScope();
}
return Serialize(Evaluate(root, scope_));
}
std::string Interpreter::Serialize(std::shared_ptr<Object> object) {
if (visited_.contains(object)) {
return "(...)";
}
visited_.insert(object);
if (!object) {
return "()";
}
if (Is<Number>(object)) {
return std::to_string(As<Number>(object)->GetValue());
}
if (Is<Symbol>(object)) {
return As<Symbol>(object)->GetName();
}
std::string ans;
ans += "(";
while (object && Is<Cell>(object)) {
ans += Serialize(As<Cell>(object)->GetFirst());
object = As<Cell>(object)->GetSecond();
if (object) {
ans += " ";
}
if (Is<Cell>(object)) {
if (visited_.contains(object)) {
object = nullptr;
ans += "(...)";
break;
}
visited_.insert(object);
}
}
if (object) {
ans += ". " + Serialize(object);
}
ans += ")";
return ans;
}