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
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
// EndBASIC
// Copyright 2024 Julio Merino
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License.  You may obtain a copy
// of the License at:
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
// License for the specific language governing permissions and limitations
// under the License.

//! Common compilers for callable arguments.

use crate::ast::*;
use crate::bytecode::*;
use crate::compiler::exprs::{compile_expr, compile_expr_as_type};
use crate::compiler::{ExprType, SymbolPrototype, SymbolsTable};
use crate::exec::ValueTag;
use crate::reader::LineCol;
use crate::syms::{CallError, SymbolKey};
use std::borrow::Cow;
use std::ops::RangeInclusive;

/// Result for argument compilation return values.
type Result<T> = std::result::Result<T, CallError>;

/// Details to compile a required scalar parameter.
#[derive(Clone, Debug)]
pub struct RequiredValueSyntax {
    /// The name of the parameter for help purposes.
    pub name: Cow<'static, str>,

    /// The type of the expected parameter.
    pub vtype: ExprType,
}

/// Details to compile a required reference parameter.
#[derive(Clone, Debug)]
pub struct RequiredRefSyntax {
    /// The name of the parameter for help purposes.
    pub name: Cow<'static, str>,

    /// If true, require an array reference; if false, a variable reference.
    pub require_array: bool,

    /// If true, allow references to undefined variables because the command will define them when
    /// missing.  Can only be set to true for commands, not functions, and `require_array` must be
    /// false.
    pub define_undefined: bool,
}

/// Details to compile an optional scalar parameter.
///
/// Optional parameters are only supported in commands.
#[derive(Clone, Debug)]
pub struct OptionalValueSyntax {
    /// The name of the parameter for help purposes.
    pub name: Cow<'static, str>,

    /// The type of the expected parameter.
    pub vtype: ExprType,

    /// Value to push onto the stack when the parameter is missing.
    pub missing_value: i32,

    /// Value to push onto the stack when the parameter is present, after which the stack contains
    /// the parameter value.
    pub present_value: i32,
}

/// Details to describe the type of a repeated parameter.
#[derive(Clone, Debug)]
pub enum RepeatedTypeSyntax {
    /// Allows any value type, including empty arguments.  The values pushed onto the stack have
    /// the same semantics as those pushed by `AnyValueSyntax`.
    AnyValue,

    /// Expects a value of the given type.
    TypedValue(ExprType),

    /// Expects a reference to a variable (not an array) and allows the variables to not be defined.
    VariableRef,
}

/// Details to compile a repeated parameter.
///
/// The repeated parameter must appear after all singular positional parameters.
#[derive(Clone, Debug)]
pub struct RepeatedSyntax {
    /// The name of the parameter for help purposes.
    pub name: Cow<'static, str>,

    /// The type of the expected parameters.
    pub type_syn: RepeatedTypeSyntax,

    /// The separator to expect between the repeated parameters.  For functions, this must be the
    /// long separator (the comma).
    pub sep: ArgSepSyntax,

    /// Whether the repeated parameter must at least have one element or not.
    pub require_one: bool,

    /// Whether to allow any parameter to not be present or not.  Can only be true for commands.
    pub allow_missing: bool,
}

impl RepeatedSyntax {
    /// Formats the repeated argument syntax for help purposes into `output`.
    ///
    /// `last_singular_sep` contains the separator of the last singular argument syntax, if any,
    /// which we need to place inside of the optional group.
    fn describe(&self, output: &mut String, last_singular_sep: Option<&ArgSepSyntax>) {
        if !self.require_one {
            output.push('[');
        }

        if let Some(sep) = last_singular_sep {
            sep.describe(output);
        }

        output.push_str(&self.name);
        output.push('1');
        if let RepeatedTypeSyntax::TypedValue(vtype) = self.type_syn {
            output.push(vtype.annotation());
        }

        if self.require_one {
            output.push('[');
        }

        self.sep.describe(output);
        output.push_str("..");
        self.sep.describe(output);

        output.push_str(&self.name);
        output.push('N');
        if let RepeatedTypeSyntax::TypedValue(vtype) = self.type_syn {
            output.push(vtype.annotation());
        }

        output.push(']');
    }
}

/// Details to compile a parameter of any scalar type.
#[derive(Clone, Debug)]
pub struct AnyValueSyntax {
    /// The name of the parameter for help purposes.
    pub name: Cow<'static, str>,

    /// Whether to allow the parameter to not be present or not.  Can only be true for commands.
    pub allow_missing: bool,
}

/// Details to process an argument separator.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum ArgSepSyntax {
    /// The argument separator must exactly be the one give.
    Exactly(ArgSep),

    /// The argument separator may be any of the ones given.
    OneOf(ArgSep, ArgSep),

    /// The argument separator is the end of the call.
    End,
}

impl ArgSepSyntax {
    /// Formats the argument separator for help purposes into `output`.
    fn describe(&self, output: &mut String) {
        match self {
            ArgSepSyntax::Exactly(sep) => {
                let (text, needs_space) = sep.describe();

                if !text.is_empty() && needs_space {
                    output.push(' ');
                }
                output.push_str(text);
                if !text.is_empty() {
                    output.push(' ');
                }
            }

            ArgSepSyntax::OneOf(sep1, sep2) => {
                let (text1, _needs_space1) = sep1.describe();
                let (text2, _needs_space2) = sep2.describe();

                output.push(' ');
                output.push_str(&format!("<{}|{}>", text1, text2));
                output.push(' ');
            }

            ArgSepSyntax::End => (),
        };
    }
}

/// Details to process a non-repeated argument.
///
/// Every item in this enum is composed of a struct that provides the details on the parameter and
/// a struct that provides the details on how this parameter is separated from the next.
#[derive(Clone, Debug)]
pub enum SingularArgSyntax {
    /// A required scalar value.
    RequiredValue(RequiredValueSyntax, ArgSepSyntax),

    /// A required reference.
    RequiredRef(RequiredRefSyntax, ArgSepSyntax),

    /// An optional scalar value.
    OptionalValue(OptionalValueSyntax, ArgSepSyntax),

    /// A required scalar value of any type.
    AnyValue(AnyValueSyntax, ArgSepSyntax),
}

/// Details to process the arguments of a callable.
///
/// Note that the description of function arguments is more restricted than that of commands.
/// The arguments compiler panics when these preconditions aren't met with the rationale that
/// builtin functions must never be ill-defined.
// TODO(jmmv): It might be nice to try to express these restrictions in the type system, but
// things are already too verbose as they are...
#[derive(Clone, Debug)]
pub(crate) struct CallableSyntax {
    /// Ordered list of singular arguments that appear before repeated arguments.
    singular: Cow<'static, [SingularArgSyntax]>,

    /// Details on the repeated argument allowed after singular arguments.
    repeated: Option<Cow<'static, RepeatedSyntax>>,
}

impl CallableSyntax {
    /// Creates a new callable arguments definition from its parts defined statically in the
    /// code.
    pub(crate) fn new_static(
        singular: &'static [SingularArgSyntax],
        repeated: Option<&'static RepeatedSyntax>,
    ) -> Self {
        Self { singular: Cow::Borrowed(singular), repeated: repeated.map(Cow::Borrowed) }
    }

    /// Creates a new callable arguments definition from its parts defined dynamically at
    /// runtime.
    pub(crate) fn new_dynamic(
        singular: Vec<SingularArgSyntax>,
        repeated: Option<RepeatedSyntax>,
    ) -> Self {
        Self { singular: Cow::Owned(singular), repeated: repeated.map(Cow::Owned) }
    }

    /// Computes the range of the expected number of parameters for this syntax.
    fn expected_nargs(&self) -> RangeInclusive<usize> {
        let mut min = self.singular.len();
        let mut max = self.singular.len();
        if let Some(syn) = self.repeated.as_ref() {
            if syn.require_one {
                min += 1;
            }
            max = usize::MAX;
        }
        min..=max
    }

    /// Produces a user-friendly description of this callable syntax.
    pub(crate) fn describe(&self) -> String {
        let mut description = String::new();
        let mut last_singular_sep = None;
        for (i, s) in self.singular.iter().enumerate() {
            let sep = match s {
                SingularArgSyntax::RequiredValue(details, sep) => {
                    description.push_str(&details.name);
                    description.push(details.vtype.annotation());
                    sep
                }

                SingularArgSyntax::RequiredRef(details, sep) => {
                    description.push_str(&details.name);
                    sep
                }

                SingularArgSyntax::OptionalValue(details, sep) => {
                    description.push('[');
                    description.push_str(&details.name);
                    description.push(details.vtype.annotation());
                    description.push(']');
                    sep
                }

                SingularArgSyntax::AnyValue(details, sep) => {
                    if details.allow_missing {
                        description.push('[');
                    }
                    description.push_str(&details.name);
                    if details.allow_missing {
                        description.push(']');
                    }
                    sep
                }
            };

            if self.repeated.is_none() || i < self.singular.len() - 1 {
                sep.describe(&mut description);
            }
            if i == self.singular.len() - 1 {
                last_singular_sep = Some(sep);
            }
        }

        if let Some(syn) = &self.repeated {
            syn.describe(&mut description, last_singular_sep);
        }

        description
    }
}

