robin/laufey

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

zeertzjqvim-patch:9.2.0265: unnecessary restrictions for defining dictionary function names (#38524)5a7df03b42

master
25.2 KiB1014 linesraw
1" Test for user functions.
2" Also test an <expr> mapping calling a function.
3" Also test that a builtin function cannot be replaced.
4" Also test for regression when calling arbitrary expression.
5
6source check.vim
7source shared.vim
8source vim9.vim
9
10func Table(title, ...)
11  let ret = a:title
12  let idx = 1
13  while idx <= a:0
14    exe "let ret = ret . a:" . idx
15    let idx = idx + 1
16  endwhile
17  return ret
18endfunc
19
20func Compute(n1, n2, divname)
21  if a:n2 == 0
22    return "fail"
23  endif
24  exe "let g:" . a:divname . " = ". a:n1 / a:n2
25  return "ok"
26endfunc
27
28func Expr1()
29  silent! normal! v
30  return "111"
31endfunc
32
33func Expr2()
34  call search('XX', 'b')
35  return "222"
36endfunc
37
38func ListItem()
39  let g:counter += 1
40  return g:counter . '. '
41endfunc
42
43func ListReset()
44  let g:counter = 0
45  return ''
46endfunc
47
48func FuncWithRef(a)
49  unlet g:FuncRef
50  return a:a
51endfunc
52
53func Test_user_func()
54  let g:FuncRef = function("FuncWithRef")
55  let g:counter = 0
56  inoremap <expr> ( ListItem()
57  inoremap <expr> [ ListReset()
58  imap <expr> + Expr1()
59  imap <expr> * Expr2()
60  let g:retval = "nop"
61
62  call assert_equal('xxx4asdf', Table("xxx", 4, "asdf"))
63  call assert_equal('fail', Compute(45, 0, "retval"))
64  call assert_equal('nop', g:retval)
65  call assert_equal('ok', Compute(45, 5, "retval"))
66  call assert_equal(9, g:retval)
67  call assert_equal(333, g:FuncRef(333))
68
69  let g:retval = "nop"
70  call assert_equal('xxx4asdf', "xxx"->Table(4, "asdf"))
71  call assert_equal('fail', 45->Compute(0, "retval"))
72  call assert_equal('nop', g:retval)
73  call assert_equal('ok', 45->Compute(5, "retval"))
74  call assert_equal(9, g:retval)
75  " call assert_equal(333, 333->g:FuncRef())
76
77  enew
78
79  normal oXX+-XX
80  call assert_equal('XX111-XX', getline('.'))
81  normal o---*---
82  call assert_equal('---222---', getline('.'))
83  normal o(one
84  call assert_equal('1. one', getline('.'))
85  normal o(two
86  call assert_equal('2. two', getline('.'))
87  normal o[(one again
88  call assert_equal('1. one again', getline('.'))
89
90  " Try to overwrite a function in the global (g:) scope
91  call assert_equal(3, max([1, 2, 3]))
92  call assert_fails("call extend(g:, {'max': function('min')})", 'E704')
93  call assert_equal(3, max([1, 2, 3]))
94
95  " Try to overwrite an user defined function with a function reference
96  call assert_fails("let Expr1 = function('min')", 'E705:')
97
98  " Regression: the first line below used to throw ?E110: Missing ')'?
99  " Second is here just to prove that this line is correct when not skipping
100  " rhs of &&.
101  call assert_equal(0, (0 && (function('tr'))(1, 2, 3)))
102  call assert_equal(1, (1 && (function('tr'))(1, 2, 3)))
103
104  delfunc Table
105  delfunc Compute
106  delfunc Expr1
107  delfunc Expr2
108  delfunc ListItem
109  delfunc ListReset
110  unlet g:retval g:counter
111  enew!
112endfunc
113
114func Log(val, base = 10)
115  return log(a:val) / log(a:base)
116endfunc
117
118func Args(mandatory, optional = v:null, ...)
119  return deepcopy(a:)
120endfunc
121
122func Args2(a = 1, b = 2, c = 3)
123  return deepcopy(a:)
124endfunc
125
126func MakeBadFunc()
127  func s:fcn(a, b=1, c)
128  endfunc
129endfunc
130
131func Test_default_arg()
132  if has('float')
133    call assert_equal(1.0, Log(10))
134    call assert_equal(log(10), Log(10, exp(1)))
135    call assert_fails("call Log(1,2,3)", 'E118')
136  endif
137
138  let res = Args(1)
139  call assert_equal(res.mandatory, 1)
140  call assert_equal(res.optional, v:null)
141  call assert_equal(res['0'], 0)
142
143  let res = Args(1,2)
144  call assert_equal(res.mandatory, 1)
145  call assert_equal(res.optional, 2)
146  call assert_equal(res['0'], 0)
147
148  let res = Args(1,2,3)
149  call assert_equal(res.mandatory, 1)
150  call assert_equal(res.optional, 2)
151  call assert_equal(res['0'], 1)
152
153  call assert_fails("call MakeBadFunc()", 'E989:')
154  call assert_fails("fu F(a=1 ,) | endf", 'E1068:')
155
156  " Since neovim does not have v:none, the ability to use the default
157  " argument with the intermediate argument set to v:none has been omitted.
158  " Therefore, this test is not performed.
159  " let d = Args2(7, v:none, 9)
160  " call assert_equal([7, 2, 9], [d.a, d.b, d.c])
161
162  call assert_equal("\n"
163	\ .. "   function Args2(a = 1, b = 2, c = 3)\n"
164	\ .. "1    return deepcopy(a:)\n"
165	\ .. "   endfunction",
166	\ execute('func Args2'))
167
168  " Error in default argument expression
169  func! s:f(x = s:undefined)
170    return a:x
171  endfunc
172  call assert_fails('echo s:f()', ['E121: Undefined variable: s:undefined',
173        \ 'E121: Undefined variable: a:x'])
174
175  func! s:f(x = s:undefined) abort
176    return a:x
177  endfunc
178  const expected_error = 'E121: Undefined variable: s:undefined'
179  " Only one error should be output; execution of the function should be aborted
180  " after the default argument expression error.
181  call assert_fails('echo s:f()', [expected_error, expected_error])
182endfunc
183
184func Test_default_argument_expression_error_while_inside_of_a_try_block()
185  func! s:f(v = s:undefined_variable)
186    let s:entered_fn_body = 1
187    return a:v
188  endfunc
189
190  unlet! s:entered_fn_body
191  try
192    call s:f()
193    throw "No exception."
194  catch
195    call assert_exception("E121: Undefined variable: s:undefined_variable")
196  endtry
197  call assert_false(exists('s:entered_fn_body'), "exists('s:entered_fn_body')")
198endfunc
199
200func s:addFoo(lead)
201  return a:lead .. 'foo'
202endfunc
203
204func Test_user_method()
205  eval 'bar'->s:addFoo()->assert_equal('barfoo')
206endfunc
207
208func Test_failed_call_in_try()
209  try | call UnknownFunc() | catch | endtry
210endfunc
211
212" Test for listing user-defined functions
213func Test_function_list()
214  call assert_fails("function Xabc", 'E123:')
215endfunc
216
217" Test for <sfile>, <slnum> in a function
218func Test_sfile_in_function()
219  func Xfunc()
220    call assert_match('..Test_sfile_in_function\[5]..Xfunc', expand('<sfile>'))
221    call assert_equal('2', expand('<slnum>'))
222  endfunc
223  call Xfunc()
224  delfunc Xfunc
225endfunc
226
227" Test trailing text after :endfunction				    {{{1
228func Test_endfunction_trailing()
229  call assert_false(exists('*Xtest'))
230
231  exe "func Xtest()\necho 'hello'\nendfunc\nlet done = 'yes'"
232  call assert_true(exists('*Xtest'))
233  call assert_equal('yes', done)
234  delfunc Xtest
235  unlet done
236
237  exe "func Xtest()\necho 'hello'\nendfunc|let done = 'yes'"
238  call assert_true(exists('*Xtest'))
239  call assert_equal('yes', done)
240  delfunc Xtest
241  unlet done
242
243  " trailing line break
244  exe "func Xtest()\necho 'hello'\nendfunc\n"
245  call assert_true(exists('*Xtest'))
246  delfunc Xtest
247
248  set verbose=1
249  exe "func Xtest()\necho 'hello'\nendfunc \" garbage"
250  call assert_notmatch('W22:', split(execute('1messages'), "\n")[0])
251  call assert_true(exists('*Xtest'))
252  delfunc Xtest
253
254  exe "func Xtest()\necho 'hello'\nendfunc garbage"
255  call assert_match('W22:', split(execute('1messages'), "\n")[0])
256  call assert_true(exists('*Xtest'))
257  delfunc Xtest
258  set verbose=0
259
260  func Xtest(a1, a2)
261    echo a:a1 .. a:a2
262  endfunc
263  set verbose=15
264  redir @a
265  call Xtest(123, repeat('x', 100))
266  redir END
267  call assert_match('calling Xtest(123, ''xxxxxxx.*x\.\.\.x.*xxxx'')', getreg('a'))
268  delfunc Xtest
269  set verbose=0
270
271  function Foo()
272    echo 'hello'
273  endfunction | echo 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
274  delfunc Foo
275endfunc
276
277func Test_delfunction_force()
278  delfunc! Xtest
279  delfunc! Xtest
280  func Xtest()
281    echo 'nothing'
282  endfunc
283  delfunc! Xtest
284  delfunc! Xtest
285
286  " Try deleting the current function
287  call assert_fails('delfunc Test_delfunction_force', 'E131:')
288endfunc
289
290func Test_function_defined_line()
291  CheckNotGui
292
293  let lines =<< trim [CODE]
294  " F1
295  func F1()
296    " F2
297    func F2()
298      "
299      "
300      "
301      return
302    endfunc
303    " F3
304    execute "func F3()\n\n\n\nreturn\nendfunc"
305    " F4
306    execute "func F4()\n
307                \\n
308                \\n
309                \\n
310                \return\n
311                \endfunc"
312  endfunc
313  " F5
314  execute "func F5()\n\n\n\nreturn\nendfunc"
315  " F6
316  execute "func F6()\n
317              \\n
318              \\n
319              \\n
320              \return\n
321              \endfunc"
322  call F1()
323  verbose func F1
324  verbose func F2
325  verbose func F3
326  verbose func F4
327  verbose func F5
328  verbose func F6
329  qall!
330  [CODE]
331
332  call writefile(lines, 'Xtest.vim')
333  let res = system(GetVimCommandClean() .. ' -es -X -S Xtest.vim')
334  call assert_equal(0, v:shell_error)
335
336  let m = matchstr(res, 'function F1()[^[:print:]]*[[:print:]]*')
337  call assert_match(' line 2$', m)
338
339  let m = matchstr(res, 'function F2()[^[:print:]]*[[:print:]]*')
340  call assert_match(' line 4$', m)
341
342  let m = matchstr(res, 'function F3()[^[:print:]]*[[:print:]]*')
343  call assert_match(' line 11$', m)
344
345  let m = matchstr(res, 'function F4()[^[:print:]]*[[:print:]]*')
346  call assert_match(' line 13$', m)
347
348  let m = matchstr(res, 'function F5()[^[:print:]]*[[:print:]]*')
349  call assert_match(' line 21$', m)
350
351  let m = matchstr(res, 'function F6()[^[:print:]]*[[:print:]]*')
352  call assert_match(' line 23$', m)
353
354  call delete('Xtest.vim')
355endfunc
356
357" Test for defining a function reference in the global scope
358func Test_add_funcref_to_global_scope()
359  let x = g:
360  let caught_E862 = 0
361  try
362    func x.Xfunc()
363      return 1
364    endfunc
365  catch /E862:/
366    let caught_E862 = 1
367  endtry
368  call assert_equal(1, caught_E862)
369endfunc
370
371func Test_funccall_garbage_collect()
372  func Func(x, ...)
373    call add(a:x, a:000)
374  endfunc
375  call Func([], [])
376  " Must not crash cause by invalid freeing
377  call test_garbagecollect_now()
378  call assert_true(v:true)
379  delfunc Func
380endfunc
381
382" Test for script-local function
383func <SID>DoLast()
384  call append(line('$'), "last line")
385endfunc
386
387func s:DoNothing()
388  call append(line('$'), "nothing line")
389endfunc
390
391func Test_script_local_func()
392  set nocp nomore viminfo+=nviminfo
393  new
394  nnoremap <buffer> _x	:call <SID>DoNothing()<bar>call <SID>DoLast()<bar>delfunc <SID>DoNothing<bar>delfunc <SID>DoLast<cr>
395
396  normal _x
397  call assert_equal('nothing line', getline(2))
398  call assert_equal('last line', getline(3))
399  close!
400
401  " Try to call a script local function in global scope
402  let lines =<< trim [CODE]
403    :call assert_fails('call s:Xfunc()', 'E81:')
404    :call assert_fails('let x = call("<SID>Xfunc", [])', ['E81:', 'E117:'])
405    :call writefile(v:errors, 'Xresult')
406    :qall
407
408  [CODE]
409  call writefile(lines, 'Xscript')
410  if RunVim([], [], '-s Xscript')
411    call assert_equal([], readfile('Xresult'))
412  endif
413  call delete('Xresult')
414  call delete('Xscript')
415endfunc
416
417" Test for errors in defining new functions
418func Test_func_def_error()
419  call assert_fails('func Xfunc abc ()', 'E124:')
420  call assert_fails('func Xfunc(', 'E125:')
421  call assert_fails('func xfunc()', 'E128:')
422
423  " Try to redefine a function that is in use
424  let caught_E127 = 0
425  try
426    func! Test_func_def_error()
427    endfunc
428  catch /E127:/
429    let caught_E127 = 1
430  endtry
431  call assert_equal(1, caught_E127)
432
433  " Try to define a function in a dict twice
434  let d = {}
435  let lines =<< trim END
436    func d.F1()
437      return 1
438    endfunc
439  END
440  let l = join(lines, "\n") . "\n"
441  exe l
442  call assert_fails('exe l', 'E717:')
443
444  " Define an autoload function with an incorrect file name
445  call writefile(['func foo#Bar()', 'return 1', 'endfunc'], 'Xscript', 'D')
446  call assert_fails('source Xscript', 'E746:')
447
448  " Try to list functions using an invalid search pattern
449  call assert_fails('function /\%(/', 'E53:')
450
451  " Use a script-local function to cover uf_name_exp.
452  func s:TestRedefine(arg1 = 1, arg2 = 10)
453    let caught_E122 = 0
454    try
455      func s:TestRedefine(arg1 = 1, arg2 = 10)
456      endfunc
457    catch /E122:/
458      let caught_E122 = 1
459    endtry
460    call assert_equal(1, caught_E122)
461
462    let caught_E127 = 0
463    try
464      func! s:TestRedefine(arg1 = 1, arg2 = 10)
465      endfunc
466    catch /E127:/
467      let caught_E127 = 1
468    endtry
469    call assert_equal(1, caught_E127)
470
471    " The failures above shouldn't cause heap-use-after-free here.
472    return [a:arg1 + a:arg2, expand('<stack>')]
473  endfunc
474
475  let stacks = []
476  " Call the function twice.
477  " Failing to redefine a function shouldn't clear its argument list.
478  for i in range(2)
479    let [val, stack] = s:TestRedefine(1000)
480    call assert_equal(1010, val)
481    call assert_match(expand('<SID>') .. 'TestRedefine\[20\]$', stack)
482    call add(stacks, stack)
483  endfor
484  call assert_equal(stacks[0], stacks[1])
485
486  delfunc s:TestRedefine
487endfunc
488
489" Test for deleting a function
490func Test_del_func()
491  call assert_fails('delfunction Xabc', 'E130:')
492  let d = {'a' : 10}
493  call assert_fails('delfunc d.a', 'E718:')
494  func d.fn()
495    return 1
496  endfunc
497
498  " cannot delete the dict function by number
499  let nr = substitute(execute('echo d'), '.*function(''\(\d\+\)'').*', '\1', '')
500  call assert_fails('delfunction g:' .. nr, 'E475: Invalid argument: g:')
501
502  delfunc d.fn
503  call assert_equal({'a' : 10}, d)
504endfunc
505
506" Test for calling return outside of a function
507func Test_return_outside_func()
508  call writefile(['return 10'], 'Xscript')
509  call assert_fails('source Xscript', 'E133:')
510  call delete('Xscript')
511endfunc
512
513" Test for errors in calling a function
514func Test_func_arg_error()
515  " Too many arguments
516  call assert_fails("call call('min', range(1,20))", 'E118:')
517  call assert_fails("call call('min', range(1,21))", 'E699:')
518  call assert_fails('echo min(0,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,0,1)',
519        \ 'E740:')
520
521  " Missing dict argument
522  func Xfunc() dict
523    return 1
524  endfunc
525  call assert_fails('call Xfunc()', 'E725:')
526  delfunc Xfunc
527endfunc
528
529func Test_func_dict()
530  let mydict = {'a': 'b'}
531  function mydict.somefunc() dict
532    return len(self)
533  endfunc
534
535  call assert_equal("{'a': 'b', 'somefunc': function('3')}", string(mydict))
536  call assert_equal(2, mydict.somefunc())
537  call assert_match("^\n   function \\d\\\+() dict"
538  \              .. "\n1      return len(self)"
539  \              .. "\n   endfunction$", execute('func mydict.somefunc'))
540  call assert_fails('call mydict.nonexist()', 'E716:')
541endfunc
542
543func Test_func_dict_bracket_key()
544  " Dictionary function can be defined with bracket notation using a key
545  " that does not follow function naming rules (e.g. containing a hyphen).
546  let obj = {}
547  function obj['foo-bar']() dict
548    return self.value
549  endfunction
550  let obj.value = 42
551  call assert_equal(42, obj['foo-bar']())
552  call assert_equal(42, call(obj['foo-bar'], []))
553endfunc
554
555func Test_func_range()
556  new
557  call setline(1, range(1, 8))
558  func FuncRange() range
559    echo a:firstline
560    echo a:lastline
561  endfunc
562  3
563  call assert_equal("\n3\n3", execute('call FuncRange()'))
564  call assert_equal("\n4\n6", execute('4,6 call FuncRange()'))
565  call assert_equal("\n   function FuncRange() range"
566  \              .. "\n1      echo a:firstline"
567  \              .. "\n2      echo a:lastline"
568  \              .. "\n   endfunction",
569  \                 execute('function FuncRange'))
570
571  bwipe!
572endfunc
573
574" Test for memory allocation failure when defining a new function
575func Test_funcdef_alloc_failure()
576  CheckFunction test_alloc_fail
577  new
578  let lines =<< trim END
579    func Xtestfunc()
580      return 321
581    endfunc
582  END
583  call setline(1, lines)
584  call test_alloc_fail(GetAllocId('get_func'), 0, 0)
585  call assert_fails('source', 'E342:')
586  call assert_false(exists('*Xtestfunc'))
587  call assert_fails('delfunc Xtestfunc', 'E117:')
588  %d _
589  let lines =<< trim END
590    def g:Xvim9func(): number
591      return 456
592    enddef
593  END
594  call setline(1, lines)
595  call test_alloc_fail(GetAllocId('get_func'), 0, 0)
596  call assert_fails('source', 'E342:')
597  call assert_false(exists('*Xvim9func'))
598  "call test_alloc_fail(GetAllocId('get_func'), 0, 0)
599  "call assert_fails('source', 'E342:')
600  "call assert_false(exists('*Xtestfunc'))
601  "call assert_fails('delfunc Xtestfunc', 'E117:')
602  bw!
603endfunc
604
605func AddDefer(arg1, ...)
606  call extend(g:deferred, [a:arg1])
607  if a:0 == 1
608    call extend(g:deferred, [a:1])
609  endif
610endfunc
611
612func WithDeferTwo()
613  call extend(g:deferred, ['in Two'])
614  for nr in range(3)
615    defer AddDefer('Two' .. nr)
616  endfor
617  call extend(g:deferred, ['end Two'])
618endfunc
619
620func WithDeferOne()
621  call extend(g:deferred, ['in One'])
622  call writefile(['text'], 'Xfuncdefer')
623  defer delete('Xfuncdefer')
624  defer AddDefer('One')
625  call WithDeferTwo()
626  call extend(g:deferred, ['end One'])
627endfunc
628
629func WithPartialDefer()
630  call extend(g:deferred, ['in Partial'])
631  let Part = funcref('AddDefer', ['arg1'])
632  defer Part("arg2")
633  call extend(g:deferred, ['end Partial'])
634endfunc
635
636func Test_defer()
637  let g:deferred = []
638  call WithDeferOne()
639
640  call assert_equal(['in One', 'in Two', 'end Two', 'Two2', 'Two1', 'Two0', 'end One', 'One'], g:deferred)
641  unlet g:deferred
642
643  call assert_equal('', glob('Xfuncdefer'))
644
645  call assert_fails('defer delete("Xfuncdefer")->Another()', 'E488:')
646  call assert_fails('defer delete("Xfuncdefer").member', 'E488:')
647
648  let g:deferred = []
649  call WithPartialDefer()
650  call assert_equal(['in Partial', 'end Partial', 'arg1', 'arg2'], g:deferred)
651  unlet g:deferred
652
653  let Part = funcref('AddDefer', ['arg1'], {})
654  call assert_fails('defer Part("arg2")', 'E1300:')
655endfunc
656
657func DeferLevelTwo()
658  call writefile(['text'], 'XDeleteTwo', 'D')
659  throw 'someerror'
660endfunc
661
662" def DeferLevelOne()
663func DeferLevelOne()
664  call writefile(['text'], 'XDeleteOne', 'D')
665  call g:DeferLevelTwo()
666" enddef
667endfunc
668
669func Test_defer_throw()
670  let caught = 'no'
671  try
672    call DeferLevelOne()
673  catch /someerror/
674    let caught = 'yes'
675  endtry
676  call assert_equal('yes', caught)
677  call assert_false(filereadable('XDeleteOne'))
678  call assert_false(filereadable('XDeleteTwo'))
679endfunc
680
681func Test_defer_quitall_func()
682  let lines =<< trim END
683      func DeferLevelTwo()
684        call writefile(['text'], 'XQuitallFuncTwo', 'D')
685        call writefile(['quit'], 'XQuitallFuncThree', 'a')
686        qa!
687      endfunc
688
689      func DeferLevelOne()
690        call writefile(['text'], 'XQuitalFunclOne', 'D')
691        defer DeferLevelTwo()
692      endfunc
693
694      call DeferLevelOne()
695  END
696  call writefile(lines, 'XdeferQuitallFunc', 'D')
697  call system(GetVimCommand() .. ' -X -S XdeferQuitallFunc')
698  call assert_equal(0, v:shell_error)
699  call assert_false(filereadable('XQuitallFuncOne'))
700  call assert_false(filereadable('XQuitallFuncTwo'))
701  call assert_equal(['quit'], readfile('XQuitallFuncThree'))
702
703  call delete('XQuitallFuncThree')
704endfunc
705
706func Test_defer_quitall_def()
707  throw 'Skipped: Vim9 script is N/A'
708  let lines =<< trim END
709      vim9script
710      def DeferLevelTwo()
711        call writefile(['text'], 'XQuitallDefTwo', 'D')
712        call writefile(['quit'], 'XQuitallDefThree', 'a')
713        qa!
714      enddef
715
716      def DeferLevelOne()
717        call writefile(['text'], 'XQuitallDefOne', 'D')
718        defer DeferLevelTwo()
719      enddef
720
721      DeferLevelOne()
722  END
723  call writefile(lines, 'XdeferQuitallDef', 'D')
724  call system(GetVimCommand() .. ' -X -S XdeferQuitallDef')
725  call assert_equal(0, v:shell_error)
726  call assert_false(filereadable('XQuitallDefOne'))
727  call assert_false(filereadable('XQuitallDefTwo'))
728  call assert_equal(['quit'], readfile('XQuitallDefThree'))
729
730  call delete('XQuitallDefThree')
731endfunc
732
733func Test_defer_quitall_autocmd()
734  let lines =<< trim END
735      func DeferLevelFive()
736        defer writefile(['5'], 'XQuitallAutocmd', 'a')
737        qa!
738      endfunc
739
740      autocmd User DeferAutocmdFive call DeferLevelFive()
741
742      " def DeferLevelFour()
743      func DeferLevelFour()
744        defer writefile(['4'], 'XQuitallAutocmd', 'a')
745        doautocmd User DeferAutocmdFive
746      " enddef
747      endfunc
748
749      func DeferLevelThree()
750        defer writefile(['3'], 'XQuitallAutocmd', 'a')
751        call DeferLevelFour()
752      endfunc
753
754      autocmd User DeferAutocmdThree ++nested call DeferLevelThree()
755
756      " def DeferLevelTwo()
757      func DeferLevelTwo()
758        defer writefile(['2'], 'XQuitallAutocmd', 'a')
759        doautocmd User DeferAutocmdThree
760      " enddef
761      endfunc
762
763      func DeferLevelOne()
764        defer writefile(['1'], 'XQuitallAutocmd', 'a')
765        call DeferLevelTwo()
766      endfunc
767
768      autocmd User DeferAutocmdOne ++nested call DeferLevelOne()
769
770      doautocmd User DeferAutocmdOne
771  END
772  call writefile(lines, 'XdeferQuitallAutocmd', 'D')
773  call system(GetVimCommand() .. ' -X -S XdeferQuitallAutocmd')
774  call assert_equal(0, v:shell_error)
775  call assert_equal(['5', '4', '3', '2', '1'], readfile('XQuitallAutocmd'))
776
777  call delete('XQuitallAutocmd')
778endfunc
779
780func Test_defer_quitall_in_expr_func()
781  throw 'Skipped: Vim9 script is N/A'
782  let lines =<< trim END
783      def DefIndex(idx: number, val: string): bool
784        call writefile([idx .. ': ' .. val], 'Xentry' .. idx, 'D')
785        if val == 'b'
786          qa!
787        endif
788        return val == 'c'
789      enddef
790
791      def Test_defer_in_funcref()
792        assert_equal(2, indexof(['a', 'b', 'c'], funcref('g:DefIndex')))
793      enddef
794      call Test_defer_in_funcref()
795  END
796  call writefile(lines, 'XdeferQuitallExpr', 'D')
797  call system(GetVimCommand() .. ' -X -S XdeferQuitallExpr')
798  call assert_equal(0, v:shell_error)
799  call assert_false(filereadable('Xentry0'))
800  call assert_false(filereadable('Xentry1'))
801  call assert_false(filereadable('Xentry2'))
802endfunc
803
804func FuncIndex(idx, val)
805  call writefile([a:idx .. ': ' .. a:val], 'Xentry' .. a:idx, 'D')
806  return a:val == 'c'
807endfunc
808
809func Test_defer_wrong_arguments()
810  call assert_fails('defer delete()', 'E119:')
811  call assert_fails('defer FuncIndex(1)', 'E119:')
812  call assert_fails('defer delete(1, 2, 3)', 'E118:')
813  call assert_fails('defer FuncIndex(1, 2, 3)', 'E118:')
814
815  throw 'Skipped: Vim9 script is N/A'
816  let lines =<< trim END
817      def DeferFunc0()
818        defer delete()
819      enddef
820      defcompile
821  END
822  call v9.CheckScriptFailure(lines, 'E119:')
823  let lines =<< trim END
824      def DeferFunc3()
825        defer delete(1, 2, 3)
826      enddef
827      defcompile
828  END
829  call v9.CheckScriptFailure(lines, 'E118:')
830  let lines =<< trim END
831      def DeferFunc2()
832        defer delete(1, 2)
833      enddef
834      defcompile
835  END
836  call v9.CheckScriptFailure(lines, 'E1013: Argument 1: type mismatch, expected string but got number')
837
838  def g:FuncOneArg(arg: string)
839    echo arg
840  enddef
841
842  let lines =<< trim END
843      def DeferUserFunc0()
844        defer g:FuncOneArg()
845      enddef
846      defcompile
847  END
848  call v9.CheckScriptFailure(lines, 'E119:')
849  let lines =<< trim END
850      def DeferUserFunc2()
851        defer g:FuncOneArg(1, 2)
852      enddef
853      defcompile
854  END
855  call v9.CheckScriptFailure(lines, 'E118:')
856  let lines =<< trim END
857      def DeferUserFunc1()
858        defer g:FuncOneArg(1)
859      enddef
860      defcompile
861  END
862  call v9.CheckScriptFailure(lines, 'E1013: Argument 1: type mismatch, expected string but got number')
863endfunc
864
865" Test for calling a deferred function after an exception
866func Test_defer_after_exception()
867  let g:callTrace = []
868  func Bar()
869    let g:callTrace += [1]
870    throw 'InnerException'
871  endfunc
872
873  func Defer()
874    let g:callTrace += [2]
875    let g:callTrace += [3]
876    try
877      call Bar()
878    catch /InnerException/
879      let g:callTrace += [4]
880    endtry
881    let g:callTrace += [5]
882    let g:callTrace += [6]
883  endfunc
884
885  func Foo()
886    defer Defer()
887    throw "TestException"
888  endfunc
889
890  try
891    call Foo()
892  catch /TestException/
893    let g:callTrace += [7]
894  endtry
895  call assert_equal([2, 3, 1, 4, 5, 6, 7], g:callTrace)
896
897  delfunc Defer
898  delfunc Foo
899  delfunc Bar
900  unlet g:callTrace
901endfunc
902
903" Test for multiple deferred function which throw exceptions.
904" Exceptions thrown by deferred functions should result in error messages but
905" not propagated into the calling functions.
906func Test_multidefer_with_exception()
907  let g:callTrace = []
908  func Except()
909    let g:callTrace += [1]
910    throw 'InnerException'
911    let g:callTrace += [2]
912  endfunc
913
914  func FirstDefer()
915    let g:callTrace += [3]
916    let g:callTrace += [4]
917  endfunc
918
919  func SecondDeferWithExcept()
920    let g:callTrace += [5]
921    call Except()
922    let g:callTrace += [6]
923  endfunc
924
925  func ThirdDefer()
926    let g:callTrace += [7]
927    let g:callTrace += [8]
928  endfunc
929
930  func Foo()
931    let g:callTrace += [9]
932    defer FirstDefer()
933    defer SecondDeferWithExcept()
934    defer ThirdDefer()
935    let g:callTrace += [10]
936  endfunc
937
938  let v:errmsg = ''
939  try
940    let g:callTrace += [11]
941    call Foo()
942    let g:callTrace += [12]
943  catch /TestException/
944    let g:callTrace += [13]
945  catch
946    let g:callTrace += [14]
947  finally
948    let g:callTrace += [15]
949  endtry
950  let g:callTrace += [16]
951
952  call assert_equal('E605: Exception not caught: InnerException', v:errmsg)
953  call assert_equal([11, 9, 10, 7, 8, 5, 1, 3, 4, 12, 15, 16], g:callTrace)
954
955  unlet g:callTrace
956  delfunc Except
957  delfunc FirstDefer
958  delfunc SecondDeferWithExcept
959  delfunc ThirdDefer
960  delfunc Foo
961endfunc
962
963func Test_func_curly_brace_invalid_name()
964  func Fail()
965    func Foo{'()'}bar()
966    endfunc
967  endfunc
968
969  call assert_fails('call Fail()', 'E475: Invalid argument: Foo()bar')
970
971  silent! call Fail()
972  call assert_equal([], getcompletion('Foo', 'function'))
973
974  set formatexpr=Fail()
975  normal! gqq
976  call assert_equal([], getcompletion('Foo', 'function'))
977
978  set formatexpr&
979  delfunc Fail
980endfunc
981
982func Test_func_return_in_try_verbose()
983  func TryReturnList()
984    try
985      return [1, 2, 3]
986    endtry
987  endfunc
988  func TryReturnNumber()
989    try
990      return 123
991    endtry
992  endfunc
993  func TryReturnOverlongString()
994    try
995      return repeat('a', 9999)
996    endtry
997  endfunc
998
999  " This should not cause heap-use-after-free
1000  call assert_match('\n:return \[1, 2, 3\] made pending\n',
1001                  \ execute('14verbose call TryReturnList()'))
1002  " This should not cause stack-use-after-scope
1003  call assert_match('\n:return 123 made pending\n',
1004                  \ execute('14verbose call TryReturnNumber()'))
1005  " An overlong string is truncated
1006  call assert_match('\n:return a\{100,}\.\.\.',
1007                  \ execute('14verbose call TryReturnOverlongString()'))
1008
1009  delfunc TryReturnList
1010  delfunc TryReturnNumber
1011  delfunc TryReturnOverlongString
1012endfunc
1013
1014" vim: shiftwidth=2 sts=2 expandtab