Initial Commit

This commit is contained in:
2026-01-23 00:52:10 +03:00
commit 6f7b5c2fe6
13 changed files with 2097 additions and 0 deletions

3
.gitignore vendored Normal file
View File

@@ -0,0 +1,3 @@
build/
cmake-build*/
.idea/

12
CMakeLists.txt Normal file
View File

@@ -0,0 +1,12 @@
cmake_minimum_required(VERSION 3.22)
project(expr-eval VERSION 0.1.0)
set(CMAKE_CXX_STANDARD 20)
add_executable(
expr-eval
src/main.cpp
src/frontend/lexer.cpp
src/frontend/ast.cpp
src/frontend/parser.cpp
src/frontend/ast.cpp
)

View File

@@ -0,0 +1,36 @@
#ifndef INTERPRETER_H
#define INTERPRETER_H
#include <stdexcept>
#include <string>
#include <format>
#include <unordered_map>
#include "runtime.h"
#include "../frontend/parser.h"
class Interpreter {
public:
Interpreter() = default;
RuntimeVar eval(const std::string& input) {
parser.parse(input);
return parser.root().eval(m_vars);
}
void addVar(const std::string& ident, RuntimeVar val) {
m_vars[ident] = val;
}
RuntimeVar getVar(const std::string& ident) {
if(!m_vars.contains(ident))
throw std::runtime_error(std::format("Undeclared variable `{}` not found!", ident));
return m_vars[ident];
}
private:
Parser parser;
std::unordered_map<std::string, RuntimeVar> m_vars;
};
#endif // INTERPRETER_H

View File

@@ -0,0 +1,122 @@
#ifndef RUNTIME_H
#define RUNTIME_H
#include <complex>
#include <stdexcept>
#include <string>
#include <format>
struct RuntimeVar {
enum class RuntimeVarType{
STRING,
NUMBER,
NIL,
BOOL
} type;
std::string value;
bool b_value = false;
double d_value = 0.0;
RuntimeVar()
: type(RuntimeVarType::NIL),
value("nil") {}
explicit RuntimeVar(const std::string& v)
: type(RuntimeVarType::STRING),
value(v) {}
explicit RuntimeVar(const bool t)
: type(RuntimeVarType::BOOL),
b_value(t),
value(t ? "true" : "false") {}
explicit RuntimeVar(const double d)
: type(RuntimeVarType::NUMBER),
d_value(d),
value(std::format("{}", d)) {}
std::string typeStr() {
switch(type) {
case RuntimeVarType::STRING: return "STRING";
case RuntimeVarType::NUMBER: return "NUMBER";
case RuntimeVarType::NIL: return "NIL";
case RuntimeVarType::BOOL: return "BOOL";
default: return "?";
}
}
double toDouble() {
if(type == RuntimeVarType::NUMBER)
return stod(value);
throw std::runtime_error("Expected number type");
}
std::string toString() {
return value;
}
bool toBool() {
if(value=="false" || value == "nil") return false;
if(type == RuntimeVarType::NUMBER) return toDouble() != 0.0f;
return true;
}
RuntimeVar operator+(RuntimeVar& other) {
if(type != other.type)
throw std::runtime_error(std::format("Expected same types to op '+' but found {} and {}.",
typeStr(), other.typeStr()));
if(type == RuntimeVarType::STRING) {
return RuntimeVar{ value + other.value };
}
if(type == RuntimeVarType::NUMBER) {
auto res = toDouble() + other.toDouble();
return RuntimeVar{ res };
}
throw std::runtime_error(std::format("Op '+' not supported for type {}", typeStr()));
}
RuntimeVar operator-(RuntimeVar& other) {
if(type != other.type)
throw std::runtime_error(std::format("Expected same types to op '+' but found {} and {}.",
typeStr(), other.typeStr()));
if(type == RuntimeVarType::NUMBER) {
auto res = toDouble() - other.toDouble();
return RuntimeVar{ res };
}
throw std::runtime_error(std::format("Op '+' not supported for type {}", typeStr()));
}
RuntimeVar operator*(RuntimeVar& other) {
if(type != other.type)
throw std::runtime_error(std::format("Expected same types to op '+' but found {} and {}.",
typeStr(), other.typeStr()));
if(type == RuntimeVarType::NUMBER) {
auto res = toDouble() * other.toDouble();
return RuntimeVar{ res };
}
throw std::runtime_error(std::format("Op '+' not supported for type {}", typeStr()));
}
RuntimeVar operator/(RuntimeVar& other) {
if(type != other.type)
throw std::runtime_error(std::format("Expected same types to op '+' but found {} and {}.",
typeStr(), other.typeStr()));
if(type == RuntimeVarType::NUMBER) {
auto res = toDouble() / other.toDouble();
return RuntimeVar{ res };
}
throw std::runtime_error(std::format("Op '+' not supported for type {}", typeStr()));
}
};
#endif // RUNTIME_H

