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
//! Dyon runtime.

use std::sync::Arc;
use std::collections::HashMap;
use rand;
use range::Range;

use ast;
use intrinsics;
use embed;

use FnIndex;
use Module;
use Variable;
use UnsafeRef;
use TINVOTS;

mod for_n;
mod for_in;

/// Which side an expression is evaluated.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Side {
    /// Whether to insert key in object when missing.
    LeftInsert(bool),
    /// Evaluating right side of assignment.
    Right
}

/// Stores return flow, used to continue executing, return, break out of loop or continue loop.
#[derive(Debug)]
pub enum Flow {
    /// Continues execution.
    Continue,
    /// Return from function.
    Return,
    /// Break loop, with optional label.
    Break(Option<Arc<String>>),
    /// Continue loop, with optional label.
    ContinueLoop(Option<Arc<String>>),
}

/// Stores function calls.
#[derive(Debug)]
pub struct Call {
    // was .0
    fn_name: Arc<String>,
    /// The index of the relative function in module.
    pub(crate) index: usize,
    file: Option<Arc<String>>,
    // was .1
    stack_len: usize,
    // was .2
    local_len: usize,
    current_len: usize,
}

lazy_static! {
    pub(crate) static ref TEXT_TYPE: Arc<String> = Arc::new("string".into());
    pub(crate) static ref F64_TYPE: Arc<String> = Arc::new("number".into());
    pub(crate) static ref VEC4_TYPE: Arc<String> = Arc::new("vec4".into());
    pub(crate) static ref MAT4_TYPE: Arc<String> = Arc::new("mat4".into());
    pub(crate) static ref RETURN_TYPE: Arc<String> = Arc::new("return".into());
    pub(crate) static ref BOOL_TYPE: Arc<String> = Arc::new("boolean".into());
    pub(crate) static ref OBJECT_TYPE: Arc<String> = Arc::new("object".into());
    pub(crate) static ref LINK_TYPE: Arc<String> = Arc::new("link".into());
    pub(crate) static ref ARRAY_TYPE: Arc<String> = Arc::new("array".into());
    pub(crate) static ref UNSAFE_REF_TYPE: Arc<String> = Arc::new("unsafe_ref".into());
    pub(crate) static ref REF_TYPE: Arc<String> = Arc::new("ref".into());
    pub(crate) static ref RUST_OBJECT_TYPE: Arc<String> = Arc::new("rust_object".into());
    pub(crate) static ref OPTION_TYPE: Arc<String> = Arc::new("option".into());
    pub(crate) static ref RESULT_TYPE: Arc<String> = Arc::new("result".into());
    pub(crate) static ref THREAD_TYPE: Arc<String> = Arc::new("thread".into());
    pub(crate) static ref CLOSURE_TYPE: Arc<String> = Arc::new("closure".into());
    pub(crate) static ref IN_TYPE: Arc<String> = Arc::new("in".into());
}

/// Stores data needed for running a Dyon program.
pub struct Runtime {
    /// Stores variables on the stack.
    pub stack: Vec<Variable>,
    /// name, file, stack_len, local_len.
    pub call_stack: Vec<Call>,
    /// Stores stack of locals.
    pub local_stack: Vec<(Arc<String>, usize)>,
    /// Stores stack of current objects.
    ///
    /// When a current object is used, the runtime searches backwards
    /// until it finds the last current variable with the name.
    pub current_stack: Vec<(Arc<String>, usize)>,
    ret: Arc<String>,
    pub(crate) rng: rand::rngs::StdRng,
}

impl Default for Runtime {
    fn default() -> Runtime {Runtime::new()}
}

#[inline(always)]
fn resolve<'a>(stack: &'a [Variable], var: &'a Variable) -> &'a Variable {
    match *var {
        Variable::Ref(ind) => &stack[ind],
        _ => var
    }
}

// Looks up an item from a variable property.
fn item_lookup(
    module: &Module,
    var: *mut Variable,
    stack: &mut [Variable],
    call_stack: &[Call],
    prop: &ast::Id,
    start_stack_len: usize,
    expr_j: &mut usize,
    insert: bool, // Whether to insert key in object.
    last: bool,   // Whether it is the last property.
) -> Result<*mut Variable, String> {
    use ast::Id;
    use std::collections::hash_map::Entry;

    unsafe {
        match *var {
            Variable::Object(ref mut obj) => {
                let id = match *prop {
                    Id::String(_, ref id) => id.clone(),
                    Id::Expression(_) => {
                        let id = start_stack_len + *expr_j;
                        // Resolve reference of computed expression.
                        let id = if let Variable::Ref(ref_id) = stack[id] {
                                ref_id
                            } else {
                                id
                            };
                        match stack[id] {
                            Variable::Text(ref id) => {
                                *expr_j += 1;
                                id.clone()
                            }
                            _ => return Err(module.error_fnindex(prop.source_range(),
                                &format!("{}\nExpected string",
                                    stack_trace(call_stack)),
                                    call_stack.last().unwrap().index))
                        }
                    }
                    Id::F64(range, _) => return Err(module.error_fnindex(range,
                        &format!("{}\nExpected string",
                            stack_trace(call_stack)),
                            call_stack.last().unwrap().index))
                };
                let v = match Arc::make_mut(obj).entry(id.clone()) {
                    Entry::Vacant(vac) => {
                        if insert && last {
                            // Insert a key to overwrite with new value.
                            vac.insert(Variable::Return)
                        } else {
                            return Err(module.error_fnindex(prop.source_range(),
                                &format!("{}\nObject has no key `{}`",
                                    stack_trace(call_stack), id),
                                    call_stack.last().unwrap().index));
                        }
                    }
                    Entry::Occupied(v) => v.into_mut()
                };
                // Resolve reference.
                if let Variable::Ref(id) = *v {
                    // Do not resolve if last, because references should be
                    // copy-on-write.
                    if last {
                        Ok(v)
                    } else {
                        Ok(&mut stack[id])
                    }
                } else {
                    Ok(v)
                }
            }
            Variable::Array(ref mut arr) => {
                let id = match *prop {
                    Id::F64(_, id) => id,
                    Id::Expression(_) => {
                        let id = start_stack_len + *expr_j;
                        // Resolve reference of computed expression.
                        let id = if let Variable::Ref(ref_id) = stack[id] {
                                ref_id
                            } else {
                                id
                            };
                        let (prev_stack, stack) = stack.split_at_mut(id);
                        match stack[0] {
                            Variable::F64(id, _) => {
                                *expr_j += 1;
                                id
                            }
                            Variable::Array(ref indices) => {
                                // Use indices in array.
                                //
                                // This uses an unsafe pointer safely, because an array lookup
                                // will always point to some object on the heap or earlier stack.
                                // The safety rule of references is enforced by the runtime,
                                // guarded by the lifetime checker, but can not be checked
                                // at compile time.
                                //
                                // `[0, 1]` are indices to look up `b` in `[[a, b], [c, d]]`.
                                //   ^  ^---- to `b` in `[a, b]`.
                                //   \---- points to first array `[a, b]`.
                                let mut arr: *mut Vec<Variable> = Arc::make_mut(arr);
                                let n = indices.len();
                                for (i, ind) in indices.iter().enumerate() {
                                    let id = match ind {
                                        &Variable::F64(id, _) => id,
                                        &Variable::Ref(x) =>
                                            if let &Variable::F64(id, _) = &prev_stack[x] {id}
                                            else {break}
                                        _ => {break}
                                    };
                                    let v = match (*arr).get_mut(id as usize) {
                                        None => return Err(module.error_fnindex(prop.source_range(),
                                                           &format!("{}\nOut of bounds `{}`",
                                                                    stack_trace(call_stack), id),
                                                                    call_stack.last().unwrap().index)),
                                        Some(x) => x
                                    };
                                    if i + 1 == n {
                                        // Resolve reference.
                                        return if let Variable::Ref(id) = *v {
                                            // Do not resolve if last, because references should be
                                            // copy-on-write.
                                            if last {
                                                Ok(v)
                                            } else {
                                                Ok(&mut prev_stack[id])
                                            }
                                        } else {
                                            Ok(v)
                                        };
                                    }
                                    match *v {
                                        Variable::Array(ref mut new_arr) => {
                                            arr = Arc::make_mut(new_arr);
                                        }
                                        Variable::Ref(x) =>
                                            if let Variable::Array(ref mut new_arr) = prev_stack[x] {
                                                arr = Arc::make_mut(new_arr);
                                            } else {
                                                break;
                                            }
                                        _ => break,
                                    }
                                }
                                return Err(module.error_fnindex(prop.source_range(),
                                            &format!("{}\nArray of indices did not match lookup array",
                                            stack_trace(call_stack)),
                                            call_stack.last().unwrap().index))
                            }
                            _ => return Err(module.error_fnindex(prop.source_range(),
                                            &format!("{}\nExpected number",
                                                stack_trace(call_stack)),
                                                call_stack.last().unwrap().index))
                        }
                    }
                    Id::String(range, _) => return Err(module.error_fnindex(range,
                        &format!("{}\nExpected number",
                            stack_trace(call_stack)),
                            call_stack.last().unwrap().index))
                };
                let v = match Arc::make_mut(arr).get_mut(id as usize) {
                    None => return Err(module.error_fnindex(prop.source_range(),
                                       &format!("{}\nOut of bounds `{}`",
                                                stack_trace(call_stack), id),
                                                call_stack.last().unwrap().index)),
                    Some(x) => x
                };
                // Resolve reference.
                if let Variable::Ref(id) = *v {
                    // Do not resolve if last, because references should be
                    // copy-on-write.
                    if last {
                        Ok(v)
                    } else {
                        Ok(&mut stack[id])
                    }
                } else {
                    Ok(v)
                }
            }
            _ => Err(module.error_fnindex(prop.source_range(),
                            &format!("{}\nLook up requires object or array",
                            stack_trace(call_stack)),
                            call_stack.last().unwrap().index))
        }
    }
}

impl Runtime {
    /// Creates a new Runtime.
    pub fn new() -> Runtime {
        use rand::FromEntropy;

        Runtime {
            stack: vec![],
            call_stack: vec![],
            local_stack: vec![],
            current_stack: vec![],
            ret: Arc::new("return".into()),
            rng: rand::rngs::StdRng::from_entropy(),
        }
    }

    /// Pops variable from stack.
    pub fn pop<T: embed::PopVariable>(&mut self) -> Result<T, String> {
        let v = self.stack.pop().unwrap_or_else(|| panic!(TINVOTS));
        T::pop_var(self, self.resolve(&v))
    }

    /// Pops 4D vector from stack.
    pub fn pop_vec4<T: embed::ConvertVec4>(&mut self) -> Result<T, String> {
        let v = self.stack.pop().unwrap_or_else(|| panic!(TINVOTS));
        match self.resolve(&v) {
            &Variable::Vec4(val) => Ok(T::from(val)),
            x => Err(self.expected(x, "vec4"))
        }
    }

    /// Pops 4D matrix from stack.
    pub fn pop_mat4<T: embed::ConvertMat4>(&mut self) -> Result<T, String> {
        let v = self.stack.pop().unwrap_or_else(|| panic!(TINVOTS));
        match self.resolve(&v) {
            &Variable::Mat4(ref val) => Ok(T::from(**val)),
            x => Err(self.expected(x, "mat4"))
        }
    }

    /// Gets variable.
    pub fn var<T: embed::PopVariable>(&self, var: &Variable) -> Result<T, String> {
        T::pop_var(self, self.resolve(&var))
    }

    /// Gets Current Object variable from the stack for Current Objects
    /// by finding the corresponding entry in the normal stack.
    /// If the Current Object can't be found in the stack of current objects,
    /// the error ("Could not find current variable `{}`", name) is thrown.
    ///
    /// ##Examples
    ///
    /// Dyon code:
    /// ```text
    /// ~ entity := 42
    /// teleport()
    /// ```
    /// Rust code:
    /// ```rust
    /// use dyon::Runtime;
    ///
    /// fn teleport(rt: &mut Runtime) -> Result<(), String> {
    ///     let current_entity_id = rt.current_object::<u32>("entity")?;
    ///     assert_eq!(current_entity_id, 42);
    ///     Ok(())
    /// }
    /// ```
    pub fn current_object<T: embed::PopVariable>(&self, name: &str) -> Result<T, String> {
        let current_object_index = self.current_stack
            .iter()
            .rev()
            .find(|(name_found, _)| **name_found == name)
            .map(|x| x.1)
            .ok_or(format!("Could not find current variable `{}`", name))
            ?;

        T::pop_var(self, self.resolve(&self.stack[current_object_index]))
    }

    /// Gets 4D vector.
    pub fn var_vec4<T: embed::ConvertVec4>(&self, var: &Variable) -> Result<T, String> {
        match self.resolve(&var) {
            &Variable::Vec4(val) => Ok(T::from(val)),
            x => Err(self.expected(x, "vec4"))
        }
    }

    /// Gets 4D matrix.
    pub fn var_mat4<T: embed::ConvertMat4>(&self, var: &Variable) -> Result<T, String> {
        match self.resolve(&var) {
            &Variable::Mat4(ref val) => Ok(T::from(**val)),
            x => Err(self.expected(x, "mat4"))
        }
    }