/// Compiles an argument that requires a reference.
///
/// If the reference does not exist and the syntax allowed undefined symbols, returns the details
/// for the symbol to insert into the symbols table, which the caller must handle because we do
/// not have mutable access to the `symtable` here.
fn compile_required_ref(
    instrs: &mut Vec<Instruction>,
    symtable: &SymbolsTable,
    require_array: bool,
    define_undefined: bool,
    expr: Option<Expr>,
) -> Result<Option<(SymbolKey, SymbolPrototype)>> {
    match expr {
        Some(Expr::Symbol(span)) => {
            let key = SymbolKey::from(span.vref.name());
            match symtable.get(&key) {
                None => {
                    if !define_undefined {
                        let message = if require_array {
                            format!("Undefined array {}", span.vref.name())
                        } else {
                            format!("Undefined variable {}", span.vref.name())
                        };
                        return Err(CallError::ArgumentError(span.pos, message));
                    }
                    debug_assert!(!require_array);

                    let vtype = span.vref.ref_type().unwrap_or(ExprType::Integer);

                    if !span.vref.accepts(vtype) {
                        return Err(CallError::ArgumentError(
                            span.pos,
                            format!("Incompatible type annotation in {} reference", span.vref),
                        ));
                    }

                    instrs.push(Instruction::LoadRef(key.clone(), vtype, span.pos));
                    Ok(Some((key, SymbolPrototype::Variable(vtype))))
                }

                Some(SymbolPrototype::Array(vtype, _)) => {
                    let vtype = *vtype;

                    if !span.vref.accepts(vtype) {
                        return Err(CallError::ArgumentError(
                            span.pos,
                            format!("Incompatible type annotation in {} reference", span.vref),
                        ));
                    }

                    if !require_array {
                        return Err(CallError::ArgumentError(
                            span.pos,
                            format!("{} is not a variable reference", span.vref),
                        ));
                    }

                    instrs.push(Instruction::LoadRef(key, vtype, span.pos));
                    Ok(None)
                }

                Some(SymbolPrototype::Variable(vtype)) => {
                    let vtype = *vtype;

                    if !span.vref.accepts(vtype) {
                        return Err(CallError::ArgumentError(
                            span.pos,
                            format!("Incompatible type annotation in {} reference", span.vref),
                        ));
                    }

                    if require_array {
                        return Err(CallError::ArgumentError(
                            span.pos,
                            format!("{} is not an array reference", span.vref),
                        ));
                    }

                    instrs.push(Instruction::LoadRef(key, vtype, span.pos));
                    Ok(None)
                }

                Some(SymbolPrototype::Callable(md)) => {
                    if !span.vref.accepts_callable(md.return_type()) {
                        return Err(CallError::ArgumentError(
                            span.pos,
                            format!("Incompatible type annotation in {} reference", span.vref),
                        ));
                    }

                    Err(CallError::ArgumentError(
                        span.pos,
                        format!("{} is not an array nor a function", span.vref.name()),
                    ))
                }
            }
        }

        Some(expr) => {
            let message = if require_array {
                "Requires an array reference, not a value"
            } else {
                "Requires a variable reference, not a value"
            };
            Err(CallError::ArgumentError(expr.start_pos(), message.to_owned()))
        }

        None => Err(CallError::SyntaxError),
    }
}

/// Locates the syntax definition that can parse the given number of arguments.
///
/// Panics if more than one syntax definition applies.
fn find_syntax(syntaxes: &[CallableSyntax], nargs: usize) -> Result<&CallableSyntax> {
    let mut matches = syntaxes.iter().filter(|s| s.expected_nargs().contains(&nargs));
    let syntax = matches.next();
    debug_assert!(matches.next().is_none(), "Ambiguous syntax definitions");
    match syntax {
        Some(syntax) => Ok(syntax),
        None => Err(CallError::SyntaxError),
    }
}

/// Compiles an argument separator with any necessary tagging.
///
/// `instrs` is the list of instructions into which insert the separator tag at `sep_tag_pc`
/// when it is needed to disambiguate separators at runtime.
///
/// `syn` contains the details about the separator syntax that is accepted.
///
/// `sep` and `sep_pos` are the details about the separator being compiled.
///
/// `is_last` indicates whether this is the last separator in the command call and is used
/// only for diagnostics purposes.
fn compile_syn_argsep(
    instrs: &mut Vec<Instruction>,
    syn: &ArgSepSyntax,
    is_last: bool,
    sep: ArgSep,
    sep_pos: LineCol,
    sep_tag_pc: Address,
) -> Result<usize> {
    debug_assert!(
        (!is_last || sep == ArgSep::End) && (is_last || sep != ArgSep::End),
        "Parser can only supply an End separator in the last argument"
    );

    match syn {
        ArgSepSyntax::Exactly(exp_sep) => {
            debug_assert!(*exp_sep != ArgSep::End, "Use ArgSepSyntax::End");
            if sep != ArgSep::End && sep != *exp_sep {
                return Err(CallError::SyntaxError);
            }
            Ok(0)
        }

        ArgSepSyntax::OneOf(exp_sep1, exp_sep2) => {
            debug_assert!(*exp_sep1 != ArgSep::End, "Use ArgSepSyntax::End");
            debug_assert!(*exp_sep2 != ArgSep::End, "Use ArgSepSyntax::End");
            if sep == ArgSep::End {
                Ok(0)
            } else {
                if sep != *exp_sep1 && sep != *exp_sep2 {
                    return Err(CallError::SyntaxError);
                }
                instrs.insert(sep_tag_pc, Instruction::PushInteger(sep as i32, sep_pos));
                Ok(1)
            }
        }

        ArgSepSyntax::End => {
            debug_assert!(is_last);
            Ok(0)
        }
    }
}

/// Compiles a single expression, expecting it to be of a `target` type.  Applies casts if
/// possible.
fn compile_arg_expr(
    instrs: &mut Vec<Instruction>,
    symtable: &SymbolsTable,
    expr: Expr,
    target: ExprType,
) -> Result<()> {
    match compile_expr_as_type(instrs, symtable, expr, target) {
        Ok(()) => Ok(()),
        Err(e) => Err(CallError::ArgumentError(e.pos, e.message)),
    }
}

