diff --git a/src/errors.cpp b/src/errors.cpp new file mode 100644 index 0000000..a03b80c --- /dev/null +++ b/src/errors.cpp @@ -0,0 +1,24 @@ +#include +#include +#include +using namespace std; + +#include "include/colors.h" +#include "include/tokenize.h" + + +void pretty_print_error(vector 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; +} \ No newline at end of file diff --git a/src/include/errors.h b/src/include/errors.h new file mode 100644 index 0000000..66ed1fd --- /dev/null +++ b/src/include/errors.h @@ -0,0 +1,6 @@ +#include +using namespace std; + +#include "tokenize.h" + +void pretty_print_error(vector history, CodePosition pos); \ No newline at end of file diff --git a/src/include/parser.h b/src/include/parser.h index f9d07de..47701e3 100644 --- a/src/include/parser.h +++ b/src/include/parser.h @@ -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; }; /** diff --git a/src/parser.cpp b/src/parser.cpp index 0d9e9aa..6f5aed5 100644 --- a/src/parser.cpp +++ b/src/parser.cpp @@ -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 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 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();