unify operator weights, add recursive weight method to TreeNode

This commit is contained in:
2026-11-07 21:50:26 +02:00
parent 7a90247dc0
commit f43a16d1b2
5 changed files with 57 additions and 45 deletions
+49
View File
@@ -5,6 +5,8 @@
#include <memory>
#include <string>
#include "print.h"
namespace Expression {
class Token {
@@ -28,6 +30,31 @@ public:
NOP // not an operator
};
static int weight_op(Operator o)
{
switch (o)
{
case Expression::Token::OPA:
case Expression::Token::CPA:
case Expression::Token::NOP:
pr_warn("Unweightable operator - this is probably a bug!");
return 0;
case Expression::Token::ADD:
return 1;
case Expression::Token::SUB:
return 1;
case Expression::Token::MUL:
return 2;
case Expression::Token::DIV:
return 2;
case Expression::Token::POW:
return 3;
default:
pr_warn("Impossible operator - this is a bug!");
return 0;
}
}
union TokenValue {
std::shared_ptr<std::string> s;
double d;
@@ -380,6 +407,28 @@ public:
delete r;
}
}
int weight()
{
int w = 0;
if (l != nullptr)
{
w += l->weight();
}
if (r != nullptr)
{
w += r->weight();
}
if (o.t == Token::OPERATOR)
{
Token::weight_op(o.v.o);
}
return w;
}
};
}