bridge_macros/
lib.rs

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
//! TODO PC ISSUE #9
//! macro crate wish list
//! 1. The macro should fail if the structure of the docs is not as expected. e.g. Type/Namespace/.../Usage/Example/
//! 2. type aliasing, need a gensym type macro so I do not conflict with names.
//! 3. trybuild tests!
//! 4. worry about inlining, e.g. are the mechanisms in place to do the type conversions constant time,
//!    and inlined? or is there a way to make them so?
//! 5. can yet another crate solve the problem of housing typehandle/passingstyle/param/errorstrings/typedwrapper in the same place?
//! 6. EVERY macro doesn't need the check for VarArgs, only signatures that have
//!    VarArgs, this can be addressed in the macro.
//! 7. Port tuple tests: <https://github.com/sl-sh-dev/sl-sh/blob/83cd1c93d1eea726ba138a83610155bdbfcab7aa/src/builtins_types.rs#L628>
//! 8. To avoid needing to do lifetimes, if the return value is one of the INPUT values have
//!     that marked in the annotation... OTHERWISE data may be copied!
//!     OR allow for simple lifetimes?
//! 9. VMError should not be new_vm
//! 10. Optional duplicates code. With the ownership model from SlFromRef, being *the* primary mechanism
//!     for crossing the boundary, it's possible having Some and None blocks multiple times is not necessary.
//! 11. Support for slices? to avoid Vec allocation? Is it a big deal to only be able to accept Vec?
//!     The decision should at least be documented.
//! 12. SINCE WHEN is it a requirement like that it *has* to return VMResult or Option

use bridge_types::Param;
use bridge_types::PassingStyle;
use bridge_types::TypeHandle;
use quote::quote;
use quote::ToTokens;
use quote::__private::TokenStream;
use std::fmt::{Display, Formatter};
use syn::__private::{Span, TokenStream2};
use syn::spanned::Spanned;
use syn::{
    parse_macro_input, AttributeArgs, Error, FnArg, GenericArgument, Generics, Ident, Item, ItemFn,
    Lit, Meta, NestedMeta, PathArguments, ReturnType, Type, TypeBareFn, TypePath, TypeReference,
    TypeTuple,
};
extern crate static_assertions;

type MacroResult<T> = Result<T, Error>;

//TODO fix for the issue where a user used a fully qualified path and the rust code fails?
const POSSIBLE_RETURN_TYPES: [&str; 2] = ["VMResult", "Option"];
const SPECIAL_ARG_TYPES: [&str; 2] = ["Option", "VarArgs"];
const POSSIBLE_ARG_TYPES: [&str; 3] = ["Option", "VarArgs", "Vec"];

#[derive(Copy, Clone)]
enum SupportedGenericReturnTypes {
    VMResult,
    Option,
}

enum RustType {
    // TypeBareFn is a syn type that is useful to leave attached for debugging purposes.
    #[allow(dead_code)]
    BareFn(TypeBareFn, Span),
    Path(TypePath, Span),
    Tuple(TypeTuple, Span),
    Reference(TypeReference, Span),
    Unsupported(Span),
}

impl RustType {
    pub fn span(&self) -> Span {
        match self {
            RustType::BareFn(_, x) => *x,
            RustType::Path(_, x) => *x,
            RustType::Tuple(_, x) => *x,
            RustType::Reference(_, x) => *x,
            RustType::Unsupported(x) => *x,
        }
    }
}

impl From<Type> for RustType {
    fn from(ty: Type) -> Self {
        match ty {
            Type::BareFn(x) => {
                let span = x.span();
                RustType::BareFn(x, span)
            }
            Type::Path(x) => {
                let span = x.span();
                RustType::Path(x, span)
            }
            Type::Reference(x) => {
                let span = x.span();
                RustType::Reference(x, span)
            }
            Type::Tuple(x) => {
                let span = x.span();
                RustType::Tuple(x, span)
            }
            x => {
                let span = x.span();
                RustType::Unsupported(span)
            }
        }
    }
}

impl Display for SupportedGenericReturnTypes {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            SupportedGenericReturnTypes::VMResult => {
                write!(f, "VMResult")
            }
            SupportedGenericReturnTypes::Option => {
                write!(f, "Option")
            }
        }
    }
}

/// returns the option of inner type and the wrapped generic type (None if it's
/// not generic. If there is no return type None, None is returned. Throws
/// an error if the generic return type is not in the list of predefined
/// constants POSSIBLE_RESULT_TYPES.
fn get_return_type(
    original_item_fn: &ItemFn,
) -> MacroResult<(Option<Type>, Option<SupportedGenericReturnTypes>)> {
    let return_type = match &original_item_fn.sig.output {
        ReturnType::Default => return Ok((None, None)),
        ReturnType::Type(_ra_arrow, ty) => *ty.clone(),
    };

    if let Some((inner_type, type_path)) = get_generic_argument_from_type(&return_type) {
        let wrapper = is_valid_generic_type(type_path, POSSIBLE_RETURN_TYPES.as_slice())?;
        match inner_type {
            GenericArgument::Type(ty) => Ok((Some(ty.clone()), Some(wrapper))),
            _ => Err(Error::new(
                original_item_fn.span(),
                format!(
                    "sl_sh_fn macros can only return generic arguments of types {:?}.",
                    &POSSIBLE_RETURN_TYPES
                ),
            )),
        }
    } else {
        Ok((Some(return_type), None))
    }
}

fn opt_is_valid_generic_type<'a>(
    type_path: &TypePath,
    possible_types: &'a [&str],
) -> Option<&'a str> {
    match type_path.path.segments.first() {
        Some(path_segment) if type_path.path.segments.len() == 1 => {
            let ident = &path_segment.ident;
            for type_name in possible_types {
                if ident == type_name {
                    return Some(type_name);
                }
            }
        }
        _ => {}
    }
    None
}

fn is_valid_generic_type(
    type_path: &TypePath,
    possible_types: &[&str],
) -> MacroResult<SupportedGenericReturnTypes> {
    if type_path.path.segments.len() == 1 && type_path.path.segments.first().is_some() {
        let path_segment = &type_path.path.segments.first().unwrap();
        let ident = &path_segment.ident;
        for type_name in possible_types {
            if ident == type_name {
                if type_name == &SupportedGenericReturnTypes::VMResult.to_string().as_str() {
                    return Ok(SupportedGenericReturnTypes::VMResult);
                } else if type_name == &SupportedGenericReturnTypes::Option.to_string().as_str() {
                    return Ok(SupportedGenericReturnTypes::Option);
                }
            }
        }
    }
    Err(Error::new(
        type_path.span(),
        format!(
            "Functions can only return GenericArguments of type {possible_types:?}, try wrapping this value in Option or VMResult."
        ),
    ))
}

fn get_generic_argument_from_type_path(
    type_path: &TypePath,
) -> Option<(&GenericArgument, &TypePath)> {
    if type_path.path.segments.len() == 1 {
        if let Some(path_segment) = &type_path.path.segments.iter().next_back() {
            if let PathArguments::AngleBracketed(args) = &path_segment.arguments {
                if let Some(ty) = args.args.iter().next_back() {
                    return Some((ty, type_path));
                }
            }
        }
    }
    None
}

fn get_generic_argument_from_type(ty: &Type) -> Option<(&GenericArgument, &TypePath)> {
    if let Type::Path(ref type_path) = ty {
        get_generic_argument_from_type_path(type_path)
    } else {
        None
    }
}

