A set of utilities for handling arithmetic expressions, converting them to RPN (Reverse Polish Notation), and evaluating them.
enum {
STI_OP_ASSOC_LEFT = -1,
STI_OP_ASSOC_NONE = 0,
STI_OP_ASSOC_RIGHT = 1,
STI_OP_OPEN_PAREN = 2,
STI_OP_CLOSE_PAREN = 3,
};
typedef struct sti_op_prec_rule {
char* token;
short prec;
char assoc;
char arity;
} sti_op_prec_rule;
int infix_to_rpn(sti_op_prec_rule* rules, char** infix, char*** rpn, size_t* rpnlen)
Converts an infix-ordered list of tokens and converts it to a list of tokens in RPN order based on the rules provided. Internally uses
the Shunting Yard algorithm.
Expression Parsing
int parse_arithmetic_string(char* src, char*** out, size_t* outlen)
Tokenizes a string containing arithmetic expressions in typical mathmatical (infix) notation and
returns a list of
duped strings for each token, trimmed of whitespace, in the order it appears in the input string.
Tokens are greedily interpreted as:
- Operators: +, -, **, *, /, ~, &, |, ^, <<, >>
- Grouping: (, ), [, ]
- Numbers: [0-9.][0-9a-fA-F.]*
Evaluation
int64_t rpn_eval_int_str(char** rpn)
Evaluates a
valid list of RPN tokens using signed 64-bit integers as the internal type. Numbers are parsed using strtol(str, NULL, 0).
Supported operators:
- + Addition.
- - Subtraction.
- * Multiplication.
- / Division.
- % Integer Modulus.
- ** Exponentiation (implemented as naive looped multiplication).
- & Bitwise AND.
- | Bitwise OR.
- ^ Bitwise XOR.
- ~ Bitwise NOT.
- << Bit shift left.
- >> Bit shift right.
double rpn_eval_double_str(char** rpn)
Evaluates a
valid list of RPN tokens using signed 64-bit integers as the internal type. Numbers are parsed using strtod(str, NULL).
Supported operators:
- + Addition.
- - Subtraction.
- * Multiplication.
- / Division.
- % Floating-point modulus.