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
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
//! Shades, a shading language EDSL in vanilla Rust.
//!
//! This crate provides an [EDSL] to build [shaders], leveraging the Rust compiler (`rustc`) and its type system to ensure
//! soundness and typing. Because shaders are written in Rust, this crate is completely language agnostic: it can in theory
//! target any shading language – the current tier-1 language being [GLSL]. The EDSL allows to statically type shaders
//! while still generating the actual shading code at runtime.
//!
//! # Motivation
//!
//! In typical graphics libraries and engines, shaders are _opaque strings_ – either hard-coded in the program, read from
//! a file at runtime, constructed via fragments of strings concatenated with each others, etc. The strings are passed to
//! the graphics drivers, which will _compile_ and _link_ the code at runtime. It is the responsibility of the runtime
//! (i.e. the graphics library, engine or the application) to check for errors and react correctly. Shading languages can
//! also be compiled _off-line_, and their bytecode is then used at runtime (c.f. SPIR-V).
//!
//! For a lot of people, this has proven okay for decades and even allowed _live coding_: because the shading code is
//! loaded at runtime, it is possible to re-load, re-compile and re-link it every time a change happens. However, this comes
//! with a non-negligible drawbacks:
//!
//! - The shading code is often checked either at runtime. In this case, ill-written shaders won’t be visible by
//!   programmers until the runtime is executed and the GPU driver refuses the shading code.
//! - When compiled off-line are transpiled to bytecode, extra specialized tooling is required (such as an external program,
//!   a language extension, etc.).
//! - Writing shaders imply learning a new language. The most widespread shading language is [GLSL] but others exist,
//!   meaning that people will have to learn specialized languages and, most of the time, weaker compilation systems. For
//!   instance, [GLSL] doesn’t have anything natively to include other [GLSL] files and it’s an old C-like language.
//! - Even though the appeal of using a language in a dynamic way can seem appealing, going from a dynamic language and
//!   using it in a statically manner is not an easy task. However, going the other way around (from a static to dynamic)
//!   is much much simpler. In other terms: it is possible to live-reload a compiled language with the help of low-level
//!   system primitives, such as `dlopen`, `dlsym`, etc. It’s more work but it’s possible. And
//!   [Rust can do it too](https://crates.io/crates/libloading).
//!
//! The author ([@phaazon]) of this crate thinks that shading code is still code, and that it should be treated as such.
//! It’s easy to see the power of live-coding / reloading, but it’s more important to provide a shading code that is
//! statically proven sound and with less bugs that without the static check. Also, as stated above, using a compiled
//! approach doesn’t prevent from writing a relocatable object, compiled isolated and reload this object, providing roughly
//! the same functionality as live-coding.
//!
//! Another important point is the choice of using an EDSL. Some people would argue that Rust has other interesting and
//! powerful ways to achieve the same goal. It is important to notice that this crate doesn’t provide a compiler to compile
//! Rust code to a shading language. Instead, it provides a Rust crate that will still generate the shading code at runtime.
//! Other alternatives would be using a [proc-macro]. Several crates who do this:
//!
//! - You can use the [glsl] and [glsl-quasiquote] crates. The first one is a parser for GLSL and the second one allows you
//!   to write GLSL in a quasi-quoter (`glsl! { /* here */  }`) and get it compiled and check at runtime. It’s still
//!   [GLSL], though, and the possibilities of runtime combinations are much less than an EDSL.
//! - You can use the [rust-gpu] project. It’s a similar project but they use a proc-macro, compiling Rust code
//!   representing GPU code. It requires a specific toolchain and doesn’t operate at the same level of this crate — it can
//!   even compile a large part of the `core` library.
//!
//! ## Influences
//!
//! - [blaze-html], a [Haskell] [EDSL] to build HTML in [Haskell].
//! - [selda], a [Haskell] [EDSL] to build SQL queries and execute them without writing SQL strings. This current crate is
//!   very similar in the approach.
//!
//! # Why you would love this
//!
//! If you like type systems, languages and basically hacking compilers (writing code for your compiler to generate the
//! runtime code!), then it’s likely you’ll like this crate. Among all the features you will find:
//!
//! - Use vanilla Rust. Because this crate is language-agnostic, the whole thing you need to know to get started is to
//!   write Rust. You don’t have to learn [GLSL] to use this crate — even though you still need to understand the concept
//!   of shaders, what they are, how they work, etc. But the _encoding of those concepts_ is now encapsulated by a native
//!   Rust crate.
//! - Types used to represent shading types are basic and native Rust types, such as `bool`, `f32` or `[T; N]`.
//! - Write a more functional code rather than imperative code. For instance, a _vertex shader_ in this crate is basically
//!   a function taking an object of type `Vertex` and returning another object, that will be passed to the next stage.
//! - Catch semantic bugs within `rustc`. For instance, assigning a `bool` to a `f32` in your shader code will trigger a
//!   `rustc` error.
//! - Make some code impossible to write. For instance, you will not be able to use in a _vertex shader_ expressions only
//!   valid in the context of a _fragment shader_, as this is not possible by their own definitions.
//! - Extend and add more items to famous shading languages. For instance, [GLSL] doesn’t have a `π` constant. This
//!   situation is fixed so you will never have to write `π` decimals by yourself anymore.
//! - Because you write Rust, benefit from all the language type candies, composability, extensibility and soundness.
//! - An experimental _monadic_ experience behind a _feature-gate_. This allows to write shaders by using the [do-notation]
//!   crate and remove a lot of boilerplate for you, making _scopes_ and _shader scopes_ hidden for you, making it feel
//!   like writing magic shading code.
//!
//! # Why you wouldn’t love this
//!
//! The crate is, as of nowadays, still very experimental. Here’s a list of things you might dislike about the crate:
//!
//! - The current verbosity is non-acceptable. Most lambdas you’ll have to use require you to annotate their arguments,
//!   even though those are clearly guessable. This situation should be addressed as soon as possible, but people has to
//!   know that the current situation implies lots of type ascriptions.
//! - Some people would argue that writing [GLSL] is much faster and simpler, and they would be right. However, you would
//!   need to learn [GLSL] in the first place; you wouldn’t be able to target SPIR-V; you wouldn’t have a solution to the
//!   static typing problem; etc.
//! - In the case of a runtime compilation / linking failure of your shading code, debugging it might be challenging, as
//!   all the identifiers (with a few exceptions) are generated for you. It’ll make it harder to understand the generated
//!   code.
//! - Some concepts, especially control-flow statements, look a bit weird. For instance, a `for` loop in [GLSL] is written
//!   with a much more convoluted way with this crate. The generated code is the same, but it is correctly more verbose via
//!   this crate.
//!
//! [@phaazon]: https://github.com/phaazon
//! [EDSL]: https://en.wikipedia.org/wiki/Domain-specific_language#External_and_Embedded_Domain_Specific_Languages
//! [shaders]: https://en.wikipedia.org/wiki/Shader
//! [GLSL]: https://www.khronos.org/registry/OpenGL/specs/gl/GLSLangSpec.4.60.pdf
//! [Haskell]: https://www.haskell.org
//! [blaze-html]: http://hackage.haskell.org/package/blaze-html
//! [selda]: http://hackage.haskell.org/package/selda
//! [proc-macro]: https://doc.rust-lang.org/reference/procedural-macros.html
//! [rust-gpu]: https://github.com/EmbarkStudios/rust-gpu
//! [do-notation]: https://crates.io/crates/do-notation

#![cfg_attr(feature = "fun-call", feature(unboxed_closures), feature(fn_traits))]

pub mod writer;

use std::{
  iter::once,
  marker::PhantomData,
  ops::{self, Deref, DerefMut},
};

/// A fully built shader stage as represented in Rust, obtained by adding the `main` function to a [`ShaderBuilder`].
#[derive(Debug)]
pub struct Shader {
  pub(crate) builder: ShaderBuilder,
}

impl AsRef<Shader> for Shader {
  fn as_ref(&self) -> &Shader {
    self
  }
}

/// A shader builder.
///
/// This opaque type is the representation of a shader stage in Rust. It contains constants, uniforms, inputs, outputs and
/// functions declarations. Such a type is used to build a shader stage and is fully built when the `main` function is
/// present in its code. See [`ShaderBuilder::main_fun`] for further details.
#[derive(Debug)]
pub struct ShaderBuilder {
  pub(crate) decls: Vec<ShaderDecl>,
  next_fun_handle: u16,
  next_global_handle: u16,
}

impl ShaderBuilder {
  /// Create a new _vertex shader_.
  ///
  /// This method creates a [`Shader`] that can be used as _vertex shader_. This is enforced by the fact only this
  /// method authorized to build a vertex [`Shader`] by using the [`VertexShaderEnv`] argument passed to the input
  /// closure.
  ///
  /// That closure takes as first argument a mutable reference on a [`ShaderBuilder`] and a [`VertexShaderEnv`] as
  /// second argument. The [`VertexShaderEnv`] allows you to access to vertex attributes found in any invocation of
  /// a vertex shader. Those are expressions (read-only) and variables (read-write) valid only in vertex shaders.
  ///
  /// # Return
  ///
  /// This method returns the fully built [`Shader`], which cannot be mutated anymore once it has been built,
  /// and can be passed to various [`writers`](crate::writer) to generate actual code for target shading languages.
  ///
  /// # Examples
  ///
  /// ```
  /// use shades::{Scope, ShaderBuilder, V3, inputs, vec4};
  ///
  /// let vertex_shader = ShaderBuilder::new_vertex_shader(|mut s, vertex| {
  ///   inputs!(s, position: V3<f32>);
  ///
  ///   s.main_fun(|s: &mut Scope<()>| {
  ///     s.set(vertex.position, vec4!(position, 1.));
  ///   })
  /// });
  /// ```
  pub fn new_vertex_shader(f: impl FnOnce(Self, VertexShaderEnv) -> Shader) -> Shader {
    f(Self::new(), VertexShaderEnv::new())
  }

  /// Create a new _tessellation control shader_.
  ///
  /// This method creates a [`Shader`] that can be used as _tessellation control shader_. This is enforced by the
  /// fact only this method authorized to build a tessellation control [`Shader`] by using the [`TessCtrlShaderEnv`]
  /// argument passed to the input closure.
  ///
  /// That closure takes as first argument a mutable reference on a [`ShaderBuilder`] and a [`TessCtrlShaderEnv`] as
  /// second argument. The [`TessCtrlShaderEnv`] allows you to access to tessellation control attributes found in any
  /// invocation of a tessellation control shader. Those are expressions (read-only) and variables (read-write) valid
  /// only in tessellation control shaders.
  ///
  /// # Return
  ///
  /// This method returns the fully built [`Shader`], which cannot be mutated anymore once it has been built,
  /// and can be passed to various [`writers`](crate::writer) to generate actual code for target shading languages.
  ///
  /// # Examples
  ///
  /// ```
  /// use shades::{Scope, ShaderBuilder, V3, vec4};
  ///
  /// let tess_ctrl_shader = ShaderBuilder::new_tess_ctrl_shader(|mut s, patch| {
  ///   s.main_fun(|s: &mut Scope<()>| {
  ///     s.set(patch.tess_level_outer.at(0), 0.1);
  ///   })
  /// });
  /// ```
  pub fn new_tess_ctrl_shader(f: impl FnOnce(Self, TessCtrlShaderEnv) -> Shader) -> Shader {
    f(Self::new(), TessCtrlShaderEnv::new())
  }

  /// Create a new _tessellation evaluation shader_.
  ///
  /// This method creates a [`Shader`] that can be used as _tessellation evaluation shader_. This is enforced by the
  /// fact only this method authorized to build a tessellation evaluation [`Shader`] by using the [`TessEvalShaderEnv`]
  /// argument passed to the input closure.
  ///
  /// That closure takes as first argument a mutable reference on a [`ShaderBuilder`] and a [`TessEvalShaderEnv`] as
  /// second argument. The [`TessEvalShaderEnv`] allows you to access to tessellation evaluation attributes found in
  /// any invocation of a tessellation evaluation shader. Those are expressions (read-only) and variables (read-write)
  /// valid only in tessellation evaluation shaders.
  ///
  /// # Return
  ///
  /// This method returns the fully built [`Shader`], which cannot be mutated anymore once it has been built,
  /// and can be passed to various [`writers`](crate::writer) to generate actual code for target shading languages.
  ///
  /// # Examples
  ///
  /// ```
  /// use shades::{Scope, ShaderBuilder, V3, inputs, vec4};
  ///
  /// let tess_eval_shader = ShaderBuilder::new_tess_eval_shader(|mut s, patch| {
  ///   inputs!(s, position: V3<f32>);
  ///
  ///   s.main_fun(|s: &mut Scope<()>| {
  ///     s.set(patch.position, vec4!(position, 1.));
  ///   })
  /// });
  /// ```
  pub fn new_tess_eval_shader(f: impl FnOnce(Self, TessEvalShaderEnv) -> Shader) -> Shader {
    f(Self::new(), TessEvalShaderEnv::new())
  }

  /// Create a new _geometry shader_.
  ///
  /// This method creates a [`Shader`] that can be used as _geometry shader_. This is enforced by the fact only this
  /// method authorized to build a geometry [`Shader`] by using the [`GeometryShaderEnv`] argument passed to the input
  /// closure.
  ///
  /// That closure takes as first argument a mutable reference on a [`ShaderBuilder`] and a [`GeometryShaderEnv`] as
  /// second argument. The [`GeometryShaderEnv`] allows you to access to geometry attributes found in any invocation of
  /// a geometry shader. Those are expressions (read-only) and variables (read-write) valid only in geometry shaders.
  ///
  /// # Return
  ///
  /// This method returns the fully built [`Shader`], which cannot be mutated anymore once it has been built,
  /// and can be passed to various [`writers`](crate::writer) to generate actual code for target shading languages.
  ///
  /// # Examples
  ///
  /// ```
  /// use shades::{LoopScope, Scope, ShaderBuilder, V3, vec4};
  ///
  /// let geo_shader = ShaderBuilder::new_geometry_shader(|mut s, vertex| {
  ///   s.main_fun(|s: &mut Scope<()>| {
  ///     s.loop_for(0, |i| i.lt(3), |i| i + 1, |s: &mut LoopScope<()>, i| {
  ///       s.set(vertex.position, vertex.input.at(i).position());
  ///     });
  ///   })
  /// });
  /// ```
  pub fn new_geometry_shader(f: impl FnOnce(Self, GeometryShaderEnv) -> Shader) -> Shader {
    f(Self::new(), GeometryShaderEnv::new())
  }

  /// Create a new _fragment shader_.
  ///
  /// This method creates a [`Shader`] that can be used as _fragment shader_. This is enforced by the fact only this
  /// method authorized to build a [`ShaderBuilder`] by using the [`FragmentShaderEnv`] argument passed to the input
  /// closure.
  ///
  /// That closure takes as first argument a mutable reference on a [`ShaderBuilder`] and a [`FragmentShaderEnv`] as
  /// second argument. The [`FragmentShaderEnv`] allows you to access to fragment attributes found in any invocation of
  /// a fragment shader. Those are expressions (read-only) and variables (read-write) valid only in fragment shaders.
  ///
  /// # Return
  ///
  /// This method returns the fully built [`Shader`], which cannot be mutated anymore once it has been built,
  /// and can be passed to various [`writers`](crate::writer) to generate actual code for target shading languages.
  ///
  /// # Examples
  ///
  /// ```
  /// use shades::{Geometry as _, Scope, ShaderBuilder, V4, outputs, vec4};
  ///
  /// let geo_shader = ShaderBuilder::new_fragment_shader(|mut s, fragment| {
  ///   outputs!(s, color: V4<f32>);
  ///
  ///   s.main_fun(|s: &mut Scope<()>| {
  ///     s.set(color, fragment.frag_coord.normalize());
  ///   })
  /// });
  /// ```
  pub fn new_fragment_shader(f: impl FnOnce(Self, FragmentShaderEnv) -> Shader) -> Shader {
    f(Self::new(), FragmentShaderEnv::new())
  }

  /// Create a new empty shader.
  fn new() -> Self {
    Self {
      decls: Vec::new(),
      next_fun_handle: 0,
      next_global_handle: 0,
    }
  }

  /// Create a new function in the shader and get its handle for future use.
  ///
  /// This method requires to pass a closure encoding the argument(s) and return type of the function to create. The
  /// closure’s body encodes the body of the function to create. The number of arguments will directly impact the
  /// number of arguments the created function will have. The return type can be [`()`](unit) if the function doesn’t
  /// return anything or [`Expr<T>`] if it does return something.
  ///
  /// The first argument of the closure is a mutable reference on a [`Scope`]. Its type parameter must be set to the
  /// return type. The scope allows you to add instructions to the function body of the generated function. As in
  /// vanilla Rust, the last expression in a function is assumed as return value, if the function returns a value.
  /// However, unlike Rust, if your function returns something, it **cannot `return` it: it has to use the
  /// expression-as-last-instruction syntax**. It means that even if you don’t use the [`Scope`] within the last
  /// expression of your function body, the returned expression will still be part of the function as special returned
  /// expression:
  ///
  /// ```
  /// # use shades::ShaderBuilder;
  /// # ShaderBuilder::new_vertex_shader(|mut s, vertex| {
  /// use shades::{Expr, Scope};
  ///
  /// let f = s.fun(|s: &mut Scope<Expr<f32>>, a: Expr<f32>| a + 1.);
  /// # s.main_fun(|s: &mut Scope<()>| {})
  /// # });
  /// ```
  ///
  /// However, as mentioned above, you cannot `return` the last expression (`leave`), as this is not accepted by the
  /// EDSL:
  ///
  /// ```compile_fail
  /// # use shades::ShaderBuilder;
  /// # ShaderBuilder::new_vertex_shader(|mut s, vertex| {
  /// use shades::{Expr, Scope};
  ///
  /// let f = s.fun(|s: &mut Scope<Expr<f32>>, a: Expr<f32>| {
  ///   s.leave(a + 1.);
  /// });
  /// # s.main_fun(|s: &mut Scope<()>| {})
  /// # });
  /// ```
  ///
  /// Please refer to the [`Scope`] documentation for a complete list of the instructions you can record.
  ///
  /// # Caveats
  ///
  /// On a last note, you can still use the `return` keyword from Rust, but it is highly discouraged, as returning with
  /// `return` cannot be captured by the EDSL. It means that you will not get the shader code you expect.
  ///
  /// ```
  /// # use shades::{Expr, Scope, ShaderBuilder};
  /// # ShaderBuilder::new_vertex_shader(|mut s, vertex| {
  /// use shades::{Expr, Scope};
  ///
  /// let f = s.fun(|s: &mut Scope<Expr<f32>>, a: Expr<f32>| {
  ///   return a + 1.;
  /// });
  /// # s.main_fun(|s: &mut Scope<()>| {})
  /// # });
  /// ```
  ///
  /// An example of a broken shader is when you use the Rust `return` keyword inside a conditional statement or looping
  /// statement:
  ///
  /// ```
  /// # use shades::ShaderBuilder;
  /// # ShaderBuilder::new_vertex_shader(|mut s, vertex| {
  /// use shades::{CanEscape as _, EscapeScope, Expr, Scope};
  ///
  /// // don’t do this.
  /// let f = s.fun(|s: &mut Scope<Expr<f32>>, a: Expr<f32>| {
  ///   s.when(a.lt(10.), |s: &mut EscapeScope<Expr<f32>>| {
  ///     // /!\ problem here /!\
  ///     return;
  ///   });
  ///
  ///   a + 1.
  /// });
  /// # s.main_fun(|s: &mut Scope<()>| {})
  /// # });
  /// ```
  ///
  /// This snippet will create a GLSL function testing whether its `a` argument is less than `10.` and if it’s the case,
  /// does nothing inside of it (the `return` is not captured by the EDSL).
  ///
  /// # Return
  ///
  /// This method returns a _function handle_, [`FunHandle<R, A>`], where `R` is the return type and `A` the argument
  /// list of the function. This handle can be used in various positions in the EDSL but the most interesting place is
  /// in [`Expr<T>`] and [`Var<T>`], when calling the function to, respectively, combine it with other expressions or
  /// assign it to a variable.
  ///
  /// ## Nightly-only: call syntax
  ///
  /// On the current version of stable `rustc` (1.49), it is not possible to use a [`FunHandle<R, A>`] as you would use
  /// a normal Rust function: you have to use the [`FunHandle::call`] method, which is not really elegant nor ergonomic.
  ///
  /// To fix this problem, enable the `fun-call` feature gate.
  ///
  /// # Examples
  ///
  /// ```
  /// use shades::{Exponential as _, Expr, Scope, ShaderBuilder, lit};
  ///
  /// let shader = ShaderBuilder::new_vertex_shader(|mut s, vertex| {
  ///   // create a function taking a floating-point number and returning its square
  ///   let square = s.fun(|s: &mut Scope<Expr<f32>>, a: Expr<f32>| {
  ///     a.pow(2.)
  ///   });
  ///
  ///   // `square` can now be used to square floats!
  ///   s.main_fun(|s: &mut Scope<()>| {
  ///     // if you use the nightly compiler
  /// #   #[cfg(feature = "fun-call")]
  ///     let nine = s.var(square(lit!(3.)));
  ///
  ///     // if you’d rather use stable
  ///     let nine = s.var(square.call(lit!(3.)));
  ///   })
  /// });
  /// ```
  pub fn fun<F, R, A>(&mut self, f: F) -> FunHandle<R, A>
  where
    F: ToFun<R, A>,
  {
    let fundef = f.build_fn();
    let handle = self.next_fun_handle;
    self.next_fun_handle += 1;

    self.decls.push(ShaderDecl::FunDef(handle, fundef.erased));

    FunHandle {
      erased: ErasedFunHandle::UserDefined(handle as _),
      _phantom: PhantomData,
    }
  }

  /// Declare the `main` function of the shader stage.
  ///
  /// This method is very similar to [`ShaderBuilder::fun`] in the sense it declares a function. However, it declares the special
  /// `main` entry-point of a shader stage, which doesn’t have have argument and returns nothing, and is the only
  /// way to finalize the building of a [`Shader`].
  ///
  /// The input closure must take a single argument: a mutable reference on a `Scope<()>`, as the `main` function
  /// cannot return anything.
  ///
  /// # Return
  ///
  /// The fully built [`Shader`], which cannot be altered anymore.
  ///
  /// # Examples
  ///
  /// ```
  /// use shades::{Scope, ShaderBuilder};
  ///
  /// let shader = ShaderBuilder::new_vertex_shader(|s, vertex| {
  ///   s.main_fun(|s: &mut Scope<()>| {
  ///     // …
  ///   })
  /// });
  /// ```
  pub fn main_fun<F, R>(mut self, f: F) -> Shader
  where
    F: ToFun<R, ()>,
  {
    let fundef = f.build_fn();

    self.decls.push(ShaderDecl::Main(fundef.erased));

    Shader { builder: self }
  }

  /// Declare a new constant, shared between all functions and constants that come next.
  ///
  /// The input argument is any object that can be transformed [`Into`] an [`Expr<T>`]. At this level in the
  /// shader, pretty much nothing but literals and other constants are accepted here.
  ///
  /// # Return
  ///
  /// An [`Expr<T>`] representing the constant passed as input.
  ///
  /// # Examples
  ///
  /// ```
  /// # use shades::{EscapeScope, Expr, Scope, ShaderBuilder, lit};
  /// # ShaderBuilder::new_vertex_shader(|mut s, vertex| {
  /// // don’t do this.
  /// let illum_coefficient: Expr<f32> = s.constant(10.);
  /// # s.main_fun(|s: &mut Scope<()>| {})
  /// # });
  /// ```
  pub fn constant<T>(&mut self, expr: impl Into<Expr<T>>) -> Expr<T>
  where
    T: ToType,
  {
    let handle = self.next_global_handle;
    self.next_global_handle += 1;

    self
      .decls
      .push(ShaderDecl::Const(handle, T::ty(), expr.into().erased));

    Expr::new(ErasedExpr::Var(ScopedHandle::global(handle)))
  }

  /// Declare a new input, shared between all functions and constants that come next.
  ///
  /// TODO
  pub unsafe fn input<T>(&mut self, name: &str) -> Var<T>
  where
    T: ToType,
  {
    let name = name.to_owned();
    self.decls.push(ShaderDecl::In(name.clone(), T::ty()));
    Var::new(ScopedHandle::Input(name))
  }

  /// TODO
  pub unsafe fn output<T>(&mut self, name: &str) -> Var<T>
  where
    T: ToType,
  {
    let name = name.to_owned();
    self.decls.push(ShaderDecl::Out(name.clone(), T::ty()));
    Var::new(ScopedHandle::Output(name))
  }

  pub unsafe fn uniform<T>(&mut self, name: &str) -> Var<T>
  where
    T: ToType,
  {
    let name = name.to_owned();
    self.decls.push(ShaderDecl::Uniform(name.clone(), T::ty()));
    Var::new(ScopedHandle::uniform(name))
  }
}

/// Shader declaration.
///
/// This contain everything that can be declared at top-level of a shader.
#[derive(Debug)]
pub(crate) enum ShaderDecl {
  /// The `main` function declaration. The [`ErasedFun`] is a function that returns nothing and has no argument.
  Main(ErasedFun),

  /// A function definition.
  ///
  /// The [`u16`] represents the _handle_ of the function, and is unique for each shader stage. The [`ErasedFun`] is
  /// the representation of the function definition.
  FunDef(u16, ErasedFun),

  /// A constant definition.
  ///
  /// The [`u16`] represents the _handle_ of the constant, and is unique for each shader stage. The [`Type`] is the
  /// the type of the constant expression. [`ErasedExpr`] is the representation of the constant.
  Const(u16, Type, ErasedExpr),

  /// An input definition.
  ///
  /// The [`u16`] represents the _handle_ of the input, and is unique for each shader stage. The [`Type`] is the
  /// the type of the input.
  In(String, Type),

  /// An output definition.
  ///
  /// The [`u16`] represents the _handle_ of the output, and is unique for each shader stage. The [`Type`] is the
  /// the type of the output.
  Out(String, Type),

  /// A uniform definition.
  Uniform(String, Type),
}

macro_rules! make_vn {
  ($t:ident, $dim:expr) => {
    /// Scalar vectors.
    ///
    /// Scalar vectors come into three flavors, based on the dimension used:
    ///
    /// - Two dimensions (2D): [`V2<T>`].
    /// - Three dimensions (3D): [`V3<T>`].
    /// - Four dimensions (4D): [`V4<T>`].
    ///
    /// Each type implements the [`From`] trait for sized array. For instance, if you want to make a `V3<f32>` from
    /// constants / literals, you can simply use the implementor `From<[f32; 3]> for V3<f32>`.
    ///
    /// A builder macro version exists for each flavor:
    ///
    /// - [`vec2`]: build [`V2<T>`].
    /// - [`vec3`]: build [`V3<T>`].
    /// - [`vec4`]: build [`V4<T>`].
    ///
    /// Those three macros can also be used with literals.
    #[derive(Clone, Debug, PartialEq)]
    pub struct $t<T>([T; $dim]);

    impl<T> From<[T; $dim]> for $t<T> {
      fn from(a: [T; $dim]) -> Self {
        Self(a)
      }
    }
  };
}

make_vn!(V2, 2);
make_vn!(V3, 3);
make_vn!(V4, 4);

/// Representation of an expression.
#[derive(Clone, Debug, PartialEq)]
enum ErasedExpr {
  // scalars
  LitInt(i32),
  LitUInt(u32),
  LitFloat(f32),
  LitBool(bool),
  // vectors
  LitInt2([i32; 2]),
  LitUInt2([u32; 2]),
  LitFloat2([f32; 2]),
  LitBool2([bool; 2]),
  LitInt3([i32; 3]),
  LitUInt3([u32; 3]),
  LitFloat3([f32; 3]),
  LitBool3([bool; 3]),
  LitInt4([i32; 4]),
  LitUInt4([u32; 4]),
  LitFloat4([f32; 4]),
  LitBool4([bool; 4]),
  // matrices
  LitM22(M22),
  // LitM23(M23),
  // LitM24(M24),
  // LitM32(M32),
  LitM33(M33),
  // LitM34(M34),
  // LitM42(M42),
  // LitM43(M43),
  LitM44(M44),
  // arrays
  Array(Type, Vec<ErasedExpr>),
  // var
  Var(ScopedHandle),
  // built-in functions and operators
  Not(Box<Self>),
  And(Box<Self>, Box<Self>),
  Or(Box<Self>, Box<Self>),
  Xor(Box<Self>, Box<Self>),
  BitOr(Box<Self>, Box<Self>),
  BitAnd(Box<Self>, Box<Self>),
  BitXor(Box<Self>, Box<Self>),
  Neg(Box<Self>),
  Add(Box<Self>, Box<Self>),
  Sub(Box<Self>, Box<Self>),
  Mul(Box<Self>, Box<Self>),
  Div(Box<Self>, Box<Self>),
  Rem(Box<Self>, Box<Self>),
  Shl(Box<Self>, Box<Self>),
  Shr(Box<Self>, Box<Self>),
  Eq(Box<Self>, Box<Self>),
  Neq(Box<Self>, Box<Self>),
  Lt(Box<Self>, Box<Self>),
  Lte(Box<Self>, Box<Self>),
  Gt(Box<Self>, Box<Self>),
  Gte(Box<Self>, Box<Self>),
  // function call
  FunCall(ErasedFunHandle, Vec<Self>),
  // swizzle
  Swizzle(Box<Self>, Swizzle),
  // field expression, as in a struct Foo { float x; }, foo.x is an Expr representing the x field on object foo
  Field { object: Box<Self>, field: Box<Self> },
  ArrayLookup { object: Box<Self>, index: Box<Self> },
}

impl ErasedExpr {
  const fn new_builtin(builtin: BuiltIn) -> Self {
    ErasedExpr::Var(ScopedHandle::builtin(builtin))
  }
}

/// Expression representation.
///
/// An expression is anything that carries a (typed) value and that can be combined in various ways with other
/// expressions. A literal, a constant or a variable are all expressions. The sum (as in `a + b`) of two expressions is
/// also an expression. A function call returning an expression is also an expression, as in `a * sin(b)`. Accessing an
/// element in an array (which is an expression as it carries items) via an index (an expression) is also an
/// expression — e.g. `levels[y * HEIGHT + x] * size`. The same thing applies to field access, swizzling, etc. etc.
///
/// On a general note, expressions are pretty central to the EDSL, as they are the _lower level concept_ you will be
/// able to manipulate. Expressions are side effect free, so a variable, for instance, can either be considered as an
/// expression or not. If `x` is a variable (see [`Var`]), then `x * 10` is an expression, but using `x` to mutate its
/// content does not make a use of `x` as an expression. It means that expressions are read-only and even though you
/// can go from higher constructs (like variables) to expressions, the opposite direction is forbidden.
///
/// # Literals
///
/// The most obvious kind of expression is a literal — e.g. `1`, `false`, `3.14`, etc. Any type `T` that defines an
/// implementor `From<T> for Expr<T>` can be used as literal. You can then use, for instance, `1.into()`,
/// `Expr::from(1)`, etc.
///
/// A much better and easier way to create literals is to use the [`lit!`](lit) macro, which basically does the lifting
/// for you, but also accept more forms to create more complex literals, such as scalar vectors. See its documentation
/// for further details.
///
/// It’s important to notice that because of how Rust infers type, type ambiguities might occur when using literals —
/// hence, the use of [`lit!`](lit) should help. For instance, in `1 + 2`, the type of `1` is ambiguous because of how
/// the implementors for [`Add`](std::ops::Add) are picked. In such a case, you are advised to use [`lit!`](lit).
///
/// ## Automatic lifting
///
/// Sometimes, you will want to pass literals to form other expressions, function calls, etc. Most of the API has been
/// written in a way that if no ambiguity would occur, then you can use the Rust type directly. For instance, if `x`
/// has the type `Expr<i32>`, then `x + 1` is the same as `x + lit!(1)`. You can use this property with literals too:
/// `lit!(1) + 2 + 3 + 4`.
///
/// That automatic lifting is valid for a lot of traits and methods throughout this crate.
///
/// # Expressions from side-effects
///
/// Some side-effects will create expressions, such as creating a variable or a constant. Most of the time, you
/// shouldn’t have to worry about the type of the expression as it should be inferred based on the side-effect.
///
/// # Expression macros
///
/// Some macros will create expressions for you, such as [`lit!`](lit), [`vec2!`](vec2), [`vec3!`](vec3) and
/// [`vec4!`](vec4) or the [`sw!`](sw) macros. Most of the time, those macros will work by automatically adding a
/// reference (`&`) to their arguments so that you don’t have to worry about that either.
#[derive(Debug)]
pub struct Expr<T>
where
  T: ?Sized,
{
  erased: ErasedExpr,
  _phantom: PhantomData<T>,
}

impl<T> From<&'_ Self> for Expr<T>
where
  T: ?Sized,
{
  fn from(e: &Self) -> Self {
    Self::new(e.erased.clone())
  }
}

impl<T> Clone for Expr<T>
where
  T: ?Sized,
{
  fn clone(&self) -> Self {
    Self::new(self.erased.clone())
  }
}

impl<T> Expr<T>
where
  T: ?Sized,
{
  /// Type an [`ErasedExpr`] and return it wrapped in [`Expr<T>`].
  const fn new(erased: ErasedExpr) -> Self {
    Self {
      erased,
      _phantom: PhantomData,
    }
  }

  /// Equality expression.
  ///
  /// This method builds an expression representing the equality between two expressions.
  ///
  /// # Return
  ///
  /// An [`Expr<bool>`] representing the equality between the two input expressions.
  ///
  /// # Examples
  ///
  /// ```
  /// # use shades::{Scope, ShaderBuilder};
  /// # ShaderBuilder::new_vertex_shader(|mut s, vertex| {
  /// use shades::{lit, vec2};
  ///
  /// let _ = lit!(1).eq(1); // 1 == 1;
  /// let _ = vec2!(1., 2.).eq(vec2!(0., 0.)); // vec2(1., 2.) == vec2(0., 0.)
  /// # s.main_fun(|s: &mut Scope<()>| {})
  /// # });
  /// ```
  pub fn eq(&self, rhs: impl Into<Expr<T>>) -> Expr<bool> {
    Expr::new(ErasedExpr::Eq(
      Box::new(self.erased.clone()),
      Box::new(rhs.into().erased),
    ))
  }

  /// Inequality expression.
  ///
  /// This method builds an expression representing the inequality between two expressions.
  ///
  /// # Return
  ///
  /// An [`Expr<bool>`] representing the inequality between the two input expressions.
  ///
  /// # Examples
  ///
  /// ```
  /// # use shades::{Scope, ShaderBuilder};
  /// # ShaderBuilder::new_vertex_shader(|mut s, vertex| {
  /// use shades::{lit, vec2};
  ///
  /// let _ = lit!(1).neq(1); // 1 != 1;
  /// let _ = vec2!(1., 2.).eq(vec2!(0., 0.)); // vec2(1., 2.) != vec2(0., 0.)
  /// # s.main_fun(|s: &mut Scope<()>| {})
  /// # });
  /// ```
  pub fn neq(&self, rhs: impl Into<Expr<T>>) -> Expr<bool> {
    Expr::new(ErasedExpr::Neq(
      Box::new(self.erased.clone()),
      Box::new(rhs.into().erased),
    ))
  }
}

/// Trait allowing to create 2D scalar vector ([`V2`])constructors.
/// 2D scalar vectors can be created from either two sole scalars or a single 2D scalar vector (identity function).
///
///
/// The `A` type variable represents the arguments type. In the case of several arguments, tuples are used.
///
/// You are advised to use the [`vec2!`](vec2) macro instead as the interface of this function is not really
/// user-friendly.
pub trait Vec2<A> {
  /// Make a [`V2`] from `A`.
  fn vec2(args: A) -> Self;
}

impl<T> Vec2<(Expr<T>, Expr<T>)> for Expr<V2<T>> {
  fn vec2(args: (Expr<T>, Expr<T>)) -> Self {
    let (x, y) = args;
    Expr::new(ErasedExpr::FunCall(
      ErasedFunHandle::Vec2,
      vec![x.erased, y.erased],
    ))
  }
}

/// Trait allowing to create 3D scalar vector ([`V3`])constructors.
///
/// 3D scalar vectors can be created from either three sole scalars, a single 2D scalar vector with a single scalar or
/// a single 3D scalar vector (identity function).
///
/// The `A` type variable represents the arguments type. In the case of several arguments, tuples are used.
///
/// You are advised to use the [`vec3!`](vec3) macro instead as the interface of this function is not really
/// user-friendly.
pub trait Vec3<A> {
  /// Make a [`V3`] from `A`.
  fn vec3(args: A) -> Self;
}

impl<T> Vec3<(Expr<V2<T>>, Expr<T>)> for Expr<V3<T>> {
  fn vec3(args: (Expr<V2<T>>, Expr<T>)) -> Self {
    let (xy, z) = args;
    Expr::new(ErasedExpr::FunCall(
      ErasedFunHandle::Vec3,
      vec![xy.erased, z.erased],
    ))
  }
}

impl<T> Vec3<(Expr<T>, Expr<T>, Expr<T>)> for Expr<V3<T>> {
  fn vec3(args: (Expr<T>, Expr<T>, Expr<T>)) -> Self {
    let (x, y, z) = args;
    Expr::new(ErasedExpr::FunCall(
      ErasedFunHandle::Vec3,
      vec![x.erased, y.erased, z.erased],
    ))
  }
}

/// Trait allowing to create 4D scalar vector ([`V4`])constructors.
///
/// 4D scalar vectors can be created from either four sole scalars, a single 3D scalar vector with a single scalar,
/// two 2D scalar vectors, a 2D scalar vector and a sole scalar or a single 4D scalar vector (identity function).
///
/// The `A` type variable represents the arguments type. In the case of several arguments, tuples are used.
///
/// You are advised to use the [`vec4!`](vec4) macro instead as the interface of this function is not really
/// user-friendly.
pub trait Vec4<A> {
  /// Make a [`V4`] from `A`.
  fn vec4(args: A) -> Self;
}

impl<T> Vec4<(Expr<V3<T>>, Expr<T>)> for Expr<V4<T>> {
  fn vec4(args: (Expr<V3<T>>, Expr<T>)) -> Self {
    let (xyz, w) = args;
    Expr::new(ErasedExpr::FunCall(
      ErasedFunHandle::Vec4,
      vec![xyz.erased, w.erased],
    ))
  }
}

impl<T> Vec4<(Expr<V2<T>>, Expr<V2<T>>)> for Expr<V4<T>> {
  fn vec4(args: (Expr<V2<T>>, Expr<V2<T>>)) -> Self {
    let (xy, zw) = args;
    Expr::new(ErasedExpr::FunCall(
      ErasedFunHandle::Vec4,
      vec![xy.erased, zw.erased],
    ))
  }
}

impl<'a, T> Vec4<(Expr<V2<T>>, Expr<T>, Expr<T>)> for Expr<V4<T>> {
  fn vec4(args: (Expr<V2<T>>, Expr<T>, Expr<T>)) -> Self {
    let (xy, z, w) = args;
    Expr::new(ErasedExpr::FunCall(
      ErasedFunHandle::Vec4,
      vec![xy.erased, z.erased, w.erased],
    ))
  }
}

impl<'a, T> Vec4<(Expr<T>, Expr<T>, Expr<T>, Expr<T>)> for Expr<V4<T>> {
  fn vec4(args: (Expr<T>, Expr<T>, Expr<T>, Expr<T>)) -> Self {
    let (x, y, z, w) = args;
    Expr::new(ErasedExpr::FunCall(
      ErasedFunHandle::Vec4,
      vec![x.erased, y.erased, z.erased, w.erased],
    ))
  }
}

impl<T> Expr<T>
where
  T: PartialOrd,
{
  /// Less-than expression.
  ///
  /// This method builds an expression representing the binary operation `a < b`.
  ///
  /// # Return
  ///
  /// An [`Expr<bool>`] representing `a < b`.
  ///
  /// # Examples
  ///
  /// ```
  /// # use shades::{Scope, ShaderBuilder};
  /// # ShaderBuilder::new_vertex_shader(|mut s, vertex| {
  /// use shades::lit;
  ///
  /// let _ = lit!(1).lt(2); // 1 < 2;
  /// # s.main_fun(|s: &mut Scope<()>| {})
  /// # });
  /// ```
  pub fn lt(&self, rhs: impl Into<Expr<T>>) -> Expr<bool> {
    Expr::new(ErasedExpr::Lt(
      Box::new(self.erased.clone()),
      Box::new(rhs.into().erased),
    ))
  }

  /// Less-than-or-equal expression.
  ///
  /// This method builds an expression representing the binary operation `a <= b`.
  ///
  /// # Return
  ///
  /// An [`Expr<bool>`] representing `a <= b`.
  ///
  /// # Examples
  ///
  /// ```
  /// # use shades::{Scope, ShaderBuilder};
  /// # ShaderBuilder::new_vertex_shader(|mut s, vertex| {
  /// use shades::lit;
  ///
  /// let _ = lit!(1).lte(2); // 1 <= 2;
  /// # s.main_fun(|s: &mut Scope<()>| {})
  /// # });
  /// ```
  pub fn lte(&self, rhs: impl Into<Expr<T>>) -> Expr<bool> {
    Expr::new(ErasedExpr::Lte(
      Box::new(self.erased.clone()),
      Box::new(rhs.into().erased),
    ))
  }

  /// Greater-than expression.
  ///
  /// This method builds an expression representing the binary operation `a > b`.
  ///
  /// # Return
  ///
  /// An [`Expr<bool>`] representing `a > b`.
  ///
  /// # Examples
  ///
  /// ```
  /// # use shades::{Scope, ShaderBuilder};
  /// # ShaderBuilder::new_vertex_shader(|mut s, vertex| {
  /// use shades::lit;
  ///
  /// let _ = lit!(1).gt(2); // 1 > 2;
  /// # s.main_fun(|s: &mut Scope<()>| {})
  /// # });
  /// ```
  pub fn gt(&self, rhs: impl Into<Expr<T>>) -> Expr<bool> {
    Expr::new(ErasedExpr::Gt(
      Box::new(self.erased.clone()),
      Box::new(rhs.into().erased),
    ))
  }

  /// Less-than-or-equal expression.
  ///
  /// This method builds an expression representing the binary operation `a <= b`.
  ///
  /// # Return
  ///
  /// An [`Expr<bool>`] representing `a <= b`.
  ///
  /// # Examples
  ///
  /// ```
  /// # use shades::{Scope, ShaderBuilder};
  /// # ShaderBuilder::new_vertex_shader(|mut s, vertex| {
  /// use shades::lit;
  ///
  /// let _ = lit!(1).lte(2); // 1 <= 2;
  /// # s.main_fun(|s: &mut Scope<()>| {})
  /// # });
  /// ```
  pub fn gte(&self, rhs: impl Into<Expr<T>>) -> Expr<bool> {
    Expr::new(ErasedExpr::Gte(
      Box::new(self.erased.clone()),
      Box::new(rhs.into().erased),
    ))
  }
}

impl Expr<bool> {
  /// Logical _and_ expression.
  ///
  /// This method builds an expression representing the logical operation `a AND b`.
  ///
  /// # Return
  ///
  /// An [`Expr<bool>`] representing `a AND b`.
  ///
  /// # Examples
  ///
  /// ```
  /// # use shades::{Scope, ShaderBuilder};
  /// # ShaderBuilder::new_vertex_shader(|mut s, vertex| {
  /// use shades::lit;
  ///
  /// let _ = lit!(true).and(false); // true && false
  /// # s.main_fun(|s: &mut Scope<()>| {})
  /// # });
  /// ```
  pub fn and(&self, rhs: impl Into<Expr<bool>>) -> Expr<bool> {
    Expr::new(ErasedExpr::And(
      Box::new(self.erased.clone()),
      Box::new(rhs.into().erased),
    ))
  }

  /// Logical _or_ expression.
  ///
  /// This method builds an expression representing the logical operation `a OR b`.
  ///
  /// # Return
  ///
  /// An [`Expr<bool>`] representing `a OR b`.
  ///
  /// # Examples
  ///
  /// ```
  /// # use shades::{Scope, ShaderBuilder};
  /// # ShaderBuilder::new_vertex_shader(|mut s, vertex| {
  /// use shades::lit;
  ///
  /// let _ = lit!(true).or(false); // true || false
  /// # s.main_fun(|s: &mut Scope<()>| {})
  /// # });
  /// ```
  pub fn or(&self, rhs: impl Into<Expr<bool>>) -> Expr<bool> {
    Expr::new(ErasedExpr::Or(
      Box::new(self.erased.clone()),
      Box::new(rhs.into().erased),
    ))
  }

  /// Logical _exclusive or_ expression.
  ///
  /// This method builds an expression representing the logical operation `a XOR b`.
  ///
  /// # Return
  ///
  /// An [`Expr<bool>`] representing `a XOR b`.
  ///
  /// # Examples
  ///
  /// ```
  /// # use shades::{Scope, ShaderBuilder};
  /// # ShaderBuilder::new_vertex_shader(|mut s, vertex| {
  /// use shades::lit;
  ///
  /// let _ = lit!(true).xor(false); // true ^^ false
  /// # s.main_fun(|s: &mut Scope<()>| {})
  /// # });
  /// ```
  pub fn xor(&self, rhs: impl Into<Expr<bool>>) -> Expr<bool> {
    Expr::new(ErasedExpr::Xor(
      Box::new(self.erased.clone()),
      Box::new(rhs.into().erased),
    ))
  }
}

impl<T> Expr<[T]> {
  /// Array lookup.
  ///
  /// The expression `a.at(i)` represents an _array lookup_, where `a` is an array — which type must be either
  /// [`Expr<[T]>`](Expr) or [`Expr<[T; N]>`](Expr) – and `i` is an [`Expr<i32>`].
  ///
  /// # Return
  ///
  /// The resulting [`Expr<T>`] represents the array lookup in `a` at index `i`.
  ///
  /// # Examples
  ///
  /// ```
  /// # use shades::{Scope, ShaderBuilder};
  /// # ShaderBuilder::new_vertex_shader(|mut s, vertex| {
  /// use shades::lit;
  ///
  /// let _ = lit!([1, 2, 3]).at(2); // [1, 2, 3][2]
  /// # s.main_fun(|s: &mut Scope<()>| {})
  /// # });
  /// ```
  pub fn at(&self, index: impl Into<Expr<i32>>) -> Expr<T> {
    Expr::new(ErasedExpr::ArrayLookup {
      object: Box::new(self.erased.clone()),
      index: Box::new(index.into().erased),
    })
  }
}

