A Rust CLI tool that parses and evaluates arithmetic expressions using a Context-Free Grammar (CFG) engine.
CFG Parser is a Rust CLI project that tokenizes, parses, and evaluates arithmetic formulas based on a formal grammar. It supports nested expressions, implicit multiplication, exponentiation, and n-th root operations with explicit error handling.
- Formal CFG-driven parsing pipeline.
- Separate tokenizer and parser/evaluator architecture.
- Real-number support (
f64) with operator precedence. - Implicit multiplication (
2(3+4),(1+2)(4-1)). - Power (
^) and n-th root ($) with semantic validation. - Clear math/parsing error types for robust diagnostics.
| Operator | What it does | Example |
|---|---|---|
+ |
Adds two values | 3 + 2 = |
- |
Subtracts one value from another | 7 - 4 = |
* |
Multiplies two values | 6 * 5 = |
/ |
Divides one value by another | 8 / 2 = |
^ |
Raises a base to a power | 2 ^ 3 = |
$ |
Computes the n-th root (base $ index) |
27 $ 3 = |
( ) |
Groups expressions and controls precedence | (1 + 2) * 3 = |
implicit * |
Multiplies adjacent terms without * |
2(3+4) = |
- Grammar details:
Grammar - Architecture overview:
Architecture - Docker guide:
Docker - Contribution guidelines:
Contributing
cargo runcargo testBuild and run:
docker build -t cfgparser .
docker run --rm cfgparserRun with custom input (CLI argument):
docker run --rm cfgparser "(1 + 2) * 3 ="Run with custom input (environment variable):
docker run --rm -e CFGPARSER_INPUT="27 $ 3 =" cfgparserFor full Docker workflows, troubleshooting, and compose examples, see Docker docs.
Simple example:
1 + 2 * 3 =
Expected output:
Result: 7.000
Complex example:
(3 + 5 * (2 - 3) ^ 2) / (4 - 1) + -2 * (5 + 2) ^ 3 - 10 =
Expected output:
Result: -693.333
The parser reports structured errors such as:
- Division by zero.
- Invalid operators or malformed numbers.
- Unmatched parentheses.
- Invalid exponentiation/root cases.
- Overflow and underflow conditions.
Contributions are welcome.
- For bugs and feature requests, open an Issue.
- For code contributions, open a Pull Request with a clear description of the change and its rationale.
- For direct contact, email me at simonesiega1@gmail.com or reach out on GitHub.
This project is licensed under the MIT License. See LICENSE.