summaryrefslogtreecommitdiff
path: root/src/testdir/test_vim9_func.vim
blob: eb608c51e8c26160802f2448a95a7a4d25422346 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
" Test various aspects of the Vim9 script language.

source check.vim
source view_util.vim
source vim9.vim
source screendump.vim

func Test_def_basic()
  def SomeFunc(): string
    return 'yes'
  enddef
  call assert_equal('yes', SomeFunc())
endfunc

def ReturnString(): string
  return 'string'
enddef

def ReturnNumber(): number
  return 123
enddef

let g:notNumber = 'string'

def ReturnGlobal(): number
  return g:notNumber
enddef

def Test_return_something()
  assert_equal('string', ReturnString())
  assert_equal(123, ReturnNumber())
  assert_fails('call ReturnGlobal()', 'E1029: Expected number but got string')
enddef

def Test_missing_return()
  CheckDefFailure(['def Missing(): number',
                   '  if g:cond',
                   '    echo "no return"',
                   '  else',
                   '    return 0',
                   '  endif'
                   'enddef'], 'E1027:')
  CheckDefFailure(['def Missing(): number',
                   '  if g:cond',
                   '    return 1',
                   '  else',
                   '    echo "no return"',
                   '  endif'
                   'enddef'], 'E1027:')
  CheckDefFailure(['def Missing(): number',
                   '  if g:cond',
                   '    return 1',
                   '  else',
                   '    return 2',
                   '  endif'
                   '  return 3'
                   'enddef'], 'E1095:')
enddef

let s:nothing = 0
def ReturnNothing()
  s:nothing = 1
  if true
    return
  endif
  s:nothing = 2
enddef

def Test_return_nothing()
  ReturnNothing()
  assert_equal(1, s:nothing)
enddef

func Increment()
  let g:counter += 1
endfunc

def Test_call_ufunc_count()
  g:counter = 1
  Increment()
  Increment()
  Increment()
  # works with and without :call
  assert_equal(4, g:counter)
  call assert_equal(4, g:counter)
  unlet g:counter
enddef

def MyVarargs(arg: string, ...rest: list<string>): string
  let res = arg
  for s in rest
    res ..= ',' .. s
  endfor
  return res
enddef

def Test_call_varargs()
  assert_equal('one', MyVarargs('one'))
  assert_equal('one,two', MyVarargs('one', 'two'))
  assert_equal('one,two,three', MyVarargs('one', 'two', 'three'))
enddef

def MyDefaultArgs(name = 'string'): string
  return name
enddef

def MyDefaultSecond(name: string, second: bool  = true): string
  return second ? name : 'none'
enddef

def Test_call_default_args()
  assert_equal('string', MyDefaultArgs())
  assert_equal('one', MyDefaultArgs('one'))
  assert_fails('call MyDefaultArgs("one", "two")', 'E118:')

  assert_equal('test', MyDefaultSecond('test'))
  assert_equal('test', MyDefaultSecond('test', true))
  assert_equal('none', MyDefaultSecond('test', false))

  CheckScriptFailure(['def Func(arg: number = asdf)', 'enddef', 'defcompile'], 'E1001:')
  CheckScriptFailure(['def Func(arg: number = "text")', 'enddef', 'defcompile'], 'E1013: argument 1: type mismatch, expected number but got string')
enddef

def Test_nested_function()
  def Nested(arg: string): string
    return 'nested ' .. arg
  enddef
  assert_equal('nested function', Nested('function'))

  CheckDefFailure(['def Nested()', 'enddef', 'Nested(66)'], 'E118:')
  CheckDefFailure(['def Nested(arg: string)', 'enddef', 'Nested()'], 'E119:')

  CheckDefFailure(['func Nested()', 'endfunc'], 'E1086:')
  CheckDefFailure(['def s:Nested()', 'enddef'], 'E1075:')
  CheckDefFailure(['def b:Nested()', 'enddef'], 'E1075:')
enddef

func Test_call_default_args_from_func()
  call assert_equal('string', MyDefaultArgs())
  call assert_equal('one', MyDefaultArgs('one'))
  call assert_fails('call MyDefaultArgs("one", "two")', 'E118:')
endfunc

def Test_nested_global_function()
  let lines =<< trim END
      vim9script
      def Outer()
          def g:Inner(): string
              return 'inner'
          enddef
      enddef
      defcompile
      Outer()
      assert_equal('inner', g:Inner())
      delfunc g:Inner
      Outer()
      assert_equal('inner', g:Inner())
      delfunc g:Inner
      Outer()
      assert_equal('inner', g:Inner())
      delfunc g:Inner
  END
  CheckScriptSuccess(lines)

  lines =<< trim END
      vim9script
      def Outer()
          def g:Inner(): string
              return 'inner'
          enddef
      enddef
      defcompile
      Outer()
      Outer()
  END
  CheckScriptFailure(lines, "E122:")

  lines =<< trim END
      vim9script
      def Func()
        echo 'script'
      enddef
      def Outer()
        def Func()
          echo 'inner'
        enddef
      enddef
      defcompile
  END
  CheckScriptFailure(lines, "E1073:")
enddef

def Test_global_local_function()
  let lines =<< trim END
      vim9script
      def g:Func(): string
          return 'global'
      enddef
      def Func(): string
          return 'local'
      enddef
      assert_equal('global', g:Func())
      assert_equal('local', Func())
  END
  CheckScriptSuccess(lines)

  lines =<< trim END
      vim9script
      def g:Funcy()
        echo 'funcy'
      enddef
      s:Funcy()
  END
  CheckScriptFailure(lines, 'E117:')
enddef

func TakesOneArg(arg)
  echo a:arg
endfunc