impl<T, const N: usize> Expr<[T; N]> {
  /// Array lookup.
  ///
  /// The expression `a.at(i)` represents an _array lookup_, where `a` is an array — which type must be either
  /// [`Expr<[T]>`](Expr) or [`Expr<[T; N]>`](Expr) – and `i` is an [`Expr<i32>`].
  ///
  /// # Return
  ///
  /// The resulting [`Expr<T>`] represents the array lookup in `a` at index `i`.
  ///
  /// # Examples
  ///
  /// ```
  /// # use shades::{Scope, ShaderBuilder};
  /// # ShaderBuilder::new_vertex_shader(|mut s, vertex| {
  /// use shades::lit;
  ///
  /// let _ = lit!([1, 2, 3]).at(2); // [1, 2, 3][2]
  /// # s.main_fun(|s: &mut Scope<()>| {})
  /// # });
  /// ```
  pub fn at(&self, index: impl Into<Expr<i32>>) -> Expr<T> {
    Expr::new(ErasedExpr::ArrayLookup {
      object: Box::new(self.erased.clone()),
      index: Box::new(index.into().erased),
    })
  }
}

// not
macro_rules! impl_Not_Expr {
  ($t:ty) => {
    impl ops::Not for Expr<$t> {
      type Output = Self;

      fn not(self) -> Self::Output {
        Expr::new(ErasedExpr::Not(Box::new(self.erased)))
      }
    }

    impl<'a> ops::Not for &'a Expr<$t> {
      type Output = Expr<$t>;

      fn not(self) -> Self::Output {
        Expr::new(ErasedExpr::Not(Box::new(self.erased.clone())))
      }
    }
  };
}

impl_Not_Expr!(bool);
impl_Not_Expr!(V2<bool>);
impl_Not_Expr!(V3<bool>);
impl_Not_Expr!(V4<bool>);

// neg
macro_rules! impl_Neg_Expr {
  ($t:ty) => {
    impl ops::Neg for Expr<$t> {
      type Output = Self;

      fn neg(self) -> Self::Output {
        Expr::new(ErasedExpr::Neg(Box::new(self.erased)))
      }
    }

    impl<'a> ops::Neg for &'a Expr<$t> {
      type Output = Expr<$t>;

      fn neg(self) -> Self::Output {
        Expr::new(ErasedExpr::Neg(Box::new(self.erased.clone())))
      }
    }
  };
}

impl_Neg_Expr!(i32);
impl_Neg_Expr!(V2<i32>);
impl_Neg_Expr!(V3<i32>);
impl_Neg_Expr!(V4<i32>);

impl_Neg_Expr!(u32);
impl_Neg_Expr!(V2<u32>);
impl_Neg_Expr!(V3<u32>);
impl_Neg_Expr!(V4<u32>);

impl_Neg_Expr!(f32);
impl_Neg_Expr!(V2<f32>);
impl_Neg_Expr!(V3<f32>);
impl_Neg_Expr!(V4<f32>);

// binary arithmetic and logical (+, -, *, /, %)
// binop
macro_rules! impl_binop_Expr {
  ($op:ident, $meth_name:ident, $a:ty, $b:ty) => {
    impl_binop_Expr!($op, $meth_name, $a, $b, $a);
  };

  ($op:ident, $meth_name:ident, $a:ty, $b:ty, $r:ty) => {
    // expr OP expr
    impl<'a> ops::$op<Expr<$b>> for Expr<$a> {
      type Output = Expr<$r>;

      fn $meth_name(self, rhs: Expr<$b>) -> Self::Output {
        Expr::new(ErasedExpr::$op(Box::new(self.erased), Box::new(rhs.erased)))
      }
    }

    // var OP expr
    impl<'a> ops::$op<Expr<$b>> for Var<$a> {
      type Output = Expr<$r>;

      fn $meth_name(self, rhs: Expr<$b>) -> Self::Output {
        Expr::new(ErasedExpr::$op(
          Box::new(self.0.erased),
          Box::new(rhs.erased),
        ))
      }
    }

    // expr OP var
    impl<'a> ops::$op<Var<$b>> for Expr<$a> {
      type Output = Expr<$r>;

      fn $meth_name(self, rhs: Var<$b>) -> Self::Output {
        Expr::new(ErasedExpr::$op(
          Box::new(self.erased),
          Box::new(rhs.0.erased),
        ))
      }
    }

    // var OP var
    impl<'a> ops::$op<Var<$b>> for Var<$a> {
      type Output = Expr<$r>;

      fn $meth_name(self, rhs: Var<$b>) -> Self::Output {
        Expr::new(ErasedExpr::$op(
          Box::new(self.0.erased),
          Box::new(rhs.0.erased),
        ))
      }
    }

    // expr OP &expr
    impl<'a> ops::$op<&'a Expr<$b>> for Expr<$a> {
      type Output = Expr<$r>;

      fn $meth_name(self, rhs: &'a Expr<$b>) -> Self::Output {
        Expr::new(ErasedExpr::$op(
          Box::new(self.erased),
          Box::new(rhs.erased.clone()),
        ))
      }
    }

    // var OP &expr
    impl<'a> ops::$op<&'a Expr<$b>> for Var<$a> {
      type Output = Expr<$r>;

      fn $meth_name(self, rhs: &'a Expr<$b>) -> Self::Output {
        Expr::new(ErasedExpr::$op(
          Box::new(self.0.erased),
          Box::new(rhs.erased.clone()),
        ))
      }
    }

    // expr OP &var
    impl<'a> ops::$op<&'a Var<$b>> for Expr<$a> {
      type Output = Expr<$r>;

      fn $meth_name(self, rhs: &'a Var<$b>) -> Self::Output {
        Expr::new(ErasedExpr::$op(
          Box::new(self.erased),
          Box::new(rhs.0.erased.clone()),
        ))
      }
    }

    // var OP &var
    impl<'a> ops::$op<&'a Var<$b>> for Var<$a> {
      type Output = Expr<$r>;

      fn $meth_name(self, rhs: &'a Var<$b>) -> Self::Output {
        Expr::new(ErasedExpr::$op(
          Box::new(self.0.erased),
          Box::new(rhs.0.erased.clone()),
        ))
      }
    }

    // &expr OP expr
    impl<'a> ops::$op<Expr<$b>> for &'a Expr<$a> {
      type Output = Expr<$r>;

      fn $meth_name(self, rhs: Expr<$b>) -> Self::Output {
        Expr::new(ErasedExpr::$op(
          Box::new(self.erased.clone()),
          Box::new(rhs.erased),
        ))
      }
    }

    // &var OP expr
    impl<'a> ops::$op<Expr<$b>> for &'a Var<$a> {
      type Output = Expr<$r>;

      fn $meth_name(self, rhs: Expr<$b>) -> Self::Output {
        Expr::new(ErasedExpr::$op(
          Box::new(self.0.erased.clone()),
          Box::new(rhs.erased),
        ))
      }
    }

    // &expr OP var
    impl<'a> ops::$op<Var<$b>> for &'a Expr<$a> {
      type Output = Expr<$r>;

      fn $meth_name(self, rhs: Var<$b>) -> Self::Output {
        Expr::new(ErasedExpr::$op(
          Box::new(self.erased.clone()),
          Box::new(rhs.0.erased),
        ))
      }
    }

    // &var OP var
    impl<'a> ops::$op<Var<$b>> for &'a Var<$a> {
      type Output = Expr<$r>;

      fn $meth_name(self, rhs: Var<$b>) -> Self::Output {
        Expr::new(ErasedExpr::$op(
          Box::new(self.0.erased.clone()),
          Box::new(rhs.0.erased),
        ))
      }
    }

    // &expr OP &expr
    impl<'a> ops::$op<&'a Expr<$b>> for &'a Expr<$a> {
      type Output = Expr<$r>;

      fn $meth_name(self, rhs: &'a Expr<$b>) -> Self::Output {
        Expr::new(ErasedExpr::$op(
          Box::new(self.erased.clone()),
          Box::new(rhs.erased.clone()),
        ))
      }
    }

    // &var OP &expr
    impl<'a> ops::$op<&'a Expr<$b>> for &'a Var<$a> {
      type Output = Expr<$r>;

      fn $meth_name(self, rhs: &'a Expr<$b>) -> Self::Output {
        Expr::new(ErasedExpr::$op(
          Box::new(self.0.erased.clone()),
          Box::new(rhs.erased.clone()),
        ))
      }
    }

    // &expr OP &var
    impl<'a> ops::$op<&'a Var<$b>> for &'a Expr<$a> {
      type Output = Expr<$r>;

      fn $meth_name(self, rhs: &'a Var<$b>) -> Self::Output {
        Expr::new(ErasedExpr::$op(
          Box::new(self.erased.clone()),
          Box::new(rhs.0.erased.clone()),
        ))
      }
    }

    // &var OP &var
    impl<'a> ops::$op<&'a Var<$b>> for &'a Var<$a> {
      type Output = Expr<$r>;

      fn $meth_name(self, rhs: &'a Var<$b>) -> Self::Output {
        Expr::new(ErasedExpr::$op(
          Box::new(self.0.erased.clone()),
          Box::new(rhs.0.erased.clone()),
        ))
      }
    }

    // expr OP t, where t is automatically lifted
    impl<'a> ops::$op<$b> for Expr<$a> {
      type Output = Expr<$r>;

      fn $meth_name(self, rhs: $b) -> Self::Output {
        let rhs = Expr::from(rhs);
        Expr::new(ErasedExpr::$op(Box::new(self.erased), Box::new(rhs.erased)))
      }
    }

    // var OP t, where t is automatically lifted
    impl<'a> ops::$op<$b> for Var<$a> {
      type Output = Expr<$r>;

      fn $meth_name(self, rhs: $b) -> Self::Output {
        let rhs = Expr::from(rhs);
        Expr::new(ErasedExpr::$op(
          Box::new(self.0.erased),
          Box::new(rhs.erased),
        ))
      }
    }

    // &expr OP t, where t is automatically lifted
    impl<'a> ops::$op<$b> for &'a Expr<$a> {
      type Output = Expr<$r>;

      fn $meth_name(self, rhs: $b) -> Self::Output {
        let rhs: Expr<$b> = rhs.into();
        Expr::new(ErasedExpr::$op(
          Box::new(self.erased.clone()),
          Box::new(rhs.erased),
        ))
      }
    }

    // &var OP t, where t is automatically lifted
    impl<'a> ops::$op<$b> for &'a Var<$a> {
      type Output = Expr<$r>;

      fn $meth_name(self, rhs: $b) -> Self::Output {
        let rhs: Expr<$b> = rhs.into();
        Expr::new(ErasedExpr::$op(
          Box::new(self.0.erased.clone()),
          Box::new(rhs.erased),
        ))
      }
    }
  };
}

// or
impl_binop_Expr!(BitOr, bitor, bool, bool);
impl_binop_Expr!(BitOr, bitor, V2<bool>, V2<bool>);
impl_binop_Expr!(BitOr, bitor, V2<bool>, bool);
impl_binop_Expr!(BitOr, bitor, V3<bool>, V3<bool>);
impl_binop_Expr!(BitOr, bitor, V3<bool>, bool);
impl_binop_Expr!(BitOr, bitor, V4<bool>, V4<bool>);
impl_binop_Expr!(BitOr, bitor, V4<bool>, bool);

// and
impl_binop_Expr!(BitAnd, bitand, bool, bool);
impl_binop_Expr!(BitAnd, bitand, V2<bool>, V2<bool>);
impl_binop_Expr!(BitAnd, bitand, V2<bool>, bool);
impl_binop_Expr!(BitAnd, bitand, V3<bool>, V3<bool>);
impl_binop_Expr!(BitAnd, bitand, V3<bool>, bool);
impl_binop_Expr!(BitAnd, bitand, V4<bool>, V4<bool>);
impl_binop_Expr!(BitAnd, bitand, V4<bool>, bool);

// xor
impl_binop_Expr!(BitXor, bitxor, bool, bool);
impl_binop_Expr!(BitXor, bitxor, V2<bool>, V2<bool>);
impl_binop_Expr!(BitXor, bitxor, V2<bool>, bool);
impl_binop_Expr!(BitXor, bitxor, V3<bool>, V3<bool>);
impl_binop_Expr!(BitXor, bitxor, V3<bool>, bool);
impl_binop_Expr!(BitXor, bitxor, V4<bool>, V4<bool>);
impl_binop_Expr!(BitXor, bitxor, V4<bool>, bool);

/// Run a macro on all supported types to generate the impl for them
///
/// The macro has to have to take two `ty` as argument and yield a `std::ops` trait implementor.
macro_rules! impl_binarith_Expr {
  ($op:ident, $meth_name:ident) => {
    impl_binop_Expr!($op, $meth_name, i32, i32);
    impl_binop_Expr!($op, $meth_name, V2<i32>, V2<i32>);
    impl_binop_Expr!($op, $meth_name, V2<i32>, i32);
    impl_binop_Expr!($op, $meth_name, V3<i32>, V3<i32>);
    impl_binop_Expr!($op, $meth_name, V3<i32>, i32);
    impl_binop_Expr!($op, $meth_name, V4<i32>, V4<i32>);
    impl_binop_Expr!($op, $meth_name, V4<i32>, i32);

    impl_binop_Expr!($op, $meth_name, u32, u32);
    impl_binop_Expr!($op, $meth_name, V2<u32>, V2<u32>);
    impl_binop_Expr!($op, $meth_name, V2<u32>, u32);
    impl_binop_Expr!($op, $meth_name, V3<u32>, V3<u32>);
    impl_binop_Expr!($op, $meth_name, V3<u32>, u32);
    impl_binop_Expr!($op, $meth_name, V4<u32>, V4<u32>);
    impl_binop_Expr!($op, $meth_name, V4<u32>, u32);

    impl_binop_Expr!($op, $meth_name, f32, f32);
    impl_binop_Expr!($op, $meth_name, V2<f32>, V2<f32>);
    impl_binop_Expr!($op, $meth_name, V2<f32>, f32);
    impl_binop_Expr!($op, $meth_name, V3<f32>, V3<f32>);
    impl_binop_Expr!($op, $meth_name, V3<f32>, f32);
    impl_binop_Expr!($op, $meth_name, V4<f32>, V4<f32>);
    impl_binop_Expr!($op, $meth_name, V4<f32>, f32);
  };
}

impl_binarith_Expr!(Add, add);
impl_binarith_Expr!(Sub, sub);
impl_binarith_Expr!(Mul, mul);
impl_binarith_Expr!(Div, div);

impl_binop_Expr!(Rem, rem, f32, f32);
impl_binop_Expr!(Rem, rem, V2<f32>, V2<f32>);
impl_binop_Expr!(Rem, rem, V2<f32>, f32);
impl_binop_Expr!(Rem, rem, V3<f32>, V3<f32>);
impl_binop_Expr!(Rem, rem, V3<f32>, f32);
impl_binop_Expr!(Rem, rem, V4<f32>, V4<f32>);
impl_binop_Expr!(Rem, rem, V4<f32>, f32);

impl_binop_Expr!(Mul, mul, M22, M22);
impl_binop_Expr!(Mul, mul, M22, V2<f32>, V2<f32>);
impl_binop_Expr!(Mul, mul, V2<f32>, M22, M22);
impl_binop_Expr!(Mul, mul, M33, M33);
impl_binop_Expr!(Mul, mul, M33, V3<f32>, V3<f32>);
impl_binop_Expr!(Mul, mul, V3<f32>, M33, M33);
impl_binop_Expr!(Mul, mul, M44, M44);
impl_binop_Expr!(Mul, mul, M44, V4<f32>, V4<f32>);
impl_binop_Expr!(Mul, mul, V4<f32>, M44, M44);

macro_rules! impl_binshift_Expr {
  ($op:ident, $meth_name:ident, $ty:ty) => {
    // expr OP expr
    impl ops::$op<Expr<u32>> for Expr<$ty> {
      type Output = Expr<$ty>;

      fn $meth_name(self, rhs: Expr<u32>) -> Self::Output {
        Expr::new(ErasedExpr::$op(Box::new(self.erased), Box::new(rhs.erased)))
      }
    }

    impl<'a> ops::$op<Expr<u32>> for &'a Expr<$ty> {
      type Output = Expr<$ty>;

      fn $meth_name(self, rhs: Expr<u32>) -> Self::Output {
        Expr::new(ErasedExpr::$op(
          Box::new(self.erased.clone()),
          Box::new(rhs.erased),
        ))
      }
    }

    impl<'a> ops::$op<&'a Expr<u32>> for Expr<$ty> {
      type Output = Expr<$ty>;

      fn $meth_name(self, rhs: &'a Expr<u32>) -> Self::Output {
        Expr::new(ErasedExpr::$op(
          Box::new(self.erased),
          Box::new(rhs.erased.clone()),
        ))
      }
    }

    impl<'a> ops::$op<&'a Expr<u32>> for &'a Expr<$ty> {
      type Output = Expr<$ty>;

      fn $meth_name(self, rhs: &'a Expr<u32>) -> Self::Output {
        Expr::new(ErasedExpr::$op(
          Box::new(self.erased.clone()),
          Box::new(rhs.erased.clone()),
        ))
      }
    }

    // expr OP bits
    impl ops::$op<u32> for Expr<$ty> {
      type Output = Self;

      fn $meth_name(self, rhs: u32) -> Self::Output {
        let rhs = Expr::from(rhs);
        Expr::new(ErasedExpr::$op(Box::new(self.erased), Box::new(rhs.erased)))
      }
    }

    impl<'a> ops::$op<u32> for &'a Expr<$ty> {
      type Output = Expr<$ty>;

      fn $meth_name(self, rhs: u32) -> Self::Output {
        let rhs = Expr::from(rhs);
        Expr::new(ErasedExpr::$op(
          Box::new(self.erased.clone()),
          Box::new(rhs.erased),
        ))
      }
    }
  };
}

/// Binary shift generating macro.
macro_rules! impl_binshifts_Expr {
  ($op:ident, $meth_name:ident) => {
    impl_binshift_Expr!($op, $meth_name, i32);
    impl_binshift_Expr!($op, $meth_name, V2<i32>);
    impl_binshift_Expr!($op, $meth_name, V3<i32>);
    impl_binshift_Expr!($op, $meth_name, V4<i32>);

    impl_binshift_Expr!($op, $meth_name, u32);
    impl_binshift_Expr!($op, $meth_name, V2<u32>);
    impl_binshift_Expr!($op, $meth_name, V3<u32>);
    impl_binshift_Expr!($op, $meth_name, V4<u32>);

    impl_binshift_Expr!($op, $meth_name, f32);
    impl_binshift_Expr!($op, $meth_name, V2<f32>);
    impl_binshift_Expr!($op, $meth_name, V3<f32>);
    impl_binshift_Expr!($op, $meth_name, V4<f32>);
  };
}

impl_binshifts_Expr!(Shl, shl);
impl_binshifts_Expr!(Shr, shr);

macro_rules! impl_From_Expr_scalar {
  ($t:ty, $q:ident) => {
    impl From<$t> for Expr<$t> {
      fn from(a: $t) -> Self {
        Self::new(ErasedExpr::$q(a))
      }
    }

    impl<'a> From<&'a $t> for Expr<$t> {
      fn from(a: &'a $t) -> Self {
        Self::new(ErasedExpr::$q(*a))
      }
    }
  };
}

impl_From_Expr_scalar!(i32, LitInt);
impl_From_Expr_scalar!(u32, LitUInt);
impl_From_Expr_scalar!(f32, LitFloat);
impl_From_Expr_scalar!(bool, LitBool);

macro_rules! impl_From_Expr_vn {
  ($t:ty, $q:ident) => {
    impl From<$t> for Expr<$t> {
      fn from(a: $t) -> Self {
        Self::new(ErasedExpr::$q(a.0))
      }
    }

    impl<'a> From<&'a $t> for Expr<$t> {
      fn from(a: &'a $t) -> Self {
        Self::new(ErasedExpr::$q(a.0))
      }
    }
  };
}

impl_From_Expr_vn!(V2<i32>, LitInt2);
impl_From_Expr_vn!(V2<u32>, LitUInt2);
impl_From_Expr_vn!(V2<f32>, LitFloat2);
impl_From_Expr_vn!(V2<bool>, LitBool2);
impl_From_Expr_vn!(V3<i32>, LitInt3);
impl_From_Expr_vn!(V3<u32>, LitUInt3);
impl_From_Expr_vn!(V3<f32>, LitFloat3);
impl_From_Expr_vn!(V3<bool>, LitBool3);
impl_From_Expr_vn!(V4<i32>, LitInt4);
impl_From_Expr_vn!(V4<u32>, LitUInt4);
impl_From_Expr_vn!(V4<f32>, LitFloat4);
impl_From_Expr_vn!(V4<bool>, LitBool4);

impl<T, const N: usize> From<[T; N]> for Expr<[T; N]>
where
  Expr<T>: From<T>,
  T: Clone + ToType,
{
  fn from(array: [T; N]) -> Self {
    let array = array
      .iter()
      .cloned()
      .map(|t| Expr::from(t).erased)
      .collect();
    Self::new(ErasedExpr::Array(<[T; N] as ToType>::ty(), array))
  }
}

impl<'a, T, const N: usize> From<&'a [T; N]> for Expr<[T; N]>
where
  Expr<T>: From<T>,
  T: Clone + ToType,
{
  fn from(array: &'a [T; N]) -> Self {
    let array = array
      .iter()
      .cloned()
      .map(|t| Expr::from(t).erased)
      .collect();
    Self::new(ErasedExpr::Array(<[T; N] as ToType>::ty(), array))
  }
}

impl<T, const N: usize> From<[Expr<T>; N]> for Expr<[T; N]>
where
  Expr<T>: From<T>,
  T: ToType,
{
  fn from(array: [Expr<T>; N]) -> Self {
    let array = array.iter().cloned().map(|e| e.erased).collect();
    Self::new(ErasedExpr::Array(<[T; N] as ToType>::ty(), array))
  }
}

impl<'a, T, const N: usize> From<&'a [Expr<T>; N]> for Expr<[T; N]>
where
  Expr<T>: From<T>,
  T: ToType,
{
  fn from(array: &'a [Expr<T>; N]) -> Self {
    let array = array.iter().cloned().map(|e| e.erased).collect();
    Self::new(ErasedExpr::Array(<[T; N] as ToType>::ty(), array))
  }
}

