aboutsummaryrefslogtreecommitdiff
path: root/src/parcom.cr
diff options
context:
space:
mode:
authorMatthew Hall <hallmatthew314@gmail.com>2023-03-09 00:28:39 +1300
committerMatthew Hall <hallmatthew314@gmail.com>2023-03-09 00:28:39 +1300
commit3e970f7aa51c69d7e659392120722ebc1611b4d6 (patch)
treeae4f6263a0f99f42ed3990ff184f01b0e91e5198 /src/parcom.cr
parent03f802e7797ca75f0dc201d762ca4d8a64c15445 (diff)
Rewrite Recover in terms of Optional
Diffstat (limited to 'src/parcom.cr')
-rw-r--r--src/parcom.cr13
1 files changed, 11 insertions, 2 deletions
diff --git a/src/parcom.cr b/src/parcom.cr
index c1eb676..9e90562 100644
--- a/src/parcom.cr
+++ b/src/parcom.cr
@@ -67,10 +67,12 @@ module Parcom
Plus.new(self, other)
end
+ # TODO: allow/change to support block invocation
def assert(f : V -> Bool)
Assert.new(self, f)
end
+ # TODO: allow/change to support block invocation
def map(f : V -> U) : Map(T, V, U) forall U
Map.new(self, f)
end
@@ -116,6 +118,7 @@ module Parcom
end
end
+ # TODO: allow/change to support block invocation
class Assert(T, V) < Parser(T, V)
def initialize(@p : Parser(T, V), @f : V -> Bool)
end
@@ -131,6 +134,7 @@ module Parcom
end
end
+ # TODO: allow/change to support block invocation
class Satisfy(T) < Parser(T, T)
def initialize(@f : T -> Bool)
end
@@ -160,6 +164,7 @@ module Parcom
end
end
+ # TODO: allow/change to support block invocation
class Map(T, V, U) < Parser(T, U)
def initialize(@p : Parser(T, V), @f : V -> U)
end
@@ -197,11 +202,15 @@ module Parcom
end
class Recover(T, V) < Parser(T, V)
- def initialize(@p : Parser(T, V), @default : V)
+ @p : Map(T, V?, V)
+
+ def initialize(p : Parser(T, V), default : V)
+ f = ->(x : V?) { x.nil? ? default : x }
+ @p = Optional.new(p).map(f)
end
def parse(tokens : TokenStream(T)) : Result(T, V)
- @p.parse?(tokens) || Result.new(tokens, @default)
+ @p.parse(tokens)
end
end