Add lexer and interpreter errors

This commit is contained in:
ala89 2023-11-15 13:40:37 +01:00
parent dfc0fd87d7
commit e9723fef07
3 changed files with 14 additions and 6 deletions

View File

@ -2,10 +2,18 @@
#define INTERPRETER_H #define INTERPRETER_H
#include <variant> #include <variant>
#include <string>
#include <stdexcept>
using namespace std; using namespace std;
using EvalResult = variant<int, monostate>; using EvalResult = variant<int, monostate>;
class RuntimeError : public runtime_error {
public:
explicit RuntimeError(const string& message)
: runtime_error(message) {}
};
/* /*
Evaluates the AST, returning the latest calulated value Evaluates the AST, returning the latest calulated value
*/ */

View File

@ -17,10 +17,10 @@ struct Token {
TokenData data { }; TokenData data { };
}; };
class TokenError : public std::runtime_error { class TokenError : public runtime_error {
public: public:
explicit TokenError(const std::string& message) explicit TokenError(const string& message)
: std::runtime_error(message) {} : runtime_error(message) {}
}; };
/* /*

View File

@ -37,13 +37,13 @@ EvalResult eval(Node &ast) {
case NodeType::Div: { case NodeType::Div: {
int e1 = get<int>(eval(node.children[0])); int e1 = get<int>(eval(node.children[0]));
int e2 = get<int>(eval(node.children[1])); int e2 = get<int>(eval(node.children[1]));
// if (e2 == 0) if (e2 == 0) throw RuntimeError("Division by 0");
return e1 / e2; return e1 / e2;
} break; } break;
case NodeType::Mod: { case NodeType::Mod: {
int e1 = get<int>(eval(node.children[0])); int e1 = get<int>(eval(node.children[0]));
int e2 = get<int>(eval(node.children[1])); int e2 = get<int>(eval(node.children[1]));
// if (e2 == 0) if (e2 == 0) throw RuntimeError("Modulo by 0");
return e1 % e2; return e1 % e2;
} break; } break;
case NodeType::UnaryPlus: { case NodeType::UnaryPlus: {
@ -106,7 +106,7 @@ EvalResult eval(Node &ast) {
} break; } break;
case TokenType::Identifier: { case TokenType::Identifier: {
string identifier = get<string>(token.data); string identifier = get<string>(token.data);
// if (!memory.contains(identifier)) return; if (!memory.contains(identifier)) throw RuntimeError("Unknown identifier");
return memory[identifier]; return memory[identifier];
} break; } break;
default: default: