Class Suffix
java.lang.Object
com.google.common.labs.parse.Suffix
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 Summary
Modifier and TypeMethodDescriptionstatic <T,R> R A convenience method to apply a suffix to a prefix.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 thecombinerfunction.A suffix parser that uses themapperfunction to transform the prefix's result.
-
Method Details
-
suffix
public static <T,S, Parser<Function<T,R> 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 thecombinerfunction. -
suffix
-
apply
A convenience method to apply a suffix to a prefix. When passed to theoptionallyFollowedBy()as a method reference (Suffix::apply), it reads in the intuitive encounter order.
-