View File

@@ -0,0 +1,150 @@
#ifndef AST_H
#define AST_H
#include <memory>
#include <string>
#include <vector>
#include <unordered_map>
#include "../backend/runtime.h"
#include "../picojson.h"
// ----- NODE TYPE ----- //
enum class NodeType {
PROGRAM,
// Primitive types
STRING_LIT,
BOOLEAN_LIT,
NUMBER_LIT,
NIL_LIT,
IDENT_LIT,
// Composites
BINARY_EXPR,
// EOF
END_OF_FILE
};
// ----- NODE ----- //
struct Node {
std::string name;
NodeType type;
Node(NodeType t, std::string name);
virtual ~Node();
virtual picojson::value dump();
virtual RuntimeVar eval(std::unordered_map<std::string, RuntimeVar> &vars);
};
// ----- PROGRAM NODE ----- //
struct Program : Node {
Program();
void addNode(std::unique_ptr<Node> node);
void clear();
picojson::value dump() override;
RuntimeVar eval(std::unordered_map<std::string, RuntimeVar> &vars) override;
private:
std::vector<std::unique_ptr<Node> > m_ast;
};
// ----- EXPR NODE ----- //
struct Expr : Node {
Expr(NodeType t, const std::string &name);
};
// ----- BINARY EXPR NODE ----- //
struct BinaryExpr : Expr {
BinaryExpr(std::unique_ptr<Node> left, std::string op, std::unique_ptr<Node> right);
picojson::value dump() override;
RuntimeVar eval(std::unordered_map<std::string, RuntimeVar> &vars) override;
private:
std::unique_ptr<Node> left, right;
std::string op;
};
// ----- NUMBER LITERAL NODE ----- //
struct NumberLiteral : Expr {
explicit NumberLiteral(const std::string &value);
picojson::value dump() override;
RuntimeVar eval(std::unordered_map<std::string, RuntimeVar> &vars) override;
private:
std::string value;
double d;
};
// ----- BOOLEAN LITERAL NODE ----- //
struct BooleanLiteral : Expr {
explicit BooleanLiteral(const std::string &value);
picojson::value dump() override;
RuntimeVar eval(std::unordered_map<std::string, RuntimeVar> &vars) override;
private:
std::string value;
bool b_value;
};
// ----- STRING LITERAL NODE ----- //
struct StringLiteral : Expr {
explicit StringLiteral(std::string value);
picojson::value dump() override;
RuntimeVar eval(std::unordered_map<std::string, RuntimeVar> &vars) override;
private:
std::string value;
};
// ----- IDENTIFIER LITERAL NODE ----- //
struct IdentifierLiteral : Expr {
explicit IdentifierLiteral(std::string value);
picojson::value dump() override;
RuntimeVar eval(std::unordered_map<std::string, RuntimeVar> &vars) override;
private:
std::string value;
};
// ----- NULL LITERAL NODE ----- //
struct NullLiteral : Expr {
NullLiteral();
picojson::value dump() override;
RuntimeVar eval(std::unordered_map<std::string, RuntimeVar> &vars) override;
private:
std::string value = "nil";
};
#endif // AST_H

