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.ExpressionGrammarrecognises 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.Evaltraverses the AST and producesLongresults (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 inswitchstatements. -
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/DIVevaluation and float maths - Add parentheses and unary operator support
- Provide interactive REPL
- Handle Spaces
Inspired by functional parser-combinator libraries in Haskell & Scala.