Skip to content

Simple Scala Example

Brian Martin edited this page Jul 29, 2013 · 10 revisions

To give you a feel for what grammar specification looks like with parboiled for Scala consider the following classic “calculator” example, with these rules in a simple pseudo notation:

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

A parboiled parser definition, complete and in ready-to-compile Scala code would look like this:

import org.parboiled.scala._

class SimpleCalculator extends Parser {

  def Expression: Rule0 = rule { Term ~ zeroOrMore(anyOf("+-") ~ Term) }

  def Term = rule { Factor ~ zeroOrMore(anyOf("*/") ~ Factor) }

  def Factor = rule { Number | "(" ~ Expression ~ ")" }

  def Number = rule { oneOrMore("0" - "9") }
}

As you can see, the rule description from above translates almost directly into readable Scala code.
The class defines the parser rules (yet without any actions), which can be used to parse actual input like this:

(1) val input = "1+2"
(2) val parser = new SimpleCalculator { override val buildParseTree = true }
(3) val result = ReportingParseRunner(parser.Expression).run(input)
(4) val parseTreePrintOut = org.parboiled.support.ParseTreeUtils.printNodeTree(result)
(5) println(parseTreePrintOut)

Line 3 uses the ReportingParseRunner to perform an actual parsing run and create a ParsingResult object. Apart from the information whether the input was successfully matched the ParsingResult object contains the root of the parse tree for the expression (if parse tree building is enabled), the result value (which is null in this parser without actions) and a list of parse errors.
A quick way for understanding how your parser digested the input is to print the created parse tree with ParseTreeUtils.printNodeTree as shown in line 4 and 5.

In general parboiled for Scala was designed to make your rule specification as clean and readable as possible under the constraints of the Scala syntax. For more examples (including actions, AST construction, etc.) please see the Scala Examples.

Clone this wiki locally