mirror of
https://github.com/allankoechke/cpp-expr-eval.git
synced 2026-12-03 01:11:19 +00:00
Initial Commit
This commit is contained in:
171
src/frontend/ast.cpp
Normal file
171
src/frontend/ast.cpp
Normal 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
136
src/frontend/lexer.cpp
Normal 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
116
src/frontend/parser.cpp
Normal 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
38
src/main.cpp
Normal 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;
|
||||
}
|
||||
Reference in New Issue
Block a user