Header lexy/dsl/peek.hpp

The peek and peek_not branch rules.

Branch rule lexy::dsl::peek

lexy/dsl/peek.hpp
namespace lexy
{
    struct peek_failure {};
}

namespace lexy::dsl
{
    struct peek // models branch-rule
    {
        template <typename Tag>
        static constexpr peek error;
    };

    constexpr peek peek(rule auto rule);
}

peek is a branch rule that checks if rule matches without consuming anything.

Parsing

Tries to match rule in a new context. If that succeeds, the branch is taken without consuming anything. Otherwise, it raises an error.

Branch parsing

Same as parsing, but backtracks instead of raising an error.

Errors

A generic error with the specified Tag or lexy::peek_failure at the position where it started to match rule. It then recovers without consuming additional input.

Values

None.

Example 1. Parse an optional number
struct production
{
    static constexpr auto rule = [] {
        // Number with optional minus sign.
        auto number = dsl::minus_sign + dsl::digits<>;

        // Only parse a number if we have a minus or digit.
        auto condition = dsl::peek(dsl::lit_c<'-'> / dsl::digit<>);
        return dsl::if_(condition >> number);
    }();
};
Note
Automatic whitespace  skipping is disabled while parsing rule.
Warning
rule does not have access to any context variables created by the context-sensitive parsing facilities and it can’t use recursion.
Caution
This rule requires backtracking, which can slow down parsing.

Branch rule lexy::dsl::peek_not

lexy/dsl/peek.hpp
namespace lexy
{
    struct unexpected {};
}

namespace lexy::dsl
{
    struct peek_not // models branch-rule
    {
        template <typename Tag>
        static constexpr peek_not error;
    };

    constexpr peek_not peek_not(rule auto rule);
}

peek_not is a branch rule that checks if rule does not match without consuming anything.

Parsing

Tries to match rule in a new context. If that does not succeed, the branch is taken without consuming anything. Otherwise, it raises an error.

Branch parsing

Same as parsing, but backtracks instead of raising an error.

Errors

A generic error with the specified Tag or lexy::unexpected covering everything rule would have consumed. It then recovers by consuming the peeked input that was matched.

Values

None.

Example 2. Explicitly prohibit trailing spaces
struct production
{
    struct trailing_spaces
    {
        static constexpr auto name = "trailing spaces";
    };

    static constexpr auto rule
        = LEXY_LIT("Hello World")
          + dsl::peek_not(dsl::while_one(dsl::ascii::space)).error<trailing_spaces> + dsl::eof;
};
Note
Automatic whitespace  skipping is disabled while parsing rule.
Warning
rule does not have access to any context variables created by the context-sensitive parsing facilities and it can’t use recursion.
Caution
This rule requires backtracking, which can slow down parsing.

See also