/// Create various forms of literal expressions.
///
/// This macro allows you to create _literal expressions_ by lifting Rust constants into the EDSL. The way this is done
/// is via several forms:
///
/// - `lit!(x)` lifts a single Rust expression into the EDSL. It’s isomorphic to `Expr::from(x)`.
/// - `lit!(x, y)` lifts two Rust expressions into the EDSL as a 2D scalar vector. It’s isomorphic to
///   `Expr::from(V2::from([x, y]))`.
/// - `lit!(x, y, z)` lifts three Rust expressions into the EDSL as a 3D scalar vector. It’s isomorphic to
///   `Expr::from(V3::from([x, y, z]))`.
/// - `lit!(x, y, z, w)` lifts three Rust expressions into the EDSL as a 3D scalar vector. It’s isomorphic to
///   `Expr::from(V4::from([x, y, z, w]))`.
///
/// Most of the time, type inference will kick in and you shouldn’t have to annotate the return expression.
///
/// # Examples
///
/// ```
/// # use shades::{Scope, ShaderBuilder};
/// # ShaderBuilder::new_vertex_shader(|mut s, vertex| {
/// use shades::{lit};
///
/// let _ = lit!(1);
/// let _ = lit!(false);
/// let _ = lit!(1., 2., 3., 4.);
/// # s.main_fun(|s: &mut Scope<()>| {})
/// # });
/// ```
#[macro_export]
macro_rules! lit {
  ($e:expr) => {
    $crate::Expr::from($e)
  };

  ($a:expr, $b:expr) => {
    $crate::Expr::from(V2::from([$a, $b]))
  };

  ($a:expr, $b:expr, $c:expr) => {
    $crate::Expr::from($crate::V3::from([$a, $b, $c]))
  };

  ($a:expr, $b:expr, $c:expr, $d:expr) => {
    $crate::Expr::from($crate::V4::from([$a, $b, $c, $d]))
  };
}

/// Create 2D scalar vectors via different forms.
///
/// This macro allows to create 2D ([`V2`]) scalar vectors from two forms:
///
/// - `vec2!(xy)`, which acts as the cast operator. Only types `T` satisfying [`Vec2`] are castable.
/// - `vec2!(x, y)`, which builds a [`V2<T>`] for `x: T` and `y: T`.
///
/// # Examples
///
/// ```
/// # use shades::{Scope, ShaderBuilder};
/// # ShaderBuilder::new_vertex_shader(|mut s, vertex| {
/// use shades::vec2;
///
/// let _ = vec2!(1, 2);
/// # s.main_fun(|s: &mut Scope<()>| {})
/// # });
/// ```
#[macro_export]
macro_rules! vec2 {
  ($a:expr) => {
    todo!("vec2 cast operator missing");
  };

  ($xy:expr, $z:expr) => {{
    use $crate::Vec2 as _;
    $crate::Expr::vec2(($crate::Expr::from(&$xy), $crate::Expr::from(&$z)))
  }};
}

/// Create 3D scalar vectors via different forms.
///
/// This macro allows to create 3D ([`V3`]) scalar vectors from several forms:
///
/// - `vec3!(xyz)`, which acts as the cast operator. Only types `T` satisfying [`Vec3`] are castable.
/// - `vec3!(xy, z)`, which builds a [`V3<T>`] with `xy` a value that can be turned into a `Expr<V2<T>>` and `z: T`
/// - `vec3!(x, y, z)`, which builds a [`V3<T>`] for `x: T`, `y: T` and `z: T`.
///
/// # Examples
///
/// ```
/// # use shades::{Scope, ShaderBuilder};
/// # ShaderBuilder::new_vertex_shader(|mut s, vertex| {
/// use shades::{vec2, vec3};
///
/// let _ = vec3!(1, 2, 3);
/// let _ = vec3!(vec2!(1, 2), 3);
/// # s.main_fun(|s: &mut Scope<()>| {})
/// # });
/// ```
#[macro_export]
macro_rules! vec3 {
  ($a:expr) => {
    todo!("vec3 cast operator missing");
  };

  ($xy:expr, $z:expr) => {{
    use $crate::Vec3 as _;
    $crate::Expr::vec3(($crate::Expr::from(&$xy), $crate::Expr::from(&$z)))
  }};

  ($x:expr, $y:expr, $z:expr) => {{
    use $crate::Vec3 as _;
    $crate::Expr::vec3((
      $crate::Expr::from(&$x),
      $crate::Expr::from(&$y),
      $crate::Expr::from(&$z),
    ))
  }};
}

/// Create 4D scalar vectors via different forms.
///
/// This macro allows to create 4D ([`V4`]) scalar vectors from several forms:
///
/// - `vec4!(xyzw)`, which acts as the cast operator. Only types `T` satisfying [`Vec4`] are castable.
/// - `vec4!(xyz, w)`, which builds a [`V4<T>`] with `xyz` a value that can be turned into a `Expr<V3<T>>` and `w: T`.
/// - `vec4!(xy, zw)`, which builds a [`V4<T>`] with `xy` and `zw` values that can be turned into `Expr<V3<T>>`.
/// - `vec4!(xy, z, w)`, which builds a [`V4<T>`] with `xy`, `z: T` and `w: T`.
/// - `vec4!(x, y, z, w)`, which builds a [`V3<T>`] for `x: T`, `y: T` and `z: T`.
///
/// # Examples
///
/// ```
/// # use shades::{Scope, ShaderBuilder};
/// # ShaderBuilder::new_vertex_shader(|mut s, vertex| {
/// use shades::{vec2, vec3, vec4};
///
/// let _ = vec4!(1, 2, 3, 4);
/// let _ = vec4!(vec3!(1, 2, 3), 4);
/// let _ = vec4!(vec2!(1, 2), vec2!(3, 4));
/// let _ = vec4!(vec2!(1, 2), 3, 4);
/// # s.main_fun(|s: &mut Scope<()>| {})
/// # });
/// ```
#[macro_export]
macro_rules! vec4 {
  ($a:expr) => {
    todo!("vec4 cast operator missing");
  };

  ($xy:expr, $zw:expr) => {{
    use $crate::Vec4 as _;
    $crate::Expr::vec4(($crate::Expr::from(&$xy), $crate::Expr::from(&$zw)))
  }};

  ($xy:expr, $z:expr, $w:expr) => {{
    use $crate::Vec4 as _;
    $crate::Expr::vec4((
      $crate::Expr::from(&$xy),
      $crate::Expr::from(&$z),
      $crate::Expr::from(&$w),
    ))
  }};

  ($x:expr, $y:expr, $z:expr, $w:expr) => {{
    use $crate::Vec4 as _;
    $crate::Expr::vec4((
      $crate::Expr::from(&$x),
      $crate::Expr::from(&$y),
      $crate::Expr::from(&$z),
      $crate::Expr::from(&$w),
    ))
  }};
}

/// Function return.
///
/// This type represents a function return and is used to annotate values that can be returned from functions (i.e.
/// expressions).
#[derive(Clone, Debug, PartialEq)]
pub struct Return {
  erased: ErasedReturn,
}

/// Erased return.
///
/// Either `Void` (i.e. `void`) or an expression. The type of the expression is also present for convenience.
#[derive(Clone, Debug, PartialEq)]
enum ErasedReturn {
  Void,
  Expr(Type, ErasedExpr),
}

impl From<()> for Return {
  fn from(_: ()) -> Self {
    Return {
      erased: ErasedReturn::Void,
    }
  }
}

impl<T> From<Expr<T>> for Return
where
  T: ToType,
{
  fn from(expr: Expr<T>) -> Self {
    Return {
      erased: ErasedReturn::Expr(T::ty(), expr.erased),
    }
  }
}

/// Function definition injection.
///
/// This trait represents _function definition injection_, i.e. types that can provide a function definition — see
/// [`FunDef`]. Ideally, only a very small number of types can do this: polymorphic types implementing the [`FnOnce`]
/// trait with different number of arguments. Namely, closures / lambdas with various numbers of arguments.
///
/// You are not supposed to implement this type by yourself. Instead, when creating functions in the EDSL, you just have
/// to pass lambdas to automatically get the proper function definition lifted into the EDSL.
///
/// See the [`ShaderBuilder::fun`] for further information.
///
/// # Caveats
///
/// This way of doing currently comes with a price: type inference is bad. You will — most of the time — have to
/// annotate the closure’s arguments. This is currently working on but progress on that matter is slow.
pub trait ToFun<R, A> {
  fn build_fn(self) -> FunDef<R, A>;
}

impl<F, R> ToFun<R, ()> for F
where
  Self: FnOnce(&mut Scope<R>) -> R,
  Return: From<R>,
{
  fn build_fn(self) -> FunDef<R, ()> {
    let mut scope = Scope::new(0);
    let ret = self(&mut scope);

    let erased = ErasedFun::new(Vec::new(), scope.erased, Return::from(ret).erased);

    FunDef::new(erased)
  }
}

macro_rules! impl_ToFun_args {
  ($($arg:ident , $arg_ident:ident , $arg_rank:expr),*) => {
    impl<F, R, $($arg),*> ToFun<R, ($(Expr<$arg>),*)> for F
    where
      Self: FnOnce(&mut Scope<R>, $(Expr<$arg>),*) -> R,
      Return: From<R>,
      $($arg: ToType),*
    {
      fn build_fn(self) -> FunDef<R, ($(Expr<$arg>),*)> {
        $( let $arg_ident = Expr::new(ErasedExpr::Var(ScopedHandle::fun_arg($arg_rank))); )*
          let args = vec![$( $arg::ty() ),*];

        let mut scope = Scope::new(0);
        let ret = self(&mut scope, $($arg_ident),*);

        let erased = ErasedFun::new(args, scope.erased, Return::from(ret).erased);

        FunDef::new(erased)
      }
    }
  }
}

impl<F, R, A> ToFun<R, Expr<A>> for F
where
  Self: FnOnce(&mut Scope<R>, Expr<A>) -> R,
  Return: From<R>,
  A: ToType,
{
  fn build_fn(self) -> FunDef<R, Expr<A>> {
    let arg = Expr::new(ErasedExpr::Var(ScopedHandle::fun_arg(0)));

    let mut scope = Scope::new(0);
    let ret = self(&mut scope, arg);

    let erased = ErasedFun::new(vec![A::ty()], scope.erased, Return::from(ret).erased);

    FunDef::new(erased)
  }
}

impl_ToFun_args!(A0, a0, 0, A1, a1, 1);
impl_ToFun_args!(A0, a0, 0, A1, a1, 1, A2, a2, 2);
impl_ToFun_args!(A0, a0, 0, A1, a1, 1, A2, a2, 2, A3, a3, 3);
impl_ToFun_args!(A0, a0, 0, A1, a1, 1, A2, a2, 2, A3, a3, 3, A4, a4, 4);
impl_ToFun_args!(A0, a0, 0, A1, a1, 1, A2, a2, 2, A3, a3, 3, A4, a4, 4, A5, a5, 5);
impl_ToFun_args!(A0, a0, 0, A1, a1, 1, A2, a2, 2, A3, a3, 3, A4, a4, 4, A5, a5, 5, A6, a6, 6);
impl_ToFun_args!(
  A0, a0, 0, A1, a1, 1, A2, a2, 2, A3, a3, 3, A4, a4, 4, A5, a5, 5, A6, a6, 6, A7, a7, 7
);
impl_ToFun_args!(
  A0, a0, 0, A1, a1, 1, A2, a2, 2, A3, a3, 3, A4, a4, 4, A5, a5, 5, A6, a6, 6, A7, a7, 7, A8, a8, 8
);
impl_ToFun_args!(
  A0, a0, 0, A1, a1, 1, A2, a2, 2, A3, a3, 3, A4, a4, 4, A5, a5, 5, A6, a6, 6, A7, a7, 7, A8, a8,
  8, A9, a9, 9
);
impl_ToFun_args!(
  A0, a0, 0, A1, a1, 1, A2, a2, 2, A3, a3, 3, A4, a4, 4, A5, a5, 5, A6, a6, 6, A7, a7, 7, A8, a8,
  8, A9, a9, 9, A10, a10, 10
);
impl_ToFun_args!(
  A0, a0, 0, A1, a1, 1, A2, a2, 2, A3, a3, 3, A4, a4, 4, A5, a5, 5, A6, a6, 6, A7, a7, 7, A8, a8,
  8, A9, a9, 9, A10, a10, 10, A11, a11, 11
);
impl_ToFun_args!(
  A0, a0, 0, A1, a1, 1, A2, a2, 2, A3, a3, 3, A4, a4, 4, A5, a5, 5, A6, a6, 6, A7, a7, 7, A8, a8,
  8, A9, a9, 9, A10, a10, 10, A11, a11, 11, A12, a12, 12
);
impl_ToFun_args!(
  A0, a0, 0, A1, a1, 1, A2, a2, 2, A3, a3, 3, A4, a4, 4, A5, a5, 5, A6, a6, 6, A7, a7, 7, A8, a8,
  8, A9, a9, 9, A10, a10, 10, A11, a11, 11, A12, a12, 12, A13, a13, 13
);
impl_ToFun_args!(
  A0, a0, 0, A1, a1, 1, A2, a2, 2, A3, a3, 3, A4, a4, 4, A5, a5, 5, A6, a6, 6, A7, a7, 7, A8, a8,
  8, A9, a9, 9, A10, a10, 10, A11, a11, 11, A12, a12, 12, A13, a13, 13, A14, a14, 14
);
impl_ToFun_args!(
  A0, a0, 0, A1, a1, 1, A2, a2, 2, A3, a3, 3, A4, a4, 4, A5, a5, 5, A6, a6, 6, A7, a7, 7, A8, a8,
  8, A9, a9, 9, A10, a10, 10, A11, a11, 11, A12, a12, 12, A13, a13, 13, A14, a14, 14, A15, a15, 15
);
impl_ToFun_args!(
  A0, a0, 0, A1, a1, 1, A2, a2, 2, A3, a3, 3, A4, a4, 4, A5, a5, 5, A6, a6, 6, A7, a7, 7, A8, a8,
  8, A9, a9, 9, A10, a10, 10, A11, a11, 11, A12, a12, 12, A13, a13, 13, A14, a14, 14, A15, a15, 15,
  A16, a16, 16
);

/// An opaque function handle, used to call user-defined functions.
///
/// Function handles are created with the [`ShaderBuilder::fun`] function, introducing new functions in the EDSL. You
/// can then call the functions in the context of generating new expressions, returning them or creating variables.
///
/// Injecting a function call in the EDSL is done via two current mechanisms:
///
/// - Either call the [`FunHandle::call`] method:
///   - It is a function without argument if the represented function doesn’t have any argument.
///   - It is a unary function if the represented function has a single argument.
///   - It takes a tuple encapsulating the arguments for a n-ary represented function.
/// - **On nightly only**, you can enable the `fun-call` feature-gate and calling the function will do the same thing
///   as [`FunHandle::call`]. However, because of how the various [`FnOnce`], [`FnMut`] and [`Fn`] traits are made,
///   functions taking several arguments take them as separate arguments as if it was a regular Rust function (they
///   don’t take a tuple as with the [`FunHandle::call`] method).
///
/// # Examples
///
/// A unary function squaring its argument, the regular way:
///
/// ```
/// # use shades::ShaderBuilder;
/// # ShaderBuilder::new_vertex_shader(|mut s, vertex| {
/// use shades::{Expr, FunHandle, Scope, lit, vec2};
///
/// let square = s.fun(|s: &mut Scope<Expr<i32>>, a: Expr<i32>| {
///   &a * &a
/// });
///
/// s.main_fun(|s: &mut Scope<()>| {
///   // call square with 3 and bind the result to a variable
///   let squared = s.var(square.call(lit!(3)));
/// })
/// # });
/// ```
///
/// The same function but with the `fun-call` feature-gate enabled:
///
/// ```
/// # use shades::ShaderBuilder;
/// # ShaderBuilder::new_vertex_shader(|mut s, vertex| {
/// use shades::{Expr, Scope, lit};
///
/// let square = s.fun(|s: &mut Scope<Expr<i32>>, a: Expr<i32>| {
///   &a * &a
/// });
///
/// s.main_fun(|s: &mut Scope<()>| {
///   // call square with 3 and bind the result to a variable
///   # #[cfg(feature = "fun-call")]
///   let squared = s.var(square(lit!(3)));
/// })
/// # });
/// ```
///
/// A function taking two 3D vectors and a floating scalar and returning their linear interpolation, called with
/// three arguments:
///
/// ```
/// # use shades::ShaderBuilder;
/// # ShaderBuilder::new_vertex_shader(|mut s, vertex| {
/// use shades::{Expr, Mix as _, Scope, V3, lit, vec3};
///
/// let lerp = s.fun(|s: &mut Scope<Expr<V3<f32>>>, a: Expr<V3<f32>>, b: Expr<V3<f32>>, t: Expr<f32>| {
///   a.mix(b, t)
/// });
///
/// s.main_fun(|s: &mut Scope<()>| {
///   # #[cfg(feature = "fun-call")]
///   let a = vec3!(0., 0., 0.);
///   let b = vec3!(1., 1., 1.);
///
///   // call lerp here and bind it to a local variable
/// # #[cfg(feature = "fun-call")]
///   let result = s.var(lerp(a, b, lit!(0.75)));
/// })
/// # });
/// ```
#[derive(Clone, Debug, PartialEq)]
pub struct FunHandle<R, A> {
  erased: ErasedFunHandle,
  _phantom: PhantomData<(R, A)>,
}

impl<R> FunHandle<Expr<R>, ()> {
  /// Create an expression representing a function call to this function.
  ///
  /// See the documentation of [`FunHandle`] for examples.
  pub fn call(&self) -> Expr<R> {
    Expr::new(ErasedExpr::FunCall(self.erased.clone(), Vec::new()))
  }
}

#[cfg(feature = "fun-call")]
impl<R> FnOnce<()> for FunHandle<Expr<R>, ()> {
  type Output = Expr<R>;

  extern "rust-call" fn call_once(self, _: ()) -> Self::Output {
    self.call()
  }
}

#[cfg(feature = "fun-call")]
impl<R> FnMut<()> for FunHandle<Expr<R>, ()> {
  extern "rust-call" fn call_mut(&mut self, _: ()) -> Self::Output {
    self.call()
  }
}

#[cfg(feature = "fun-call")]
impl<R> Fn<()> for FunHandle<Expr<R>, ()> {
  extern "rust-call" fn call(&self, _: ()) -> Self::Output {
    self.call()
  }
}

impl<R, A> FunHandle<Expr<R>, Expr<A>> {
  /// Create an expression representing a function call to this function.
  ///
  /// See the documentation of [`FunHandle`] for examples.
  pub fn call(&self, a: Expr<A>) -> Expr<R> {
    Expr::new(ErasedExpr::FunCall(self.erased.clone(), vec![a.erased]))
  }
}

#[cfg(feature = "fun-call")]
impl<R, A> FnOnce<(Expr<A>,)> for FunHandle<Expr<R>, Expr<A>> {
  type Output = Expr<R>;

  extern "rust-call" fn call_once(self, a: (Expr<A>,)) -> Self::Output {
    self.call(a.0)
  }
}

#[cfg(feature = "fun-call")]
impl<R, A> FnMut<(Expr<A>,)> for FunHandle<Expr<R>, Expr<A>> {
  extern "rust-call" fn call_mut(&mut self, a: (Expr<A>,)) -> Self::Output {
    self.call(a.0)
  }
}

#[cfg(feature = "fun-call")]
impl<R, A> Fn<(Expr<A>,)> for FunHandle<Expr<R>, Expr<A>> {
  extern "rust-call" fn call(&self, a: (Expr<A>,)) -> Self::Output {
    self.call(a.0)
  }
}

// the first stage must be named S0
macro_rules! impl_FunCall {
  ( $( ( $arg_name:ident, $arg_ty:ident ) ),*) => {
    impl<R, $($arg_ty),*> FunHandle<Expr<R>, ($(Expr<$arg_ty>),*)>
    {
      /// Create an expression representing a function call to this function.
      ///
      /// See the documentation of [`FunHandle`] for examples.
      pub fn call(&self, $($arg_name : Expr<$arg_ty>),*) -> Expr<R> {
        Expr::new(ErasedExpr::FunCall(self.erased.clone(), vec![$($arg_name.erased),*]))
      }
    }

    #[cfg(feature = "fun-call")]
    impl<R, $($arg_ty),*> FnOnce<($(Expr<$arg_ty>),*)> for FunHandle<Expr<R>, ($(Expr<$arg_ty>),*)>
    {
      type Output = Expr<R>;

      extern "rust-call" fn call_once(self, ($($arg_name),*): ($(Expr<$arg_ty>),*)) -> Self::Output {
        self.call($($arg_name),*)
      }
    }

    #[cfg(feature = "fun-call")]
    impl<R, $($arg_ty),*> FnMut<($(Expr<$arg_ty>),*)> for FunHandle<Expr<R>, ($(Expr<$arg_ty>),*)>
    {
      extern "rust-call" fn call_mut(&mut self, ($($arg_name),*): ($(Expr<$arg_ty>),*)) -> Self::Output {
        self.call($($arg_name),*)
      }
    }

    #[cfg(feature = "fun-call")]
    impl<R, $($arg_ty),*> Fn<($(Expr<$arg_ty>),*)> for FunHandle<Expr<R>, ($(Expr<$arg_ty>),*)>
    {
      extern "rust-call" fn call(&self, ($($arg_name),*): ($(Expr<$arg_ty>),*)) -> Self::Output {
        self.call($($arg_name),*)
      }
    }
  };
}

// implement function calls for Expr up to 16 arguments
macro_rules! impl_FunCall_rec {
  ( ( $a:ident, $b:ident ) , ( $x:ident, $y:ident )) => {
    impl_FunCall!(($a, $b), ($x, $y));
  };

  ( ( $a:ident, $b:ident ) , ( $x: ident, $y: ident ) , $($r:tt)* ) => {
    impl_FunCall_rec!(($a, $b), $($r)*);
    impl_FunCall!(($a, $b), ($x, $y), $($r)*);
  };
}
impl_FunCall_rec!(
  (a, A),
  (b, B),
  (c, C),
  (d, D),
  (e, E),
  (f, F),
  (g, G),
  (h, H),
  (i, I),
  (j, J),
  (k, K),
  (l, L),
  (m, M),
  (n, N),
  (o, O),
  (p, P)
);

/// Erased function handle.
#[derive(Clone, Debug, PartialEq)]
enum ErasedFunHandle {
  // cast operators
  Vec2,
  Vec3,
  Vec4,
  // trigonometry
  Radians,
  Degrees,
  Sin,
  Cos,
  Tan,
  ASin,
  ACos,
  ATan,
  SinH,
  CosH,
  TanH,
  ASinH,
  ACosH,
  ATanH,
  // exponential
  Pow,
  Exp,
  Exp2,
  Log,
  Log2,
  Sqrt,
  InverseSqrt,
  // common
  Abs,
  Sign,
  Floor,
  Trunc,
  Round,
  RoundEven,
  Ceil,
  Fract,
  Min,
  Max,
  Clamp,
  Mix,
  Step,
  SmoothStep,
  IsNan,
  IsInf,
  FloatBitsToInt,
  IntBitsToFloat,
  UIntBitsToFloat,
  FMA,
  Frexp,
  Ldexp,
  // floating-point pack and unpack functions
  PackUnorm2x16,
  PackSnorm2x16,
  PackUnorm4x8,
  PackSnorm4x8,
  UnpackUnorm2x16,
  UnpackSnorm2x16,
  UnpackUnorm4x8,
  UnpackSnorm4x8,
  PackHalf2x16,
  UnpackHalf2x16,
  // geometry functions
  Length,
  Distance,
  Dot,
  Cross,
  Normalize,
  FaceForward,
  Reflect,
  Refract,
  // matrix functions
  // TODO
  // vector relational functions
  VLt,
  VLte,
  VGt,
  VGte,
  VEq,
  VNeq,
  VAny,
  VAll,
  VNot,
  // integer functions
  UAddCarry,
  USubBorrow,
  UMulExtended,
  IMulExtended,
  BitfieldExtract,
  BitfieldInsert,
  BitfieldReverse,
  BitCount,
  FindLSB,
  FindMSB,
  // texture functions
  // TODO
  // geometry shader functions
  EmitStreamVertex,
  EndStreamPrimitive,
  EmitVertex,
  EndPrimitive,
  // fragment processing functions
  DFDX,
  DFDY,
  DFDXFine,
  DFDYFine,
  DFDXCoarse,
  DFDYCoarse,
  FWidth,
  FWidthFine,
  FWidthCoarse,
  InterpolateAtCentroid,
  InterpolateAtSample,
  InterpolateAtOffset,
  // shader invocation control functions
  Barrier,
  MemoryBarrier,
  MemoryBarrierAtomic,
  MemoryBarrierBuffer,
  MemoryBarrierShared,
  MemoryBarrierImage,
  GroupMemoryBarrier,
  // shader invocation group functions
  AnyInvocation,
  AllInvocations,
  AllInvocationsEqual,
  UserDefined(u16),
}

