diff options
| author | Matthew Hall <hallmatthew314@gmail.com> | 2023-03-08 20:55:04 +1300 |
|---|---|---|
| committer | Matthew Hall <hallmatthew314@gmail.com> | 2023-03-08 20:55:04 +1300 |
| commit | e199329cbb23352fbd18c2eb2586b564ad9b206c (patch) | |
| tree | 72e98e0339991ae194ad14a18568fde55dde69f3 | |
| parent | b61aba7186cb7c616d6c8f9a3b9e6442173cbbf6 (diff) | |
Add Parser#recover
| -rw-r--r-- | spec/parcom_spec.cr | 2 | ||||
| -rw-r--r-- | src/parcom.cr | 10 |
2 files changed, 5 insertions, 7 deletions
diff --git a/spec/parcom_spec.cr b/spec/parcom_spec.cr index 2f3f6ba..00c59a0 100644 --- a/spec/parcom_spec.cr +++ b/spec/parcom_spec.cr @@ -337,7 +337,7 @@ describe Phrase do end describe Recover do - p = Recover.new(Token.new('t'), '@') + p = Token.new('t').recover('@') describe "#parse" do it "succeeds and returns the wrapped parser's value if it succeeds" do diff --git a/src/parcom.cr b/src/parcom.cr index 87c73c5..a2b8b92 100644 --- a/src/parcom.cr +++ b/src/parcom.cr @@ -74,6 +74,10 @@ module Parcom def map(f : V -> U) : Map(T, V, U) forall U Map.new(self, f) end + + def recover(default : T) + Recover.new(self, default) + end end class Flunk(T, V) < Parser(T, V) @@ -209,12 +213,6 @@ module Parcom 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) |
