-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFrontEnd.cpp
67 lines (53 loc) · 2.05 KB
/
FrontEnd.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
#include "FrontEnd.h"
#include "ASTBuilder.h"
#include "ASTVisualizer.h"
#include "ParseError.h"
#include "PrettyPrinter.h"
#include "TIPLexer.h"
#include "TIPParser.h"
#include "loguru.hpp"
using namespace std;
using namespace antlr4;
void LexerErrorListener::syntaxError(Recognizer *recognizer,
Token *offendingSymbol, size_t line,
size_t charPositionInLine,
const std::string &msg,
std::exception_ptr e) {
throw ParseError(msg + "@" + std::to_string(line) + ":" +
std::to_string(charPositionInLine));
}
void ParserErrorListener::syntaxError(Recognizer *recognizer,
Token *offendingSymbol, size_t line,
size_t charPositionInLine,
const std::string &msg,
std::exception_ptr e) {
throw ParseError(msg + "@" + std::to_string(line) + ":" +
std::to_string(charPositionInLine));
}
std::shared_ptr<ASTProgram> FrontEnd::parse(std::istream &stream) {
ANTLRInputStream input(stream);
TIPLexer lexer(&input);
CommonTokenStream tokens(&lexer);
TIPParser parser(&tokens);
LexerErrorListener lexerErrorListener;
ParserErrorListener parserErrorListener;
// Add error listeners
lexer.removeErrorListeners();
lexer.addErrorListener(&lexerErrorListener);
parser.removeParseListeners();
parser.removeErrorListeners();
parser.addErrorListener(&parserErrorListener);
LOG_S(1) << "Parsing program";
TIPParser::ProgramContext *tree = parser.program();
LOG_S(1) << "Building AST";
ASTBuilder ab(&parser);
return ab.build(tree);
}
void FrontEnd::prettyprint(ASTProgram *program, std::ostream &os) {
PrettyPrinter::print(program, os, ' ', 2);
}
void FrontEnd::astVisualize(std::shared_ptr<ASTNode> node, std::ostream &os) {
ASTVisualizer visualizer(os);
SyntaxTree syntaxTree(node);
visualizer.buildGraph(syntaxTree);
}