/// A function definition.
///
/// Function definitions contain the information required to know how to represent a function’s arguments, return type
/// and its body.
#[derive(Debug)]
pub struct FunDef<R, A> {
  erased: ErasedFun,
  _phantom: PhantomData<(R, A)>,
}

impl<R, A> FunDef<R, A> {
  fn new(erased: ErasedFun) -> Self {
    Self {
      erased,
      _phantom: PhantomData,
    }
  }
}

/// Erased function definition.
#[derive(Debug)]
struct ErasedFun {
  args: Vec<Type>,
  scope: ErasedScope,
  ret: ErasedReturn,
}

impl ErasedFun {
  fn new(args: Vec<Type>, scope: ErasedScope, ret: ErasedReturn) -> Self {
    Self { args, scope, ret }
  }
}

/// Lexical scope that must output a `R`.
///
/// Scopes are the only way to add control flow expressions to shaders. [`Scope<R>`] is the most general one, parent
/// of all scopes. Depending on the kind of control flow, several kind of scopes are possible:
///
/// - [`Scope<R>`] is the most general one and every scopes share its features.
/// - [`EscapeScope<R>`] is a special kind of [`Scope<R>`] that allows escaping from anywhere in the scope.
/// - [`LoopScope<R>`] is a special kind of [`EscapeScope<R>`] that also allows to escape local looping expressions,
///   such as `for` and `while` loops.
///
/// A [`Scope<R>`] allows to perform a bunch of actions:
///
/// - Creating variable via [`Scope::var`]. Expressions of type [`Expr<T>`] where [`T: ToType`](ToType) are bound in a
///   [`Scope<R>`] via [`Scope::var`] and a [`Var<T>`] is returned, representing the bound variable.
/// - Variable mutation via [`Scope::set`]. Any [`Var<T>`] declared previously and still reachable in the current [`Scope`]
///   can be mutated.
/// - Introducing conditional statements with [`Scope::when`] and [`Scope::unless`].
/// - Introducing looping statements with [`Scope::loop_for`] and [`Scope::loop_while`].
#[derive(Debug)]
pub struct Scope<R> {
  erased: ErasedScope,
  _phantom: PhantomData<R>,
}

impl<R> Scope<R>
where
  Return: From<R>,
{
  /// Create a new [`Scope<R>`] for which the ID is explicitly passed.
  ///
  /// The ID is unique in the scope hierarchy, but is not necessarily unique in the parent scope. What it means is that
  /// creating a scope `s` in a (parent) scope of ID `p` will give `s` the ID `p + 1`. So any scope created directly
  /// under the scope of ID `p` will get the `p + 1` ID. The reason for this is that variables go out of scope at the
  /// end of the scope they were created in, so it’s safe to reuse the same ID for sibling scopes, as they can’t share
  /// variables.
  fn new(id: u16) -> Self {
    Self {
      erased: ErasedScope::new(id),
      _phantom: PhantomData,
    }
  }

  /// Create a new fresh scope under the current scope.
  fn deeper(&self) -> Self {
    Scope::new(self.erased.id + 1)
  }

  /// Bind an expression to a variable in the current scope.
  ///
  /// `let v = s.var(e);` binds the `e` expression to `v` in the `s` [`Scope<T>`], and `e` must have type [`Expr<T>`]
  /// and `v` must be a [`Var<T>`], with [`T: ToType`](ToType).
  ///
  /// # Return
  ///
  /// The resulting [`Var<T>`] contains the representation of the binding in the EDSL and the actual binding is
  /// recorded in the current scope.
  ///
  /// # Examples
  ///
  /// ```
  /// # use shades::{Scope, ShaderBuilder};
  /// # ShaderBuilder::new_vertex_shader(|mut s, vertex| {
  /// #   s.main_fun(|s: &mut Scope<()>| {
  /// let v = s.var(3.1415); // assign the literal 3.1415 to v
  /// let q = s.var(v * 2.); // assign v * 2. to q
  /// #   })
  /// # });
  /// ```
  pub fn var<T>(&mut self, init_value: impl Into<Expr<T>>) -> Var<T>
  where
    T: ToType,
  {
    let n = self.erased.next_var;
    let handle = ScopedHandle::fun_var(self.erased.id, n);

    self.erased.next_var += 1;

    self.erased.instructions.push(ScopeInstr::VarDecl {
      ty: T::ty(),
      handle: handle.clone(),
      init_value: init_value.into().erased,
    });

    Var::new(handle)
  }

  /// For looping statement — `for`.
  ///
  /// `s.loop_for(i, |i| /* cond */, |i| /* fold */, |i| /* body */ )` inserts a looping statement into the EDSL
  /// representing a typical “for” loop. `i` is an [`Expr<T>`] satisfying [`T: ToType`](ToType) and is used as
  /// _initial_ value.
  ///
  /// In all the following closures, `i` refers to the initial value.
  ///
  /// The first `cond` closure must return an [`Expr<bool>`], representing the condition that is held until the loop
  /// exits. The second `fold` closure is a pure computation that must return an [`Expr<T>`] and that will be evaluated
  /// at the end of each iteration before the next check on `cond`. The last and third `body` closure is the body of the
  /// loop.
  ///
  /// The behaviors of the first two closures is important to understand. Those are akin to _filtering_ and _folding_.
  /// The closure returning the [`Expr<bool>`] is given the [`Expr<T>`] at each iteration and the second closure creates
  /// the new [`Expr<T>`] for the next iteration. Normally, people are used to write this pattern as `i++`, for
  /// instance, but in the case of our EDSL, it is more akin go `i + 1`, and this value is affected to a local
  /// accumulator hidden from the user.
  ///
  /// The [`LoopScope<R>`] argument to the `body` closure is a specialization of [`Scope<R>`] that allows breaking out
  /// of loops.
  ///
  /// # Examples
  ///
  /// ```
  /// use shades::{CanEscape as _, LoopScope, Scope, ShaderBuilder};
  ///
  /// ShaderBuilder::new_vertex_shader(|mut s, vertex| {
  ///   s.main_fun(|s: &mut Scope<()>| {
  ///     s.loop_for(0, |i| i.lt(10), |i| i + 1, |s: &mut LoopScope<()>, i| {
  ///       s.when(i.eq(5), |s: &mut LoopScope<()>| {
  ///         // when i == 5, abort from the main function
  ///         s.abort();
  ///       });
  ///     });
  ///   })
  /// });
  /// ```
  pub fn loop_for<T>(
    &mut self,
    init_value: impl Into<Expr<T>>,
    condition: impl FnOnce(&Expr<T>) -> Expr<bool>,
    iter_fold: impl FnOnce(&Expr<T>) -> Expr<T>,
    body: impl FnOnce(&mut LoopScope<R>, &Expr<T>),
  ) where
    T: ToType,
  {
    let mut scope = LoopScope::new(self.deeper());

    // bind the init value so that it’s available in all closures
    let init_var = scope.var(init_value);

    let condition = condition(&init_var);

    // generate the “post expr”, which is basically the free from of the third part of the for loop; people usually
    // set this to ++i, i++, etc., but in our case, the expression is to treat as a fold’s accumulator
    let post_expr = iter_fold(&init_var);

    body(&mut scope, &init_var);

    let scope = Scope::from(scope);
    self.erased.instructions.push(ScopeInstr::For {
      init_ty: T::ty(),
      init_handle: ScopedHandle::fun_var(scope.erased.id, 0),
      init_expr: init_var.to_expr().erased,
      condition: condition.erased,
      post_expr: post_expr.erased,
      scope: scope.erased,
    });
  }

  /// While looping statement — `while`.
  ///
  /// `s.loop_while(cond, body)` inserts a looping statement into the EDSL representing a typical “while” loop.
  ///
  /// `cond` is an [`Expr<bool>`], representing the condition that is held until the loop exits. `body` is the content
  /// the loop will execute at each iteration.
  ///
  /// The [`LoopScope<R>`] argument to the `body` closure is a specialization of [`Scope<R>`] that allows breaking out
  /// of loops.
  ///
  /// # Examples
  ///
  /// ```
  /// use shades::{CanEscape as _, LoopScope, Scope, ShaderBuilder};
  ///
  /// ShaderBuilder::new_vertex_shader(|mut s, vertex| {
  ///   s.main_fun(|s: &mut Scope<()>| {
  ///     let i = s.var(10);
  ///
  ///     s.loop_while(i.lt(10), |s| {
  ///       s.set(&i, &i + 1);
  ///     });
  ///   })
  /// });
  /// ```
  pub fn loop_while(
    &mut self,
    condition: impl Into<Expr<bool>>,
    body: impl FnOnce(&mut LoopScope<R>),
  ) {
    let mut scope = LoopScope::new(self.deeper());
    body(&mut scope);

    self.erased.instructions.push(ScopeInstr::While {
      condition: condition.into().erased,
      scope: Scope::from(scope).erased,
    });
  }

  /// Mutate a variable in the current scope.
  ///
  /// # Examples
  ///
  /// ```
  /// # use shades::{Scope, ShaderBuilder};
  /// # ShaderBuilder::new_vertex_shader(|mut s, vertex| {
  /// #   s.main_fun(|s: &mut Scope<()>| {
  /// let v = s.var(1); // v = 1
  /// s.set(&v, 10); // v = 10
  /// #   })
  /// # });
  /// ```
  pub fn set<T>(&mut self, var: impl Into<Var<T>>, value: impl Into<Expr<T>>) {
    self.erased.instructions.push(ScopeInstr::MutateVar {
      var: var.into().to_expr().erased,
      expr: value.into().erased,
    });
  }
}

/// A special kind of [`Scope`] that can also escape expressions out of its parent scope.
#[derive(Debug)]
pub struct EscapeScope<R>(Scope<R>);

impl<R> From<EscapeScope<R>> for Scope<R> {
  fn from(s: EscapeScope<R>) -> Self {
    s.0
  }
}

impl<R> Deref for EscapeScope<R> {
  type Target = Scope<R>;

  fn deref(&self) -> &Self::Target {
    &self.0
  }
}

impl<R> DerefMut for EscapeScope<R> {
  fn deref_mut(&mut self) -> &mut Self::Target {
    &mut self.0
  }
}

impl<R> EscapeScope<R>
where
  Return: From<R>,
{
  fn new(s: Scope<R>) -> Self {
    Self(s)
  }

  /// Early-return the current function with an expression.
  ///
  /// # Examples
  ///
  /// ```
  /// # use shades::ShaderBuilder;
  /// # ShaderBuilder::new_vertex_shader(|mut s, vertex| {
  /// use shades::{CanEscape as _, Expr, Scope};
  ///
  /// let _fun = s.fun(|s: &mut Scope<Expr<i32>>, arg: Expr<i32>| {
  ///   // if arg is less than 10, early-return with 0
  ///   s.when(arg.lt(10), |s| {
  ///     s.leave(0);
  ///   });
  ///
  ///   arg
  /// });
  ///
  /// #   s.main_fun(|s: &mut Scope<()>| {
  /// #   })
  /// # });
  /// ```
  pub fn leave(&mut self, ret: impl Into<R>) {
    self
      .erased
      .instructions
      .push(ScopeInstr::Return(Return::from(ret.into()).erased));
  }
}

impl EscapeScope<()> {
  /// Early-abort the current function.
  ///
  /// # Examples
  ///
  /// ```
  /// # use shades::ShaderBuilder;
  /// # ShaderBuilder::new_vertex_shader(|mut s, vertex| {
  /// use shades::{CanEscape as _, Expr, Scope};
  ///
  /// let _fun = s.fun(|s: &mut Scope<()>, arg: Expr<i32>| {
  ///   // if arg is less than 10, early-return with 0
  ///   s.when(arg.lt(10), |s| {
  ///     s.abort();
  ///   });
  ///
  ///   // do something else…
  /// });
  ///
  /// #   s.main_fun(|s: &mut Scope<()>| {
  /// #   })
  /// # });
  /// ```
  pub fn abort(&mut self) {
    self
      .erased
      .instructions
      .push(ScopeInstr::Return(ErasedReturn::Void));
  }
}

/// A special kind of [`EscapeScope`] that can also break loops.
#[derive(Debug)]
pub struct LoopScope<R>(EscapeScope<R>);

impl<R> From<LoopScope<R>> for Scope<R> {
  fn from(s: LoopScope<R>) -> Self {
    s.0.into()
  }
}

impl<R> Deref for LoopScope<R> {
  type Target = EscapeScope<R>;

  fn deref(&self) -> &Self::Target {
    &self.0
  }
}

impl<R> DerefMut for LoopScope<R> {
  fn deref_mut(&mut self) -> &mut Self::Target {
    &mut self.0
  }
}

impl<R> LoopScope<R>
where
  Return: From<R>,
{
  fn new(s: Scope<R>) -> Self {
    Self(EscapeScope::new(s))
  }

  /// Break the current iteration of the nearest loop and continue to the next iteration.
  ///
  /// # Examples
  ///
  /// ```
  /// # use shades::{Scope, ShaderBuilder};
  /// # ShaderBuilder::new_vertex_shader(|mut s, vertex| {
  /// #   s.main_fun(|s: &mut Scope<()>| {
  /// use shades::CanEscape as _;
  ///
  /// s.loop_while(true, |s| {
  ///   s.loop_continue();
  /// });
  /// #   })
  /// # });
  /// ```
  pub fn loop_continue(&mut self) {
    self.erased.instructions.push(ScopeInstr::Continue);
  }

  /// Break the nearest loop.
  ///
  /// # Examples
  ///
  /// ```
  /// # use shades::{Scope, ShaderBuilder};
  /// # ShaderBuilder::new_vertex_shader(|mut s, vertex| {
  /// #   s.main_fun(|s: &mut Scope<()>| {
  /// use shades::CanEscape as _;
  ///
  /// s.loop_while(true, |s| {
  ///   s.loop_break();
  /// });
  /// #   })
  /// # });
  /// ```
  pub fn loop_break(&mut self) {
    self.erased.instructions.push(ScopeInstr::Break);
  }
}

#[derive(Debug, PartialEq)]
struct ErasedScope {
  id: u16,
  instructions: Vec<ScopeInstr>,
  next_var: u16,
}

impl ErasedScope {
  fn new(id: u16) -> Self {
    Self {
      id,
      instructions: Vec::new(),
      next_var: 0,
    }
  }
}

/// Scopes allowing to enter conditional scopes.
///
/// Conditional scopes allow to break out of a function by early-return / aborting the function.
pub trait CanEscape<R>
where
  Return: From<R>,
{
  /// Scope type inside the scope of the conditional.
  type InnerScope;

  /// Conditional statement — `if`.
  ///
  /// `s.when(cond, |s: &mut EscapeScope<R>| { /* body */ })` inserts a conditional branch in the EDSL using the `cond`
  /// expression as truth and the passed closure as body to run when the represented condition is `true`. The
  /// [`EscapeScope<R>`] provides you with the possibility to escape and leave the function earlier, either by returning
  /// an expression or by aborting the function, depending on the value of `R`: `Expr<_>` allows for early-returns and
  /// `()` allows for aborting.
  ///
  /// # Return
  ///
  /// A [`When<R>`], authorizing the same escape rules with `R`. This object allows you to chain other conditional
  /// statements, commonly referred to as `else if` and `else` in common languages.
  ///
  /// Have a look at the documentation of [`When`] for further information.
  ///
  /// # Examples
  ///
  /// Early-return:
  ///
  /// ```
  /// use shades::{CanEscape as _, EscapeScope, Expr, Scope, ShaderBuilder, lit};
  ///
  /// ShaderBuilder::new_vertex_shader(|mut s, vertex| {
  ///   let f = s.fun(|s: &mut Scope<Expr<i32>>| {
  ///     s.when(lit!(1).lt(3), |s: &mut EscapeScope<Expr<i32>>| {
  ///       // do something in here
  ///
  ///       // early-return with 0; only possible if the function returns Expr<i32>
  ///       s.leave(0);
  ///     });
  ///
  ///     lit!(1)
  ///   });
  ///
  ///   s.main_fun(|s: &mut Scope<()>| {
  /// # #[cfg(feature = "fun-call")]
  ///     let x = s.var(f());
  ///   })
  /// });
  /// ```
  ///
  /// Aborting a function:
  ///
  /// ```
  /// use shades::{CanEscape as _, EscapeScope, Scope, ShaderBuilder, lit};
  ///
  /// ShaderBuilder::new_vertex_shader(|mut s, vertex| {
  ///   s.main_fun(|s: &mut Scope<()>| {
  ///     s.when(lit!(1).lt(3), |s: &mut EscapeScope<()>| {
  ///       // do something in here
  ///
  ///       // break the parent function by aborting; this is possible because the return type is ()
  ///       s.abort();
  ///     });
  ///   })
  /// });
  /// ```
  fn when<'a>(
    &'a mut self,
    condition: impl Into<Expr<bool>>,
    body: impl FnOnce(&mut Self::InnerScope),
  ) -> When<'a, R>;

  /// Complement form of [`Scope::when`].
  ///
  /// This method does the same thing as [`Scope::when`] but applies the [`Not::not`](std::ops::Not::not) operator on
  /// the condition first.
  fn unless<'a>(
    &'a mut self,
    condition: impl Into<Expr<bool>>,
    body: impl FnOnce(&mut Self::InnerScope),
  ) -> When<'a, R> {
    self.when(!condition.into(), body)
  }
}

impl<R> CanEscape<R> for Scope<R>
where
  Return: From<R>,
{
  type InnerScope = EscapeScope<R>;

  fn when<'a>(
    &'a mut self,
    condition: impl Into<Expr<bool>>,
    body: impl FnOnce(&mut Self::InnerScope),
  ) -> When<'a, R> {
    let mut scope = EscapeScope::new(self.deeper());
    body(&mut scope);

    self.erased.instructions.push(ScopeInstr::If {
      condition: condition.into().erased,
      scope: Scope::from(scope).erased,
    });

    When { parent_scope: self }
  }
}

impl<R> CanEscape<R> for LoopScope<R>
where
  Return: From<R>,
{
  type InnerScope = LoopScope<R>;

  fn when<'a>(
    &'a mut self,
    condition: impl Into<Expr<bool>>,
    body: impl FnOnce(&mut Self::InnerScope),
  ) -> When<'a, R> {
    let mut scope = LoopScope::new(self.deeper());
    body(&mut scope);

    self.erased.instructions.push(ScopeInstr::If {
      condition: condition.into().erased,
      scope: Scope::from(scope).erased,
    });

    When { parent_scope: self }
  }
}

/// Conditional combinator.
///
/// A [`When<R>`] is returned from functions such as [`CanEscape::when`] or [`CanEscape::unless`] and allows to continue
/// chaining conditional statements, encoding the concept of `else if` and `else` in more traditional languages.
#[derive(Debug)]
pub struct When<'a, R> {
  /// The scope from which this [`When`] expression comes from.
  ///
  /// This will be handy if we want to chain this when with others (corresponding to `else if` and `else`, for
  /// instance).
  parent_scope: &'a mut Scope<R>,
}

impl<R> When<'_, R>
where
  Return: From<R>,
{
  /// Add a conditional branch — `else if`.
  ///
  /// This method is often found chained after [`CanEscape::when`] and allows to add a new conditional if the previous
  /// conditional fails (i.e. `else if`). The behavior is the same as with [`CanEscape::when`].
  ///
  /// # Return
  ///
  /// Another [`When<R>`], allowing to add more conditional branches.
  ///
  /// # Examples
  ///
  /// ```
  /// # use shades::{Scope, ShaderBuilder};
  /// # ShaderBuilder::new_vertex_shader(|mut s, vertex| {
  /// #   s.main_fun(|s: &mut Scope<()>| {
  /// use shades::{CanEscape as _, lit};
  ///
  /// let x = lit!(1);
  ///
  /// // you will need CanEscape in order to use when
  /// s.when(x.lt(2), |s| {
  ///   // do something if x < 2
  /// }).or_else(x.lt(10), |s| {
  ///   // do something if x < 10
  /// });
  /// #   })
  /// # });
  /// ```
  pub fn or_else(
    self,
    condition: impl Into<Expr<bool>>,
    body: impl FnOnce(&mut EscapeScope<R>),
  ) -> Self {
    let mut scope = EscapeScope::new(self.parent_scope.deeper());
    body(&mut scope);

    self
      .parent_scope
      .erased
      .instructions
      .push(ScopeInstr::ElseIf {
        condition: condition.into().erased,
        scope: Scope::from(scope).erased,
      });

    self
  }

  /// Add a final catch-all conditional branch — `else`.
  ///
  /// This method is often found chained after [`CanEscape::when`] and allows to finish the chain of conditional
  /// branches if the previous conditional fails (i.e. `else`). The behavior is the same as with [`CanEscape::when`].
  ///
  /// # Examples
  ///
  /// ```
  /// # use shades::{Scope, ShaderBuilder};
  /// # ShaderBuilder::new_vertex_shader(|mut s, vertex| {
  /// #   s.main_fun(|s: &mut Scope<()>| {
  /// use shades::{CanEscape as _, lit};
  ///
  /// let x = lit!(1);
  ///
  /// // you will need CanEscape in order to use when
  /// s.when(x.lt(2), |s| {
  ///   // do something if x < 2
  /// }).or(|s| {
  ///   // do something if x >= 2
  /// });
  /// #   })
  /// # });
  /// ```
  ///
  /// Can chain and mix conditional but [`When::or`] cannot be anywhere else but the end of the chain:
  ///
  /// ```
  /// # use shades::{Scope, ShaderBuilder};
  /// # ShaderBuilder::new_vertex_shader(|mut s, vertex| {
  /// #   s.main_fun(|s: &mut Scope<()>| {
  /// use shades::{CanEscape as _, lit};
  ///
  /// let x = lit!(1);
  ///
  /// // you will need CanEscape in order to use when
  /// s.when(x.lt(2), |s| {
  ///   // do something if x < 2
  /// }).or_else(x.lt(5), |s| {
  ///   // do something if x < 5
  /// }).or_else(x.lt(10), |s| {
  ///   // do something if x < 10
  /// }).or(|s| {
  ///   // else, do this
  /// });
  /// #   })
  /// # });
  /// ```
  pub fn or(self, body: impl FnOnce(&mut EscapeScope<R>)) {
    let mut scope = EscapeScope::new(self.parent_scope.deeper());
    body(&mut scope);

    self
      .parent_scope
      .erased
      .instructions
      .push(ScopeInstr::Else {
        scope: Scope::from(scope).erased,
      });
  }
}