/// Parses the arguments to a command or a function and generates expressions to compute them.
///
/// Returns the number of arguments that the instructions added to `instrs` will push into the
/// stack and returns the list of new symbols that need to be inserted into `symtable`.
fn compile_args(
    syntaxes: &[CallableSyntax],
    instrs: &mut Vec<Instruction>,
    symtable: &SymbolsTable,
    _pos: LineCol,
    args: Vec<ArgSpan>,
) -> Result<(usize, Vec<(SymbolKey, SymbolPrototype)>)> {
    let syntax = find_syntax(syntaxes, args.len())?;

    let input_nargs = args.len();
    let mut aiter = args.into_iter().rev();

    let mut nargs = 0;
    let mut to_insert = vec![];

    let mut remaining;
    if let Some(syn) = syntax.repeated.as_ref() {
        let mut min_nargs = syntax.singular.len();
        if syn.require_one {
            min_nargs += 1;
        }
        if input_nargs < min_nargs {
            return Err(CallError::SyntaxError);
        }

        let need_tags = syn.allow_missing || matches!(syn.type_syn, RepeatedTypeSyntax::AnyValue);

        remaining = input_nargs;
        while remaining > syntax.singular.len() {
            let span = aiter.next().expect("Args and their syntax must advance in unison");

            let sep_tag_pc = instrs.len();

            match span.expr {
                Some(expr) => {
                    let pos = expr.start_pos();
                    match syn.type_syn {
                        RepeatedTypeSyntax::AnyValue => {
                            debug_assert!(need_tags);
                            let etype = compile_expr(instrs, symtable, expr, false)?;
                            instrs
                                .push(Instruction::PushInteger(ValueTag::from(etype) as i32, pos));
                            nargs += 2;
                        }

                        RepeatedTypeSyntax::VariableRef => {
                            let to_insert_one =
                                compile_required_ref(instrs, symtable, false, true, Some(expr))?;
                            if let Some(to_insert_one) = to_insert_one {
                                to_insert.push(to_insert_one);
                            }
                            nargs += 1;
                        }

                        RepeatedTypeSyntax::TypedValue(vtype) => {
                            compile_arg_expr(instrs, symtable, expr, vtype)?;
                            if need_tags {
                                instrs.push(Instruction::PushInteger(
                                    ValueTag::from(vtype) as i32,
                                    pos,
                                ));
                                nargs += 2;
                            } else {
                                nargs += 1;
                            }
                        }
                    }
                }
                None => {
                    if !syn.allow_missing {
                        return Err(CallError::SyntaxError);
                    }
                    instrs.push(Instruction::PushInteger(ValueTag::Missing as i32, span.sep_pos));
                    nargs += 1;
                }
            }

            nargs += compile_syn_argsep(
                instrs,
                &syn.sep,
                input_nargs == remaining,
                span.sep,
                span.sep_pos,
                sep_tag_pc,
            )?;

            remaining -= 1;
        }
    } else {
        remaining = syntax.singular.len();
    }

    for syn in syntax.singular.iter().rev() {
        let span = aiter.next().expect("Args and their syntax must advance in unison");

        let sep_tag_pc = instrs.len();

        let exp_sep = match syn {
            SingularArgSyntax::RequiredValue(details, sep) => {
                match span.expr {
                    Some(expr) => {
                        compile_arg_expr(instrs, symtable, expr, details.vtype)?;
                        nargs += 1;
                    }
                    None => return Err(CallError::SyntaxError),
                }
                sep
            }

            SingularArgSyntax::RequiredRef(details, sep) => {
                let to_insert_one = compile_required_ref(
                    instrs,
                    symtable,
                    details.require_array,
                    details.define_undefined,
                    span.expr,
                )?;
                if let Some(to_insert_one) = to_insert_one {
                    to_insert.push(to_insert_one);
                }
                nargs += 1;
                sep
            }

            SingularArgSyntax::OptionalValue(details, sep) => {
                let (tag, pos) = match span.expr {
                    Some(expr) => {
                        let pos = expr.start_pos();
                        compile_arg_expr(instrs, symtable, expr, details.vtype)?;
                        nargs += 1;
                        (details.present_value, pos)
                    }
                    None => (details.missing_value, span.sep_pos),
                };
                instrs.push(Instruction::PushInteger(tag, pos));
                nargs += 1;
                sep
            }

            SingularArgSyntax::AnyValue(details, sep) => {
                let (tag, pos) = match span.expr {
                    Some(expr) => {
                        let pos = expr.start_pos();
                        let etype = compile_expr(instrs, symtable, expr, false)?;
                        nargs += 2;
                        (ValueTag::from(etype), pos)
                    }
                    None => {
                        if !details.allow_missing {
                            return Err(CallError::ArgumentError(
                                span.sep_pos,
                                "Missing expression before separator".to_owned(),
                            ));
                        }
                        nargs += 1;
                        (ValueTag::Missing, span.sep_pos)
                    }
                };
                instrs.push(Instruction::PushInteger(tag as i32, pos));
                sep
            }
        };

        nargs += compile_syn_argsep(
            instrs,
            exp_sep,
            input_nargs == remaining,
            span.sep,
            span.sep_pos,
            sep_tag_pc,
        )?;

        remaining -= 1;
    }

    Ok((nargs, to_insert))
}

/// Parses the arguments to a buitin command and generates expressions to compute them.
///
/// This can be used to help the runtime by doing type checking during compilation and then
/// allowing the runtime to assume that the values on the stack are correctly typed.
pub(super) fn compile_command_args(
    syntaxes: &[CallableSyntax],
    instrs: &mut Vec<Instruction>,
    symtable: &mut SymbolsTable,
    pos: LineCol,
    args: Vec<ArgSpan>,
) -> Result<usize> {
    let (nargs, to_insert) = compile_args(syntaxes, instrs, symtable, pos, args)?;
    for (key, proto) in to_insert {
        if !symtable.contains_key(&key) {
            symtable.insert(key, proto);
        }
    }
    Ok(nargs)
}

/// Parses the arguments to a function and generates expressions to compute them.
///
/// This can be used to help the runtime by doing type checking during compilation and then
/// allowing the runtime to assume that the values on the stack are correctly typed.
pub(super) fn compile_function_args(
    syntaxes: &[CallableSyntax],
    instrs: &mut Vec<Instruction>,
    symtable: &SymbolsTable,
    pos: LineCol,
    args: Vec<ArgSpan>,
) -> Result<usize> {
    let (nargs, to_insert) = compile_args(syntaxes, instrs, symtable, pos, args)?;
    debug_assert!(to_insert.is_empty());
    Ok(nargs)
}

#[cfg(test)]
mod testutils {
    use super::*;
    use std::collections::HashMap;

    /// Syntactic sugar to instantiate a `LineCol` for tests.
    pub(super) fn lc(line: usize, col: usize) -> LineCol {
        LineCol { line, col }
    }

    /// Builder pattern to instantiate a test scenario.
    #[derive(Default)]
    #[must_use]
    pub(super) struct Tester {
        syntaxes: Vec<CallableSyntax>,
        symtable: SymbolsTable,
    }

    impl Tester {
        /// Registers a syntax definition in the arguments compiler.
        pub(super) fn syntax(
            mut self,
            singular: &'static [SingularArgSyntax],
            repeated: Option<&'static RepeatedSyntax>,
        ) -> Self {
            self.syntaxes.push(CallableSyntax::new_static(singular, repeated));
            self
        }

        /// Registers a pre-existing symbol in the symbols table.
        pub(super) fn symbol(mut self, key: &str, proto: SymbolPrototype) -> Self {
            self.symtable.insert(SymbolKey::from(key), proto);
            self
        }

        /// Feeds command `args` into the arguments compiler and returns a checker to validate
        /// expectations.
        pub(super) fn compile_command<A: Into<Vec<ArgSpan>>>(mut self, args: A) -> Checker {
            let args = args.into();
            let mut instrs = vec![
                // Start with one instruction to validate that the args compiler doesn't touch it.
                Instruction::Nop,
            ];
            let result = compile_command_args(
                &self.syntaxes,
                &mut instrs,
                &mut self.symtable,
                lc(1000, 2000),
                args,
            );
            Checker {
                result,
                instrs,
                symtable: self.symtable,
                exp_result: Ok(0),
                exp_instrs: vec![Instruction::Nop],
                exp_vars: HashMap::default(),
            }
        }
    }

    /// Builder pattern to validate expectations in a test scenario.
    #[must_use]
    pub(super) struct Checker {
        result: Result<usize>,
        instrs: Vec<Instruction>,
        symtable: SymbolsTable,
        exp_result: Result<usize>,
        exp_instrs: Vec<Instruction>,
        exp_vars: HashMap<SymbolKey, ExprType>,
    }

    impl Checker {
        /// Expects the compilation to succeeded and produce `nargs` arguments.
        pub(super) fn exp_nargs(mut self, nargs: usize) -> Self {
            self.exp_result = Ok(nargs);
            self
        }

        /// Expects the compilation to fail with the given `error`.
        pub(super) fn exp_error(mut self, error: CallError) -> Self {
            self.exp_result = Err(error);
            self
        }

        /// Adds the given instruction to the expected instructions on success.
        pub(super) fn exp_instr(mut self, instr: Instruction) -> Self {
            self.exp_instrs.push(instr);
            self
        }

        /// Expects the compilation to define a new variable `key` of type `etype`.
        pub(super) fn exp_symbol<K: AsRef<str>>(mut self, key: K, etype: ExprType) -> Self {
            self.exp_vars.insert(SymbolKey::from(key), etype);
            self
        }

        /// Formats a `CallError` as a string to simplify comparisons.
        fn format_call_error(e: CallError) -> String {
            match e {
                CallError::ArgumentError(pos, e) => format!("{}:{}: {}", pos.line, pos.col, e),
                CallError::EvalError(pos, e) => format!("{}:{}: {}", pos.line, pos.col, e),
                CallError::InternalError(_pos, e) => panic!("Must not happen here: {}", e),
                CallError::IoError(e) => panic!("Must not happen here: {}", e),
                CallError::NestedError(e) => panic!("Must not happen here: {}", e),
                CallError::SyntaxError => "Syntax error".to_owned(),
            }
        }

