-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser_check.cpp
More file actions
68 lines (56 loc) · 1.81 KB
/
parser_check.cpp
File metadata and controls
68 lines (56 loc) · 1.81 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
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
#include "Lexer.h"
#include "Token.h"
#include "parser.h"
#include "ast_printer.h"
static void printUsage(const char* prog) {
std::cerr << "Usage:\n " << prog << " <source-file>\n";
}
int main(int argc, char** argv) {
if (argc != 2) {
printUsage(argv[0]);
return 1;
}
const char* filename = argv[1];
std::ifstream in(filename);
if (!in) {
std::cerr << "Error: cannot open file: " << filename << "\n";
return 1;
}
std::stringstream buffer;
buffer << in.rdbuf();
std::string source = buffer.str();
Lexer lexer(source);
std::vector<Token> tokens = lexer.tokenizeAll();
if (tokens.empty() || tokens.back().type != TokenType::END_OF_FILE) {
tokens.emplace_back(TokenType::END_OF_FILE, "", 0, 0);
}
std::cout << "=== TOKENS ===\n";
for (const Token& tok : tokens) {
std::cout << "Line " << tok.line << ", Col " << tok.column
<< " | " << tokenTypeToString(tok.type)
<< " | \"" << tok.lexeme << "\"\n";
}
Parser parser(tokens);
ASTNodePtr ast;
try {
ast = parser.parseProgram();
} catch (const ParseException&) {}
if (parser.hasErrors()) {
const auto& errs = parser.getErrors();
std::cerr << "\n=== PARSE ERRORS (" << errs.size() << ") ===\n";
for (std::size_t i = 0; i < errs.size(); ++i) {
const auto& e = errs[i];
std::cerr << " [" << (i + 1) << "] Line " << e.line
<< ", Col " << e.column << " : " << e.message << "\n";
}
return 1;
}
std::cout << "\n=== PARSE OK ===\n";
printAST(ast);
return 0;
}