Implementing PEG in Java
Continue exploring PEG implementations in this look into the basic implementation of scanner-less PEG parsers.
Join the DZone community and get the full member experience.
Join For FreeIn 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:
<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.
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 Rule
s. 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.
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.
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.
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.
Opinions expressed by DZone contributors are their own.
Comments