    /// Push value to stack.
    pub fn push<T: embed::PushVariable>(&mut self, val: T) {
        self.stack.push(val.push_var())
    }

    /// Push Vec4 to stack.
    pub fn push_vec4<T: embed::ConvertVec4>(&mut self, val: T) {
        self.stack.push(Variable::Vec4(val.to()))
    }

    /// Push Mat4 to stack.
    pub fn push_mat4<T: embed::ConvertMat4>(&mut self, val: T) {
        self.stack.push(Variable::Mat4(Box::new(val.to())))
    }

    /// Pushes Rust object to stack.
    pub fn push_rust<T: 'static>(&mut self, val: T) {
        use std::sync::Mutex;
        use RustObject;
        self.stack.push(Variable::RustObject(Arc::new(Mutex::new(val)) as RustObject))
    }

    /// Generates error message that a certain type was expected.
    pub fn expected(&self, var: &Variable, ty: &str) -> String {
        let found_ty = var.typeof_var();
        format!("{}\nExpected `{}`, found `{}`", self.stack_trace(), ty, found_ty)
    }

    /// Resolves a variable reference if any, getting a pointer to the variable on the stack.
    #[inline(always)]
    pub fn resolve<'a>(&'a self, var: &'a Variable) -> &'a Variable {
        resolve(&self.stack, var)
    }

    #[inline(always)]
    fn push_fn(
        &mut self,
        name: Arc<String>,
        index: usize,
        file: Option<Arc<String>>,
        st: usize,
        lc: usize,
        cu: usize,
    ) {
        self.call_stack.push(Call {
            fn_name: name,
            index,
            file,
            stack_len: st,
            local_len: lc,
            current_len: cu,
        });
    }
    fn pop_fn(&mut self, name: Arc<String>) {
        match self.call_stack.pop() {
            None => panic!("Did not call `{}`", name),
            Some(Call { fn_name, stack_len: st, local_len: lc, current_len: cu, .. }) => {
                if name != fn_name {
                    panic!("Calling `{}`, did not call `{}`", fn_name, name);
                }
                self.stack.truncate(st);
                self.local_stack.truncate(lc);
                self.current_stack.truncate(cu);
            }
        }
    }

    pub(crate) fn expression(
        &mut self,
        expr: &ast::Expression,
        side: Side,
        module: &Arc<Module>
    ) -> Result<(Option<Variable>, Flow), String> {
        use ast::Expression::*;

        match *expr {
            Link(ref link) => self.link(link, module),
            Object(ref obj) => self.object(obj, module),
            Array(ref arr) => self.array(arr, module),
            ArrayFill(ref array_fill) => self.array_fill(array_fill, module),
            Block(ref block) => self.block(block, module),
            Return(ref ret) => {
                let x = match self.expression(ret, Side::Right, module)? {
                    (Some(x), Flow::Continue) => x,
                    (x, Flow::Return) => { return Ok((x, Flow::Return)); }
                    _ => return Err(module.error(expr.source_range(),
                                    &format!("{}\nExpected something",
                                        self.stack_trace()), self))
                };
                Ok((Some(x), Flow::Return))
            }
            ReturnVoid(_) => Ok((None, Flow::Return)),
            Break(ref b) => Ok((None, Flow::Break(b.label.clone()))),
            Continue(ref b) => Ok((None, Flow::ContinueLoop(b.label.clone()))),
            Go(ref go) => self.go(go, module),
            Call(ref call) => {
                let loader = false;
                self.call_internal(call, loader, module)
            }
            Item(ref item) => self.item(item, side, module),
            Norm(ref norm) => self.norm(norm, side, module),
            UnOp(ref unop) => self.unop(unop, side, module),
            BinOp(ref binop) => self.binop(binop, side, module),
            Assign(ref assign) => self.assign(assign.op, &assign.left, &assign.right, module),
            Vec4(ref vec4) => self.vec4(vec4, side, module),
            Mat4(ref mat4) => self.mat4(mat4, side, module),
            For(ref for_expr) => self.for_expr(for_expr, module),
            ForN(ref for_n_expr) => self.for_n_expr(for_n_expr, module),
            ForIn(ref for_in_expr) => self.for_in_expr(for_in_expr, module),
            Sum(ref for_n_expr) => self.sum_n_expr(for_n_expr, module),
            SumIn(ref sum_in_expr) => self.sum_in_expr(sum_in_expr, module),
            SumVec4(ref for_n_expr) => self.sum_vec4_n_expr(for_n_expr, module),
            Prod(ref for_n_expr) => self.prod_n_expr(for_n_expr, module),
            ProdIn(ref for_in_expr) => self.prod_in_expr(for_in_expr, module),
            ProdVec4(ref for_n_expr) => self.prod_vec4_n_expr(for_n_expr, module),
            Min(ref for_n_expr) => self.min_n_expr(for_n_expr, module),
            MinIn(ref for_in_expr) => self.min_in_expr(for_in_expr, module),
            Max(ref for_n_expr) => self.max_n_expr(for_n_expr, module),
            MaxIn(ref for_in_expr) => self.max_in_expr(for_in_expr, module),
            Sift(ref for_n_expr) => self.sift_n_expr(for_n_expr, module),
            SiftIn(ref for_in_expr) => self.sift_in_expr(for_in_expr, module),
            Any(ref for_n_expr) => self.any_n_expr(for_n_expr, module),
            AnyIn(ref for_in_expr) => self.any_in_expr(for_in_expr, module),
            All(ref for_n_expr) => self.all_n_expr(for_n_expr, module),
            AllIn(ref for_in_expr) => self.all_in_expr(for_in_expr, module),
            LinkFor(ref for_n_expr) => self.link_for_n_expr(for_n_expr, module),
            LinkIn(ref for_in_expr) => self.link_for_in_expr(for_in_expr, module),
            If(ref if_expr) => self.if_expr(if_expr, module),
            Compare(ref compare) => self.compare(compare, module),
            Variable(ref range_var) => Ok((Some(range_var.1.clone()), Flow::Continue)),
            Try(ref expr) => self.try(expr, side, module),
            Swizzle(ref sw) => {
                let flow = self.swizzle(sw, module)?;
                Ok((None, flow))
            }
            Closure(ref closure) => self.closure(closure, module),
            CallClosure(ref call) => self.call_closure(call, module),
            Grab(ref expr) => Err(module.error(expr.source_range,
                    &format!("{}\n`grab` expressions must be inside a closure",
                        self.stack_trace()), self)),
            TryExpr(ref try_expr) => self.try_expr(try_expr, module),
            In(ref in_expr) => self.in_expr(in_expr, module),
        }
    }

    fn in_expr(&mut self, in_expr: &ast::In, module: &Arc<Module>)
    -> Result<(Option<Variable>, Flow), String> {
        use std::sync::mpsc::channel;
        use std::sync::Mutex;
        use std::sync::atomic::Ordering;

        match in_expr.f_index.get() {
            FnIndex::Loaded(f_index) => {
                let relative = self.call_stack.last().map(|c| c.index).unwrap_or(0);
                let new_index = (f_index + relative as isize) as usize;
                let f = &module.functions[new_index];
                let (tx, rx) = channel();
                // Guard the change of flag to avoid data race.
                let mut guard = f.senders.1.lock().unwrap();
                guard.push(tx);
                f.senders.0.store(true, Ordering::Relaxed);
                drop(guard);
                Ok((Some(::Variable::In(Arc::new(Mutex::new(rx)))), Flow::Continue))
            }
            _ => Err(module.error(in_expr.source_range,
                    &format!("{}\nExpected loaded function",
                        self.stack_trace()), self)),
        }
    }

    fn try_expr(&mut self, try_expr: &ast::TryExpr, module: &Arc<Module>)
    -> Result<(Option<Variable>, Flow), String> {
        use Error;

        let cs = self.call_stack.len();
        let st = self.stack.len();
        let lc = self.local_stack.len();
        let cu = self.current_stack.len();
        match self.expression(&try_expr.expr, Side::Right, module) {
            Ok((Some(x), Flow::Continue)) => Ok((
                Some(Variable::Result(Ok(Box::new(x)))),
                Flow::Continue
            )),
            Ok((None, Flow::Continue)) => Err(module.error(try_expr.source_range,
                &format!("{}\nExpected something", self.stack_trace()), self)),
            Ok((x, flow)) => Ok((x, flow)),
            Err(err) => {
                self.call_stack.truncate(cs);
                self.stack.truncate(st);
                self.local_stack.truncate(lc);
                self.current_stack.truncate(cu);
                Ok((
                    Some(Variable::Result(Err(Box::new(Error {
                        message: Variable::Text(Arc::new(err)),
                        trace: vec![],
                    }
                    )))),
                    Flow::Continue
                ))
            }
        }
    }

    fn closure(&mut self, closure: &ast::Closure, module: &Arc<Module>)
    -> Result<(Option<Variable>, Flow), String> {
        use grab::{self, Grabbed};
        use ClosureEnvironment;

        // Create closure.
        let relative = self.call_stack.last().map(|c| c.index).unwrap_or(0);
        // Evaluate `grab` expressions and generate new AST.
        let new_expr = match grab::grab_expr(1, self, &closure.expr, Side::Right, module)? {
            (Grabbed::Expression(x), Flow::Continue) => x,
            (Grabbed::Variable(x), Flow::Return) => { return Ok((x, Flow::Return)); }
            _ => return Err(module.error(closure.expr.source_range(),
                            &format!("{}\nExpected something",
                                self.stack_trace()), self))
        };

        Ok((Some(::Variable::Closure(Arc::new(ast::Closure {
            currents: closure.currents.clone(),
            args: closure.args.clone(),
            source_range: closure.source_range,
            ret: closure.ret.clone(),
            file: closure.file.clone(),
            source: closure.source.clone(),
            expr: new_expr,
        }), Box::new(ClosureEnvironment {
            module: module.clone(),
            relative
        }))), Flow::Continue))
    }

    fn try_msg(v: &Variable) -> Option<Result<Box<Variable>, Box<::Error>>> {
        use Error;

        Some(match *v {
            Variable::Result(ref res) => res.clone(),
            Variable::Option(ref opt) => {
                match *opt {
                    Some(ref some) => Ok(some.clone()),
                    None => Err(Box::new(Error {
                        message: Variable::Text(Arc::new(
                            "Expected `some(_)`, found `none()`"
                            .into())),
                        trace: vec![]
                    }))
                }
            }
            Variable::Bool(true, None) => {
                Err(Box::new(Error {
                    message: Variable::Text(Arc::new(
                        "This does not make sense, perhaps an array is empty?"
                        .into())),
                    trace: vec![]
                }))
            }
            Variable::Bool(false, _) => {
                Err(Box::new(Error {
                    message: Variable::Text(Arc::new(
                        "Must be `true` to have meaning, try add or remove `!`"
                        .into())),
                    trace: vec![]
                }))
            }
            Variable::Bool(true, ref sec) => {
                match *sec {
                    None => Err(Box::new(Error {
                        message: Variable::Text(Arc::new(
                            "Expected `some(_)`, found `none()`"
                            .into())),
                        trace: vec![]
                    })),
                    Some(_) => {
                        Ok(Box::new(Variable::Bool(true, sec.clone())))
                    }
                }
            }
            Variable::F64(val, ref sec) => {
                if val.is_nan() {
                    Err(Box::new(Error {
                        message: Variable::Text(Arc::new(
                            "Expected number, found `NaN`"
                            .into())),
                        trace: vec![]
                    }))
                } else if sec.is_none() {
                    Err(Box::new(Error {
                        message: Variable::Text(Arc::new(
                            "This does not make sense, perhaps an array is empty?"
                            .into())),
                        trace: vec![]
                    }))
                } else {
                    Ok(Box::new(Variable::F64(val, sec.clone())))
                }
            }
            _ => return None
        })
    }

    fn try(
        &mut self,
        expr: &ast::Expression,
        side: Side,
        module: &Arc<Module>
    ) -> Result<(Option<Variable>, Flow), String> {
        let v = match self.expression(expr, side, module)? {
            (Some(x), Flow::Continue) => x,
            (x, Flow::Return) => { return Ok((x, Flow::Return)); }
            _ => return Err(module.error(expr.source_range(),
                            &format!("{}\nExpected something",
                                self.stack_trace()), self))
        };
        let v = match Runtime::try_msg(self.resolve(&v)) {
            Some(v) => v,
            None => {
                return Err(module.error(expr.source_range(),
                    &format!("{}\nExpected `ok(_)`, `err(_)`, `bool`, `f64`",
                        self.stack_trace()), self));
            }
        };
        match v {
            Ok(ok) => {
                Ok((Some(*ok), Flow::Continue))
            }
            Err(mut err) => {
                let call = self.call_stack.last().unwrap();
                if call.stack_len == 0 {
                    return Err(module.error(expr.source_range(),
                        &format!("{}\nRequires `->` on function `{}`",
                        self.stack_trace(),
                        &call.fn_name), self));
                }
                if let Variable::Return = self.stack[call.stack_len - 1] {}
                else {
                    return Err(module.error(expr.source_range(),
                        &format!("{}\nRequires `->` on function `{}`",
                        self.stack_trace(),
                        &call.fn_name), self));
                }
                let file = match call.file {
                    None => "".into(),
                    Some(ref f) => format!(" ({})", f)
                };
                err.trace.push(module.error(expr.source_range(),
                    &format!("In function `{}`{}",
                    &call.fn_name, file), self));
                Ok((Some(Variable::Result(Err(err))), Flow::Return))
            }
        }
    }

    /// Run `main` function in a module.
    pub fn run(&mut self, module: &Arc<Module>) -> Result<(), String> {
        use std::cell::Cell;

        let name: Arc<String> = Arc::new("main".into());
        let call = ast::Call {
            alias: None,
            name: name.clone(),
            f_index: Cell::new(module.find_function(&name, 0)),
            args: vec![],
            custom_source: None,
            source_range: Range::empty(0),
        };
        match call.f_index.get() {
            FnIndex::Loaded(f_index) => {
                let f = &module.functions[f_index as usize];
                if !f.args.is_empty() {
                    return Err(module.error(f.args[0].source_range,
                               "`main` should not have arguments", self))
                }
                let loader = false;
                self.call_internal(&call, loader, &module)?;
                Ok(())
            }
            _ => Err(module.error(call.source_range,
                               "Could not find function `main`", self))
        }
    }

    fn block(
        &mut self,
        block: &ast::Block,
        module: &Arc<Module>
    ) -> Result<(Option<Variable>, Flow), String> {
        let mut expect = None;
        let st = self.stack.len();
        let lc = self.local_stack.len();
        let cu = self.current_stack.len();
        for e in &block.expressions {
            expect = match self.expression(e, Side::Right, module)? {
                (x, Flow::Continue) => x,
                x => {
                    self.stack.truncate(st);
                    self.local_stack.truncate(lc);
                    self.current_stack.truncate(cu);
                    return Ok(x);
                }
            }
        }

        self.stack.truncate(st);
        self.local_stack.truncate(lc);
        self.current_stack.truncate(cu);
        Ok((expect, Flow::Continue))
    }

    /// Start a new thread and return the handle.
    pub fn go(&mut self, go: &ast::Go, module: &Arc<Module>) -> Result<(Option<Variable>, Flow), String> {
        use std::thread::{self, JoinHandle};
        use std::cell::Cell;
        use Thread;

        let n = go.call.args.len();
        let mut stack = vec![];
        let relative = self.call_stack.last().map(|c| c.index).unwrap();
        let mut fake_call = ast::Call {
            alias: go.call.alias.clone(),
            name: go.call.name.clone(),
            f_index: Cell::new(module.find_function(&go.call.name, relative)),
            args: Vec::with_capacity(n),
            custom_source: None,
            source_range: go.call.source_range,
        };
        // Evaluate the arguments and put a deep clone on the new stack.
        // This prevents the arguments from containing any reference to other variables.
        for (i, arg) in go.call.args.iter().enumerate() {
            let v = match self.expression(arg, Side::Right, module)? {
                (Some(x), Flow::Continue) => x,
                (x, Flow::Return) => { return Ok((x, Flow::Return)); }
                _ => return Err(module.error(arg.source_range(),
                                &format!("{}\nExpected something. \
                                Expression did not return a value.",
                                self.stack_trace()), self))
            };
            stack.push(v.deep_clone(&self.stack));
            fake_call.args.push(ast::Expression::Variable(Box::new((
                go.call.args[i].source_range(), Variable::Ref(n-i-1)))));
        }
        stack.reverse();

        let last_call = self.call_stack.last().unwrap();
        let new_rt = Runtime {
            stack,
            local_stack: vec![],
            current_stack: vec![],
            // Add last call because of loaded functions
            // use relative index to the function it is calling from.
            call_stack: vec![Call {
                fn_name: last_call.fn_name.clone(),
                index: last_call.index,
                file: last_call.file.clone(),
                stack_len: 0,
                local_len: 0,
                current_len: 0,
            }],
            rng: self.rng.clone(),
            ret: self.ret.clone(),
        };
        let new_module = module.clone();
        let handle: JoinHandle<Result<Variable, String>> = thread::spawn(move || {
            let mut new_rt = new_rt;
            let new_module = new_module;
            let fake_call = fake_call;
            let loader = false;
            Ok(match new_rt.call_internal(&fake_call, loader, &new_module) {
                Err(err) => return Err(err),
                Ok((None, _)) => {
                    new_rt.stack.pop().expect(TINVOTS)
                }
                Ok((Some(x), _)) => x,
            }.deep_clone(&new_rt.stack))
        });
        Ok((Some(Variable::Thread(Thread::new(handle))), Flow::Continue))
    }

    /// Call closure.
    pub fn call_closure(
        &mut self,
        call: &ast::CallClosure,
        module: &Arc<Module>
    ) -> Result<(Option<Variable>, Flow), String> {
        // Find item.
        let item = match self.item(&call.item, Side::Right, module)? {
            (Some(x), Flow::Continue) => x,
            (x, Flow::Return) => { return Ok((x, Flow::Return)); }
            _ => return Err(module.error(call.item.source_range,
                            &format!("{}\nExpected something. \
                            Check that item returns a value.",
                            self.stack_trace()), self))
        };

        let (f, env) = match self.resolve(&item) {
            &Variable::Closure(ref f, ref env) => (f.clone(), env.clone()),
            x => return Err(module.error(call.source_range,
                    &self.expected(x, "closure"), self))
        };

        if call.arg_len() != f.args.len() {
            return Err(module.error(call.source_range,
                &format!("{}\nExpected {} arguments but found {}",
                self.stack_trace(),
                f.args.len(),
                call.arg_len()), self));
        }
        // Arguments must be computed.
        if f.returns() {
            // Add return value before arguments on the stack.
            // The stack value should remain, but the local should not.
            self.stack.push(Variable::Return);
        }
        let st = self.stack.len();
        let lc = self.local_stack.len();
        let cu = self.current_stack.len();
        for arg in &call.args {
            match self.expression(arg, Side::Right, module)? {
                (Some(x), Flow::Continue) => self.stack.push(x),
                (None, Flow::Continue) => {}
                (x, Flow::Return) => { return Ok((x, Flow::Return)); }
                _ => return Err(module.error(arg.source_range(),
                                &format!("{}\nExpected something. \
                                Check that expression returns a value.",
                                self.stack_trace()), self))
            };
        }

        // Look for variable in current stack.
        if !f.currents.is_empty() {
            for current in &f.currents {
                let mut res = None;
                for &(ref cname, ind) in self.current_stack.iter().rev() {
                    if cname == &current.name {
                        res = Some(ind);
                        break;
                    }
                }
                if let Some(ind) = res {
                    self.local_stack.push((current.name.clone(), self.stack.len()));
                    self.stack.push(Variable::Ref(ind));
                } else {
                    return Err(module.error(call.source_range, &format!(
                        "{}\nCould not find current variable `{}`",
                            self.stack_trace(), current.name), self));
                }
            }
        }

        self.push_fn(call.item.name.clone(), env.relative, Some(f.file.clone()), st, lc, cu);
        if f.returns() {
            self.local_stack.push((self.ret.clone(), st - 1));
        }
        for (i, arg) in f.args.iter().enumerate() {
            // Do not resolve locals to keep fixed length from end of stack.
            self.local_stack.push((arg.name.clone(), st + i));
        }
        let (x, flow) = self.expression(&f.expr, Side::Right, &env.module)?;
        match flow {
            Flow::Break(None) =>
                return Err(module.error(call.source_range,
                           &format!("{}\nCan not break from function",
                                self.stack_trace()), self)),
            Flow::ContinueLoop(None) =>
                return Err(module.error(call.source_range,
                           &format!("{}\nCan not continue from function",
                                self.stack_trace()), self)),
            Flow::Break(Some(ref label)) =>
                return Err(module.error(call.source_range,
                    &format!("{}\nThere is no loop labeled `{}`",
                             self.stack_trace(), label), self)),
            Flow::ContinueLoop(Some(ref label)) =>
                return Err(module.error(call.source_range,
                    &format!("{}\nThere is no loop labeled `{}`",
                            self.stack_trace(), label), self)),
            _ => {}
        }
        self.pop_fn(call.item.name.clone());
        match (f.returns(), x) {
            (true, None) => {
                match self.stack.pop().expect(TINVOTS) {
                    Variable::Return => {
                        Err(module.error(
                            call.source_range, &format!(
                            "{}\nFunction `{}` did not return a value",
                            self.stack_trace(),
                            call.item.name), self))
                    }
                    x => {
                        // This happens when return is only
                        // assigned to `return = x`.
                        Ok((Some(x), Flow::Continue))
                    }
                }
            }
            (false, Some(_)) => {
                Err(module.error(call.source_range,
                    &format!(
                        "{}\nFunction `{}` should not return a value",
                        self.stack_trace(),
                        call.item.name), self))
            }
            (true, Some(Variable::Return)) => {
                // TODO: Could return the last value on the stack.
                //       Requires .pop_fn delayed after.
                Err(module.error(call.source_range,
                    &format!(
                    "{}\nFunction `{}` did not return a value. \
                    Did you forget a `return`?",
                        self.stack_trace(),
                        call.item.name), self))
            }
            (returns, b) => {
                if returns { self.stack.pop(); }
                Ok((b, Flow::Continue))
            }
        }
    }

    /// Called from the outside, e.g. a loader script by `call` or `call_ret` intrinsic.
    pub fn call(
        &mut self,
        call: &ast::Call,
        module: &Arc<Module>
    ) -> Result<(Option<Variable>, Flow), String> {
        self.call_internal(call, true, module)
    }

    /// Used internally because loaded functions are resolved
    /// relative to the caller, which stores its index on the
    /// call stack.
    ///
    /// The `loader` flag is set to `true` when called from the outside.
    fn call_internal(
        &mut self,
        call: &ast::Call,
        loader: bool,
        module: &Arc<Module>
    ) -> Result<(Option<Variable>, Flow), String> {
        use FnExternalRef;

        match call.f_index.get() {
            FnIndex::Intrinsic(index) => {
                intrinsics::call_standard(self, index, call, module)
            }
            FnIndex::ExternalVoid(FnExternalRef(f)) => {
                for arg in &call.args {
                    match self.expression(arg, Side::Right, module)? {
                        (Some(x), Flow::Continue) => self.stack.push(x),
                        (x, Flow::Return) => { return Ok((x, Flow::Return)); }
                        _ => return Err(module.error(arg.source_range(),
                                        &format!("{}\nExpected something. \
                                        Expression did not return a value.",
                                        self.stack_trace()), self))
                    };
                }
                (f)(self).map_err(|err|
                    module.error(call.source_range, &err, self))?;
                Ok((None, Flow::Continue))
            }
            FnIndex::ExternalReturn(FnExternalRef(f)) => {
                for arg in &call.args {
                    match self.expression(arg, Side::Right, module)? {
                        (Some(x), Flow::Continue) => self.stack.push(x),
                        (x, Flow::Return) => { return Ok((x, Flow::Return)); }
                        _ => return Err(module.error(arg.source_range(),
                                        &format!("{}\nExpected something. \
                                        Expression did not return a value.",
                                        self.stack_trace()), self))
                    };
                }
                (f)(self).map_err(|err|
                    module.error(call.source_range, &err, self))?;
                Ok((Some(self.stack.pop().expect(TINVOTS)), Flow::Continue))
            }
            FnIndex::Loaded(f_index) => {
                use std::sync::atomic::Ordering;

                let relative = if loader {0} else {
                    self.call_stack.last().map(|c| c.index).unwrap_or(0)
                };
                let new_index = (f_index + relative as isize) as usize;
                let f = &module.functions[new_index];
                if call.arg_len() != f.args.len() {
                    return Err(module.error(call.source_range,
                        &format!("{}\nExpected {} arguments but found {}",
                        self.stack_trace(),
                        f.args.len(),
                        call.arg_len()), self));
                }
                // Arguments must be computed.
                if f.returns() {
                    // Add return value before arguments on the stack.
                    // The stack value should remain, but the local should not.
                    self.stack.push(Variable::Return);
                }
                let st = self.stack.len();
                let lc = self.local_stack.len();
                let cu = self.current_stack.len();

                for arg in &call.args {
                    match self.expression(arg, Side::Right, module)? {
                        (Some(x), Flow::Continue) => self.stack.push(x),
                        (None, Flow::Continue) => {}
                        (x, Flow::Return) => { return Ok((x, Flow::Return)); }
                        _ => return Err(module.error(arg.source_range(),
                                        &format!("{}\nExpected something. \
                                        Check that expression returns a value.",
                                        self.stack_trace()), self))
                    };
                }

                // Look for variable in current stack.
                if !f.currents.is_empty() {
                    for current in &f.currents {
                        let mut res = None;
                        for &(ref cname, ind) in self.current_stack.iter().rev() {
                            if cname == &current.name {
                                res = Some(ind);
                                break;
                            }
                        }
                        if let Some(ind) = res {
                            self.local_stack.push((current.name.clone(), self.stack.len()));
                            self.stack.push(Variable::Ref(ind));
                        } else {
                            return Err(module.error(call.source_range, &format!(
                                "{}\nCould not find current variable `{}`",
                                    self.stack_trace(), current.name), self));
                        }
                    }
                }

                // Send arguments to senders.
                if f.senders.0.load(Ordering::Relaxed) {
                    let n = self.stack.len();
                    let mut msg = Vec::with_capacity(n - st);
                    for i in st..n {
                        msg.push(self.stack[i].deep_clone(&self.stack));
                    }
                    let msg = Arc::new(msg);
                    // Uses smart swapping of channels to put the closed ones at the end.
                    let mut channels = f.senders.1.lock().unwrap();
                    let mut open = channels.len();
                    for i in (0..channels.len()).rev() {
                        match channels[i].send(Variable::Array(msg.clone())) {
                            Ok(_) => {}
                            Err(_) => {
                                open -= 1;
                                channels.swap(i, open);
                            }
                        }
                    }
                    channels.truncate(open);
                    if channels.len() == 0 {
                        // Change of flag is guarded by the mutex.
                        f.senders.0.store(false, Ordering::Relaxed);
                    }
                    drop(channels);
                }

                self.push_fn(call.name.clone(), new_index, Some(f.file.clone()), st, lc, cu);
                if f.returns() {
                    self.local_stack.push((self.ret.clone(), st - 1));
                }
                for (i, arg) in f.args.iter().enumerate() {
                    // Do not resolve locals to keep fixed length from end of stack.
                    self.local_stack.push((arg.name.clone(), st + i));
                }
                let (x, flow) = self.block(&f.block, module)?;
                match flow {
                    Flow::Break(None) =>
                        return Err(module.error(call.source_range,
                                   &format!("{}\nCan not break from function",
                                        self.stack_trace()), self)),
                    Flow::ContinueLoop(None) =>
                        return Err(module.error(call.source_range,
                                   &format!("{}\nCan not continue from function",
                                        self.stack_trace()), self)),
                    Flow::Break(Some(ref label)) =>
                        return Err(module.error(call.source_range,
                            &format!("{}\nThere is no loop labeled `{}`",
                                     self.stack_trace(), label), self)),
                    Flow::ContinueLoop(Some(ref label)) =>
                        return Err(module.error(call.source_range,
                            &format!("{}\nThere is no loop labeled `{}`",
                                    self.stack_trace(), label), self)),
                    _ => {}
                }
                self.pop_fn(call.name.clone());
                match (f.returns(), x) {
                    (true, None) => {
                        match self.stack.pop().expect(TINVOTS) {
                            Variable::Return => {
                                let source = call.custom_source.as_ref().unwrap_or(
                                    &module.functions[
                                        self.call_stack.last().unwrap().index
                                    ].source
                                );
                                Err(module.error_source(
                                call.source_range, &format!(
                                "{}\nFunction `{}` did not return a value",
                                self.stack_trace(),
                                f.name), source))
                            }
                            x => {
                                // This happens when return is only
                                // assigned to `return = x`.
                                Ok((Some(x), Flow::Continue))
                            }
                        }
                    }
                    (false, Some(_)) => {
                        let source = call.custom_source.as_ref().unwrap_or(
                            &module.functions[self.call_stack.last().unwrap().index].source
                        );
                        Err(module.error_source(call.source_range,
                            &format!(
                                "{}\nFunction `{}` should not return a value",
                                self.stack_trace(),
                                f.name), source))
                    }
                    (true, Some(Variable::Return)) => {
                        // TODO: Could return the last value on the stack.
                        //       Requires .pop_fn delayed after.
                        let source = call.custom_source.as_ref().unwrap_or(
                            &module.functions[self.call_stack.last().unwrap().index].source
                        );
                        Err(module.error_source(call.source_range,
                            &format!(
                            "{}\nFunction `{}` did not return a value. \
                            Did you forget a `return`?",
                                self.stack_trace(),
                                f.name), source))
                    }
                    (returns, b) => {
                        if returns { self.stack.pop(); }
                        Ok((b, Flow::Continue))
                    }
                }
            }
            FnIndex::None => {
                Err(module.error(call.source_range,
                    &format!("{}\nUnknown function `{}`", self.stack_trace(), call.name), self))
            }
        }
    }

    /// Calls function by name.
    pub fn call_str(
        &mut self,
        function: &str,
        args: &[Variable],
        module: &Arc<Module>
    ) -> Result<(), String> {
        use std::cell::Cell;

        let name: Arc<String> = Arc::new(function.into());
        match module.find_function(&name, 0) {
            FnIndex::Loaded(f_index) => {
                let call = ast::Call {
                    alias: None,
                    name: name.clone(),
                    f_index: Cell::new(FnIndex::Loaded(f_index)),
                    args: args.iter()
                            .map(|arg| ast::Expression::Variable(Box::new((
                                       Range::empty(0), arg.clone()))))
                            .collect(),
                    custom_source: None,
                    source_range: Range::empty(0),
                };
                self.call(&call, &module)?;
                Ok(())
            }
            _ => Err(format!("Could not find function `{}`",function))
        }
    }

    /// Call function by name, returning a value.
    pub fn call_str_ret(
        &mut self,
        function: &str,
        args: &[Variable],
        module: &Arc<Module>
    ) -> Result<Variable, String> {
        use std::cell::Cell;

        let name: Arc<String> = Arc::new(function.into());
        let fn_index = module.find_function(&name, 0);
        if let FnIndex::None = fn_index {
            return Err(format!("Could not find function `{}`", function));
        }

        let call = ast::Call {
            alias: None,
            name: name.clone(),
            f_index: Cell::new(fn_index),
            args: args
                .iter()
                .map(|arg| ast::Expression::Variable(Box::new((Range::empty(0), arg.clone()))))
                .collect(),
            custom_source: None,
            source_range: Range::empty(0),
        };
        match self.call(&call, &module) {
            Ok((Some(val), Flow::Continue)) => Ok(val),
            Err(err) => Err(err),
            _ => Err(module.error(
                call.source_range,
                &format!("{}\nExpected something", self.stack_trace()),
                self,
            )),
        }
    }

    fn swizzle(&mut self, sw: &ast::Swizzle, module: &Arc<Module>) -> Result<Flow, String> {
        let v = match self.expression(&sw.expr, Side::Right, module)? {
            (Some(x), Flow::Continue) => x,
            (_, Flow::Return) => { return Ok(Flow::Return); }
            _ => return Err(module.error(sw.expr.source_range(),
                            &format!("{}\nExpected something",
                                self.stack_trace()), self))
        };
        let v = match self.resolve(&v) {
            &Variable::Vec4(v) => v,
            x => return Err(module.error(sw.source_range,
                    &self.expected(x, "vec4"), self))
        };
        self.stack.push(Variable::f64(f64::from(v[sw.sw0])));
        self.stack.push(Variable::f64(f64::from(v[sw.sw1])));
        if let Some(ind) = sw.sw2 {
            self.stack.push(Variable::f64(f64::from(v[ind])));
        }
        if let Some(ind) = sw.sw3 {
            self.stack.push(Variable::f64(f64::from(v[ind])));
        }
        Ok(Flow::Continue)
    }

    fn link(
        &mut self,
        link: &ast::Link,
        module: &Arc<Module>
    ) -> Result<(Option<Variable>, Flow), String> {
        use Link;

        Ok((Some(if link.items.is_empty() {
            Variable::Link(Box::new(Link::new()))
        } else {
            let st = self.stack.len();
            let lc = self.local_stack.len();
            let cu = self.current_stack.len();
            let mut new_link = Link::new();
            for item in &link.items {
                let v = match self.expression(item, Side::Right, module)? {
                    (Some(x), Flow::Continue) => x,
                    (None, Flow::Continue) => continue,
                    (res, flow) => { return Ok((res, flow)); }
                };
                match new_link.push(self.resolve(&v)) {
                    Err(err) => {
                        return Err(module.error(item.source_range(),
                            &format!("{}\n{}", self.stack_trace(),
                            err), self))
                    }
                    Ok(()) => {}
                }
            }
            self.stack.truncate(st);
            self.local_stack.truncate(lc);
            self.current_stack.truncate(cu);
            Variable::Link(Box::new(new_link))
        }), Flow::Continue))
    }

    fn object(
        &mut self,
        obj: &ast::Object,
        module: &Arc<Module>
    ) -> Result<(Option<Variable>, Flow), String> {
        let mut object: HashMap<_, _> = HashMap::new();
        for &(ref key, ref expr) in &obj.key_values {
            let x = match self.expression(expr, Side::Right, module)? {
                (Some(x), Flow::Continue) => x,
                (x, Flow::Return) => { return Ok((x, Flow::Return)); }
                _ => return Err(module.error(expr.source_range(),
                                &format!("{}\nExpected something",
                                    self.stack_trace()), self))
            };
            match object.insert(key.clone(), x) {
                None => {}
                Some(_) => return Err(module.error(expr.source_range(),
                    &format!("{}\nDuplicate key in object `{}`",
                        self.stack_trace(), key), self))
            }
        }
        Ok((Some(Variable::Object(Arc::new(object))), Flow::Continue))
    }

    fn array(
        &mut self,
        arr: &ast::Array,
        module: &Arc<Module>
    ) -> Result<(Option<Variable>, Flow), String> {
        let mut array: Vec<Variable> = Vec::new();
        for item in &arr.items {
            array.push(match self.expression(item, Side::Right, module)? {
                (Some(x), Flow::Continue) => x,
                (x, Flow::Return) => return Ok((x, Flow::Return)),
                _ => return Err(module.error(item.source_range(),
                    &format!("{}\nExpected something",
                        self.stack_trace()), self))
            });
        }
        Ok((Some(Variable::Array(Arc::new(array))), Flow::Continue))
    }

    fn array_fill(
        &mut self,
        array_fill: &ast::ArrayFill,
        module: &Arc<Module>
    ) -> Result<(Option<Variable>, Flow), String> {
        let fill = match self.expression(&array_fill.fill, Side::Right, module)? {
            (x, Flow::Return) => return Ok((x, Flow::Return)),
            (Some(x), Flow::Continue) => x,
            _ => return Err(module.error(array_fill.fill.source_range(),
                            &format!("{}\nExpected something",
                                self.stack_trace()), self))
        };
        let n = match self.expression(&array_fill.n, Side::Right, module)? {
            (x, Flow::Return) => return Ok((x, Flow::Return)),
            (Some(x), Flow::Continue) => x,
            _ => return Err(module.error(array_fill.n.source_range(),
                            &format!("{}\nExpected something",
                                self.stack_trace()), self))
        };
        let v = match (self.resolve(&fill), self.resolve(&n)) {
            (x, &Variable::F64(n, _)) => {
                Variable::Array(Arc::new(vec![x.clone(); n as usize]))
            }
            _ => return Err(module.error(array_fill.n.source_range(),
                &format!("{}\nExpected number for length in `[value; length]`",
                    self.stack_trace()), self))
        };
        Ok((Some(v), Flow::Continue))
    }

    fn assign(
        &mut self,
        op: ast::AssignOp,
        left: &ast::Expression,
        right: &ast::Expression,
        module: &Arc<Module>
    ) -> Result<(Option<Variable>, Flow), String> {
        use ast::AssignOp::*;
        use ast::Expression;

        if op != Assign {
            // Evaluate right side before left because the left leaves
            // an raw pointer on the stack which might point to wrong place
            // if there are side effects of the right side affecting it.
            let b = match self.expression(right, Side::Right, module)? {
                (Some(x), Flow::Continue) => x,
                (x, Flow::Return) => return Ok((x, Flow::Return)),
                _ => return Err(module.error(right.source_range(),
                        &format!("{}\nExpected something from the right side",
                            self.stack_trace()), self))
            };
            let a = match self.expression(left, Side::LeftInsert(false), module)? {
                (Some(x), Flow::Continue) => x,
                (x, Flow::Return) => return Ok((x, Flow::Return)),
                _ => return Err(module.error(left.source_range(),
                        &format!("{}\nExpected something from the left side",
                            self.stack_trace()), self))
            };
            let r = match a {
                Variable::UnsafeRef(r) => {
                    // If reference, use a shallow clone to type check,
                    // without affecting the original object.
                    unsafe {
                        if let Variable::Ref(ind) = *r.0 {
                            *r.0 = self.stack[ind].clone()
                        }
                    }
                    r
                }
                Variable::Ref(ind) => {
                    UnsafeRef(&mut self.stack[ind] as *mut Variable)
                }
                x => panic!("Expected reference, found `{}`", x.typeof_var())
            };

            match *self.resolve(&b) {
                Variable::F64(b, ref sec) => {
                    unsafe {
                        match *r.0 {
                            Variable::F64(ref mut n, ref mut n_sec) => {
                                match op {
                                    Set => *n = b,
                                    Add => *n += b,
                                    Sub => *n -= b,
                                    Mul => *n *= b,
                                    Div => *n /= b,
                                    Rem => *n %= b,
                                    Pow => *n = n.powf(b),
                                    Assign => {}
                                };
                                *n_sec = sec.clone()
                            }
                            Variable::Vec4(ref mut n) => {
                                let b = b as f32;
                                match op {
                                    Add => *n = [n[0] + b, n[1] + b,
                                                 n[2] + b, n[3] + b],
                                    Sub => *n = [n[0] - b, n[1] - b,
                                                 n[2] - b, n[3] - b],
                                    Mul => *n = [n[0] * b, n[1] * b,
                                                 n[2] * b, n[3] * b],
                                    Div => *n = [n[0] / b, n[1] / b,
                                                 n[2] / b, n[3] / b],
                                    Rem => *n = [n[0] % b, n[1] % b,
                                                 n[2] % b, n[3] % b],
                                    Pow => *n = [n[0].powf(b), n[1].powf(b),
                                                 n[2].powf(b), n[3].powf(b)],
                                    _ => return Err(module.error(
                                            left.source_range(),
                                            &format!("{}\nExpected assigning to a number",
                                                self.stack_trace()), self))
                                }
                            }
                            Variable::Return => {
                                if let Set = op {
                                    *r.0 = Variable::F64(b, sec.clone())
                                } else {
                                    return Err(module.error(
                                        left.source_range(),
                                        &format!("{}\nReturn has no value",
                                            self.stack_trace()), self))
                                }
                            }
                            Variable::Link(ref mut n) => {
                                if let Add = op {
                                    n.push(&Variable::f64(b))?;
                                } else {
                                    return Err(module.error(
                                        left.source_range(),
                                        &format!("{}\nCan not use this assignment \
                                        operator with `link` and `number`",
                                            self.stack_trace()), self));
                                }
                            }
                            _ => return Err(module.error(
                                    left.source_range(),
                                    &format!("{}\nExpected assigning to a number",
                                        self.stack_trace()), self))
                        };
                    }
                }
                Variable::Vec4(b) => {
                    unsafe {
                        match *r.0 {
                            Variable::Vec4(ref mut n) => {
                                match op {
                                    Set => *n = b,
                                    Add => *n = [n[0] + b[0], n[1] + b[1],
                                                 n[2] + b[2], n[3] + b[3]],
                                    Sub => *n = [n[0] - b[0], n[1] - b[1],
                                                 n[2] - b[2], n[3] - b[3]],
                                    Mul => *n = [n[0] * b[0], n[1] * b[1],
                                                 n[2] * b[2], n[3] * b[3]],
                                    Div => *n = [n[0] / b[0], n[1] / b[1],
                                                 n[2] / b[2], n[3] / b[3]],
                                    Rem => *n = [n[0] % b[0], n[1] % b[1],
                                                 n[2] % b[2], n[3] % b[3]],
                                    Pow => *n = [n[0].powf(b[0]), n[1].powf(b[1]),
                                                 n[2].powf(b[2]), n[3].powf(b[3])],
                                    Assign => {}
                                }
                            }
                            Variable::Return => {
                                if let Set = op {
                                    *r.0 = Variable::Vec4(b)
                                } else {
                                    return Err(module.error(
                                        left.source_range(),
                                        &format!("{}\nReturn has no value",
                                            self.stack_trace()), self))
                                }
                            }
                            _ => return Err(module.error(
                                    left.source_range(),
                                    &format!("{}\nExpected assigning to a vec4",
                                        self.stack_trace()), self))
                        };
                    }
                }
                Variable::Mat4(ref b) => {
                    unsafe {
                        match *r.0 {
                            Variable::Mat4(ref mut n) => {
                                match op {
                                    Set => {
                                        **n = **b;
                                    }
                                    Mul => {
                                        use vecmath::col_mat4_mul;

                                        **n = col_mat4_mul(**n, **b);
                                    }
                                    Add => {
                                        use vecmath::mat4_add;

                                        **n = mat4_add(**n, **b);
                                    }
                                    Sub => {
                                        use vecmath::mat4_sub;

                                        **n = mat4_sub(**n, **b);
                                    }
                                    _ => {
                                        return Err(module.error(
                                            left.source_range(),
                                            &format!("{}\nCan not use this assignment \
                                            operator with `mat4`",
                                                self.stack_trace()), self));
                                    }
                                }
                            }
                            Variable::Return => {
                                if let Set = op {
                                    *r.0 = Variable::Mat4(b.clone())
                                } else {
                                    return Err(module.error(
                                        left.source_range(),
                                        &format!("{}\nReturn has no value",
                                            self.stack_trace()), self))
                                }
                            }
                            _ => return Err(module.error(
                                    left.source_range(),
                                    &format!("{}\nExpected assigning to a mat4",
                                        self.stack_trace()), self))
                        }
                    }
                }
                Variable::Bool(b, ref sec) => {
                    unsafe {
                        match *r.0 {
                            Variable::Bool(ref mut n, ref mut n_sec) => {
                                match op {
                                    Set => *n = b,
                                    _ => unimplemented!()
                                };
                                *n_sec = sec.clone();
                            }
                            Variable::Return => {
                                if let Set = op {
                                    *r.0 = Variable::Bool(b, sec.clone())
                                } else {
                                    return Err(module.error(
                                        left.source_range(),
                                        &format!("{}\nReturn has no value",
                                            self.stack_trace()), self))
                                }
                            }
                            Variable::Link(ref mut n) => {
                                if let Add = op {
                                    n.push(&Variable::bool(b))?;
                                } else {
                                    return Err(module.error(
                                        left.source_range(),
                                        &format!("{}\nCan not use this assignment \
                                        operator with `link` and `bool`",
                                            self.stack_trace()), self));
                                }
                            }
                            _ => return Err(module.error(
                                    left.source_range(),
                                    &format!("{}\nExpected assigning to a bool",
                                        self.stack_trace()), self))
                        };
                    }
                }
                Variable::Text(ref b) => {
                    unsafe {
                        match *r.0 {
                            Variable::Text(ref mut n) => {
                                match op {
                                    Set => *n = b.clone(),
                                    Add => Arc::make_mut(n).push_str(b),
                                    _ => unimplemented!()
                                }
                            }
                            Variable::Return => {
                                if let Set = op {
                                    *r.0 = Variable::Text(b.clone())
                                } else {
                                    return Err(module.error(
                                        left.source_range(),
                                        &format!("{}\nReturn has no value",
                                            self.stack_trace()), self))
                                }
                            }
                            Variable::Link(ref mut n) => {
                                if let Add = op {
                                    n.push(&Variable::Text(b.clone()))?;
                                } else {
                                    return Err(module.error(
                                        left.source_range(),
                                        &format!("{}\nCan not use this assignment \
                                        operator with `link` and `text`",
                                            self.stack_trace()), self));
                                }
                            }
                            _ => return Err(module.error(
                                left.source_range(),
                                &format!("{}\nExpected assigning to text",
                                    self.stack_trace()), self))
                        }
                    }
                }
                Variable::Object(ref b) => {
                    unsafe {
                        match *r.0 {
                            Variable::Object(_) => {
                                if let Set = op {
                                    *r.0 = Variable::Object(b.clone())
                                } else {
                                    unimplemented!()
                                }
                            }
                            Variable::Return => {
                                if let Set = op {
                                    *r.0 = Variable::Object(b.clone())
                                } else {
                                    return Err(module.error(
                                        left.source_range(),
                                        &format!("{}\nReturn has no value",
                                            self.stack_trace()), self))
                                }
                            }
                            _ => return Err(module.error(
                                left.source_range(),
                                &format!("{}\nExpected assigning to object",
                                    self.stack_trace()), self))
                        }
                    }
                }
                Variable::Array(ref b) => {
                    unsafe {
                        match *r.0 {
                            Variable::Array(_) => {
                                if let Set = op {
                                    *r.0 = Variable::Array(b.clone())
                                } else {
                                    unimplemented!()
                                }
                            }
                            Variable::Return => {
                                if let Set = op {
                                    *r.0 = Variable::Array(b.clone())
                                } else {
                                    return Err(module.error(
                                        left.source_range(),
                                        &format!("{}\nReturn has no value",
                                            self.stack_trace()), self))
                                }
                            }
                            _ => return Err(module.error(
                                left.source_range(),
                                &format!("{}\nExpected assigning to array",
                                    self.stack_trace()), self))
                        }
                    }
                }
                Variable::Link(ref b) => {
                    unsafe {
                        match *r.0 {
                            Variable::Link(ref mut n) => {
                                match op {
                                    Set => *n = b.clone(),
                                    Add => **n = n.add(b),
                                    Sub => **n = b.add(n),
                                    _ => unimplemented!()
                                }
                            }
                            Variable::Return => {
                                if let Set = op {
                                    *r.0 = Variable::Link(b.clone())
                                } else {
                                    return Err(module.error(
                                        left.source_range(),
                                        &format!("{}\nReturn has no value",
                                            self.stack_trace()), self))
                                }
                            }
                            _ => return Err(module.error(
                                left.source_range(),
                                &format!("{}\nExpected assigning to link",
                                    self.stack_trace()), self))
                        }
                    }
                }
                Variable::Option(ref b) => {
                    unsafe {
                        match *r.0 {
                            Variable::Option(_) => {
                                if let Set = op {
                                    *r.0 = Variable::Option(b.clone())
                                } else {
                                    unimplemented!()
                                }
                            }
                            Variable::Return => {
                                if let Set = op {
                                    *r.0 = Variable::Option(b.clone())
                                } else {
                                    return Err(module.error(
                                        left.source_range(),
                                        &format!("{}\nReturn has no value",
                                            self.stack_trace()), self))
                                }
                            }
                            _ => return Err(module.error(
                                left.source_range(),
                                &format!("{}\nExpected assigning to option",
                                    self.stack_trace()), self))
                        }
                    }
                }
                Variable::Result(ref b) => {
                    unsafe {
                        match *r.0 {
                            Variable::Result(_) => {
                                if let Set = op {
                                    *r.0 = Variable::Result(b.clone())
                                } else {
                                    unimplemented!()
                                }
                            }
                            Variable::Return => {
                                if let Set = op {
                                    *r.0 = Variable::Result(b.clone())
                                } else {
                                    return Err(module.error(
                                        left.source_range(),
                                        &format!("{}\nReturn has no value",
                                            self.stack_trace()), self))
                                }
                            }
                            _ => return Err(module.error(
                                left.source_range(),
                                &format!("{}\nExpected assigning to result",
                                    self.stack_trace()), self))
                        }
                    }
                }
                Variable::RustObject(ref b) => {
                    unsafe {
                        match *r.0 {
                            Variable::RustObject(_) => {
                                if let Set = op {
                                    *r.0 = Variable::RustObject(b.clone())
                                } else {
                                    unimplemented!()
                                }
                            }
                            Variable::Return => {
                                if let Set = op {
                                    *r.0 = Variable::RustObject(b.clone())
                                } else {
                                    return Err(module.error(
                                        left.source_range(),
                                        &format!("{}\nReturn has no value",
                                            self.stack_trace()), self))
                                }
                            }
                            _ => return Err(module.error(
                                left.source_range(),
                                &format!(
                                    "{}\nExpected assigning to rust_object",
                                    self.stack_trace()), self))
                        }
                    }
                }
                Variable::Closure(ref b, ref env) => {
                    unsafe {
                        match *r.0 {
                            Variable::Closure(_, _) => {
                                if let Set = op {
                                    *r.0 = Variable::Closure(b.clone(), env.clone())
                                } else {
                                    unimplemented!()
                                }
                            }
                            Variable::Return => {
                                if let Set = op {
                                    *r.0 = Variable::Closure(b.clone(), env.clone())
                                } else {
                                    return Err(module.error(
                                        left.source_range(),
                                        &format!("{}\nReturn has no value",
                                            self.stack_trace()), self))
                                }
                            }
                            _ => return Err(module.error(
                                left.source_range(),
                                &format!(
                                    "{}\nExpected assigning to closure",
                                    self.stack_trace()), self))
                        }
                    }
                }
                ref x => {
                    return Err(module.error(
                        left.source_range(),
                        &format!("{}\nCan not use this assignment operator with `{}`",
                            self.stack_trace(), x.typeof_var()), self));
                }
            };
            Ok((None, Flow::Continue))
        } else {
            match *left {
                Expression::Item(ref item) => {
                    let x = match self.expression(right, Side::Right, module)? {
                        (x, Flow::Return) => return Ok((x, Flow::Return)),
                        (Some(x), Flow::Continue) => x,
                        _ => return Err(module.error(right.source_range(),
                                    &format!("{}\nExpected something from the right side",
                                        self.stack_trace()), self))
                    };
                    let v = match x {
                        // Use a shallow clone of a reference.
                        Variable::Ref(ind) => self.stack[ind].clone(),
                        x => x
                    };
                    if !item.ids.is_empty() {
                        let x = match self.expression(left, Side::LeftInsert(true), module)? {
                            (Some(x), Flow::Continue) => x,
                            (x, Flow::Return) => return Ok((x, Flow::Return)),
                            _ => return Err(module.error(left.source_range(),
                                    &format!("{}\nExpected something from the left side",
                                        self.stack_trace()), self))
                        };
                        match x {
                            Variable::UnsafeRef(r) => {
                                unsafe { *r.0 = v }
                            }
                            _ => panic!("Expected unsafe reference")
                        }
                    } else {
                        self.local_stack.push((item.name.clone(), self.stack.len()));
                        if item.current {
                            self.current_stack.push((item.name.clone(), self.stack.len()));
                        }
                        self.stack.push(v);
                    }
                    Ok((None, Flow::Continue))
                }
                _ => Err(module.error(left.source_range(),
                                &format!("{}\nExpected item",
                                    self.stack_trace()), self))
            }
        }
    }
    // `insert` is true for `:=` and false for `=`.
    // This works only on objects, but does not have to check since it is
    // ignored for arrays.
    fn item(
        &mut self,
        item: &ast::Item,
        side: Side,
        module: &Arc<Module>
    ) -> Result<(Option<Variable>, Flow), String> {
        use Error;

        #[inline(always)]
        fn try(
            stack: &mut Vec<Variable>,
            call_stack: &[Call],
            v: Result<Box<Variable>, Box<Error>>,
            source_range: Range,
            module: &Module
        ) -> Result<(Option<Variable>, Flow), String> {
            match v {
                Ok(ok) => Ok((Some(*ok), Flow::Continue)),
                Err(mut err) => {
                    let call = call_stack.last().unwrap();
                    if call.stack_len == 0 {
                        return Err(module.error_fnindex(source_range,
                            &format!("{}\nRequires `->` on function `{}`",
                            stack_trace(call_stack),
                            &call.fn_name), call.index));
                    }
                    if let Variable::Return = stack[call.stack_len - 1] {}
                    else {
                        return Err(module.error_fnindex(source_range,
                            &format!("{}\nRequires `->` on function `{}`",
                            stack_trace(call_stack),
                            &call.fn_name),
                            call.index));
                    }
                    let file = match call.file {
                        None => "".into(),
                        Some(ref f) => format!(" ({})", f)
                    };
                    err.trace.push(module.error_fnindex(
                        source_range,
                        &format!("In function `{}`{}", call.fn_name, file),
                        call.index));
                    Ok((Some(Variable::Result(Err(err))), Flow::Return))
                }
            }
        }

        use ast::Id;

        let locals = self.local_stack.len() - self.call_stack.last().unwrap().local_len;
        let stack_id = {
            if cfg!(not(feature = "debug_resolve")) {
                self.stack.len() - item.static_stack_id.get().unwrap()
            } else {
                match item.stack_id.get() {
                    Some(val) => self.stack.len() - val,
                    None => {
                        let name: &str = &**item.name;
                        let mut found = false;
                        for &(ref n, id) in self.local_stack.iter().rev().take(locals) {
                            if **n == name {
                                let new_val = Some(self.stack.len() - id);
                                item.stack_id.set(new_val);

                                let static_stack_id = item.static_stack_id.get();
                                if new_val != static_stack_id {
                                    return Err(module.error(item.source_range,
                                        &format!(
                                            "DEBUG: resolved not same for {} `{:?}` vs static `{:?}`",
                                            name,
                                            new_val,
                                            static_stack_id
                                        ), self));
                                }

                                found = true;
                                break;
                            }
                        }
                        if found {
                            self.stack.len() - item.stack_id.get().unwrap()
                        } else if name == "return" {
                            return Err(module.error(item.source_range, &format!(
                                "{}\nRequires `->` on function `{}`",
                                self.stack_trace(),
                                &self.call_stack.last().unwrap().fn_name), self));
                        } else {
                            return Err(module.error(item.source_range, &format!(
                                "{}\nCould not find local or current variable `{}`",
                                    self.stack_trace(), name), self));
                        }
                    }
                }
            }
        };

        if cfg!(feature = "debug_resolve") {
            for &(ref n, id) in self.local_stack.iter().rev().take(locals) {
                if **n == **item.name {
                    if stack_id != id {
                        return Err(module.error(item.source_range,
                            &format!("DEBUG: Not same for {} stack_id `{:?}` vs id `{:?}`",
                                item.name,
                                stack_id,
                                id), self));
                    }
                    break;
                }
            }
        }

        let stack_id = if let Variable::Ref(ref_id) = self.stack[stack_id] {
                ref_id
            } else {
                stack_id
            };
        if item.ids.is_empty() {
            if item.try {
                // Check for `err(_)` or unwrap when `?` follows item.
                let v = match Runtime::try_msg(&self.stack[stack_id]) {
                    Some(v) => v,
                    None => {
                        return Err(module.error(item.source_range,
                            &format!("{}\nExpected `ok(_)`, `err(_)`, `bool`, `f64`",
                                self.stack_trace()), self));
                    }
                };
                return try(&mut self.stack, &self.call_stack, v,
                           item.source_range, module);
            } else {
                return Ok((Some(Variable::Ref(stack_id)), Flow::Continue));
            }
        }

        // Pre-evaluate expressions for identity.
        let start_stack_len = self.stack.len();
        for id in &item.ids {
            if let Id::Expression(ref expr) = *id {
                match self.expression(expr, Side::Right, module)? {
                    (x, Flow::Return) => return Ok((x, Flow::Return)),
                    (Some(x), Flow::Continue) => self.stack.push(x),
                    _ => return Err(module.error(expr.source_range(),
                        &format!("{}\nExpected something for index",
                            self.stack_trace()), self))
                };
            }
        }
        let &mut Runtime {
            ref mut stack,
            ref mut call_stack,
            ..
        } = self;
        let mut expr_j = 0;
        let insert = match side {
            Side::Right => false,
            Side::LeftInsert(insert) => insert,
        };

        let v = {
            let item_len = item.ids.len();
            // Get the first variable (a.x).y
            let mut var: *mut Variable = item_lookup(
                module,
                &mut stack[stack_id],
                stack,
                call_stack,
                &item.ids[0],
                start_stack_len,
                &mut expr_j,
                insert,
                item_len == 1
            )?;
            let mut try_id_ind = 0;
            if !item.try_ids.is_empty() && item.try_ids[try_id_ind] == 0 {
                // Check for error on `?` for first id.
                let v = unsafe {match Runtime::try_msg(&*var) {
                    Some(v) => v,
                    None => {
                        return Err(module.error_fnindex(item.ids[0].source_range(),
                            &format!("{}\nExpected `ok(_)` or `err(_)`",
                                stack_trace(call_stack)),
                                call_stack.last().unwrap().index));
                    }
                }};
                match v {
                    Ok(ref ok) => unsafe {
                        *var = (**ok).clone();
                        try_id_ind += 1;
                    },
                    Err(ref err) => {
                        let call = call_stack.last().unwrap();
                        if call.stack_len == 0 {
                            return Err(module.error_fnindex(
                                item.ids[0].source_range(),
                                &format!("{}\nRequires `->` on function `{}`",
                                stack_trace(call_stack),
                                &call.fn_name),
                                call.index));
                        }
                        if let Variable::Return = stack[call.stack_len - 1] {}
                        else {
                            return Err(module.error_fnindex(
                                item.ids[0].source_range(),
                                &format!("{}\nRequires `->` on function `{}`",
                                stack_trace(call_stack),
                                &call.fn_name),
                                call.index));
                        }
                        let mut err = err.clone();
                        let file = match call.file.as_ref() {
                            None => "".into(),
                            Some(f) => format!(" ({})", f)
                        };
                        err.trace.push(module.error_fnindex(
                            item.ids[0].source_range(),
                            &format!("In function `{}`{}",
                                &call.fn_name, file),
                                call.index));
                        return Ok((Some(Variable::Result(Err(err))), Flow::Return));
                    }
                }
            }
            // Get the rest of the variables.
            for (i, prop) in item.ids[1..].iter().enumerate() {
                var = item_lookup(
                    module,
                    unsafe { &mut *var },
                    stack,
                    call_stack,
                    prop,
                    start_stack_len,
                    &mut expr_j,
                    insert,
                    // `i` skips first index.
                    i + 2 == item_len
                )?;

                if item.try_ids.len() > try_id_ind &&
                   item.try_ids[try_id_ind] == i + 1 {
                    // Check for error on `?` for rest of ids.
                    let v = unsafe {match Runtime::try_msg(&*var) {
                        Some(v) => v,
                        None => {
                            return Err(module.error_fnindex(prop.source_range(),
                                &format!("{}\nExpected `ok(_)`, `err(_)`, `bool`, `f64`",
                                    stack_trace(call_stack)),
                                    call_stack.last().unwrap().index));
                        }
                    }};
                    match v {
                        Ok(ref ok) => unsafe {
                            *var = (**ok).clone();
                            try_id_ind += 1;
                        },
                        Err(ref err) => {
                            let call = call_stack.last().unwrap();
                            if call.stack_len == 0 {
                                return Err(module.error_fnindex(
                                    prop.source_range(),
                                    &format!("{}\nRequires `->` on function `{}`",
                                        stack_trace(call_stack),
                                        &call.fn_name),
                                        call.index));
                            }
                            if let Variable::Return = stack[call.stack_len - 1] {}
                            else {
                                return Err(module.error_fnindex(
                                    prop.source_range(),
                                    &format!("{}\nRequires `->` on function `{}`",
                                        stack_trace(call_stack),
                                        &call.fn_name),
                                        call.index));
                            }
                            let mut err = err.clone();
                            let file = match call.file.as_ref() {
                                None => "".into(),
                                Some(f) => format!(" ({})", f)
                            };
                            err.trace.push(module.error_fnindex(
                                prop.source_range(),
                                &format!("In function `{}`{}",
                                    &call.fn_name, file),
                                    call.index));
                            return Ok((Some(Variable::Result(Err(err))), Flow::Return));
                        }
                    }
                }
            }

            match side {
                Side::Right => unsafe {&*var}.clone(),
                Side::LeftInsert(_) => Variable::UnsafeRef(UnsafeRef(var))
            }
        };
        stack.truncate(start_stack_len);
        Ok((Some(v), Flow::Continue))
    }

    fn compare(
        &mut self,
        compare: &ast::Compare,
        module: &Arc<Module>
    ) -> Result<(Option<Variable>, Flow), String> {
        fn sub_compare(
            rt: &Runtime,
            compare: &ast::Compare,
            module: &Module,
            a: &Variable,
            b: &Variable
        ) -> Result<Variable, String> {
            use ast::CompareOp::*;

            match (rt.resolve(&b), rt.resolve(&a)) {
                (&Variable::F64(b, _), &Variable::F64(a, ref sec)) => {
                    Ok(Variable::Bool(match compare.op {
                        Less => a < b,
                        LessOrEqual => a <= b,
                        Greater => a > b,
                        GreaterOrEqual => a >= b,
                        Equal => a == b,
                        NotEqual => a != b
                    }, sec.clone()))
                }
                (&Variable::Text(ref b), &Variable::Text(ref a)) => {
                    Ok(Variable::bool(match compare.op {
                        Less => a < b,
                        LessOrEqual => a <= b,
                        Greater => a > b,
                        GreaterOrEqual => a >= b,
                        Equal => a == b,
                        NotEqual => a != b
                    }))
                }
                (&Variable::Bool(b, _), &Variable::Bool(a, ref sec)) => {
                    Ok(Variable::Bool(match compare.op {
                        Equal => a == b,
                        NotEqual => a != b,
                        x => return Err(module.error(compare.source_range,
                            &format!("{}\n`{}` can not be used with bools",
                                rt.stack_trace(),
                                x.symbol()), rt))
                    }, sec.clone()))
                }
                (&Variable::Vec4(ref b), &Variable::Vec4(ref a)) => {
                    Ok(Variable::bool(match compare.op {
                        Equal => a == b,
                        NotEqual => a != b,
                        x => return Err(module.error(compare.source_range,
                            &format!("{}\n`{}` can not be used with vec4s",
                                rt.stack_trace(),
                                x.symbol()), rt))
                    }))
                }
                (&Variable::Object(ref b), &Variable::Object(ref a)) => {
                    Ok(Variable::bool(match compare.op {
                        Equal => {
                            a.len() == b.len() &&
                            a.iter().all(|a| {
                                if let Some(b_val) = b.get(a.0) {
                                    if let Ok(Variable::Bool(true, _)) =
                                        sub_compare(rt, compare, module, &a.1, b_val) {true}
                                    else {false}
                                } else {false}
                            })
                        }
                        NotEqual => {
                            a.len() != b.len() ||
                            a.iter().any(|a| {
                                if let Some(b_val) = b.get(a.0) {
                                    if let Ok(Variable::Bool(false, _)) =
                                        sub_compare(rt, compare, module, &a.1, b_val) {false}
                                    else {true}
                                } else {true}
                            })
                        }
                        x => return Err(module.error(compare.source_range,
                            &format!("{}\n`{}` can not be used with objects",
                                rt.stack_trace(),
                                x.symbol()), rt))
                    }))
                }
                (&Variable::Array(ref b), &Variable::Array(ref a)) => {
                    Ok(Variable::bool(match compare.op {
                        Equal => {
                            a.len() == b.len() &&
                            a.iter().zip(b.iter()).all(|(a, b)| {
                                if let Ok(Variable::Bool(true, _)) =
                                    sub_compare(rt, compare, module, a, b) {true} else {false}
                            })
                        }
                        NotEqual => {
                            a.len() != b.len() ||
                            a.iter().zip(b.iter()).any(|(a, b)| {
                                if let Ok(Variable::Bool(false, _)) =
                                    sub_compare(rt, compare, module, a, b) {false} else {true}
                            })
                        }
                        x => return Err(module.error(compare.source_range,
                            &format!("{}\n`{}` can not be used with arrays",
                                rt.stack_trace(),
                                x.symbol()), rt))
                    }))
                }
                (&Variable::Option(None), &Variable::Option(None)) => {
                    Ok(Variable::bool(match compare.op {
                        Equal => true,
                        NotEqual => false,
                        x => return Err(module.error(compare.source_range,
                            &format!("{}\n`{}` can not be used with options",
                                rt.stack_trace(),
                                x.symbol()), rt))
                    }))
                }
                (&Variable::Option(None), &Variable::Option(_)) => {
                    Ok(Variable::bool(match compare.op {
                        Equal => false,
                        NotEqual => true,
                        x => return Err(module.error(compare.source_range,
                            &format!("{}\n`{}` can not be used with options",
                                rt.stack_trace(),
                                x.symbol()), rt))
                    }))
                }
                (&Variable::Option(_), &Variable::Option(None)) => {
                    Ok(Variable::bool(match compare.op {
                        Equal => false,
                        NotEqual => true,
                        x => return Err(module.error(compare.source_range,
                            &format!("{}\n`{}` can not be used with options",
                                rt.stack_trace(),
                                x.symbol()), rt))
                    }))
                }
                (&Variable::Option(Some(ref b)),
                 &Variable::Option(Some(ref a))) => {
                    sub_compare(rt, compare, module, a, b)
                }
                (b, a) => Err(module.error(compare.source_range,
                    &format!(
                    "{}\n`{}` can not be used with `{}` and `{}`",
                    rt.stack_trace(),
                    compare.op.symbol(),
                    a.typeof_var(),
                    b.typeof_var()), rt))
            }
        }

        let left = match self.expression(&compare.left, Side::Right, module)? {
            (Some(x), Flow::Continue) => x,
            (x, Flow::Return) => { return Ok((x, Flow::Return)); }
            _ => return Err(module.error(compare.left.source_range(),
                &format!("{}\nExpected something from the left argument",
                    self.stack_trace()), self))
        };
        let right = match self.expression(&compare.right, Side::Right, module)? {
            (Some(x), Flow::Continue) => x,
            (x, Flow::Return) => return Ok((x, Flow::Return)),
            _ => return Err(module.error(compare.right.source_range(),
                &format!("{}\nExpected something from the right argument",
                    self.stack_trace()), self))
        };
        Ok((Some(sub_compare(self, compare, module, &left, &right)?), Flow::Continue))
    }
    fn if_expr(
        &mut self,
        if_expr: &ast::If,
        module: &Arc<Module>
    ) -> Result<(Option<Variable>, Flow), String> {
        let cond = match self.expression(&if_expr.cond, Side::Right, module)? {
            (Some(x), Flow::Continue) => x,
            (x, Flow::Return) => { return Ok((x, Flow::Return)); }
            _ => return Err(module.error(if_expr.cond.source_range(),
                &format!("{}\nExpected bool from if condition",
                    self.stack_trace()), self))
        };
        let val = match *self.resolve(&cond) {
            Variable::Bool(val, _) => val,
            _ => return Err(module.error(if_expr.cond.source_range(),
                &format!("{}\nExpected bool from if condition",
                    self.stack_trace()), self))
        };
        if val {
            return self.block(&if_expr.true_block, module);
        }
        for (cond, body) in if_expr.else_if_conds.iter()
            .zip(if_expr.else_if_blocks.iter()) {
            let else_if_cond = match self.expression(cond, Side::Right, module)? {
                (Some(x), Flow::Continue) => x,
                (x, Flow::Return) => {
                    return Ok((x, Flow::Return));
                }
                _ => return Err(module.error(cond.source_range(),
                    &format!("{}\nExpected bool from else if condition",
                        self.stack_trace()), self))
            };
            match *self.resolve(&else_if_cond) {
                Variable::Bool(false, _) => {}
                Variable::Bool(true, _) => {
                    return self.block(body, module);
                }
                _ => return Err(module.error(cond.source_range(),
                    &format!("{}\nExpected bool from else if condition",
                        self.stack_trace()), self))
            }
        }
        if let Some(ref block) = if_expr.else_block {
            self.block(block, module)
        } else {
            Ok((None, Flow::Continue))
        }
    }
    fn for_expr(
        &mut self,
        for_expr: &ast::For,
        module: &Arc<Module>
    ) -> Result<(Option<Variable>, Flow), String> {
        let prev_st = self.stack.len();
        let prev_lc = self.local_stack.len();
        match self.expression(&for_expr.init, Side::Right, module)? {
        (None, Flow::Continue) => {}
            (x, Flow::Return) => { return Ok((x, Flow::Return)); }
            _ => return Err(module.error(for_expr.init.source_range(),
                &format!("{}\nExpected nothing from for init",
                    self.stack_trace()), self))
        };
        let st = self.stack.len();
        let lc = self.local_stack.len();
        let mut flow = Flow::Continue;
        loop {
            let val = match self.expression(&for_expr.cond, Side::Right, module)? {
                (Some(x), Flow::Continue) => x,
                (x, Flow::Return) => return Ok((x, Flow::Return)),
                _ => return Err(module.error(for_expr.cond.source_range(),
                    &format!("{}\nExpected bool from for condition",
                        self.stack_trace()), self))
            };
            let val = match val {
                Variable::Bool(val, _) => val,
                _ => return Err(module.error(
                    for_expr.cond.source_range(),
                    &format!("{}\nExpected bool", self.stack_trace()), self))
            };
            if !val { break }
            match self.block(&for_expr.block, module)? {
                (x, Flow::Return) => return Ok((x, Flow::Return)),
                (_, Flow::Continue) => {}
                (_, Flow::Break(x)) => {
                    if let Some(label) = x {
                        let same =
                        if let Some(ref for_label) = for_expr.label {
                            &label == for_label
                        } else { false };
                        if !same {
                            flow = Flow::Break(Some(label))
                        }
                    }
                    break;
                }
                (_, Flow::ContinueLoop(x)) => {
                    if let Some(label) = x {
                        let same =
                        if let Some(ref for_label) = for_expr.label {
                            &label == for_label
                        } else { false };
                        if !same {
                            flow = Flow::ContinueLoop(Some(label));
                            break;
                        }
                    }
                    match self.expression(&for_expr.step, Side::Right, module)? {
                        (None, Flow::Continue) => {}
                        (x, Flow::Return) => return Ok((x, Flow::Return)),
                        _ => return Err(module.error(
                            for_expr.step.source_range(),
                            &format!("{}\nExpected nothing from for step",
                                self.stack_trace()), self))
                    };
                    continue;
                }
            }
            match self.expression(&for_expr.step, Side::Right, module)? {
                (None, Flow::Continue) => {}
                (x, Flow::Return) => return Ok((x, Flow::Return)),
                _ => return Err(module.error(
                    for_expr.step.source_range(),
                    &format!("{}\nExpected nothing from for step",
                        self.stack_trace()), self))
            };
            self.stack.truncate(st);
            self.local_stack.truncate(lc);
        };
        self.stack.truncate(prev_st);
        self.local_stack.truncate(prev_lc);
        Ok((None, flow))
    }
    fn vec4(
        &mut self,
        vec4: &ast::Vec4,
        side: Side,
        module: &Arc<Module>
    ) -> Result<(Option<Variable>, Flow), String> {
        let st = self.stack.len();
        for expr in &vec4.args {
            match self.expression(expr, side, module)? {
                (None, Flow::Continue) => {}
                (Some(x), Flow::Continue) => self.stack.push(x),
                (x, Flow::Return) => return Ok((x, Flow::Return)),
                _ => return Err(module.error(expr.source_range(),
                    &format!("{}\nExpected something from vec4 argument",
                        self.stack_trace()), self))
            };
            // Skip the rest if swizzling pushes arguments.
            if self.stack.len() - st > 3 { break; }
        }
        let w = self.stack.pop().expect(TINVOTS);
        let w = match self.resolve(&w) {
            &Variable::F64(val, _) => val,
            x => return Err(module.error(vec4.args[3].source_range(),
                &self.expected(x, "number"), self))
        };
        let z = self.stack.pop().expect(TINVOTS);
        let z = match self.resolve(&z) {
            &Variable::F64(val, _) => val,
            x => return Err(module.error(vec4.args[2].source_range(),
                &self.expected(x, "number"), self))
        };
        let y = self.stack.pop().expect(TINVOTS);
        let y = match self.resolve(&y) {
            &Variable::F64(val, _) => val,
            x => return Err(module.error(vec4.args[1].source_range(),
                &self.expected(x, "number"), self))
        };
        let x = self.stack.pop().expect(TINVOTS);
        let x = match self.resolve(&x) {
            &Variable::F64(val, _) => val,
            x => return Err(module.error(vec4.args[0].source_range(),
                &self.expected(x, "number"), self))
        };
        Ok((Some(Variable::Vec4([x as f32, y as f32, z as f32, w as f32])), Flow::Continue))
    }
    fn mat4(
        &mut self,
        mat4: &ast::Mat4,
        side: Side,
        module: &Arc<Module>
    ) -> Result<(Option<Variable>, Flow), String> {
        for expr in &mat4.args {
            match self.expression(expr, side, module)? {
                (None, Flow::Continue) => {}
                (Some(x), Flow::Continue) => self.stack.push(x),
                (x, Flow::Return) => return Ok((x, Flow::Return)),
                _ => return Err(module.error(expr.source_range(),
                    &format!("{}\nExpected something from mat4 argument",
                        self.stack_trace()), self))
            };
        }
        let w = self.stack.pop().expect(TINVOTS);
        let w = match self.resolve(&w) {
            &Variable::Vec4(val) => val,
            x => return Err(module.error(mat4.args[3].source_range(),
                &self.expected(x, "vec4"), self))
        };
        let z = self.stack.pop().expect(TINVOTS);
        let z = match self.resolve(&z) {
            &Variable::Vec4(val) => val,
            x => return Err(module.error(mat4.args[2].source_range(),
                &self.expected(x, "vec4"), self))
        };
        let y = self.stack.pop().expect(TINVOTS);
        let y = match self.resolve(&y) {
            &Variable::Vec4(val) => val,
            x => return Err(module.error(mat4.args[1].source_range(),
                &self.expected(x, "vec4"), self))
        };
        let x = self.stack.pop().expect(TINVOTS);
        let x = match self.resolve(&x) {
            &Variable::Vec4(val) => val,
            x => return Err(module.error(mat4.args[0].source_range(),
                &self.expected(x, "vec4"), self))
        };
        Ok((Some(Variable::Mat4(Box::new([
            [x[0], y[0], z[0], w[0]],
            [x[1], y[1], z[1], w[1]],
            [x[2], y[2], z[2], w[2]],
            [x[3], y[3], z[3], w[3]],
        ]))), Flow::Continue))
    }
    fn norm(
        &mut self,
        norm: &ast::Norm,
        side: Side,
        module: &Arc<Module>
    ) -> Result<(Option<Variable>, Flow), String> {
        let val = match self.expression(&norm.expr, side, module)? {
            (Some(x), Flow::Continue) => x,
            (x, Flow::Return) => return Ok((x, Flow::Return)),
            _ => return Err(module.error(norm.source_range,
                &format!("{}\nExpected something from unary argument",
                    self.stack_trace()), self))
        };
        let v = match *self.resolve(&val) {
            Variable::Vec4(b) => {
                Variable::f64(f64::from(b[0] * b[0] + b[1] * b[1] + b[2] * b[2]).sqrt())
            }
            ref x => return Err(module.error(norm.source_range,
                &self.expected(x, "vec4"), self))
        };
        Ok((Some(v), Flow::Continue))
    }
    fn unop(
        &mut self,
        unop: &ast::UnOpExpression,
        side: Side,
        module: &Arc<Module>
    ) -> Result<(Option<Variable>, Flow), String> {
        let val = match self.expression(&unop.expr, side, module)? {
            (Some(x), Flow::Continue) => x,
            (x, Flow::Return) => return Ok((x, Flow::Return)),
            _ => return Err(module.error(unop.source_range,
                &format!("{}\nExpected something from unary argument",
                    self.stack_trace()), self))
        };
        let v = match *self.resolve(&val) {
            Variable::Bool(b, ref sec) => {
                Variable::Bool(match unop.op {
                    ast::UnOp::Not => !b,
                    _ => return Err(module.error(unop.source_range,
                                    &format!("{}\nUnknown boolean unary operator",
                                             self.stack_trace()), self))
                }, sec.clone())
            }
            Variable::F64(v, ref sec) => {
                Variable::F64(match unop.op {
                    ast::UnOp::Neg => -v,
                    _ => return Err(module.error(unop.source_range,
                                    &format!("{}\nUnknown number unary operator",
                                             self.stack_trace()), self))
                }, sec.clone())
            }
            Variable::Vec4(v) => {
                Variable::Vec4(match unop.op {
                    ast::UnOp::Neg => [-v[0], -v[1], -v[2], -v[3]],
                    _ => return Err(module.error(unop.source_range,
                                    &format!("{}\nUnknown vec4 unary operator",
                                             self.stack_trace()), self))
                })
            }
            Variable::Mat4(ref m) => {
                match unop.op {
                    ast::UnOp::Neg => Variable::Mat4(Box::new([
                            [-m[0][0], -m[0][1], -m[0][2], -m[0][3]],
                            [-m[1][0], -m[1][1], -m[1][2], -m[1][3]],
                            [-m[2][0], -m[2][1], -m[2][2], -m[2][3]],
                            [-m[3][0], -m[3][1], -m[3][2], -m[3][3]],
                        ])),
                    _ => return Err(module.error(unop.source_range,
                                    &format!("{}\nUnknown mat4 unary operator",
                                             self.stack_trace()), self))
                }
            }
            _ => return Err(module.error(unop.source_range,
                &format!("{}\nInvalid type for unary operator, expected bool, f64, vec4 or mat4", self.stack_trace()), self))
        };
        Ok((Some(v), Flow::Continue))
    }
    fn binop(
        &mut self,
        binop: &ast::BinOpExpression,
        side: Side,
        module: &Arc<Module>
    ) -> Result<(Option<Variable>, Flow), String> {
        use ast::BinOp::*;

        let left = match self.expression(&binop.left, side, module)? {
            (Some(x), Flow::Continue) => x,
            (x, Flow::Return) => return Ok((x, Flow::Return)),
            _ => return Err(module.error(binop.source_range,
                &format!("{}\nExpected something from left argument",
                    self.stack_trace()), self))
        };

        // Check lazy boolean expressions.
        match binop.op {
            OrElse => {
                if let Variable::Bool(true, ref sec) = *self.resolve(&left) {
                    return Ok((Some(Variable::Bool(true, sec.clone())), Flow::Continue));
                }
            }
            AndAlso => {
                if let Variable::Bool(false, ref sec) = *self.resolve(&left) {
                    return Ok((Some(Variable::Bool(false, sec.clone())), Flow::Continue));
                }
            }
            _ => {}
        }

        let right = match self.expression(&binop.right, side, module)? {
            (Some(x), Flow::Continue) => x,
            (x, Flow::Return) => return Ok((x, Flow::Return)),
            _ => return Err(module.error(binop.source_range,
                &format!("{}\nExpected something from right argument",
                    self.stack_trace()), self))
        };
        let v = match (self.resolve(&left), self.resolve(&right)) {
            (&Variable::F64(a, ref sec), &Variable::F64(b, _)) => {
                Variable::F64(match binop.op {
                    Add => a + b,
                    Sub => a - b,
                    Mul => a * b,
                    Div => a / b,
                    Rem => a % b,
                    Pow => a.powf(b),
                    _ => return Err(module.error(binop.source_range,
                        &format!("{}\nUnknown number operator `{:?}`",
                            self.stack_trace(),
                            binop.op.symbol()), self))
                }, sec.clone())
            }
            (&Variable::Vec4(a), &Variable::Vec4(b)) => {
                match binop.op {
                    Add => Variable::Vec4([a[0] + b[0], a[1] + b[1], a[2] + b[2], a[3] + b[3]]),
                    Sub => Variable::Vec4([a[0] - b[0], a[1] - b[1], a[2] - b[2], a[3] - b[3]]),
                    Mul => Variable::Vec4([a[0] * b[0], a[1] * b[1], a[2] * b[2], a[3] * b[3]]),
                    Dot => Variable::f64(f64::from(a[0] * b[0] + a[1] * b[1] +
                                                   a[2] * b[2] + a[3] * b[3])),
                    Cross => Variable::Vec4([a[1] * b[2] - a[2] * b[1],
                                             a[2] * b[0] - a[0] * b[2],
                                             a[0] * b[1] - a[1] * b[0], 0.0]),
                    Div => Variable::Vec4([a[0] / b[0], a[1] / b[1], a[2] / b[2], a[3] / b[3]]),
                    Rem => Variable::Vec4([a[0] % b[0], a[1] % b[1], a[2] % b[2], a[3] % b[3]]),
                    Pow => Variable::Vec4([a[0].powf(b[0]), a[1].powf(b[1]),
                                           a[2].powf(b[2]), a[3].powf(b[3])]),
                    AndAlso | OrElse => return Err(module.error(binop.source_range,
                        &format!("{}\nUnknown operator `{:?}` for `vec4` and `vec4`",
                            self.stack_trace(),
                            binop.op.symbol_bool()), self)),
                }
            }
            (&Variable::Vec4(a), &Variable::F64(b, _)) => {
                let b = b as f32;
                match binop.op {
                    Add => Variable::Vec4([a[0] + b, a[1] + b, a[2] + b, a[3] + b]),
                    Sub => Variable::Vec4([a[0] - b, a[1] - b, a[2] - b, a[3] - b]),
                    Mul => Variable::Vec4([a[0] * b, a[1] * b, a[2] * b, a[3] * b]),
                    Dot => Variable::f64(f64::from(a[0] * b + a[1] * b + a[2] * b + a[3] * b)),
                    Cross => return Err(module.error(binop.source_range,
                        &format!("{}\nExpected two vec4 for `{:?}`",
                            self.stack_trace(), binop.op.symbol()), self)),
                    Div => Variable::Vec4([a[0] / b, a[1] / b, a[2] / b, a[3] / b]),
                    Rem => Variable::Vec4([a[0] % b, a[1] % b, a[2] % b, a[3] % b]),
                    Pow => Variable::Vec4([a[0].powf(b), a[1].powf(b),
                                           a[2].powf(b), a[3].powf(b)]),
                    AndAlso | OrElse => return Err(module.error(binop.source_range,
                        &format!("{}\nUnknown operator `{:?}` for `vec4` and `f64`",
                            self.stack_trace(),
                            binop.op.symbol_bool()), self)),
                }
            }
            (&Variable::F64(a, _), &Variable::Vec4(b)) => {
                let a = a as f32;
                match binop.op {
                    Add => Variable::Vec4([a + b[0], a + b[1], a + b[2], a + b[3]]),
                    Sub => Variable::Vec4([a - b[0], a - b[1], a - b[2], a - b[3]]),
                    Mul => Variable::Vec4([a * b[0], a * b[1], a * b[2], a * b[3]]),
                    Dot => Variable::f64(f64::from(a * b[0] + a * b[1] + a * b[2] + a * b[3])),
                    Div => Variable::Vec4([a / b[0], a / b[1], a / b[2], a / b[3]]),
                    Rem => Variable::Vec4([a % b[0], a % b[1], a % b[2], a % b[3]]),
                    Pow => Variable::Vec4([a.powf(b[0]), a.powf(b[1]),
                                           a.powf(b[2]), a.powf(b[3])]),
                    Cross => return Err(module.error(binop.source_range,
                        &format!("{}\nExpected two vec4 for `{:?}`",
                            self.stack_trace(), binop.op.symbol()), self)),
                    AndAlso | OrElse => return Err(module.error(binop.source_range,
                        &format!("{}\nUnknown operator `{:?}` for `f64` and `vec4`",
                            self.stack_trace(),
                            binop.op.symbol_bool()), self)),
                }
            }
            (&Variable::Mat4(ref a), &Variable::Mat4(ref b)) => {
                use vecmath::{mat4_add, mat4_sub, col_mat4_mul};

                match binop.op {
                    Add => Variable::Mat4(Box::new(mat4_add(**a, **b))),
                    Sub => Variable::Mat4(Box::new(mat4_sub(**a, **b))),
                    Mul => Variable::Mat4(Box::new(col_mat4_mul(**a, **b))),
                    _ => return Err(module.error(binop.source_range,
                        &format!("{}\nUnknown operator `{:?}` for `mat4` and `mat4`",
                            self.stack_trace(),
                            binop.op.symbol_bool()), self)),
                }
            }
            (&Variable::F64(a, _), &Variable::Mat4(ref b)) => {
                let a = a as f32;
                match binop.op {
                    Add => Variable::Mat4(Box::new([
                            [b[0][0] + a, b[0][1] + a, b[0][2] + a, b[0][3] + a],
                            [b[1][0] + a, b[1][1] + a, b[1][2] + a, b[1][3] + a],
                            [b[2][0] + a, b[2][1] + a, b[2][2] + a, b[2][3] + a],
                            [b[3][0] + a, b[3][1] + a, b[3][2] + a, b[3][3] + a]
                        ])),
                    Sub => Variable::Mat4(Box::new([
                            [a - b[0][0], a - b[0][1], a - b[0][2], a - b[0][3]],
                            [a - b[1][0], a - b[1][1], a - b[1][2], a - b[1][3]],
                            [a - b[2][0], a - b[2][1], a - b[2][2], a - b[2][3]],
                            [a - b[3][0], a - b[3][1], a - b[3][2], a - b[3][3]]
                        ])),
                    Mul => Variable::Mat4(Box::new([
                            [b[0][0] * a, b[0][1] * a, b[0][2] * a, b[0][3] * a],
                            [b[1][0] * a, b[1][1] * a, b[1][2] * a, b[1][3] * a],
                            [b[2][0] * a, b[2][1] * a, b[2][2] * a, b[2][3] * a],
                            [b[3][0] * a, b[3][1] * a, b[3][2] * a, b[3][3] * a]
                        ])),
                    _ => return Err(module.error(binop.source_range,
                        &format!("{}\nUnknown operator `{:?}` for `f64` and `mat4`",
                            self.stack_trace(),
                            binop.op.symbol_bool()), self)),
                }
            }
            (&Variable::Mat4(ref b), &Variable::F64(a, _)) => {
                let a = a as f32;
                match binop.op {
                    Add => Variable::Mat4(Box::new([
                            [b[0][0] + a, b[0][1] + a, b[0][2] + a, b[0][3] + a],
                            [b[1][0] + a, b[1][1] + a, b[1][2] + a, b[1][3] + a],
                            [b[2][0] + a, b[2][1] + a, b[2][2] + a, b[2][3] + a],
                            [b[3][0] + a, b[3][1] + a, b[3][2] + a, b[3][3] + a]
                        ])),
                    Sub => Variable::Mat4(Box::new([
                            [b[0][0] - a, b[0][1] - a, b[0][2] - a, b[0][3] - a],
                            [b[1][0] - a, b[1][1] - a, b[1][2] - a, b[1][3] - a],
                            [b[2][0] - a, b[2][1] - a, b[2][2] - a, b[2][3] - a],
                            [b[3][0] - a, b[3][1] - a, b[3][2] - a, b[3][3] - a]
                        ])),
                    Mul => Variable::Mat4(Box::new([
                            [b[0][0] * a, b[0][1] * a, b[0][2] * a, b[0][3] * a],
                            [b[1][0] * a, b[1][1] * a, b[1][2] * a, b[1][3] * a],
                            [b[2][0] * a, b[2][1] * a, b[2][2] * a, b[2][3] * a],
                            [b[3][0] * a, b[3][1] * a, b[3][2] * a, b[3][3] * a]
                        ])),
                    _ => return Err(module.error(binop.source_range,
                        &format!("{}\nUnknown operator `{:?}` for `f64` and `mat4`",
                            self.stack_trace(),
                            binop.op.symbol_bool()), self)),
                }
            }
            (&Variable::Mat4(ref a), &Variable::Vec4(b)) => {
                use vecmath::col_mat4_transform;

                match binop.op {
                    Mul => Variable::Vec4(col_mat4_transform(**a, b)),
                    _ => return Err(module.error(binop.source_range,
                        &format!("{}\nUnknown operator `{:?}` for `mat4` and `vec4`",
                            self.stack_trace(),
                            binop.op.symbol_bool()), self)),
                }
            }
            (&Variable::Bool(a, ref sec), &Variable::Bool(b, _)) => {
                Variable::Bool(match binop.op {
                    Add | OrElse => a || b,
                    // Boolean subtraction with lazy precedence.
                    Sub => a && !b,
                    Mul | AndAlso => a && b,
                    Pow => a ^ b,
                    _ => return Err(module.error(binop.source_range,
                        &format!("{}\nUnknown boolean operator `{:?}`",
                            self.stack_trace(),
                            binop.op.symbol_bool()), self))
                }, sec.clone())
            }
            (&Variable::Text(ref a), &Variable::Text(ref b)) => {
                match binop.op {
                    Add => {
                        let mut res = String::with_capacity(a.len() + b.len());
                        res.push_str(a);
                        res.push_str(b);
                        Variable::Text(Arc::new(res))
                    }
                    _ => return Err(module.error(binop.source_range,
                        &format!("{}\nThis operation can not be used with strings",
                            self.stack_trace()), self))
                }
            }
            (&Variable::Text(_), _) =>
                return Err(module.error(binop.source_range,
                &format!("{}\nThe right argument must be a string. \
                Try the `str` function", self.stack_trace()), self)),
            (&Variable::Link(ref a), &Variable::Link(ref b)) => {
                match binop.op {
                    Add => {
                        Variable::Link(Box::new(a.add(b)))
                    }
                    _ => return Err(module.error(binop.source_range,
                        &format!("{}\nThis operation can not be used with links",
                            self.stack_trace()), self))
                }
            }
            _ => return Err(module.error(binop.source_range, &format!(
                "{}\nInvalid type for binary operator `{:?}`, \
                expected numbers, vec4s, bools or strings",
                self.stack_trace(),
                binop.op.symbol()), self))
        };

        Ok((Some(v), Flow::Continue))
    }
    pub(crate) fn stack_trace(&self) -> String {
        stack_trace(&self.call_stack)
    }
}

fn stack_trace(call_stack: &[Call]) -> String {
    let mut s = String::new();
    for call in call_stack.iter() {
        s.push_str(&call.fn_name);
        if let Some(ref file) = call.file {
            s.push_str(" (");
            s.push_str(file);
            s.push(')');
        }
        s.push('\n')
    }
    s
}