aboutsummaryrefslogtreecommitdiff
path: root/spec/practical/json_spec.cr
blob: 0ae7920296415dde76cb30520e1e0c555274496a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
require "../spec_helper"

include Parcom

# NOTE: WORK IN PROGRESS

alias JSONType = Nil \
               | Bool \
               | Int64 \
               | Float64 \
               | String \
               | Array(JSONValue) \
               | Hash(String, JSONValue)

struct JSONValue
  property data : JSONType

  def initialize(@data)
  end
end

def json_null
  Parser.token_sequence("null".chars).map_const(JSONValue.new(nil))
end

def json_bool
  t = Parser.token_sequence("true".chars).map_const(true)
  f = Parser.token_sequence("false".chars).map_const(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_const(-1).recover(1)
#  (sign + base_num).map { |s, n| JSONValue.new(s.to_i64 * n) }
#end

def json_number
  digits = Parser(Char, Char).satisfy(&.ascii_number?).many
  sign = Parser.token('-').map_const(-1).recover(1)
  point = Parser.token('.').optional

  sign.and_then do |s|
    digits.and_then do |front|
      point.and_then do |p|
        digits.and_then do |back|
          if front.empty? && back.empty?
            Parser(Char, JSONValue).flunk
          else
            x = 
              case
                when front.empty? && !p.nil? # {[], '.', _} # 0 <= x < 1
                  "0.#{back.join}".to_f64
                when back.empty? #{_, _, []} # whole number
                  front.join.to_i64
                else #when !front.empty? && !p.nil? && !back.empty? # some other float
                  "#{front.join}.#{back.join}".to_f64
                #else
                #  raise "json_number, Should be unreachable: #{front} #{p} #{back}"
              end
 
            x = x.to_i64 if x.is_a?(Float64) && (x % 1).zero?
            Parser(Char, JSONValue).pure(JSONValue.new(x * s))
          end
        end
      end
    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

describe "example: JSON parsing" do
  describe "json_null" do
    it "parses the string 'null' and returns nil when successful" do
      result = json_null.parse(Tokens.from_string("null"))
      result.value.data.should be_nil
      result.tokens.empty?.should be_true

      expect_raises(ParserFail) { json_null.parse(Tokens.from_string("")) }
    end
  end

  describe "json_bool" do
    it "parses the strings 'true' or 'false' and returns bool" do
      result = json_bool.parse(Tokens.from_string("true"))
      result.value.data.should be_true
      result.tokens.empty?.should be_true

      result = json_bool.parse(Tokens.from_string("false"))
      result.value.data.should be_false
      result.tokens.empty?.should be_true

      expect_raises(ParserFail) { json_bool.parse(Tokens.from_string("")) }
    end
  end

  describe "json_number" do
    it "parses positive and negative integers" do
      {"42", "42.", "42.000000"}.each do |s|
        result = json_number.parse(Tokens.from_string(s))
        result.value.data.should eq(42)
        result.value.data.should be_a(Int64)
        result.tokens.empty?.should be_true

        result = json_number.parse(Tokens.from_string("-#{s}"))
        result.value.data.should eq(-42)
        result.value.data.should be_a(Int64)
        result.tokens.empty?.should be_true
      end
    end

    it "parses positive and negative floats between -1 and 1" do
      {"0.1234", ".1234", ".12340000"}.each do |s|
        result = json_number.parse(Tokens.from_string(s))
        result.value.data.should eq(0.1234)
        result.value.data.should be_a(Float64)
        result.tokens.empty?.should be_true

        result = json_number.parse(Tokens.from_string("-#{s}"))
        result.value.data.should eq(-0.1234)
        result.value.data.should be_a(Float64)
        result.tokens.empty?.should be_true
      end
    end

    it "parses positive and negative floats with a whole-number component" do
      {"12.34", "0012.3400"}.each do |s|
        result = json_number.parse(Tokens.from_string(s))
        result.value.data.should eq(12.34)
        result.value.data.should be_a(Float64)
        result.tokens.empty?.should be_true

        result = json_number.parse(Tokens.from_string("-#{s}"))
        result.value.data.should eq(-12.34)
        result.value.data.should be_a(Float64)
        result.tokens.empty?.should be_true
      end
    end

    it "parses 0 as an int in various forms" do
      {"0", "0.0", "0000", ".000", "000.", "-0", "-0.", "-.0", "-0.0"}.each do |s|
        result = json_number.parse(Tokens.from_string(s))
        result.value.data.should eq(0)
        result.value.data.should be_a(Int64)
        result.tokens.empty?.should be_true
      end
    end

    it "does not parse '.' or '-.' as 0" do
      expect_raises(ParserFail) { json_number.parse(Tokens.from_string(".")) }
    end

    it "fails when input if not a number" do
      expect_raises(ParserFail) { json_number.parse(Tokens.from_string("")) }
      expect_raises(ParserFail) { json_number.parse(Tokens.from_string("foo")) }
    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"))
      result.value.data.should be_nil
      result.tokens.empty?.should be_true
    end

    it "parses bools" do
      result = json_value.parse(Tokens.from_string("true"))
      result.value.data.should be_true
      result.tokens.empty?.should be_true

      result = json_value.parse(Tokens.from_string("false"))
      result.value.data.should be_false
      result.tokens.empty?.should be_true
    end

    it "parses ints" do
      result = json_value.parse(Tokens.from_string("42"))
      result.value.data.should eq(42)
      result.value.data.should be_a(Int64)
      result.tokens.empty?.should be_true

      result = json_value.parse(Tokens.from_string("-42"))
      result.value.data.should eq(-42)
      result.value.data.should be_a(Int64)
      result.tokens.empty?.should be_true
    end

    it "parses floats" do
      result = json_value.parse(Tokens.from_string("12.34"))
      result.value.data.should eq(12.34)
      result.value.data.should be_a(Float64)
      result.tokens.empty?.should be_true

      result = json_value.parse(Tokens.from_string("-12.34"))
      result.value.data.should eq(-12.34)
      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