/// Mutable variable.
///
/// A [`Var<T>`] is akin to an [`Expr<T>`] that can be mutated. You can go from a [`Var<T>`] to an [`Expr<T>`] via
/// either the [`From`] or [`Var::to_expr`] method.
///
/// Variables, because they allow mutations, allow to write more complicated shader functions. Also, lots of graphics
/// pipelines’ properties are variables you will have to write to, such as [`VertexShaderEnv::position`].
#[derive(Debug)]
pub struct Var<T>(Expr<T>)
where
  T: ?Sized;

impl<'a, T> From<&'a Var<T>> for Var<T>
where
  T: ?Sized,
{
  fn from(v: &'a Self) -> Self {
    Var(v.0.clone())
  }
}

impl<T> From<Var<T>> for Expr<T>
where
  T: ?Sized,
{
  fn from(v: Var<T>) -> Self {
    v.0
  }
}

impl<'a, T> From<&'a Var<T>> for Expr<T>
where
  T: ?Sized,
{
  fn from(v: &'a Var<T>) -> Self {
    v.0.clone()
  }
}

impl<T> Var<T>
where
  T: ?Sized,
{
  /// Create a new [`Var<T>`] from a [`ScopedHandle`].
  const fn new(handle: ScopedHandle) -> Self {
    Self(Expr::new(ErasedExpr::Var(handle)))
  }

  /// Coerce [`Var<T>`] into [`Expr<T>`].
  ///
  /// Remember that doing so will move the [`Var<T>`]. `clone` it if you want to preserve the source variable.
  ///
  /// > Note: use this function only when necessary. Lots of functions will accept both [`Expr<T>`] and [`Var<T>`],
  /// > performing the coercion for you automatically.
  ///
  /// # Return
  ///
  /// The expression representation of [`Var<T>`], allowing to pass the variable to functions or expressions that don’t
  /// easily coerce it automatically to [`Expr<T>`] already.
  ///
  /// # Examples
  ///
  /// ```
  /// # use shades::{Scope, ShaderBuilder};
  /// # ShaderBuilder::new_vertex_shader(|mut s, vertex| {
  /// #   s.main_fun(|s: &mut Scope<()>| {
  /// let v = s.var(123); // Var<i32>
  /// let e = v.to_expr(); // Expr<i32>
  /// #   })
  /// # });
  /// ```
  pub fn to_expr(&self) -> Expr<T> {
    self.0.clone()
  }
}

impl<T> Var<[T]> {
  pub fn at(&self, index: impl Into<Expr<i32>>) -> Var<T> {
    Var(self.to_expr().at(index))
  }
}

impl<T, const N: usize> Var<[T; N]> {
  pub fn at(&self, index: impl Into<Expr<i32>>) -> Var<T> {
    Var(self.to_expr().at(index))
  }
}

impl<T> ops::Deref for Var<T>
where
  T: ?Sized,
{
  type Target = Expr<T>;

  fn deref(&self) -> &Self::Target {
    &self.0
  }
}

/// Hierarchical and namespaced handle.
///
/// Handles live in different namespaces:
///
/// - The _built-in_ namespace gathers all built-ins.
/// - The _global_ namespace gathers everything that can be declared at top-level of a shader stage — i.e. mainly
///   constants for this namespace.
/// - The _input_ namespace gathers inputs.
/// - The _output_ namespace gathers outputs.
/// - The _function argument_ namespace gives handles to function arguments, which exist only in a function body.
/// - The _function variable_ namespace gives handles to variables defined in function bodies. This namespace is
/// hierarchical: for each scope, a new namespace is created. The depth at which a namespace is located is referred to
/// as its _subscope_.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
enum ScopedHandle {
  BuiltIn(BuiltIn),
  Global(u16),
  FunArg(u16),
  FunVar { subscope: u16, handle: u16 },
  Input(String),
  Output(String),
  Uniform(String),
}

impl ScopedHandle {
  const fn builtin(b: BuiltIn) -> Self {
    Self::BuiltIn(b)
  }

  const fn global(handle: u16) -> Self {
    Self::Global(handle)
  }

  const fn fun_arg(handle: u16) -> Self {
    Self::FunArg(handle)
  }

  const fn fun_var(subscope: u16, handle: u16) -> Self {
    Self::FunVar { subscope, handle }
  }

  fn uniform(name: impl Into<String>) -> Self {
    Self::Uniform(name.into())
  }
}

#[derive(Debug, PartialEq)]
enum ScopeInstr {
  VarDecl {
    ty: Type,
    handle: ScopedHandle,
    init_value: ErasedExpr,
  },

  Return(ErasedReturn),

  Continue,

  Break,

  If {
    condition: ErasedExpr,
    scope: ErasedScope,
  },

  ElseIf {
    condition: ErasedExpr,
    scope: ErasedScope,
  },

  Else {
    scope: ErasedScope,
  },

  For {
    init_ty: Type,
    init_handle: ScopedHandle,
    init_expr: ErasedExpr,
    condition: ErasedExpr,
    post_expr: ErasedExpr,
    scope: ErasedScope,
  },

  While {
    condition: ErasedExpr,
    scope: ErasedScope,
  },

  MutateVar {
    var: ErasedExpr,
    expr: ErasedExpr,
  },
}

/// Dimension of a primitive type.
///
/// Primitive types currently can have one of four dimension:
///
/// - [`Dim::Scalar`]: designates a scalar value.
/// - [`Dim::D2`]: designates a 2D vector.
/// - [`Dim::D3`]: designates a 3D vector.
/// - [`Dim::D4`]: designates a 4D vector.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum Dim {
  /// Scalar value.
  Scalar,

  /// 2D vector.
  D2,

  /// 3D vector.
  D3,

  /// 4D vector.
  D4,
}

/// Matrix wrapper.
///
/// This type represents a matrix of a given dimension, deduced from the wrapped type.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Matrix<T>(T);

impl<T, const M: usize, const N: usize> From<[[T; N]; M]> for Matrix<[[T; N]; M]> {
  fn from(a: [[T; N]; M]) -> Self {
    Matrix(a)
  }
}

macro_rules! make_mat_ty {
  ($t:ident, $lit:ident, $m:expr, $n:expr, $mdim:ident) => {
    pub type $t = Matrix<[[f32; $n]; $m]>;

    impl ToPrimType for Matrix<[[f32; $n]; $m]> {
      const PRIM_TYPE: PrimType = PrimType::Matrix(MatrixDim::$mdim);
    }

    impl From<Matrix<[[f32; $n]; $m]>> for Expr<Matrix<[[f32; $n]; $m]>> {
      fn from(matrix: Matrix<[[f32; $n]; $m]>) -> Self {
        Self::new(ErasedExpr::$lit(matrix))
      }
    }
  };
}

make_mat_ty!(M22, LitM22, 2, 2, D22);
// make_mat_ty!(M23, LitM23, 2, 3, D23);
// make_mat_ty!(M24, LitM24, 2, 4, D24);
// make_mat_ty!(M32, LitM32, 3, 2, D32);
make_mat_ty!(M33, LitM33, 3, 3, D33);
// make_mat_ty!(M34, LitM34, 3, 4, D34);
// make_mat_ty!(M42, LitM42, 4, 2, D42);
// make_mat_ty!(M43, LitM43, 4, 3, D43);
make_mat_ty!(M44, LitM44, 4, 4, D44);

/// Matrix dimension.
///
/// Matrices can have several dimensions. Most of the time, you will be interested in squared dimensions, e.g. 2×2, 3×3
/// and 4×4. However, other dimensions exist.
///
/// > Note: matrices are expressed in column-major.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum MatrixDim {
  /// Squared 2 dimension.
  D22,
  /// 2×3 dimension.
  D23,
  /// 2×4 dimension.
  D24,
  /// 3×2 dimension.
  D32,
  /// Squared 3 dimension.
  D33,
  /// 3×4 dimension.
  D34,
  /// 4×2 dimension.
  D42,
  /// 4×3 dimension.
  D43,
  /// Squared 4 dimension.
  D44,
}

/// Type representation — akin to [`PrimType`] glued with array dimensions, if any.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Type {
  /// Primitive type, representing a type without array dimensions.
  prim_ty: PrimType,

  /// Array dimensions, if any.
  ///
  /// Dimensions are sorted from outer to inner; i.e. `[[i32; N]; M]`’s dimensions is encoded as `vec![M, N]`.
  array_dims: Vec<usize>,
}

/// Primitive supported types.
///
/// Types without array dimensions are known as _primitive types_ and are exhaustively constructed thanks to
/// [`PrimType`].
#[non_exhaustive]
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum PrimType {
  /// An integral type.
  ///
  /// The [`Dim`] argument represents the vector dimension — do not confuse it with an array dimension.
  Int(Dim),

  /// An unsigned integral type.
  ///
  /// The [`Dim`] argument represents the vector dimension — do not confuse it with an array dimension.
  UInt(Dim),

  /// An floating type.
  ///
  /// The [`Dim`] argument represents the vector dimension — do not confuse it with an array dimension.
  Float(Dim),

  /// A boolean type.
  ///
  /// The [`Dim`] argument represents the vector dimension — do not confuse it with an array dimension.
  Bool(Dim),

  /// A N×M floating matrix.
  ///
  /// The [`MatrixDim`] provides the information required to know the exact dimension of the matrix.
  Matrix(MatrixDim),
}

/// Class of types that are recognized by the EDSL.
///
/// Any type implementing this type family is _representable_ in the EDSL.
pub trait ToPrimType {
  /// Mapped primitive type.
  const PRIM_TYPE: PrimType;
}

macro_rules! impl_ToPrimType {
  ($t:ty, $q:ident, $d:ident) => {
    impl ToPrimType for $t {
      const PRIM_TYPE: PrimType = PrimType::$q(Dim::$d);
    }
  };
}

impl_ToPrimType!(i32, Int, Scalar);
impl_ToPrimType!(u32, UInt, Scalar);
impl_ToPrimType!(f32, Float, Scalar);
impl_ToPrimType!(bool, Bool, Scalar);
impl_ToPrimType!(V2<i32>, Int, D2);
impl_ToPrimType!(V2<u32>, UInt, D2);
impl_ToPrimType!(V2<f32>, Float, D2);
impl_ToPrimType!(V2<bool>, Bool, D2);
impl_ToPrimType!(V3<i32>, Int, D3);
impl_ToPrimType!(V3<u32>, UInt, D3);
impl_ToPrimType!(V3<f32>, Float, D3);
impl_ToPrimType!(V3<bool>, Bool, D3);
impl_ToPrimType!(V4<i32>, Int, D4);
impl_ToPrimType!(V4<u32>, UInt, D4);
impl_ToPrimType!(V4<f32>, Float, D4);
impl_ToPrimType!(V4<bool>, Bool, D4);

/// Represent a type (primitive type and array dimension) in the EDSL.
///
/// Any type implementing [`ToType`] is representable in the EDSL. Any type implementing [`ToPrimType`] automatically
/// also implements [`ToType`].
pub trait ToType {
  fn ty() -> Type;
}

impl<T> ToType for T
where
  T: ToPrimType,
{
  fn ty() -> Type {
    Type {
      prim_ty: T::PRIM_TYPE,
      array_dims: Vec::new(),
    }
  }
}

impl<T, const N: usize> ToType for [T; N]
where
  T: ToType,
{
  fn ty() -> Type {
    let Type {
      prim_ty,
      array_dims,
    } = T::ty();
    let array_dims = once(N).chain(array_dims).collect();

    Type {
      prim_ty,
      array_dims,
    }
  }
}

/// Select a channel to extract from into a swizzled expession.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SwizzleSelector {
  /// Select the `.x` (or `.r`) channel.
  X,

  /// Select the `.y` (or `.g`) channel.
  Y,

  /// Select the `.z` (or `.b`) channel.
  Z,

  /// Select the `.w` (or `.a`) channel.
  W,
}

/// Swizzle channel selector.
///
/// This type gives the dimension of the target expression (output) and dimension of the source expression (input). The
/// [`SwizzleSelector`] also to select a specific channel in the input expression.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Swizzle {
  /// Create a one-channel expression.
  D1(SwizzleSelector),

  /// Create a two-channel expression.
  D2(SwizzleSelector, SwizzleSelector),

  /// Create a three-channel expression.
  D3(SwizzleSelector, SwizzleSelector, SwizzleSelector),

  /// Create a four-channel expression.
  D4(
    SwizzleSelector,
    SwizzleSelector,
    SwizzleSelector,
    SwizzleSelector,
  ),
}

/// Interface to implement to swizzle an expression.
///
/// If you plan to use your implementor with the [`sw!`](sw) macro, `S` must be one of the following types:
///
/// - [`SwizzleSelector`]: to implement `sw!(.x)`.
/// - [[`SwizzleSelector`]; 2]: to implement `sw!(.xx)`.
/// - [[`SwizzleSelector`]; 3]: to implement `sw!(.xxx)`.
/// - [[`SwizzleSelector`]; 4]: to implement `sw!(.xxxx)`.
pub trait Swizzlable<S> {
  fn swizzle(&self, sw: S) -> Self;
}

// 2D
impl<T> Swizzlable<SwizzleSelector> for Expr<V2<T>> {
  fn swizzle(&self, x: SwizzleSelector) -> Self {
    Expr::new(ErasedExpr::Swizzle(
      Box::new(self.erased.clone()),
      Swizzle::D1(x),
    ))
  }
}

impl<T> Swizzlable<[SwizzleSelector; 2]> for Expr<V2<T>> {
  fn swizzle(&self, [x, y]: [SwizzleSelector; 2]) -> Self {
    Expr::new(ErasedExpr::Swizzle(
      Box::new(self.erased.clone()),
      Swizzle::D2(x, y),
    ))
  }
}

// 3D
impl<T> Swizzlable<SwizzleSelector> for Expr<V3<T>> {
  fn swizzle(&self, x: SwizzleSelector) -> Self {
    Expr::new(ErasedExpr::Swizzle(
      Box::new(self.erased.clone()),
      Swizzle::D1(x),
    ))
  }
}

impl<T> Swizzlable<[SwizzleSelector; 2]> for Expr<V3<T>> {
  fn swizzle(&self, [x, y]: [SwizzleSelector; 2]) -> Self {
    Expr::new(ErasedExpr::Swizzle(
      Box::new(self.erased.clone()),
      Swizzle::D2(x, y),
    ))
  }
}

impl<T> Swizzlable<[SwizzleSelector; 3]> for Expr<V3<T>> {
  fn swizzle(&self, [x, y, z]: [SwizzleSelector; 3]) -> Self {
    Expr::new(ErasedExpr::Swizzle(
      Box::new(self.erased.clone()),
      Swizzle::D3(x, y, z),
    ))
  }
}

// 4D
impl<T> Swizzlable<SwizzleSelector> for Expr<V4<T>> {
  fn swizzle(&self, x: SwizzleSelector) -> Self {
    Expr::new(ErasedExpr::Swizzle(
      Box::new(self.erased.clone()),
      Swizzle::D1(x),
    ))
  }
}

impl<T> Swizzlable<[SwizzleSelector; 2]> for Expr<V4<T>> {
  fn swizzle(&self, [x, y]: [SwizzleSelector; 2]) -> Self {
    Expr::new(ErasedExpr::Swizzle(
      Box::new(self.erased.clone()),
      Swizzle::D2(x, y),
    ))
  }
}

impl<T> Swizzlable<[SwizzleSelector; 3]> for Expr<V4<T>> {
  fn swizzle(&self, [x, y, z]: [SwizzleSelector; 3]) -> Self {
    Expr::new(ErasedExpr::Swizzle(
      Box::new(self.erased.clone()),
      Swizzle::D3(x, y, z),
    ))
  }
}

impl<T> Swizzlable<[SwizzleSelector; 4]> for Expr<V4<T>> {
  fn swizzle(&self, [x, y, z, w]: [SwizzleSelector; 4]) -> Self {
    Expr::new(ErasedExpr::Swizzle(
      Box::new(self.erased.clone()),
      Swizzle::D4(x, y, z, w),
    ))
  }
}

/// Swizzle macro.
///
/// This macro allows to swizzle expressions to yield expressions reorganizing the vector attributes. For instance,
/// `sw!(color, .rgbr)` will take a 4D color and will output a 4D color for which the alpha channel is overridden with
/// the red channel.
///
/// The current syntax allows to extract and construct from a lot of types. Have a look at [`Swizzlable`] for a
/// comprehensive list of what you can do.
#[macro_export]
macro_rules! sw {
  ($e:expr, . $a:tt) => {
    $e.swizzle($crate::sw_extract!($a))
  };

  ($e:expr, . $a:tt . $b:tt) => {
    $e.swizzle([$crate::sw_extract!($a), $crate::sw_extract!($b)])
  };

  ($e:expr, . $a:tt . $b:tt . $c:tt) => {
    $e.swizzle([
      $crate::sw_extract!($a),
      $crate::sw_extract!($b),
      $crate::sw_extract!($c),
    ])
  };

  ($e:expr, . $a:tt . $b:tt . $c:tt . $d:tt) => {
    $e.swizzle([
      $crate::sw_extract!($a),
      $crate::sw_extract!($b),
      $crate::sw_extract!($c),
      $crate::sw_extract!($d),
    ])
  };
}

#[doc(hidden)]
#[macro_export]
macro_rules! sw_extract {
  (x) => {
    $crate::SwizzleSelector::X
  };

  (r) => {
    $crate::SwizzleSelector::X
  };

  (y) => {
    $crate::SwizzleSelector::Y
  };

  (g) => {
    $crate::SwizzleSelector::Y
  };

  (z) => {
    $crate::SwizzleSelector::Z
  };

  (b) => {
    $crate::SwizzleSelector::Z
  };

  (w) => {
    $crate::SwizzleSelector::Z
  };

  (a) => {
    $crate::SwizzleSelector::Z
  };
}

/// Input declaration.
///
/// # Examples
///
/// ```
/// use shades::{Scope, ShaderBuilder, Swizzlable, V3, V4, inputs, sw};
///
/// ShaderBuilder::new_vertex_shader(|mut s, vertex| {
///   inputs!(s,
///     position: V3<f32>,
///     color: V4<f32>
///   );
///
///   s.main_fun(|s: &mut Scope<()>| {
///     let rgb = sw!(color, .r.g.b);
///   })
/// });
/// ```
#[macro_export]
macro_rules! inputs {
  ($s:ident, $( $name:ident : $t:ty ),+) => {
    $(
      let $name = unsafe { $s.input::<$t>(stringify!($name)) };
    )+
  }
}

/// Output declaration.
///
/// # Examples
///
/// ```
/// use shades::{Scope, ShaderBuilder, V3, lit, outputs};
///
/// ShaderBuilder::new_vertex_shader(|mut s, vertex| {
///   outputs!(s,
///     position: V3<f32>
///   );
///
///   s.main_fun(|s: &mut Scope<()>| {
///     s.set(&position, lit!(0., 0., 0.));
///   })
/// });
/// ```
#[macro_export]
macro_rules! outputs {
  ($s:ident, $( $name:ident : $t:ty ),+) => {
    $(
      let $name = unsafe { $s.output::<$t>(stringify!($name)) };
    )+
  }
}

/// Uniform declaration.
///
/// # Examples
///
/// ```
/// use shades::{Scope, ShaderBuilder, V3, uniforms, vec4};
///
/// ShaderBuilder::new_vertex_shader(|mut s, vertex| {
///   uniforms!(s,
///     time: f32
///   );
///
///   s.main_fun(|s: &mut Scope<()>| {
///     s.set(vertex.position, vec4!(time, 0., 0., 1.));
///   })
/// });
/// ```
#[macro_export]
macro_rules! uniforms {
  ($s:ident, $( $name:ident : $t:ty ),+) => {
    $(
      let $name = unsafe { $s.uniform::<$t>(stringify!($name)) };
    )+
  }
}

#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
enum BuiltIn {
  Vertex(VertexBuiltIn),
  TessCtrl(TessCtrlBuiltIn),
  TessEval(TessEvalBuiltIn),
  Geometry(GeometryBuiltIn),
  Fragment(FragmentBuiltIn),
}

#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
enum VertexBuiltIn {
  VertexID,
  InstanceID,
  BaseVertex,
  BaseInstance,
  Position,
  PointSize,
  ClipDistance,
}

#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
enum TessCtrlBuiltIn {
  MaxPatchVerticesIn,
  PatchVerticesIn,
  PrimitiveID,
  InvocationID,
  TessellationLevelOuter,
  TessellationLevelInner,
  In,
  Out,
  Position,
  PointSize,
  ClipDistance,
  CullDistance,
}

#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
enum TessEvalBuiltIn {
  TessCoord,
  MaxPatchVerticesIn,
  PatchVerticesIn,
  PrimitiveID,
  TessellationLevelOuter,
  TessellationLevelInner,
  In,
  Out,
  Position,
  PointSize,
  ClipDistance,
  CullDistance,
}

#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
enum GeometryBuiltIn {
  In,
  Out,
  Position,
  PointSize,
  ClipDistance,
  CullDistance,
  PrimitiveID,
  PrimitiveIDIn,
  InvocationID,
  Layer,
  ViewportIndex,
}

#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
enum FragmentBuiltIn {
  FragCoord,
  FrontFacing,
  PointCoord,
  SampleID,
  SamplePosition,
  SampleMaskIn,
  ClipDistance,
  CullDistance,
  PrimitiveID,
  Layer,
  ViewportIndex,
  FragDepth,
  SampleMask,
  HelperInvocation,
}

/// Vertex shader environment.
#[derive(Debug)]
pub struct VertexShaderEnv {
  // inputs
  /// ID of the current vertex.
  pub vertex_id: Expr<i32>,

  /// Instance ID of the current vertex.
  pub instance_id: Expr<i32>,

  /// Base vertex offset.
  pub base_vertex: Expr<i32>,

  /// Base instance vertex offset.
  pub base_instance: Expr<i32>,

  // outputs
  /// 4D position of the vertex.
  pub position: Var<V4<f32>>,

  /// Point size of the vertex.
  pub point_size: Var<f32>,

  // Clip distances to user-defined plans.
  pub clip_distance: Var<[f32]>,
}

impl VertexShaderEnv {
  fn new() -> Self {
    let vertex_id = Expr::new(ErasedExpr::new_builtin(BuiltIn::Vertex(
      VertexBuiltIn::VertexID,
    )));
    let instance_id = Expr::new(ErasedExpr::new_builtin(BuiltIn::Vertex(
      VertexBuiltIn::InstanceID,
    )));
    let base_vertex = Expr::new(ErasedExpr::new_builtin(BuiltIn::Vertex(
      VertexBuiltIn::BaseVertex,
    )));
    let base_instance = Expr::new(ErasedExpr::new_builtin(BuiltIn::Vertex(
      VertexBuiltIn::BaseInstance,
    )));
    let position = Var(Expr::new(ErasedExpr::new_builtin(BuiltIn::Vertex(
      VertexBuiltIn::Position,
    ))));
    let point_size = Var(Expr::new(ErasedExpr::new_builtin(BuiltIn::Vertex(
      VertexBuiltIn::PointSize,
    ))));
    let clip_distance = Var(Expr::new(ErasedExpr::new_builtin(BuiltIn::Vertex(
      VertexBuiltIn::ClipDistance,
    ))));

    Self {
      vertex_id,
      instance_id,
      base_vertex,
      base_instance,
      position,
      point_size,
      clip_distance,
    }
  }
}