fn generate_assertions_code_for_return_type_conversions(return_type: &Type) -> TokenStream2 {
    quote! {
      static_assertions::assert_impl_all!(#return_type: bridge_adapters::lisp_adapters::SlInto<slvm::Value>);
    }
}

fn get_attribute_value_with_key(
    original_item_fn: &ItemFn,
    key: &str,
    values: &[(String, String)],
) -> MacroResult<Option<String>> {
    if values.is_empty() {
        Err(Error::new(
            original_item_fn.span(),
            "sl_sh_fn requires at least one name-value pair, 'fn_name = \"<name-of-sl-sh-fun>\"'.",
        ))
    } else {
        for name_value in values {
            if name_value.0 == key {
                return Ok(Some(name_value.1.to_string()));
            }
        }
        Ok(None)
    }
}

fn get_bool_attribute_value_with_key(
    original_item_fn: &ItemFn,
    key: &str,
    values: &[(String, String)],
) -> MacroResult<bool> {
    if values.is_empty() {
        Err(Error::new(
            original_item_fn.span(),
            "sl_sh_fn requires at least one name-value pair, 'fn_name = \"<name-of-sl-sh-fun>\"'.",
        ))
    } else {
        for name_value in values {
            if name_value.0 == key {
                return Ok(name_value.1 == "true");
            }
        }
        Ok(false)
    }
}

fn get_attribute_name_value(nested_meta: &NestedMeta) -> MacroResult<(String, String)> {
    match nested_meta {
        NestedMeta::Meta(meta) => match meta {
            Meta::NameValue(pair) => {
                let path = &pair.path;
                let lit = &pair.lit;
                match (path.get_ident(), lit) {
                    (Some(ident), Lit::Str(partial_name)) => {
                        Ok((ident.to_string(), partial_name.value()))
                    }
                    (Some(ident), Lit::Bool(b)) => {
                        Ok((ident.to_string(), b.value.to_string()))
                    }
                    (_, _) => Err(Error::new(
                        meta.span(),
                        "sl_sh_fn requires one name-value pair, 'fn_name'. Supports optional name-value pair 'eval_values = true')",
                    )),
                }
            }
            other => Err(Error::new(
                other.span(),
                "sl_sh_fn only supports one name-value pair attribute argument, 'fn_name'.",
            )),
        },
        other => Err(Error::new(
            other.span(),
            "sl_sh_fn only supports one name-value pair attribute argument, 'fn_name'.",
        )),
    }
}

fn get_type_handle(type_path: &TypePath) -> TypeHandle {
    if let Some((_generic, type_path)) = get_generic_argument_from_type_path(type_path) {
        let wrapper = opt_is_valid_generic_type(type_path, SPECIAL_ARG_TYPES.as_slice());
        match wrapper {
            Some("Option") => {
                return TypeHandle::Optional;
            }
            Some("VarArgs") => {
                return TypeHandle::VarArgs;
            }
            _ => {}
        }
    }
    TypeHandle::Direct
}

fn no_parse_param(
    _arg_name: &Ident,
    inner: TokenStream,
    _param: Param,
    _required_args: usize,
    _idx: usize,
) -> TokenStream {
    inner
}

fn parse_param(
    arg_name: &Ident,
    inner: TokenStream,
    param: Param,
    required_args: usize,
    idx: usize,
) -> TokenStream {
    match param.handle {
        TypeHandle::Direct => {
            quote! {
                let param = arg_types[#idx];
                match param.handle {
                    bridge_types::TypeHandle::Direct => match args.get(#idx) {
                        None => {
                            return Err(slvm::VMError::new_vm(format!(
                                "{} not given enough arguments, expected at least {} arguments, got {}.",
                                fn_name,
                                #required_args,
                                args.len()
                            )));
                        }
                        Some(#arg_name) => {
                            let #arg_name = *#arg_name;
                            #inner
                        },
                    },
                    _ => {
                        return Err(slvm::VMError::new_vm(format!(
                            "{} failed to parse its arguments, internal error.",
                            fn_name,
                        )));
                    },
                }
            }
        }
        TypeHandle::Optional => {
            quote! {
                let param = arg_types[#idx];
                let #arg_name = args.get(#idx);
                match param.handle {
                    bridge_types::TypeHandle::Optional => {
                        #inner
                    },
                    _ => {
                        return Err(slvm::VMError::new_vm(format!(
                            "{} failed to parse its arguments, internal error.",
                            fn_name,
                        )));
                    },
                }
            }
        }
        TypeHandle::VarArgs => {
            quote! {
                let param = arg_types[#idx];
                let arg = args.get(#idx);
                match param.handle {
                    bridge_types::TypeHandle::VarArgs => {
                        let #arg_name: &[slvm::Value] = if arg.is_none() {
                            &[]
                        } else {
                            &args[#idx..]
                        };
                        #inner
                    },
                    _ => {
                        return Err(slvm::VMError::new_vm(format!(
                            "{} failed to parse its arguments, internal error.",
                            fn_name,
                        )));
                    }
                }
            }
        }
    }
}

fn get_parser_for_type_handle(
    noop_outer_parse: bool,
) -> fn(&Ident, TokenStream, Param, usize, usize) -> TokenStream {
    match noop_outer_parse {
        true => no_parse_param,
        false => parse_param,
    }
}

/// generate an (optionally inlined) call to the original fn with the names of all of the variables,
/// arg_names, filled in,, e.g. `fn myfn(arg_0, arg_1, arg_2, ...) { ... }`.
/// This function also inserts a dynamic check to throw an error if too many
/// arguments were provided based on the signature of the target function.
fn make_orig_fn_call(
    inline: bool,
    takes_env: bool,
    original_item_fn: &ItemFn,
    original_fn_name: &Ident,
    required_args: usize,
    arg_names: Vec<Ident>,
) -> MacroResult<TokenStream> {
    // the original function call must return a Value object
    // this means all returned rust native types must implement TryIntoExpression
    // this is nested inside the builtin expression which must always
    // return a VMResult.
    let skip = usize::from(takes_env);
    let takes_env = if takes_env {
        quote! {environment, } // environment is the name that is passed in to this function
    } else {
        quote! {}
    };

    let (return_type, lisp_return) = get_return_type(original_item_fn)?;
    let returns_none = "()" == return_type.to_token_stream().to_string();
    let fn_body = if inline {
        let mut inline_toks = vec![];
        for (fn_arg, arg_name) in original_item_fn
            .sig
            .inputs
            .iter()
            .skip(skip)
            .zip(arg_names.iter())
        {
            match fn_arg {
                FnArg::Receiver(_) => {}
                FnArg::Typed(typed) => {
                    let pat = typed.pat.clone();
                    let ty = typed.ty.clone();
                    let binding = quote! {
                        let #pat: #ty = #arg_name;
                    };
                    inline_toks.push(binding);
                }
            }
        }

        let block = original_item_fn.block.clone();
        match &original_item_fn.sig.output {
            ReturnType::Default => {
                quote! {{
                    #(#inline_toks)*
                    let res = {
                        #block
                    };
                    res
                }}
            }
            ReturnType::Type(_ra_arrow, ty) => {
                quote! {{
                    #(#inline_toks)*
                    let res: #ty = {
                        #block
                    };
                    res
                }}
            }
        }
    } else {
        quote! {
            #original_fn_name(#takes_env #(#arg_names),*)
        }
    };

    let original_fn_call = match (return_type, lisp_return, returns_none) {
        (Some(_), Some(SupportedGenericReturnTypes::VMResult), true) => quote! {
            #fn_body?;
            return Ok(slvm::Value::Nil);
        },
        (Some(_), Some(SupportedGenericReturnTypes::Option), true) => quote! {
            #fn_body;
            return Ok(slvm::Value::Nil);
        },
        (Some(_), Some(SupportedGenericReturnTypes::VMResult), false) => quote! {
            use bridge_adapters::lisp_adapters::SlInto;
            return #fn_body.and_then(|x| x.sl_into(environment));
        },
        (Some(_), Some(SupportedGenericReturnTypes::Option), false) => quote! {
            if let Some(val) = #fn_body {
                use bridge_adapters::lisp_adapters::SlFrom;
                let val = slvm::Value::sl_from(val, environment)?;
                Ok(val)
            } else {
                return Ok(slvm::Value::Nil);
            }
        },
        // coerce to Expression
        (Some(_), None, _) => quote! {
            use bridge_adapters::lisp_adapters::SlInto;
            return #fn_body.sl_into(environment);
        },
        (None, Some(_), _) => {
            unreachable!("If this functions returns a VMResult it must also return a value.");
        }
        // no return
        (None, None, _) => quote! {
            #fn_body;
            return Ok(slvm::Value::Nil);
        },
    };
    let const_params_len = get_const_params_len_ident();
    Ok(quote! {
        match args.get(#const_params_len) {
            Some(_) if #const_params_len == 0 || arg_types[#const_params_len - 1].handle != bridge_types::TypeHandle::VarArgs => {
                return Err(slvm::VMError::new_vm(format!(
                    "{} given too many arguments, expected at least {} arguments, got {}.",
                    fn_name,
                    #required_args,
                    args.len()
                )));
            }
            _ => {
                #original_fn_call
            }
        }
    })
}

/// create two lists that can be joined by macro syntax to create the inner part of a function
/// signature, e.g. (arg_0: a_type, arg_1: b_type, ...) in some existing rust function:
/// fn myfn(arg_0: a_type, arg_1: b_type, ...) { ... }
fn generate_inner_fn_signature_to_orig_fn_call(
    original_item_fn: &ItemFn,
    takes_env: bool,
) -> MacroResult<Vec<Ident>> {
    let len = if takes_env {
        original_item_fn.sig.inputs.len() - 1
    } else {
        original_item_fn.sig.inputs.len()
    };
    let mut arg_names = vec![];
    for i in 0..len {
        let parse_name = "arg_".to_string() + &i.to_string();
        let parse_name = Ident::new(&parse_name, Span::call_site());
        arg_names.push(parse_name);
    }
    Ok(arg_names)
}

/// return a code for how to refer to the inner exp enum referent type in
/// an function call.
fn tokens_for_matching_references(passing_style: PassingStyle, ty: &TypePath) -> TokenStream {
    match passing_style {
        PassingStyle::Value => quote! {#ty},
        PassingStyle::Reference => quote! {&#ty},
        PassingStyle::MutReference => quote! {& mut #ty},
    }
}

fn get_arg_pos(ident: &Ident) -> MacroResult<String> {
    let arg_string = ident.to_string();
    arg_string.split('_').nth(1).map(|x| x.to_string()).ok_or_else(|| Error::new(
        ident.span(),
        "Arg name should be in form arg_2 which means it should always have two and only two items. Internal error.",
    ))
}

/// if expecting a Vec then the actual expression itself should be iterable
/// (Pair/Vector/Nil), set arg_name_itself_is_iter = true. Otherwise it's
/// varargs which means the original args vector is passed in and
/// iterated over. the implication of passing in Vec is that if the Exp
/// doesn't match one of a few underlying sl-sh types passing it to
/// this function is an error.
fn parse_variadic_args_type(
    arg_name_itself_is_iter: bool,
    ty: &TypePath,
    fn_name: &str,
    arg_name: &Ident,
    inner: TokenStream,
    collect_type: TokenStream,
) -> MacroResult<TokenStream> {
    let rust_type = get_type_or_wrapped_type(ty, POSSIBLE_ARG_TYPES.as_slice());
    let arg_pos = get_arg_pos(arg_name)?;
    match rust_type {
        RustType::Path(_wrapped_ty, _span) => {
            if arg_name_itself_is_iter {
                // This means the target type is a Vec<T> this means the passed in Value
                // must be a list or vector or pair.
                // use .iter(environment) if type is correct and coerce all elements
                // to target type.
                Ok(quote! {
                    let #arg_name = if matches!(#arg_name, slvm::Value::List(_, _) | slvm::Value::Vector(_) | slvm::Value::Pair(_))
                    {
                        let #arg_name = #arg_name
                            .iter(environment)
                            .map(|#arg_name| {
                                use bridge_adapters::lisp_adapters::SlIntoRef;
                                #arg_name.sl_into_ref(environment)
                            })
                            .collect::<slvm::VMResult<#ty>>()?;
                        #inner
                    } else {
                        let err_str = format!("{}: Expected a vector or list for argument at position {}.", #fn_name, #arg_pos);
                        return Err(slvm::VMError::new_vm(err_str));
                    };
                })
            } else {
                // varargs needs all items to be flattened into a single vector.
                // call iter_all so no value save nil is skipped.
                Ok(quote! {
                    let #arg_name = #arg_name.iter()
                        .flat_map(|#arg_name| #arg_name.iter_all(environment))
                        .map(|#arg_name| {
                            use bridge_adapters::lisp_adapters::SlIntoRef;
                            #arg_name.sl_into_ref(environment)
                        })
                        .collect::<slvm::VMResult<#ty>>()?;
                    #inner
                })
            }
        }
        RustType::Tuple(type_tuple, _span) => {
            if !type_tuple.elems.is_empty() {
                let arg_pos = get_arg_pos(arg_name)?;
                let arg_check = if arg_name_itself_is_iter {
                    quote! {
                        if !matches!(#arg_name, slvm::Value::List(_, _) | slvm::Value::Vector(_) | slvm::Value::Pair(_))
                        {
                            let err_str = format!("{}: Expected a vector or list for argument at position {}.", #fn_name, #arg_pos);
                            return Err(slvm::VMError::new_vm(err_str));
                        }
                    }
                } else {
                    quote! {}
                };
                let tuple_len = type_tuple.elems.len();
                let arg_name_base = arg_name.to_string() + "_";
                let arg_names = (0..type_tuple.elems.len())
                    .map(|x| {
                        Ident::new(
                            &(arg_name_base.to_string() + &x.to_string()),
                            Span::call_site(),
                        )
                    })
                    .collect::<Vec<Ident>>();
                let mut types = vec![];
                let mut type_assertions = vec![];
                let mut args = vec![];
                for (elem, arg_name) in type_tuple.elems.iter().zip(arg_names.iter()) {
                    types.push(elem.clone());
                    type_assertions.push(quote! {
                        static_assertions::assert_impl_all!(slvm::Value: bridge_adapters::lisp_adapters::SlFrom<#elem>);
                    });
                    args.push(quote! {
                        use bridge_adapters::lisp_adapters::SlInto;
                        //TODO put #fn_name back in
                        let #arg_name: #elem = #arg_name.sl_into(environment)?;
                    })
                }
                Ok(quote! {{
                    //TODO PC SlIntoRef?
                    use bridge_adapters::lisp_adapters::SlInto;
                    #(#type_assertions)*
                    #arg_check
                    let #arg_name = #arg_name
                        .iter()
                        .map(|#arg_name| {
                            let #arg_name = #arg_name.iter().collect::<Vec<slvm::Value>>();
                            match #arg_name.sl_into(environment) {
                                Ok(#arg_name) => {
                                    let #arg_name: [slvm::Value; #tuple_len] = #arg_name;
                                    let [#(#arg_names),*] = #arg_name;
                                    #(#args)*
                                    Ok((#(#arg_names),*))
                                }
                                Err(_) => {
                                    let err_str = format!("{}: Expected a sl_sh vector or list of tuples of length {} corresponding to the argument at position {}.", #fn_name, #tuple_len, #arg_pos);
                                    Err(slvm::VMError::new_vm(err_str))
                                }
                            }
                        })
                        .collect::<slvm::VMResult<#collect_type<(#(#types),*)>>>()?;
                    #inner
                }})
            } else {
                let arg_pos = get_arg_pos(arg_name)?;
                let err_str = format!(
                    "Error with argument at position {}, sl_sh_fn only supports tuple pairs.",
                    arg_pos
                );
                Err(Error::new(type_tuple.span(), err_str))
            }
        }
        ty => {
            let err_str = "Vec<T> and VarArgs<T> only support T of type Type::Path or Type::Tuple.";
            Err(Error::new(ty.span(), err_str))
        }
    }
}

/// for [`Option<Value>`] values the ref_exp must first be parsed as an
/// Option, and only in the case that the option is Some will it be
/// necessary to match against every ExpEnum variant.
#[allow(clippy::too_many_arguments)]
fn parse_optional_type(
    ty: &TypePath,
    fn_name: &str,
    fn_name_ident: &Ident,
    arg_name: &Ident,
    passing_style: PassingStyle,
    inner: TokenStream,
    idx: usize,
    required_args: usize,
    param: Param,
) -> MacroResult<TokenStream> {
    let some_inner = quote! {
        let #arg_name = Some(#arg_name);
        #inner
    };
    // in the case that the value is some, which means the Value is no longer
    // wrapped in Option, the parse_typehandle_value_type can be repurposed but
    // with the caveat that after the value of inner it is handed first wraps
    // the matched ExpEnum in Some bound to the #arg_name like the
    // rust native function expects.
    let some_arg_value_type_parsing_code = parse_direct_type(
        ty,
        fn_name,
        fn_name_ident,
        arg_name,
        passing_style,
        some_inner,
        idx,
        required_args,
        param,
    )?;
    Ok(quote! {
        match #arg_name {
            None => {
                let #arg_name = None;
                #inner
            }
            Some(#arg_name) => {
               let #arg_name = *#arg_name;
               #some_arg_value_type_parsing_code
            }
        }
    })
}

/// None if not Rust type vec
fn is_vec(ty: &TypePath) -> Option<Type> {
    if let Some((ty, type_path)) = get_generic_argument_from_type_path(ty) {
        let wrapper = opt_is_valid_generic_type(type_path, &["Vec"]);
        if let (GenericArgument::Type(ty), Some(_)) = (ty, wrapper) {
            match <Type as Into<RustType>>::into(ty.clone()) {
                RustType::Path(_, _) | RustType::Tuple(_, _) => return Some(ty.clone()),
                _ => {}
            }
        }
    }
    None
}

/// at this point the macro is only operating on types it expects
/// which are any rust types, any rust types wrapped in Option,
/// and any rust types wrapped in Vec. If in the future this is
/// confusing wrapper types can be made, i.e. SlshVarArgs,
/// so normal rust Vec could be used without being turned into
/// a SlshVarArgs
fn get_type_or_wrapped_type<'a>(ty: &'a TypePath, possible_types: &'a [&str]) -> RustType {
    if let Some((ty, type_path)) = get_generic_argument_from_type_path(ty) {
        let wrapper = opt_is_valid_generic_type(type_path, possible_types);
        if let (GenericArgument::Type(ty), Some(_)) = (ty, wrapper) {
            return <Type as Into<RustType>>::into(ty.clone());
        }
    }
    RustType::Path(ty.clone(), ty.span())
}

/// for regular Value values (no Optional/VarArgs) ref_exp
/// just needs to be matched based on it's ExpEnum variant.
#[allow(clippy::too_many_arguments)]
fn parse_direct_type(
    ty: &TypePath,
    fn_name: &str,
    fn_name_ident: &Ident,
    arg_name: &Ident,
    passing_style: PassingStyle,
    inner: TokenStream,
    idx: usize,
    required_args: usize,
    param: Param,
) -> MacroResult<TokenStream> {
    if is_vec(ty).is_some() {
        parse_variadic_args_type(true, ty, fn_name, arg_name, inner, quote! { Vec })
    } else {
        let ty = get_type_or_wrapped_type(ty, SPECIAL_ARG_TYPES.as_slice());
        match ty {
            RustType::Path(ty, _span) => {
                let (passing_style, ty) = (
                    passing_style,
                    tokens_for_matching_references(passing_style, &ty),
                );

                match passing_style {
                    PassingStyle::Value => Ok(quote! {{
                        use bridge_adapters::lisp_adapters::SlIntoRef;
                        let #arg_name: #ty = #arg_name.sl_into_ref(environment)?;
                        #inner
                    }}),
                    PassingStyle::Reference => Ok(quote! {{
                        use bridge_adapters::lisp_adapters::SlIntoRef;
                        let #arg_name: #ty = #arg_name.sl_into_ref(environment)?;
                        #inner
                    }}),
                    PassingStyle::MutReference => Ok(quote! {{
                        use bridge_adapters::lisp_adapters::SlIntoRefMut;
                        let #arg_name: #ty = #arg_name.sl_into_ref_mut(environment)?;
                        #inner
                    }}),
                }
            }
            RustType::Tuple(type_tuple, _span) => parse_type_tuple(
                &type_tuple,
                fn_name,
                fn_name_ident,
                inner,
                arg_name,
                idx,
                required_args,
                param,
                no_parse_param,
            ),
            RustType::BareFn(_, _) | RustType::Reference(_, _) | RustType::Unsupported(_) => {
                let arg_pos = get_arg_pos(arg_name)?;
                let err_str = format!(
                    "Error with argument at position {}, sl_sh_fn only supports Vec<T>, Option<T>, and T where T is a Type::Path or Type::Tuple and can be moved, passed by reference, or passed by mutable reference (|&|&mut )(Type Path | (Type Path,*))",
                    arg_pos
                );
                Err(Error::new(ty.span(), err_str))
            }
        }
    }
}

/// create the nested match statements to parse rust types into sl_sh types.
/// the rust types will determine what sl_sh functions will be used for
/// transformation. If this function throws errors it means that the
/// inputs, val/passing style are wrong and aren't matching to the ArgType(s)
/// properly, or the rust type lookup function is busted.
#[allow(clippy::too_many_arguments)]
fn parse_type(
    ty: &TypePath,
    fn_name: (&str, &Ident),
    inner: TokenStream,
    param: Param,
    arg_name: &Ident,
    passing_style: PassingStyle,
    idx: usize,
    required_args: usize,
    outer_parse: fn(&Ident, TokenStream, Param, usize, usize) -> TokenStream,
) -> MacroResult<TokenStream> {
    let tokens = match param.handle {
        TypeHandle::Direct => parse_direct_type(
            ty,
            fn_name.0,
            fn_name.1,
            arg_name,
            passing_style,
            inner,
            idx,
            required_args,
            param,
        )?,
        TypeHandle::Optional => parse_optional_type(
            ty,
            fn_name.0,
            fn_name.1,
            arg_name,
            passing_style,
            inner,
            idx,
            required_args,
            param,
        )?,
        TypeHandle::VarArgs => parse_variadic_args_type(
            false,
            ty,
            fn_name.0,
            arg_name,
            inner,
            quote! { bridge_types::VarArgs },
        )?,
    };
    Ok(outer_parse(arg_name, tokens, param, required_args, idx))
}

/// create a vec literal of the expected Param types so code can check its arguments at runtime for
/// API arity/type correctness.
fn embed_params_vec(params: &[Param]) -> TokenStream {
    let mut tokens = vec![];
    for param in params {
        tokens.push(match (param.handle, param.passing_style) {
            (TypeHandle::Direct, PassingStyle::MutReference) => {
                quote! { bridge_types::Param {
                    handle: bridge_types::TypeHandle::Direct,
                    passing_style: bridge_types::PassingStyle::MutReference
                }}
            }
            (TypeHandle::Optional, PassingStyle::MutReference) => {
                quote! { bridge_types::Param {
                    handle: bridge_types::TypeHandle::Optional,
                    passing_style: bridge_types::PassingStyle::MutReference
                }}
            }
            (TypeHandle::VarArgs, PassingStyle::MutReference) => {
                quote! { bridge_types::Param {
                    handle: bridge_types::TypeHandle::VarArgs,
                    passing_style: bridge_types::PassingStyle::MutReference
                }}
            }
            (TypeHandle::Direct, PassingStyle::Reference) => {
                quote! {bridge_types::Param {
                    handle: bridge_types::TypeHandle::Direct,
                    passing_style: bridge_types::PassingStyle::Reference
                }}
            }
            (TypeHandle::Optional, PassingStyle::Reference) => {
                quote! { bridge_types::Param {
                    handle: bridge_types::TypeHandle::Optional,
                    passing_style: bridge_types::PassingStyle::Reference
                }}
            }
            (TypeHandle::VarArgs, PassingStyle::Reference) => {
                quote! { bridge_types::Param {
                    handle: bridge_types::TypeHandle::VarArgs,
                    passing_style: bridge_types::PassingStyle::Reference
                }}
            }
            (TypeHandle::Direct, PassingStyle::Value) => {
                quote! { bridge_types::Param {
                    handle: bridge_types::TypeHandle::Direct,
                    passing_style: bridge_types::PassingStyle::Value
                }}
            }
            (TypeHandle::Optional, PassingStyle::Value) => {
                quote! { bridge_types::Param {
                    handle: bridge_types::TypeHandle::Optional,
                    passing_style: bridge_types::PassingStyle::Value
                }}
            }
            (TypeHandle::VarArgs, PassingStyle::Value) => {
                quote! { bridge_types::Param {
                    handle: bridge_types::TypeHandle::VarArgs,
                    passing_style: bridge_types::PassingStyle::Value
                }}
            }
        });
    }
    let const_params_len = get_const_params_len_ident();
    quote! {
        let arg_types: [bridge_types::Param; #const_params_len] = [ #(#tokens),* ];
    }
}

/// write the intern_ function code. This code is generated to be called within sl-sh to avoid writing
/// boilerplate code to submit a function symbol and the associated code to the runtime. Every builtin
/// function must be inserted into a hashmap where the key is the name of the function and the value
/// is a function expression that stores the name of the rust function to call and its documentation.
/// It looks like the following in all cases:
// ```
// fn intern_one_int_to_float<S: std::hash::BuildHasher>(
//    interner: &mut sl_sh::Interner,
//    data: &mut std::collections::HashMap<&'static str, (sl_sh::types::Expression, String), S>,
//) {
//    let fn_name = "oneintofloat";
//    data.insert(
//        interner.intern(fn_name),
//        sl_sh::types::Expression::make_function(parse_one_int_to_float, " my docs\n"),
//    );
//}
// ```
fn generate_intern_fn(
    original_fn_name_str: &str,
    fn_name_ident: &Ident,
    fn_name: &str,
    doc_comments: String,
) -> TokenStream {
    let parse_name = get_parse_fn_name(original_fn_name_str);
    let intern_name = get_intern_fn_name(original_fn_name_str);
    quote! {
        fn #intern_name(env: &mut compile_state::state::SloshVm) {
            let #fn_name_ident = #fn_name;
            bridge_adapters::add_builtin(env, #fn_name_ident, #parse_name, #doc_comments);
        }
    }
}

/// write the parse_ version of the provided function. The function it generates takes an environment
/// and a list of Value, evaluates those expressions and then maps the provided list of expressions
/// to a list of ArgType values. To accomplish this information from compile time, arg_types,
/// is manually inserted into this function. This way the evaluated list of args and the expected
/// list of args can be compared and the appropriate vector of arguments can be created and
/// passed to the builtin function. To map a vector of ArgType structs to an actual function
/// call the ExpandVecToArgs trait is used. A sample parse_ function for a function that takes
/// one argument is shown below.
fn generate_parse_fn(
    generics: Option<Generics>,
    original_fn_name_str: &str,
    fn_name_ident: &Ident,
    fn_name: &str,
    args_len: usize,
    params: &[Param],
    inner: TokenStream,
) -> TokenStream {
    let parse_name = get_parse_fn_name(original_fn_name_str);
    let arg_vec_literal = embed_params_vec(params);

    let const_params_len = get_const_params_len_ident();
    if let Some(generics) = generics {
        let params = generics.params.clone();
        quote! {
            fn #parse_name #generics(
                environment: &#params mut compile_state::state::SloshVm,
                args: &#params [slvm::Value],
            ) -> slvm::VMResult<slvm::Value> {
                let #fn_name_ident = #fn_name;
                const #const_params_len: usize = #args_len;
                #arg_vec_literal

                #inner
            }
        }
    } else {
        quote! {
            fn #parse_name(
                environment: &mut compile_state::state::SloshVm,
                args: &[slvm::Value],
            ) -> slvm::VMResult<slvm::Value> {
                let #fn_name_ident = #fn_name;
                const #const_params_len: usize = #args_len;
                #arg_vec_literal

                #inner
            }
        }
    }
}

fn num_required_args(params: &[Param]) -> usize {
    params.iter().fold(0, |accumulator, nxt| {
        if nxt.handle == TypeHandle::Direct {
            accumulator + 1
        } else {
            accumulator
        }
    })
}

/// write the builtin_ version of the provided function. This function is the function that makes
/// a direct call to the original rust native function to which the macro was applied. To accomplish
/// this the builtin_ function generates takes some number of ArgType structs (the wrapper enum that
/// enables passing optional and varargs). the body of the function handles unwrapping the ArgType
/// variables and then unwrapping the Expressions those contain into the proper rust native
/// function. The process is done in a for loop but it recursively builds the body of builtin_
/// by passing around a token stream.
///
/// The token stream is initialized with code to call to the original rust native function with
/// pre-generated names for each of the arguments, e.g. `my_rust_native_function(arg_0, arg_1);`.
/// Each subsequent iteration of the loop takes the previous token stream returned by the loop and
/// uses that as it's innermost scope. Thus the original function call is at the core of a series
/// of scopes that create all the necessary arguments with the proper types that were specified on
/// initialization. For a function of one argument that means the code would look something like:
fn generate_builtin_fn(
    original_item_fn: &ItemFn,
    original_fn_name_str: &str,
    fn_name: &str,
    params: &[Param],
    fn_name_ident: &Ident,
    takes_env: bool,
    inline: bool,
) -> MacroResult<TokenStream> {
    let original_fn_name = Ident::new(original_fn_name_str, Span::call_site());
    let arg_names = generate_inner_fn_signature_to_orig_fn_call(original_item_fn, takes_env)?;
    let required_args = num_required_args(params);

    let orig_fn_call = make_orig_fn_call(
        inline,
        takes_env,
        original_item_fn,
        &original_fn_name,
        required_args,
        arg_names.clone(),
    )?;
    // initialize the innermost token stream to the code of the original_fn_call
    let mut prev_token_stream = orig_fn_call;
    let skip = usize::from(takes_env);
    let inputs_less_env_len = original_item_fn.sig.inputs.len() - skip;
    if inputs_less_env_len != params.len() {
        let err_str = format!(
            "sl_sh_fn macro is broken, signature of target function has an arity of {}, but this macro computed its arity as: {} (arity is - 1 if takes_env is true).",
            inputs_less_env_len,
            params.len(),
        );
        return Err(Error::new(original_item_fn.span(), err_str));
    }
    let fn_args = original_item_fn
        .sig
        .inputs
        .iter()
        .skip(skip)
        .zip(arg_names.iter())
        .zip(params.iter());
    for (idx, ((fn_arg, arg_name), param)) in fn_args.enumerate() {
        if let FnArg::Typed(ty) = fn_arg {
            // this needs to use the args.iter() pattern now.
            prev_token_stream = parse_fn_arg_type(
                &ty.ty,
                fn_name,
                fn_name_ident,
                prev_token_stream,
                arg_name,
                false,
                idx,
                *param,
                required_args,
            )?;
        }
    }
    let (return_type, _) = get_return_type(original_item_fn)?;
    let mut conversions_assertions_code = vec![];
    if let Some(return_type) = return_type {
        if get_generic_argument_from_type(&return_type).is_none() {
            conversions_assertions_code.push(generate_assertions_code_for_return_type_conversions(
                &return_type,
            ));
        }
    }
    let tokens = quote! {
        #(#conversions_assertions_code)*
        // let #fn_name_ident = #fn_name; already included in parse function
        // as well as `args`, a vec of expression,
        // `fn_name_ident` the ident of the fn_name
        // `ARGS_LEN` constant representing arity of original fn
        // and `arg_types` the embedded vec of Arg's available at runtime.
        #prev_token_stream
    };
    Ok(tokens)
}

/// recursively wrap the received sl_sh args at the given idx in callback functions that parse the Expressions
/// into the a variable with a predefined  name with the same type as the corresponding parameter
/// in the rust native function.
#[allow(clippy::too_many_arguments)]
fn parse_fn_arg_type(
    ty: &Type,
    fn_name: &str,
    fn_name_ident: &Ident,
    prev_token_stream: TokenStream,
    arg_name: &Ident,
    noop_outer_parse: bool,
    idx: usize,
    param: Param,
    required_args: usize,
) -> MacroResult<TokenStream> {
    match <Type as Into<RustType>>::into(ty.clone()) {
        RustType::Path(ty, _span) => {
            let parse_layer_1 = get_parser_for_type_handle(noop_outer_parse);
            let passing_style = PassingStyle::Value;
            parse_type(
                &ty,
                (fn_name, fn_name_ident),
                prev_token_stream,
                param,
                arg_name,
                passing_style,
                idx,
                required_args,
                parse_layer_1,
            )
        }
        RustType::Tuple(type_tuple, _span) => {
            let parse_layer_1 = get_parser_for_type_handle(noop_outer_parse);
            parse_type_tuple(
                &type_tuple,
                fn_name,
                fn_name_ident,
                prev_token_stream,
                arg_name,
                idx,
                required_args,
                param,
                parse_layer_1,
            )
        }
        RustType::Reference(ty_ref, _span) => match <Type as Into<RustType>>::into(*ty_ref.elem) {
            RustType::Path(ty, _span) => {
                let parse_layer_1 = get_parser_for_type_handle(noop_outer_parse);
                let passing_style = if ty_ref.mutability.is_some() {
                    PassingStyle::MutReference
                } else {
                    PassingStyle::Reference
                };
                parse_type(
                    &ty,
                    (fn_name, fn_name_ident),
                    prev_token_stream,
                    param,
                    arg_name,
                    passing_style,
                    idx,
                    required_args,
                    parse_layer_1,
                )
            }
            RustType::Tuple(type_tuple, _span) => {
                let parse_layer_1 = get_parser_for_type_handle(noop_outer_parse);
                parse_type_tuple(
                    &type_tuple,
                    fn_name,
                    fn_name_ident,
                    prev_token_stream,
                    arg_name,
                    idx,
                    required_args,
                    param,
                    parse_layer_1,
                )
            }
            RustType::BareFn(_, _) | RustType::Unsupported(_) | RustType::Reference(_, _) => {
                let arg_pos = get_arg_pos(arg_name)?;
                let err_str = format!(
                    "Error with argument at position {}, sl_sh_fn only supports Vec<T>, Option<T>, and T where T is a Type::Path or Type::Tuple and can be moved, passed by reference, or passed by mutable reference (|&|&mut )(Type Path | (Type Path,*))",
                    arg_pos
                );
                Err(Error::new(ty.span(), err_str))
            }
        },
        RustType::BareFn(_, _) | RustType::Unsupported(_) => {
            let arg_pos = get_arg_pos(arg_name)?;
            let err_str = format!(
                "Error with argument at position {}, sl_sh_fn only supports Vec<T>, Option<T>, and T where T is a Type::Path or Type::Tuple and can be moved, passed by reference, or passed by mutable reference (|&|&mut )(Type Path | (Type Path,*))",
                arg_pos
            );
            Err(Error::new(ty.span(), err_str))
        }
    }
}

#[allow(clippy::too_many_arguments)]
fn parse_type_tuple(
    type_tuple: &TypeTuple,
    fn_name: &str,
    fn_name_ident: &Ident,
    inner: TokenStream,
    arg_name: &Ident,
    idx: usize,
    required_args: usize,
    param: Param,
    outer_parse: fn(&Ident, TokenStream, Param, usize, usize) -> TokenStream,
) -> MacroResult<TokenStream> {
    // at the end of all the tuple parsing the inner token stream expects
    // arg_name to be:
    // let arg_name_N: (T, U) = (arg_name_N_0, arg_name_N_1);
    // this means that first we must take the arg_names of what will be the
    // tuple pair and put them back into the ident that this recursive process
    // expects.
    let arg_name_base = arg_name.to_string() + "_";
    let arg_names = (0..type_tuple.elems.len())
        .map(|x| {
            Ident::new(
                &(arg_name_base.to_string() + &x.to_string()),
                Span::call_site(),
            )
        })
        .collect::<Vec<Ident>>();
    let mut inner = quote! {
        let #arg_name = (#(#arg_names),*);
        #inner
    };
    let mut expressions = vec![];
    let tuple_len = type_tuple.elems.len();
    let tokens = if !type_tuple.elems.is_empty() {
        for (i, ty) in type_tuple.elems.iter().enumerate() {
            expressions.push(quote! { slvm::Value });
            let arg_name_pair = Ident::new(
                &(arg_name_base.to_string() + &i.to_string()),
                Span::call_site(),
            );
            let param = get_param_from_type(ty.clone(), ty.span(), i)?;
            inner = parse_fn_arg_type(
                ty,
                fn_name,
                fn_name_ident,
                inner,
                &arg_name_pair,
                true,
                i,
                param,
                required_args,
            )?;
        }
        inner
    } else {
        inner
    };
    let arg_pos = get_arg_pos(arg_name)?;
    let tokens = quote! {{
        use bridge_adapters::lisp_adapters::SlInto;
        if !matches!(#arg_name, slvm::Value::List(_, _) | slvm::Value::Vector(_) | slvm::Value::Pair(_))
        {
            let err_str = format!("{}: Expected a vector or list for argument at position {}.", #fn_name, #arg_pos);
            return Err(slvm::VMError::new_vm(err_str));
        }
        let #arg_name = #arg_name.iter().collect::<Vec<slvm::Value>>();
        match #arg_name.sl_into(environment) {
            Ok(#arg_name) => {
                let #arg_name: [slvm::Value; #tuple_len] = #arg_name;
                let [#(#arg_names),*] = #arg_name;
                #tokens
            }
            Err(_) => {
                let err_str = format!("{}: Expected a sl_sh vector or list with {} elements corresponding to the tuple at argument position {}.", #fn_name, #tuple_len, #arg_pos);
                return Err(slvm::VMError::new_vm(err_str));
            }
        }
    }};
    Ok(outer_parse(arg_name, tokens, param, required_args, idx))
}

/// Optional and VarArgs types are supported to create the idea of items that might be provided or
/// for providing a list of zero or more items that can be passed in.
/// The nature of optional and varargs are context dependent because variable numbers of
/// arguments have to be at the end of the function signature. This method verifies that items
/// marked as Optional are last, and VarArgs is supported but only in the last position, which can
/// be after any number of Optional arguments. This means non Optional/VarArgs types must
/// come before all Optional and VarArgs types.
fn are_args_valid(original_item_fn: &ItemFn, params: &[Param], takes_env: bool) -> MacroResult<()> {
    if params.is_empty() || (!takes_env && params.len() == 1 || takes_env && params.len() == 2) {
        Ok(())
    } else {
        let mut found_opt = false;
        let mut found_value = false;
        for (i, param) in params.iter().rev().enumerate() {
            match (i, param.handle, found_opt, found_value) {
                (i, TypeHandle::VarArgs, _, _) if i > 0 => {
                    return Err(Error::new(
                        original_item_fn.span(),
                        "Only one Vec argument is supported and it must be the last argument.",
                    ));
                }
                (_, TypeHandle::Optional, _, true) => {
                    return Err(Error::new(
                        original_item_fn.span(),
                        "Optional argument(s) must be placed last.",
                    ));
                }
                (_, TypeHandle::Optional, _, _) => {
                    found_opt = true;
                }
                (_, TypeHandle::Direct, _, _) => {
                    found_value = true;
                }
                (_, _, _, _) => {}
            }
        }
        Ok(())
    }
}

fn get_param_from_type(ty: Type, span: Span, pos: usize) -> MacroResult<Param> {
    let ty_clone = ty.clone();
    let param = match <Type as Into<RustType>>::into(ty) {
        RustType::Path(ty, _span) => {
            let val = get_type_handle(&ty);
            Param {
                handle: val,
                passing_style: PassingStyle::Value,
            }
        }
        RustType::Tuple(_type_tuple, _span) => Param {
            handle: TypeHandle::Direct,
            passing_style: PassingStyle::Value,
        },
        RustType::Reference(ty_ref, _span) => {
            let passing_style = if ty_ref.mutability.is_some() {
                PassingStyle::MutReference
            } else {
                PassingStyle::Reference
            };
            match <Type as Into<RustType>>::into(*ty_ref.elem) {
                RustType::Path(ty, _span) => {
                    let val = get_type_handle(&ty);
                    Param {
                        handle: val,
                        passing_style,
                    }
                }
                RustType::Tuple(_type_tuple, _span) => Param {
                    handle: TypeHandle::Direct,
                    passing_style,
                },
                _ => {
                    return Err(Error::new(
                        span,
                        format!(
                            "Error with argument at position {}, sl_sh_fn only supports passing Type::Path and Type::Tuple by value or ref/ref mut, no either syn::Type's are supported: {:?}.",
                            pos,
                            ty_clone.to_token_stream(),
                        ),
                    ));
                }
            }
        }
        _ => {
            return Err(Error::new(
                span,
                format!(
                    "Error with argument at position {}, sl_sh_fn only supports passing Type::Path and Type::Tuple by value or ref/ref mut, no either syn::Type's are supported: {:?}.",
                    pos,
                    ty_clone.to_token_stream(),
                ),
            ));
        }
    };
    Ok(param)
}

/// Create a [`Vec<Param>`] from the original fn's signature. Information is needed at compile and
/// run time to translate the list of sl_sh expressions to rust native types. This Arg types
/// stores the information about the rust native type (Value/Option/Var) as well as whether it's moved, passed
/// by reference, or passed by mutable reference.
fn parse_src_function_arguments(
    original_item_fn: &ItemFn,
    takes_env: bool,
) -> MacroResult<Vec<Param>> {
    let mut parsed_args = vec![];
    let len = if takes_env {
        original_item_fn.sig.inputs.len() - 1
    } else {
        original_item_fn.sig.inputs.len()
    };
    let mut arg_names = vec![];
    for i in 0..len {
        let parse_name = "arg_".to_string() + &i.to_string();
        let parse_name = Ident::new(&parse_name, Span::call_site());
        arg_names.push(parse_name);
    }

    let skip = usize::from(takes_env);

    for (i, fn_arg) in original_item_fn.sig.inputs.iter().enumerate().skip(skip) {
        match fn_arg {
            FnArg::Receiver(_) => {
                return Err(Error::new(
                    original_item_fn.span(),
                    "Associated functions that take the self argument are not supported.",
                ))
            }
            FnArg::Typed(ty) => {
                parsed_args.push(get_param_from_type(
                    *ty.ty.clone(),
                    original_item_fn.span(),
                    i,
                )?);
            }
        }
    }
    Ok(parsed_args)
}

/// return the function names the macro will create. Given a base name, <base>
/// return intern_<base> Ident to be used as function name
fn get_intern_fn_name(original_fn_name: &str) -> Ident {
    let builtin_name = "intern_".to_string() + original_fn_name;
    Ident::new(&builtin_name, Span::call_site())
}

/// return the function names the macro will create. Given a base name, <base>
/// return parse_<base> Ident to be used as function name
fn get_parse_fn_name(original_fn_name: &str) -> Ident {
    let builtin_name = "parse_".to_string() + original_fn_name;
    Ident::new(&builtin_name, Span::call_site())
}

/// Pull out every #doc attribute on the target fn for the proc macro attribute.
/// Ignore any other attributes and only Err if there are no #doc attributes.
fn get_documentation_for_fn(original_item_fn: &ItemFn) -> MacroResult<String> {
    let mut docs = "".to_string();
    for attr in &original_item_fn.attrs {
        for path_segment in attr.path.segments.iter() {
            if &path_segment.ident.to_string() == "doc" {
                if let Ok(Meta::NameValue(pair)) = attr.parse_meta() {
                    if let Lit::Str(partial_name) = &pair.lit {
                        docs += (*partial_name.value()).trim();
                        docs += "\n";
                    }
                }
            }
        }
    }
    if docs.is_empty() {
        Err(Error::new(
            original_item_fn.span(),
            "Functions with this attribute included must have documentation.",
        ))
    } else {
        Ok(docs)
    }
}

fn get_const_params_len_ident() -> Ident {
    Ident::new("PARAMS_LEN", Span::call_site())
}

fn parse_attributes(
    original_item_fn: &ItemFn,
    attr_args: AttributeArgs,
) -> MacroResult<(String, Ident, bool, bool, Option<Generics>)> {
    let vals = attr_args
        .iter()
        .map(get_attribute_name_value)
        .collect::<MacroResult<Vec<(String, String)>>>()?;
    let fn_name_ident = "fn_name".to_string();
    let fn_name = get_attribute_value_with_key(original_item_fn, &fn_name_ident, vals.as_slice())?
        .ok_or_else(|| {
            Error::new(
                original_item_fn.span(),
                "sl_sh_fn requires name-value pair, 'fn_name'",
            )
        })?;
    let fn_name_ident = Ident::new(&fn_name_ident, Span::call_site());

    let takes_env =
        get_bool_attribute_value_with_key(original_item_fn, "takes_env", vals.as_slice())?;

    // all functions default to inlining unless explicitly overriden.
    let inline =
        !get_bool_attribute_value_with_key(original_item_fn, "do_not_inline", vals.as_slice())?;

    let generics = original_item_fn.sig.generics.clone();
    let generics = match generics.params.len() {
        0 => None,
        1 => Some(generics),
        _ => {
            return Err(Error::new(
                original_item_fn.sig.generics.span(),
                "sl_sh_fn only supports functions with 0 or 1 generic lifetime parameters.",
            ))
        }
    };
    Ok((fn_name, fn_name_ident, takes_env, inline, generics))
}

/// this function outputs all of the generated code, it is composed into two different functions:
/// intern_<original_fn_name>
/// parse_<original_fn_name>
/// - intern_ is the simplest function, it is generated to be called within sl-sh to avoid writing
///   boilerplate code to submit a function symbol and the associated code to the runtime.
/// - parse_ has the same function signature as all rust native functions, it takes the environment
///   and a list of args. It evals those arguments at runtime and converts them to rust types
///   they can be consumed by the target rust function.
fn generate_sl_sh_fn(
    original_item_fn: &ItemFn,
    attr_args: AttributeArgs,
) -> MacroResult<TokenStream> {
    let (fn_name, fn_name_ident, takes_env, inline, generics) =
        parse_attributes(original_item_fn, attr_args)?;
    let original_fn_name_str = original_item_fn.sig.ident.to_string();
    let original_fn_name_str = original_fn_name_str.as_str();

    let params = parse_src_function_arguments(original_item_fn, takes_env)?;
    are_args_valid(original_item_fn, params.as_slice(), takes_env)?;
    let builtin_fn = generate_builtin_fn(
        original_item_fn,
        original_fn_name_str,
        fn_name.as_str(),
        params.as_slice(),
        &fn_name_ident,
        takes_env,
        inline,
    )?;

    let args_len = if takes_env {
        original_item_fn.sig.inputs.len() - 1
    } else {
        original_item_fn.sig.inputs.len()
    };
    let doc_comments = get_documentation_for_fn(original_item_fn)?;
    let intern_fn = generate_intern_fn(
        original_fn_name_str,
        &fn_name_ident,
        fn_name.as_str(),
        doc_comments,
    );
    let parse_fn = generate_parse_fn(
        generics,
        original_fn_name_str,
        &fn_name_ident,
        fn_name.as_str(),
        args_len,
        params.as_slice(),
        builtin_fn,
    );
    let tokens = quote! {
        #parse_fn

        #intern_fn
    };
    Ok(tokens)
}

/// macro that creates a bridge between rust native code and sl-sh code, specify the lisp
/// function name to be interned with the "fn_name" attribute. This macro outputs all of the
/// generated bridge code as well as the original function's code so it can be used
/// by the generated bridge code.
#[proc_macro_attribute]
pub fn sl_sh_fn(
    attr: proc_macro::TokenStream,
    input: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
    let attr_args = parse_macro_input!(attr as AttributeArgs);

    let tokens = match syn::parse::<Item>(input) {
        Ok(item) => match &item {
            Item::Fn(original_item_fn) => {
                let generated_code = match generate_sl_sh_fn(original_item_fn, attr_args) {
                    Ok(generated_code) => generated_code,
                    Err(e) => e.to_compile_error(),
                };
                let original_fn_code = item.into_token_stream();
                quote! {
                    #generated_code

                    #[allow(dead_code)]
                    #original_fn_code
                }
            }
            _ => Error::new(item.span(), "This attribute only supports functions.")
                .to_compile_error(),
        },
        Err(e) => Error::new(e.span(), "Failed to parse proc_macro_attribute.").to_compile_error(),
    };

    proc_macro::TokenStream::from(tokens)
}

//TODO
//  - functions that return Values, tuple return types?
//  - functions that accept iters?
//  - then... compare against inline the function being called... randomize variable names...
//      and fn names too? could pick some random string and prefix all generated idents.
//  - ISSUE #119 trybuild!

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

    // serves as a model for what it's like at runtime to iterate over the parameters of a function,
    // T serves as a generic so these tests can run with some data, but in practice T is some
    // type from the consuming library.
    fn loop_over_to_inline<T, const N: usize>(
        fn_name: &str,
        params: &[Param; N],
        args: &[T],
    ) -> Result<(), String> {
        let required_args = num_required_args(params);
        for idx in 0..N {
            to_inline(fn_name, idx, required_args, params, args)?;
        }
        if N > 0 {
            too_many_args_detection(fn_name, params, N, args)?;
        }

        Ok(())
    }

    // run last to see if the number of received arguments has exceeded the number expected based
    // on the arity of the rust function, and whether or not it ends in a varargs/array.
    fn too_many_args_detection<T>(
        fn_name: &str,
        arg_types: &[Param],
        len: usize,
        args: &[T],
    ) -> Result<(), String> {
        match args.get(len) {
            Some(_) if arg_types[len - 1].handle != TypeHandle::VarArgs => {
                return Err(format!(
                    "{} given too many arguments, expected {}, got {}.",
                    fn_name,
                    arg_types.len(),
                    args.len()
                ));
            }
            _ => {
                //macro
                println!("macro")
            }
        }
        Ok(())
    }

    // loop over each input and check based on current idx and presence of Arg or not
    // whether the args received is lower than needed based on the arity of the rust function.
    fn to_inline<T>(
        fn_name: &str,
        idx: usize,
        required_args: usize,
        params: &[Param],
        args: &[T],
    ) -> Result<(), String> {
        let param = params[idx];
        match args.get(idx) {
            None if param.handle == TypeHandle::Direct => {
                return Err(format!(
                    "{} not given enough arguments, expected at least {} arguments, got {}.",
                    fn_name,
                    required_args,
                    args.len()
                ));
            }
            _arg => {
                // insert
                println!("macro");
            }
        }
        Ok(())
    }
    struct Foo {}

    #[test]
    fn test_params_values_only() {
        let two_moved_values = vec![
            Param {
                handle: TypeHandle::Direct,
                passing_style: PassingStyle::Value,
            },
            Param {
                handle: TypeHandle::Direct,
                passing_style: PassingStyle::Value,
            },
        ];

        // if there are not enough arguments we throw an error.
        let args = vec![Foo {}];
        let args = loop_over_to_inline::<Foo, 2>(
            "foo",
            two_moved_values.as_slice().try_into().unwrap(),
            args.as_slice(),
        );
        assert!(args.unwrap_err().contains("not given enough arguments"));

        // if there are too many arguments we throw an error.
        let args = vec![Foo {}, Foo {}, Foo {}];
        let args = loop_over_to_inline::<Foo, 2>(
            "foo",
            two_moved_values.as_slice().try_into().unwrap(),
            args.as_slice(),
        );
        assert!(args.unwrap_err().contains("given too many"));

        let args = vec![Foo {}, Foo {}];
        loop_over_to_inline::<Foo, 2>(
            "foo",
            two_moved_values.as_slice().try_into().unwrap(),
            args.as_slice(),
        )
        .expect("Parsing should succeed.");
    }

    #[test]
    fn test_params_optionals() {
        let one_val_one_opt = vec![
            Param {
                handle: TypeHandle::Direct,
                passing_style: PassingStyle::Value,
            },
            Param {
                handle: TypeHandle::Optional,
                passing_style: PassingStyle::Value,
            },
        ];
        let args = vec![Foo {}, Foo {}];
        loop_over_to_inline::<Foo, 2>(
            "foo",
            one_val_one_opt.as_slice().try_into().unwrap(),
            args.as_slice(),
        )
        .expect("Parsing should succeed.");

        let args = vec![Foo {}];
        loop_over_to_inline::<Foo, 2>(
            "foo",
            one_val_one_opt.as_slice().try_into().unwrap(),
            args.as_slice(),
        )
        .expect("Parsing should succeed.");

        let args = vec![];
        let args = loop_over_to_inline::<Foo, 2>(
            "foo",
            one_val_one_opt.as_slice().try_into().unwrap(),
            args.as_slice(),
        );
        assert!(args.unwrap_err().contains("not given enough arguments"));

        let args = vec![Foo {}, Foo {}, Foo {}];
        let args = loop_over_to_inline::<Foo, 2>(
            "foo",
            one_val_one_opt.as_slice().try_into().unwrap(),
            args.as_slice(),
        );
        assert!(args.unwrap_err().contains("given too many"));

        let val_and_opt = vec![
            Param {
                handle: TypeHandle::Direct,
                passing_style: PassingStyle::Value,
            },
            Param {
                handle: TypeHandle::Optional,
                passing_style: PassingStyle::Value,
            },
        ];
        let args = vec![Foo {}, Foo {}];
        loop_over_to_inline::<Foo, 2>(
            "foo",
            val_and_opt.as_slice().try_into().unwrap(),
            args.as_slice(),
        )
        .expect("Parsing should succeed.");

        let args = vec![Foo {}];
        loop_over_to_inline::<Foo, 2>(
            "foo",
            val_and_opt.as_slice().try_into().unwrap(),
            args.as_slice(),
        )
        .expect("Parsing should succeed.");

        let args = vec![];
        let args = loop_over_to_inline::<Foo, 2>(
            "foo",
            val_and_opt.as_slice().try_into().unwrap(),
            args.as_slice(),
        );
        assert!(args.unwrap_err().contains("not given enough arguments"));

        let args = vec![Foo {}, Foo {}, Foo {}];
        let args = loop_over_to_inline::<Foo, 2>(
            "foo",
            val_and_opt.as_slice().try_into().unwrap(),
            args.as_slice(),
        );
        assert!(args.unwrap_err().contains("given too many"));
    }

    #[test]
    fn test_params_vec() {
        let one_vec = vec![Param {
            handle: TypeHandle::VarArgs,
            passing_style: PassingStyle::MutReference,
        }];

        let args = vec![];
        loop_over_to_inline::<Foo, 1>(
            "foo",
            one_vec.as_slice().try_into().unwrap(),
            args.as_slice(),
        )
        .expect("Parsing should succeed.");

        let args = vec![Foo {}];
        loop_over_to_inline::<Foo, 1>(
            "foo",
            one_vec.as_slice().try_into().unwrap(),
            args.as_slice(),
        )
        .expect("Parsing should succeed.");

        let args = vec![Foo {}, Foo {}];
        loop_over_to_inline::<Foo, 1>(
            "foo",
            one_vec.as_slice().try_into().unwrap(),
            args.as_slice(),
        )
        .expect("Parsing should succeed.");

        let args = vec![Foo {}, Foo {}, Foo {}];
        loop_over_to_inline::<Foo, 1>(
            "foo",
            one_vec.as_slice().try_into().unwrap(),
            args.as_slice(),
        )
        .expect("Parsing should succeed.");
    }

    #[test]
    fn test_params_vec_with_options() {
        let val_opt_and_vec = vec![
            Param {
                handle: TypeHandle::Direct,
                passing_style: PassingStyle::Reference,
            },
            Param {
                handle: TypeHandle::Optional,
                passing_style: PassingStyle::MutReference,
            },
            Param {
                handle: TypeHandle::VarArgs,
                passing_style: PassingStyle::Value,
            },
        ];

        let args = vec![];
        let args = loop_over_to_inline::<Foo, 3>(
            "foo",
            val_opt_and_vec.as_slice().try_into().unwrap(),
            args.as_slice(),
        );
        assert!(args.unwrap_err().contains("not given enough arguments"));
        let args = vec![Foo {}];
        loop_over_to_inline::<Foo, 3>(
            "foo",
            val_opt_and_vec.as_slice().try_into().unwrap(),
            args.as_slice(),
        )
        .expect("Parsing should succeed.");
        let args = vec![Foo {}, Foo {}];
        loop_over_to_inline::<Foo, 3>(
            "foo",
            val_opt_and_vec.as_slice().try_into().unwrap(),
            args.as_slice(),
        )
        .expect("Parsing should succeed.");
        let args = vec![Foo {}, Foo {}, Foo {}];
        loop_over_to_inline::<Foo, 3>(
            "foo",
            val_opt_and_vec.as_slice().try_into().unwrap(),
            args.as_slice(),
        )
        .expect("Parsing should succeed.");
        let args = vec![Foo {}, Foo {}, Foo {}, Foo {}, Foo {}];
        loop_over_to_inline::<Foo, 3>(
            "foo",
            val_opt_and_vec.as_slice().try_into().unwrap(),
            args.as_slice(),
        )
        .expect("Parsing should succeed.");

        let opts_and_vec = vec![
            Param {
                handle: TypeHandle::Optional,
                passing_style: PassingStyle::Reference,
            },
            Param {
                handle: TypeHandle::Optional,
                passing_style: PassingStyle::MutReference,
            },
            Param {
                handle: TypeHandle::VarArgs,
                passing_style: PassingStyle::Value,
            },
        ];

        let args = vec![];
        loop_over_to_inline::<Foo, 3>(
            "foo",
            opts_and_vec.as_slice().try_into().unwrap(),
            args.as_slice(),
        )
        .expect("Parsing should succeed.");
        let args = vec![Foo {}];
        loop_over_to_inline::<Foo, 3>(
            "foo",
            opts_and_vec.as_slice().try_into().unwrap(),
            args.as_slice(),
        )
        .expect("Parsing should succeed.");
        let args = vec![Foo {}, Foo {}];
        loop_over_to_inline::<Foo, 3>(
            "foo",
            opts_and_vec.as_slice().try_into().unwrap(),
            args.as_slice(),
        )
        .expect("Parsing should succeed.");
        let args = vec![Foo {}, Foo {}, Foo {}];
        loop_over_to_inline::<Foo, 3>(
            "foo",
            opts_and_vec.as_slice().try_into().unwrap(),
            args.as_slice(),
        )
        .expect("Parsing should succeed.");
        let args = vec![Foo {}, Foo {}, Foo {}, Foo {}, Foo {}];
        loop_over_to_inline::<Foo, 3>(
            "foo",
            opts_and_vec.as_slice().try_into().unwrap(),
            args.as_slice(),
        )
        .expect("Parsing should succeed.");
    }
}