Class Suffix

java.lang.Object
com.google.common.labs.parse.Suffix

public final class Suffix extends Object
A convenience helper to manage multiple optional suffixes.

Usually when you have an optional suffix, you should use optionallyFollowedBy() directly, such as:


 expr.optionallyFollowedBy("!", (Integer n) -> factorial(n));
 
However when there are more than one optional suffixes to be applied after the same parser, it becomes awkward to compose them in a readable way.

The following is an example using the Suffix helper and Parser.anyOf(Parser...) to compose the optional suffix operators together before passing to optionallyFollowedBy():


 import static com.google.common.labs.parse.Suffix.suffix;

 expr.optionallyFollowedBy(
     anyOf(
         suffix("!", (Integer n) -> factorial(n)),
         suffix(exponential, (Integer i, Double e) -> pow(i, e))),
     Suffix::apply);
 

Occasionally you may need to wrap the left parser's result with or without optional suffixes, regardless. For example, the parsed string needs to be wrapped in either one of Expr AST types as determined by the optional suffixes, or wrapped in the default LiteralExpr when no suffix is present, you can use:


 import static com.google.common.labs.parse.Suffix.suffix;

 Parser.sequence(
     expr,
     anyOf(
         suffix("!", FactorialExpr::new),
         suffix(exponential, PowExpr::new))
       .orElse(LiteralExpr::new),
     Suffix::apply);
 
Or even a single optional suffix can benefit too:

 import static com.google.common.labs.parse.Suffix.suffix;

 Parser.sequence(
     expr,
     suffix(exponential, PowExpr::new).orElse(LiteralExpr::new),
     Suffix::apply);
 
Since:
10.7
  • Method Details

    • suffix

      public static <T,S,R> Parser<Function<T,R>> suffix(Parser<S> suffix, BiFunction<? super T, ? super S, ? extends R> combiner)
      A suffix parser that combines together with its prefix parse's result using the combiner function.
    • suffix

      public static <T,R> Parser<Function<T,R>> suffix(String suffix, Function<? super T, ? extends R> mapper)
      A suffix parser that uses the mapper function to transform the prefix's result.
    • apply

      public static <T,R> R apply(T prefix, Function<? super T, ? extends R> suffix)
      A convenience method to apply a suffix to a prefix. When passed to the optionallyFollowedBy() as a method reference (Suffix::apply), it reads in the intuitive encounter order.