/// Tessellation control shader environment.
#[derive(Debug)]
pub struct TessCtrlShaderEnv {
  // inputs
  /// Maximum number of vertices per patch.
  pub max_patch_vertices_in: Expr<i32>,

  /// Number of vertices for the current patch.
  pub patch_vertices_in: Expr<i32>,

  /// ID of the current primitive.
  pub primitive_id: Expr<i32>,

  /// ID of the current tessellation control shader invocation.
  pub invocation_id: Expr<i32>,

  /// Array of per-vertex input expressions.
  pub input: Expr<[TessControlPerVertexIn]>,

  // outputs
  /// Outer tessellation levels.
  pub tess_level_outer: Var<[f32; 4]>,

  /// Inner tessellation levels.
  pub tess_level_inner: Var<[f32; 2]>,

  /// Array of per-vertex output variables.
  pub output: Var<[TessControlPerVertexOut]>,
}

impl TessCtrlShaderEnv {
  fn new() -> Self {
    let max_patch_vertices_in = Expr::new(ErasedExpr::new_builtin(BuiltIn::TessCtrl(
      TessCtrlBuiltIn::MaxPatchVerticesIn,
    )));
    let patch_vertices_in = Expr::new(ErasedExpr::new_builtin(BuiltIn::TessCtrl(
      TessCtrlBuiltIn::PatchVerticesIn,
    )));
    let primitive_id = Expr::new(ErasedExpr::new_builtin(BuiltIn::TessCtrl(
      TessCtrlBuiltIn::PrimitiveID,
    )));
    let invocation_id = Expr::new(ErasedExpr::new_builtin(BuiltIn::TessCtrl(
      TessCtrlBuiltIn::InvocationID,
    )));
    let input = Expr::new(ErasedExpr::new_builtin(BuiltIn::TessCtrl(
      TessCtrlBuiltIn::In,
    )));
    let tess_level_outer = Var::new(ScopedHandle::BuiltIn(BuiltIn::TessCtrl(
      TessCtrlBuiltIn::TessellationLevelOuter,
    )));
    let tess_level_inner = Var::new(ScopedHandle::BuiltIn(BuiltIn::TessCtrl(
      TessCtrlBuiltIn::TessellationLevelInner,
    )));
    let output = Var::new(ScopedHandle::BuiltIn(BuiltIn::TessCtrl(
      TessCtrlBuiltIn::Out,
    )));

    Self {
      max_patch_vertices_in,
      patch_vertices_in,
      primitive_id,
      invocation_id,
      input,
      tess_level_outer,
      tess_level_inner,
      output,
    }
  }
}

/// Read-only, input tessellation control shader environment.
#[derive(Debug)]
pub struct TessControlPerVertexIn;

impl Expr<TessControlPerVertexIn> {
  ///
  pub fn position(&self) -> Expr<V4<f32>> {
    let erased = ErasedExpr::Field {
      object: Box::new(self.erased.clone()),
      field: Box::new(ErasedExpr::new_builtin(BuiltIn::TessCtrl(
        TessCtrlBuiltIn::Position,
      ))),
    };

    Expr::new(erased)
  }

  pub fn point_size(&self) -> Expr<f32> {
    let erased = ErasedExpr::Field {
      object: Box::new(self.erased.clone()),
      field: Box::new(ErasedExpr::new_builtin(BuiltIn::TessCtrl(
        TessCtrlBuiltIn::PointSize,
      ))),
    };

    Expr::new(erased)
  }

  pub fn clip_distance(&self) -> Expr<[f32]> {
    let erased = ErasedExpr::Field {
      object: Box::new(self.erased.clone()),
      field: Box::new(ErasedExpr::new_builtin(BuiltIn::TessCtrl(
        TessCtrlBuiltIn::ClipDistance,
      ))),
    };

    Expr::new(erased)
  }

  pub fn cull_distance(&self) -> Expr<[f32]> {
    let erased = ErasedExpr::Field {
      object: Box::new(self.erased.clone()),
      field: Box::new(ErasedExpr::new_builtin(BuiltIn::TessCtrl(
        TessCtrlBuiltIn::CullDistance,
      ))),
    };

    Expr::new(erased)
  }
}

/// Output tessellation control shader environment.
#[derive(Debug)]
pub struct TessControlPerVertexOut(());

impl Expr<TessControlPerVertexOut> {
  /// 4D position of the verte.
  pub fn position(&self) -> Var<V4<f32>> {
    let expr = ErasedExpr::Field {
      object: Box::new(self.erased.clone()),
      field: Box::new(ErasedExpr::new_builtin(BuiltIn::TessCtrl(
        TessCtrlBuiltIn::Position,
      ))),
    };

    Var(Expr::new(expr))
  }

  /// Point size of the vertex.
  pub fn point_size(&self) -> Var<f32> {
    let expr = ErasedExpr::Field {
      object: Box::new(self.erased.clone()),
      field: Box::new(ErasedExpr::new_builtin(BuiltIn::TessCtrl(
        TessCtrlBuiltIn::PointSize,
      ))),
    };

    Var(Expr::new(expr))
  }

  /// Clip distances to user-defined planes.
  pub fn clip_distance(&self) -> Var<[f32]> {
    let expr = ErasedExpr::Field {
      object: Box::new(self.erased.clone()),
      field: Box::new(ErasedExpr::new_builtin(BuiltIn::TessCtrl(
        TessCtrlBuiltIn::ClipDistance,
      ))),
    };

    Var(Expr::new(expr))
  }

  /// Cull distances to user-defined planes.
  pub fn cull_distance(&self) -> Var<[f32]> {
    let expr = ErasedExpr::Field {
      object: Box::new(self.erased.clone()),
      field: Box::new(ErasedExpr::new_builtin(BuiltIn::TessCtrl(
        TessCtrlBuiltIn::CullDistance,
      ))),
    };

    Var(Expr::new(expr))
  }
}

/// Tessellation evalution shader environm.nt
#[derive(Debug)]
pub struct TessEvalShaderEnv {
  // inputs
  /// Number of vertices in the current patch.
  pub patch_vertices_in: Expr<i32>,

  /// ID of the current primitive.
  pub primitive_id: Expr<i32>,

  /// Tessellation coordinates of the current vertex.
  pub tess_coord: Expr<V3<f32>>,

  /// Outer tessellation levels.
  pub tess_level_outer: Expr<[f32; 4]>,

  /// Inner tessellation levels.
  pub tess_level_inner: Expr<[f32; 2]>,

  /// Array of per-evertex expressions.
  pub input: Expr<[TessEvaluationPerVertexIn]>,

  // outputs
  /// 4D position of the vertex.
  pub position: Var<V4<f32>>,

  /// Point size of the vertex.
  pub point_size: Var<f32>,

  /// Clip distances to user-defined planes.
  pub clip_distance: Var<[f32]>,

  /// Cull distances to user-defined planes.
  pub cull_distance: Var<[f32]>,
}

impl TessEvalShaderEnv {
  fn new() -> Self {
    let patch_vertices_in = Expr::new(ErasedExpr::new_builtin(BuiltIn::TessEval(
      TessEvalBuiltIn::PatchVerticesIn,
    )));
    let primitive_id = Expr::new(ErasedExpr::new_builtin(BuiltIn::TessEval(
      TessEvalBuiltIn::PrimitiveID,
    )));
    let tess_coord = Expr::new(ErasedExpr::new_builtin(BuiltIn::TessEval(
      TessEvalBuiltIn::TessCoord,
    )));
    let tess_level_outer = Expr::new(ErasedExpr::new_builtin(BuiltIn::TessEval(
      TessEvalBuiltIn::TessellationLevelOuter,
    )));
    let tess_level_inner = Expr::new(ErasedExpr::new_builtin(BuiltIn::TessEval(
      TessEvalBuiltIn::TessellationLevelInner,
    )));
    let input = Expr::new(ErasedExpr::new_builtin(BuiltIn::TessEval(
      TessEvalBuiltIn::In,
    )));

    let position = Var::new(ScopedHandle::BuiltIn(BuiltIn::TessEval(
      TessEvalBuiltIn::Position,
    )));
    let point_size = Var::new(ScopedHandle::BuiltIn(BuiltIn::TessEval(
      TessEvalBuiltIn::PointSize,
    )));
    let clip_distance = Var::new(ScopedHandle::BuiltIn(BuiltIn::TessEval(
      TessEvalBuiltIn::ClipDistance,
    )));
    let cull_distance = Var::new(ScopedHandle::BuiltIn(BuiltIn::TessEval(
      TessEvalBuiltIn::ClipDistance,
    )));

    Self {
      patch_vertices_in,
      primitive_id,
      tess_coord,
      tess_level_outer,
      tess_level_inner,
      input,
      position,
      point_size,
      clip_distance,
      cull_distance,
    }
  }
}

/// Tessellation evaluation per-vertex expression.
#[derive(Debug)]
pub struct TessEvaluationPerVertexIn;

impl Expr<TessEvaluationPerVertexIn> {
  /// 4D position of the vertex.
  pub fn position(&self) -> Expr<V4<f32>> {
    let erased = ErasedExpr::Field {
      object: Box::new(self.erased.clone()),
      field: Box::new(ErasedExpr::new_builtin(BuiltIn::TessEval(
        TessEvalBuiltIn::Position,
      ))),
    };

    Expr::new(erased)
  }

  /// Point size of the vertex.
  pub fn point_size(&self) -> Expr<f32> {
    let erased = ErasedExpr::Field {
      object: Box::new(self.erased.clone()),
      field: Box::new(ErasedExpr::new_builtin(BuiltIn::TessEval(
        TessEvalBuiltIn::PointSize,
      ))),
    };

    Expr::new(erased)
  }

  /// Clip distances to user-defined planes.
  pub fn clip_distance(&self) -> Expr<[f32]> {
    let erased = ErasedExpr::Field {
      object: Box::new(self.erased.clone()),
      field: Box::new(ErasedExpr::new_builtin(BuiltIn::TessEval(
        TessEvalBuiltIn::ClipDistance,
      ))),
    };

    Expr::new(erased)
  }

  /// Cull distances to user-defined planes.
  pub fn cull_distance(&self) -> Expr<[f32]> {
    let erased = ErasedExpr::Field {
      object: Box::new(self.erased.clone()),
      field: Box::new(ErasedExpr::new_builtin(BuiltIn::TessEval(
        TessEvalBuiltIn::CullDistance,
      ))),
    };

    Expr::new(erased)
  }
}

/// Geometry shader environment.
#[derive(Debug)]
pub struct GeometryShaderEnv {
  // inputs
  /// Contains the index of the current primitive.
  pub primitive_id_in: Expr<i32>,

  /// ID of the current invocation of the geometry shader.
  pub invocation_id: Expr<i32>,

  /// Read-only environment for each vertices.
  pub input: Expr<[GeometryPerVertexIn]>,

  // outputs
  /// Output 4D vertex position.
  pub position: Var<V4<f32>>,

  /// Output vertex point size.
  pub point_size: Var<f32>,

  /// Output clip distances to user-defined planes.
  pub clip_distance: Var<[f32]>,

  /// Output cull distances to user-defined planes.
  pub cull_distance: Var<[f32]>,

  /// Primitive ID to write to in.
  pub primitive_id: Var<i32>,

  /// Layer to write to in.
  pub layer: Var<i32>,

  /// Viewport index to write to.
  pub viewport_index: Var<i32>,
}

impl GeometryShaderEnv {
  fn new() -> Self {
    let primitive_id_in = Expr::new(ErasedExpr::new_builtin(BuiltIn::Geometry(
      GeometryBuiltIn::PrimitiveIDIn,
    )));
    let invocation_id = Expr::new(ErasedExpr::new_builtin(BuiltIn::Geometry(
      GeometryBuiltIn::InvocationID,
    )));
    let input = Expr::new(ErasedExpr::new_builtin(BuiltIn::Geometry(
      GeometryBuiltIn::In,
    )));

    let position = Var::new(ScopedHandle::BuiltIn(BuiltIn::Geometry(
      GeometryBuiltIn::Position,
    )));
    let point_size = Var::new(ScopedHandle::BuiltIn(BuiltIn::Geometry(
      GeometryBuiltIn::PointSize,
    )));
    let clip_distance = Var::new(ScopedHandle::BuiltIn(BuiltIn::Geometry(
      GeometryBuiltIn::ClipDistance,
    )));
    let cull_distance = Var::new(ScopedHandle::BuiltIn(BuiltIn::Geometry(
      GeometryBuiltIn::CullDistance,
    )));
    let primitive_id = Var::new(ScopedHandle::BuiltIn(BuiltIn::Geometry(
      GeometryBuiltIn::PrimitiveID,
    )));
    let layer = Var::new(ScopedHandle::BuiltIn(BuiltIn::Geometry(
      GeometryBuiltIn::Layer,
    )));
    let viewport_index = Var::new(ScopedHandle::BuiltIn(BuiltIn::Geometry(
      GeometryBuiltIn::ViewportIndex,
    )));

    Self {
      primitive_id_in,
      invocation_id,
      input,
      position,
      point_size,
      clip_distance,
      cull_distance,
      primitive_id,
      layer,
      viewport_index,
    }
  }
}

/// Read-only, input geometry shader environment.
#[derive(Debug)]
pub struct GeometryPerVertexIn;

impl Expr<GeometryPerVertexIn> {
  /// Provides 4D the position of the vertex.
  pub fn position(&self) -> Expr<V4<f32>> {
    let erased = ErasedExpr::Field {
      object: Box::new(self.erased.clone()),
      field: Box::new(ErasedExpr::new_builtin(BuiltIn::Geometry(
        GeometryBuiltIn::Position,
      ))),
    };

    Expr::new(erased)
  }

  /// Provides the size point of the vertex if it’s currently being rendered in point mode.
  pub fn point_size(&self) -> Expr<f32> {
    let erased = ErasedExpr::Field {
      object: Box::new(self.erased.clone()),
      field: Box::new(ErasedExpr::new_builtin(BuiltIn::Geometry(
        GeometryBuiltIn::PointSize,
      ))),
    };

    Expr::new(erased)
  }

  /// Clip distances to user planes of the vertex.
  pub fn clip_distance(&self) -> Expr<[f32]> {
    let erased = ErasedExpr::Field {
      object: Box::new(self.erased.clone()),
      field: Box::new(ErasedExpr::new_builtin(BuiltIn::Geometry(
        GeometryBuiltIn::ClipDistance,
      ))),
    };

    Expr::new(erased)
  }

  /// Cull distances to user planes of the vertex.
  pub fn cull_distance(&self) -> Expr<[f32]> {
    let erased = ErasedExpr::Field {
      object: Box::new(self.erased.clone()),
      field: Box::new(ErasedExpr::new_builtin(BuiltIn::Geometry(
        GeometryBuiltIn::CullDistance,
      ))),
    };

    Expr::new(erased)
  }
}

/// Fragment shader environment.
///
/// This type contains everything you have access to when writing a fragment shader.
#[derive(Debug)]
pub struct FragmentShaderEnv {
  // inputs
  /// Fragment coordinate in the framebuffer.
  pub frag_coord: Expr<V4<f32>>,

  /// Whether the fragment is front-facing.
  pub front_facing: Expr<bool>,

  /// Clip distances to user planes.
  ///
  /// This is an array giving the clip distances to each of the user clip planes.
  pub clip_distance: Expr<[f32]>,

  /// Cull distances to user planes.
  ///
  /// This is an array giving the cull distances to each of the user clip planes.
  pub cull_distance: Expr<[f32]>,

  /// Contains the 2D coordinates of a fragment within a point primitive.
  pub point_coord: Expr<V2<f32>>,

  /// ID of the primitive being currently rendered.
  pub primitive_id: Expr<i32>,

  /// ID of the sample being currently rendered.
  pub sample_id: Expr<i32>,

  /// Sample 2D coordinates.
  pub sample_position: Expr<V2<f32>>,

  /// Contains the computed sample coverage mask for the current fragment.
  pub sample_mask_in: Expr<i32>,

  /// Layer the fragment will be written to.
  pub layer: Expr<i32>,

  /// Viewport index the fragment will be written to.
  pub viewport_index: Expr<i32>,

  /// Indicates whether we are in a helper invocation of a fragment shader.
  pub helper_invocation: Expr<bool>,

  // outputs
  /// Depth of the fragment.
  pub frag_depth: Var<f32>,

  /// Sample mask of the fragment.
  pub sample_mask: Var<[i32]>,
}

impl FragmentShaderEnv {
  fn new() -> Self {
    let frag_coord = Expr::new(ErasedExpr::new_builtin(BuiltIn::Fragment(
      FragmentBuiltIn::FragCoord,
    )));
    let front_facing = Expr::new(ErasedExpr::new_builtin(BuiltIn::Fragment(
      FragmentBuiltIn::FrontFacing,
    )));
    let clip_distance = Expr::new(ErasedExpr::new_builtin(BuiltIn::Fragment(
      FragmentBuiltIn::ClipDistance,
    )));
    let cull_distance = Expr::new(ErasedExpr::new_builtin(BuiltIn::Fragment(
      FragmentBuiltIn::CullDistance,
    )));
    let point_coord = Expr::new(ErasedExpr::new_builtin(BuiltIn::Fragment(
      FragmentBuiltIn::PointCoord,
    )));
    let primitive_id = Expr::new(ErasedExpr::new_builtin(BuiltIn::Fragment(
      FragmentBuiltIn::PrimitiveID,
    )));
    let sample_id = Expr::new(ErasedExpr::new_builtin(BuiltIn::Fragment(
      FragmentBuiltIn::SampleID,
    )));
    let sample_position = Expr::new(ErasedExpr::new_builtin(BuiltIn::Fragment(
      FragmentBuiltIn::SamplePosition,
    )));
    let sample_mask_in = Expr::new(ErasedExpr::new_builtin(BuiltIn::Fragment(
      FragmentBuiltIn::SampleMaskIn,
    )));
    let layer = Expr::new(ErasedExpr::new_builtin(BuiltIn::Fragment(
      FragmentBuiltIn::Layer,
    )));
    let viewport_index = Expr::new(ErasedExpr::new_builtin(BuiltIn::Fragment(
      FragmentBuiltIn::ViewportIndex,
    )));
    let helper_invocation = Expr::new(ErasedExpr::new_builtin(BuiltIn::Fragment(
      FragmentBuiltIn::HelperInvocation,
    )));

    let frag_depth = Var::new(ScopedHandle::BuiltIn(BuiltIn::Fragment(
      FragmentBuiltIn::FragDepth,
    )));
    let sample_mask = Var::new(ScopedHandle::BuiltIn(BuiltIn::Fragment(
      FragmentBuiltIn::SampleMask,
    )));

    Self {
      frag_coord,
      front_facing,
      clip_distance,
      cull_distance,
      point_coord,
      primitive_id,
      sample_id,
      sample_position,
      sample_mask_in,
      layer,
      viewport_index,
      helper_invocation,
      frag_depth,
      sample_mask,
    }
  }
}

// standard library

pub trait Trigonometry {
  fn radians(&self) -> Self;

  fn degrees(&self) -> Self;

  fn sin(&self) -> Self;

  fn cos(&self) -> Self;

  fn tan(&self) -> Self;

  fn asin(&self) -> Self;

  fn acos(&self) -> Self;

  fn atan(&self) -> Self;

  fn sinh(&self) -> Self;

  fn cosh(&self) -> Self;

  fn tanh(&self) -> Self;

  fn asinh(&self) -> Self;

  fn acosh(&self) -> Self;

  fn atanh(&self) -> Self;
}

macro_rules! impl_Trigonometry {
  ($t:ty) => {
    impl Trigonometry for Expr<$t> {
      fn radians(&self) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::Radians,
          vec![self.erased.clone()],
        ))
      }

      fn degrees(&self) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::Degrees,
          vec![self.erased.clone()],
        ))
      }

      fn sin(&self) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::Sin,
          vec![self.erased.clone()],
        ))
      }

      fn cos(&self) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::Cos,
          vec![self.erased.clone()],
        ))
      }

      fn tan(&self) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::Tan,
          vec![self.erased.clone()],
        ))
      }

      fn asin(&self) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::ASin,
          vec![self.erased.clone()],
        ))
      }

      fn acos(&self) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::ACos,
          vec![self.erased.clone()],
        ))
      }

      fn atan(&self) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::ATan,
          vec![self.erased.clone()],
        ))
      }

      fn sinh(&self) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::SinH,
          vec![self.erased.clone()],
        ))
      }

      fn cosh(&self) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::CosH,
          vec![self.erased.clone()],
        ))
      }

      fn tanh(&self) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::TanH,
          vec![self.erased.clone()],
        ))
      }

      fn asinh(&self) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::ASinH,
          vec![self.erased.clone()],
        ))
      }

      fn acosh(&self) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::ACosH,
          vec![self.erased.clone()],
        ))
      }

      fn atanh(&self) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::ATanH,
          vec![self.erased.clone()],
        ))
      }
    }
  };
}

impl_Trigonometry!(f32);
impl_Trigonometry!(V2<f32>);
impl_Trigonometry!(V3<f32>);
impl_Trigonometry!(V4<f32>);

pub trait Exponential: Sized {
  fn pow(&self, p: impl Into<Self>) -> Self;

  fn exp(&self) -> Self;

  fn exp2(&self) -> Self;

  fn log(&self) -> Self;

  fn log2(&self) -> Self;

  fn sqrt(&self) -> Self;

  fn isqrt(&self) -> Self;
}

macro_rules! impl_Exponential {
  ($t:ty) => {
    impl Exponential for Expr<$t> {
      fn pow(&self, p: impl Into<Self>) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::Pow,
          vec![self.erased.clone(), p.into().erased],
        ))
      }

      fn exp(&self) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::Exp,
          vec![self.erased.clone()],
        ))
      }

      fn exp2(&self) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::Exp2,
          vec![self.erased.clone()],
        ))
      }

      fn log(&self) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::Log,
          vec![self.erased.clone()],
        ))
      }

      fn log2(&self) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::Log2,
          vec![self.erased.clone()],
        ))
      }

      fn sqrt(&self) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::Sqrt,
          vec![self.erased.clone()],
        ))
      }

      fn isqrt(&self) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::InverseSqrt,
          vec![self.erased.clone()],
        ))
      }
    }
  };
}

impl_Exponential!(f32);
impl_Exponential!(V2<f32>);
impl_Exponential!(V3<f32>);
impl_Exponential!(V4<f32>);

pub trait Relative {
  fn abs(&self) -> Self;

  fn sign(&self) -> Self;
}

macro_rules! impl_Relative {
  ($t:ty) => {
    impl Relative for Expr<$t> {
      fn abs(&self) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::Abs,
          vec![self.erased.clone()],
        ))
      }

      fn sign(&self) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::Sign,
          vec![self.erased.clone()],
        ))
      }
    }
  };
}

impl_Relative!(i32);
impl_Relative!(V2<i32>);
impl_Relative!(V3<i32>);
impl_Relative!(V4<i32>);
impl_Relative!(f32);
impl_Relative!(V2<f32>);
impl_Relative!(V3<f32>);
impl_Relative!(V4<f32>);

pub trait Floating {
  fn floor(&self) -> Self;

  fn trunc(&self) -> Self;

  fn round(&self) -> Self;

  fn ceil(&self) -> Self;

  fn fract(&self) -> Self;
}

