diff options
| -rw-r--r-- | spec/parcom_spec.cr | 4 | ||||
| -rw-r--r-- | src/parcom.cr | 12 | ||||
| -rw-r--r-- | src/parcom/eof.cr | 23 |
3 files changed, 26 insertions, 13 deletions
diff --git a/spec/parcom_spec.cr b/spec/parcom_spec.cr index f28c560..11d2446 100644 --- a/spec/parcom_spec.cr +++ b/spec/parcom_spec.cr @@ -125,8 +125,8 @@ describe AnyToken do end end -describe Eof do - p = Eof(Char).new +describe EOF do + p = EOF(Char).new describe "#parse" do it "succeeds when input is empty" do diff --git a/src/parcom.cr b/src/parcom.cr index f6d1e05..4612887 100644 --- a/src/parcom.cr +++ b/src/parcom.cr @@ -81,16 +81,6 @@ module Parcom end end - class Eof(T) < Parser(T, Nil) - def parse(tokens : Tokens(T)) : Result(T, Nil) - if tokens.empty? - Result.new(tokens, nil) - else - raise ParserFail.new("Eof: input was not empty") - end - end - end - class Peek(T, V) < Parser(T, V) def initialize(@p : Parser(T, V)) end @@ -179,7 +169,7 @@ module Parcom @p : Map(T, {V, Nil}, V) def initialize(p : Parser(T, V)) - @p = (p + Eof(T).new).map &.first + @p = (p + EOF(T).new).map &.first end def parse(tokens : Tokens(T)) : Result(T, V) diff --git a/src/parcom/eof.cr b/src/parcom/eof.cr new file mode 100644 index 0000000..650da56 --- /dev/null +++ b/src/parcom/eof.cr @@ -0,0 +1,23 @@ +require "./parser.cr" + +module Parcom + # `EOF` is a `Parser` succeeds if the input stream is empty. + # + # This parser retuns `nil` when successful because there is no + # other meaningful value to return. + # + # This parser is also one of the few cases where it is ideal to not + # modify or take from the input stream, as it should be empty anyway. + class EOF(T) < Parser(T, Nil) + # Succeeds is the input stream is empty and returns `nil`. + # Raises a `ParserFail` exception when the input is not empty. + def parse(tokens : Tokens(T)) : Result(T, Nil) + if tokens.empty? + Result.new(tokens, nil) + else + raise ParserFail.new("Eof: input was not empty") + end + end + end +end + |
