blob: 45900f9cdc0c685a72b197810df9f6bfa4b18096 (
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
34
35
36
37
38
|
require "./parser.cr"
require "./sequence.cr"
module Parcom
# `TokenSeq` is a `Parser` that attempts to parse a specific
# string of tokens. If the expected tokens are not at the start
# of the input stream, the parser fails.
#
# Example:
# ```
# parse_test = TokenSeq(Char).new("test".chars)
# tokens = Tokens.from_string("testing")
#
# result = parse_test.parse(tokens)
#
# puts result.value # => ['t', 'e', 's', 't']
# puts result.tokens # => ['i', 'n', 'g']
# ```
class TokenSeq(T) < Parser(T, Array(T))
@p : Sequence(T, T)
# Accepts the tokens to try and parse, in order.
def initialize(expected : Iterable(T))
ps = [] of Parser(T, T)
expected.each { |t| ps << Token.new(t) }
@p = Sequence.new(ps)
end
# Tries to parse the list of tokens.
def parse(tokens : Tokens(T)) : Result(T, Array(T))
@p.parse(tokens)
rescue ex : ParserFail
raise ParserFail.new("TokenSeq: #{ex.message}")
end
end
end
|