macro_rules! impl_Floating {
  ($t:ty) => {
    impl Floating for Expr<$t> {
      fn floor(&self) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::Floor,
          vec![self.erased.clone()],
        ))
      }

      fn trunc(&self) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::Trunc,
          vec![self.erased.clone()],
        ))
      }

      fn round(&self) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::Round,
          vec![self.erased.clone()],
        ))
      }

      fn ceil(&self) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::Ceil,
          vec![self.erased.clone()],
        ))
      }

      fn fract(&self) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::Fract,
          vec![self.erased.clone()],
        ))
      }
    }
  };
}

impl_Floating!(f32);
impl_Floating!(V2<f32>);
impl_Floating!(V3<f32>);
impl_Floating!(V4<f32>);

trait Bounded: Sized {
  fn min(&self, rhs: impl Into<Self>) -> Self;

  fn max(&self, rhs: impl Into<Self>) -> Self;

  fn clamp(&self, min_value: impl Into<Self>, max_value: impl Into<Self>) -> Self;
}

macro_rules! impl_Bounded {
  ($t:ty) => {
    impl Bounded for Expr<$t> {
      fn min(&self, rhs: impl Into<Self>) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::Min,
          vec![self.erased.clone(), rhs.into().erased],
        ))
      }

      fn max(&self, rhs: impl Into<Self>) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::Max,
          vec![self.erased.clone(), rhs.into().erased],
        ))
      }

      fn clamp(&self, min_value: impl Into<Self>, max_value: impl Into<Self>) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::Clamp,
          vec![
            self.erased.clone(),
            min_value.into().erased,
            max_value.into().erased,
          ],
        ))
      }
    }
  };
}

impl_Bounded!(i32);
impl_Bounded!(V2<i32>);
impl_Bounded!(V3<i32>);
impl_Bounded!(V4<i32>);

impl_Bounded!(u32);
impl_Bounded!(V2<u32>);
impl_Bounded!(V3<u32>);
impl_Bounded!(V4<u32>);

impl_Bounded!(f32);
impl_Bounded!(V2<f32>);
impl_Bounded!(V3<f32>);
impl_Bounded!(V4<f32>);

impl_Bounded!(bool);
impl_Bounded!(V2<bool>);
impl_Bounded!(V3<bool>);
impl_Bounded!(V4<bool>);

pub trait Mix<RHS>: Sized {
  fn mix(&self, y: impl Into<Self>, a: RHS) -> Self;

  fn step(&self, edge: RHS) -> Self;

  fn smooth_step(&self, edge_a: RHS, edge_b: RHS) -> Self;
}

macro_rules! impl_Mix {
  ($t:ty, $q:ty) => {
    impl Mix<Expr<$q>> for Expr<$t> {
      fn mix(&self, y: impl Into<Self>, a: Expr<$q>) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::Mix,
          vec![self.erased.clone(), y.into().erased, a.erased],
        ))
      }

      fn step(&self, edge: Expr<$q>) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::Step,
          vec![self.erased.clone(), edge.erased],
        ))
      }

      fn smooth_step(&self, edge_a: Expr<$q>, edge_b: Expr<$q>) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::SmoothStep,
          vec![self.erased.clone(), edge_a.erased, edge_b.erased],
        ))
      }
    }
  };
}

impl_Mix!(f32, f32);
impl_Mix!(V2<f32>, f32);
impl_Mix!(V2<f32>, V2<f32>);

impl_Mix!(V3<f32>, f32);
impl_Mix!(V3<f32>, V3<f32>);

impl_Mix!(V4<f32>, f32);
impl_Mix!(V4<f32>, V4<f32>);

pub trait FloatingExt {
  type BoolExpr;

  fn is_nan(&self) -> Self::BoolExpr;

  fn is_inf(&self) -> Self::BoolExpr;
}

macro_rules! impl_FloatingExt {
  ($t:ty, $bool_expr:ty) => {
    impl FloatingExt for Expr<$t> {
      type BoolExpr = Expr<$bool_expr>;

      fn is_nan(&self) -> Self::BoolExpr {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::IsNan,
          vec![self.erased.clone()],
        ))
      }

      fn is_inf(&self) -> Self::BoolExpr {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::IsInf,
          vec![self.erased.clone()],
        ))
      }
    }
  };
}

impl_FloatingExt!(f32, bool);
impl_FloatingExt!(V2<f32>, V2<bool>);
impl_FloatingExt!(V3<f32>, V3<bool>);
impl_FloatingExt!(V4<f32>, V4<bool>);

pub trait Geometry: Sized {
  type LengthExpr;

  fn length(&self) -> Self::LengthExpr;

  fn distance(&self, other: impl Into<Self>) -> Self::LengthExpr;

  fn dot(&self, other: impl Into<Self>) -> Self::LengthExpr;

  fn cross(&self, other: impl Into<Self>) -> Self;

  fn normalize(&self) -> Self;

  fn face_forward(&self, normal: impl Into<Self>, reference: impl Into<Self>) -> Self;

  fn reflect(&self, normal: impl Into<Self>) -> Self;

  fn refract(&self, normal: impl Into<Self>, eta: impl Into<Expr<f32>>) -> Self;
}

macro_rules! impl_Geometry {
  ($t:ty, $l:ty) => {
    impl Geometry for Expr<$t> {
      type LengthExpr = Expr<$l>;

      fn length(&self) -> Self::LengthExpr {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::Length,
          vec![self.erased.clone()],
        ))
      }

      fn distance(&self, other: impl Into<Self>) -> Self::LengthExpr {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::Distance,
          vec![self.erased.clone(), other.into().erased],
        ))
      }

      fn dot(&self, other: impl Into<Self>) -> Self::LengthExpr {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::Dot,
          vec![self.erased.clone(), other.into().erased],
        ))
      }

      fn cross(&self, other: impl Into<Self>) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::Cross,
          vec![self.erased.clone(), other.into().erased],
        ))
      }

      fn normalize(&self) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::Normalize,
          vec![self.erased.clone()],
        ))
      }

      fn face_forward(&self, normal: impl Into<Self>, reference: impl Into<Self>) -> Self {
        // note: this function call is super weird as the normal and incident (i.e. self) arguments are swapped
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::FaceForward,
          vec![
            normal.into().erased,
            self.erased.clone(),
            reference.into().erased,
          ],
        ))
      }

      fn reflect(&self, normal: impl Into<Self>) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::Reflect,
          vec![self.erased.clone(), normal.into().erased],
        ))
      }

      fn refract(&self, normal: impl Into<Self>, eta: impl Into<Expr<f32>>) -> Self {
        Expr::new(ErasedExpr::FunCall(
          ErasedFunHandle::Refract,
          vec![self.erased.clone(), normal.into().erased, eta.into().erased],
        ))
      }
    }
  };
}

impl_Geometry!(V2<f32>, f32);
impl_Geometry!(V3<f32>, f32);
impl_Geometry!(V4<f32>, f32);

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

  #[test]
  fn expr_lit() {
    assert_eq!(lit!(true).erased, ErasedExpr::LitBool(true));
    assert_eq!(lit![1, 2].erased, ErasedExpr::LitInt2([1, 2]));
  }

  #[test]
  fn expr_unary() {
    let mut scope = Scope::<()>::new(0);

    let a = !lit!(true);
    let b = -lit!(3i32);
    let c = scope.var(17);

    assert_eq!(
      a.erased,
      ErasedExpr::Not(Box::new(ErasedExpr::LitBool(true)))
    );
    assert_eq!(b.erased, ErasedExpr::Neg(Box::new(ErasedExpr::LitInt(3))));
    assert_eq!(c.erased, ErasedExpr::Var(ScopedHandle::fun_var(0, 0)));
  }

  #[test]
  fn expr_binary() {
    let a = lit!(1i32) + lit!(2);
    let b = lit!(1i32) + 2;

    assert_eq!(a.erased, b.erased);
    assert_eq!(
      a.erased,
      ErasedExpr::Add(
        Box::new(ErasedExpr::LitInt(1)),
        Box::new(ErasedExpr::LitInt(2)),
      )
    );
    assert_eq!(
      b.erased,
      ErasedExpr::Add(
        Box::new(ErasedExpr::LitInt(1)),
        Box::new(ErasedExpr::LitInt(2)),
      )
    );

    let a = lit!(1i32) - lit!(2);
    let b = lit!(1i32) - 2;

    assert_eq!(a.erased, b.erased);
    assert_eq!(
      a.erased,
      ErasedExpr::Sub(
        Box::new(ErasedExpr::LitInt(1)),
        Box::new(ErasedExpr::LitInt(2)),
      )
    );
    assert_eq!(
      b.erased,
      ErasedExpr::Sub(
        Box::new(ErasedExpr::LitInt(1)),
        Box::new(ErasedExpr::LitInt(2)),
      )
    );

    let a = lit!(1i32) * lit!(2);
    let b = lit!(1i32) * 2;

    assert_eq!(a.erased, b.erased);
    assert_eq!(
      a.erased,
      ErasedExpr::Mul(
        Box::new(ErasedExpr::LitInt(1)),
        Box::new(ErasedExpr::LitInt(2)),
      )
    );
    assert_eq!(
      b.erased,
      ErasedExpr::Mul(
        Box::new(ErasedExpr::LitInt(1)),
        Box::new(ErasedExpr::LitInt(2)),
      )
    );

    let a = lit!(1i32) / lit!(2);
    let b = lit!(1i32) / 2;

    assert_eq!(a.erased, b.erased);
    assert_eq!(
      a.erased,
      ErasedExpr::Div(
        Box::new(ErasedExpr::LitInt(1)),
        Box::new(ErasedExpr::LitInt(2)),
      )
    );
    assert_eq!(
      b.erased,
      ErasedExpr::Div(
        Box::new(ErasedExpr::LitInt(1)),
        Box::new(ErasedExpr::LitInt(2)),
      )
    );
  }

  #[test]
  fn expr_ref_inference() {
    let a = lit!(1i32);
    let b = a.clone() + 1;
    let c = a + 1;

    assert_eq!(b.erased, c.erased);
  }

  #[test]
  fn expr_var() {
    let mut scope = Scope::<()>::new(0);

    let x = scope.var(0);
    let y = scope.var(1u32);
    let z = scope.var(lit![false, true, false]);

    assert_eq!(x.erased, ErasedExpr::Var(ScopedHandle::fun_var(0, 0)));
    assert_eq!(y.erased, ErasedExpr::Var(ScopedHandle::fun_var(0, 1)));
    assert_eq!(
      z.erased,
      ErasedExpr::Var(ScopedHandle::fun_var(0, 2).into())
    );
    assert_eq!(scope.erased.instructions.len(), 3);
    assert_eq!(
      scope.erased.instructions[0],
      ScopeInstr::VarDecl {
        ty: Type {
          prim_ty: PrimType::Int(Dim::Scalar),
          array_dims: Vec::new(),
        },
        handle: ScopedHandle::fun_var(0, 0),
        init_value: ErasedExpr::LitInt(0),
      }
    );
    assert_eq!(
      scope.erased.instructions[1],
      ScopeInstr::VarDecl {
        ty: Type {
          prim_ty: PrimType::UInt(Dim::Scalar),
          array_dims: Vec::new(),
        },
        handle: ScopedHandle::fun_var(0, 1),
        init_value: ErasedExpr::LitUInt(1),
      }
    );
    assert_eq!(
      scope.erased.instructions[2],
      ScopeInstr::VarDecl {
        ty: Type {
          prim_ty: PrimType::Bool(Dim::D3),
          array_dims: Vec::new(),
        },
        handle: ScopedHandle::fun_var(0, 2),
        init_value: ErasedExpr::LitBool3([false, true, false]),
      }
    );
  }

  #[test]
  fn min_max_clamp() {
    let a = lit!(1i32);
    let b = lit!(2);
    let c = lit!(3);

    assert_eq!(
      a.min(&b).erased,
      ErasedExpr::FunCall(
        ErasedFunHandle::Min,
        vec![ErasedExpr::LitInt(1), ErasedExpr::LitInt(2)],
      )
    );

    assert_eq!(
      a.max(&b).erased,
      ErasedExpr::FunCall(
        ErasedFunHandle::Max,
        vec![ErasedExpr::LitInt(1), ErasedExpr::LitInt(2)],
      )
    );

    assert_eq!(
      a.clamp(b, c).erased,
      ErasedExpr::FunCall(
        ErasedFunHandle::Clamp,
        vec![
          ErasedExpr::LitInt(1),
          ErasedExpr::LitInt(2),
          ErasedExpr::LitInt(3)
        ],
      )
    );
  }

  #[test]
  fn fun0() {
    let mut shader = ShaderBuilder::new();
    let fun = shader.fun(|s: &mut Scope<()>| {
      let _x = s.var(3);
    });

    assert_eq!(fun.erased, ErasedFunHandle::UserDefined(0));

    match shader.decls[0] {
      ShaderDecl::FunDef(0, ref fun) => {
        assert_eq!(fun.ret, ErasedReturn::Void);
        assert_eq!(fun.args, vec![]);
        assert_eq!(fun.scope.instructions.len(), 1);
        assert_eq!(
          fun.scope.instructions[0],
          ScopeInstr::VarDecl {
            ty: Type {
              prim_ty: PrimType::Int(Dim::Scalar),
              array_dims: Vec::new(),
            },
            handle: ScopedHandle::fun_var(0, 0),
            init_value: ErasedExpr::LitInt(3),
          }
        )
      }
      _ => panic!("wrong type"),
    }
  }

  #[test]
  fn fun1() {
    let mut shader = ShaderBuilder::new();
    let fun = shader.fun(|f: &mut Scope<Expr<i32>>, _arg: Expr<i32>| {
      let x = f.var(lit!(3i32));
      x.into()
    });

    assert_eq!(fun.erased, ErasedFunHandle::UserDefined(0));

    match shader.decls[0] {
      ShaderDecl::FunDef(0, ref fun) => {
        assert_eq!(
          fun.ret,
          ErasedReturn::Expr(i32::ty(), ErasedExpr::Var(ScopedHandle::fun_var(0, 0)))
        );
        assert_eq!(
          fun.args,
          vec![Type {
            prim_ty: PrimType::Int(Dim::Scalar),
            array_dims: Vec::new(),
          }]
        );
        assert_eq!(fun.scope.instructions.len(), 1);
        assert_eq!(
          fun.scope.instructions[0],
          ScopeInstr::VarDecl {
            ty: Type {
              prim_ty: PrimType::Int(Dim::Scalar),
              array_dims: Vec::new(),
            },
            handle: ScopedHandle::fun_var(0, 0),
            init_value: ErasedExpr::LitInt(3),
          }
        )
      }
      _ => panic!("wrong type"),
    }
  }

  #[test]
  fn swizzling() {
    let mut scope = Scope::<()>::new(0);
    let foo = scope.var(lit![1, 2]);
    let foo_xy = sw!(foo, .x.y);
    let foo_xx = sw!(foo, .x.x);

    assert_eq!(
      foo_xy.erased,
      ErasedExpr::Swizzle(
        Box::new(ErasedExpr::Var(ScopedHandle::fun_var(0, 0))),
        Swizzle::D2(SwizzleSelector::X, SwizzleSelector::Y),
      )
    );

    assert_eq!(
      foo_xx.erased,
      ErasedExpr::Swizzle(
        Box::new(ErasedExpr::Var(ScopedHandle::fun_var(0, 0))),
        Swizzle::D2(SwizzleSelector::X, SwizzleSelector::X),
      )
    );
  }

  #[test]
  fn when() {
    let mut s = Scope::<Expr<V4<f32>>>::new(0);

    let x = s.var(1);
    s.when(x.eq(lit!(2)), |s| {
      let y = s.var(lit![1., 2., 3., 4.]);
      s.leave(y);
    })
    .or_else(x.eq(lit!(0)), |s| s.leave(lit![0., 0., 0., 0.]))
    .or(|_| ());

    assert_eq!(s.erased.instructions.len(), 4);

    assert_eq!(
      s.erased.instructions[0],
      ScopeInstr::VarDecl {
        ty: Type {
          prim_ty: PrimType::Int(Dim::Scalar),
          array_dims: Vec::new(),
        },
        handle: ScopedHandle::fun_var(0, 0),
        init_value: ErasedExpr::LitInt(1),
      }
    );

    // if
    let mut scope = ErasedScope::new(1);
    scope.next_var = 1;
    scope.instructions.push(ScopeInstr::VarDecl {
      ty: Type {
        prim_ty: PrimType::Float(Dim::D4),
        array_dims: Vec::new(),
      },
      handle: ScopedHandle::fun_var(1, 0),
      init_value: ErasedExpr::LitFloat4([1., 2., 3., 4.]),
    });
    scope
      .instructions
      .push(ScopeInstr::Return(ErasedReturn::Expr(
        V4::<f32>::ty(),
        ErasedExpr::Var(ScopedHandle::fun_var(1, 0)),
      )));

    assert_eq!(
      s.erased.instructions[1],
      ScopeInstr::If {
        condition: ErasedExpr::Eq(
          Box::new(ErasedExpr::Var(ScopedHandle::fun_var(0, 0))),
          Box::new(ErasedExpr::LitInt(2)),
        ),
        scope,
      }
    );

    // else if
    let mut scope = ErasedScope::new(1);
    scope
      .instructions
      .push(ScopeInstr::Return(ErasedReturn::Expr(
        V4::<f32>::ty(),
        ErasedExpr::LitFloat4([0., 0., 0., 0.]),
      )));

    assert_eq!(
      s.erased.instructions[2],
      ScopeInstr::ElseIf {
        condition: ErasedExpr::Eq(
          Box::new(ErasedExpr::Var(ScopedHandle::fun_var(0, 0))),
          Box::new(ErasedExpr::LitInt(0)),
        ),
        scope,
      }
    );

    // else
    assert_eq!(
      s.erased.instructions[3],
      ScopeInstr::Else {
        scope: ErasedScope::new(1)
      }
    );
  }

  #[test]
  fn for_loop() {
    let mut scope: Scope<Expr<i32>> = Scope::new(0);

    scope.loop_for(
      0,
      |a| a.lt(lit!(10)),
      |a| a + 1,
      |s, a| {
        s.leave(a);
      },
    );

    assert_eq!(scope.erased.instructions.len(), 1);

    let mut loop_scope = ErasedScope::new(1);
    loop_scope.next_var = 1;
    loop_scope.instructions.push(ScopeInstr::VarDecl {
      ty: Type {
        prim_ty: PrimType::Int(Dim::Scalar),
        array_dims: Vec::new(),
      },
      handle: ScopedHandle::fun_var(1, 0),
      init_value: ErasedExpr::LitInt(0),
    });
    loop_scope
      .instructions
      .push(ScopeInstr::Return(ErasedReturn::Expr(
        i32::ty(),
        ErasedExpr::Var(ScopedHandle::fun_var(1, 0)),
      )));

    assert_eq!(
      scope.erased.instructions[0],
      ScopeInstr::For {
        init_ty: i32::ty(),
        init_handle: ScopedHandle::fun_var(1, 0),
        init_expr: ErasedExpr::Var(ScopedHandle::fun_var(1, 0)),
        condition: ErasedExpr::Lt(
          Box::new(ErasedExpr::Var(ScopedHandle::fun_var(1, 0))),
          Box::new(ErasedExpr::LitInt(10)),
        ),
        post_expr: ErasedExpr::Add(
          Box::new(ErasedExpr::Var(ScopedHandle::fun_var(1, 0))),
          Box::new(ErasedExpr::LitInt(1)),
        ),
        scope: loop_scope,
      }
    );
  }

  #[test]
  fn while_loop() {
    let mut scope: Scope<Expr<i32>> = Scope::new(0);

    scope.loop_while(lit!(1).lt(lit!(2)), LoopScope::loop_continue);

    let mut loop_scope = ErasedScope::new(1);
    loop_scope.instructions.push(ScopeInstr::Continue);

    assert_eq!(scope.erased.instructions.len(), 1);
    assert_eq!(
      scope.erased.instructions[0],
      ScopeInstr::While {
        condition: ErasedExpr::Lt(
          Box::new(ErasedExpr::LitInt(1)),
          Box::new(ErasedExpr::LitInt(2)),
        ),
        scope: loop_scope,
      }
    );
  }

  #[test]
  fn vertex_id_commutative() {
    let vertex = VertexShaderEnv::new();

    let x = lit!(1);
    let _ = &vertex.vertex_id + &x;
    let _ = x + vertex.vertex_id;
  }

  #[test]
  fn array_lookup() {
    let vertex = VertexShaderEnv::new();
    let clip_dist_expr = vertex.clip_distance.at(1);

    assert_eq!(
      clip_dist_expr.erased,
      ErasedExpr::ArrayLookup {
        object: Box::new(vertex.clip_distance.erased.clone()),
        index: Box::new(ErasedExpr::LitInt(1)),
      }
    );
  }

  #[test]
  fn array_creation() {
    let _ = Expr::from([1, 2, 3]);
    let _ = Expr::from(&[1, 2, 3]);
    let two_d = Expr::from([[1, 2], [3, 4]]);

    assert_eq!(
      two_d.erased,
      ErasedExpr::Array(
        <[[i32; 2]; 2] as ToType>::ty(),
        vec![
          ErasedExpr::Array(
            <[i32; 2] as ToType>::ty(),
            vec![ErasedExpr::LitInt(1), ErasedExpr::LitInt(2)]
          ),
          ErasedExpr::Array(
            <[i32; 2] as ToType>::ty(),
            vec![ErasedExpr::LitInt(3), ErasedExpr::LitInt(4)]
          )
        ]
      )
    );
  }

  #[test]
  fn vec3_ctor() {
    let xy = lit!(1., 2.);
    let xyz2 = vec3!(xy, lit!(3.));
    let xyz3 = vec3!(lit!(1.), lit!(2.), lit!(3.));

    assert_eq!(
      xyz2.erased,
      ErasedExpr::FunCall(ErasedFunHandle::Vec3, vec![xy.erased, lit!(3.).erased])
    );

    assert_eq!(
      xyz3.erased,
      ErasedExpr::FunCall(
        ErasedFunHandle::Vec3,
        vec![lit!(1.).erased, lit!(2.).erased, lit!(3.).erased]
      )
    );
  }

  #[test]
  fn vec4_ctor() {
    let xy: Expr<V2<f32>> = lit!(1., 2.);
    let xyzw22 = vec4!(xy, xy);
    let xyzw211 = vec4!(xy, 3., 4.);
    let xyzw31 = vec4!(vec3!(1., 2., 3.), 4.);
    let xyzw4 = vec4!(1., 2., 3., 4.);

    assert_eq!(
      xyzw22.erased,
      ErasedExpr::FunCall(
        ErasedFunHandle::Vec4,
        vec![xy.clone().erased, xy.clone().erased]
      )
    );

    assert_eq!(
      xyzw211.erased,
      ErasedExpr::FunCall(
        ErasedFunHandle::Vec4,
        vec![xy.clone().erased, lit!(3.).erased, lit!(4.).erased]
      )
    );

    assert_eq!(
      xyzw31.erased,
      ErasedExpr::FunCall(
        ErasedFunHandle::Vec4,
        vec![vec3!(1., 2., 3.).erased, lit!(4.).erased]
      )
    );

    assert_eq!(
      xyzw4.erased,
      ErasedExpr::FunCall(
        ErasedFunHandle::Vec4,
        vec![
          lit!(1.).erased,
          lit!(2.).erased,
          lit!(3.).erased,
          lit!(4.).erased
        ]
      )
    );
  }
}