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