aboutsummaryrefslogtreecommitdiff
path: root/src/__OLD_parcom/plus.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/plus.cr
parent77c370d27be174e0b036b33d1469e84e67a7153a (diff)
Second rewrite attempt, this one should work, monkaS
Diffstat (limited to 'src/__OLD_parcom/plus.cr')
-rw-r--r--src/__OLD_parcom/plus.cr54
1 files changed, 54 insertions, 0 deletions
diff --git a/src/__OLD_parcom/plus.cr b/src/__OLD_parcom/plus.cr
new file mode 100644
index 0000000..53c9b4f
--- /dev/null
+++ b/src/__OLD_parcom/plus.cr
@@ -0,0 +1,54 @@
+require "./parser.cr"
+
+module Parcom
+ # `Plus` is a parser that tries to parse with two different
+ # parsers in succession and fails if either of the two parsers fails.
+ # The return type of this parser is `{V, U}`, where `V` is the return
+ # type of the first parser and `U` is the return type of the second.
+ #
+ # Example:
+ # ```
+ # parse1 = Token.new('1')
+ # parse2 = Token.new('2')
+ # tokens = Tokens.from_string("12")
+ # result = (parse1 + parse2).parse(tokens) # succeeds
+ # result = (parse2 + parse1).parse(tokens) # fails, wrong order
+ # ```
+ #
+ # `Plus` parsers can be chained together, but the resulting return type
+ # can become unweildly with too many combined parsers:
+ # ```
+ # letter_a = Token.new('a')
+ # a5 = letter_a + letter_a + letter_a + letter_a + letter_a
+ # tokens = Tokens.from_string("aaaaa")
+ # a5.parse(tokens) # succeeds
+ # # `a5` has a return type of { { { {Char, Char}, Char}, Char}, Char}
+ # ```
+ #
+ # If you need to parse more than two things in this manner,
+ # consider using `Many`, `Some`, `Sequence`, or `TokenSeq` instead.
+ class Plus(T, V, U) < Parser(T, {V, U})
+ # Accepts the two parsers to use, in order.
+ def initialize(@p1 : Parser(T, V), @p2 : Parser(T, U))
+ end
+
+ # Tries to parse with the two given parsers, and returns
+ # their results in a tuple if the both succeed.
+ def parse(tokens : Tokens(T)) : Result(T, {V, U})
+ begin
+ r1 = @p1.parse(tokens)
+ rescue ex : ParserFail
+ raise ParserFail.new("Plus (left): #{ex.message}")
+ end
+
+ begin
+ r2 = @p2.parse(r1.tokens)
+ rescue ex : ParserFail
+ raise ParserFail.new("Plus (right): #{ex.message}")
+ end
+
+ Result.new(r2.tokens, {r1.value, r2.value})
+ end
+ end
+end
+