From 66c0cef400329f1b4fb1e265738f2a58a645b9d4 Mon Sep 17 00:00:00 2001 From: Matthew Hall Date: Sun, 26 Mar 2023 21:55:54 +1300 Subject: CURRENTLY BROKEN: NEEDS LAZY EVALUATION --- spec/practical/json_spec.cr | 49 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/spec/practical/json_spec.cr b/spec/practical/json_spec.cr index 43455da..0ae7920 100644 --- a/spec/practical/json_spec.cr +++ b/spec/practical/json_spec.cr @@ -70,12 +70,35 @@ def json_number end end end + +def json_string + q = Parser.token('"') + s_char = Parser(Char, Char).first_of([ + Parser.token_sequence(['\\', '"']).map_const('"'), + Parser(Char, Char).satisfy(&.!=('"')), + ]) + (q >> s_char.many << q).map { |cs| JSONValue.new(cs.join) } +end + +def ws + Parser(Char, Char).satisfy(&.whitespace?).many +end + +def json_array + delim = ws >> Parser.token(',') >> ws + elements = json_value.sep_by(delim) + front = Parser.token('[') >> ws + back = ws >> Parser.token(']') + (front >> elements << back).map { |es| JSONValue.new(es) } +end def json_value : Parser(Char, JSONValue) Parser.first_of([ json_null, json_bool, json_number, + json_string, + json_array, ]) end @@ -166,6 +189,26 @@ describe "example: JSON parsing" do end end + describe "json_string" do + it "can parse non-empty strings" do + result = json_string.parse(Tokens.from_string("\"foo\"")) + result.value.data.should eq("foo") + result.tokens.empty?.should be_true + end + + it "can parse empty strings" do + result = json_string.parse(Tokens.from_string("\"\"")) + result.value.data.should eq("") + result.tokens.empty?.should be_true + end + + it "can parse escaped quotes" do + result = json_string.parse(Tokens.from_string("\"escaped \\\"\\\" quotes\"")) + result.value.data.should eq("escaped \"\" quotes") + result.tokens.empty?.should be_true + end + end + describe "json_value" do it "parses null" do result = json_value.parse(Tokens.from_string("null")) @@ -206,6 +249,12 @@ describe "example: JSON parsing" do result.value.data.should be_a(Float64) result.tokens.empty?.should be_true end + + it "parses strings" do + result = json_value.parse(Tokens.from_string("\"foo\"")) + result.value.data.should eq("foo") + result.tokens.empty?.should be_true + end end end -- cgit v1.2.1