        /// Checks that the compilation ended with the configured expectations.
        pub(super) fn check(self) {
            let is_ok = self.result.is_ok();
            assert_eq!(
                self.exp_result.map_err(Self::format_call_error),
                self.result.map_err(Self::format_call_error),
            );

            if !is_ok {
                return;
            }

            assert_eq!(self.exp_instrs, self.instrs);

            let mut exp_keys = self.symtable.keys();
            for (key, exp_etype) in &self.exp_vars {
                match self.symtable.get(key) {
                    Some(SymbolPrototype::Variable(etype)) => {
                        assert_eq!(
                            exp_etype, etype,
                            "Variable {} was defined with the wrong type",
                            key
                        );
                    }
                    Some(_) => panic!("Symbol {} was defined but not as a variable", key),
                    None => panic!("Symbol {} was not defined", key),
                }
                exp_keys.insert(key);
            }

            assert_eq!(exp_keys, self.symtable.keys(), "Unexpected variables defined");
        }
    }
}

#[cfg(test)]
mod description_tests {
    use super::*;

    #[test]
    fn test_no_args() {
        assert_eq!("", CallableSyntax::new_static(&[], None).describe());
    }

    #[test]
    fn test_singular_required_value() {
        assert_eq!(
            "the-arg%",
            CallableSyntax::new_static(
                &[SingularArgSyntax::RequiredValue(
                    RequiredValueSyntax {
                        name: Cow::Borrowed("the-arg"),
                        vtype: ExprType::Integer
                    },
                    ArgSepSyntax::End,
                )],
                None,
            )
            .describe(),
        );
    }

    #[test]
    fn test_singular_required_ref() {
        assert_eq!(
            "the-arg",
            CallableSyntax::new_static(
                &[SingularArgSyntax::RequiredRef(
                    RequiredRefSyntax {
                        name: Cow::Borrowed("the-arg"),
                        require_array: false,
                        define_undefined: false
                    },
                    ArgSepSyntax::End,
                )],
                None,
            )
            .describe()
        );
    }

    #[test]
    fn test_singular_optional_value() {
        assert_eq!(
            "[the-arg%]",
            CallableSyntax::new_static(
                &[SingularArgSyntax::OptionalValue(
                    OptionalValueSyntax {
                        name: Cow::Borrowed("the-arg"),
                        vtype: ExprType::Integer,
                        missing_value: 0,
                        present_value: 1,
                    },
                    ArgSepSyntax::End,
                )],
                None,
            )
            .describe()
        );
    }

    #[test]
    fn test_singular_any_value_required() {
        assert_eq!(
            "the-arg",
            CallableSyntax::new_static(
                &[SingularArgSyntax::AnyValue(
                    AnyValueSyntax { name: Cow::Borrowed("the-arg"), allow_missing: false },
                    ArgSepSyntax::End,
                )],
                None,
            )
            .describe()
        );
    }

    #[test]
    fn test_singular_any_value_optional() {
        assert_eq!(
            "[the-arg]",
            CallableSyntax::new_static(
                &[SingularArgSyntax::AnyValue(
                    AnyValueSyntax { name: Cow::Borrowed("the-arg"), allow_missing: true },
                    ArgSepSyntax::End,
                )],
                None,
            )
            .describe()
        );
    }

    #[test]
    fn test_singular_exactly_separators() {
        assert_eq!(
            "a; b AS c, d",
            CallableSyntax::new_static(
                &[
                    SingularArgSyntax::AnyValue(
                        AnyValueSyntax { name: Cow::Borrowed("a"), allow_missing: false },
                        ArgSepSyntax::Exactly(ArgSep::Short),
                    ),
                    SingularArgSyntax::AnyValue(
                        AnyValueSyntax { name: Cow::Borrowed("b"), allow_missing: false },
                        ArgSepSyntax::Exactly(ArgSep::As),
                    ),
                    SingularArgSyntax::AnyValue(
                        AnyValueSyntax { name: Cow::Borrowed("c"), allow_missing: false },
                        ArgSepSyntax::Exactly(ArgSep::Long),
                    ),
                    SingularArgSyntax::AnyValue(
                        AnyValueSyntax { name: Cow::Borrowed("d"), allow_missing: false },
                        ArgSepSyntax::Exactly(ArgSep::End),
                    ),
                ],
                None,
            )
            .describe()
        );
    }

    #[test]
    fn test_singular_oneof_separators() {
        assert_eq!(
            "a <;|,> b <AS|,> c",
            CallableSyntax::new_static(
                &[
                    SingularArgSyntax::AnyValue(
                        AnyValueSyntax { name: Cow::Borrowed("a"), allow_missing: false },
                        ArgSepSyntax::OneOf(ArgSep::Short, ArgSep::Long),
                    ),
                    SingularArgSyntax::AnyValue(
                        AnyValueSyntax { name: Cow::Borrowed("b"), allow_missing: false },
                        ArgSepSyntax::OneOf(ArgSep::As, ArgSep::Long),
                    ),
                    SingularArgSyntax::AnyValue(
                        AnyValueSyntax { name: Cow::Borrowed("c"), allow_missing: false },
                        ArgSepSyntax::Exactly(ArgSep::End),
                    ),
                ],
                None,
            )
            .describe()
        );
    }

    #[test]
    fn test_repeated_require_one() {
        assert_eq!(
            "rep1[; ..; repN]",
            CallableSyntax::new_static(
                &[],
                Some(&RepeatedSyntax {
                    name: Cow::Borrowed("rep"),
                    type_syn: RepeatedTypeSyntax::AnyValue,
                    sep: ArgSepSyntax::Exactly(ArgSep::Short),
                    require_one: true,
                    allow_missing: false,
                }),
            )
            .describe()
        );
    }

    #[test]
    fn test_repeated_allow_missing() {
        assert_eq!(
            "[rep1, .., repN]",
            CallableSyntax::new_static(
                &[],
                Some(&RepeatedSyntax {
                    name: Cow::Borrowed("rep"),
                    type_syn: RepeatedTypeSyntax::AnyValue,
                    sep: ArgSepSyntax::Exactly(ArgSep::Long),
                    require_one: false,
                    allow_missing: true,
                }),
            )
            .describe()
        );
    }

    #[test]
    fn test_repeated_value() {
        assert_eq!(
            "rep1$[ AS .. AS repN$]",
            CallableSyntax::new_static(
                &[],
                Some(&RepeatedSyntax {
                    name: Cow::Borrowed("rep"),
                    type_syn: RepeatedTypeSyntax::TypedValue(ExprType::Text),
                    sep: ArgSepSyntax::Exactly(ArgSep::As),
                    require_one: true,
                    allow_missing: false,
                }),
            )
            .describe()
        );
    }

    #[test]
    fn test_repeated_ref() {
        assert_eq!(
            "rep1[ AS .. AS repN]",
            CallableSyntax::new_static(
                &[],
                Some(&RepeatedSyntax {
                    name: Cow::Borrowed("rep"),
                    type_syn: RepeatedTypeSyntax::VariableRef,
                    sep: ArgSepSyntax::Exactly(ArgSep::As),
                    require_one: true,
                    allow_missing: false,
                }),
            )
            .describe()
        );
    }

    #[test]
    fn test_singular_and_repeated() {
        assert_eq!(
            "arg%[, rep1 <;|,> .. <;|,> repN]",
            CallableSyntax::new_static(
                &[SingularArgSyntax::RequiredValue(
                    RequiredValueSyntax { name: Cow::Borrowed("arg"), vtype: ExprType::Integer },
                    ArgSepSyntax::Exactly(ArgSep::Long),
                )],
                Some(&RepeatedSyntax {
                    name: Cow::Borrowed("rep"),
                    type_syn: RepeatedTypeSyntax::AnyValue,
                    sep: ArgSepSyntax::OneOf(ArgSep::Short, ArgSep::Long),
                    require_one: false,
                    allow_missing: false,
                }),
            )
            .describe()
        );
    }
}

#[cfg(test)]
mod compile_tests {
    use super::testutils::*;
    use super::*;

    #[test]
    fn test_no_syntaxes_yields_error() {
        Tester::default().compile_command([]).exp_error(CallError::SyntaxError).check();
    }

    #[test]
    fn test_no_args_ok() {
        Tester::default().syntax(&[], None).compile_command([]).check();
    }

    #[test]
    fn test_no_args_mismatch() {
        Tester::default()
            .syntax(&[], None)
            .compile_command([ArgSpan {
                expr: Some(Expr::Integer(IntegerSpan { value: 3, pos: lc(1, 2) })),
                sep: ArgSep::End,
                sep_pos: lc(1, 3),
            }])
            .exp_error(CallError::SyntaxError)
            .check();
    }

