robin/laufey

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

Justin M. KeyesMerge #40865 from justinmk/fixcif907614088

master
17.5 KiB582 linesraw
1local t = require('test.testutil')
2local n = require('test.functional.testnvim')()
3
4local describe, it, before_each, after_each = t.describe, t.it, t.before_each, t.after_each
5local assert_alive = n.assert_alive
6local clear, source = n.clear, n.source
7local api = n.api
8local insert = n.insert
9local eq, next_msg = t.eq, n.next_msg
10local matches = t.matches
11local exec_lua = n.exec_lua
12local command = n.command
13local eval = n.eval
14local pcall_err = t.pcall_err
15
16describe('Vimscript dictionary notifications', function()
17  local channel
18
19  before_each(function()
20    clear()
21    channel = api.nvim_get_chan_info(0).id
22    api.nvim_set_var('channel', channel)
23  end)
24
25  -- the same set of tests are applied to top-level dictionaries(g:, b:, w: and
26  -- t:) and a dictionary variable, so we generate them in the following
27  -- function.
28  local function gentests(dict_expr, dict_init)
29    local is_g = dict_expr == 'g:'
30
31    local function update(opval, key)
32      if not key then
33        key = 'watched'
34      end
35      if opval == '' then
36        command(("unlet %s['%s']"):format(dict_expr, key))
37      else
38        command(("let %s['%s'] %s"):format(dict_expr, key, opval))
39      end
40    end
41
42    local function update_with_api(opval, key)
43      if not key then
44        key = 'watched'
45      end
46      if opval == '' then
47        exec_lua(("vim.api.nvim_del_var('%s')"):format(key))
48      else
49        exec_lua(("vim.api.nvim_set_var('%s', %s)"):format(key, opval))
50      end
51    end
52
53    local function update_with_vim_g(opval, key)
54      if not key then
55        key = 'watched'
56      end
57      if opval == '' then
58        exec_lua(('vim.g.%s = nil'):format(key))
59      else
60        exec_lua(('vim.g.%s %s'):format(key, opval))
61      end
62    end
63
64    local function verify_echo()
65      -- helper to verify that no notifications are sent after certain change
66      -- to a dict
67      command("call rpcnotify(g:channel, 'echo')")
68      eq({ 'notification', 'echo', {} }, next_msg())
69    end
70
71    local function verify_value(vals, key)
72      if not key then
73        key = 'watched'
74      end
75      eq({ 'notification', 'values', { key, vals } }, next_msg())
76    end
77
78    describe(dict_expr .. ' watcher', function()
79      if dict_init then
80        before_each(function()
81          source(dict_init)
82        end)
83      end
84
85      before_each(function()
86        source([[
87        function! g:Changed(dict, key, value)
88          if a:dict isnot ]] .. dict_expr .. [[ |
89            throw 'invalid dict'
90          endif
91          call rpcnotify(g:channel, 'values', a:key, a:value)
92        endfunction
93        call dictwatcheradd(]] .. dict_expr .. [[, "watched", "g:Changed")
94        call dictwatcheradd(]] .. dict_expr .. [[, "watched2", "g:Changed")
95        ]])
96      end)
97
98      after_each(function()
99        source([[
100        call dictwatcherdel(]] .. dict_expr .. [[, "watched", "g:Changed")
101        call dictwatcherdel(]] .. dict_expr .. [[, "watched2", "g:Changed")
102        ]])
103        update('= "test"')
104        update('= "test2"', 'watched2')
105        update('', 'watched2')
106        update('')
107        verify_echo()
108        if is_g then
109          update_with_api('"test"')
110          update_with_api('"test2"', 'watched2')
111          update_with_api('', 'watched2')
112          update_with_api('')
113          verify_echo()
114          update_with_vim_g('= "test"')
115          update_with_vim_g('= "test2"', 'watched2')
116          update_with_vim_g('', 'watched2')
117          update_with_vim_g('')
118          verify_echo()
119        end
120      end)
121
122      it('is not triggered when unwatched keys are updated', function()
123        update('= "noop"', 'unwatched')
124        update('.= "noop2"', 'unwatched')
125        update('', 'unwatched')
126        verify_echo()
127        if is_g then
128          update_with_api('"noop"', 'unwatched')
129          update_with_api('vim.g.unwatched .. "noop2"', 'unwatched')
130          update_with_api('', 'unwatched')
131          verify_echo()
132          update_with_vim_g('= "noop"', 'unwatched')
133          update_with_vim_g('= vim.g.unwatched .. "noop2"', 'unwatched')
134          update_with_vim_g('', 'unwatched')
135          verify_echo()
136        end
137      end)
138
139      it('is triggered by remove()', function()
140        update('= "test"')
141        verify_value({ new = 'test' })
142        command('call remove(' .. dict_expr .. ', "watched")')
143        verify_value({ old = 'test' })
144      end)
145
146      if is_g then
147        it('is triggered by remove() when updated with nvim_*_var', function()
148          update_with_api('"test"')
149          verify_value({ new = 'test' })
150          command('call remove(' .. dict_expr .. ', "watched")')
151          verify_value({ old = 'test' })
152        end)
153
154        it('is triggered by remove() when updated with vim.g', function()
155          update_with_vim_g('= "test"')
156          verify_value({ new = 'test' })
157          command('call remove(' .. dict_expr .. ', "watched")')
158          verify_value({ old = 'test' })
159        end)
160      end
161
162      it('is triggered by extend()', function()
163        update('= "xtend"')
164        verify_value({ new = 'xtend' })
165        command([[
166          call extend(]] .. dict_expr .. [[, {'watched': 'xtend2', 'watched2': 5, 'watched3': 'a'})
167        ]])
168        verify_value({ old = 'xtend', new = 'xtend2' })
169        verify_value({ new = 5 }, 'watched2')
170        update('')
171        verify_value({ old = 'xtend2' })
172        update('', 'watched2')
173        verify_value({ old = 5 }, 'watched2')
174        update('', 'watched3')
175        verify_echo()
176      end)
177
178      it('is triggered with key patterns', function()
179        source([[
180        call dictwatcheradd(]] .. dict_expr .. [[, "wat*", "g:Changed")
181        ]])
182        update('= 1')
183        verify_value({ new = 1 })
184        verify_value({ new = 1 })
185        update('= 3', 'watched2')
186        verify_value({ new = 3 }, 'watched2')
187        verify_value({ new = 3 }, 'watched2')
188        verify_echo()
189        source([[
190        call dictwatcherdel(]] .. dict_expr .. [[, "wat*", "g:Changed")
191        ]])
192        -- watch every key pattern
193        source([[
194        call dictwatcheradd(]] .. dict_expr .. [[, "*", "g:Changed")
195        ]])
196        update('= 3', 'another_key')
197        update('= 4', 'another_key')
198        update('', 'another_key')
199        update('= 2')
200        verify_value({ new = 3 }, 'another_key')
201        verify_value({ old = 3, new = 4 }, 'another_key')
202        verify_value({ old = 4 }, 'another_key')
203        verify_value({ old = 1, new = 2 })
204        verify_value({ old = 1, new = 2 })
205        verify_echo()
206        source([[
207        call dictwatcherdel(]] .. dict_expr .. [[, "*", "g:Changed")
208        ]])
209      end)
210
211      it('is triggered for empty keys', function()
212        command([[
213        call dictwatcheradd(]] .. dict_expr .. [[, "", "g:Changed")
214        ]])
215        update('= 1', '')
216        verify_value({ new = 1 }, '')
217        update('= 2', '')
218        verify_value({ old = 1, new = 2 }, '')
219        command([[
220        call dictwatcherdel(]] .. dict_expr .. [[, "", "g:Changed")
221        ]])
222      end)
223
224      it('is triggered for empty keys when using catch-all *', function()
225        command([[
226        call dictwatcheradd(]] .. dict_expr .. [[, "*", "g:Changed")
227        ]])
228        update('= 1', '')
229        verify_value({ new = 1 }, '')
230        update('= 2', '')
231        verify_value({ old = 1, new = 2 }, '')
232        command([[
233        call dictwatcherdel(]] .. dict_expr .. [[, "*", "g:Changed")
234        ]])
235      end)
236
237      -- test a sequence of updates of different types to ensure proper memory
238      -- management(with ASAN)
239      local function test_updates(tests)
240        it('test change sequence', function()
241          local input, output
242          for i = 1, #tests do
243            input, output = unpack(tests[i])
244            update(input)
245            verify_value(output)
246          end
247        end)
248      end
249
250      test_updates({
251        { '= 3', { new = 3 } },
252        { '= 6', { old = 3, new = 6 } },
253        { '+= 3', { old = 6, new = 9 } },
254        { '', { old = 9 } },
255      })
256
257      test_updates({
258        { '= "str"', { new = 'str' } },
259        { '= "str2"', { old = 'str', new = 'str2' } },
260        { '.= "2str"', { old = 'str2', new = 'str22str' } },
261        { '', { old = 'str22str' } },
262      })
263
264      test_updates({
265        { '= [1, 2]', { new = { 1, 2 } } },
266        { '= [1, 2, 3]', { old = { 1, 2 }, new = { 1, 2, 3 } } },
267        -- the += will update the list in place, so old and new are the same
268        { '+= [4, 5]', { old = { 1, 2, 3, 4, 5 }, new = { 1, 2, 3, 4, 5 } } },
269        { '', { old = { 1, 2, 3, 4, 5 } } },
270      })
271
272      test_updates({
273        { '= {"k": "v"}', { new = { k = 'v' } } },
274        { '= {"k1": 2}', { old = { k = 'v' }, new = { k1 = 2 } } },
275        { '', { old = { k1 = 2 } } },
276      })
277    end)
278  end
279
280  gentests('g:')
281  gentests('b:')
282  gentests('w:')
283  gentests('t:')
284  gentests('g:dict_var', 'let g:dict_var = {}')
285
286  describe('multiple watchers on the same dict/key', function()
287    before_each(function()
288      source([[
289      function! g:Watcher1(dict, key, value)
290        call rpcnotify(g:channel, '1', a:key, a:value)
291      endfunction
292      function! g:Watcher2(dict, key, value)
293        call rpcnotify(g:channel, '2', a:key, a:value)
294      endfunction
295      call dictwatcheradd(g:, "key", "g:Watcher1")
296      call dictwatcheradd(g:, "key", "g:Watcher2")
297      ]])
298    end)
299
300    it('invokes all callbacks when the key is changed', function()
301      command('let g:key = "value"')
302      eq({ 'notification', '1', { 'key', { new = 'value' } } }, next_msg())
303      eq({ 'notification', '2', { 'key', { new = 'value' } } }, next_msg())
304    end)
305
306    it('only removes watchers that fully match dict, key and callback', function()
307      command('let g:key = "value"')
308      eq({ 'notification', '1', { 'key', { new = 'value' } } }, next_msg())
309      eq({ 'notification', '2', { 'key', { new = 'value' } } }, next_msg())
310      command('call dictwatcherdel(g:, "key", "g:Watcher1")')
311      command('let g:key = "v2"')
312      eq({ 'notification', '2', { 'key', { old = 'value', new = 'v2' } } }, next_msg())
313    end)
314  end)
315
316  it('errors out when adding to v:_null_dict', function()
317    command([[
318    function! g:Watcher1(dict, key, value)
319      call rpcnotify(g:channel, '1', a:key, a:value)
320    endfunction
321    ]])
322    eq(
323      'Vim(call):E46: Cannot change read-only variable "dictwatcheradd() argument"',
324      pcall_err(command, 'call dictwatcheradd(v:_null_dict, "x", "g:Watcher1")')
325    )
326  end)
327
328  describe('errors', function()
329    before_each(function()
330      source([[
331      function! g:Watcher1(dict, key, value)
332        call rpcnotify(g:channel, '1', a:key, a:value)
333      endfunction
334      function! g:Watcher2(dict, key, value)
335        call rpcnotify(g:channel, '2', a:key, a:value)
336      endfunction
337      ]])
338    end)
339
340    -- WARNING: This suite depends on the above tests
341    it('fails to remove if no watcher with matching callback is found', function()
342      eq(
343        "Vim(call):Couldn't find a watcher matching key and callback",
344        pcall_err(command, 'call dictwatcherdel(g:, "key", "g:Watcher1")')
345      )
346    end)
347
348    it('fails to remove if no watcher with matching key is found', function()
349      eq(
350        "Vim(call):Couldn't find a watcher matching key and callback",
351        pcall_err(command, 'call dictwatcherdel(g:, "invalid_key", "g:Watcher2")')
352      )
353    end)
354
355    it("does not fail to add/remove if the callback doesn't exist", function()
356      command('call dictwatcheradd(g:, "key", "g:InvalidCb")')
357      command('call dictwatcherdel(g:, "key", "g:InvalidCb")')
358    end)
359
360    it('fails to remove watcher from v:_null_dict', function()
361      eq(
362        "Vim(call):Couldn't find a watcher matching key and callback",
363        pcall_err(command, 'call dictwatcherdel(v:_null_dict, "x", "g:Watcher2")')
364      )
365    end)
366
367    --[[
368       [ it("fails to add/remove if the callback doesn't exist", function()
369       [   eq("Vim(call):Function g:InvalidCb doesn't exist",
370       [     pcall_err(command, 'call dictwatcheradd(g:, "key", "g:InvalidCb")'))
371       [   eq("Vim(call):Function g:InvalidCb doesn't exist",
372       [     pcall_err(command, 'call dictwatcherdel(g:, "key", "g:InvalidCb")'))
373       [ end)
374       ]]
375
376    it('does not fail to replace a watcher function', function()
377      source([[
378      let g:key = 'v2'
379      call dictwatcheradd(g:, "key", "g:Watcher2")
380      function! g:ReplaceWatcher2()
381        function! g:Watcher2(dict, key, value)
382          call rpcnotify(g:channel, '2b', a:key, a:value)
383        endfunction
384      endfunction
385      ]])
386      command('call g:ReplaceWatcher2()')
387      command('let g:key = "value"')
388      eq({ 'notification', '2b', { 'key', { old = 'v2', new = 'value' } } }, next_msg())
389    end)
390
391    it('does not crash when freeing a watched dictionary', function()
392      source([[
393      function! Watcher(dict, key, value)
394        echo a:key string(a:value)
395      endfunction
396
397      function! MakeWatch()
398        let d = {'foo': 'bar'}
399        call dictwatcheradd(d, 'foo', function('Watcher'))
400      endfunction
401      ]])
402
403      command('call MakeWatch()')
404      assert_alive()
405    end)
406  end)
407
408  describe('with lambdas', function()
409    it('works correctly', function()
410      source([[
411      let d = {'foo': 'baz'}
412      call dictwatcheradd(d, 'foo', {dict, key, value -> rpcnotify(g:channel, '2', key, value)})
413      let d.foo = 'bar'
414      ]])
415      eq({ 'notification', '2', { 'foo', { old = 'baz', new = 'bar' } } }, next_msg())
416    end)
417  end)
418
419  it('for b:changedtick', function()
420    source([[
421      function! OnTickChanged(dict, key, value)
422        call rpcnotify(g:channel, 'SendChangeTick', a:key, a:value)
423      endfunction
424      call dictwatcheradd(b:, 'changedtick', 'OnTickChanged')
425    ]])
426
427    insert('t')
428    eq({ 'notification', 'SendChangeTick', { 'changedtick', { old = 2, new = 3 } } }, next_msg())
429
430    command([[call dictwatcherdel(b:, 'changedtick', 'OnTickChanged')]])
431    insert('t')
432    assert_alive()
433
434    command([[call dictwatcheradd(b:, 'changedtick', {-> execute('bwipe!')})]])
435    insert('t')
436    eq('E937: Attempt to delete a buffer that is in use: [No Name]', api.nvim_get_vvar('errmsg'))
437    assert_alive()
438
439    command([[enew | set modified | call dictwatcheradd(b:, 'changedtick', {-> execute('split')})]])
440    -- Used to instead leave a window open to a NULL buffer.
441    matches(
442      'E565: Not allowed to change text or change window: split$',
443      pcall_err(command, 'bdelete!')
444    )
445  end)
446
447  it('does not cause use-after-free when unletting from callback', function()
448    source([[
449      let g:called = 0
450      function W(...) abort
451        unlet g:d
452        let g:called = 1
453      endfunction
454      let g:d = {}
455      call dictwatcheradd(g:d, '*', function('W'))
456      let g:d.foo = 123
457    ]])
458    eq(1, eval('g:called'))
459  end)
460
461  it('does not crash when using dictwatcherdel in callback', function()
462    source([[
463      let g:d = {}
464
465      function! W1(...)
466        " Delete current and following watcher.
467        call dictwatcherdel(g:d, '*', function('W1'))
468        call dictwatcherdel(g:d, '*', function('W2'))
469        try
470          call dictwatcherdel({}, 'meh', function('tr'))
471        catch
472          let g:exc = v:exception
473        endtry
474      endfunction
475      call dictwatcheradd(g:d, '*', function('W1'))
476
477      function! W2(...)
478      endfunction
479      call dictwatcheradd(g:d, '*', function('W2'))
480
481      let g:d.foo = 23
482    ]])
483    eq(23, eval('g:d.foo'))
484    eq("Vim(call):Couldn't find a watcher matching key and callback", eval('g:exc'))
485  end)
486
487  it('does not call watcher added in callback', function()
488    source([[
489      let g:d = {}
490      let g:calls = []
491
492      function! W1(...) abort
493        call add(g:calls, 'W1')
494        call dictwatcheradd(g:d, '*', function('W2'))
495      endfunction
496
497      function! W2(...) abort
498        call add(g:calls, 'W2')
499      endfunction
500
501      call dictwatcheradd(g:d, '*', function('W1'))
502      let g:d.foo = 23
503    ]])
504    eq(23, eval('g:d.foo'))
505    eq({ 'W1' }, eval('g:calls'))
506  end)
507
508  it('calls watcher deleted in callback', function()
509    source([[
510      let g:d = {}
511      let g:calls = []
512
513      function! W1(...) abort
514        call add(g:calls, "W1")
515        call dictwatcherdel(g:d, '*', function('W2'))
516      endfunction
517
518      function! W2(...) abort
519        call add(g:calls, "W2")
520      endfunction
521
522      call dictwatcheradd(g:d, '*', function('W1'))
523      call dictwatcheradd(g:d, '*', function('W2'))
524      let g:d.foo = 123
525
526      unlet g:d
527      let g:d = {}
528      call dictwatcheradd(g:d, '*', function('W2'))
529      call dictwatcheradd(g:d, '*', function('W1'))
530      let g:d.foo = 123
531    ]])
532    eq(123, eval('g:d.foo'))
533    eq({ 'W1', 'W2', 'W2', 'W1' }, eval('g:calls'))
534  end)
535end)
536describe('tabpagebuflist() with dict watcher during buffer close/wipe', function()
537  before_each(function()
538    clear()
539  end)
540
541  it(
542    'does not segfault when called from dict watcher on b:changedtick (bufhidden=unload)',
543    function()
544      command([[
545    new
546    set bufhidden=unload
547    call dictwatcheradd(b:, 'changedtick', {-> tabpagebuflist()})
548    close
549    ]])
550
551      assert_alive()
552    end
553  )
554
555  it('does not segfault when wiping buffer with dict watcher', function()
556    command([[
557    new
558    call setline(1, 'test')
559    call dictwatcheradd(b:, 'changedtick', {-> tabpagebuflist()})
560    bwipeout!
561    ]])
562
563    assert_alive()
564  end)
565
566  it('does not segfault with multiple windows in the tabpage', function()
567    command([[
568    " create two windows in the current tab
569    edit foo
570    vnew
571    call setline(1, 'bar')
572
573    " attach watcher to the current buffer in the split
574    call dictwatcheradd(b:, 'changedtick', {-> tabpagebuflist()})
575
576    " close the split window (triggers close_buffer on this buffer)
577    close
578    ]])
579
580    assert_alive()
581  end)
582end)