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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
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
Partner Zones AWS Cloud
by AWS Developer Relations
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
Partner Zones
AWS Cloud
by AWS Developer Relations

Trending

  • You Love GraphQL – Here’s How To Make Sure Your Organization Does, Too
  • Troubleshooting, Dynamic Logging, and Observability for .Net — A New Kid on the Block
  • [DZone Survey] What’s Your Superpower?
  • Use Golang for Data Processing With Amazon SNS and AWS Lambda
  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.

Vinod Pahuja user avatar by
Vinod Pahuja
·
Mar. 24, 23 · Tutorial
Like (3)
Save
Tweet
Share
4.93K 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.

Trending

  • You Love GraphQL – Here’s How To Make Sure Your Organization Does, Too
  • Troubleshooting, Dynamic Logging, and Observability for .Net — A New Kid on the Block
  • [DZone Survey] What’s Your Superpower?
  • Use Golang for Data Processing With Amazon SNS and AWS Lambda

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: