aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorMatthew Hall <hallmatthew314@gmail.com>2023-03-08 20:53:17 +1300
committerMatthew Hall <hallmatthew314@gmail.com>2023-03-08 20:53:17 +1300
commitb61aba7186cb7c616d6c8f9a3b9e6442173cbbf6 (patch)
treeb5be1d3315da3ac7afa8fd74973d224fcb6636a1 /src
parent61a58de90c2781562aacc8006616e97a3ff12005 (diff)
Implement Optional (sort of)
Diffstat (limited to 'src')
-rw-r--r--src/parcom.cr19
1 files changed, 18 insertions, 1 deletions
diff --git a/src/parcom.cr b/src/parcom.cr
index f102728..87c73c5 100644
--- a/src/parcom.cr
+++ b/src/parcom.cr
@@ -201,7 +201,24 @@ module Parcom
end
end
- class Optional
+ # TODO: find a way to make this use Recover on the back end
+ class Optional(T, V) < Parser(T, V?)
+ def initialize(@p : Parser(T, V))
+ end
+
+ def parse(tokens : TokenStream(T)) : Result(T, V?)
+ r = @p.parse?(tokens)
+
+ if r.nil?
+ Result.new(tokens, nil)
+ else
+ Result.new(r.tokens, r.value || nil)
+ end
+
+ new_tokens = r.nil? ? tokens : r.tokens
+ new_value = r.nil? ? nil : r.value
+ Result.new(new_tokens, new_value)
+ end
end
class Tokens