def Test_call_wrong_args()
  call CheckDefFailure(['TakesOneArg()'], 'E119:')
  call CheckDefFailure(['TakesOneArg(11, 22)'], 'E118:')
  call CheckDefFailure(['bufnr(xxx)'], 'E1001:')
  call CheckScriptFailure(['def Func(Ref: func(s: string))'], 'E475:')

  let lines =<< trim END
    vim9script
    def Func(s: string)
      echo s
    enddef
    Func([])
  END
  call CheckScriptFailure(lines, 'E1013: argument 1: type mismatch, expected string but got list<unknown>', 5)
enddef

" Default arg and varargs
def MyDefVarargs(one: string, two = 'foo', ...rest: list<string>): string
  let res = one .. ',' .. two
  for s in rest
    res ..= ',' .. s
  endfor
  return res
enddef

def Test_call_def_varargs()
  call assert_fails('call MyDefVarargs()', 'E119:')
  assert_equal('one,foo', MyDefVarargs('one'))
  assert_equal('one,two', MyDefVarargs('one', 'two'))
  assert_equal('one,two,three', MyDefVarargs('one', 'two', 'three'))
  CheckDefFailure(['MyDefVarargs("one", 22)'],
      'E1013: argument 2: type mismatch, expected string but got number')
  CheckDefFailure(['MyDefVarargs("one", "two", 123)'],
      'E1013: argument 3: type mismatch, expected string but got number')

  let lines =<< trim END
      vim9script
      def Func(...l: list<string>)
        echo l
      enddef
      Func('a', 'b', 'c')
  END
  CheckScriptSuccess(lines)

  lines =<< trim END
      vim9script
      def Func(...l: list<string>)
        echo l
      enddef
      Func()
  END
  CheckScriptSuccess(lines)

  lines =<< trim END
      vim9script
      def Func(...l: list<string>)
        echo l
      enddef
      Func(1, 2, 3)
  END
  CheckScriptFailure(lines, 'E1013: argument 1: type mismatch')

  lines =<< trim END
      vim9script
      def Func(...l: list<string>)
        echo l
      enddef
      Func('a', 9)
  END
  CheckScriptFailure(lines, 'E1013: argument 2: type mismatch')

  lines =<< trim END
      vim9script
      def Func(...l: list<string>)
        echo l
      enddef
      Func(1, 'a')
  END
  CheckScriptFailure(lines, 'E1013: argument 1: type mismatch')
enddef

def Test_call_call()
  let l = [3, 2, 1]
  call('reverse', [l])
  assert_equal([1, 2, 3], l)
enddef

let s:value = ''

def FuncOneDefArg(opt = 'text')
  s:value = opt
enddef

def FuncTwoDefArg(nr = 123, opt = 'text'): string
  return nr .. opt
enddef

def FuncVarargs(...arg: list<string>): string
  return join(arg, ',')
enddef

def Test_func_type_varargs()
  let RefDefArg: func(?string)
  RefDefArg = FuncOneDefArg
  RefDefArg()
  assert_equal('text', s:value)
  RefDefArg('some')
  assert_equal('some', s:value)

  let RefDef2Arg: func(?number, ?string): string
  RefDef2Arg = FuncTwoDefArg
  assert_equal('123text', RefDef2Arg())
  assert_equal('99text', RefDef2Arg(99))
  assert_equal('77some', RefDef2Arg(77, 'some'))

  call CheckDefFailure(['let RefWrong: func(string?)'], 'E1010:')
  call CheckDefFailure(['let RefWrong: func(?string, string)'], 'E1007:')

  let RefVarargs: func(...list<string>): string
  RefVarargs = FuncVarargs
  assert_equal('', RefVarargs())
  assert_equal('one', RefVarargs('one'))
  assert_equal('one,two', RefVarargs('one', 'two'))

  call CheckDefFailure(['let RefWrong: func(...list<string>, string)'], 'E110:')
  call CheckDefFailure(['let RefWrong: func(...list<string>, ?string)'], 'E110:')
enddef

" Only varargs
def MyVarargsOnly(...args: list<string>): string
  return join(args, ',')
enddef

def Test_call_varargs_only()
  assert_equal('', MyVarargsOnly())
  assert_equal('one', MyVarargsOnly('one'))
  assert_equal('one,two', MyVarargsOnly('one', 'two'))
  call CheckDefFailure(['MyVarargsOnly(1)'], 'E1013: argument 1: type mismatch, expected string but got number')
  call CheckDefFailure(['MyVarargsOnly("one", 2)'], 'E1013: argument 2: type mismatch, expected string but got number')
enddef

def Test_using_var_as_arg()
  call writefile(['def Func(x: number)',  'let x = 234', 'enddef', 'defcompile'], 'Xdef')
  call assert_fails('so Xdef', 'E1006:')
  call delete('Xdef')
enddef

def DictArg(arg: dict<string>)
  arg['key'] = 'value'
enddef

def ListArg(arg: list<string>)
  arg[0] = 'value'
enddef

def Test_assign_to_argument()
  # works for dict and list
  let d: dict<string> = {}
  DictArg(d)
  assert_equal('value', d['key'])
  let l: list<string> = []
  ListArg(l)
  assert_equal('value', l[0])

  call CheckScriptFailure(['def Func(arg: number)', 'arg = 3', 'enddef', 'defcompile'], 'E1090:')
enddef

def Test_call_func_defined_later()
  call assert_equal('one', g:DefinedLater('one'))
  call assert_fails('call NotDefined("one")', 'E117:')
enddef

func DefinedLater(arg)
  return a:arg
endfunc

