11#include <unordered_map>
50 inline std::unordered_map<std::string, uint64_t>
vars;
77 auto val = t.getTokenValue();
85 }
else if (val ==
"+") {
87 }
else if (val ==
"-") {
89 }
else if (val ==
"*") {
91 }
else if (val ==
"/") {
93 }
else if (val ==
"%") {
95 }
else if (val ==
"(") {
97 }
else if (val ==
")") {
99 }
else if (val ==
"+=") {
101 }
else if (val ==
"-=") {
103 }
else if (val ==
"^") {
105 }
else if (val ==
"|") {
107 }
else if (val ==
"&") {
109 }
else if (val ==
"&&") {
111 }
else if (val ==
"||") {
113 }
else if (val ==
"!") {
115 }
else if (val ==
"==") {
117 }
else if (val ==
"!=") {
119 }
else if (val ==
">") {
121 }
else if (val ==
">=") {
123 }
else if (val ==
"<") {
125 }
else if (val ==
"<=") {
263 throw std::runtime_error(
"Division by zero");
269 throw std::runtime_error(
"Modulo by zero");
285 uint64_t v =
lexer.peek().value;
289 std::string var_name =
lexer.variable;
291 auto v =
vars.find(var_name);
292 if (v ==
vars.end()) {
295 return vars[var_name];
300 throw std::runtime_error(
"Expected ')'");
304 throw std::runtime_error(
"Unexpected token");
Lexer for constant integer expressions.
std::string variable
last scanned variable name
ExprLexer(const std::string &input)
Construct a lexer and scan the input string.
ExprToken current
most recently read token
void consume()
Consume the current token and advance to the next.
scan::Scanner scanner
underlying scanner for tokenization
void next()
Advance to the next token and update current.
size_t pos
current position in the token stream
ExprToken peek() const
Return the current token without consuming it.
uint64_t parseAdd()
Parse additive expressions (+, -).
uint64_t parseBitwise()
Parse bitwise expressions (^, |, &).
ExprParser(ExprLexer &lexer)
Construct a parser bound to a lexer.
uint64_t parseLogical()
Parse logical expressions (&&, ||) — lowest precedence.
uint64_t parse()
Parse and evaluate the expression.
uint64_t parseTerm()
Parse multiplicative expressions (*, /, %).
uint64_t parseFactor()
Parse primary expressions: numbers, variables, unary ops, and parenthesised sub-expressions.
ExprLexer & lexer
reference to the token source
uint64_t parseComparison()
Parse comparison expressions (==, !=, >, >=, <, <=).
General-purpose exception with errno-aware factory method.
Lexical scanner that tokenizes source text.
Exception class, hex formatting utilities, and terminal color definitions.
std::unordered_map< std::string, uint64_t > vars
Global variable map for the expression evaluator.
ExprTokenType
Token types for the constant expression parser.
@ VARIABLE
named variable reference
@ TT_HEX
hexadecimal numeric literal
@ TT_ID
identifier or keyword
@ TT_NUM
decimal numeric literal
Lexical scanner that tokenizes source text into typed tokens.
A single expression token holding its type and optional numeric value.
uint64_t value
numeric value (valid when type == NUMBER)
ExprTokenType type
token classification