    #[test]
    fn test_one_required_value_ok() {
        Tester::default()
            .syntax(
                &[SingularArgSyntax::RequiredValue(
                    RequiredValueSyntax { name: Cow::Borrowed("arg1"), vtype: ExprType::Integer },
                    ArgSepSyntax::End,
                )],
                None,
            )
            .compile_command([ArgSpan {
                expr: Some(Expr::Integer(IntegerSpan { value: 3, pos: lc(1, 2) })),
                sep: ArgSep::End,
                sep_pos: lc(1, 3),
            }])
            .exp_instr(Instruction::PushInteger(3, lc(1, 2)))
            .exp_nargs(1)
            .check();
    }

    #[test]
    fn test_one_required_value_type_promotion() {
        Tester::default()
            .syntax(
                &[SingularArgSyntax::RequiredValue(
                    RequiredValueSyntax { name: Cow::Borrowed("arg1"), vtype: ExprType::Integer },
                    ArgSepSyntax::End,
                )],
                None,
            )
            .compile_command([ArgSpan {
                expr: Some(Expr::Double(DoubleSpan { value: 3.0, pos: lc(1, 2) })),
                sep: ArgSep::End,
                sep_pos: lc(1, 5),
            }])
            .exp_instr(Instruction::PushDouble(3.0, lc(1, 2)))
            .exp_instr(Instruction::DoubleToInteger)
            .exp_nargs(1)
            .check();
    }

    #[test]
    fn test_one_required_ref_variable_ok() {
        Tester::default()
            .symbol("foo", SymbolPrototype::Variable(ExprType::Text))
            .syntax(
                &[SingularArgSyntax::RequiredRef(
                    RequiredRefSyntax {
                        name: Cow::Borrowed("ref"),
                        require_array: false,
                        define_undefined: false,
                    },
                    ArgSepSyntax::End,
                )],
                None,
            )
            .compile_command([ArgSpan {
                expr: Some(Expr::Symbol(SymbolSpan {
                    vref: VarRef::new("foo", None),
                    pos: lc(1, 2),
                })),
                sep: ArgSep::End,
                sep_pos: lc(1, 5),
            }])
            .exp_instr(Instruction::LoadRef(SymbolKey::from("foo"), ExprType::Text, lc(1, 2)))
            .exp_nargs(1)
            .check();
    }

    #[test]
    fn test_one_required_ref_variable_not_defined() {
        Tester::default()
            .syntax(
                &[SingularArgSyntax::RequiredRef(
                    RequiredRefSyntax {
                        name: Cow::Borrowed("ref"),
                        require_array: false,
                        define_undefined: false,
                    },
                    ArgSepSyntax::End,
                )],
                None,
            )
            .compile_command([ArgSpan {
                expr: Some(Expr::Symbol(SymbolSpan {
                    vref: VarRef::new("foo", None),
                    pos: lc(1, 2),
                })),
                sep: ArgSep::End,
                sep_pos: lc(1, 5),
            }])
            .exp_error(CallError::ArgumentError(lc(1, 2), "Undefined variable foo".to_owned()))
            .check();
    }

    #[test]
    fn test_one_required_ref_variable_disallow_value() {
        Tester::default()
            .syntax(
                &[SingularArgSyntax::RequiredRef(
                    RequiredRefSyntax {
                        name: Cow::Borrowed("ref"),
                        require_array: false,
                        define_undefined: false,
                    },
                    ArgSepSyntax::End,
                )],
                None,
            )
            .compile_command([ArgSpan {
                expr: Some(Expr::Integer(IntegerSpan { value: 5, pos: lc(1, 2) })),
                sep: ArgSep::End,
                sep_pos: lc(1, 5),
            }])
            .exp_error(CallError::ArgumentError(
                lc(1, 2),
                "Requires a variable reference, not a value".to_owned(),
            ))
            .check();
    }

    #[test]
    fn test_one_required_ref_variable_wrong_type() {
        Tester::default()
            .symbol("foo", SymbolPrototype::Array(ExprType::Text, 1))
            .syntax(
                &[SingularArgSyntax::RequiredRef(
                    RequiredRefSyntax {
                        name: Cow::Borrowed("ref"),
                        require_array: false,
                        define_undefined: false,
                    },
                    ArgSepSyntax::End,
                )],
                None,
            )
            .compile_command([ArgSpan {
                expr: Some(Expr::Symbol(SymbolSpan {
                    vref: VarRef::new("foo", None),
                    pos: lc(1, 2),
                })),
                sep: ArgSep::End,
                sep_pos: lc(1, 5),
            }])
            .exp_error(CallError::ArgumentError(
                lc(1, 2),
                "foo is not a variable reference".to_owned(),
            ))
            .check();
    }

    #[test]
    fn test_one_required_ref_variable_wrong_annotation() {
        Tester::default()
            .symbol("foo", SymbolPrototype::Variable(ExprType::Text))
            .syntax(
                &[SingularArgSyntax::RequiredRef(
                    RequiredRefSyntax {
                        name: Cow::Borrowed("ref"),
                        require_array: false,
                        define_undefined: false,
                    },
                    ArgSepSyntax::End,
                )],
                None,
            )
            .compile_command([ArgSpan {
                expr: Some(Expr::Symbol(SymbolSpan {
                    vref: VarRef::new("foo", Some(ExprType::Integer)),
                    pos: lc(1, 2),
                })),
                sep: ArgSep::End,
                sep_pos: lc(1, 5),
            }])
            .exp_error(CallError::ArgumentError(
                lc(1, 2),
                "Incompatible type annotation in foo% reference".to_owned(),
            ))
            .check();
    }

    #[test]
    fn test_one_required_ref_variable_define_undefined_default_type() {
        Tester::default()
            .syntax(
                &[SingularArgSyntax::RequiredRef(
                    RequiredRefSyntax {
                        name: Cow::Borrowed("ref"),
                        require_array: false,
                        define_undefined: true,
                    },
                    ArgSepSyntax::End,
                )],
                None,
            )
            .compile_command([ArgSpan {
                expr: Some(Expr::Symbol(SymbolSpan {
                    vref: VarRef::new("foo", None),
                    pos: lc(1, 2),
                })),
                sep: ArgSep::End,
                sep_pos: lc(1, 5),
            }])
            .exp_instr(Instruction::LoadRef(SymbolKey::from("foo"), ExprType::Integer, lc(1, 2)))
            .exp_nargs(1)
            .exp_symbol("foo", ExprType::Integer)
            .check();
    }

    #[test]
    fn test_one_required_ref_variable_define_undefined_explicit_type() {
        Tester::default()
            .syntax(
                &[SingularArgSyntax::RequiredRef(
                    RequiredRefSyntax {
                        name: Cow::Borrowed("ref"),
                        require_array: false,
                        define_undefined: true,
                    },
                    ArgSepSyntax::End,
                )],
                None,
            )
            .compile_command([ArgSpan {
                expr: Some(Expr::Symbol(SymbolSpan {
                    vref: VarRef::new("foo", Some(ExprType::Text)),
                    pos: lc(1, 2),
                })),
                sep: ArgSep::End,
                sep_pos: lc(1, 6),
            }])
            .exp_instr(Instruction::LoadRef(SymbolKey::from("foo"), ExprType::Text, lc(1, 2)))
            .exp_nargs(1)
            .exp_symbol("foo", ExprType::Text)
            .check();
    }

    #[test]
    fn test_multiple_required_ref_variable_define_undefined_repeated_ok() {
        Tester::default()
            .syntax(
                &[
                    SingularArgSyntax::RequiredRef(
                        RequiredRefSyntax {
                            name: Cow::Borrowed("ref1"),
                            require_array: false,
                            define_undefined: true,
                        },
                        ArgSepSyntax::Exactly(ArgSep::Long),
                    ),
                    SingularArgSyntax::RequiredRef(
                        RequiredRefSyntax {
                            name: Cow::Borrowed("ref2"),
                            require_array: false,
                            define_undefined: true,
                        },
                        ArgSepSyntax::End,
                    ),
                ],
                None,
            )
            .compile_command([
                ArgSpan {
                    expr: Some(Expr::Symbol(SymbolSpan {
                        vref: VarRef::new("foo", None),
                        pos: lc(1, 2),
                    })),
                    sep: ArgSep::Long,
                    sep_pos: lc(1, 5),
                },
                ArgSpan {
                    expr: Some(Expr::Symbol(SymbolSpan {
                        vref: VarRef::new("foo", None),
                        pos: lc(1, 2),
                    })),
                    sep: ArgSep::End,
                    sep_pos: lc(1, 5),
                },
            ])
            .exp_instr(Instruction::LoadRef(SymbolKey::from("foo"), ExprType::Integer, lc(1, 2)))
            .exp_instr(Instruction::LoadRef(SymbolKey::from("foo"), ExprType::Integer, lc(1, 2)))
            .exp_nargs(2)
            .exp_symbol("foo", ExprType::Integer)
            .check();
    }