def Test_call_funcref()
  assert_equal(3, g:SomeFunc('abc'))
  assert_fails('NotAFunc()', 'E117:') # comment after call
  assert_fails('g:NotAFunc()', 'E117:')

  let lines =<< trim END
    vim9script
    def RetNumber(): number
      return 123
    enddef
    let Funcref: func: number = function('RetNumber')
    assert_equal(123, Funcref())
  END
  CheckScriptSuccess(lines)

  lines =<< trim END
    vim9script
    def RetNumber(): number
      return 123
    enddef
    def Bar(F: func: number): number
      return F()
    enddef
    let Funcref = function('RetNumber')
    assert_equal(123, Bar(Funcref))
  END
  CheckScriptSuccess(lines)

  lines =<< trim END
    vim9script
    def UseNumber(nr: number)
      echo nr
    enddef
    let Funcref: func(number) = function('UseNumber')
    Funcref(123)
  END
  CheckScriptSuccess(lines)

  lines =<< trim END
    vim9script
    def UseNumber(nr: number)
      echo nr
    enddef
    let Funcref: func(string) = function('UseNumber')
  END
  CheckScriptFailure(lines, 'E1012: type mismatch, expected func(string) but got func(number)')

  lines =<< trim END
    vim9script
    def EchoNr(nr = 34)
      g:echo = nr
    enddef
    let Funcref: func(?number) = function('EchoNr')
    Funcref()
    assert_equal(34, g:echo)
    Funcref(123)
    assert_equal(123, g:echo)
  END
  CheckScriptSuccess(lines)

  lines =<< trim END
    vim9script
    def EchoList(...l: list<number>)
      g:echo = l
    enddef
    let Funcref: func(...list<number>) = function('EchoList')
    Funcref()
    assert_equal([], g:echo)
    Funcref(1, 2, 3)
    assert_equal([1, 2, 3], g:echo)
  END
  CheckScriptSuccess(lines)

  lines =<< trim END
    vim9script
    def OptAndVar(nr: number, opt = 12, ...l: list<number>): number
      g:optarg = opt
      g:listarg = l
      return nr
    enddef
    let Funcref: func(number, ?number, ...list<number>): number = function('OptAndVar')
    assert_equal(10, Funcref(10))
    assert_equal(12, g:optarg)
    assert_equal([], g:listarg)

    assert_equal(11, Funcref(11, 22))
    assert_equal(22, g:optarg)
    assert_equal([], g:listarg)

    assert_equal(17, Funcref(17, 18, 1, 2, 3))
    assert_equal(18, g:optarg)
    assert_equal([1, 2, 3], g:listarg)
  END
  CheckScriptSuccess(lines)
enddef

let SomeFunc = function('len')
let NotAFunc = 'text'

def CombineFuncrefTypes()
  # same arguments, different return type
  let Ref1: func(bool): string
  let Ref2: func(bool): number
  let Ref3: func(bool): any
  Ref3 = g:cond ? Ref1 : Ref2

  # different number of arguments
  let Refa1: func(bool): number
  let Refa2: func(bool, number): number
  let Refa3: func: number
  Refa3 = g:cond ? Refa1 : Refa2

  # different argument types
  let Refb1: func(bool, string): number
  let Refb2: func(string, number): number
  let Refb3: func(any, any): number
  Refb3 = g:cond ? Refb1 : Refb2
enddef

def FuncWithForwardCall()
  return g:DefinedEvenLater("yes")
enddef

def DefinedEvenLater(arg: string): string
  return arg
enddef

def Test_error_in_nested_function()
  # Error in called function requires unwinding the call stack.
  assert_fails('call FuncWithForwardCall()', 'E1096:')
enddef

def Test_return_type_wrong()
  CheckScriptFailure([
        'def Func(): number',
        'return "a"',
        'enddef',
        'defcompile'], 'expected number but got string')
  CheckScriptFailure([
        'def Func(): string',
        'return 1',
        'enddef',
        'defcompile'], 'expected string but got number')
  CheckScriptFailure([
        'def Func(): void',
        'return "a"',
        'enddef',
        'defcompile'],
        'E1096: Returning a value in a function without a return type')
  CheckScriptFailure([
        'def Func()',
        'return "a"',
        'enddef',
        'defcompile'],
        'E1096: Returning a value in a function without a return type')

  CheckScriptFailure([
        'def Func(): number',
        'return',
        'enddef',
        'defcompile'], 'E1003:')

  CheckScriptFailure(['def Func(): list', 'return []', 'enddef'], 'E1008:')
  CheckScriptFailure(['def Func(): dict', 'return {}', 'enddef'], 'E1008:')
  CheckScriptFailure(['def Func()', 'return 1'], 'E1057:')

  CheckScriptFailure([
        'vim9script',
        'def FuncB()',
        '  return 123',
        'enddef',
        'def FuncA()',
        '   FuncB()',
        'enddef',
        'defcompile'], 'E1096:')
enddef

def Test_arg_type_wrong()
  CheckScriptFailure(['def Func3(items: list)', 'echo "a"', 'enddef'], 'E1008: Missing <type>')
  CheckScriptFailure(['def Func4(...)', 'echo "a"', 'enddef'], 'E1055: Missing name after ...')
  CheckScriptFailure(['def Func5(items:string)', 'echo "a"'], 'E1069:')
  CheckScriptFailure(['def Func5(items)', 'echo "a"'], 'E1077:')
enddef

