A lightweight, self-contained expression parser & evaluator implemented in pure Java using functional parser-combinator techniques.
- Parser-Combinator Core –
parser.*
providesParser<T>
, combinators (map
,filter
,zip
,optional
,zeroOrMore
, …) and utility parsers. - Arithmetic Grammar –
grammar.ExpressionGrammar
recognises integers, floats, addition, subtraction, multiplication, and division with correct precedence. - Modern AST – Built with Java 17 sealed interfaces & records (
ast.AST
) for strong exhaustiveness checks. - Evaluation Engine –
eval.Eval
traverses the AST and producesLong
results (multiplication/division coming soon). - Zero Dependencies – Compiles and runs with nothing but a JDK 24+.
- Self-Contained Tests –
ExprEvaluator.main()
performs assertion-based smoke tests and prints All Test Successful on success.
└── src
├── ast # Sealed interfaces & records representing the syntax tree
├── eval # AST Evaluation Logic
├── ExprEvaluator.java
├── grammar # Grammar built via Parser combinator
├── model
├── parser # Fully Functional Parser Library from Scratch
├── repl
└── test
- Java 24 or newer (for records, sealed interfaces, and pattern matching).
-1 + ((1 - 2) * 3) + 4.0 / 2
=>-2.0D
- Running the tests
java -ea src/ExprEvaluator.java
- Running REPL
java src/ExprEvaluator.java -r
# or directly
./src/ExprEvaluator.java -r
-
Parser-Combinator Library The generic interface
Parser<T>
exposesparse(String)
returning anOptional<ParseResult<T>>
. Core combinators (map
,filter
,zeroOrMore
,oneOrMore
, etc.) allow composition of complex parsers in a functional style. -
Grammar Construction (
ExpressionGrammar
)number → integer | float primary → number | "(" expr ")" factor → "+" factor | "-" factor | primary term → factor (('*'|'/') factor)* expr → term (('+'|'-') term)*
The grammar is encoded declaratively by composing smaller parsers with combinators like
zip
,optional
, andoneOf
. -
AST Representation (
ast.AST
) Uses sealed interfaces (AST.Num
) and records (Expr
,Term
,Factor
) ensuring exhaustiveness inswitch
statements. -
Evaluation (
eval.Eval
) Traverses the AST to compute results. Addition/Subtraction for integers is implemented; multiplication/division and floating-point support are planned.
- Implement
MULT
/DIV
evaluation and float maths - Add parentheses and unary operator support
- Provide interactive REPL
- Handle Spaces
Inspired by functional parser-combinator libraries in Haskell & Scala.