Add lexer and interpreter errors
This commit is contained in:
parent
dfc0fd87d7
commit
e9723fef07
@ -2,10 +2,18 @@
|
||||
#define INTERPRETER_H
|
||||
|
||||
#include <variant>
|
||||
#include <string>
|
||||
#include <stdexcept>
|
||||
using namespace std;
|
||||
|
||||
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
|
||||
*/
|
||||
|
@ -17,10 +17,10 @@ struct Token {
|
||||
TokenData data { };
|
||||
};
|
||||
|
||||
class TokenError : public std::runtime_error {
|
||||
class TokenError : public runtime_error {
|
||||
public:
|
||||
explicit TokenError(const std::string& message)
|
||||
: std::runtime_error(message) {}
|
||||
explicit TokenError(const string& message)
|
||||
: runtime_error(message) {}
|
||||
};
|
||||
|
||||
/*
|
||||
|
@ -37,13 +37,13 @@ EvalResult eval(Node &ast) {
|
||||
case NodeType::Div: {
|
||||
int e1 = get<int>(eval(node.children[0]));
|
||||
int e2 = get<int>(eval(node.children[1]));
|
||||
// if (e2 == 0)
|
||||
if (e2 == 0) throw RuntimeError("Division by 0");
|
||||
return e1 / e2;
|
||||
} break;
|
||||
case NodeType::Mod: {
|
||||
int e1 = get<int>(eval(node.children[0]));
|
||||
int e2 = get<int>(eval(node.children[1]));
|
||||
// if (e2 == 0)
|
||||
if (e2 == 0) throw RuntimeError("Modulo by 0");
|
||||
return e1 % e2;
|
||||
} break;
|
||||
case NodeType::UnaryPlus: {
|
||||
@ -106,7 +106,7 @@ EvalResult eval(Node &ast) {
|
||||
} break;
|
||||
case TokenType::Identifier: {
|
||||
string identifier = get<string>(token.data);
|
||||
// if (!memory.contains(identifier)) return;
|
||||
if (!memory.contains(identifier)) throw RuntimeError("Unknown identifier");
|
||||
return memory[identifier];
|
||||
} break;
|
||||
default:
|
||||
|
Loading…
Reference in New Issue
Block a user