Skip to content

Commit

Permalink
expression eval function
Browse files Browse the repository at this point in the history
  • Loading branch information
ckrause committed Dec 17, 2023
1 parent e880a44 commit 25906be
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
54 changes: 54 additions & 0 deletions src/form/expression_util.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
#include "form/expression_util.hpp"

#include "lang/semantics.hpp"

Expression ExpressionUtil::newConstant(int64_t value) {
return Expression(Expression::Type::CONSTANT, "", Number(value));
}
Expand Down Expand Up @@ -314,3 +316,55 @@ void ExpressionUtil::collectNames(const Expression& e, Expression::Type type,
collectNames(*c, type, target);
}
}

void assertNumChildren(const Expression& e, size_t num) {
if (e.children.size() != num) {
throw std::runtime_error("unexpected number of terms in " + e.toString());
}
}

Number ExpressionUtil::eval(const Expression& e,
const std::map<std::string, Number> params) {
switch (e.type) {
case Expression::Type::CONSTANT: {
return e.value;
}
case Expression::Type::PARAMETER: {
return params.at(e.name);
}
case Expression::Type::SUM: {
auto result = Number::ZERO;
for (auto c : e.children) {
result = Semantics::add(result, eval(*c, params));
}
return result;
}
case Expression::Type::PRODUCT: {
auto result = Number::ONE;
for (auto c : e.children) {
result = Semantics::mul(result, eval(*c, params));
}
return result;
}
case Expression::Type::FRACTION: {
assertNumChildren(e, 2);
auto a = eval(*e.children[0], params);
auto b = eval(*e.children[1], params);
return Semantics::div(a, b);
}
case Expression::Type::POWER: {
assertNumChildren(e, 2);
auto a = eval(*e.children[0], params);
auto b = eval(*e.children[1], params);
return Semantics::pow(a, b);
}
case Expression::Type::MODULUS: {
assertNumChildren(e, 2);
auto a = eval(*e.children[0], params);
auto b = eval(*e.children[1], params);
return Semantics::mod(a, b);
}
default:
throw std::runtime_error("cannot evaluate " + e.toString());
}
}
4 changes: 4 additions & 0 deletions src/form/expression_util.hpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#pragma once

#include <map>
#include <set>

#include "form/expression.hpp"
Expand All @@ -20,4 +21,7 @@ class ExpressionUtil {

static void collectNames(const Expression& e, Expression::Type type,
std::set<std::string>& target);

static Number eval(const Expression& e,
const std::map<std::string, Number> params);
};

0 comments on commit 25906be

Please sign in to comment.