Skip to content

simonesiega/cfg-parser

Repository files navigation

CFG Parser logo
CFG Parser

A Rust CLI tool that parses and evaluates arithmetic expressions using a Context-Free Grammar (CFG) engine.

GitHub stars Open issues Open pull requests Last commit License Rust 2024 edition

Overview

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.

Key Features

  • 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.

Supported Operators

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) =

Documentation and design details are documented in the docs directory:

Quick Start

Run with Rust

cargo run

Run Tests

cargo test

Docker Usage

Build and run:

docker build -t cfgparser .
docker run --rm cfgparser

Run 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 =" cfgparser

For full Docker workflows, troubleshooting, and compose examples, see Docker docs.

Example Expression

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

Error Handling

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.

Contributing & support 🤝

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.

License

This project is licensed under the MIT License. See LICENSE.

Authors 🧑‍💻

Contributors

About

Rust CLI parser and evaluator for arithmetic expressions using a context-free grammar.

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Contributors