Add error pretty print

This commit is contained in:
augustin64 2023-11-15 14:37:20 +01:00
parent cb3444fcf3
commit b87bcd68b0
4 changed files with 51 additions and 9 deletions

24
src/errors.cpp Normal file
View File

@ -0,0 +1,24 @@
#include <vector>
#include <string>
#include <iostream>
using namespace std;
#include "include/colors.h"
#include "include/tokenize.h"
void pretty_print_error(vector<string> history, CodePosition pos) {
if (pos.column == -1 || pos.line == -1)
return;
cout << pos.column << ";" << pos.line << endl;
string line = history[pos.line];
printf(BOLD "%4d " RESET , pos.line+1);
cout << line << endl;
for (int i=0; i < pos.column + 5; i++)
cout << " ";
cout << BOLD RED "^--" RESET << endl;
}

6
src/include/errors.h Normal file
View File

@ -0,0 +1,6 @@
#include <string>
using namespace std;
#include "tokenize.h"
void pretty_print_error(vector<string> history, CodePosition pos);

View File

@ -111,10 +111,12 @@ class ParseException : public std::exception {
}
};
class SyntaxError : public std::runtime_error {
class SyntaxError : public runtime_error {
public:
explicit SyntaxError(const std::string& message)
: std::runtime_error(message) {}
explicit SyntaxError(const string& message, CodePosition pos)
: runtime_error(message), pos(pos) {}
const CodePosition pos;
};
/**

View File

@ -16,13 +16,13 @@ void _debug_print_tree(const Node& node, int depth, const string& prefix = "") {
string new_prefix = prefix;
size_t pos = new_prefix.find("└──");
while (pos != std::string::npos) {
while (pos != string::npos) {
new_prefix.replace(pos, 9, " ");
pos = new_prefix.find("└──", pos + 4);
}
pos = new_prefix.find("├──");
while (pos != std::string::npos) {
while (pos != string::npos) {
new_prefix.replace(pos, 9, "");
pos = new_prefix.find("├──", pos + 6);
}
@ -43,8 +43,13 @@ void _debug_print_tree(const Node& node, int depth, const string& prefix = "") {
Node parse(vector<Token> tokens) {
reverse(tokens.begin(), tokens.end());
if (tokens.size() == 0)
throw SyntaxError("Input must not be empty");
if (tokens.size() == 0) {
CodePosition pos = {
.line = -1,
.column = -1
};
throw SyntaxError("Input must not be empty", pos);
}
// At least 1 instruction
@ -417,8 +422,13 @@ ParseReturn parse_f(vector<Token> tokens) {
ParseReturn ret = parse_expr(tokens);
tokens=ret.tokens;
if (tokens.size() < 1 || tokens.back().type != TokenType::RParenthese)
throw SyntaxError("Missing ')'");
if (tokens.size() < 1 || tokens.back().type != TokenType::RParenthese) {
CodePosition pos = {
.line = -1,
.column = -1
};
throw SyntaxError("Missing ')'", pos);
}
tokens.pop_back();