DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Choosing a Library to Build a REST API in Java
  • Fluent-API: Creating Easier, More Intuitive Code With a Fluent API
  • Jakarta NoSQL 1.0: A Way To Bring Java and NoSQL Together
  • How to Get Word Document Form Values Using Java

Trending

  • Streamlining Event Data in Event-Driven Ansible
  • GDPR Compliance With .NET: Securing Data the Right Way
  • Cookies Revisited: A Networking Solution for Third-Party Cookies
  • Emerging Data Architectures: The Future of Data Management
  1. DZone
  2. Coding
  3. Java
  4. Implementing PEG in Java

Implementing PEG in Java

Continue exploring PEG implementations in this look into the basic implementation of scanner-less PEG parsers.

By 
Vinod Pahuja user avatar
Vinod Pahuja
·
Mar. 24, 23 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
6.4K Views

Join the DZone community and get the full member experience.

Join For Free

In Part 1 of the series on PEG implementation, I explained the basics of Parser Expression Grammar and how to implement it in JavaScript. This second part of the series is focused on implementation in Java using the parboiled library. We will try to build the same example for parsing arithmetic expressions but using different syntax and API.

QuickStart

parboiled is a lightweight and easy-to-use library to parse text input based on formal rules defined using Parser Expression Grammar. Unlike other parsers that use external grammar definition, parboiled provides a quick DSL (domain-specific language) to define grammar rules that can be used to generate parser rules on the runtime. This approach helps to avoid separate parsing and lexing phases and also does not require additional build steps.

Installation

The parboiled library is packaged into two level dependencies. There is a core artifact and two implementation artifacts for Java and Scala support. Both Java and Scala artifacts depend on the core and can be used independently in respective environments. They are available as Maven dependencies and can be downloaded from Maven central with the coordinates below:

XML
 
<dependency>
  <groupId>org.parboiled</groupId>
  <artifactId>parboiled-java</artifactId>
  <version>1.4.1</version>
</dependency>


Defining the Grammar Rules

Let’s take the same example we used earlier to define rules to parse arithmetic expressions.

 
Expression ← Term ((‘+’ / ‘-’) Term)*
Term ← Factor ((‘*’ / ‘/’) Factor)*
Factor ← Number / ‘(’ Expression ‘)’
Number ← [0-9]+


With the help of integrated DSL, the following rules can be easily defined as follows.

Java
 
public class CalculatorParser extends BaseParser {

    Rule Expression() {
        return Sequence( Term(), ZeroOrMore(AnyOf("+-"), Term()));
    }

    Rule Term() {
        return Sequence(Factor(), ZeroOrMore(AnyOf("*/"), Factor()));
    }
    Rule Factor() {
        return FirstOf(Number(), Sequence('(', Expression(), ')'));
    }

    Rule Number() {
        return OneOrMore(CharRange('0', '9'));
    }
}


If we take a closer look at the example, the parser class inherits all the DSL functions from its parent class BaseParser. It provides various builder methods for creating different types of Rules. By combining and nesting those you can build your custom grammar rules. There needs to be starting rules that recursively expand to terminal rules which are usually literals and character classes.

Generating the Parser

parbolied’s createParser API will take the DSL input and generates a parser class by enhancing the byte code of the existing class on the runtime using the ASM utils library.

Java
 
CalculatorParser parser = Parboiled.createParser(CalculatorParser.class);


Using the Parser

The generated parser is then passed to a parse runner which lazily initializes the rule tree for the first time and uses it for the subsequent run.

Java
 
String input = "1+2";
ParseRunner runner = new ReportingParseRunner(parser.Expression());
ParsingResult<?> result = runner.run(input);


Here, the thing to care about is that both the generated parser and parse runner are not thread-safe. So, we need to keep it minimum scope and avoid sharing it across multiple threads.

Understanding the Parse Result/Tree

The output parse result encapsulates information about parse success or failure. A successful run generates a parse tree with the appropriate label and text fragments. ParseTreeUtils can be used to print the whole or partial parse tree based on passed filters.

Java
 
String parseTreePrintOut = ParseTreeUtils.printNodeTree(result);
System.out.println(parseTreePrintOut);


For more fine-grained control over the parse tree, you can use the visitor API and traverse it to collect the required information out of it.

Sample Implementation

There are some sample implementations available with the library itself. It contains samples for calculators, Java, SPARQL, and time formats. Visit this GitHub repository for more.

Conclusion

As we observed, it is very quick and easy to build/use the parser using the parboiled library. However, there might be some use cases that can lead to performance and memory issues while using it on large input with a complex rule tree. Therefore, we need to be careful about complexity and ambiguity while defining the rules.

API Library Java (programming language) Tree (data structure) Domain-Specific Language

Opinions expressed by DZone contributors are their own.

Related

  • Choosing a Library to Build a REST API in Java
  • Fluent-API: Creating Easier, More Intuitive Code With a Fluent API
  • Jakarta NoSQL 1.0: A Way To Bring Java and NoSQL Together
  • How to Get Word Document Form Values Using Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!