Header lexy/dsl/branch.hpp

The operator>> overload for rules and else_ branch rule.

lexy/dsl/branch.hpp
template <typename T>
concept branch-rule = rule<T> && ;

A branch rule is a rule that has an associated condition. The parsing algorithm can efficiently check whether the condition would match at the current reader position. As such, they are used to make decisions: once a branch condition matches, the branch is taken without backtracking.

Branch rule lexy::dsl::operator>>

lexy/dsl/branch.hpp
namespace lexy::dsl
{
    struct branch {}; // models branch-rule

    constexpr branch operator>>(branch-rule auto condition, rule auto then);
}

operator>> (branch) turns a rule into a branch rule by giving it another branch rule as condition.

Parsing

Parses condition and then in sequence .

Branch parsing

Tries to parse condition and backtracks if that backtracks. Then parses then.

Errors

All errors raised by condition and then. The rule then fails if they have failed.

Values

All values produced by condition followed by all values of then.

If the result of operator>> is used in the beginning of a sequence  with a rule, i.e. as (condition >> rule1) + rule2, this is equivalent to condition >> rule1 + rule2, i.e. the original branch is extended. rule1 + (condition >> rule2), on the other hand, is equivalent to rule1 + condition + rule2.

Example 1. Only parse a fraction if preceded by a dot
struct production
{
    static constexpr auto rule = [] {
        auto integer  = dsl::digits<>.no_leading_zero();
        auto fraction = dsl::digits<>;

        return integer + dsl::if_(dsl::period >> fraction);
    }();
};
Note
A branch rule is only parsed as a branch if its required. If you just use it by itself, the branch condition does not matter. Use lexy::dsl::if_  to conditionally execute a branch.
Caution
If then is also a branch rule, it will still only use condition as the condition.

Branch rule lexy::dsl::else_

lexy/dsl/branch.hpp
namespace lexy::dsl
{
    struct else // note: not a rule itself
    {
        friend constexpr branch-rule operator>>(else, rule auto rule);
    };

    constexpr else else_;
}

else_ is a tag that can be used as the condition for operator>> to indicate that the rule should always be taken.

(Branch) Parsing

Parses rule without every backtracking.

Errors

All errors raised by parsing rule.

Values

All values produced by rule.

Example 2. If it is not a known greeting, require that the empty is empty
struct production
{
    static constexpr auto rule
        // Input should be empty if greeting isn't known.
        = LEXY_LIT("Hello") | LEXY_LIT("Hi") | dsl::else_ >> dsl::eof;
};

See also