diff options
| author | Matthew Hall <hallmatthew314@gmail.com> | 2023-03-13 19:31:28 +1300 |
|---|---|---|
| committer | Matthew Hall <hallmatthew314@gmail.com> | 2023-03-13 19:31:28 +1300 |
| commit | 48ea163f12653a709b575f4c26b8348ef53ae0d5 (patch) | |
| tree | f8e8777e878840d14c1a7f68a81259e3c9e14c35 | |
| parent | 8e9993e91da2cd28c5c1c3ce46bd2b1884ab91c6 (diff) | |
Documentation for sequence
| -rw-r--r-- | src/parcom.cr | 21 | ||||
| -rw-r--r-- | src/parcom/sequence.cr | 33 |
2 files changed, 33 insertions, 21 deletions
diff --git a/src/parcom.cr b/src/parcom.cr index 4f35420..b6e6c3b 100644 --- a/src/parcom.cr +++ b/src/parcom.cr @@ -81,27 +81,6 @@ module Parcom end end - class Sequence(T, V) < Parser(T, Array(V)) - def initialize(@ps : Iterable(Parser(T, V))) - end - - # TODO: this can probably be optimised more for Arrays - # TODO: might be better to use #zip - def parse(tokens : Tokens(T)) : Result(T, Array(V)) - parsed = [] of V - - @ps.each do |p| - r = p.parse(tokens) - parsed << r.value - tokens = r.tokens - end - - Result.new(tokens, parsed) - rescue ex : ParserFail - raise ParserFail.new("Sequence: #{ex.message}") - end - end - class TokenSeq(T) < Parser(T, Array(T)) @p : Sequence(T, T) diff --git a/src/parcom/sequence.cr b/src/parcom/sequence.cr new file mode 100644 index 0000000..6a05cde --- /dev/null +++ b/src/parcom/sequence.cr @@ -0,0 +1,33 @@ +require "./parser.cr" + +module Parcom + # `Sequence` is a `Parser` that combines multiple parsers and + # tries to parse all of them in succession. If all of the parsers + # succeed, the values parsed are returned in an array, in the order + # they were parsed in. If any of the parsers fail, + # the `Sequence` also fails. + class Sequence(T, V) < Parser(T, Array(V)) + # Accepts the parsers to use. + def initialize(@ps : Iterable(Parser(T, V))) + end + + # Tries each parser in order, and returns their results. + # Fail if any of the wrapped parsers fail. + # TODO: this can probably be optimised more for Arrays + # TODO: might be better to use #zip + def parse(tokens : Tokens(T)) : Result(T, Array(V)) + parsed = [] of V + + @ps.each do |p| + r = p.parse(tokens) + parsed << r.value + tokens = r.tokens + end + + Result.new(tokens, parsed) + rescue ex : ParserFail + raise ParserFail.new("Sequence: #{ex.message}") + end + end +end + |
