Fundamentals 16 min read

How to Build Your Own Expression Language with ANTLR and Java

This article walks through the complete process of designing a simple domain‑specific expression language, defining its grammar, generating a lexer and parser with ANTLR, implementing an AST visitor in Java, and integrating the engine into a Java project.

Yuewen Technology
Yuewen Technology
Yuewen Technology
How to Build Your Own Expression Language with ANTLR and Java

Hand‑by‑hand Build Your Own Language

We need a small tool that, given a user's state, can tell whether a business rule is satisfied and provide intermediate results; this motivates creating a custom expression language.

Background

Typical business logic problems include questions like why a user cannot see ads, why a login button is missing, or why a user cannot claim a new‑user benefit. The solution is an expression engine that evaluates such conditions.

Language Features

Online editing

Online debugging

Simplified syntax

Weak typing

No null‑pointer exceptions

Runs on Java

These features are summarized as: the expression language is a script language .

Expression Language Definition

We adopt the expression definitions from the Java Language Specification, classifying expressions into:

Name expressions – simple names (e.g., welfare ) or qualified names (e.g., welfare.startTime ).

Basic expressions – literals (e.g., true , numbers, strings), parenthesized expressions, and method calls.

Unary expressions – currently only logical NOT ( !expr ).

Binary expressions – arithmetic, logical, comparison operators with left‑to‑right associativity and precedence (*/ > +‑ > comparisons > && > ||).

ternary expressions – conditional operator cond ? trueExpr : falseExpr with right‑to‑left associativity.

Formal Grammar

To describe the language to a computer we use a formal grammar. A type‑2 (context‑free) grammar is sufficient for most programming languages.

Example of a simple sentence grammar (type‑2):

The production rules are visualized with state‑machine diagrams:

Derived sentences such as "人吃雨", "天下面" are syntactically correct even if semantically odd.

Compiler Theory

Implementing the language requires a lexer (tokenizer) and a parser (syntax analyzer) that produce an Abstract Syntax Tree (AST). The lexer reads characters and emits tokens like INT(1) , PLUS , etc. Example:

1+1*(2+3) → INT(1) PLUS INT(1) MULTIPLY LEFT_PAR INT(2) PLUS INT(3) RIGHT_PAR

Parsing can be done with recursive‑descent (LL) or shift‑reduce (LR) algorithms. ANTLR can generate both lexer and parser automatically.

ANTLR

Using ANTLR V4 we write a .g4 grammar file. The file name must match the language name (e.g., BizExpression.g4 ). Each rule ends with a semicolon. To avoid indirect left recursion, rewrite the grammar accordingly.

Operator precedence is expressed by ordering rules: higher‑precedence operators appear before lower‑precedence ones. Associativity can be set with <assoc=right> for right‑associative operators such as the ternary operator.

After defining the grammar, ANTLR generates Lexer , Parser , and Visitor classes. Maven can invoke the antlr4-maven-plugin to compile the grammar:

mvn compile

The generated code resides in target/generated-sources/antlr4 and can be used directly in the Java project.

Visitor Implementation

The generated BaseVisitor is extended to evaluate expressions. Implementations handle literals, arithmetic, logical, and ternary expressions. Short‑circuit evaluation for && and || is demonstrated.

Potential pitfalls include handling visitTerminal and aggregateResult to avoid null results when terminals are visited.

Entry Logic

The main program reads an input expression, invokes the lexer, parser, and visitor, and prints the evaluation result.

Running the program shows the computed value.

Conclusion

The article demonstrates how a real business scenario leads to a DSL, outlines the steps of language design, uses ANTLR to generate parsing infrastructure, and implements an interpreter in Java, providing a complete end‑to‑end example of building a custom expression engine.

JavaDSLCompilerANTLRParserExpression Language
Yuewen Technology
Written by

Yuewen Technology

The Yuewen Group tech team supports and powers services like QQ Reading, Qidian Books, and Hongxiu Reading. This account targets internet developers, sharing high‑quality original technical content. Follow us for the latest Yuewen tech updates.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.