1" Test using builtin functions in the Vim9 script language.
2
3source check.vim
4source vim9.vim
5
6" Test for passing too many or too few arguments to builtin functions
7func Test_internalfunc_arg_error()
8  let l =<< trim END
9    def! FArgErr(): float
10      return ceil(1.1, 2)
11    enddef
12    defcompile
13  END
14  call writefile(l, 'Xinvalidarg')
15  call assert_fails('so Xinvalidarg', 'E118:', '', 1, 'FArgErr')
16  let l =<< trim END
17    def! FArgErr(): float
18      return ceil()
19    enddef
20    defcompile
21  END
22  call writefile(l, 'Xinvalidarg')
23  call assert_fails('so Xinvalidarg', 'E119:', '', 1, 'FArgErr')
24  call delete('Xinvalidarg')
25endfunc
26
27" Test for builtin functions returning different types
28func Test_InternalFuncRetType()
29  let lines =<< trim END
30    def RetFloat(): float
31      return ceil(1.456)
32    enddef
33
34    def RetListAny(): list<any>
35      return items({k: 'v'})
36    enddef
37
38    def RetListString(): list<string>
39      return split('a:b:c', ':')
40    enddef
41
42    def RetListDictAny(): list<dict<any>>
43      return getbufinfo()
44    enddef
45
46    def RetDictNumber(): dict<number>
47      return wordcount()
48    enddef
49
50    def RetDictString(): dict<string>
51      return environ()
52    enddef
53  END
54  call writefile(lines, 'Xscript')
55  source Xscript
56
57  call RetFloat()->assert_equal(2.0)
58  call RetListAny()->assert_equal([['k', 'v']])
59  call RetListString()->assert_equal(['a', 'b', 'c'])
60  call RetListDictAny()->assert_notequal([])
61  call RetDictNumber()->assert_notequal({})
62  call RetDictString()->assert_notequal({})
63  call delete('Xscript')
64endfunc
65
66def Test_abs()
67  assert_equal(0, abs(0))
68  assert_equal(2, abs(-2))
69  assert_equal(3, abs(3))
70  CheckDefFailure(['abs("text")'], 'E1013: Argument 1: type mismatch, expected number but got string', 1)
71  if has('float')
72    assert_equal(0, abs(0))
73    assert_equal(2.0, abs(-2.0))
74    assert_equal(3.0, abs(3.0))
75  endif
76enddef
77
78def Test_add_list()
79  var l: list<number>  # defaults to empty list
80  add(l, 9)
81  assert_equal([9], l)
82
83  var lines =<< trim END
84      var l: list<number>
85      add(l, "x")
86  END
87  CheckDefFailure(lines, 'E1012:', 2)
88
89  lines =<< trim END
90      add(test_null_list(), 123)
91  END
92  CheckDefExecAndScriptFailure(lines, 'E1130:', 1)
93
94  lines =<< trim END
95      var l: list<number> = test_null_list()
96      add(l, 123)
97  END
98  CheckDefExecFailure(lines, 'E1130:', 2)
99
100  # Getting variable with NULL list allocates a new list at script level
101  lines =<< trim END
102      vim9script
103      var l: list<number> = test_null_list()
104      add(l, 123)
105  END
106  CheckScriptSuccess(lines)
107enddef
108
109def Test_add_blob()
110  var b1: blob = 0z12
111  add(b1, 0x34)
112  assert_equal(0z1234, b1)
113
114  var b2: blob # defaults to empty blob
115  add(b2, 0x67)
116  assert_equal(0z67, b2)
117
118  var lines =<< trim END
119      var b: blob
120      add(b, "x")
121  END
122  CheckDefFailure(lines, 'E1012:', 2)
123
124  lines =<< trim END
125      add(test_null_blob(), 123)
126  END
127  CheckDefExecAndScriptFailure(lines, 'E1131:', 1)
128
129  lines =<< trim END
130      var b: blob = test_null_blob()
131      add(b, 123)
132  END
133  CheckDefExecFailure(lines, 'E1131:', 2)
134
135  # Getting variable with NULL blob allocates a new blob at script level
136  lines =<< trim END
137      vim9script
138      var b: blob = test_null_blob()
139      add(b, 123)
140  END
141  CheckScriptSuccess(lines)
142enddef
143
144def Test_append()
145  new
146  setline(1, range(3))
147  var res1: number = append(1, 'one')
148  assert_equal(0, res1)
149  var res2: bool = append(3, 'two')
150  assert_equal(false, res2)
151  assert_equal(['0', 'one', '1', 'two', '2'], getline(1, 6))
152
153  append(0, 'zero')
154  assert_equal('zero', getline(1))
155  bwipe!
156enddef
157
158def Test_balloon_show()
159  CheckGui
160  CheckFeature balloon_eval
161
162  assert_fails('balloon_show(true)', 'E1174:')
163enddef
164
165def Test_balloon_split()
166  CheckFeature balloon_eval_term
167
168  assert_fails('balloon_split(true)', 'E1174:')
169enddef
170
171def Test_browse()
172  CheckFeature browse
173
174  var lines =<< trim END
175      browse(1, 2, 3, 4)
176  END
177  CheckDefExecAndScriptFailure(lines, 'E1174: String required for argument 2')
178  lines =<< trim END
179      browse(1, 'title', 3, 4)
180  END
181  CheckDefExecAndScriptFailure(lines, 'E1174: String required for argument 3')
182  lines =<< trim END
183      browse(1, 'title', 'dir', 4)
184  END
185  CheckDefExecAndScriptFailure(lines, 'E1174: String required for argument 4')
186enddef
187
188def Test_bufexists()
189  assert_fails('bufexists(true)', 'E1174')
190enddef
191
192def Test_buflisted()
193  var res: bool = buflisted('asdf')
194  assert_equal(false, res)
195  assert_fails('buflisted(true)', 'E1174')
196enddef
197
198def Test_bufname()
199  split SomeFile
200  bufname('%')->assert_equal('SomeFile')
201  edit OtherFile
202  bufname('#')->assert_equal('SomeFile')
203  close
204enddef
205
206def Test_bufnr()
207  var buf = bufnr()
208  bufnr('%')->assert_equal(buf)
209
210  buf = bufnr('Xdummy', true)
211  buf->assert_notequal(-1)
212  exe 'bwipe! ' .. buf
213enddef
214
215def Test_bufwinid()
216  var origwin = win_getid()
217  below split SomeFile
218  var SomeFileID = win_getid()
219  below split OtherFile
220  below split SomeFile
221  bufwinid('SomeFile')->assert_equal(SomeFileID)
222
223  win_gotoid(origwin)
224  only
225  bwipe SomeFile
226  bwipe OtherFile
227
228  assert_fails('bufwinid(true)', 'E1138')
229enddef
230
231def Test_call_call()
232  var l = [3, 2, 1]
233  call('reverse', [l])
234  l->assert_equal([1, 2, 3])
235enddef
236
237def Test_ch_logfile()
238  if !has('channel')
239    CheckFeature channel
240  endif
241  assert_fails('ch_logfile(true)', 'E1174')
242  assert_fails('ch_logfile("foo", true)', 'E1174')
243enddef
244
245def Test_char2nr()
246  char2nr('あ', true)->assert_equal(12354)
247
248  assert_fails('char2nr(true)', 'E1174')
249enddef
250
251def Test_charclass()
252  assert_fails('charclass(true)', 'E1174')
253enddef
254
255def Test_chdir()
256  assert_fails('chdir(true)', 'E1174')
257enddef
258
259def Test_col()
260  new
261  setline(1, 'asdf')
262  col([1, '$'])->assert_equal(5)
263
264  assert_fails('col(true)', 'E1174')
265enddef
266
267def Test_confirm()
268  if !has('dialog_con') && !has('dialog_gui')
269    CheckFeature dialog_con
270  endif
271
272  assert_fails('confirm(true)', 'E1174')
273  assert_fails('confirm("yes", true)', 'E1174')
274  assert_fails('confirm("yes", "maybe", 2, true)', 'E1174')
275enddef
276
277def Test_copy_return_type()
278  var l = copy([1, 2, 3])
279  var res = 0
280  for n in l
281    res += n
282  endfor
283  res->assert_equal(6)
284
285  var dl = deepcopy([1, 2, 3])
286  res = 0
287  for n in dl
288    res += n
289  endfor
290  res->assert_equal(6)
291
292  dl = deepcopy([1, 2, 3], true)
293enddef
294
295def Test_count()
296  count('ABC ABC ABC', 'b', true)->assert_equal(3)
297  count('ABC ABC ABC', 'b', false)->assert_equal(0)
298enddef
299
300def Test_cursor()
301  new
302  setline(1, range(4))
303  cursor(2, 1)
304  assert_equal(2, getcurpos()[1])
305  cursor('$', 1)
306  assert_equal(4, getcurpos()[1])
307
308  var lines =<< trim END
309    cursor('2', 1)
310  END
311  CheckDefExecAndScriptFailure(lines, 'E475:')
312enddef
313
314def Test_delete()
315  var res: bool = delete('doesnotexist')
316  assert_equal(true, res)
317enddef
318
319def Test_executable()
320  assert_false(executable(""))
321  assert_false(executable(test_null_string()))
322
323  CheckDefExecFailure(['echo executable(123)'], 'E1174:')
324  CheckDefExecFailure(['echo executable(true)'], 'E1174:')
325enddef
326
327def Test_exepath()
328  CheckDefExecFailure(['echo exepath(true)'], 'E1174:')
329  CheckDefExecFailure(['echo exepath(v:null)'], 'E1174:')
330  CheckDefExecFailure(['echo exepath("")'], 'E1175:')
331enddef
332
333def Test_expand()
334  split SomeFile
335  expand('%', true, true)->assert_equal(['SomeFile'])
336  close
337enddef
338
339def Test_expandcmd()
340  $FOO = "blue"
341  assert_equal("blue sky", expandcmd("`=$FOO .. ' sky'`"))
342
343  assert_equal("yes", expandcmd("`={a: 'yes'}['a']`"))
344enddef
345
346def Test_extend_arg_types()
347  g:number_one = 1
348  g:string_keep = 'keep'
349  var lines =<< trim END
350      assert_equal([1, 2, 3], extend([1, 2], [3]))
351      assert_equal([3, 1, 2], extend([1, 2], [3], 0))
352      assert_equal([1, 3, 2], extend([1, 2], [3], 1))
353      assert_equal([1, 3, 2], extend([1, 2], [3], g:number_one))
354
355      assert_equal({a: 1, b: 2, c: 3}, extend({a: 1, b: 2}, {c: 3}))
356      assert_equal({a: 1, b: 4}, extend({a: 1, b: 2}, {b: 4}))
357      assert_equal({a: 1, b: 2}, extend({a: 1, b: 2}, {b: 4}, 'keep'))
358      assert_equal({a: 1, b: 2}, extend({a: 1, b: 2}, {b: 4}, g:string_keep))
359
360      var res: list<dict<any>>
361      extend(res, mapnew([1, 2], (_, v) => ({})))
362      assert_equal([{}, {}], res)
363  END
364  CheckDefAndScriptSuccess(lines)
365
366  CheckDefFailure(['extend("a", 1)'], 'E1013: Argument 1: type mismatch, expected list<any> but got string')
367  CheckDefFailure(['extend([1, 2], 3)'], 'E1013: Argument 2: type mismatch, expected list<number> but got number')
368  CheckDefFailure(['extend([1, 2], ["x"])'], 'E1013: Argument 2: type mismatch, expected list<number> but got list<string>')
369  CheckDefFailure(['extend([1, 2], [3], "x")'], 'E1013: Argument 3: type mismatch, expected number but got string')
370
371  CheckDefFailure(['extend({a: 1}, 42)'], 'E1013: Argument 2: type mismatch, expected dict<number> but got number')
372  CheckDefFailure(['extend({a: 1}, {b: "x"})'], 'E1013: Argument 2: type mismatch, expected dict<number> but got dict<string>')
373  CheckDefFailure(['extend({a: 1}, {b: 2}, 1)'], 'E1013: Argument 3: type mismatch, expected string but got number')
374
375  CheckDefFailure(['extend([1], ["b"])'], 'E1013: Argument 2: type mismatch, expected list<number> but got list<string>')
376  CheckDefExecFailure(['extend([1], ["b", 1])'], 'E1013: Argument 2: type mismatch, expected list<number> but got list<any>')
377enddef
378
379def Test_extendnew()
380  assert_equal([1, 2, 'a'], extendnew([1, 2], ['a']))
381  assert_equal({one: 1, two: 'a'}, extendnew({one: 1}, {two: 'a'}))
382
383  CheckDefFailure(['extendnew({a: 1}, 42)'], 'E1013: Argument 2: type mismatch, expected dict<number> but got number')
384  CheckDefFailure(['extendnew({a: 1}, [42])'], 'E1013: Argument 2: type mismatch, expected dict<number> but got list<number>')
385  CheckDefFailure(['extendnew([1, 2], "x")'], 'E1013: Argument 2: type mismatch, expected list<number> but got string')
386  CheckDefFailure(['extendnew([1, 2], {x: 1})'], 'E1013: Argument 2: type mismatch, expected list<number> but got dict<number>')
387enddef
388
389def Test_extend_return_type()
390  var l = extend([1, 2], [3])
391  var res = 0
392  for n in l
393    res += n
394  endfor
395  res->assert_equal(6)
396enddef
397
398func g:ExtendDict(d)
399  call extend(a:d, #{xx: 'x'})
400endfunc
401
402def Test_extend_dict_item_type()
403  var lines =<< trim END
404       var d: dict<number> = {a: 1}
405       extend(d, {b: 2})
406  END
407  CheckDefAndScriptSuccess(lines)
408
409  lines =<< trim END
410       var d: dict<number> = {a: 1}
411       extend(d, {b: 'x'})
412  END
413  CheckDefAndScriptFailure(lines, 'E1013: Argument 2: type mismatch, expected dict<number> but got dict<string>', 2)
414
415  lines =<< trim END
416       var d: dict<number> = {a: 1}
417       g:ExtendDict(d)
418  END
419  CheckDefExecFailure(lines, 'E1012: Type mismatch; expected number but got string', 0)
420  CheckScriptFailure(['vim9script'] + lines, 'E1012:', 1)
421enddef
422
423func g:ExtendList(l)
424  call extend(a:l, ['x'])
425endfunc
426
427def Test_extend_list_item_type()
428  var lines =<< trim END
429       var l: list<number> = [1]
430       extend(l, [2])
431  END
432  CheckDefAndScriptSuccess(lines)
433
434  lines =<< trim END
435       var l: list<number> = [1]
436       extend(l, ['x'])
437  END
438  CheckDefAndScriptFailure(lines, 'E1013: Argument 2: type mismatch, expected list<number> but got list<string>', 2)
439
440  lines =<< trim END
441       var l: list<number> = [1]
442       g:ExtendList(l)
443  END
444  CheckDefExecFailure(lines, 'E1012: Type mismatch; expected number but got string', 0)
445  CheckScriptFailure(['vim9script'] + lines, 'E1012:', 1)
446enddef
447
448def Test_extend_with_error_function()
449  var lines =<< trim END
450      vim9script
451      def F()
452        {
453          var m = 10
454        }
455        echo m
456      enddef
457
458      def Test()
459        var d: dict<any> = {}
460        d->extend({A: 10, Func: function('F', [])})
461      enddef
462
463      Test()
464  END
465  CheckScriptFailure(lines, 'E1001: Variable not found: m')
466enddef
467
468def Test_job_info_return_type()
469  if has('job')
470    job_start(&shell)
471    var jobs = job_info()
472    assert_equal('list<job>', typename(jobs))
473    assert_equal('dict<any>', typename(job_info(jobs[0])))
474    job_stop(jobs[0])
475  endif
476enddef
477
478def Test_filereadable()
479  assert_false(filereadable(""))
480  assert_false(filereadable(test_null_string()))
481
482  CheckDefExecFailure(['echo filereadable(123)'], 'E1174:')
483  CheckDefExecFailure(['echo filereadable(true)'], 'E1174:')
484enddef
485
486def Test_filewritable()
487  assert_false(filewritable(""))
488  assert_false(filewritable(test_null_string()))
489
490  CheckDefExecFailure(['echo filewritable(123)'], 'E1174:')
491  CheckDefExecFailure(['echo filewritable(true)'], 'E1174:')
492enddef
493
494def Test_finddir()
495  CheckDefExecFailure(['echo finddir(true)'], 'E1174:')
496  CheckDefExecFailure(['echo finddir(v:null)'], 'E1174:')
497  CheckDefExecFailure(['echo finddir("")'], 'E1175:')
498enddef
499
500def Test_findfile()
501  CheckDefExecFailure(['echo findfile(true)'], 'E1174:')
502  CheckDefExecFailure(['echo findfile(v:null)'], 'E1174:')
503  CheckDefExecFailure(['echo findfile("")'], 'E1175:')
504enddef
505
506def Test_flattennew()
507  var lines =<< trim END
508      var l = [1, [2, [3, 4]], 5]
509      call assert_equal([1, 2, 3, 4, 5], flattennew(l))
510      call assert_equal([1, [2, [3, 4]], 5], l)
511
512      call assert_equal([1, 2, [3, 4], 5], flattennew(l, 1))
513      call assert_equal([1, [2, [3, 4]], 5], l)
514  END
515  CheckDefAndScriptSuccess(lines)
516
517  lines =<< trim END
518      echo flatten([1, 2, 3])
519  END
520  CheckDefAndScriptFailure(lines, 'E1158:')
521enddef
522
523def Test_fnamemodify()
524  CheckDefSuccess(['echo fnamemodify(test_null_string(), ":p")'])
525  CheckDefSuccess(['echo fnamemodify("", ":p")'])
526  CheckDefSuccess(['echo fnamemodify("file", test_null_string())'])
527  CheckDefSuccess(['echo fnamemodify("file", "")'])
528
529  CheckDefExecFailure(['echo fnamemodify(true, ":p")'], 'E1174: String required for argument 1')
530  CheckDefExecFailure(['echo fnamemodify(v:null, ":p")'], 'E1174: String required for argument 1')
531  CheckDefExecFailure(['echo fnamemodify("file", true)'], 'E1174: String required for argument 2')
532enddef
533
534def Wrong_dict_key_type(items: list<number>): list<number>
535  return filter(items, (_, val) => get({[val]: 1}, 'x'))
536enddef
537
538def Test_filter_wrong_dict_key_type()
539  assert_fails('Wrong_dict_key_type([1, v:null, 3])', 'E1013:')
540enddef
541
542def Test_filter_return_type()
543  var l = filter([1, 2, 3], (_, _) => 1)
544  var res = 0
545  for n in l
546    res += n
547  endfor
548  res->assert_equal(6)
549enddef
550
551def Test_filter_missing_argument()
552  var dict = {aa: [1], ab: [2], ac: [3], de: [4]}
553  var res = dict->filter((k, _) => k =~ 'a' && k !~ 'b')
554  res->assert_equal({aa: [1], ac: [3]})
555enddef
556
557def Test_fullcommand()
558  assert_equal('next', fullcommand('n'))
559  assert_equal('noremap', fullcommand('no'))
560  assert_equal('noremap', fullcommand('nor'))
561  assert_equal('normal', fullcommand('norm'))
562
563  assert_equal('', fullcommand('k'))
564  assert_equal('keepmarks', fullcommand('ke'))
565  assert_equal('keepmarks', fullcommand('kee'))
566  assert_equal('keepmarks', fullcommand('keep'))
567  assert_equal('keepjumps', fullcommand('keepj'))
568
569  assert_equal('dlist', fullcommand('dl'))
570  assert_equal('', fullcommand('dp'))
571  assert_equal('delete', fullcommand('del'))
572  assert_equal('', fullcommand('dell'))
573  assert_equal('', fullcommand('delp'))
574
575  assert_equal('srewind', fullcommand('sre'))
576  assert_equal('scriptnames', fullcommand('scr'))
577  assert_equal('', fullcommand('scg'))
578enddef
579
580def Test_garbagecollect()
581  garbagecollect(true)
582enddef
583
584def Test_getbufinfo()
585  var bufinfo = getbufinfo(bufnr())
586  getbufinfo('%')->assert_equal(bufinfo)
587
588  edit Xtestfile1
589  hide edit Xtestfile2
590  hide enew
591  getbufinfo({bufloaded: true, buflisted: true, bufmodified: false})
592      ->len()->assert_equal(3)
593  bwipe Xtestfile1 Xtestfile2
594enddef
595
596def Test_getbufline()
597  e SomeFile
598  var buf = bufnr()
599  e #
600  var lines = ['aaa', 'bbb', 'ccc']
601  setbufline(buf, 1, lines)
602  getbufline('#', 1, '$')->assert_equal(lines)
603  getbufline(-1, '$', '$')->assert_equal([])
604  getbufline(-1, 1, '$')->assert_equal([])
605
606  bwipe!
607enddef
608
609def Test_getchangelist()
610  new
611  setline(1, 'some text')
612  var changelist = bufnr()->getchangelist()
613  getchangelist('%')->assert_equal(changelist)
614  bwipe!
615enddef
616
617def Test_getchar()
618  while getchar(0)
619  endwhile
620  getchar(true)->assert_equal(0)
621enddef
622
623def Test_getenv()
624  if getenv('does-not_exist') == ''
625    assert_report('getenv() should return null')
626  endif
627  if getenv('does-not_exist') == null
628  else
629    assert_report('getenv() should return null')
630  endif
631  $SOMEENVVAR = 'some'
632  assert_equal('some', getenv('SOMEENVVAR'))
633  unlet $SOMEENVVAR
634enddef
635
636def Test_getcompletion()
637  set wildignore=*.vim,*~
638  var l = getcompletion('run', 'file', true)
639  l->assert_equal([])
640  set wildignore&
641enddef
642
643def Test_getloclist_return_type()
644  var l = getloclist(1)
645  l->assert_equal([])
646
647  var d = getloclist(1, {items: 0})
648  d->assert_equal({items: []})
649enddef
650
651def Test_getfperm()
652  assert_equal('', getfperm(""))
653  assert_equal('', getfperm(test_null_string()))
654
655  CheckDefExecFailure(['echo getfperm(true)'], 'E1174:')
656  CheckDefExecFailure(['echo getfperm(v:null)'], 'E1174:')
657enddef
658
659def Test_getfsize()
660  assert_equal(-1, getfsize(""))
661  assert_equal(-1, getfsize(test_null_string()))
662
663  CheckDefExecFailure(['echo getfsize(true)'], 'E1174:')
664  CheckDefExecFailure(['echo getfsize(v:null)'], 'E1174:')
665enddef
666
667def Test_getftime()
668  assert_equal(-1, getftime(""))
669  assert_equal(-1, getftime(test_null_string()))
670
671  CheckDefExecFailure(['echo getftime(true)'], 'E1174:')
672  CheckDefExecFailure(['echo getftime(v:null)'], 'E1174:')
673enddef
674
675def Test_getftype()
676  assert_equal('', getftype(""))
677  assert_equal('', getftype(test_null_string()))
678
679  CheckDefExecFailure(['echo getftype(true)'], 'E1174:')
680  CheckDefExecFailure(['echo getftype(v:null)'], 'E1174:')
681enddef
682
683def Test_getqflist_return_type()
684  var l = getqflist()
685  l->assert_equal([])
686
687  var d = getqflist({items: 0})
688  d->assert_equal({items: []})
689enddef
690
691def Test_getreg()
692  var lines = ['aaa', 'bbb', 'ccc']
693  setreg('a', lines)
694  getreg('a', true, true)->assert_equal(lines)
695  assert_fails('getreg("ab")', 'E1162:')
696enddef
697
698def Test_getreg_return_type()
699  var s1: string = getreg('"')
700  var s2: string = getreg('"', 1)
701  var s3: list<string> = getreg('"', 1, 1)
702enddef
703
704def Test_getreginfo()
705  var text = 'abc'
706  setreg('a', text)
707  getreginfo('a')->assert_equal({regcontents: [text], regtype: 'v', isunnamed: false})
708  assert_fails('getreginfo("ab")', 'E1162:')
709enddef
710
711def Test_getregtype()
712  var lines = ['aaa', 'bbb', 'ccc']
713  setreg('a', lines)
714  getregtype('a')->assert_equal('V')
715  assert_fails('getregtype("ab")', 'E1162:')
716enddef
717
718def Test_glob()
719  glob('runtest.vim', true, true, true)->assert_equal(['runtest.vim'])
720enddef
721
722def Test_globpath()
723  globpath('.', 'runtest.vim', true, true, true)->assert_equal(['./runtest.vim'])
724enddef
725
726def Test_has()
727  has('eval', true)->assert_equal(1)
728enddef
729
730def Test_hasmapto()
731  hasmapto('foobar', 'i', true)->assert_equal(0)
732  iabbrev foo foobar
733  hasmapto('foobar', 'i', true)->assert_equal(1)
734  iunabbrev foo
735enddef
736
737def Test_index()
738  index(['a', 'b', 'a', 'B'], 'b', 2, true)->assert_equal(3)
739enddef
740
741let s:number_one = 1
742let s:number_two = 2
743let s:string_keep = 'keep'
744
745def Test_insert()
746  var l = insert([2, 1], 3)
747  var res = 0
748  for n in l
749    res += n
750  endfor
751  res->assert_equal(6)
752
753  var m: any = []
754  insert(m, 4)
755  call assert_equal([4], m)
756  extend(m, [6], 0)
757  call assert_equal([6, 4], m)
758
759  var lines =<< trim END
760      insert(test_null_list(), 123)
761  END
762  CheckDefExecAndScriptFailure(lines, 'E1130:', 1)
763
764  lines =<< trim END
765      insert(test_null_blob(), 123)
766  END
767  CheckDefExecAndScriptFailure(lines, 'E1131:', 1)
768
769  assert_equal([1, 2, 3], insert([2, 3], 1))
770  assert_equal([1, 2, 3], insert([2, 3], s:number_one))
771  assert_equal([1, 2, 3], insert([1, 2], 3, 2))
772  assert_equal([1, 2, 3], insert([1, 2], 3, s:number_two))
773  assert_equal(['a', 'b', 'c'], insert(['b', 'c'], 'a'))
774  assert_equal(0z1234, insert(0z34, 0x12))
775
776  CheckDefFailure(['insert("a", 1)'], 'E1013: Argument 1: type mismatch, expected list<any> but got string', 1)
777  CheckDefFailure(['insert([2, 3], "a")'], 'E1013: Argument 2: type mismatch, expected number but got string', 1)
778  CheckDefFailure(['insert([2, 3], 1, "x")'], 'E1013: Argument 3: type mismatch, expected number but got string', 1)
779enddef
780
781def Test_keys_return_type()
782  const var: list<string> = {a: 1, b: 2}->keys()
783  var->assert_equal(['a', 'b'])
784enddef
785
786def Test_line()
787  assert_fails('line(true)', 'E1174')
788enddef
789
790def Test_list2str_str2list_utf8()
791  var s = "\u3042\u3044"
792  var l = [0x3042, 0x3044]
793  str2list(s, true)->assert_equal(l)
794  list2str(l, true)->assert_equal(s)
795enddef
796
797def SID(): number
798  return expand('<SID>')
799          ->matchstr('<SNR>\zs\d\+\ze_$')
800          ->str2nr()
801enddef
802
803def Test_map_function_arg()
804  var lines =<< trim END
805      def MapOne(i: number, v: string): string
806        return i .. ':' .. v
807      enddef
808      var l = ['a', 'b', 'c']
809      map(l, MapOne)
810      assert_equal(['0:a', '1:b', '2:c'], l)
811  END
812  CheckDefAndScriptSuccess(lines)
813enddef
814
815def Test_map_item_type()
816  var lines =<< trim END
817      var l = ['a', 'b', 'c']
818      map(l, (k, v) => k .. '/' .. v )
819      assert_equal(['0/a', '1/b', '2/c'], l)
820  END
821  CheckDefAndScriptSuccess(lines)
822
823  lines =<< trim END
824    var l: list<number> = [0]
825    echo map(l, (_, v) => [])
826  END
827  CheckDefExecAndScriptFailure(lines, 'E1012: Type mismatch; expected number but got list<unknown>', 2)
828
829  lines =<< trim END
830    var l: list<number> = range(2)
831    echo map(l, (_, v) => [])
832  END
833  CheckDefExecAndScriptFailure(lines, 'E1012: Type mismatch; expected number but got list<unknown>', 2)
834
835  lines =<< trim END
836    var d: dict<number> = {key: 0}
837    echo map(d, (_, v) => [])
838  END
839  CheckDefExecAndScriptFailure(lines, 'E1012: Type mismatch; expected number but got list<unknown>', 2)
840enddef
841
842def Test_maparg()
843  var lnum = str2nr(expand('<sflnum>'))
844  map foo bar
845  maparg('foo', '', false, true)->assert_equal({
846        lnum: lnum + 1,
847        script: 0,
848        mode: ' ',
849        silent: 0,
850        noremap: 0,
851        lhs: 'foo',
852        lhsraw: 'foo',
853        nowait: 0,
854        expr: 0,
855        sid: SID(),
856        rhs: 'bar',
857        buffer: 0})
858  unmap foo
859enddef
860
861def Test_mapcheck()
862  iabbrev foo foobar
863  mapcheck('foo', 'i', true)->assert_equal('foobar')
864  iunabbrev foo
865enddef
866
867def Test_maparg_mapset()
868  nnoremap <F3> :echo "hit F3"<CR>
869  var mapsave = maparg('<F3>', 'n', false, true)
870  mapset('n', false, mapsave)
871
872  nunmap <F3>
873enddef
874
875def Test_map_failure()
876  CheckFeature job
877
878  var lines =<< trim END
879      vim9script
880      writefile([], 'Xtmpfile')
881      silent e Xtmpfile
882      var d = {[bufnr('%')]: {a: 0}}
883      au BufReadPost * Func()
884      def Func()
885          if d->has_key('')
886          endif
887          eval d[expand('<abuf>')]->mapnew((_, v: dict<job>) => 0)
888      enddef
889      e
890  END
891  CheckScriptFailure(lines, 'E1013:')
892  au! BufReadPost
893  delete('Xtmpfile')
894enddef
895
896def Test_max()
897  g:flag = true
898  var l1: list<number> = g:flag
899          ? [1, max([2, 3])]
900          : [4, 5]
901  assert_equal([1, 3], l1)
902
903  g:flag = false
904  var l2: list<number> = g:flag
905          ? [1, max([2, 3])]
906          : [4, 5]
907  assert_equal([4, 5], l2)
908enddef
909
910def Test_min()
911  g:flag = true
912  var l1: list<number> = g:flag
913          ? [1, min([2, 3])]
914          : [4, 5]
915  assert_equal([1, 2], l1)
916
917  g:flag = false
918  var l2: list<number> = g:flag
919          ? [1, min([2, 3])]
920          : [4, 5]
921  assert_equal([4, 5], l2)
922enddef
923
924def Test_nr2char()
925  nr2char(97, true)->assert_equal('a')
926enddef
927
928def Test_readdir()
929   eval expand('sautest')->readdir((e) => e[0] !=# '.')
930   eval expand('sautest')->readdirex((e) => e.name[0] !=# '.')
931enddef
932
933def Test_readblob()
934  var blob = 0z12341234
935  writefile(blob, 'Xreadblob')
936  var read: blob = readblob('Xreadblob')
937  assert_equal(blob, read)
938
939  var lines =<< trim END
940      var read: list<string> = readblob('Xreadblob')
941  END
942  CheckDefAndScriptFailure(lines, 'E1012: Type mismatch; expected list<string> but got blob', 1)
943  delete('Xreadblob')
944enddef
945
946def Test_readfile()
947  var text = ['aaa', 'bbb', 'ccc']
948  writefile(text, 'Xreadfile')
949  var read: list<string> = readfile('Xreadfile')
950  assert_equal(text, read)
951
952  var lines =<< trim END
953      var read: dict<string> = readfile('Xreadfile')
954  END
955  CheckDefAndScriptFailure(lines, 'E1012: Type mismatch; expected dict<string> but got list<string>', 1)
956  delete('Xreadfile')
957enddef
958
959def Test_remove_return_type()
960  var l = remove({one: [1, 2], two: [3, 4]}, 'one')
961  var res = 0
962  for n in l
963    res += n
964  endfor
965  res->assert_equal(3)
966enddef
967
968def Test_reverse_return_type()
969  var l = reverse([1, 2, 3])
970  var res = 0
971  for n in l
972    res += n
973  endfor
974  res->assert_equal(6)
975enddef
976
977def Test_search()
978  new
979  setline(1, ['foo', 'bar'])
980  var val = 0
981  # skip expr returns boolean
982  search('bar', 'W', 0, 0, () => val == 1)->assert_equal(2)
983  :1
984  search('bar', 'W', 0, 0, () => val == 0)->assert_equal(0)
985  # skip expr returns number, only 0 and 1 are accepted
986  :1
987  search('bar', 'W', 0, 0, () => 0)->assert_equal(2)
988  :1
989  search('bar', 'W', 0, 0, () => 1)->assert_equal(0)
990  assert_fails("search('bar', '', 0, 0, () => -1)", 'E1023:')
991  assert_fails("search('bar', '', 0, 0, () => -1)", 'E1023:')
992
993  setline(1, "find this word")
994  normal gg
995  var col = 7
996  assert_equal(1, search('this', '', 0, 0, 'col(".") > col'))
997  normal 0
998  assert_equal([1, 6], searchpos('this', '', 0, 0, 'col(".") > col'))
999
1000  col = 5
1001  normal 0
1002  assert_equal(0, search('this', '', 0, 0, 'col(".") > col'))
1003  normal 0
1004  assert_equal([0, 0], searchpos('this', '', 0, 0, 'col(".") > col'))
1005  bwipe!
1006enddef
1007
1008def Test_searchcount()
1009  new
1010  setline(1, "foo bar")
1011  :/foo
1012  searchcount({recompute: true})
1013      ->assert_equal({
1014          exact_match: 1,
1015          current: 1,
1016          total: 1,
1017          maxcount: 99,
1018          incomplete: 0})
1019  bwipe!
1020enddef
1021
1022def Test_searchpair()
1023  new
1024  setline(1, "here { and } there")
1025
1026  normal f{
1027  var col = 15
1028  assert_equal(1, searchpair('{', '', '}', '', 'col(".") > col'))
1029  assert_equal(12, col('.'))
1030  normal 0f{
1031  assert_equal([1, 12], searchpairpos('{', '', '}', '', 'col(".") > col'))
1032
1033  col = 8
1034  normal 0f{
1035  assert_equal(0, searchpair('{', '', '}', '', 'col(".") > col'))
1036  assert_equal(6, col('.'))
1037  normal 0f{
1038  assert_equal([0, 0], searchpairpos('{', '', '}', '', 'col(".") > col'))
1039
1040  var lines =<< trim END
1041      vim9script
1042      setline(1, '()')
1043      normal gg
1044      def Fail()
1045        try
1046          searchpairpos('(', '', ')', 'nW', '[0]->map("")')
1047        catch
1048          g:caught = 'yes'
1049        endtry
1050      enddef
1051      Fail()
1052  END
1053  CheckScriptSuccess(lines)
1054  assert_equal('yes', g:caught)
1055
1056  unlet g:caught
1057  bwipe!
1058enddef
1059
1060def Test_set_get_bufline()
1061  # similar to Test_setbufline_getbufline()
1062  var lines =<< trim END
1063      new
1064      var b = bufnr('%')
1065      hide
1066      assert_equal(0, setbufline(b, 1, ['foo', 'bar']))
1067      assert_equal(['foo'], getbufline(b, 1))
1068      assert_equal(['bar'], getbufline(b, '$'))
1069      assert_equal(['foo', 'bar'], getbufline(b, 1, 2))
1070      exe "bd!" b
1071      assert_equal([], getbufline(b, 1, 2))
1072
1073      split Xtest
1074      setline(1, ['a', 'b', 'c'])
1075      b = bufnr('%')
1076      wincmd w
1077
1078      assert_equal(1, setbufline(b, 5, 'x'))
1079      assert_equal(1, setbufline(b, 5, ['x']))
1080      assert_equal(1, setbufline(b, 5, []))
1081      assert_equal(1, setbufline(b, 5, test_null_list()))
1082
1083      assert_equal(1, 'x'->setbufline(bufnr('$') + 1, 1))
1084      assert_equal(1, ['x']->setbufline(bufnr('$') + 1, 1))
1085      assert_equal(1, []->setbufline(bufnr('$') + 1, 1))
1086      assert_equal(1, test_null_list()->setbufline(bufnr('$') + 1, 1))
1087
1088      assert_equal(['a', 'b', 'c'], getbufline(b, 1, '$'))
1089
1090      assert_equal(0, setbufline(b, 4, ['d', 'e']))
1091      assert_equal(['c'], b->getbufline(3))
1092      assert_equal(['d'], getbufline(b, 4))
1093      assert_equal(['e'], getbufline(b, 5))
1094      assert_equal([], getbufline(b, 6))
1095      assert_equal([], getbufline(b, 2, 1))
1096
1097      if has('job')
1098        setbufline(b, 2, [function('eval'), {key: 123}, test_null_job()])
1099        assert_equal(["function('eval')",
1100                        "{'key': 123}",
1101                        "no process"],
1102                        getbufline(b, 2, 4))
1103      endif
1104
1105      exe 'bwipe! ' .. b
1106  END
1107  CheckDefAndScriptSuccess(lines)
1108enddef
1109
1110def Test_searchdecl()
1111  searchdecl('blah', true, true)->assert_equal(1)
1112enddef
1113
1114def Test_setbufvar()
1115  setbufvar(bufnr('%'), '&syntax', 'vim')
1116  &syntax->assert_equal('vim')
1117  setbufvar(bufnr('%'), '&ts', 16)
1118  &ts->assert_equal(16)
1119  setbufvar(bufnr('%'), '&ai', true)
1120  &ai->assert_equal(true)
1121  setbufvar(bufnr('%'), '&ft', 'filetype')
1122  &ft->assert_equal('filetype')
1123
1124  settabwinvar(1, 1, '&syntax', 'vam')
1125  &syntax->assert_equal('vam')
1126  settabwinvar(1, 1, '&ts', 15)
1127  &ts->assert_equal(15)
1128  setlocal ts=8
1129  settabwinvar(1, 1, '&list', false)
1130  &list->assert_equal(false)
1131  settabwinvar(1, 1, '&list', true)
1132  &list->assert_equal(true)
1133  setlocal list&
1134
1135  setbufvar('%', 'myvar', 123)
1136  getbufvar('%', 'myvar')->assert_equal(123)
1137enddef
1138
1139def Test_setloclist()
1140  var items = [{filename: '/tmp/file', lnum: 1, valid: true}]
1141  var what = {items: items}
1142  setqflist([], ' ', what)
1143  setloclist(0, [], ' ', what)
1144enddef
1145
1146def Test_setreg()
1147  setreg('a', ['aaa', 'bbb', 'ccc'])
1148  var reginfo = getreginfo('a')
1149  setreg('a', reginfo)
1150  getreginfo('a')->assert_equal(reginfo)
1151  assert_fails('setreg("ab", 0)', 'E1162:')
1152enddef
1153
1154def Test_slice()
1155  assert_equal('12345', slice('012345', 1))
1156  assert_equal('123', slice('012345', 1, 4))
1157  assert_equal('1234', slice('012345', 1, -1))
1158  assert_equal('1', slice('012345', 1, -4))
1159  assert_equal('', slice('012345', 1, -5))
1160  assert_equal('', slice('012345', 1, -6))
1161
1162  assert_equal([1, 2, 3, 4, 5], slice(range(6), 1))
1163  assert_equal([1, 2, 3], slice(range(6), 1, 4))
1164  assert_equal([1, 2, 3, 4], slice(range(6), 1, -1))
1165  assert_equal([1], slice(range(6), 1, -4))
1166  assert_equal([], slice(range(6), 1, -5))
1167  assert_equal([], slice(range(6), 1, -6))
1168
1169  assert_equal(0z1122334455, slice(0z001122334455, 1))
1170  assert_equal(0z112233, slice(0z001122334455, 1, 4))
1171  assert_equal(0z11223344, slice(0z001122334455, 1, -1))
1172  assert_equal(0z11, slice(0z001122334455, 1, -4))
1173  assert_equal(0z, slice(0z001122334455, 1, -5))
1174  assert_equal(0z, slice(0z001122334455, 1, -6))
1175enddef
1176
1177def Test_spellsuggest()
1178  if !has('spell')
1179    MissingFeature 'spell'
1180  else
1181    spellsuggest('marrch', 1, true)->assert_equal(['March'])
1182  endif
1183enddef
1184
1185def Test_sort_return_type()
1186  var res: list<number>
1187  res = [1, 2, 3]->sort()
1188enddef
1189
1190def Test_sort_argument()
1191  var lines =<< trim END
1192    var res = ['b', 'a', 'c']->sort('i')
1193    res->assert_equal(['a', 'b', 'c'])
1194
1195    def Compare(a: number, b: number): number
1196      return a - b
1197    enddef
1198    var l = [3, 6, 7, 1, 8, 2, 4, 5]
1199    sort(l, Compare)
1200    assert_equal([1, 2, 3, 4, 5, 6, 7, 8], l)
1201  END
1202  CheckDefAndScriptSuccess(lines)
1203enddef
1204
1205def Test_split()
1206  split('  aa  bb  ', '\W\+', true)->assert_equal(['', 'aa', 'bb', ''])
1207enddef
1208
1209def Run_str2float()
1210  if !has('float')
1211    MissingFeature 'float'
1212  endif
1213    str2float("1.00")->assert_equal(1.00)
1214    str2float("2e-2")->assert_equal(0.02)
1215
1216    CheckDefFailure(['echo str2float(123)'], 'E1013:')
1217    CheckScriptFailure(['vim9script', 'echo str2float(123)'], 'E1024:')
1218  endif
1219enddef
1220
1221def Test_str2nr()
1222  str2nr("1'000'000", 10, true)->assert_equal(1000000)
1223
1224  CheckDefFailure(['echo str2nr(123)'], 'E1013:')
1225  CheckScriptFailure(['vim9script', 'echo str2nr(123)'], 'E1024:')
1226  CheckDefFailure(['echo str2nr("123", "x")'], 'E1013:')
1227  CheckScriptFailure(['vim9script', 'echo str2nr("123", "x")'], 'E1030:')
1228  CheckDefFailure(['echo str2nr("123", 10, "x")'], 'E1013:')
1229  CheckScriptFailure(['vim9script', 'echo str2nr("123", 10, "x")'], 'E1135:')
1230enddef
1231
1232def Test_strchars()
1233  strchars("A\u20dd", true)->assert_equal(1)
1234enddef
1235
1236def Test_submatch()
1237  var pat = 'A\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)'
1238  var Rep = () => range(10)->mapnew((_, v) => submatch(v, true))->string()
1239  var actual = substitute('A123456789', pat, Rep, '')
1240  var expected = "[['A123456789'], ['1'], ['2'], ['3'], ['4'], ['5'], ['6'], ['7'], ['8'], ['9']]"
1241  actual->assert_equal(expected)
1242enddef
1243
1244def Test_synID()
1245  new
1246  setline(1, "text")
1247  synID(1, 1, true)->assert_equal(0)
1248  bwipe!
1249enddef
1250
1251def Test_term_gettty()
1252  if !has('terminal')
1253    MissingFeature 'terminal'
1254  else
1255    var buf = Run_shell_in_terminal({})
1256    term_gettty(buf, true)->assert_notequal('')
1257    StopShellInTerminal(buf)
1258  endif
1259enddef
1260
1261def Test_term_start()
1262  if !has('terminal')
1263    MissingFeature 'terminal'
1264  else
1265    botright new
1266    var winnr = winnr()
1267    term_start(&shell, {curwin: true})
1268    winnr()->assert_equal(winnr)
1269    bwipe!
1270  endif
1271enddef
1272
1273def Test_timer_paused()
1274  var id = timer_start(50, () => 0)
1275  timer_pause(id, true)
1276  var info = timer_info(id)
1277  info[0]['paused']->assert_equal(1)
1278  timer_stop(id)
1279enddef
1280
1281def Test_win_execute()
1282  assert_equal("\n" .. winnr(), win_execute(win_getid(), 'echo winnr()'))
1283  assert_equal('', win_execute(342343, 'echo winnr()'))
1284enddef
1285
1286def Test_win_splitmove()
1287  split
1288  win_splitmove(1, 2, {vertical: true, rightbelow: true})
1289  close
1290enddef
1291
1292def Test_winrestcmd()
1293  split
1294  var cmd = winrestcmd()
1295  wincmd _
1296  exe cmd
1297  assert_equal(cmd, winrestcmd())
1298  close
1299enddef
1300
1301def Test_winsaveview()
1302  var view: dict<number> = winsaveview()
1303
1304  var lines =<< trim END
1305      var view: list<number> = winsaveview()
1306  END
1307  CheckDefAndScriptFailure(lines, 'E1012: Type mismatch; expected list<number> but got dict<number>', 1)
1308enddef
1309
1310
1311
1312
1313" vim: ts=8 sw=2 sts=2 expandtab tw=80 fdm=marker
1314