-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCompileContext.cpp
58 lines (45 loc) · 1.75 KB
/
CompileContext.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
#include "CompileContext.h"
#include <sstream>
#include "../AstSerialise.h"
namespace enact {
CompileContext::CompileContext(Options options) : m_options{std::move(options)} {
}
CompileResult CompileContext::compile(std::string source) {
m_source = std::move(source);
std::vector<std::unique_ptr<Stmt>> ast = m_parser.parse();
// TODO: serialise and print AST
AstSerialise serialise{};
for (const std::unique_ptr<Stmt>& stmt : ast) {
std::cout << serialise(*stmt) << '\n';
}
}
std::string CompileContext::getSourceLine(line_t line) {
std::istringstream stream{m_source};
line_t lineNumber{1};
std::string lineContents;
while (std::getline(stream, lineContents) && lineNumber < line) {
++lineNumber;
}
return lineContents;
}
void CompileContext::reportErrorAt(const Token &token, const std::string &msg) {
std::cerr << "[line " << token.line << "] Error";
if (token.type == TokenType::END_OF_FILE) {
std::cerr << " at end: " << msg << "\n\n";
} else {
if (token.type == TokenType::ERROR) {
std::cerr << ":\n";
} else {
std::cerr << " at " << (token.lexeme == "\n" ? "newline" : "'" + token.lexeme + "'") << ":\n";
}
std::cerr << " " << getSourceLine(token.lexeme == "\n" ? token.line - 1 : token.line) << "\n ";
for (int i = 1; i <= token.col - token.lexeme.size(); ++i) {
std::cerr << " ";
}
for (int i = 1; i <= token.lexeme.size(); ++i) {
std::cerr << "^";
}
std::cerr << "\n" << msg << "\n\n";
}
}
}