robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
34.5 KiB1021 linesraw
1local t = require('test.testutil')
2local n = require('test.functional.testnvim')()
3
4local describe, it, setup = t.describe, t.it, t.setup
5local clear = n.clear
6local fn = n.fn
7local api = n.api
8local eq = t.eq
9local matches = t.matches
10local eval = n.eval
11local command = n.command
12local pcall_err = t.pcall_err
13local NIL = vim.NIL
14local source = n.source
15
16describe('json_decode() function', function()
17  setup(function()
18    clear()
19    source([[
20      language C
21      function Eq(exp, act)
22        let act = a:act
23        let exp = a:exp
24        if type(exp) != type(act)
25          return 0
26        endif
27        if type(exp) == type({})
28          if sort(keys(exp)) !=# sort(keys(act))
29            return 0
30          endif
31          if sort(keys(exp)) ==# ['_TYPE', '_VAL']
32            let exp_typ = v:msgpack_types[exp._TYPE]
33            let act_typ = act._TYPE
34            if exp_typ isnot act_typ
35              return 0
36            endif
37            return Eq(exp._VAL, act._VAL)
38          else
39            return empty(filter(copy(exp), '!Eq(v:val, act[v:key])'))
40          endif
41        else
42          if type(exp) == type([])
43            if len(exp) != len(act)
44              return 0
45            endif
46            return empty(filter(copy(exp), '!Eq(v:val, act[v:key])'))
47          endif
48          return exp ==# act
49        endif
50        return 1
51      endfunction
52      function EvalEq(exp, act_expr)
53        let act = eval(a:act_expr)
54        if Eq(a:exp, act)
55          return 1
56        else
57          return string(act)
58        endif
59      endfunction
60    ]])
61  end)
62
63  local speq = function(expected, actual_expr)
64    eq(1, fn.EvalEq(expected, actual_expr))
65  end
66
67  it('accepts readfile()-style list', function()
68    eq(
69      { Test = 1 },
70      fn.json_decode({
71        '{',
72        '\t"Test": 1',
73        '}',
74      })
75    )
76  end)
77
78  it('accepts strings with newlines', function()
79    eq(
80      { Test = 1 },
81      fn.json_decode([[
82      {
83        "Test": 1
84      }
85    ]])
86    )
87  end)
88
89  it('parses null, true, false', function()
90    eq(NIL, fn.json_decode('null'))
91    eq(true, fn.json_decode('true'))
92    eq(false, fn.json_decode('false'))
93  end)
94
95  it('fails to parse incomplete null, true, false', function()
96    eq('Vim(call):E474: Expected null: n', pcall_err(command, 'call json_decode("n")'))
97    eq('Vim(call):E474: Expected null: nu', pcall_err(command, 'call json_decode("nu")'))
98    eq('Vim(call):E474: Expected null: nul', pcall_err(command, 'call json_decode("nul")'))
99    matches(
100      'Vim%(call%):E474: Expected null: nul',
101      pcall_err(command, 'call json_decode("nul\\n\\t")')
102    )
103
104    eq('Vim(call):E474: Expected true: t', pcall_err(command, 'call json_decode("t")'))
105    eq('Vim(call):E474: Expected true: tr', pcall_err(command, 'call json_decode("tr")'))
106    eq('Vim(call):E474: Expected true: tru', pcall_err(command, 'call json_decode("tru")'))
107    matches(
108      'Vim%(call%):E474: Expected true: tru',
109      pcall_err(command, 'call json_decode("tru\\t\\n")')
110    )
111
112    eq('Vim(call):E474: Expected false: f', pcall_err(command, 'call json_decode("f")'))
113    eq('Vim(call):E474: Expected false: fa', pcall_err(command, 'call json_decode("fa")'))
114    eq('Vim(call):E474: Expected false: fal', pcall_err(command, 'call json_decode("fal")'))
115    eq(
116      'Vim(call):E474: Expected false: fal   <',
117      pcall_err(command, 'call json_decode("   fal   <")')
118    )
119    eq('Vim(call):E474: Expected false: fals', pcall_err(command, 'call json_decode("fals")'))
120  end)
121
122  it('parses integer numbers', function()
123    eq(100000, fn.json_decode('100000'))
124    eq(-100000, fn.json_decode('-100000'))
125    eq(100000, fn.json_decode('  100000  '))
126    eq(-100000, fn.json_decode('  -100000  '))
127    eq(0, fn.json_decode('0'))
128    eq(0, fn.json_decode('-0'))
129  end)
130
131  it('fails to parse +numbers and .number', function()
132    eq('Vim(call):E474: Unidentified byte: +1000', pcall_err(command, 'call json_decode("+1000")'))
133    eq('Vim(call):E474: Unidentified byte: .1000', pcall_err(command, 'call json_decode(".1000")'))
134  end)
135
136  it('fails to parse numbers with leading zeroes', function()
137    eq(
138      'Vim(call):E474: Leading zeroes are not allowed: 00.1',
139      pcall_err(command, 'call json_decode("00.1")')
140    )
141    eq(
142      'Vim(call):E474: Leading zeroes are not allowed: 01',
143      pcall_err(command, 'call json_decode("01")')
144    )
145    eq(
146      'Vim(call):E474: Leading zeroes are not allowed: -01',
147      pcall_err(command, 'call json_decode("-01")')
148    )
149    eq(
150      'Vim(call):E474: Leading zeroes are not allowed: -001.0',
151      pcall_err(command, 'call json_decode("-001.0")')
152    )
153  end)
154
155  it('fails to parse incomplete numbers', function()
156    eq(
157      'Vim(call):E474: Missing number after minus sign: -.1',
158      pcall_err(command, 'call json_decode("-.1")')
159    )
160    eq(
161      'Vim(call):E474: Missing number after minus sign: -',
162      pcall_err(command, 'call json_decode("-")')
163    )
164    eq(
165      'Vim(call):E474: Missing number after decimal dot: -1.',
166      pcall_err(command, 'call json_decode("-1.")')
167    )
168    eq(
169      'Vim(call):E474: Missing number after decimal dot: 0.',
170      pcall_err(command, 'call json_decode("0.")')
171    )
172    eq('Vim(call):E474: Missing exponent: 0.0e', pcall_err(command, 'call json_decode("0.0e")'))
173    eq('Vim(call):E474: Missing exponent: 0.0e+', pcall_err(command, 'call json_decode("0.0e+")'))
174    eq('Vim(call):E474: Missing exponent: 0.0e-', pcall_err(command, 'call json_decode("0.0e-")'))
175    eq('Vim(call):E474: Missing exponent: 0.0e-', pcall_err(command, 'call json_decode("0.0e-")'))
176    eq(
177      'Vim(call):E474: Missing number after decimal dot: 1.e5',
178      pcall_err(command, 'call json_decode("1.e5")')
179    )
180    eq(
181      'Vim(call):E474: Missing number after decimal dot: 1.e+5',
182      pcall_err(command, 'call json_decode("1.e+5")')
183    )
184    eq(
185      'Vim(call):E474: Missing number after decimal dot: 1.e+',
186      pcall_err(command, 'call json_decode("1.e+")')
187    )
188  end)
189
190  it('parses floating-point numbers', function()
191    -- Also test method call (->) syntax
192    eq('100000.0', eval('"100000.0"->json_decode()->string()'))
193    eq(100000.5, fn.json_decode('100000.5'))
194    eq(-100000.5, fn.json_decode('-100000.5'))
195    eq(-100000.5e50, fn.json_decode('-100000.5e50'))
196    eq(100000.5e50, fn.json_decode('100000.5e50'))
197    eq(100000.5e50, fn.json_decode('100000.5e+50'))
198    eq(-100000.5e-50, fn.json_decode('-100000.5e-50'))
199    eq(100000.5e-50, fn.json_decode('100000.5e-50'))
200    eq(100000e-50, fn.json_decode('100000e-50'))
201    eq(0.5, fn.json_decode('0.5'))
202    eq(0.005, fn.json_decode('0.005'))
203    eq(0.005, fn.json_decode('0.00500'))
204    eq(0.5, fn.json_decode('0.00500e+002'))
205    eq(0.00005, fn.json_decode('0.00500e-002'))
206
207    eq(-0.0, fn.json_decode('-0.0'))
208    eq(-0.0, fn.json_decode('-0.0e0'))
209    eq(-0.0, fn.json_decode('-0.0e+0'))
210    eq(-0.0, fn.json_decode('-0.0e-0'))
211    eq(-0.0, fn.json_decode('-0e-0'))
212    eq(-0.0, fn.json_decode('-0e-2'))
213    eq(-0.0, fn.json_decode('-0e+2'))
214
215    eq(0.0, fn.json_decode('0.0'))
216    eq(0.0, fn.json_decode('0.0e0'))
217    eq(0.0, fn.json_decode('0.0e+0'))
218    eq(0.0, fn.json_decode('0.0e-0'))
219    eq(0.0, fn.json_decode('0e-0'))
220    eq(0.0, fn.json_decode('0e-2'))
221    eq(0.0, fn.json_decode('0e+2'))
222  end)
223
224  it('fails to parse numbers with spaces inside', function()
225    eq(
226      'Vim(call):E474: Missing number after minus sign: - 1000',
227      pcall_err(command, 'call json_decode("- 1000")')
228    )
229    eq(
230      'Vim(call):E474: Missing number after decimal dot: 0. ',
231      pcall_err(command, 'call json_decode("0. ")')
232    )
233    eq(
234      'Vim(call):E474: Missing number after decimal dot: 0. 0',
235      pcall_err(command, 'call json_decode("0. 0")')
236    )
237    eq('Vim(call):E474: Missing exponent: 0.0e 1', pcall_err(command, 'call json_decode("0.0e 1")'))
238    eq(
239      'Vim(call):E474: Missing exponent: 0.0e+ 1',
240      pcall_err(command, 'call json_decode("0.0e+ 1")')
241    )
242    eq(
243      'Vim(call):E474: Missing exponent: 0.0e- 1',
244      pcall_err(command, 'call json_decode("0.0e- 1")')
245    )
246  end)
247
248  it('fails to parse "," and ":"', function()
249    eq(
250      'Vim(call):E474: Comma not inside container: ,  ',
251      pcall_err(command, 'call json_decode("  ,  ")')
252    )
253    eq(
254      'Vim(call):E474: Colon not inside container: :  ',
255      pcall_err(command, 'call json_decode("  :  ")')
256    )
257  end)
258
259  it('parses empty containers', function()
260    eq({}, fn.json_decode('[]'))
261    eq('[]', eval('string(json_decode("[]"))'))
262  end)
263
264  it('fails to parse "[" and "{"', function()
265    eq('Vim(call):E474: Unexpected end of input: {', pcall_err(command, 'call json_decode("{")'))
266    eq('Vim(call):E474: Unexpected end of input: [', pcall_err(command, 'call json_decode("[")'))
267  end)
268
269  it('fails to parse "}" and "]"', function()
270    eq('Vim(call):E474: No container to close: ]', pcall_err(command, 'call json_decode("]")'))
271    eq('Vim(call):E474: No container to close: }', pcall_err(command, 'call json_decode("}")'))
272  end)
273
274  it('fails to parse containers which are closed by different brackets', function()
275    eq(
276      'Vim(call):E474: Closing dictionary with square bracket: ]',
277      pcall_err(command, 'call json_decode("{]")')
278    )
279    eq(
280      'Vim(call):E474: Closing list with curly bracket: }',
281      pcall_err(command, 'call json_decode("[}")')
282    )
283  end)
284
285  it('fails to parse concat inside container', function()
286    eq(
287      'Vim(call):E474: Expected comma before list item: []]',
288      pcall_err(command, 'call json_decode("[[][]]")')
289    )
290    eq(
291      'Vim(call):E474: Expected comma before list item: {}]',
292      pcall_err(command, 'call json_decode("[{}{}]")')
293    )
294    eq(
295      'Vim(call):E474: Expected comma before list item: ]',
296      pcall_err(command, 'call json_decode("[1 2]")')
297    )
298    eq(
299      'Vim(call):E474: Expected comma before dictionary key: ": 4}',
300      pcall_err(command, 'call json_decode("{\\"1\\": 2 \\"3\\": 4}")')
301    )
302    eq(
303      'Vim(call):E474: Expected colon before dictionary value: , "3" 4}',
304      pcall_err(command, 'call json_decode("{\\"1\\" 2, \\"3\\" 4}")')
305    )
306  end)
307
308  it('fails to parse containers with leading comma or colon', function()
309    eq('Vim(call):E474: Leading comma: ,}', pcall_err(command, 'call json_decode("{,}")'))
310    eq('Vim(call):E474: Leading comma: ,]', pcall_err(command, 'call json_decode("[,]")'))
311    eq(
312      'Vim(call):E474: Using colon not in dictionary: :]',
313      pcall_err(command, 'call json_decode("[:]")')
314    )
315    eq('Vim(call):E474: Unexpected colon: :}', pcall_err(command, 'call json_decode("{:}")'))
316  end)
317
318  it('fails to parse containers with trailing comma', function()
319    eq('Vim(call):E474: Trailing comma: ]', pcall_err(command, 'call json_decode("[1,]")'))
320    eq('Vim(call):E474: Trailing comma: }', pcall_err(command, 'call json_decode("{\\"1\\": 2,}")'))
321  end)
322
323  it('fails to parse dictionaries with missing value', function()
324    eq(
325      'Vim(call):E474: Expected value after colon: }',
326      pcall_err(command, 'call json_decode("{\\"1\\":}")')
327    )
328    eq('Vim(call):E474: Expected value: }', pcall_err(command, 'call json_decode("{\\"1\\"}")'))
329  end)
330
331  it('fails to parse containers with two commas or colons', function()
332    eq(
333      'Vim(call):E474: Duplicate comma: , "2": 2}',
334      pcall_err(command, 'call json_decode("{\\"1\\": 1,, \\"2\\": 2}")')
335    )
336    eq(
337      'Vim(call):E474: Duplicate comma: , "2", 2]',
338      pcall_err(command, 'call json_decode("[\\"1\\", 1,, \\"2\\", 2]")')
339    )
340    eq(
341      'Vim(call):E474: Duplicate colon: : 2}',
342      pcall_err(command, 'call json_decode("{\\"1\\": 1, \\"2\\":: 2}")')
343    )
344    eq(
345      'Vim(call):E474: Comma after colon: , 2}',
346      pcall_err(command, 'call json_decode("{\\"1\\": 1, \\"2\\":, 2}")')
347    )
348    eq(
349      'Vim(call):E474: Unexpected colon: : "2": 2}',
350      pcall_err(command, 'call json_decode("{\\"1\\": 1,: \\"2\\": 2}")')
351    )
352    eq(
353      'Vim(call):E474: Unexpected colon: :, "2": 2}',
354      pcall_err(command, 'call json_decode("{\\"1\\": 1:, \\"2\\": 2}")')
355    )
356  end)
357
358  it('fails to parse concat of two values', function()
359    eq('Vim(call):E474: Trailing characters: []', pcall_err(command, 'call json_decode("{}[]")'))
360  end)
361
362  it('parses containers', function()
363    eq({ 1 }, fn.json_decode('[1]'))
364    eq({ NIL, 1 }, fn.json_decode('[null, 1]'))
365    eq({ ['1'] = 2 }, fn.json_decode('{"1": 2}'))
366    eq(
367      { ['1'] = 2, ['3'] = { { ['4'] = { ['5'] = { {}, 1 } } } } },
368      fn.json_decode('{"1": 2, "3": [{"4": {"5": [[], 1]}}]}')
369    )
370  end)
371
372  it('fails to parse incomplete strings', function()
373    matches(
374      'Vim%(call%):E474: Expected string end:',
375      pcall_err(command, 'call json_decode("\\t\\"")')
376    )
377    matches(
378      'Vim%(call%):E474: Expected string end:',
379      pcall_err(command, 'call json_decode("\\t\\"abc")')
380    )
381    matches(
382      'Vim%(call%):E474: Unfinished escape sequence:',
383      pcall_err(command, 'call json_decode("\\t\\"abc\\\\")')
384    )
385    matches(
386      'Vim%(call%):E474: Unfinished unicode escape sequence:',
387      pcall_err(command, 'call json_decode("\\t\\"abc\\\\u")')
388    )
389    matches(
390      'Vim%(call%):E474: Unfinished unicode escape sequence:',
391      pcall_err(command, 'call json_decode("\\t\\"abc\\\\u0")')
392    )
393    matches(
394      'Vim%(call%):E474: Unfinished unicode escape sequence:',
395      pcall_err(command, 'call json_decode("\\t\\"abc\\\\u00")')
396    )
397    matches(
398      'Vim%(call%):E474: Unfinished unicode escape sequence:',
399      pcall_err(command, 'call json_decode("\\t\\"abc\\\\u000")')
400    )
401    eq(
402      'Vim(call):E474: Expected four hex digits after \\u: \\u"    ',
403      pcall_err(command, 'call json_decode("\\t\\"abc\\\\u\\"    ")')
404    )
405    eq(
406      'Vim(call):E474: Expected four hex digits after \\u: \\u0"    ',
407      pcall_err(command, 'call json_decode("\\t\\"abc\\\\u0\\"    ")')
408    )
409    eq(
410      'Vim(call):E474: Expected four hex digits after \\u: \\u00"    ',
411      pcall_err(command, 'call json_decode("\\t\\"abc\\\\u00\\"    ")')
412    )
413    eq(
414      'Vim(call):E474: Expected four hex digits after \\u: \\u000"    ',
415      pcall_err(command, 'call json_decode("\\t\\"abc\\\\u000\\"    ")')
416    )
417    matches(
418      'Vim%(call%):E474: Expected string end:',
419      pcall_err(command, 'call json_decode("\\t\\"abc\\\\u0000")')
420    )
421  end)
422
423  it('fails to parse unknown escape sequences', function()
424    eq(
425      'Vim(call):E474: Unknown escape sequence: \\a"',
426      pcall_err(command, 'call json_decode("\\t\\"\\\\a\\"")')
427    )
428  end)
429
430  it('parses strings properly', function()
431    eq('\n', fn.json_decode('"\\n"'))
432    eq('', fn.json_decode('""'))
433    eq('\\/"\t\b\n\r\f', fn.json_decode([["\\\/\"\t\b\n\r\f"]]))
434    eq('/a', fn.json_decode([["\/a"]]))
435    -- Unicode characters: 2-byte, 3-byte, 4-byte
436    eq(
437      {
438        '«',
439        'ફ',
440        '\240\144\128\128',
441      },
442      fn.json_decode({
443        '[',
444        '"«",',
445        '"ફ",',
446        '"\240\144\128\128"',
447        ']',
448      })
449    )
450  end)
451
452  it('fails on strings with invalid bytes', function()
453    eq(
454      'Vim(call):E474: Only UTF-8 strings allowed: \255"',
455      pcall_err(command, 'call json_decode("\\t\\"\\xFF\\"")')
456    )
457    eq(
458      'Vim(call):E474: ASCII control characters cannot be present inside string: ',
459      pcall_err(command, 'call json_decode(["\\"\\n\\""])')
460    )
461    -- 0xC2 starts 2-byte unicode character
462    eq(
463      'Vim(call):E474: Only UTF-8 strings allowed: \194"',
464      pcall_err(command, 'call json_decode("\\t\\"\\xC2\\"")')
465    )
466    -- 0xE0 0xAA starts 3-byte unicode character
467    eq(
468      'Vim(call):E474: Only UTF-8 strings allowed: \224"',
469      pcall_err(command, 'call json_decode("\\t\\"\\xE0\\"")')
470    )
471    eq(
472      'Vim(call):E474: Only UTF-8 strings allowed: \224\170"',
473      pcall_err(command, 'call json_decode("\\t\\"\\xE0\\xAA\\"")')
474    )
475    -- 0xF0 0x90 0x80 starts 4-byte unicode character
476    eq(
477      'Vim(call):E474: Only UTF-8 strings allowed: \240"',
478      pcall_err(command, 'call json_decode("\\t\\"\\xF0\\"")')
479    )
480    eq(
481      'Vim(call):E474: Only UTF-8 strings allowed: \240\144"',
482      pcall_err(command, 'call json_decode("\\t\\"\\xF0\\x90\\"")')
483    )
484    eq(
485      'Vim(call):E474: Only UTF-8 strings allowed: \240\144\128"',
486      pcall_err(command, 'call json_decode("\\t\\"\\xF0\\x90\\x80\\"")')
487    )
488    -- 0xF9 0x80 0x80 0x80 starts 5-byte unicode character
489    eq(
490      'Vim(call):E474: Only UTF-8 strings allowed: \249"',
491      pcall_err(command, 'call json_decode("\\t\\"\\xF9\\"")')
492    )
493    eq(
494      'Vim(call):E474: Only UTF-8 strings allowed: \249\128"',
495      pcall_err(command, 'call json_decode("\\t\\"\\xF9\\x80\\"")')
496    )
497    eq(
498      'Vim(call):E474: Only UTF-8 strings allowed: \249\128\128"',
499      pcall_err(command, 'call json_decode("\\t\\"\\xF9\\x80\\x80\\"")')
500    )
501    eq(
502      'Vim(call):E474: Only UTF-8 strings allowed: \249\128\128\128"',
503      pcall_err(command, 'call json_decode("\\t\\"\\xF9\\x80\\x80\\x80\\"")')
504    )
505    -- 0xFC 0x90 0x80 0x80 0x80 starts 6-byte unicode character
506    eq(
507      'Vim(call):E474: Only UTF-8 strings allowed: \252"',
508      pcall_err(command, 'call json_decode("\\t\\"\\xFC\\"")')
509    )
510    eq(
511      'Vim(call):E474: Only UTF-8 strings allowed: \252\144"',
512      pcall_err(command, 'call json_decode("\\t\\"\\xFC\\x90\\"")')
513    )
514    eq(
515      'Vim(call):E474: Only UTF-8 strings allowed: \252\144\128"',
516      pcall_err(command, 'call json_decode("\\t\\"\\xFC\\x90\\x80\\"")')
517    )
518    eq(
519      'Vim(call):E474: Only UTF-8 strings allowed: \252\144\128\128"',
520      pcall_err(command, 'call json_decode("\\t\\"\\xFC\\x90\\x80\\x80\\"")')
521    )
522    eq(
523      'Vim(call):E474: Only UTF-8 strings allowed: \252\144\128\128\128"',
524      pcall_err(command, 'call json_decode("\\t\\"\\xFC\\x90\\x80\\x80\\x80\\"")')
525    )
526    -- Specification does not allow unquoted characters above 0x10FFFF
527    eq(
528      'Vim(call):E474: Only UTF-8 code points up to U+10FFFF are allowed to appear unescaped: \249\128\128\128\128"',
529      pcall_err(command, 'call json_decode("\\t\\"\\xF9\\x80\\x80\\x80\\x80\\"")')
530    )
531    eq(
532      'Vim(call):E474: Only UTF-8 code points up to U+10FFFF are allowed to appear unescaped: \252\144\128\128\128\128"',
533      pcall_err(command, 'call json_decode("\\t\\"\\xFC\\x90\\x80\\x80\\x80\\x80\\"")')
534    )
535    -- '"\249\128\128\128\128"',
536    -- '"\252\144\128\128\128\128"',
537  end)
538
539  it('parses surrogate pairs properly', function()
540    eq('\240\144\128\128', fn.json_decode('"\\uD800\\uDC00"'))
541    eq('\237\160\128a\237\176\128', fn.json_decode('"\\uD800a\\uDC00"'))
542    eq('\237\160\128\t\237\176\128', fn.json_decode('"\\uD800\\t\\uDC00"'))
543
544    eq('\237\160\128', fn.json_decode('"\\uD800"'))
545    eq('\237\160\128a', fn.json_decode('"\\uD800a"'))
546    eq('\237\160\128\t', fn.json_decode('"\\uD800\\t"'))
547
548    eq('\237\176\128', fn.json_decode('"\\uDC00"'))
549    eq('\237\176\128a', fn.json_decode('"\\uDC00a"'))
550    eq('\237\176\128\t', fn.json_decode('"\\uDC00\\t"'))
551
552    eq('\237\176\128', fn.json_decode('"\\uDC00"'))
553    eq('a\237\176\128', fn.json_decode('"a\\uDC00"'))
554    eq('\t\237\176\128', fn.json_decode('"\\t\\uDC00"'))
555
556    eq('\237\160\128¬', fn.json_decode('"\\uD800\\u00AC"'))
557
558    eq('\237\160\128\237\160\128', fn.json_decode('"\\uD800\\uD800"'))
559  end)
560
561  local sp_decode_eq = function(expected, json)
562    api.nvim_set_var('__json', json)
563    speq(expected, 'json_decode(g:__json)')
564    command('unlet! g:__json')
565  end
566
567  it('parses strings with NUL properly', function()
568    sp_decode_eq('\000', '"\\u0000"')
569    sp_decode_eq('\000\n\000', '"\\u0000\\n\\u0000"')
570    sp_decode_eq('\000«\000', '"\\u0000\\u00AB\\u0000"')
571  end)
572
573  it('parses dictionaries with duplicate keys to special maps', function()
574    sp_decode_eq({ _TYPE = 'map', _VAL = { { 'a', 1 }, { 'a', 2 } } }, '{"a": 1, "a": 2}')
575    sp_decode_eq(
576      { _TYPE = 'map', _VAL = { { 'b', 3 }, { 'a', 1 }, { 'a', 2 } } },
577      '{"b": 3, "a": 1, "a": 2}'
578    )
579    sp_decode_eq(
580      { _TYPE = 'map', _VAL = { { 'b', 3 }, { 'a', 1 }, { 'c', 4 }, { 'a', 2 } } },
581      '{"b": 3, "a": 1, "c": 4, "a": 2}'
582    )
583    sp_decode_eq(
584      { _TYPE = 'map', _VAL = { { 'b', 3 }, { 'a', 1 }, { 'c', 4 }, { 'a', 2 }, { 'c', 4 } } },
585      '{"b": 3, "a": 1, "c": 4, "a": 2, "c": 4}'
586    )
587    sp_decode_eq(
588      { { _TYPE = 'map', _VAL = { { 'b', 3 }, { 'a', 1 }, { 'c', 4 }, { 'a', 2 }, { 'c', 4 } } } },
589      '[{"b": 3, "a": 1, "c": 4, "a": 2, "c": 4}]'
590    )
591    sp_decode_eq({
592      {
593        d = {
594          _TYPE = 'map',
595          _VAL = { { 'b', 3 }, { 'a', 1 }, { 'c', 4 }, { 'a', 2 }, { 'c', 4 } },
596        },
597      },
598    }, '[{"d": {"b": 3, "a": 1, "c": 4, "a": 2, "c": 4}}]')
599    sp_decode_eq({
600      1,
601      {
602        d = {
603          _TYPE = 'map',
604          _VAL = { { 'b', 3 }, { 'a', 1 }, { 'c', 4 }, { 'a', 2 }, { 'c', 4 } },
605        },
606      },
607    }, '[1, {"d": {"b": 3, "a": 1, "c": 4, "a": 2, "c": 4}}]')
608    sp_decode_eq({
609      1,
610      {
611        a = {},
612        d = {
613          _TYPE = 'map',
614          _VAL = {
615            { 'b', 3 },
616            { 'a', 1 },
617            { 'c', 4 },
618            { 'a', 2 },
619            {
620              'c',
621              4,
622            },
623          },
624        },
625      },
626    }, '[1, {"a": [], "d": {"b": 3, "a": 1, "c": 4, "a": 2, "c": 4}}]')
627    sp_decode_eq(
628      { _TYPE = 'map', _VAL = { { '', 3 }, { 'a', 1 }, { 'c', 4 }, { 'd', 2 }, { '', 4 } } },
629      '{"": 3, "a": 1, "c": 4, "d": 2, "": 4}'
630    )
631    sp_decode_eq(
632      { { _TYPE = 'map', _VAL = { { '', 3 }, { 'a', 1 }, { 'c', 4 }, { 'd', 2 }, { '', 4 } } } },
633      '[{"": 3, "a": 1, "c": 4, "d": 2, "": 4}]'
634    )
635  end)
636
637  it('parses dictionaries with empty keys', function()
638    eq({ [''] = 4 }, fn.json_decode('{"": 4}'))
639    eq(
640      { b = 3, a = 1, c = 4, d = 2, [''] = 4 },
641      fn.json_decode('{"b": 3, "a": 1, "c": 4, "d": 2, "": 4}')
642    )
643  end)
644
645  it('parses dictionaries with keys with NUL bytes to special maps', function()
646    sp_decode_eq({ _TYPE = 'map', _VAL = { { 'a\000\nb', 4 } } }, '{"a\\u0000\\nb": 4}')
647    sp_decode_eq({ _TYPE = 'map', _VAL = { { 'a\000\nb\n', 4 } } }, '{"a\\u0000\\nb\\n": 4}')
648    sp_decode_eq({
649      _TYPE = 'map',
650      _VAL = {
651        { 'b', 3 },
652        { 'a', 1 },
653        { 'c', 4 },
654        { 'd', 2 },
655        { '\000', 4 },
656      },
657    }, '{"b": 3, "a": 1, "c": 4, "d": 2, "\\u0000": 4}')
658  end)
659
660  it('parses U+00C3 correctly', function()
661    eq('\195\131', fn.json_decode('"\195\131"'))
662  end)
663
664  it('fails to parse empty string', function()
665    eq(
666      'Vim(call):E474: Attempt to decode a blank string',
667      pcall_err(command, 'call json_decode("")')
668    )
669    eq(
670      'Vim(call):E474: Attempt to decode a blank string',
671      pcall_err(command, 'call json_decode([])')
672    )
673    eq(
674      'Vim(call):E474: Attempt to decode a blank string',
675      pcall_err(command, 'call json_decode([""])')
676    )
677    eq(
678      'Vim(call):E474: Attempt to decode a blank string',
679      pcall_err(command, 'call json_decode(" ")')
680    )
681    eq(
682      'Vim(call):E474: Attempt to decode a blank string',
683      pcall_err(command, 'call json_decode("\\t")')
684    )
685    eq(
686      'Vim(call):E474: Attempt to decode a blank string',
687      pcall_err(command, 'call json_decode("\\n")')
688    )
689    eq(
690      'Vim(call):E474: Attempt to decode a blank string',
691      pcall_err(command, 'call json_decode(" \\t\\n \\n\\t\\t \\n\\t\\n \\n \\t\\n\\t ")')
692    )
693  end)
694
695  it('accepts all spaces in every position where space may be put', function()
696    local s =
697      ' \t\n\r \t\r\n \n\t\r \n\r\t \r\t\n \r\n\t\t \n\r\t \r\n\t\n \r\t\n\r \t\r \n\t\r\n \n \t\r\n \r\t\n\t \r\n\t\r \n\r \t\n\r\t \r \t\n\r \n\t\r\t \n\r\t\n \r\n \t\r\n\t'
698    local str = ('%s{%s"key"%s:%s[%s"val"%s,%s"val2"%s]%s,%s"key2"%s:%s1%s}%s'):gsub('%%s', s)
699    eq({ key = { 'val', 'val2' }, key2 = 1 }, fn.json_decode(str))
700  end)
701
702  it('does not overflow when writing error message about decoding ["", ""]', function()
703    eq(
704      'Vim(call):E474: Attempt to decode a blank string',
705      pcall_err(command, 'call json_decode(["", ""])')
706    )
707  end)
708end)
709
710describe('json_encode() function', function()
711  setup(function()
712    clear()
713    command('language C')
714  end)
715
716  it('dumps strings', function()
717    eq('"Test"', fn.json_encode('Test'))
718    eq('""', fn.json_encode(''))
719    eq('"\\t"', fn.json_encode('\t'))
720    eq('"\\n"', fn.json_encode('\n'))
721    eq('"\\u001B"', fn.json_encode('\27'))
722    eq('"þÿþ"', fn.json_encode('þÿþ'))
723  end)
724
725  it('dumps blobs', function()
726    eq('[]', eval('json_encode(0z)'))
727    eq('[222, 173, 190, 239]', eval('json_encode(0zDEADBEEF)'))
728  end)
729
730  it('dumps numbers', function()
731    eq('0', fn.json_encode(0))
732    eq('10', fn.json_encode(10))
733    eq('-10', fn.json_encode(-10))
734  end)
735
736  it('dumps floats', function()
737    -- Also test method call (->) syntax
738    eq('0.0', eval('0.0->json_encode()'))
739    eq('10.5', fn.json_encode(10.5))
740    eq('-10.5', fn.json_encode(-10.5))
741    eq('-1.0e-5', fn.json_encode(-1e-5))
742    eq('1.0e50', eval('1.0e50->json_encode()'))
743  end)
744
745  it('fails to dump NaN and infinite values', function()
746    eq(
747      'Vim(call):E474: Unable to represent NaN value in JSON',
748      pcall_err(command, 'call json_encode(str2float("nan"))')
749    )
750    eq(
751      'Vim(call):E474: Unable to represent infinity in JSON',
752      pcall_err(command, 'call json_encode(str2float("inf"))')
753    )
754    eq(
755      'Vim(call):E474: Unable to represent infinity in JSON',
756      pcall_err(command, 'call json_encode(-str2float("inf"))')
757    )
758  end)
759
760  it('dumps lists', function()
761    eq('[]', fn.json_encode({}))
762    eq('[[]]', fn.json_encode({ {} }))
763    eq('[[], []]', fn.json_encode({ {}, {} }))
764  end)
765
766  it('dumps dictionaries', function()
767    eq('{}', eval('json_encode({})'))
768    eq('{"d": []}', fn.json_encode({ d = {} }))
769    eq('{"d": [], "e": []}', fn.json_encode({ d = {}, e = {} }))
770    -- Empty keys are allowed per JSON spec (and Vim dicts, and msgpack).
771    eq('{"": []}', fn.json_encode({ [''] = {} }))
772  end)
773
774  it('cannot dump generic mapping with generic mapping keys and values', function()
775    command('let todump = {"_TYPE": v:msgpack_types.map, "_VAL": []}')
776    command('let todumpv1 = {"_TYPE": v:msgpack_types.map, "_VAL": []}')
777    command('let todumpv2 = {"_TYPE": v:msgpack_types.map, "_VAL": []}')
778    command('call add(todump._VAL, [todumpv1, todumpv2])')
779    eq(
780      'Vim(call):E474: Invalid key in special dictionary',
781      pcall_err(command, 'call json_encode(todump)')
782    )
783  end)
784
785  it('cannot dump generic mapping with ext key', function()
786    command('let todump = {"_TYPE": v:msgpack_types.ext, "_VAL": [5, ["",""]]}')
787    command('let todump = {"_TYPE": v:msgpack_types.map, "_VAL": [[todump, 1]]}')
788    eq(
789      'Vim(call):E474: Invalid key in special dictionary',
790      pcall_err(command, 'call json_encode(todump)')
791    )
792  end)
793
794  it('cannot dump generic mapping with array key', function()
795    command('let todump = {"_TYPE": v:msgpack_types.array, "_VAL": [5, [""]]}')
796    command('let todump = {"_TYPE": v:msgpack_types.map, "_VAL": [[todump, 1]]}')
797    eq(
798      'Vim(call):E474: Invalid key in special dictionary',
799      pcall_err(command, 'call json_encode(todump)')
800    )
801  end)
802
803  it('cannot dump generic mapping with UINT64_MAX key', function()
804    command('let todump = {"_TYPE": v:msgpack_types.integer}')
805    command('let todump._VAL = [1, 3, 0x7FFFFFFF, 0x7FFFFFFF]')
806    command('let todump = {"_TYPE": v:msgpack_types.map, "_VAL": [[todump, 1]]}')
807    eq(
808      'Vim(call):E474: Invalid key in special dictionary',
809      pcall_err(command, 'call json_encode(todump)')
810    )
811  end)
812
813  it('cannot dump generic mapping with floating-point key', function()
814    command('let todump = {"_TYPE": v:msgpack_types.float, "_VAL": 0.125}')
815    command('let todump = {"_TYPE": v:msgpack_types.map, "_VAL": [[todump, 1]]}')
816    eq(
817      'Vim(call):E474: Invalid key in special dictionary',
818      pcall_err(command, 'call json_encode(todump)')
819    )
820  end)
821
822  it('can dump generic mapping with STR special key and NUL', function()
823    command('let todump = {"_TYPE": v:msgpack_types.string, "_VAL": ["\\n"]}')
824    command('let todump = {"_TYPE": v:msgpack_types.map, "_VAL": [[todump, 1]]}')
825    eq('{"\\u0000": 1}', eval('json_encode(todump)'))
826  end)
827
828  it('can dump STR special mapping with NUL and NL', function()
829    command('let todump = {"_TYPE": v:msgpack_types.string, "_VAL": ["\\n", ""]}')
830    eq('"\\u0000\\n"', eval('json_encode(todump)'))
831  end)
832
833  it('cannot dump special ext mapping', function()
834    command('let todump = {"_TYPE": v:msgpack_types.ext, "_VAL": [5, ["",""]]}')
835    eq(
836      'Vim(call):E474: Unable to convert EXT string to JSON',
837      pcall_err(command, 'call json_encode(todump)')
838    )
839  end)
840
841  it('can dump special array mapping', function()
842    command('let todump = {"_TYPE": v:msgpack_types.array, "_VAL": [5, [""]]}')
843    eq('[5, [""]]', eval('json_encode(todump)'))
844  end)
845
846  it('can dump special UINT64_MAX mapping', function()
847    command('let todump = {"_TYPE": v:msgpack_types.integer}')
848    command('let todump._VAL = [1, 3, 0x7FFFFFFF, 0x7FFFFFFF]')
849    eq('18446744073709551615', eval('json_encode(todump)'))
850  end)
851
852  it('can dump special INT64_MIN mapping', function()
853    command('let todump = {"_TYPE": v:msgpack_types.integer}')
854    command('let todump._VAL = [-1, 2, 0, 0]')
855    eq('-9223372036854775808', eval('json_encode(todump)'))
856  end)
857
858  it('can dump special BOOLEAN true mapping', function()
859    command('let todump = {"_TYPE": v:msgpack_types.boolean, "_VAL": 1}')
860    eq('true', eval('json_encode(todump)'))
861  end)
862
863  it('can dump special BOOLEAN false mapping', function()
864    command('let todump = {"_TYPE": v:msgpack_types.boolean, "_VAL": 0}')
865    eq('false', eval('json_encode(todump)'))
866  end)
867
868  it('can dump special NIL mapping', function()
869    command('let todump = {"_TYPE": v:msgpack_types.nil, "_VAL": 0}')
870    eq('null', eval('json_encode(todump)'))
871  end)
872
873  it('fails to dump a function reference', function()
874    eq(
875      'Vim(call):E474: Error while dumping encode_tv2json() argument, itself: attempt to dump function reference',
876      pcall_err(command, 'call json_encode(function("tr"))')
877    )
878  end)
879
880  it('fails to dump a partial', function()
881    command('function T() dict\nendfunction')
882    eq(
883      'Vim(call):E474: Error while dumping encode_tv2json() argument, itself: attempt to dump function reference',
884      pcall_err(command, 'call json_encode(function("T", [1, 2], {}))')
885    )
886  end)
887
888  it('fails to dump a function reference in a list', function()
889    eq(
890      'Vim(call):E474: Error while dumping encode_tv2json() argument, index 0: attempt to dump function reference',
891      pcall_err(command, 'call json_encode([function("tr")])')
892    )
893  end)
894
895  it('fails to dump a recursive list', function()
896    command('let todump = [[[]]]')
897    command('call add(todump[0][0], todump)')
898    eq(
899      'Vim(call):E724: unable to correctly dump variable with self-referencing container',
900      pcall_err(command, 'call json_encode(todump)')
901    )
902  end)
903
904  it('fails to dump a recursive dict', function()
905    command('let todump = {"d": {"d": {}}}')
906    command('call extend(todump.d.d, {"d": todump})')
907    eq(
908      'Vim(call):E724: unable to correctly dump variable with self-referencing container',
909      pcall_err(command, 'call json_encode([todump])')
910    )
911  end)
912
913  it('can dump dict with two same dicts inside', function()
914    command('let inter = {}')
915    command('let todump = {"a": inter, "b": inter}')
916    eq('{"a": {}, "b": {}}', eval('json_encode(todump)'))
917  end)
918
919  it('can dump list with two same lists inside', function()
920    command('let inter = []')
921    command('let todump = [inter, inter]')
922    eq('[[], []]', eval('json_encode(todump)'))
923  end)
924
925  it('fails to dump a recursive list in a special dict', function()
926    command('let todump = {"_TYPE": v:msgpack_types.array, "_VAL": []}')
927    command('call add(todump._VAL, todump)')
928    eq(
929      'Vim(call):E724: unable to correctly dump variable with self-referencing container',
930      pcall_err(command, 'call json_encode(todump)')
931    )
932  end)
933
934  it('fails to dump a recursive (val) map in a special dict', function()
935    command('let todump = {"_TYPE": v:msgpack_types.map, "_VAL": []}')
936    command('call add(todump._VAL, ["", todump])')
937    eq(
938      'Vim(call):E724: unable to correctly dump variable with self-referencing container',
939      pcall_err(command, 'call json_encode([todump])')
940    )
941  end)
942
943  it('fails to dump a recursive (val) map in a special dict, _VAL reference', function()
944    command('let todump = {"_TYPE": v:msgpack_types.map, "_VAL": [["", []]]}')
945    command('call add(todump._VAL[0][1], todump._VAL)')
946    eq(
947      'Vim(call):E724: unable to correctly dump variable with self-referencing container',
948      pcall_err(command, 'call json_encode(todump)')
949    )
950  end)
951
952  it('fails to dump a recursive (val) special list in a special dict', function()
953    command('let todump = {"_TYPE": v:msgpack_types.array, "_VAL": []}')
954    command('call add(todump._VAL, ["", todump._VAL])')
955    eq(
956      'Vim(call):E724: unable to correctly dump variable with self-referencing container',
957      pcall_err(command, 'call json_encode(todump)')
958    )
959  end)
960
961  it('fails when called with no arguments', function()
962    eq(
963      'Vim(call):E119: Not enough arguments for function: json_encode',
964      pcall_err(command, 'call json_encode()')
965    )
966  end)
967
968  it('fails when called with two arguments', function()
969    eq(
970      'Vim(call):E118: Too many arguments for function: json_encode',
971      pcall_err(command, 'call json_encode(["", ""], 1)')
972    )
973  end)
974
975  it('fails when using surrogate character in a UTF-8 string', function()
976    eq(
977      'Vim(call):E474: UTF-8 string contains code point which belongs to a surrogate pair: \237\160\128',
978      pcall_err(command, 'call json_encode("\237\160\128")')
979    )
980    eq(
981      'Vim(call):E474: UTF-8 string contains code point which belongs to a surrogate pair: \237\175\191',
982      pcall_err(command, 'call json_encode("\237\175\191")')
983    )
984  end)
985
986  it('dumps control characters as expected', function()
987    eq(
988      [["\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000B\f\r\u000E\u000F\u0010\u0011\u0012\u0013"]],
989      eval(
990        'json_encode({"_TYPE": v:msgpack_types.string, "_VAL": ["\n\1\2\3\4\5\6\7\8\9", "\11\12\13\14\15\16\17\18\19"]})'
991      )
992    )
993  end)
994
995  it('can dump NULL string', function()
996    eq('""', eval('json_encode($XXX_UNEXISTENT_VAR_XXX)'))
997  end)
998
999  it('can dump NULL blob', function()
1000    eq('[]', eval('json_encode(v:_null_blob)'))
1001  end)
1002
1003  it('can dump NULL list', function()
1004    eq('[]', eval('json_encode(v:_null_list)'))
1005  end)
1006
1007  it('can dump NULL dict', function()
1008    eq('{}', eval('json_encode(v:_null_dict)'))
1009  end)
1010
1011  it('fails to parse NULL strings and lists', function()
1012    eq(
1013      'Vim(call):E474: Attempt to decode a blank string',
1014      pcall_err(command, 'call json_decode($XXX_UNEXISTENT_VAR_XXX)')
1015    )
1016    eq(
1017      'Vim(call):E474: Attempt to decode a blank string',
1018      pcall_err(command, 'call json_decode(v:_null_list)')
1019    )
1020  end)
1021end)