    #[test]
    fn test_one_required_ref_array_ok() {
        Tester::default()
            .symbol("foo", SymbolPrototype::Array(ExprType::Text, 0))
            .syntax(
                &[SingularArgSyntax::RequiredRef(
                    RequiredRefSyntax {
                        name: Cow::Borrowed("ref"),
                        require_array: true,
                        define_undefined: false,
                    },
                    ArgSepSyntax::End,
                )],
                None,
            )
            .compile_command([ArgSpan {
                expr: Some(Expr::Symbol(SymbolSpan {
                    vref: VarRef::new("foo", None),
                    pos: lc(1, 2),
                })),
                sep: ArgSep::End,
                sep_pos: lc(1, 5),
            }])
            .exp_instr(Instruction::LoadRef(SymbolKey::from("foo"), ExprType::Text, lc(1, 2)))
            .exp_nargs(1)
            .check();
    }

    #[test]
    fn test_one_required_ref_array_not_defined() {
        Tester::default()
            .syntax(
                &[SingularArgSyntax::RequiredRef(
                    RequiredRefSyntax {
                        name: Cow::Borrowed("ref"),
                        require_array: true,
                        define_undefined: false,
                    },
                    ArgSepSyntax::End,
                )],
                None,
            )
            .compile_command([ArgSpan {
                expr: Some(Expr::Symbol(SymbolSpan {
                    vref: VarRef::new("foo", None),
                    pos: lc(1, 2),
                })),
                sep: ArgSep::End,
                sep_pos: lc(1, 5),
            }])
            .exp_error(CallError::ArgumentError(lc(1, 2), "Undefined array foo".to_owned()))
            .check();
    }

    #[test]
    fn test_one_required_ref_array_disallow_value() {
        Tester::default()
            .syntax(
                &[SingularArgSyntax::RequiredRef(
                    RequiredRefSyntax {
                        name: Cow::Borrowed("ref"),
                        require_array: true,
                        define_undefined: false,
                    },
                    ArgSepSyntax::End,
                )],
                None,
            )
            .compile_command([ArgSpan {
                expr: Some(Expr::Integer(IntegerSpan { value: 5, pos: lc(1, 2) })),
                sep: ArgSep::End,
                sep_pos: lc(1, 5),
            }])
            .exp_error(CallError::ArgumentError(
                lc(1, 2),
                "Requires an array reference, not a value".to_owned(),
            ))
            .check();
    }

    #[test]
    fn test_one_required_ref_array_wrong_type() {
        Tester::default()
            .symbol("foo", SymbolPrototype::Variable(ExprType::Text))
            .syntax(
                &[SingularArgSyntax::RequiredRef(
                    RequiredRefSyntax {
                        name: Cow::Borrowed("ref"),
                        require_array: true,
                        define_undefined: false,
                    },
                    ArgSepSyntax::End,
                )],
                None,
            )
            .compile_command([ArgSpan {
                expr: Some(Expr::Symbol(SymbolSpan {
                    vref: VarRef::new("foo", None),
                    pos: lc(1, 2),
                })),
                sep: ArgSep::End,
                sep_pos: lc(1, 5),
            }])
            .exp_error(CallError::ArgumentError(
                lc(1, 2),
                "foo is not an array reference".to_owned(),
            ))
            .check();
    }

    #[test]
    fn test_one_required_ref_array_wrong_annotation() {
        Tester::default()
            .symbol("foo", SymbolPrototype::Array(ExprType::Text, 0))
            .syntax(
                &[SingularArgSyntax::RequiredRef(
                    RequiredRefSyntax {
                        name: Cow::Borrowed("ref"),
                        require_array: true,
                        define_undefined: false,
                    },
                    ArgSepSyntax::End,
                )],
                None,
            )
            .compile_command([ArgSpan {
                expr: Some(Expr::Symbol(SymbolSpan {
                    vref: VarRef::new("foo", Some(ExprType::Integer)),
                    pos: lc(1, 2),
                })),
                sep: ArgSep::End,
                sep_pos: lc(1, 5),
            }])
            .exp_error(CallError::ArgumentError(
                lc(1, 2),
                "Incompatible type annotation in foo% reference".to_owned(),
            ))
            .check();
    }

    #[test]
    fn test_one_optional_value_ok_is_present() {
        Tester::default()
            .syntax(
                &[SingularArgSyntax::OptionalValue(
                    OptionalValueSyntax {
                        name: Cow::Borrowed("ref"),
                        vtype: ExprType::Double,
                        missing_value: 10,
                        present_value: 20,
                    },
                    ArgSepSyntax::End,
                )],
                None,
            )
            .compile_command([ArgSpan {
                expr: Some(Expr::Double(DoubleSpan { value: 3.0, pos: lc(1, 2) })),
                sep: ArgSep::End,
                sep_pos: lc(1, 5),
            }])
            .exp_instr(Instruction::PushDouble(3.0, lc(1, 2)))
            .exp_instr(Instruction::PushInteger(20, lc(1, 2)))
            .exp_nargs(2)
            .check();
    }

    #[test]
    fn test_one_optional_value_ok_is_missing() {
        Tester::default()
            .syntax(
                &[SingularArgSyntax::OptionalValue(
                    OptionalValueSyntax {
                        name: Cow::Borrowed("ref"),
                        vtype: ExprType::Double,
                        missing_value: 10,
                        present_value: 20,
                    },
                    ArgSepSyntax::End,
                )],
                None,
            )
            .compile_command([ArgSpan { expr: None, sep: ArgSep::End, sep_pos: lc(1, 2) }])
            .exp_instr(Instruction::PushInteger(10, lc(1, 2)))
            .exp_nargs(1)
            .check();
    }

    #[test]
    fn test_multiple_any_value_ok() {
        Tester::default()
            .syntax(
                &[
                    SingularArgSyntax::AnyValue(
                        AnyValueSyntax { name: Cow::Borrowed("arg1"), allow_missing: false },
                        ArgSepSyntax::Exactly(ArgSep::Long),
                    ),
                    SingularArgSyntax::AnyValue(
                        AnyValueSyntax { name: Cow::Borrowed("arg2"), allow_missing: false },
                        ArgSepSyntax::Exactly(ArgSep::Long),
                    ),
                    SingularArgSyntax::AnyValue(
                        AnyValueSyntax { name: Cow::Borrowed("arg3"), allow_missing: false },
                        ArgSepSyntax::Exactly(ArgSep::Long),
                    ),
                    SingularArgSyntax::AnyValue(
                        AnyValueSyntax { name: Cow::Borrowed("arg4"), allow_missing: false },
                        ArgSepSyntax::End,
                    ),
                ],
                None,
            )
            .compile_command([
                ArgSpan {
                    expr: Some(Expr::Boolean(BooleanSpan { value: false, pos: lc(1, 2) })),
                    sep: ArgSep::Long,
                    sep_pos: lc(1, 3),
                },
                ArgSpan {
                    expr: Some(Expr::Double(DoubleSpan { value: 2.0, pos: lc(1, 4) })),
                    sep: ArgSep::Long,
                    sep_pos: lc(1, 5),
                },
                ArgSpan {
                    expr: Some(Expr::Integer(IntegerSpan { value: 3, pos: lc(1, 6) })),
                    sep: ArgSep::Long,
                    sep_pos: lc(1, 7),
                },
                ArgSpan {
                    expr: Some(Expr::Text(TextSpan { value: "foo".to_owned(), pos: lc(1, 8) })),
                    sep: ArgSep::End,
                    sep_pos: lc(1, 9),
                },
            ])
            .exp_instr(Instruction::PushString("foo".to_owned(), lc(1, 8)))
            .exp_instr(Instruction::PushInteger(ValueTag::Text as i32, lc(1, 8)))
            .exp_instr(Instruction::PushInteger(3, lc(1, 6)))
            .exp_instr(Instruction::PushInteger(ValueTag::Integer as i32, lc(1, 6)))
            .exp_instr(Instruction::PushDouble(2.0, lc(1, 4)))
            .exp_instr(Instruction::PushInteger(ValueTag::Double as i32, lc(1, 4)))
            .exp_instr(Instruction::PushBoolean(false, lc(1, 2)))
            .exp_instr(Instruction::PushInteger(ValueTag::Boolean as i32, lc(1, 2)))
            .exp_nargs(8)
            .check();
    }