View File

@@ -0,0 +1,68 @@
#ifndef LEXER_H
#define LEXER_H
#include <string>
#include <utility>
#include <vector>
enum class TokenType {
TOK_NUMBERS_LIT,
TOK_STRING_LIT,
TOK_BOOL_LIT,
TOK_NULL_LIT,
TOK_IDENT_LIT,
TOK_ADD_OP,
TOK_SUB_OP,
TOK_DIV_OP,
TOK_MULT_OP,
TOK_OPEN_PAREN, // (
TOK_CLOSE_PAREN, // )
TOK_EOF
};
struct Token {
TokenType type;
std::string name, value;
Token(TokenType _type, std::string _name, std::string _value);
};
class Lexer {
public:
Lexer() = default;
// Given user input, convert it to vector of token object
const std::vector<Token> &tokenize(const std::string &src);
// Return the vector of token object
const std::vector<Token> &tokens();
private:
void tokenizeNumbers();
void tokenizeString();
void tokenizeIdentifiers();
void tokenizeOperators();
void skipWhitespaces();
[[nodiscard]] char peek() const;
char advance();
[[nodiscard]] bool eof() const;
void expect(char c, const std::string &error);
int m_cursor = 0;
std::string m_src;
std::vector<Token> m_tokens;
};
#endif // LEXER_H

View File

@@ -0,0 +1,45 @@
#ifndef PARSER_H
#define PARSER_H
#include <memory>
#include "../picojson.h"
#include "lexer.h"
#include "ast.h"
class Parser {
public:
Parser() = default;
void parse(const std::string &src);
picojson::value dump();
Program &root();
private:
std::unique_ptr<Node> parseExpr();
std::unique_ptr<Node> parseAdditives();
std::unique_ptr<Node> parseFactors();
std::unique_ptr<Node> parsePrimary();
Token peek();
Token advance();
bool eof();
void expect(TokenType t, const std::string &error);
int m_cursor = 0;
Lexer lexer;
// Store root node for the AST, in our case the Program node
Program m_program;
};
#endif // PARSER_H

File diff suppressed because it is too large Load Diff

View File

171
src/frontend/ast.cpp Normal file
View File

