robin/laufey

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

Justin M. KeyesMerge #40865 from justinmk/fixcif907614088

master
13.7 KiB402 linesraw
1local t = require('test.testutil')
2local n = require('test.functional.testnvim')()
3
4local describe, it, setup = t.describe, t.it, t.setup
5local eq = t.eq
6local pcall_err = t.pcall_err
7local NIL = vim.NIL
8local eval = n.eval
9local clear = n.clear
10local api = n.api
11local fn = n.fn
12local source = n.source
13local dedent = t.dedent
14local command = n.command
15local exec_capture = n.exec_capture
16local matches = t.matches
17
18describe(':echo :echon :echomsg :echoerr', function()
19  local fn_tbl = { 'String', 'StringN', 'StringMsg', 'StringErr' }
20  local function assert_same_echo_dump(expected, input, use_eval)
21    for _, v in pairs(fn_tbl) do
22      eq(expected, use_eval and eval(v .. '(' .. input .. ')') or fn[v](input))
23    end
24  end
25  local function assert_matches_echo_dump(expected, input, use_eval)
26    for _, v in pairs(fn_tbl) do
27      matches(expected, use_eval and eval(v .. '(' .. input .. ')') or fn[v](input))
28    end
29  end
30
31  setup(function()
32    clear()
33    source([[
34      function String(s)
35        return execute('echo a:s')[1:]
36      endfunction
37      function StringMsg(s)
38        return execute('echomsg a:s')[1:]
39      endfunction
40      function StringN(s)
41        return execute('echon a:s')
42      endfunction
43      function StringErr(s)
44        try
45          execute 'echoerr a:s'
46        catch
47          return substitute(v:exception, '^Vim(echoerr):', '', '')
48        endtry
49      endfunction
50    ]])
51  end)
52
53  describe('used to represent floating-point values', function()
54    it('dumps NaN values', function()
55      assert_same_echo_dump("str2float('nan')", "str2float('nan')", true)
56    end)
57
58    it('dumps infinite values', function()
59      assert_same_echo_dump("str2float('inf')", "str2float('inf')", true)
60      assert_same_echo_dump("-str2float('inf')", "str2float('-inf')", true)
61    end)
62
63    it('dumps regular values', function()
64      assert_same_echo_dump('1.5', 1.5)
65      assert_same_echo_dump('1.56e-20', 1.56000e-020)
66      assert_same_echo_dump('0.0', '0.0', true)
67    end)
68
69    it('dumps special v: values', function()
70      eq('v:true', eval('String(v:true)'))
71      eq('v:false', eval('String(v:false)'))
72      eq('v:null', eval('String(v:null)'))
73      eq('v:true', fn.String(true))
74      eq('v:false', fn.String(false))
75      eq('v:null', fn.String(NIL))
76      eq('v:true', eval('StringMsg(v:true)'))
77      eq('v:false', eval('StringMsg(v:false)'))
78      eq('v:null', eval('StringMsg(v:null)'))
79      eq('v:true', fn.StringMsg(true))
80      eq('v:false', fn.StringMsg(false))
81      eq('v:null', fn.StringMsg(NIL))
82      eq('v:true', eval('StringErr(v:true)'))
83      eq('v:false', eval('StringErr(v:false)'))
84      eq('v:null', eval('StringErr(v:null)'))
85      eq('v:true', fn.StringErr(true))
86      eq('v:false', fn.StringErr(false))
87      eq('v:null', fn.StringErr(NIL))
88    end)
89
90    it('dumps values with at most six digits after the decimal point', function()
91      assert_same_echo_dump('1.234568e-20', 1.23456789123456789123456789e-020)
92      assert_same_echo_dump('1.234568', 1.23456789123456789123456789)
93    end)
94
95    it('dumps values with at most seven digits before the decimal point', function()
96      assert_same_echo_dump('1234567.891235', 1234567.89123456789123456789)
97      assert_same_echo_dump('1.234568e7', 12345678.9123456789123456789)
98    end)
99
100    it('dumps negative values', function()
101      assert_same_echo_dump('-1.5', -1.5)
102      assert_same_echo_dump('-1.56e-20', -1.56000e-020)
103      assert_same_echo_dump('-1.234568e-20', -1.23456789123456789123456789e-020)
104      assert_same_echo_dump('-1.234568', -1.23456789123456789123456789)
105      assert_same_echo_dump('-1234567.891235', -1234567.89123456789123456789)
106      assert_same_echo_dump('-1.234568e7', -12345678.9123456789123456789)
107    end)
108  end)
109
110  describe('used to represent numbers', function()
111    it('dumps regular values', function()
112      assert_same_echo_dump('0', 0)
113      assert_same_echo_dump('-1', -1)
114      assert_same_echo_dump('1', 1)
115    end)
116
117    it('dumps large values', function()
118      assert_same_echo_dump('2147483647', 2 ^ 31 - 1)
119      assert_same_echo_dump('-2147483648', -2 ^ 31)
120    end)
121  end)
122
123  describe('used to represent strings', function()
124    it('dumps regular strings', function()
125      assert_same_echo_dump('test', 'test')
126    end)
127
128    it('dumps empty strings', function()
129      assert_same_echo_dump('', '')
130    end)
131
132    it("dumps strings with ' inside", function()
133      assert_same_echo_dump("'''", "'''")
134      assert_same_echo_dump("a'b''", "a'b''")
135      assert_same_echo_dump("'b''d", "'b''d")
136      assert_same_echo_dump("a'b'c'd", "a'b'c'd")
137    end)
138
139    it('dumps NULL strings', function()
140      assert_same_echo_dump('', '$XXX_UNEXISTENT_VAR_XXX', true)
141    end)
142
143    it('dumps NULL lists', function()
144      assert_same_echo_dump('[]', 'v:_null_list', true)
145    end)
146
147    it('dumps NULL dictionaries', function()
148      assert_same_echo_dump('{}', 'v:_null_dict', true)
149    end)
150  end)
151
152  describe('used to represent funcrefs', function()
153    setup(function()
154      source([[
155        function Test1()
156        endfunction
157
158        function s:Test2() dict
159        endfunction
160
161        function g:Test3() dict
162        endfunction
163
164        let g:Test2_f = function('s:Test2')
165      ]])
166    end)
167
168    it('dumps references to built-in functions', function()
169      eq('function', eval('String(function("function"))'))
170      eq("function('function')", eval('StringMsg(function("function"))'))
171      eq("function('function')", eval('StringErr(function("function"))'))
172    end)
173
174    it('dumps references to user functions', function()
175      eq('Test1', eval('String(function("Test1"))'))
176      eq('g:Test3', eval('String(function("g:Test3"))'))
177      eq("function('Test1')", eval("StringMsg(function('Test1'))"))
178      eq("function('g:Test3')", eval("StringMsg(function('g:Test3'))"))
179      eq("function('Test1')", eval("StringErr(function('Test1'))"))
180      eq("function('g:Test3')", eval("StringErr(function('g:Test3'))"))
181    end)
182
183    it('dumps references to script functions', function()
184      eq('<SNR>1_Test2', eval('String(Test2_f)'))
185      eq("function('<SNR>1_Test2')", eval('StringMsg(Test2_f)'))
186      eq("function('<SNR>1_Test2')", eval('StringErr(Test2_f)'))
187    end)
188
189    it('dump references to lambdas', function()
190      assert_matches_echo_dump("function%('<lambda>%d+'%)", '{-> 1234}', true)
191    end)
192
193    it('dumps partials with self referencing a partial', function()
194      source([[
195        function TestDict() dict
196        endfunction
197        let d = {}
198        let TestDictRef = function('TestDict', d)
199        let d.tdr = TestDictRef
200      ]])
201      eq(
202        dedent([[
203          function('TestDict', {'tdr': function('TestDict', {...@1})})]]),
204        exec_capture('echo String(d.tdr)')
205      )
206    end)
207
208    it('dumps automatically created partials', function()
209      assert_same_echo_dump(
210        "function('<SNR>1_Test2', {'f': function('<SNR>1_Test2')})",
211        '{"f": Test2_f}.f',
212        true
213      )
214      assert_same_echo_dump(
215        "function('<SNR>1_Test2', [1], {'f': function('<SNR>1_Test2', [1])})",
216        '{"f": function(Test2_f, [1])}.f',
217        true
218      )
219    end)
220
221    it('dumps manually created partials', function()
222      assert_same_echo_dump("function('Test3', [1, 2], {})", "function('Test3', [1, 2], {})", true)
223      assert_same_echo_dump("function('Test3', [1, 2])", "function('Test3', [1, 2])", true)
224      assert_same_echo_dump("function('Test3', {})", "function('Test3', {})", true)
225    end)
226
227    it('does not crash or halt when dumping partials with reference cycles in self', function()
228      api.nvim_set_var('d', { v = true })
229      eq(
230        dedent(
231          [[
232          {'p': function('<SNR>1_Test2', {...@0}), 'f': function('<SNR>1_Test2'), 'v': v:true}]]
233        ),
234        exec_capture('echo String(extend(extend(g:d, {"f": g:Test2_f}), {"p": g:d.f}))')
235      )
236    end)
237
238    it('does not show errors when dumping partials referencing the same dictionary', function()
239      command('let d = {}')
240      -- Regression for “eval/typval_encode: Dump empty dictionary before
241      -- checking for refcycle”, results in error.
242      eq(
243        "[function('tr', {}), function('tr', {})]",
244        eval('String([function("tr", d), function("tr", d)])')
245      )
246      -- Regression for “eval: Work with reference cycles in partials (self)
247      -- properly”, results in crash.
248      eval('extend(d, {"a": 1})')
249      eq(
250        "[function('tr', {'a': 1}), function('tr', {'a': 1})]",
251        eval('String([function("tr", d), function("tr", d)])')
252      )
253    end)
254
255    it('does not crash or halt when dumping partials with reference cycles in arguments', function()
256      api.nvim_set_var('l', {})
257      eval('add(l, l)')
258      -- Regression: the below line used to crash (add returns original list and
259      -- there was error in dumping partials). Tested explicitly in
260      -- test/unit/api/private_helpers_spec.lua.
261      eval('add(l, function("Test1", l))')
262      eq(
263        dedent(
264          [=[
265          function('Test1', [[[...@2], function('Test1', [[...@2]])], function('Test1', [[[...@4], function('Test1', [[...@4]])]])])]=]
266        ),
267        exec_capture('echo String(function("Test1", l))')
268      )
269    end)
270
271    it(
272      'does not crash or halt when dumping partials with reference cycles in self and arguments',
273      function()
274        api.nvim_set_var('d', { v = true })
275        api.nvim_set_var('l', {})
276        eval('add(l, l)')
277        eval('add(l, function("Test1", l))')
278        eval('add(l, function("Test1", d))')
279        eq(
280          dedent(
281            [=[
282          {'p': function('<SNR>1_Test2', [[[...@3], function('Test1', [[...@3]]), function('Test1', {...@0})], function('Test1', [[[...@5], function('Test1', [[...@5]]), function('Test1', {...@0})]]), function('Test1', {...@0})], {...@0}), 'f': function('<SNR>1_Test2'), 'v': v:true}]=]
283          ),
284          exec_capture(
285            'echo String(extend(extend(g:d, {"f": g:Test2_f}), {"p": function(g:d.f, l)}))'
286          )
287        )
288      end
289    )
290  end)
291
292  describe('used to represent lists', function()
293    it('dumps empty list', function()
294      assert_same_echo_dump('[]', {})
295    end)
296
297    it('dumps non-empty list', function()
298      assert_same_echo_dump('[1, 2]', { 1, 2 })
299    end)
300
301    it('dumps nested lists', function()
302      assert_same_echo_dump('[[[[[]]]]]', { { { { {} } } } })
303    end)
304
305    it('dumps nested non-empty lists', function()
306      assert_same_echo_dump('[1, [[3, [[5], 4]], 2]]', { 1, { { 3, { { 5 }, 4 } }, 2 } })
307    end)
308
309    it('does not error when dumping recursive lists', function()
310      api.nvim_set_var('l', {})
311      eval('add(l, l)')
312      command('echo String(l)')
313    end)
314
315    it('dumps recursive lists without error', function()
316      api.nvim_set_var('l', {})
317      eval('add(l, l)')
318      eq('[[...@0]]', exec_capture('echo String(l)'))
319      eq('[[[...@1]]]', exec_capture('echo String([l])'))
320    end)
321  end)
322
323  describe('used to represent dictionaries', function()
324    it('dumps empty dictionary', function()
325      assert_same_echo_dump('{}', '{}', true)
326    end)
327
328    it('dumps list with two same empty dictionaries, also in partials', function()
329      command('let d = {}')
330      assert_same_echo_dump('[{}, {}]', '[d, d]', true)
331      eq("[function('tr', {}), {}]", eval('String([function("tr", d), d])'))
332      eq("[{}, function('tr', {})]", eval('String([d, function("tr", d)])'))
333    end)
334
335    it('dumps non-empty dictionary', function()
336      assert_same_echo_dump("{'t''est': 1}", { ["t'est"] = 1 })
337    end)
338
339    it('does not error when dumping recursive dictionaries', function()
340      api.nvim_set_var('d', { d = 1 })
341      eval('extend(d, {"d": d})')
342      command('echo String(d)')
343    end)
344
345    it('dumps recursive dictionaries without the error', function()
346      api.nvim_set_var('d', { d = 1 })
347      eval('extend(d, {"d": d})')
348      eq("{'d': {...@0}}", exec_capture('echo String(d)'))
349      eq("{'out': {'d': {...@1}}}", exec_capture('echo String({"out": d})'))
350    end)
351  end)
352
353  describe('used to represent special values', function()
354    local function chr(_n)
355      return ('%c'):format(_n)
356    end
357    local function ctrl(c)
358      return ('%c'):format(c:upper():byte() - 0x40)
359    end
360    it('displays hex as hex', function()
361      -- Regression: due to missing (uint8_t) cast \x80 was represented as
362      -- ~@<80>.
363      eq('<80>', fn.String(chr(0x80)))
364      eq('<81>', fn.String(chr(0x81)))
365      eq('<8e>', fn.String(chr(0x8e)))
366      eq('<c2>', fn.String(('«'):sub(1, 1)))
367      eq('«', fn.String(('«'):sub(1, 2)))
368
369      eq('<80>', fn.StringMsg(chr(0x80)))
370      eq('<81>', fn.StringMsg(chr(0x81)))
371      eq('<8e>', fn.StringMsg(chr(0x8e)))
372      eq('<c2>', fn.StringMsg(('«'):sub(1, 1)))
373      eq('«', fn.StringMsg(('«'):sub(1, 2)))
374    end)
375    it('displays ASCII control characters using ^X notation', function()
376      eq('^C', fn.String(ctrl('c')))
377      eq('^A', fn.String(ctrl('a')))
378      eq('^F', fn.String(ctrl('f')))
379      eq('^C', fn.StringMsg(ctrl('c')))
380      eq('^A', fn.StringMsg(ctrl('a')))
381      eq('^F', fn.StringMsg(ctrl('f')))
382    end)
383    it('prints CR, NL and tab as-is', function()
384      eq('\n', fn.String('\n'))
385      eq('\r', fn.String('\r'))
386      eq('\t', fn.String('\t'))
387    end)
388    it('prints non-printable UTF-8 in <> notation', function()
389      -- SINGLE SHIFT TWO, unicode control
390      eq('<8e>', fn.String(fn.nr2char(0x8E)))
391      eq('<8e>', fn.StringMsg(fn.nr2char(0x8E)))
392      -- Surrogate pair: U+1F0A0 PLAYING CARD BACK is represented in UTF-16 as
393      -- 0xD83C 0xDCA0. This is not valid in UTF-8.
394      eq('<d83c>', fn.String(fn.nr2char(0xD83C)))
395      eq('<dca0>', fn.String(fn.nr2char(0xDCA0)))
396      eq('<d83c><dca0>', fn.String(fn.nr2char(0xD83C) .. fn.nr2char(0xDCA0)))
397      eq('<d83c>', fn.StringMsg(fn.nr2char(0xD83C)))
398      eq('<dca0>', fn.StringMsg(fn.nr2char(0xDCA0)))
399      eq('<d83c><dca0>', fn.StringMsg(fn.nr2char(0xD83C) .. fn.nr2char(0xDCA0)))
400    end)
401  end)
402end)