-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
105 lines (79 loc) · 1.77 KB
/
main.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include "interpreter.hpp"
#include "parsers.hpp"
#include "syntax.hpp"
#include <iostream>
void usage()
{
std::cout << "usage: langlang [script]" << std::endl;
}
bool interpret(interpreter& interp, const std::string& source)
{
// XXX wow this sucks
std::vector<token> tokens;
for(token_range rng{source}; auto t : rng)
{
tokens.push_back(t);
}
using namespace parsers;
auto result = parse_program(tokens);
if(not result)
{
auto error = result.error();
token tok = error.remaining.front();
auto message = std::format("Syntax error: {} at '{}': {}", tok.location(), tok.lexeme(), error.message);
std::cerr << message << std::endl;
return false;
}
program prog = result.value().value;
try
{
interp(prog);
}
catch(std::runtime_error& error)
{
std::cerr << "Runtime error: " << error.what() << std::endl;
return false;
}
return true;
}
bool interpret_from_file(const char* filename)
{
std::ifstream file(filename);
std::stringstream source;
source << file.rdbuf();
interpreter interp;
return interpret(interp, source.str());
}
int interpret_from_prompt()
{
interpreter interp;
std::string line;
std::cout << "> ";
while(getline(std::cin, line))
{
interpret(interp, line);
std::cout << "> ";
}
return 0;
}
// XXX TODO NEXT: AST nodes should not be copyable. we can't take the addresses of nodes
// and have them mean anything if nodes can be copied without warning
// ideally, nodes should be immutable as well
int main(int argc, char** argv)
{
if(argc > 2)
{
usage();
return 0;
}
bool result = true;
if(argc == 2)
{
result = interpret_from_file(argv[1]);
}
else
{
interpret_from_prompt();
}
return result ? 0 : -1;
}