    #[test]
    fn test_one_any_value_expr_error() {
        Tester::default()
            .symbol("foo", SymbolPrototype::Variable(ExprType::Double))
            .syntax(
                &[SingularArgSyntax::AnyValue(
                    AnyValueSyntax { name: Cow::Borrowed("arg1"), allow_missing: false },
                    ArgSepSyntax::End,
                )],
                None,
            )
            .compile_command([ArgSpan {
                expr: Some(Expr::Symbol(SymbolSpan {
                    vref: VarRef::new("foo", Some(ExprType::Boolean)),
                    pos: lc(1, 2),
                })),
                sep: ArgSep::End,
                sep_pos: lc(1, 3),
            }])
            .exp_error(CallError::ArgumentError(
                lc(1, 2),
                "Incompatible type annotation in foo? reference".to_owned(),
            ))
            .check();
    }

    #[test]
    fn test_one_any_value_disallow_missing() {
        Tester::default()
            .symbol("foo", SymbolPrototype::Variable(ExprType::Double))
            .syntax(
                &[SingularArgSyntax::AnyValue(
                    AnyValueSyntax { name: Cow::Borrowed("arg1"), allow_missing: false },
                    ArgSepSyntax::End,
                )],
                None,
            )
            .compile_command([ArgSpan { expr: None, sep: ArgSep::End, sep_pos: lc(1, 3) }])
            .exp_error(CallError::ArgumentError(
                lc(1, 3),
                "Missing expression before separator".to_owned(),
            ))
            .check();
    }

    #[test]
    fn test_one_any_value_allow_missing() {
        Tester::default()
            .syntax(
                &[SingularArgSyntax::AnyValue(
                    AnyValueSyntax { name: Cow::Borrowed("arg1"), allow_missing: true },
                    ArgSepSyntax::End,
                )],
                None,
            )
            .compile_command([ArgSpan { expr: None, sep: ArgSep::End, sep_pos: lc(1, 3) }])
            .exp_instr(Instruction::PushInteger(ValueTag::Missing as i32, lc(1, 3)))
            .exp_nargs(1)
            .check();
    }

    #[test]
    fn test_multiple_separator_types_ok() {
        Tester::default()
            .syntax(
                &[
                    SingularArgSyntax::AnyValue(
                        AnyValueSyntax { name: Cow::Borrowed("arg1"), allow_missing: true },
                        ArgSepSyntax::Exactly(ArgSep::As),
                    ),
                    SingularArgSyntax::AnyValue(
                        AnyValueSyntax { name: Cow::Borrowed("arg2"), allow_missing: true },
                        ArgSepSyntax::OneOf(ArgSep::Long, ArgSep::Short),
                    ),
                    SingularArgSyntax::AnyValue(
                        AnyValueSyntax { name: Cow::Borrowed("arg3"), allow_missing: true },
                        ArgSepSyntax::OneOf(ArgSep::Long, ArgSep::Short),
                    ),
                    SingularArgSyntax::AnyValue(
                        AnyValueSyntax { name: Cow::Borrowed("arg4"), allow_missing: true },
                        ArgSepSyntax::End,
                    ),
                ],
                None,
            )
            .compile_command([
                ArgSpan { expr: None, sep: ArgSep::As, sep_pos: lc(1, 1) },
                ArgSpan { expr: None, sep: ArgSep::Long, sep_pos: lc(1, 2) },
                ArgSpan { expr: None, sep: ArgSep::Short, sep_pos: lc(1, 3) },
                ArgSpan { expr: None, sep: ArgSep::End, sep_pos: lc(1, 4) },
            ])
            .exp_instr(Instruction::PushInteger(ValueTag::Missing as i32, lc(1, 4)))
            .exp_instr(Instruction::PushInteger(ArgSep::Short as i32, lc(1, 3)))
            .exp_instr(Instruction::PushInteger(ValueTag::Missing as i32, lc(1, 3)))
            .exp_instr(Instruction::PushInteger(ArgSep::Long as i32, lc(1, 2)))
            .exp_instr(Instruction::PushInteger(ValueTag::Missing as i32, lc(1, 2)))
            .exp_instr(Instruction::PushInteger(ValueTag::Missing as i32, lc(1, 1)))
            .exp_nargs(6)
            .check();
    }

    #[test]
    fn test_multiple_separator_exactly_mismatch() {
        Tester::default()
            .syntax(
                &[
                    SingularArgSyntax::AnyValue(
                        AnyValueSyntax { name: Cow::Borrowed("arg1"), allow_missing: true },
                        ArgSepSyntax::Exactly(ArgSep::As),
                    ),
                    SingularArgSyntax::AnyValue(
                        AnyValueSyntax { name: Cow::Borrowed("arg2"), allow_missing: true },
                        ArgSepSyntax::End,
                    ),
                ],
                None,
            )
            .compile_command([
                ArgSpan { expr: None, sep: ArgSep::Short, sep_pos: lc(1, 1) },
                ArgSpan { expr: None, sep: ArgSep::End, sep_pos: lc(1, 4) },
            ])
            .exp_error(CallError::SyntaxError)
            .check();
    }

    #[test]
    fn test_multiple_separator_oneof_mismatch() {
        Tester::default()
            .syntax(
                &[
                    SingularArgSyntax::AnyValue(
                        AnyValueSyntax { name: Cow::Borrowed("arg1"), allow_missing: true },
                        ArgSepSyntax::OneOf(ArgSep::Short, ArgSep::Long),
                    ),
                    SingularArgSyntax::AnyValue(
                        AnyValueSyntax { name: Cow::Borrowed("arg2"), allow_missing: true },
                        ArgSepSyntax::End,
                    ),
                ],
                None,
            )
            .compile_command([
                ArgSpan { expr: None, sep: ArgSep::As, sep_pos: lc(1, 1) },
                ArgSpan { expr: None, sep: ArgSep::End, sep_pos: lc(1, 4) },
            ])
            .exp_error(CallError::SyntaxError)
            .check();
    }

    #[test]
    fn test_repeated_none() {
        Tester::default()
            .syntax(
                &[],
                Some(&RepeatedSyntax {
                    name: Cow::Borrowed("arg"),
                    type_syn: RepeatedTypeSyntax::TypedValue(ExprType::Integer),
                    sep: ArgSepSyntax::Exactly(ArgSep::Long),
                    allow_missing: false,
                    require_one: false,
                }),
            )
            .compile_command([])
            .exp_nargs(0)
            .check();
    }

    #[test]
    fn test_repeated_multiple_and_cast() {
        Tester::default()
            .syntax(
                &[],
                Some(&RepeatedSyntax {
                    name: Cow::Borrowed("arg"),
                    type_syn: RepeatedTypeSyntax::TypedValue(ExprType::Integer),
                    sep: ArgSepSyntax::Exactly(ArgSep::Long),
                    allow_missing: false,
                    require_one: false,
                }),
            )
            .compile_command([
                ArgSpan {
                    expr: Some(Expr::Double(DoubleSpan { value: 3.0, pos: lc(1, 2) })),
                    sep: ArgSep::Long,
                    sep_pos: lc(1, 2),
                },
                ArgSpan {
                    expr: Some(Expr::Integer(IntegerSpan { value: 5, pos: lc(1, 4) })),
                    sep: ArgSep::End,
                    sep_pos: lc(1, 3),
                },
            ])
            .exp_instr(Instruction::PushInteger(5, lc(1, 4)))
            .exp_instr(Instruction::PushDouble(3.0, lc(1, 2)))
            .exp_instr(Instruction::DoubleToInteger)
            .exp_nargs(2)
            .check();
    }

    #[test]
    fn test_repeated_require_one_just_one() {
        Tester::default()
            .syntax(
                &[],
                Some(&RepeatedSyntax {
                    name: Cow::Borrowed("arg"),
                    type_syn: RepeatedTypeSyntax::TypedValue(ExprType::Integer),
                    sep: ArgSepSyntax::Exactly(ArgSep::Long),
                    allow_missing: false,
                    require_one: true,
                }),
            )
            .compile_command([ArgSpan {
                expr: Some(Expr::Integer(IntegerSpan { value: 5, pos: lc(1, 2) })),
                sep: ArgSep::End,
                sep_pos: lc(1, 2),
            }])
            .exp_instr(Instruction::PushInteger(5, lc(1, 2)))
            .exp_nargs(1)
            .check();
    }

    #[test]
    fn test_repeated_require_one_missing() {
        Tester::default()
            .syntax(
                &[],
                Some(&RepeatedSyntax {
                    name: Cow::Borrowed("arg"),
                    type_syn: RepeatedTypeSyntax::TypedValue(ExprType::Integer),
                    sep: ArgSepSyntax::Exactly(ArgSep::Long),
                    allow_missing: false,
                    require_one: true,
                }),
            )
            .compile_command([])
            .exp_error(CallError::SyntaxError)
            .check();
    }

