aboutsummaryrefslogtreecommitdiff
path: root/spec/practical/json_spec.cr
diff options
context:
space:
mode:
authorMatthew Hall <hallmatthew314@gmail.com>2023-03-26 15:16:10 +1300
committerMatthew Hall <hallmatthew314@gmail.com>2023-03-26 15:16:10 +1300
commit63dcfef9b99de484a737043afabe8c48d5105eb6 (patch)
tree2a98e69f6806d8b108a0bf2e39463decfc812ad7 /spec/practical/json_spec.cr
parent9154b5c67ef2a04059256520adf8d4cf9c3d096f (diff)
Int parsing + some tweaks
Diffstat (limited to 'spec/practical/json_spec.cr')
-rw-r--r--spec/practical/json_spec.cr45
1 files changed, 41 insertions, 4 deletions
diff --git a/spec/practical/json_spec.cr b/spec/practical/json_spec.cr
index 7373d91..ed0fcfb 100644
--- a/spec/practical/json_spec.cr
+++ b/spec/practical/json_spec.cr
@@ -2,6 +2,8 @@ require "../spec_helper"
include Parcom
+# NOTE: WORK IN PROGRESS
+
alias JSONType = Nil \
| Bool \
| Int64 \
@@ -10,7 +12,7 @@ alias JSONType = Nil \
| Array(JSONValue) \
| Hash(String, JSONValue)
-class JSONValue
+struct JSONValue
property data : JSONType
def initialize(@data)
@@ -22,15 +24,25 @@ def json_null
end
def json_bool
- t = Parser.token_sequence("true".chars).map { |_| JSONValue.new(true) }
- f = Parser.token_sequence("false".chars).map { |_| JSONValue.new(false) }
- t | f
+ t = Parser.token_sequence("true".chars).map { |_| true }
+ f = Parser.token_sequence("false".chars).map { |_| false }
+ (t | f).map { |b| JSONValue.new(b) }
+end
+
+# Only standard decimal ints for now
+def json_number
+ base_num = Parser(Char, Char).satisfy(&.ascii_number?).some.map do |cs|
+ cs.join.to_i64
+ end
+ sign = Parser.token('-').map { |_| -1 }.recover(1)
+ (sign + base_num).map { |s, n| JSONValue.new(s.to_i64 * n) }
end
def json_value : Parser(Char, JSONValue)
Parser.first_of([
json_null,
json_bool,
+ json_number,
])
end
@@ -59,6 +71,21 @@ describe "example: JSON parsing" do
end
end
+ describe "json_number" do
+ it "parses strings of digits and other key characters and converts to number" do
+ result = json_number.parse(Tokens.from_string("42"))
+ result.value.data.should eq(42)
+ result.tokens.empty?.should be_true
+
+ result = json_number.parse(Tokens.from_string("-42"))
+ result.value.data.should eq(-42)
+ result.tokens.empty?.should be_true
+
+ expect_raises(ParserFail) { json_number.parse(Tokens.from_string("")) }
+ expect_raises(ParserFail) { json_number.parse(Tokens.from_string("foo")) }
+ end
+ end
+
describe "json_value" do
it "parses null" do
result = json_value.parse(Tokens.from_string("null"))
@@ -75,6 +102,16 @@ describe "example: JSON parsing" do
result.value.data.should be_false
result.tokens.empty?.should be_true
end
+
+ it "parsers ints" do
+ result = json_value.parse(Tokens.from_string("42"))
+ result.value.data.should eq(42)
+ result.tokens.empty?.should be_true
+
+ result = json_value.parse(Tokens.from_string("-42"))
+ result.value.data.should eq(-42)
+ result.tokens.empty?.should be_true
+ end
end
end