diff options
| author | Matthew Hall <hallmatthew314@gmail.com> | 2023-03-26 21:55:54 +1300 |
|---|---|---|
| committer | Matthew Hall <hallmatthew314@gmail.com> | 2023-03-26 21:58:47 +1300 |
| commit | 66c0cef400329f1b4fb1e265738f2a58a645b9d4 (patch) | |
| tree | 7a60818871474b20bd246069a874e677fd6cbcaf /spec/practical | |
| parent | 7634947b2274bf7297709d90522093dcba7b9f3c (diff) | |
CURRENTLY BROKEN: NEEDS LAZY EVALUATION
Diffstat (limited to 'spec/practical')
| -rw-r--r-- | spec/practical/json_spec.cr | 49 |
1 files changed, 49 insertions, 0 deletions
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 |
