aboutsummaryrefslogtreecommitdiff
path: root/src/__OLD_parcom/phrase.cr
blob: 1996fd4b03cd151281041524b9fe72da576e5f53 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
require "./parser.cr"
require "./eof.cr"
require "./map.cr"

module Parcom
  # `Phrase` is a `Parser` that tries to parse with another parser,
  # but will fail if any of the input has not been consumed.
  #
  # Example:
  # ```
  # letter_a = Token.new('a')
  # tokens = Tokens.from_string("aaa")
  # one_a = Phrase(Char, Char).new(letter_a)
  # result = one_a.parse(tokens) # This fails
  # ```
  class Phrase(T, V) < Parser(T, V)
    @p : Map(T, {V, Nil}, V)

    # Accepts the parser to parse with.
    def initialize(p : Parser(T, V))
      @p = (p + EOF(T).new).map &.first
    end

    # Tries to parse with the given parser, fails if there
    # is any un-parsed input remaining.
    def parse(tokens : Tokens(T)) : Result(T, V)
      @p.parse(tokens)
    rescue ex : ParserFail
      raise ParserFail.new("Phrase: #{ex.message}")
    end
  end
end