@@ -0,0 +1,171 @@
#include "../../includes/expr-eval/frontend/ast.h"
#include <stdexcept>
Node::Node(const NodeType t, std::string name)
: name(std::move(name)),
type(t) {
}
Node::~Node() = default;
picojson::value Node::dump() {
picojson::object obj;
obj["name"] = picojson::value(name);
return picojson::value(obj);
}
RuntimeVar Node::eval(std::unordered_map<std::string, RuntimeVar> &vars) {
return {};
}
Program::Program()
: Node(NodeType::PROGRAM, "Program") {
}
void Program::addNode(std::unique_ptr<Node> node) {
m_ast.push_back(std::move(node));
}
void Program::clear() {
m_ast.clear();
}
picojson::value Program::dump() {
picojson::object obj;
obj["name"] = picojson::value(name);
picojson::array arr;
for (const auto &e: m_ast) {
arr.push_back(e->dump());
}
obj["body"] = picojson::value(arr);
return picojson::value(obj);
}
RuntimeVar Program::eval(std::unordered_map<std::string, RuntimeVar> &vars) {
RuntimeVar res;
for (const auto &node: m_ast) {
res = node->eval(vars);
}
return res;
}
Expr::Expr(const NodeType t, const std::string &name) : Node{t, name} {
}
BinaryExpr::BinaryExpr(std::unique_ptr<Node> left,
std::string op, std::unique_ptr<Node> right)
: Expr(NodeType::BINARY_EXPR, "BinaryExpr"),
left(std::move(left)),
right(std::move(right)),
op(std::move(op)) {
}
picojson::value BinaryExpr::dump() {
picojson::object obj;
obj["name"] = picojson::value(name);
obj["left"] = left->dump();
obj["op"] = picojson::value(op);
obj["right"] = right->dump();
return picojson::value(obj);
}
RuntimeVar BinaryExpr::eval(std::unordered_map<std::string, RuntimeVar> &vars) {
auto _l = left->eval(vars);
auto _r = right->eval(vars);
if (op == "+") return _l + _r;
if (op == "-") return _l - _r;
if (op == "*") return _l * _r;
if (op == "/") return _l / _r;
throw std::runtime_error(std::format("Unimplemented op `{}`", op));
}
NumberLiteral::NumberLiteral(const std::string &value)
: Expr(NodeType::NUMBER_LIT, "NumberLiteral"),
value(value) {
d = stod(value);
}
picojson::value NumberLiteral::dump() {
picojson::object obj;
obj["name"] = picojson::value(name);
obj["value"] = picojson::value(d);
return picojson::value(obj);
}
RuntimeVar NumberLiteral::eval(std::unordered_map<std::string, RuntimeVar> &vars) {
return RuntimeVar{d};
}
BooleanLiteral::BooleanLiteral(const std::string &value)
: Expr(NodeType::BOOLEAN_LIT, "BooleanLiteral"),
value(value), b_value(value == "true") {
}
picojson::value BooleanLiteral::dump() {
picojson::object obj;
obj["name"] = picojson::value(name);
obj["value"] = picojson::value(b_value);
return picojson::value(obj);
}
RuntimeVar BooleanLiteral::eval(std::unordered_map<std::string, RuntimeVar> &vars) {
return RuntimeVar{b_value};
}
StringLiteral::StringLiteral(std::string value)
: Expr(NodeType::STRING_LIT, "StringLiteral"),
value(std::move(value)) {
}
picojson::value StringLiteral::dump() {
picojson::object obj;
obj["name"] = picojson::value(name);
obj["value"] = picojson::value(value);
return picojson::value(obj);
}
RuntimeVar StringLiteral::eval(std::unordered_map<std::string, RuntimeVar> &vars) {
return RuntimeVar{value};
}
IdentifierLiteral::IdentifierLiteral(std::string value)
: Expr(NodeType::IDENT_LIT, "IdentifierLiteral"),
value(std::move(value)) {
}
picojson::value IdentifierLiteral::dump() {
picojson::object obj;
obj["name"] = picojson::value(name);
obj["value"] = picojson::value(value);
return picojson::value(obj);
}
RuntimeVar IdentifierLiteral::eval(std::unordered_map<std::string, RuntimeVar> &vars) {
if (!vars.contains(value)) {
throw std::runtime_error(std::format("Use of undefined variable `{}`", value));
}
return vars[value];
}
NullLiteral::NullLiteral()
: Expr(NodeType::NIL_LIT, "NullLiteral") {
}
picojson::value NullLiteral::dump() {
picojson::object obj;
obj["name"] = picojson::value(name);
obj["value"] = picojson::value(value);
return picojson::value(obj);
}
RuntimeVar NullLiteral::eval(std::unordered_map<std::string, RuntimeVar> &vars) {
return RuntimeVar{};
}

136
src/frontend/lexer.cpp Normal file
View File

