Class Parser.Rule<T>

java.lang.Object
com.google.common.labs.parse.Parser<T>
com.google.common.labs.parse.Parser.Rule<T>
All Implemented Interfaces:
Production<T>
Enclosing class:
Parser<T>

@ThreadSafe public static final class Parser.Rule<T> extends Parser<T>
A forward-declared production rule, to be used for recursive grammars.

For example, to create a parser for a simple calculator that supports single-digit numbers, addition, and parentheses, you can write:


 var rule = new Parser.Rule<Integer>();
 Parser<Integer> num = Parser.single(CharPredicate.inRange('0', '9')).map(c -> c - '0');
 Parser<Integer> atomic = rule.between("(", ")").or(num);
 Parser<Integer> expr =
     atomic.atLeastOnceDelimitedBy("+")
         .map(nums -> nums.stream().mapToInt(n -> n).sum());
 return rule.definedAs(expr);
 

For simple definitions, you could use the Parser.define(java.util.function.Function<? super com.google.common.labs.parse.Parser<T>, ? extends com.google.common.labs.parse.Parser<? extends T>>) method with a lambda to elide the need of an explicit forward declaration.

To prevent StackOverflowError, rules enforce a maximum recursion depth limit. The recursion depth is tracked globally per parse operation across all recursive rules on the call stack. Each rule enforces its own limit against this global depth.

  • Constructor Details

    • Rule

      public Rule()
      Creates a rule with a default maximum recursion depth of 100.
    • Rule

      public Rule(int maxRecursionDepth)
      Creates a rule with the given maximum recursion depth.

      The recursion depth is tracked globally per parse operation across all recursive rules on the call stack.

      Throws:
      IllegalArgumentException - if maxRecursionDepth is not positive.
      Since:
      10.6
  • Method Details

    • definedAs

      public <S extends T> Parser<S> definedAs(Parser<S> parser)
      Define this rule as parser and returns it.