    #[test]
    fn test_repeated_require_one_ref_ok() {
        Tester::default()
            .syntax(
                &[],
                Some(&RepeatedSyntax {
                    name: Cow::Borrowed("arg"),
                    type_syn: RepeatedTypeSyntax::VariableRef,
                    sep: ArgSepSyntax::Exactly(ArgSep::Long),
                    allow_missing: false,
                    require_one: true,
                }),
            )
            .compile_command([ArgSpan {
                expr: Some(Expr::Symbol(SymbolSpan {
                    vref: VarRef::new("foo", Some(ExprType::Text)),
                    pos: lc(1, 2),
                })),
                sep: ArgSep::End,
                sep_pos: lc(1, 2),
            }])
            .exp_instr(Instruction::LoadRef(SymbolKey::from("foo"), ExprType::Text, lc(1, 2)))
            .exp_nargs(1)
            .check();
    }

    #[test]
    fn test_repeated_require_one_ref_error() {
        Tester::default()
            .syntax(
                &[],
                Some(&RepeatedSyntax {
                    name: Cow::Borrowed("arg"),
                    type_syn: RepeatedTypeSyntax::VariableRef,
                    sep: ArgSepSyntax::Exactly(ArgSep::Long),
                    allow_missing: false,
                    require_one: true,
                }),
            )
            .compile_command([ArgSpan {
                expr: Some(Expr::Integer(IntegerSpan { value: 5, pos: lc(1, 2) })),
                sep: ArgSep::End,
                sep_pos: lc(1, 2),
            }])
            .exp_error(CallError::ArgumentError(
                lc(1, 2),
                "Requires a variable reference, not a value".to_owned(),
            ))
            .check();
    }

    #[test]
    fn test_repeated_oneof_separator() {
        Tester::default()
            .syntax(
                &[],
                Some(&RepeatedSyntax {
                    name: Cow::Borrowed("arg"),
                    type_syn: RepeatedTypeSyntax::TypedValue(ExprType::Double),
                    sep: ArgSepSyntax::OneOf(ArgSep::Long, ArgSep::Short),
                    allow_missing: false,
                    require_one: false,
                }),
            )
            .compile_command([
                ArgSpan {
                    expr: Some(Expr::Double(DoubleSpan { value: 3.0, pos: lc(1, 2) })),
                    sep: ArgSep::Short,
                    sep_pos: lc(1, 3),
                },
                ArgSpan {
                    expr: Some(Expr::Double(DoubleSpan { value: 5.0, pos: lc(1, 4) })),
                    sep: ArgSep::Long,
                    sep_pos: lc(1, 5),
                },
                ArgSpan {
                    expr: Some(Expr::Double(DoubleSpan { value: 2.0, pos: lc(1, 6) })),
                    sep: ArgSep::End,
                    sep_pos: lc(1, 7),
                },
            ])
            .exp_instr(Instruction::PushDouble(2.0, lc(1, 6)))
            .exp_instr(Instruction::PushInteger(ArgSep::Long as i32, lc(1, 5)))
            .exp_instr(Instruction::PushDouble(5.0, lc(1, 4)))
            .exp_instr(Instruction::PushInteger(ArgSep::Short as i32, lc(1, 3)))
            .exp_instr(Instruction::PushDouble(3.0, lc(1, 2)))
            .exp_nargs(5)
            .check();
    }

    #[test]
    fn test_repeated_oneof_separator_and_missing_in_last_position() {
        Tester::default()
            .syntax(
                &[],
                Some(&RepeatedSyntax {
                    name: Cow::Borrowed("arg"),
                    type_syn: RepeatedTypeSyntax::TypedValue(ExprType::Double),
                    sep: ArgSepSyntax::OneOf(ArgSep::Long, ArgSep::Short),
                    allow_missing: true,
                    require_one: false,
                }),
            )
            .compile_command([
                ArgSpan {
                    expr: Some(Expr::Double(DoubleSpan { value: 3.0, pos: lc(1, 2) })),
                    sep: ArgSep::Short,
                    sep_pos: lc(1, 3),
                },
                ArgSpan { expr: None, sep: ArgSep::End, sep_pos: lc(1, 4) },
            ])
            .exp_instr(Instruction::PushInteger(ValueTag::Missing as i32, lc(1, 4)))
            .exp_instr(Instruction::PushInteger(ArgSep::Short as i32, lc(1, 3)))
            .exp_instr(Instruction::PushDouble(3.0, lc(1, 2)))
            .exp_instr(Instruction::PushInteger(ValueTag::Double as i32, lc(1, 2)))
            .exp_nargs(4)
            .check();
    }

    #[test]
    fn test_repeated_any_value() {
        Tester::default()
            .syntax(
                &[],
                Some(&RepeatedSyntax {
                    name: Cow::Borrowed("arg"),
                    type_syn: RepeatedTypeSyntax::AnyValue,
                    sep: ArgSepSyntax::Exactly(ArgSep::Long),
                    allow_missing: true,
                    require_one: false,
                }),
            )
            .compile_command([
                ArgSpan {
                    expr: Some(Expr::Boolean(BooleanSpan { value: false, pos: lc(1, 2) })),
                    sep: ArgSep::Long,
                    sep_pos: lc(1, 3),
                },
                ArgSpan {
                    expr: Some(Expr::Double(DoubleSpan { value: 2.0, pos: lc(1, 4) })),
                    sep: ArgSep::Long,
                    sep_pos: lc(1, 5),
                },
                ArgSpan {
                    expr: Some(Expr::Integer(IntegerSpan { value: 3, pos: lc(1, 6) })),
                    sep: ArgSep::Long,
                    sep_pos: lc(1, 7),
                },
                ArgSpan {
                    expr: Some(Expr::Text(TextSpan { value: "foo".to_owned(), pos: lc(1, 8) })),
                    sep: ArgSep::Long,
                    sep_pos: lc(1, 9),
                },
                ArgSpan { expr: None, sep: ArgSep::End, sep_pos: lc(1, 10) },
            ])
            .exp_instr(Instruction::PushInteger(ValueTag::Missing as i32, lc(1, 10)))
            .exp_instr(Instruction::PushString("foo".to_owned(), lc(1, 8)))
            .exp_instr(Instruction::PushInteger(ValueTag::Text as i32, lc(1, 8)))
            .exp_instr(Instruction::PushInteger(3, lc(1, 6)))
            .exp_instr(Instruction::PushInteger(ValueTag::Integer as i32, lc(1, 6)))
            .exp_instr(Instruction::PushDouble(2.0, lc(1, 4)))
            .exp_instr(Instruction::PushInteger(ValueTag::Double as i32, lc(1, 4)))
            .exp_instr(Instruction::PushBoolean(false, lc(1, 2)))
            .exp_instr(Instruction::PushInteger(ValueTag::Boolean as i32, lc(1, 2)))
            .exp_nargs(9)
            .check();
    }

    #[test]
    fn test_singular_and_repeated() {
        Tester::default()
            .syntax(
                &[SingularArgSyntax::RequiredValue(
                    RequiredValueSyntax { name: Cow::Borrowed("arg"), vtype: ExprType::Double },
                    ArgSepSyntax::Exactly(ArgSep::Short),
                )],
                Some(&RepeatedSyntax {
                    name: Cow::Borrowed("rep"),
                    type_syn: RepeatedTypeSyntax::TypedValue(ExprType::Integer),
                    sep: ArgSepSyntax::Exactly(ArgSep::Long),
                    allow_missing: false,
                    require_one: false,
                }),
            )
            .compile_command([
                ArgSpan {
                    expr: Some(Expr::Double(DoubleSpan { value: 4.0, pos: lc(1, 2) })),
                    sep: ArgSep::Short,
                    sep_pos: lc(1, 2),
                },
                ArgSpan {
                    expr: Some(Expr::Integer(IntegerSpan { value: 5, pos: lc(1, 5) })),
                    sep: ArgSep::Long,
                    sep_pos: lc(1, 2),
                },
                ArgSpan {
                    expr: Some(Expr::Integer(IntegerSpan { value: 6, pos: lc(1, 7) })),
                    sep: ArgSep::End,
                    sep_pos: lc(1, 2),
                },
            ])
            .exp_nargs(3)
            .exp_instr(Instruction::PushInteger(6, lc(1, 7)))
            .exp_instr(Instruction::PushInteger(5, lc(1, 5)))
            .exp_instr(Instruction::PushDouble(4.0, lc(1, 2)))
            .check();
    }
}