@@ -0,0 +1,136 @@
#include "../../includes/expr-eval/frontend/lexer.h"
#include <cctype>
#include <stdexcept>
#include <format>
Token::Token(const TokenType _type, std::string _name, std::string _value)
: type(_type),
name(std::move(_name)),
value(std::move(_value)) {
}
const std::vector<Token> &Lexer::tokenize(const std::string &src) {
m_src = src; // Assign source string for tokenization
m_cursor = 0; // Reset cursor position
m_tokens.clear(); // Reset token list
while (!eof()) {
if (std::isdigit(peek()))
// Tokenize number literals (decimal and floating point)
tokenizeNumbers();
else if (peek() == '"')
// Tokenize string literals like "a string"
tokenizeString();
else if (std::isalpha(peek()) || peek() == '_')
// Parse variables, keywords, functions, etc.
tokenizeIdentifiers();
else if (std::isspace(peek()))
// Skip any whitespaces (tab, space, new line, carriage, etc
skipWhitespaces();
else if (peek() == '(')
m_tokens.emplace_back(
TokenType::TOK_OPEN_PAREN,
"TOK_OPEN_PAREN",
std::string{advance()});
else if (peek() == ')')
m_tokens.emplace_back(
TokenType::TOK_CLOSE_PAREN,
"TOK_CLOSE_PAREN",
std::string{advance()});
// Let's assume at this point, what remains is
// operators.
else tokenizeOperators();
}
m_tokens.emplace_back(TokenType::TOK_EOF, "TOK_EOF", "");
return m_tokens;
}
const std::vector<Token> &Lexer::tokens() {
return m_tokens;
}
void Lexer::tokenizeNumbers() {
std::string num;
while (!eof() && std::isdigit(peek())) {
num += advance();
}
m_tokens.emplace_back(TokenType::TOK_NUMBERS_LIT, "TOK_NUMBERS_LIT", num);
}
void Lexer::tokenizeString() {
std::string str;
advance();
while (!eof() && peek() != '"') {
str += advance();
}
expect('"', "Expected '\"' to close the string");
m_tokens.emplace_back(TokenType::TOK_STRING_LIT, "TOK_STRING_LIT", str);
}
void Lexer::tokenizeIdentifiers() {
std::string ident;
while (!eof() && (peek() == '_' || std::isalnum(peek()))) {
ident += advance();
}
if (ident == "true" || ident == "false") {
m_tokens.emplace_back(TokenType::TOK_BOOL_LIT, "TOK_BOOL_LIT", ident);
} else if (ident == "nil") {
m_tokens.emplace_back(TokenType::TOK_NULL_LIT, "TOK_NULL_LIT", ident);
} else
m_tokens.emplace_back(TokenType::TOK_IDENT_LIT, "TOK_IDENT_LIT", ident);
}
void Lexer::tokenizeOperators() {
auto op = advance();
if (op == '+')
m_tokens.emplace_back(TokenType::TOK_ADD_OP, "TOK_ADD_LIT", std::string{op});
else if (op == '-')
m_tokens.emplace_back(TokenType::TOK_SUB_OP, "TOK_SUB_LIT", std::string{op});
else if (op == '*')
m_tokens.emplace_back(TokenType::TOK_MULT_OP, "TOK_MULT_LIT", std::string{op});
else if (op == '/')
m_tokens.emplace_back(TokenType::TOK_DIV_OP, "TOK_DIV_LIT", std::string{op});
else throw std::runtime_error(std::format("Unknown Character `{}` in the input string", peek()));
}
void Lexer::skipWhitespaces() {
if (std::isspace(peek())) {
advance();
}
}
char Lexer::peek() const {
return m_src[m_cursor];
}
char Lexer::advance() {
return m_src[m_cursor++];
}
bool Lexer::eof() const {
return m_cursor >= m_src.size();
}
void Lexer::expect(const char c, const std::string &error) {
if (!eof() && peek() == c) {
advance();
return;
}
throw std::runtime_error(error);
}

116
src/frontend/parser.cpp Normal file
View File

