Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions include/parsi/fn/peek.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
#ifndef PARSI_FN_PEEK_HPP
#define PARSI_FN_PEEK_HPP

#include <type_traits>

#include "parsi/base.hpp"

namespace parsi::fn {

/**
* A parser combinator that checks whether the given parser is valid or not
* without changing the stream cursor.
*/
template <is_parser F>
struct Peek {
std::remove_cvref_t<F> parser;

[[nodiscard]] constexpr auto operator()(Stream stream) const noexcept -> Result
{
return Result{stream, parser(stream).is_valid()};
};
};

} // namespace parsi::fn

#endif // PARSI_FN_PEEK_HPP
14 changes: 14 additions & 0 deletions include/parsi/parsi.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
#include "parsi/fn/expect.hpp"
#include "parsi/fn/extract.hpp"
#include "parsi/fn/optional.hpp"
#include "parsi/fn/peek.hpp"
#include "parsi/fn/repeated.hpp"
#include "parsi/fn/sequence.hpp"
#include "parsi/internal/optimizer.hpp"
Expand Down Expand Up @@ -196,6 +197,19 @@ template <is_parser F>
return internal::optimize(fn::Optional<std::remove_cvref_t<F>>{std::forward<F>(parser)});
}

/**
* Creates a parser that only checks whether
* the given `parser` can parse the current
* stream, but does not move the stream forward.
*
* @see fn::Peek
*/
template <is_parser F>
[[nodiscard]] constexpr auto peek(F&& parser) noexcept
{
return internal::optimize(fn::Peek<std::remove_cvref_t<F>>{std::forward<F>(parser)});
}

} // namespace parsi

#endif // PARSI_PARSI_HPP
14 changes: 14 additions & 0 deletions tests/parsers.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,20 @@ TEST_CASE("extract")
[](std::string_view str) { return str == "not test"; })("test"));
}

TEST_CASE("peek")
{
auto parser = pr::peek(pr::expect("x"));

CHECK(parser("x"));
CHECK(parser("x").stream().as_string_view() == "x");

CHECK(parser("xxa"));
CHECK(parser("xxa").stream().as_string_view() == "xxa");

CHECK(not parser("a"));
CHECK(parser("a").stream().as_string_view() == "a");
}

TEST_CASE("complex composition")
{
auto parser = pr::sequence(
Expand Down
Loading