aboutsummaryrefslogtreecommitdiff
path: root/src/__OLD_parcom/some.cr
diff options
context:
space:
mode:
authorMatthew Hall <hallmatthew314@gmail.com>2023-03-16 20:36:03 +1300
committerMatthew Hall <hallmatthew314@gmail.com>2023-03-16 20:36:03 +1300
commitb274828831fec26cd8b3089ffef14cb96ce2de2f (patch)
treeff5927b85a59b4d85c9e4aa269a475a7a37a54a0 /src/__OLD_parcom/some.cr
parent77c370d27be174e0b036b33d1469e84e67a7153a (diff)
Second rewrite attempt, this one should work, monkaS
Diffstat (limited to 'src/__OLD_parcom/some.cr')
-rw-r--r--src/__OLD_parcom/some.cr33
1 files changed, 33 insertions, 0 deletions
diff --git a/src/__OLD_parcom/some.cr b/src/__OLD_parcom/some.cr
new file mode 100644
index 0000000..a2e3563
--- /dev/null
+++ b/src/__OLD_parcom/some.cr
@@ -0,0 +1,33 @@
+require "./parser.cr"
+require "./assert.cr"
+require "./many.cr"
+
+module Parcom
+ # `Some` is a `Parser` that repeatedly tries to parse with another parser.
+ # The `Some` object will collect all success values in an array, and
+ # return them with the final state of the input stream. If the wrapped
+ # parser ever fails or succeeds without parsing any input, the `Some`
+ # object will stop attempting to parse and will return the array of
+ # previous successes.
+ #
+ # `Some` will raise a `ParserFail` exception if the parser never succeeds
+ # or consumes input. For cases where parsing should allow for 0 successes,
+ # use `Many`.
+ class Some(T, V) < Parser(T, Array(V))
+ @p : Assert(T, Array(V))
+
+ # Accepts the parser to use.
+ def initialize(p : Parser(T, V))
+ @p = Many.new(p).assert { |arr| !arr.empty? }
+ end
+
+ # Continuously parses with the wrapped parser, returns all successes.
+ # Fails if there are no successes.
+ def parse(tokens : Tokens(T)) : Result(T, Array(V))
+ @p.parse(tokens)
+ rescue ex : ParserFail
+ raise ParserFail.new("Some: #{ex.message}")
+ end
+ end
+end
+