@@ -0,0 +1,116 @@
#include "../../includes/expr-eval/frontend/parser.h"
#include "../../includes/expr-eval/frontend/lexer.h"
#include "../../includes/expr-eval/frontend/ast.h"
#include <exception>
#include <memory>
#include <stdexcept>
#include <format>
void Parser::parse(const std::string &src) {
lexer.tokenize(src);
m_cursor = 0;
m_program.clear();
while (peek().type != TokenType::TOK_EOF) {
m_program.addNode(parseExpr());
}
}
picojson::value Parser::dump() {
return m_program.dump();
}
Program &Parser::root() {
return m_program;
}
std::unique_ptr<Node> Parser::parseExpr() {
return parseAdditives();
}
std::unique_ptr<Node> Parser::parseAdditives() {
auto left = parseFactors();
while (!eof() && (
peek().type == TokenType::TOK_ADD_OP ||
peek().type == TokenType::TOK_SUB_OP
)) {
std::string op = advance().value;
auto right = parseFactors();
left = std::make_unique<BinaryExpr>(std::move(left), op, std::move(right));
}
return left;
}
std::unique_ptr<Node> Parser::parseFactors() {
auto left = parsePrimary();
while (!eof() && (
peek().type == TokenType::TOK_MULT_OP ||
peek().type == TokenType::TOK_DIV_OP
)) {
std::string op = advance().value;
auto right = parsePrimary();
left = std::make_unique<BinaryExpr>(std::move(left), op, std::move(right));
}
return left;
}
std::unique_ptr<Node> Parser::parsePrimary() {
switch (peek().type) {
case TokenType::TOK_NUMBERS_LIT: {
auto token = advance();
return std::make_unique<NumberLiteral>(token.value);
}
case TokenType::TOK_STRING_LIT: {
auto token = advance();
return std::make_unique<StringLiteral>(token.value);
}
case TokenType::TOK_BOOL_LIT: {
auto token = advance();
return std::make_unique<BooleanLiteral>(token.value);
}
case TokenType::TOK_NULL_LIT: {
auto token = advance();
return std::make_unique<NullLiteral>();
}
case TokenType::TOK_IDENT_LIT: {
auto token = advance();
return std::make_unique<IdentifierLiteral>(token.value);
}
case TokenType::TOK_OPEN_PAREN: {
advance();
auto left = parseExpr();
expect(TokenType::TOK_CLOSE_PAREN,
"Expected closing parens ')' but was not found!");
return left;
}
default: {
throw std::runtime_error(std::format("Unknown Token `{}`", peek().value));
}
}
}
Token Parser::peek() {
return lexer.tokens().at(m_cursor);
}
Token Parser::advance() {
return lexer.tokens().at(m_cursor++);
}
bool Parser::eof() {
return m_cursor >= lexer.tokens().size();
}
void Parser::expect(const TokenType t, const std::string &error) {
if (!eof() && peek().type == t) {
advance();
return;
}
throw std::runtime_error(error);
}

38
src/main.cpp Normal file
View File

@@ -0,0 +1,38 @@
#include <exception>
#include <iostream>
#include <string>
#include <format>
#include "../includes/expr-eval/frontend/lexer.h"
#include "../includes/expr-eval/frontend/parser.h"
#include "../includes/expr-eval/frontend/ast.h"
#include "../includes/expr-eval/backend/runtime.h"
#include "../includes/expr-eval/backend/interpreter.h"
// REPL
int main() {
// Create an Interpreter instance
Interpreter ip;
ip.addVar("f_name", RuntimeVar(std::string{"John"}));
ip.addVar("l_name", RuntimeVar(std::string{"Doe"}));
ip.addVar("x", RuntimeVar(23.45));
ip.addVar("PI", RuntimeVar(3.14));
while(true) {
std::cout << ">>> ";
std::string input;
std::getline(std::cin, input);
// Exit REPL using `exit` command
if(input == "exit") break;
try {
auto res = ip.eval(input);
std::cout << res.toString() << std::endl;
} catch(const std::exception& e) {
std::cerr << e.what() << std::endl;
}
}
return 0;
}