def Test_vim9script_call()
  let lines =<< trim END
    vim9script
    let var = ''
    def MyFunc(arg: string)
       var = arg
    enddef
    MyFunc('foobar')
    assert_equal('foobar', var)

    let str = 'barfoo'
    str->MyFunc()
    assert_equal('barfoo', var)

    g:value = 'value'
    g:value->MyFunc()
    assert_equal('value', var)

    let listvar = []
    def ListFunc(arg: list<number>)
       listvar = arg
    enddef
    [1, 2, 3]->ListFunc()
    assert_equal([1, 2, 3], listvar)

    let dictvar = {}
    def DictFunc(arg: dict<number>)
       dictvar = arg
    enddef
    {'a': 1, 'b': 2}->DictFunc()
    assert_equal(#{a: 1, b: 2}, dictvar)
    def CompiledDict()
      {'a': 3, 'b': 4}->DictFunc()
    enddef
    CompiledDict()
    assert_equal(#{a: 3, b: 4}, dictvar)

    #{a: 3, b: 4}->DictFunc()
    assert_equal(#{a: 3, b: 4}, dictvar)

    ('text')->MyFunc()
    assert_equal('text', var)
    ("some")->MyFunc()
    assert_equal('some', var)

    # line starting with single quote is not a mark
    # line starting with double quote can be a method call
    'asdfasdf'->MyFunc()
    assert_equal('asdfasdf', var)
    "xyz"->MyFunc()
    assert_equal('xyz', var)

    def UseString()
      'xyork'->MyFunc()
    enddef
    UseString()
    assert_equal('xyork', var)

    def UseString2()
      "knife"->MyFunc()
    enddef
    UseString2()
    assert_equal('knife', var)

    # prepending a colon makes it a mark
    new
    setline(1, ['aaa', 'bbb', 'ccc'])
    normal! 3Gmt1G
    :'t
    assert_equal(3, getcurpos()[1])
    bwipe!

    MyFunc(
        'continued'
        )
    assert_equal('continued',
            var
            )

    call MyFunc(
        'more'
          ..
          'lines'
        )
    assert_equal(
        'morelines',
        var)
  END
  writefile(lines, 'Xcall.vim')
  source Xcall.vim
  delete('Xcall.vim')
enddef

def Test_vim9script_call_fail_decl()
  let lines =<< trim END
    vim9script
    let var = ''
    def MyFunc(arg: string)
       let var = 123
    enddef
    defcompile
  END
  CheckScriptFailure(lines, 'E1054:')
enddef

def Test_vim9script_call_fail_type()
  let lines =<< trim END
    vim9script
    def MyFunc(arg: string)
      echo arg
    enddef
    MyFunc(1234)
  END
  CheckScriptFailure(lines, 'E1013: argument 1: type mismatch, expected string but got number')
enddef

def Test_vim9script_call_fail_const()
  let lines =<< trim END
    vim9script
    const var = ''
    def MyFunc(arg: string)
       var = 'asdf'
    enddef
    defcompile
  END
  writefile(lines, 'Xcall_const.vim')
  assert_fails('source Xcall_const.vim', 'E46:')
  delete('Xcall_const.vim')
enddef

" Test that inside :function a Python function can be defined, :def is not
" recognized.
func Test_function_python()
  CheckFeature python3
  let py = 'python3'
  execute py "<< EOF"
def do_something():
  return 1
EOF
endfunc

def Test_delfunc()
  let lines =<< trim END
    vim9script
    def g:GoneSoon()
      echo 'hello'
    enddef

    def CallGoneSoon()
      GoneSoon()
    enddef
    defcompile

    delfunc g:GoneSoon
    CallGoneSoon()
  END
  writefile(lines, 'XToDelFunc')
  assert_fails('so XToDelFunc', 'E933:')
  assert_fails('so XToDelFunc', 'E933:')

  delete('XToDelFunc')
enddef

def Test_redef_failure()
  call writefile(['def Func0(): string',  'return "Func0"', 'enddef'], 'Xdef')
  so Xdef
  call writefile(['def Func1(): string',  'return "Func1"', 'enddef'], 'Xdef')
  so Xdef
  call writefile(['def! Func0(): string', 'enddef', 'defcompile'], 'Xdef')
  call assert_fails('so Xdef', 'E1027:')
  call writefile(['def Func2(): string',  'return "Func2"', 'enddef'], 'Xdef')
  so Xdef
  call delete('Xdef')

  call assert_equal(0, g:Func0())
  call assert_equal('Func1', g:Func1())
  call assert_equal('Func2', g:Func2())

  delfunc! Func0
  delfunc! Func1
  delfunc! Func2
enddef

def Test_vim9script_func()
  let lines =<< trim END
    vim9script
    func Func(arg)
      echo a:arg
    endfunc
    Func('text')
  END
  writefile(lines, 'XVim9Func')
  so XVim9Func

  delete('XVim9Func')
enddef

" Test for internal functions returning different types
func Test_InternalFuncRetType()
  let lines =<< trim END
    def RetFloat(): float
      return ceil(1.456)
    enddef

    def RetListAny(): list<any>
      return items({'k': 'v'})
    enddef

    def RetListString(): list<string>
      return split('a:b:c', ':')
    enddef

    def RetListDictAny(): list<dict<any>>
      return getbufinfo()
    enddef

    def RetDictNumber(): dict<number>
      return wordcount()
    enddef

    def RetDictString(): dict<string>
      return environ()
    enddef
  END
  call writefile(lines, 'Xscript')
  source Xscript

  call assert_equal(2.0, RetFloat())
  call assert_equal([['k', 'v']], RetListAny())
  call assert_equal(['a', 'b', 'c'], RetListString())
  call assert_notequal([], RetListDictAny())
  call assert_notequal({}, RetDictNumber())
  call assert_notequal({}, RetDictString())
  call delete('Xscript')
endfunc

" Test for passing too many or too few arguments to internal functions
func Test_internalfunc_arg_error()
  let l =<< trim END
    def! FArgErr(): float
      return ceil(1.1, 2)
    enddef
    defcompile
  END
  call writefile(l, 'Xinvalidarg')
  call assert_fails('so Xinvalidarg', 'E118:')
  let l =<< trim END
    def! FArgErr(): float
      return ceil()
    enddef
    defcompile
  END
  call writefile(l, 'Xinvalidarg')
  call assert_fails('so Xinvalidarg', 'E119:')
  call delete('Xinvalidarg')
endfunc

let s:funcResult = 0

def FuncNoArgNoRet()
  s:funcResult = 11
enddef

def FuncNoArgRetNumber(): number
  s:funcResult = 22
  return 1234
enddef

def FuncNoArgRetString(): string
  s:funcResult = 45
  return 'text'
enddef

def FuncOneArgNoRet(arg: number)
  s:funcResult = arg
enddef

def FuncOneArgRetNumber(arg: number): number
  s:funcResult = arg
  return arg
enddef

def FuncTwoArgNoRet(one: bool, two: number)
  s:funcResult = two
enddef

def FuncOneArgRetString(arg: string): string
  return arg
enddef

def FuncOneArgRetAny(arg: any): any
  return arg
enddef

def Test_func_type()
  let Ref1: func()
  s:funcResult = 0
  Ref1 = FuncNoArgNoRet
  Ref1()
  assert_equal(11, s:funcResult)

  let Ref2: func
  s:funcResult = 0
  Ref2 = FuncNoArgNoRet
  Ref2()
  assert_equal(11, s:funcResult)

  s:funcResult = 0
  Ref2 = FuncOneArgNoRet
  Ref2(12)
  assert_equal(12, s:funcResult)

  s:funcResult = 0
  Ref2 = FuncNoArgRetNumber
  assert_equal(1234, Ref2())
  assert_equal(22, s:funcResult)

  s:funcResult = 0
  Ref2 = FuncOneArgRetNumber
  assert_equal(13, Ref2(13))
  assert_equal(13, s:funcResult)
enddef

def Test_repeat_return_type()
  let res = 0
  for n in repeat([1], 3)
    res += n
  endfor
  assert_equal(3, res)

  res = 0
  for n in add([1, 2], 3)
    res += n
  endfor
  assert_equal(6, res)
enddef

def Test_argv_return_type()
  next fileone filetwo
  let res = ''
  for name in argv()
    res ..= name
  endfor
  assert_equal('fileonefiletwo', res)
enddef

def Test_func_type_part()
  let RefVoid: func: void
  RefVoid = FuncNoArgNoRet
  RefVoid = FuncOneArgNoRet
  CheckDefFailure(['let RefVoid: func: void', 'RefVoid = FuncNoArgRetNumber'], 'E1012: type mismatch, expected func() but got func(): number')
  CheckDefFailure(['let RefVoid: func: void', 'RefVoid = FuncNoArgRetString'], 'E1012: type mismatch, expected func() but got func(): string')

  let RefAny: func(): any
  RefAny = FuncNoArgRetNumber
  RefAny = FuncNoArgRetString
  CheckDefFailure(['let RefAny: func(): any', 'RefAny = FuncNoArgNoRet'], 'E1012: type mismatch, expected func(): any but got func()')
  CheckDefFailure(['let RefAny: func(): any', 'RefAny = FuncOneArgNoRet'], 'E1012: type mismatch, expected func(): any but got func(number)')

  let RefNr: func: number
  RefNr = FuncNoArgRetNumber
  RefNr = FuncOneArgRetNumber
  CheckDefFailure(['let RefNr: func: number', 'RefNr = FuncNoArgNoRet'], 'E1012: type mismatch, expected func(): number but got func()')
  CheckDefFailure(['let RefNr: func: number', 'RefNr = FuncNoArgRetString'], 'E1012: type mismatch, expected func(): number but got func(): string')

  let RefStr: func: string
  RefStr = FuncNoArgRetString
  RefStr = FuncOneArgRetString
  CheckDefFailure(['let RefStr: func: string', 'RefStr = FuncNoArgNoRet'], 'E1012: type mismatch, expected func(): string but got func()')
  CheckDefFailure(['let RefStr: func: string', 'RefStr = FuncNoArgRetNumber'], 'E1012: type mismatch, expected func(): string but got func(): number')
enddef

def Test_func_type_fails()
  CheckDefFailure(['let ref1: func()'], 'E704:')

  CheckDefFailure(['let Ref1: func()', 'Ref1 = FuncNoArgRetNumber'], 'E1012: type mismatch, expected func() but got func(): number')
  CheckDefFailure(['let Ref1: func()', 'Ref1 = FuncOneArgNoRet'], 'E1012: type mismatch, expected func() but got func(number)')
  CheckDefFailure(['let Ref1: func()', 'Ref1 = FuncOneArgRetNumber'], 'E1012: type mismatch, expected func() but got func(number): number')
  CheckDefFailure(['let Ref1: func(bool)', 'Ref1 = FuncTwoArgNoRet'], 'E1012: type mismatch, expected func(bool) but got func(bool, number)')
  CheckDefFailure(['let Ref1: func(?bool)', 'Ref1 = FuncTwoArgNoRet'], 'E1012: type mismatch, expected func(?bool) but got func(bool, number)')
  CheckDefFailure(['let Ref1: func(...bool)', 'Ref1 = FuncTwoArgNoRet'], 'E1012: type mismatch, expected func(...bool) but got func(bool, number)')

  call CheckDefFailure(['let RefWrong: func(string ,number)'], 'E1068:')
  call CheckDefFailure(['let RefWrong: func(string,number)'], 'E1069:')
  call CheckDefFailure(['let RefWrong: func(bool, bool, bool, bool, bool, bool, bool, bool, bool, bool, bool, bool, bool, bool, bool, bool, bool, bool, bool, bool)'], 'E1005:')
  call CheckDefFailure(['let RefWrong: func(bool):string'], 'E1069:')
enddef

def Test_func_return_type()
  let nr: number
  nr = FuncNoArgRetNumber()
  assert_equal(1234, nr)

  nr = FuncOneArgRetAny(122)
  assert_equal(122, nr)

  let str: string
  str = FuncOneArgRetAny('yes')
  assert_equal('yes', str)

  CheckDefFailure(['let str: string', 'str = FuncNoArgRetNumber()'], 'E1012: type mismatch, expected string but got number')
enddef

def MultiLine(
    arg1: string,
    arg2 = 1234,
    ...rest: list<string>
      ): string
  return arg1 .. arg2 .. join(rest, '-')
enddef

def MultiLineComment(
    arg1: string, # comment
    arg2 = 1234, # comment
    ...rest: list<string> # comment
      ): string # comment
  return arg1 .. arg2 .. join(rest, '-')
enddef

def Test_multiline()
  assert_equal('text1234', MultiLine('text'))
  assert_equal('text777', MultiLine('text', 777))
  assert_equal('text777one', MultiLine('text', 777, 'one'))
  assert_equal('text777one-two', MultiLine('text', 777, 'one', 'two'))
enddef

func Test_multiline_not_vim9()
  call assert_equal('text1234', MultiLine('text'))
  call assert_equal('text777', MultiLine('text', 777))
  call assert_equal('text777one', MultiLine('text', 777, 'one'))
  call assert_equal('text777one-two', MultiLine('text', 777, 'one', 'two'))
endfunc


" When using CheckScriptFailure() for the below test, E1010 is generated instead
" of E1056.
func Test_E1056_1059()
  let caught_1056 = 0
  try
    def F():
      return 1
    enddef
  catch /E1056:/
    let caught_1056 = 1
  endtry
  call assert_equal(1, caught_1056)

  let caught_1059 = 0
  try
    def F5(items : list)
      echo 'a'
    enddef
  catch /E1059:/
    let caught_1059 = 1
  endtry
  call assert_equal(1, caught_1059)
endfunc

func DelMe()
  echo 'DelMe'
endfunc

def Test_error_reporting()
  # comment lines at the start of the function
  let lines =<< trim END
    " comment
    def Func()
      # comment
      # comment
      invalid
    enddef
    defcompile
  END
  call writefile(lines, 'Xdef')
  try
    source Xdef
    assert_report('should have failed')
  catch /E476:/
    assert_match('Invalid command: invalid', v:exception)
    assert_match(', line 3$', v:throwpoint)
  endtry

  # comment lines after the start of the function
  lines =<< trim END
    " comment
    def Func()
      let x = 1234
      # comment
      # comment
      invalid
    enddef
    defcompile
  END
  call writefile(lines, 'Xdef')
  try
    source Xdef
    assert_report('should have failed')
  catch /E476:/
    assert_match('Invalid command: invalid', v:exception)
    assert_match(', line 4$', v:throwpoint)
  endtry

  lines =<< trim END
    vim9script
    def Func()
      let db = #{foo: 1, bar: 2}
      # comment
      let x = db.asdf
    enddef
    defcompile
    Func()
  END
  call writefile(lines, 'Xdef')
  try
    source Xdef
    assert_report('should have failed')
  catch /E716:/
    assert_match('_Func, line 3$', v:throwpoint)
  endtry

  call delete('Xdef')
enddef

def Test_deleted_function()
  CheckDefExecFailure([
      'let RefMe: func = function("g:DelMe")',
      'delfunc g:DelMe',
      'echo RefMe()'], 'E117:')
enddef

def Test_unknown_function()
  CheckDefExecFailure([
      'let Ref: func = function("NotExist")',
      'delfunc g:NotExist'], 'E700:')
enddef

def RefFunc(Ref: func(string): string): string
  return Ref('more')
enddef

def Test_closure_simple()
  let local = 'some '
  assert_equal('some more', RefFunc({s -> local .. s}))
enddef

def MakeRef()
  let local = 'some '
  g:Ref = {s -> local .. s}
enddef

def Test_closure_ref_after_return()
  MakeRef()
  assert_equal('some thing', g:Ref('thing'))
  unlet g:Ref
enddef

def MakeTwoRefs()
  let local = ['some']
  g:Extend = {s -> local->add(s)}
  g:Read = {-> local}
enddef

def Test_closure_two_refs()
  MakeTwoRefs()
  assert_equal('some', join(g:Read(), ' '))
  g:Extend('more')
  assert_equal('some more', join(g:Read(), ' '))
  g:Extend('even')
  assert_equal('some more even', join(g:Read(), ' '))

  unlet g:Extend
  unlet g:Read
enddef

def ReadRef(Ref: func(): list<string>): string
  return join(Ref(), ' ')
enddef

def ExtendRef(Ref: func(string), add: string)
  Ref(add)
enddef

def Test_closure_two_indirect_refs()
  MakeTwoRefs()
  assert_equal('some', ReadRef(g:Read))
  ExtendRef(g:Extend, 'more')
  assert_equal('some more', ReadRef(g:Read))
  ExtendRef(g:Extend, 'even')
  assert_equal('some more even', ReadRef(g:Read))

  unlet g:Extend
  unlet g:Read
enddef

def MakeArgRefs(theArg: string)
  let local = 'loc_val'
  g:UseArg = {s -> theArg .. '/' .. local .. '/' .. s}
enddef

def MakeArgRefsVarargs(theArg: string, ...rest: list<string>)
  let local = 'the_loc'
  g:UseVararg = {s -> theArg .. '/' .. local .. '/' .. s .. '/' .. join(rest)}
enddef

def Test_closure_using_argument()
  MakeArgRefs('arg_val')
  assert_equal('arg_val/loc_val/call_val', g:UseArg('call_val'))

  MakeArgRefsVarargs('arg_val', 'one', 'two')
  assert_equal('arg_val/the_loc/call_val/one two', g:UseVararg('call_val'))

  unlet g:UseArg
  unlet g:UseVararg
enddef

def MakeGetAndAppendRefs()
  let local = 'a'

  def Append(arg: string)
    local ..= arg
  enddef
  g:Append = Append

  def Get(): string
    return local
  enddef
  g:Get = Get
enddef

def Test_closure_append_get()
  MakeGetAndAppendRefs()
  assert_equal('a', g:Get())
  g:Append('-b')
  assert_equal('a-b', g:Get())
  g:Append('-c')
  assert_equal('a-b-c', g:Get())

  unlet g:Append
  unlet g:Get
enddef

def Test_nested_closure()
  let local = 'text'
  def Closure(arg: string): string
    return local .. arg
  enddef
  assert_equal('text!!!', Closure('!!!'))
enddef

func GetResult(Ref)
  return a:Ref('some')
endfunc

def Test_call_closure_not_compiled()
  let text = 'text'
  g:Ref = {s ->  s .. text}
  assert_equal('sometext', GetResult(g:Ref))
enddef

def Test_sort_return_type()
  let res: list<number>
  res = [1, 2, 3]->sort()
enddef

def Test_getqflist_return_type()
  let l = getqflist()
  assert_equal([], l)

  let d = getqflist(#{items: 0})
  assert_equal(#{items: []}, d)
enddef

def Test_getloclist_return_type()
  let l = getloclist(1)
  assert_equal([], l)

  let d = getloclist(1, #{items: 0})
  assert_equal(#{items: []}, d)
enddef

def Test_copy_return_type()
  let l = copy([1, 2, 3])
  let res = 0
  for n in l
    res += n
  endfor
  assert_equal(6, res)

  let dl = deepcopy([1, 2, 3])
  res = 0
  for n in dl
    res += n
  endfor
  assert_equal(6, res)

  dl = deepcopy([1, 2, 3], true)
enddef

def Test_extend_return_type()
  let l = extend([1, 2], [3])
  let res = 0
  for n in l
    res += n
  endfor
  assert_equal(6, res)
enddef

def Test_garbagecollect()
  garbagecollect(true)
enddef

def Test_insert_return_type()
  let l = insert([2, 1], 3)
  let res = 0
  for n in l
    res += n
  endfor
  assert_equal(6, res)
enddef

def Test_keys_return_type()
  const var: list<string> = #{a: 1, b: 2}->keys()
  assert_equal(['a', 'b'], var)
enddef

def Test_reverse_return_type()
  let l = reverse([1, 2, 3])
  let res = 0
  for n in l
    res += n
  endfor
  assert_equal(6, res)
enddef

def Test_remove_return_type()
  let l = remove(#{one: [1, 2], two: [3, 4]}, 'one')
  let res = 0
  for n in l
    res += n
  endfor
  assert_equal(3, res)
enddef

def Test_filter_return_type()
  let l = filter([1, 2, 3], {-> 1})
  let res = 0
  for n in l
    res += n
  endfor
  assert_equal(6, res)
enddef

def Test_bufnr()
  let buf = bufnr()
  assert_equal(buf, bufnr('%'))

  buf = bufnr('Xdummy', true)
  assert_notequal(-1, buf)
  exe 'bwipe! ' .. buf
enddef

def Test_col()
  new
  setline(1, 'asdf')
  assert_equal(5, col([1, '$']))
enddef

def Test_char2nr()
  assert_equal(12354, char2nr('あ', true))
enddef

def Test_getreg_return_type()
  let s1: string = getreg('"')
  let s2: string = getreg('"', 1)
  let s3: list<string> = getreg('"', 1, 1)
enddef

def Wrong_dict_key_type(items: list<number>): list<number>
  return filter(items, {_, val -> get({val: 1}, 'x')})
enddef

def Test_wrong_dict_key_type()
  assert_fails('Wrong_dict_key_type([1, 2, 3])', 'E1029:')
enddef

def Line_continuation_in_def(dir: string = ''): string
    let path: string = empty(dir)
            \ ? 'empty'
            \ : 'full'
    return path
enddef

def Test_line_continuation_in_def()
  assert_equal('full', Line_continuation_in_def('.'))
enddef

def Line_continuation_in_lambda(): list<number>
  let x = range(97, 100)
      ->map({_, v -> nr2char(v)
          ->toupper()})
      ->reverse()
  return x
enddef

def Test_line_continuation_in_lambda()
  assert_equal(['D', 'C', 'B', 'A'], Line_continuation_in_lambda())
enddef

func Test_silent_echo()
  CheckScreendump

  let lines =<< trim END
    vim9script
    def EchoNothing()
      silent echo ''
    enddef
    defcompile
  END
  call writefile(lines, 'XTest_silent_echo')

  " Check that the balloon shows up after a mouse move
  let buf = RunVimInTerminal('-S XTest_silent_echo', {'rows': 6})
  call term_sendkeys(buf, ":abc")
  call VerifyScreenDump(buf, 'Test_vim9_silent_echo', {})

  " clean up
  call StopVimInTerminal(buf)
  call delete('XTest_silent_echo')
endfunc

def Test_search()
  new
  setline(1, ['foo', 'bar'])
  let val = 0
  # skip expr returns boolean
  assert_equal(2, search('bar', 'W', 0, 0, {-> val == 1}))
  :1
  assert_equal(0, search('bar', 'W', 0, 0, {-> val == 0}))
  # skip expr returns number, only 0 and 1 are accepted
  :1
  assert_equal(2, search('bar', 'W', 0, 0, {-> 0}))
  :1
  assert_equal(0, search('bar', 'W', 0, 0, {-> 1}))
  assert_fails("search('bar', '', 0, 0, {-> -1})", 'E1023:')
  assert_fails("search('bar', '', 0, 0, {-> -1})", 'E1023:')
enddef

def Test_readdir()
   eval expand('sautest')->readdir({e -> e[0] !=# '.'})
   eval expand('sautest')->readdirex({e -> e.name[0] !=# '.'})
enddef

def Test_setbufvar()
   setbufvar(bufnr('%'), '&syntax', 'vim')
   assert_equal('vim', &syntax)
   setbufvar(bufnr('%'), '&ts', 16)
   assert_equal(16, &ts)
   settabwinvar(1, 1, '&syntax', 'vam')
   assert_equal('vam', &syntax)
   settabwinvar(1, 1, '&ts', 15)
   assert_equal(15, &ts)
   setlocal ts=8

   setbufvar('%', 'myvar', 123)
   assert_equal(123, getbufvar('%', 'myvar'))
enddef

def Test_bufwinid()
  let origwin = win_getid()
  below split SomeFile
  let SomeFileID = win_getid()
  below split OtherFile
  below split SomeFile
  assert_equal(SomeFileID, bufwinid('SomeFile'))

  win_gotoid(origwin)
  only
  bwipe SomeFile
  bwipe OtherFile
enddef

def Test_getbufline()
  e SomeFile
  let buf = bufnr()
  e #
  let lines = ['aaa', 'bbb', 'ccc']
  setbufline(buf, 1, lines)
  assert_equal(lines, getbufline('#', 1, '$'))

  bwipe!
enddef

def Test_getchangelist()
  new
  setline(1, 'some text')
  let changelist = bufnr()->getchangelist()
  assert_equal(changelist, getchangelist('%'))
  bwipe!
enddef

def Test_setreg()
  setreg('a', ['aaa', 'bbb', 'ccc'])
  let reginfo = getreginfo('a')
  setreg('a', reginfo)
  assert_equal(reginfo, getreginfo('a'))
enddef 

def Test_bufname()
  split SomeFile
  assert_equal('SomeFile', bufname('%'))
  edit OtherFile
  assert_equal('SomeFile', bufname('#'))
  close
enddef

def Test_getbufinfo()
  let bufinfo = getbufinfo(bufnr())
  assert_equal(bufinfo, getbufinfo('%'))

  edit Xtestfile1
  hide edit Xtestfile2
  hide enew
  getbufinfo(#{bufloaded: true, buflisted: true, bufmodified: false})
      ->len()->assert_equal(3)
  bwipe Xtestfile1 Xtestfile2
enddef

def Test_getchar()
  assert_equal(0, getchar(true))
enddef

def Test_getcompletion()
  set wildignore=*.vim,*~
  let l = getcompletion('run', 'file', true)
  assert_equal([], l)
  set wildignore&
enddef

def Fibonacci(n: number): number
  if n < 2
    return n
  else
    return Fibonacci(n - 1) + Fibonacci(n - 2)
  endif
enddef

def Test_count()
  assert_equal(3, count('ABC ABC ABC', 'b', true))
  assert_equal(0, count('ABC ABC ABC', 'b', false))
enddef

def Test_index()
  assert_equal(3, index(['a', 'b', 'a', 'B'], 'b', 2, true))
enddef

def Test_expand()
  split SomeFile
  assert_equal(['SomeFile'], expand('%', true, true))
  close
enddef

def Test_getreg()
  let lines = ['aaa', 'bbb', 'ccc']
  setreg('a', lines)
  assert_equal(lines, getreg('a', true, true))
enddef

def Test_glob()
  assert_equal(['runtest.vim'], glob('runtest.vim', true, true, true))
enddef

def Test_globpath()
  assert_equal(['./runtest.vim'], globpath('.', 'runtest.vim', true, true, true))
enddef

def Test_hasmapto()
  assert_equal(0, hasmapto('foobar', 'i', true))
  iabbrev foo foobar
  assert_equal(1, hasmapto('foobar', 'i', true))
  iunabbrev foo
enddef

def SID(): number
  return expand('<SID>')
          ->matchstr('<SNR>\zs\d\+\ze_$')
          ->str2nr()
enddef

def Test_maparg()
  let lnum = str2nr(expand('<sflnum>'))
  map foo bar
  assert_equal(#{
        lnum: lnum + 1,
        script: 0,
        mode: ' ',
        silent: 0,
        noremap: 0,
        lhs: 'foo',
        lhsraw: 'foo',
        nowait: 0,
        expr: 0,
        sid: SID(),
        rhs: 'bar',
        buffer: 0},
        maparg('foo', '', false, true))
  unmap foo
enddef

def Test_mapcheck()
  iabbrev foo foobar
  assert_equal('foobar', mapcheck('foo', 'i', true))
  iunabbrev foo
enddef

def Test_recursive_call()
  assert_equal(6765, Fibonacci(20))
enddef

def TreeWalk(dir: string): list<any>
  return readdir(dir)->map({_, val ->
            fnamemodify(dir .. '/' .. val, ':p')->isdirectory()
               ? {val: TreeWalk(dir .. '/' .. val)}
               : val
             })
enddef

def Test_closure_in_map()
  mkdir('XclosureDir/tdir', 'p')
  writefile(['111'], 'XclosureDir/file1')
  writefile(['222'], 'XclosureDir/file2')
  writefile(['333'], 'XclosureDir/tdir/file3')

  assert_equal(['file1', 'file2', {'tdir': ['file3']}], TreeWalk('XclosureDir'))

  delete('XclosureDir', 'rf')
enddef

def Test_partial_call()
  let Xsetlist = function('setloclist', [0])
  Xsetlist([], ' ', {'title': 'test'})
  assert_equal({'title': 'test'}, getloclist(0, {'title': 1}))

  Xsetlist = function('setloclist', [0, [], ' '])
  Xsetlist({'title': 'test'})
  assert_equal({'title': 'test'}, getloclist(0, {'title': 1}))

  Xsetlist = function('setqflist')
  Xsetlist([], ' ', {'title': 'test'})
  assert_equal({'title': 'test'}, getqflist({'title': 1}))

  Xsetlist = function('setqflist', [[], ' '])
  Xsetlist({'title': 'test'})
  assert_equal({'title': 'test'}, getqflist({'title': 1}))
enddef

def Test_cmd_modifier()
  tab echo '0'
  call CheckDefFailure(['5tab echo 3'], 'E16:')
enddef

def Test_restore_modifiers()
  # check that when compiling a :def function command modifiers are not messed
  # up.
  let lines =<< trim END
      vim9script
      set eventignore=
      autocmd QuickFixCmdPost * copen
      def AutocmdsDisabled()
          eval 0
      enddef
      func Func()
        noautocmd call s:AutocmdsDisabled()
        let g:ei_after = &eventignore
      endfunc
      Func()
  END
  CheckScriptSuccess(lines)
  assert_equal('', g:ei_after)
enddef


" vim: ts=8 sw=2 sts=2 expandtab tw=80 fdm=marker