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
//! Reduction system of the lambda calculus.
//!
//! [evaluation strategies]: https://en.wikipedia.org/wiki/Evaluation_strategy
//! [reduction strategies]: https://en.wikipedia.org/wiki/Lambda_calculus#Reduction_strategies

use std::cell::RefCell;
use std::collections::HashSet;
use std::iter::FromIterator;
use std::marker::PhantomData;
use std::mem;
use std::rc::Rc;

use environment::Environment;
use inspect::{Inspect, Limit, NoOp, Stop};
use term::{Term, Term::*, VarName};

fn dummy_term() -> Term {
    Var(VarName(String::new()))
}

impl Term {
    /// Returns whether this `Term` is a [beta redex].
    ///
    /// A beta redex is a term of the form (λx.A) M
    ///
    /// The term redex, short for reducible expression, refers to subterms that
    /// can be reduced by one of the reduction rules.
    ///
    /// # Examples
    ///
    /// ```
    /// # use lamcal::{var, lam, app};
    /// let expr1 = app(lam("a", var("a")), var("x"));
    ///
    /// assert!(expr1.is_beta_redex());
    ///
    /// let expr2 = app(var("x"), lam("a", var("a")));
    ///
    /// assert!(!expr2.is_beta_redex());
    ///
    /// let expr3 = app(var("x"), app(lam("a", var("a")), var("y")));
    ///
    /// assert!(expr3.is_beta_redex());
    /// ```
    ///
    /// [beta redex]: https://en.wikipedia.org/wiki/Beta_normal_form#Beta_reduction
    pub fn is_beta_redex(&self) -> bool {
        let mut to_check = Vec::with_capacity(2);
        to_check.push(self);
        while let Some(term) = to_check.pop() {
            match *term {
                Var(_) => {},
                Lam(_, ref body) => to_check.push(body),
                App(ref lhs, ref rhs) => match **lhs {
                    Lam(_, _) => return true,
                    _ => {
                        to_check.push(rhs);
                        to_check.push(lhs);
                    },
                },
            }
        }
        false
    }

    /// Returns whether this `Term` is a [beta normal form].
    ///
    /// A beta normal form is a term that does not contain any beta redex,
    /// i.e. that cannot be further reduced.
    ///
    /// [beta normal form]: https://en.wikipedia.org/wiki/Beta_normal_form
    pub fn is_beta_normal(&self) -> bool {
        !self.is_beta_redex()
    }

    /// Performs an [α-conversion] on this `Term`.
    ///
    /// [α-conversion]: https://en.wikipedia.org/wiki/Lambda_calculus#%CE%B1-conversion
    pub fn alpha<A>(&mut self, names: &HashSet<&VarName>)
    where
        A: AlphaRename,
    {
        alpha_tramp::<A>(self, names)
    }

    /// [Substitutes] all occurrences of `var` as free variables with the
    /// expression `rhs` recursively on the structure of this `Term`.
    ///
    /// [substitutes]: https://en.wikipedia.org/wiki/Lambda_calculus#Substitution
    pub fn substitute(&mut self, var: &VarName, rhs: &Term) {
        substitute_tramp(self, var, rhs)
    }

    /// Applies the expression `rhs` to the param of this lambda abstraction if
    /// this `Term` is of variant `Term::Lam` by recursively substituting all
    /// occurrences of the bound variable in the body of the lambda abstraction
    /// with the expression `rhs`.
    ///
    /// If this `Term` is not a lambda abstraction this function does nothing.
    ///
    /// To avoid name clashes this function performs α-conversions when
    /// appropriate. Therefore a strategy for α-conversion must be given as the
    /// type parameter `A`.
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate lamcal;
    /// # use lamcal::{app, lam, var, Enumerate};
    /// let mut expr = lam("x", app(var("y"), var("x")));
    ///
    /// expr.apply::<Enumerate>(&var("z"));
    ///
    /// assert_eq!(expr, app(var("y"), var("z")));
    /// ```
    pub fn apply<A>(&mut self, rhs: &Term)
    where
        A: AlphaRename,
    {
        apply_mut::<A>(self, rhs)
    }

    /// Performs a [β-reduction] on this `Term`.
    ///
    /// The reduction strategy to be used must be given as the type parameter
    /// `B`, like in the example below.
    ///
    /// If the reduction of the term diverges it can go through an infinite
    /// sequence of evaluation steps. To avoid endless loops, a default limit
    /// of `u32::MAX` reduction steps is applied. Thus this method returns
    /// when either no more reduction is possible or the limit of `u32::MAX`
    /// iterations has been reached.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[macro_use]
    /// # extern crate lamcal;
    /// # use lamcal::{var, lam, app, NormalOrder, Enumerate};
    /// # fn main() {
    /// let mut expr = app![
    ///     lam("a", var("a")),
    ///     lam("b", lam("c", var("b"))),
    ///     var("x"),
    ///     lam("e", var("f"))
    /// ];
    ///
    /// expr.reduce::<NormalOrder<Enumerate>>();
    ///
    /// assert_eq!(expr, var("x"));
    /// # }
    /// ```
    ///
    /// [β-reduction]: https://en.wikipedia.org/wiki/Lambda_calculus#%CE%B2-reduction
    pub fn reduce<B>(&mut self)
    where
        B: BetaReduce,
    {
        let expr = mem::replace(self, dummy_term());
        *self = <B as BetaReduce>::reduce(expr);
    }

    /// Performs a [β-reduction] on this `Term` with inspection.
    ///
    /// The given inspection is called before each contraction (reduction step).
    /// See the documentation of the [`inspect`](mod.inspect.html) module for
    /// information on how to define an inspection and the implementations that
    /// are provided.
    ///
    /// The reduction strategy to be used must be given as the type parameter
    /// `B`.
    pub fn reduce_inspected<B, I>(&mut self, inspect: &mut I)
    where
        B: BetaReduce,
        I: Inspect,
    {
        let expr = mem::replace(self, dummy_term());
        *self = <B as BetaReduce>::reduce_inspected(expr, inspect)
    }

    /// Replaces free variables with the term bound to the variable's name in
    /// the given environment.
    ///
    /// This method walks through the whole term and replaces any free variable
    /// with the term bound to the variable's name in the given environment.
    /// Bound variables are not replaced.
    ///
    /// This method modifies this `Term` in place. If you want to expand named
    /// constants and get the result as a new `Term` while keeping the original
    /// `Term` unchanged use the standalone function [`expand`](fn.expand.html)
    /// instead.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[macro_use]
    /// # extern crate lamcal;
    /// # use lamcal::{app, expand, lam, var, Environment};
    /// # fn main() {
    /// let env = Environment::default();
    ///
    /// let mut expr = app![
    ///     var("C"),
    ///     lam("a", app(var("K"), var("I"))),
    ///     var("e"),
    ///     var("f")
    /// ];
    ///
    /// expr.expand(&env);
    ///
    /// assert_eq!(
    ///     expr,
    ///     app![
    ///         lam("a", lam("b", lam("c", app![var("a"), var("c"), var("b")]))),
    ///         lam("a", app(lam("a", lam("b", var("a"))), lam("a", var("a")))),
    ///         var("e"),
    ///         var("f")
    ///     ]
    /// );
    /// # }
    /// ```
    pub fn expand(&mut self, env: &Environment) {
        expand_tramp_inspected(self, env, &mut NoOp)
    }

    /// Replaces free variables with the term bound to the variable's name in
    /// the given environment with inspection.
    ///
    /// This method walks through the whole term and replaces any free variable
    /// with the term bound to the variable's name in the given environment.
    /// Bound variables are not replaced.
    ///
    /// Before each substitution of a variable with its bound term from the
    /// environment the given inspection is called. See the documentation
    /// of the [`inspect`](mod.inspect.html) module for information on how to
    /// define an inspection and the implementations that are provided.
    ///
    /// This method modifies this `Term` in place. If you want to expand named
    /// constants and get the result as a new `Term` while keeping the original
    /// `Term` unchanged use the standalone function
    /// [`expand`](fn.expand_inspected.html) instead.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[macro_use]
    /// # extern crate lamcal;
    /// # use lamcal::{app, expand_inspected, lam, var, Environment};
    /// # use lamcal::inspect::Collect;
    /// # fn main() {
    /// let env = Environment::default();
    ///
    /// let mut expr = app![
    ///     var("C"),
    ///     lam("a", app(var("K"), var("I"))),
    ///     var("e"),
    ///     var("f")
    /// ];
    ///
    /// let mut collected = Collect::new();
    /// expr.expand_inspected(&env, &mut collected);
    ///
    /// assert_eq!(
    ///     collected.terms(),
    ///     &vec![
    ///         app![
    ///             var("C"),
    ///             lam("a", app(var("K"), var("I"))),
    ///             var("e"),
    ///             var("f")
    ///         ],
    ///         app![
    ///             lam("a", lam("b", lam("c", app![var("a"), var("c"), var("b")]))),
    ///             lam("a", app(var("K"), var("I"))),
    ///             var("e"),
    ///             var("f")
    ///         ],
    ///         app![
    ///             lam("a", lam("b", lam("c", app![var("a"), var("c"), var("b")]))),
    ///             lam("a", app(lam("a", lam("b", var("a"))), var("I"))),
    ///             var("e"),
    ///             var("f")
    ///         ],
    ///     ][..],
    /// );
    /// assert_eq!(
    ///     expr,
    ///     app![
    ///         lam("a", lam("b", lam("c", app![var("a"), var("c"), var("b")]))),
    ///         lam("a", app(lam("a", lam("b", var("a"))), lam("a", var("a")))),
    ///         var("e"),
    ///         var("f")
    ///     ]
    /// );
    /// # }
    /// ```
    pub fn expand_inspected(&mut self, env: &Environment, inspect: &mut impl Inspect) {
        expand_tramp_inspected(self, env, inspect)
    }

    /// Evaluates this lambda expression in the given environment.
    ///
    /// Evaluation comprises the following steps in the given order:
    ///
    /// * expand all named constants with their bound terms found in the
    ///   environment recursively
    /// * perform β-reduction on the expression
    /// * perform α-conversion where needed to avoid name clashes
    ///
    /// For the β-reduction step a reduction strategy is required. Therefore the
    /// reduction strategy must be specified as the type parameter `B`.
    ///
    /// The expansion of named constants step as done by this function is
    /// equivalent to calling the
    /// [`Term::expand`](enum.Term.html#method.expand) method. Similar the
    /// β-reduction step performed by this the function is equivalent to calling
    /// the [`Term::reduce`](enum.Term.html#method.reduce) method.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[macro_use]
    /// # extern crate lamcal;
    /// # use lamcal::{app, evaluate, lam, var, Enumerate, Environment, NormalOrder};
    /// # fn main() {
    /// let env = Environment::default();
    ///
    /// let mut expr = app![
    ///     var("C"),
    ///     lam("x", lam("y", app(var("x"), var("y")))),
    ///     var("e"),
    ///     var("f")
    /// ];
    ///
    /// expr.evaluate::<NormalOrder<Enumerate>>(&env);
    ///
    /// assert_eq!(expr, app(var("f"), var("e")));
    /// # }
    /// ```
    pub fn evaluate<B>(&mut self, env: &Environment)
    where
        B: BetaReduce,
    {
        expand_tramp_inspected(self, env, &mut NoOp);
        let expr = mem::replace(self, dummy_term());
        *self = <B as BetaReduce>::reduce(expr);
    }

    /// Evaluates this lambda expression with inspection in the given
    /// environment.
    ///
    /// For the β-reduction step a reduction strategy is required. Therefore the
    /// reduction strategy must be specified as the type parameter `B`.
    ///
    /// The given inspection is called before each substitution of a free
    /// variable with its bound term and before each contraction (reduction
    /// step). See the documentation of the [`inspect`](mod.inspect.html)
    /// for information on how to define an inspection and the implementations
    /// that are provided.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[macro_use]
    /// # extern crate lamcal;
    /// # use lamcal::{app, evaluate, lam, var, Enumerate, Environment, NormalOrder};
    /// # use lamcal::inspect::{Collect};
    /// # fn main() {
    /// let env = Environment::default();
    ///
    /// let mut expr = app![
    ///     var("C"),
    ///     lam("x", lam("y", app(var("x"), var("y")))),
    ///     var("e"),
    ///     var("f")
    /// ];
    ///
    /// let mut collected = Collect::new();
    ///
    /// expr.evaluate_inspected::<NormalOrder<Enumerate>, _>(&env, &mut collected);
    ///
    /// assert_eq!(
    ///     collected.terms(),
    ///     &vec![
    ///         app![
    ///             var("C"),
    ///             lam("x", lam("y", app(var("x"), var("y")))),
    ///             var("e"),
    ///             var("f")
    ///         ],
    ///         app![
    ///             lam("a", lam("b", lam("c", app![var("a"), var("c"), var("b")]))),
    ///             lam("x", lam("y", app(var("x"), var("y")))),
    ///             var("e"),
    ///             var("f")
    ///         ],
    ///         app![
    ///             lam(
    ///                 "b",
    ///                 lam(
    ///                     "c",
    ///                     app![
    ///                         lam("x", lam("y", app(var("x"), var("y")))),
    ///                         var("c"),
    ///                         var("b")
    ///                     ]
    ///                 )
    ///             ),
    ///             var("e"),
    ///             var("f")
    ///         ],
    ///         app![
    ///             lam(
    ///                 "b",
    ///                 lam("c", app![lam("y", app(var("c"), var("y"))), var("b")])
    ///             ),
    ///             var("e"),
    ///             var("f")
    ///         ],
    ///         app![
    ///             lam("b", lam("c", app(var("c"), var("b")),)),
    ///             var("e"),
    ///             var("f")
    ///         ],
    ///         app![lam("c", app(var("c"), var("e"))), var("f")],
    ///     ][..],
    /// );
    /// assert_eq!(expr, app(var("f"), var("e")));
    /// # }
    /// ```
    pub fn evaluate_inspected<B, I>(&mut self, env: &Environment, inspect: &mut I)
    where
        B: BetaReduce,
        I: Inspect,
    {
        expand_tramp_inspected(self, env, inspect);
        let expr = mem::replace(self, dummy_term());
        *self = <B as BetaReduce>::reduce_inspected(expr, inspect);
    }
}

/// Evaluates a lambda expression in the given environment.
///
/// This function takes the given expression by reference and returns a new
/// `Term` with the evaluation applied. The given `Term` remains unchanged.
///
/// Evaluation comprises the following steps in the given order:
///
/// * expand all named constants with their bound terms found in the
///   environment recursively
/// * perform β-reduction on the expression
/// * perform α-conversion where needed to avoid name clashes
///
/// For the β-reduction step a reduction strategy is required. Therefore the
/// reduction strategy must be specified as the type parameter `B`.
///
/// The expansion of named constants step as done by this function is
/// equivalent to calling the [`expand`](fn.expand.html) function. Similar the
/// β-reduction step performed by this the function is equivalent to calling
/// the [`reduce`](fn.reduce.html) function.
///
/// # Examples
///
/// ```
/// # #[macro_use]
/// # extern crate lamcal;
/// # use lamcal::{app, evaluate, lam, var, Enumerate, Environment, NormalOrder};
/// # fn main() {
/// let env = Environment::default();
///
/// let expr = app![
///     var("C"),
///     lam("x", lam("y", app(var("x"), var("y")))),
///     var("e"),
///     var("f")
/// ];
///
/// let result = evaluate::<NormalOrder<Enumerate>>(&expr, &env);
///
/// assert_eq!(result, app(var("f"), var("e")));
/// # }
/// ```
pub fn evaluate<B>(expr: &Term, env: &Environment) -> Term
where
    B: BetaReduce,
{
    let mut expr2 = expr.clone();
    expand_tramp_inspected(&mut expr2, env, &mut NoOp);
    <B as BetaReduce>::reduce(expr2)
}

/// Evaluates a lambda expression with inspection in the given environment.
///
/// This function takes the given expression by reference and returns a new
/// `Term` with the evaluation applied. The given `Term` remains unchanged.
///
/// For the β-reduction step a reduction strategy is required. Therefore the
/// reduction strategy must be specified as the type parameter `B`.
///
/// The given inspection is called before each substitution of a free variable
/// with its bound term from the environment and before each contraction
/// (reduction step). See the documentation of the
/// [`inspect`](mod.inspect.html) for information on how to define an
/// inspection and the implementations that are provided.
///
/// # Examples
///
/// ```
/// # #[macro_use]
/// # extern crate lamcal;
/// # use lamcal::{app, evaluate_inspected, lam, var, Enumerate, Environment, NormalOrder};
/// # use lamcal::inspect::{Collect};
/// # fn main() {
/// let env = Environment::default();
///
/// let expr = app![
///     var("C"),
///     lam("x", lam("y", app(var("x"), var("y")))),
///     var("e"),
///     var("f")
/// ];
///
/// let mut collected = Collect::new();
///
/// let result = evaluate_inspected::<NormalOrder<Enumerate>, _>(&expr, &env, &mut collected);
///
/// assert_eq!(
///     collected.terms(),
///     &vec![
///         app![
///             var("C"),
///             lam("x", lam("y", app(var("x"), var("y")))),
///             var("e"),
///             var("f")
///         ],
///         app![
///             lam("a", lam("b", lam("c", app![var("a"), var("c"), var("b")]))),
///             lam("x", lam("y", app(var("x"), var("y")))),
///             var("e"),
///             var("f")
///         ],
///         app![
///             lam(
///                 "b",
///                 lam(
///                     "c",
///                     app![
///                         lam("x", lam("y", app(var("x"), var("y")))),
///                         var("c"),
///                         var("b")
///                     ]
///                 )
///             ),
///             var("e"),
///             var("f")
///         ],
///         app![
///             lam(
///                 "b",
///                 lam("c", app![lam("y", app(var("c"), var("y"))), var("b")])
///             ),
///             var("e"),
///             var("f")
///         ],
///         app![
///             lam("b", lam("c", app(var("c"), var("b")),)),
///             var("e"),
///             var("f")
///         ],
///         app![lam("c", app(var("c"), var("e"))), var("f")],
///     ][..],
/// );
/// assert_eq!(result, app(var("f"), var("e")));
/// # }
/// ```
pub fn evaluate_inspected<B, I>(expr: &Term, env: &Environment, inspect: &mut I) -> Term
where
    B: BetaReduce,
    I: Inspect,
{
    let mut expr2 = expr.clone();
    expand_tramp_inspected(&mut expr2, env, inspect);
    <B as BetaReduce>::reduce_inspected(expr2, inspect)
}

/// Replaces free variables in a term with the term that is bound to the
/// variable's name in the given environment.
///
/// This function walks through the whole term and replaces any free variable
/// with the term bound to the variable's name in the given environment. Bound
/// variables are not replaced.
///
/// The result is returned as a new `Term`. The given term remains unchanged. If
/// you want to expand named constants in a term in place use the associated
/// function [`Term::expand`](enum.Term.html#method.expand) instead.
///
/// # Examples
///
/// ```
/// # #[macro_use]
/// # extern crate lamcal;
/// # use lamcal::{app, expand, lam, var, Environment};
/// # fn main() {
/// let env = Environment::default();
///
/// let expr = app![
///     var("C"),
///     lam("a", app(var("K"), var("I"))),
///     var("e"),
///     var("f")
/// ];
///
/// let result = expand(&expr, &env);
///
/// assert_eq!(
///     result,
///     app![
///         lam("a", lam("b", lam("c", app![var("a"), var("c"), var("b")]))),
///         lam("a", app(lam("a", lam("b", var("a"))), lam("a", var("a")))),
///         var("e"),
///         var("f")
///     ]
/// );
/// # }
/// ```
///
/// Bound variables are not replaced even though there is a bound term for the
/// identifier `K` defined in the environment:
///
/// ```
/// # extern crate lamcal;
/// # use lamcal::{app, expand, lam, var, Environment};
/// # fn main() {
/// let env = Environment::default();
///
/// let expr = lam("K", app(var("K"), var("I")));
///
/// let result = expand(&expr, &env);
///
/// assert_eq!(result, lam("K", app(var("K"), lam("a", var("a")))));
/// # }
/// ```
pub fn expand(expr: &Term, env: &Environment) -> Term {
    let mut expr2 = expr.clone();
    expand_tramp_inspected(&mut expr2, env, &mut NoOp);
    expr2
}

/// Replaces free variables in a term with the term that is bound to the
/// variable's name in the given environment.
///
/// This function walks through the whole term and replaces any free variable
/// with the term bound to the variable's name in the given environment. Bound
/// variables are not replaced.
///
/// Before each substitution of a variable with its bound term from the
/// environment the given inspection is called. See the documentation
/// of the [`inspect`](mod.inspect.html) module for information on how to
/// define an inspection and the implementations that are provided.
///
/// The result is returned as a new `Term`. The given term remains unchanged. If
/// you want to expand named constants in a term in place use the associated
/// function [`Term::expand`](enum.Term.html#method.expand) instead.
///
/// # Examples
///
/// ```
/// # #[macro_use]
/// # extern crate lamcal;
/// # use lamcal::{app, expand_inspected, lam, var, Environment};
/// # use lamcal::inspect::Collect;
/// # fn main() {
/// let env = Environment::default();
///
/// let expr = app![
///     var("C"),
///     lam("a", app(var("K"), var("I"))),
///     var("e"),
///     var("f")
/// ];
///
/// let mut collected = Collect::new();
/// let result = expand_inspected(&expr, &env, &mut collected);
///
/// assert_eq!(
///     collected.terms(),
///     &vec![
///         app![
///             var("C"),
///             lam("a", app(var("K"), var("I"))),
///             var("e"),
///             var("f")
///         ],
///         app![
///             lam("a", lam("b", lam("c", app![var("a"), var("c"), var("b")]))),
///             lam("a", app(var("K"), var("I"))),
///             var("e"),
///             var("f")
///         ],
///         app![
///             lam("a", lam("b", lam("c", app![var("a"), var("c"), var("b")]))),
///             lam("a", app(lam("a", lam("b", var("a"))), var("I"))),
///             var("e"),
///             var("f")
///         ],
///     ][..],
/// );
/// assert_eq!(
///     result,
///     app![
///         lam("a", lam("b", lam("c", app![var("a"), var("c"), var("b")]))),
///         lam("a", app(lam("a", lam("b", var("a"))), lam("a", var("a")))),
///         var("e"),
///         var("f")
///     ]
/// );
/// # }
/// ```
pub fn expand_inspected(expr: &Term, env: &Environment, inspect: &mut impl Inspect) -> Term {
    let mut expr2 = expr.clone();
    expand_tramp_inspected(&mut expr2, env, inspect);
    expr2
}

fn expand_tramp_inspected(expr: &mut Term, env: &Environment, inspect: &mut impl Inspect) {
    let mut todo: Vec<(RefCell<*mut Term>, HashSet<VarName>)> = Vec::with_capacity(2);
    todo.push((RefCell::new(expr), HashSet::with_capacity(4)));
    while let Some((term, mut bound_vars)) = todo.pop() {
        unsafe {
            let maybe_expand_with = match **term.borrow() {
                Var(ref name) if !bound_vars.contains(name) => env.lookup_term(name).cloned(),
                _ => None,
            };
            if let Some(mut expand_with) = maybe_expand_with {
                if Stop::Yes == inspect.inspect(expr) {
                    break;
                }
                **term.borrow_mut() = expand_with;
                todo.push((term, bound_vars));
            } else {
                match **term.borrow() {
                    Var(_) => {},
                    Lam(ref param, ref mut body) => {
                        bound_vars.insert(param.to_owned());
                        todo.push((RefCell::new(&mut **body), bound_vars));
                    },
                    App(ref mut lhs, ref mut rhs) => {
                        todo.push((RefCell::new(&mut **rhs), bound_vars.clone()));
                        todo.push((RefCell::new(&mut **lhs), bound_vars));
                    },
                }
            }
        }
    }
}

/// Performs an [α-conversion] on a given lambda expression and returns the
/// result as a new `Term`.
///
/// The type parameter `A` defines the strategy to be used for renaming bound
/// variables.
///
/// The result is returned as a new `Term`. The original term `expr` is not
/// changed. If you want to perform an α-conversion on a term in place use the
/// associated function [`Term::alpha`](enum.Term.html#method.alpha) instead.
///
/// [α-conversion]: https://en.wikipedia.org/wiki/Lambda_calculus#%CE%B1-conversion
pub fn alpha<A>(expr: &Term, names: &HashSet<&VarName>) -> Term
where
    A: AlphaRename,
{
    let mut expr2 = expr.clone();
    alpha_tramp::<A>(&mut expr2, names);
    expr2
}

fn alpha_tramp<A>(expr: &mut Term, names: &HashSet<&VarName>)
where
    A: AlphaRename,
{
    let free_vars: HashSet<VarName> = HashSet::from_iter(
        names
            .into_iter()
            .cloned()
            .cloned()
            .chain(expr.free_vars().into_iter().cloned()),
    );
    let mut todo = Vec::with_capacity(2);
    todo.push((expr, HashSet::<VarName>::with_capacity(4)));
    while let Some((term, mut bound_vars)) = todo.pop() {
        match *term {
            Var(ref mut name) => {
                if bound_vars.contains(name) {
                    while free_vars.contains(name) {
                        <A as AlphaRename>::rename(&mut **name);
                    }
                }
            },
            Lam(ref mut name, ref mut body) => {
                bound_vars.insert(name.to_owned());
                while free_vars.contains(name) {
                    <A as AlphaRename>::rename(&mut **name);
                }
                todo.push((body, bound_vars));
            },
            App(ref mut lhs, ref mut rhs) => {
                todo.push((rhs, bound_vars.clone()));
                todo.push((lhs, bound_vars));
            },
        }
    }
}

/// Defines a strategy for renaming variables during [α-conversion] of terms.
///
/// A possible implementations may choose the next letter in the alphabet for
/// single character names. Another strategy may be to enumerate the variables
/// by appending an increasing number. A third example for an implementation
/// is appending a tick symbol to the variable name.
///
/// [α-conversion]: https://en.wikipedia.org/wiki/Lambda_calculus#%CE%B1-conversion
pub trait AlphaRename {
    /// Renames the given variable name according the implemented strategy.
    fn rename(name: &mut String);
}

/// Implementation of `AlphaRename` that appends an increasing number to the
/// name.
///
/// If the given name ends with a number this number is replaced by the number
/// increased by one. If the last character is a letter the digit 1 is appended.
#[derive(Default, Debug, Clone, Copy, PartialEq)]
pub struct Enumerate;

impl AlphaRename for Enumerate {
    fn rename(name: &mut String) {
        let digits = name
            .chars()
            .rev()
            .take_while(char::is_ascii_digit)
            .collect::<String>()
            .chars()
            .rev()
            .collect::<String>();
        // digits should be either a parsable number or an empty string
        if let Ok(number) = digits.parse::<usize>() {
            let index = name.len() - digits.len();
            name.drain(index..);
            name.push_str(&(number + 1).to_string());
        } else {
            name.push('1');
        }
    }
}

/// Implementation of `AlphaRename` that appends a tick symbol `'` at the end
/// of a variable name.
///
/// If the given name already ends with a tick symbol another tick symbol is
/// appended.
#[derive(Default, Debug, Clone, Copy, PartialEq)]
pub struct Prime;

impl AlphaRename for Prime {
    fn rename(name: &mut String) {
        name.push('\'');
    }
}

/// Replaces all free occurrences of the variable `var` in the expression
/// `expr` with the expression `subst` and returns the resulting expression.
///
/// This function implements [substitution] in terms of the lambda calculus as
/// a recursion on the structure of the given `expr`.
///
/// The result is returned as a new `Term`. The original term `expr` is not
/// changed.
///
/// To avoid name clashes this function performs α-conversions when appropriate.
/// Therefore a strategy for α-conversion must be specified as the type
/// parameter `A`.
///
/// This function returns the result as a new `Term`. The given term `expr`
/// remains unmodified. If you want to substitute the original term in place use
/// the associated function [`Term::subst`](enum.Term.html#method.subst)
/// instead.
///
/// [substitution]: https://en.wikipedia.org/wiki/Lambda_calculus#Substitution
pub fn substitute<A>(expr: &Term, var: &VarName, subst: &Term) -> Term
where
    A: AlphaRename,
{
    let mut expr2 = expr.clone();
    alpha_tramp::<A>(&mut expr2, &subst.free_vars());
    substitute_tramp(&mut expr2, var, subst);
    expr2
}

fn substitute_tramp(expr: &mut Term, var: &VarName, subst: &Term) {
    let mut todo: Vec<&mut Term> = Vec::with_capacity(2);
    todo.push(expr);
    while let Some(term) = todo.pop() {
        let do_subst = match term {
            Var(ref name) => name == var,
            _ => false,
        };
        if do_subst {
            *term = subst.clone();
        } else {
            match term {
                Var(_) => {},
                Lam(ref mut param, ref mut body) => {
                    if param != var {
                        todo.push(body);
                    }
                },
                App(ref mut lhs, ref mut rhs) => {
                    todo.push(rhs);
                    todo.push(lhs);
                },
            }
        }
    }
}

/// Applies a given lambda abstraction to the given substitution term and
/// returns the result as a new `Term`.
///
/// If the given term `expr` is a lambda abstraction (that is of variant
/// `Term::Lam`) any occurrence of its bound variable in its body is replaced by
/// the given term `subst`. The substitution is applied recursively.
///
/// The result is returned as a new `Term`. The original term `expr` is not
/// changed. If the given expression `expr` is not a lambda abstraction an
/// unmodified clone of the term `expr` is returned.
///
/// To avoid name clashes this function performs α-conversions when appropriate.
/// Therefore a strategy for α-conversion must be specified as a type parameter
/// `A`.
///
/// This function returns the result as a new `Term`. The given term `expr`
/// remains unmodified. If you want to apply an α-conversion on the original
/// term in place use the associated function
/// [`Term::apply`](enum.Term.html#method.apply) instead.
///
/// # Examples
///
/// In the first example a lambda abstraction is applied to a variable z:
///
/// ```
/// # extern crate lamcal;
/// # use lamcal::{app, lam, var, apply, Enumerate};
/// let expr1 = lam("x", app(var("x"), var("y")));
///
/// let expr2 = apply::<Enumerate>(&expr1, &var("z"));
///
/// assert_eq!(expr2, app(var("z"), var("y")));
/// ```
///
/// In this example a function application is applied to the variable z. Due
/// to an application can not be applied to a variable, the returned expression
/// is the same as the input expression:
///
/// ```
/// # extern crate lamcal;
/// # use lamcal::{app, lam, var, apply, Enumerate};
/// let expr1 = app(var("x"), var("y"));
///
/// let expr2 = apply::<Enumerate>(&expr1, &var("z"));
///
/// assert_eq!(expr2, expr1);
/// ```
pub fn apply<A>(expr: &Term, subst: &Term) -> Term
where
    A: AlphaRename,
{
    let expr2 = expr.clone();
    if let Lam(param, mut body) = expr2 {
        alpha_tramp::<A>(&mut body, &subst.free_vars());
        substitute_tramp(&mut body, &param, subst);
        *body
    } else {
        expr2
    }
}

fn apply_mut<A>(expr: &mut Term, subst: &Term)
where
    A: AlphaRename,
{
    if let Some(replace_with) = match *expr {
        Lam(ref param, ref mut body) => {
            alpha_tramp::<A>(body, &subst.free_vars());
            substitute_tramp(body, param, subst);
            Some(mem::replace(&mut **body, dummy_term()))
        },
        _ => None,
    } {
        *expr = replace_with;
    }
}

/// Performs a [β-reduction] on a given lambda expression applying the given
/// reduction strategy.
///
/// The reduction strategy to be used must be given as the type parameter `B`,
/// like in the example below.
///
/// This function returns the result as a new `Term`. The given `Term` remains
/// unchanged. If you want to apply a β-reduction modifying the term in place
/// use the associated function [`Term::reduce`](enum.Term.html#method.reduce)
/// instead.
///
/// # Examples
///
/// ```
/// # #[macro_use]
/// # extern crate lamcal;
/// # use lamcal::{var, lam, app, reduce, NormalOrder, Enumerate};
/// # fn main() {
/// let expr = app![
///     lam("a", var("a")),
///     lam("b", lam("c", var("b"))),
///     var("x"),
///     lam("e", var("f"))
/// ];
///
/// let reduced = reduce::<NormalOrder<Enumerate>>(&expr);
///
/// assert_eq!(reduced, var("x"));
/// # }
/// ```
///
/// [β-reduction]: https://en.wikipedia.org/wiki/Lambda_calculus#%CE%B2-reduction
pub fn reduce<B>(expr: &Term) -> Term
where
    B: BetaReduce,
{
    <B as BetaReduce>::reduce(expr.clone())
}

/// Performs a [β-reduction] on a given lambda expression with inspection
/// applying the given reduction strategy and inspection.
///
/// The reduction strategy to be used must be given as the type parameter `B`.
///
/// The given inspection is called before each contraction (reduction step).
/// See the documentation of the [`inspect`](mod.inspect.html) for how to
/// define an inspection and the provided implementations.
///
/// This function returns the result as a new `Term`. The given `Term` remains
/// unchanged. If you want to apply a β-reduction modifying the term in place
/// use the associated function
/// [`Term::reduce_inspected`](enum.Term.html#method.reduce_inspected) instead.
pub fn reduce_inspected<B, I>(expr: &Term, inspect: &mut I) -> Term
where
    B: BetaReduce,
    I: Inspect,
{
    <B as BetaReduce>::reduce_inspected(expr.clone(), inspect)
}

/// Defines a strategy for [β-reduction] of terms.
///
/// Possible implementations may follow the strategies described in the
/// [reduction strategy] article on wikipedia.
///
/// [β-reduction]: https://en.wikipedia.org/wiki/Lambda_calculus#%CE%B2-reduction
/// [reduction strategy]: https://en.wikipedia.org/wiki/Reduction_strategy_(lambda_calculus)
pub trait BetaReduce {
    /// Performs β-reduction on the given `Term` and returns the result.
    ///
    /// The default implementation limits the reduction to `Limit::default()`
    /// reduction steps to prevent endless loops on diverging expressions.
    fn reduce(expr: Term) -> Term {
        Self::reduce_inspected(expr, &mut Limit::default())
    }

    /// Performs one step of β-reduction on the given `Term` and returns the
    /// result.
    fn reduce_once(expr: Term) -> Term {
        Self::reduce_inspected(expr, &mut Limit::new(1))
    }

    /// Performs β-reduction allowing to inspect the current term before
    /// each contraction.
    ///
    /// Implementations must call the `Inspect::inspect` function of the given
    /// `Inspect` instance exactly once before each contraction and respect
    /// their return value. If the `Inspect::inspect` function returns
    /// `Stop::Yes` the reduction must be stopped immediately, so that no
    /// further reduction is performed.
    fn reduce_inspected(expr: Term, inspect: &mut impl Inspect) -> Term;
}

/// Call-By-Name [β-reduction] to weak head normal form.
///
/// * Reduces the leftmost outermost redex not inside a lambda abstraction
///   first.
/// * It treats free variables as non-strict data constructors.
/// * Only leftmost redexes are contracted.
/// * No reduction is performed under abstractions.
///
/// This strategy is uniform as its definition involves no other reduction
/// strategy.
///
/// [β-reduction]: https://en.wikipedia.org/wiki/Lambda_calculus#%CE%B2-reduction
#[derive(Default, Debug, Clone, Copy, PartialEq)]
pub struct CallByName<A> {
    _alpha_rename: PhantomData<A>,
}

impl<A> BetaReduce for CallByName<A>
where
    A: AlphaRename,
{
    fn reduce_inspected(mut expr: Term, inspect: &mut impl Inspect) -> Term {
        Self::reduce_inspected_mut(&mut expr, inspect);
        expr
    }
}

impl<A> CallByName<A>
where
    A: AlphaRename,
{
    #[cfg(test)]
    fn reduce_rec(expr: &mut Term) {
        if let Some(subst_with) = match *expr {
            App(ref mut lhs, ref rhs) => {
                Self::reduce_rec(lhs);
                match **lhs {
                    Lam(_, _) => {
                        apply_mut::<A>(lhs, rhs);
                        Self::reduce_rec(lhs);
                        // defer actual substitution outside match expression
                        // because of the borrow checker
                        //TODO refactor when non-lexical-lifetimes are stabilized, see [issue 43234](https://github.com/rust-lang/rust/issues/43234)
                        Some(mem::replace(&mut **lhs, dummy_term()))
                    },
                    _ => None,
                }
            },
            _ => None,
        } {
            *expr = subst_with;
        }
    }

    fn reduce_inspected_mut(expr: &mut Term, inspect: &mut impl Inspect) {
        let mut temp_term = dummy_term();
        let mut parents: Vec<Rc<RefCell<*mut Term>>> = Vec::with_capacity(8);
        let base_term: Rc<RefCell<*mut Term>> = Rc::new(RefCell::new(expr));
        unsafe {
            descend_left(base_term.clone(), &mut parents);
            while let Some(term) = parents.pop() {
                if Stop::Yes == match **term.borrow() {
                    App(ref lhs, _) => match **lhs {
                        Lam(_, _) => inspect.inspect(&**base_term.borrow()),
                        _ => Stop::No,
                    },
                    _ => Stop::No,
                } {
                    break;
                }
                let do_swap = match **term.borrow_mut() {
                    App(ref mut lhs, ref rhs) => match **lhs {
                        Lam(_, _) => {
                            apply_mut::<A>(lhs, rhs);
                            // defer actual substitution outside match expression
                            // because of the borrow checker
                            //TODO refactor when non-lexical-lifetimes are stabilized, see [issue 43234](https://github.com/rust-lang/rust/issues/43234)
                            mem::swap(&mut temp_term, &mut **lhs);
                            true
                        },
                        _ => false,
                    },
                    _ => false,
                };
                if do_swap {
                    term.borrow_mut().swap(&mut temp_term);
                    parents.push(term.clone());
                    descend_left(term, &mut parents);
                }
            }
        }
    }
}

unsafe fn descend_left(term: Rc<RefCell<*mut Term>>, parents: &mut Vec<Rc<RefCell<*mut Term>>>) {
    let mut to_check: Vec<Rc<RefCell<*mut Term>>> = Vec::with_capacity(1);
    to_check.push(term);
    while let Some(term) = to_check.pop() {
        if let App(ref mut lhs, _) = **term.borrow_mut() {
            parents.push(term.clone());
            if let App(_, _) = **lhs {
                to_check.push(Rc::new(RefCell::new(&mut **lhs)));
            } else {
                break;
            }
        }
    }
}

/// Normal-Order [β-reduction] to normal form.
///
/// * Reduces the leftmost outermost redex first.
/// * In an application (e1 e2) the function term e1 is reduced using the
///   call-by-name strategy ([`CallByName`](struct.CallByName.html)).
/// * Any redex that is contracted is the leftmost one not contained in any
///   other redex.
/// * Reductions are performed also under lambda abstractions.
///
/// This strategy is a hybrid as it uses call-by-name for the reduction of the
/// expression e1 in function position in applications (e1 e2).
///
/// [β-reduction]: https://en.wikipedia.org/wiki/Lambda_calculus#%CE%B2-reduction
#[derive(Default, Debug, Clone, Copy, PartialEq)]
pub struct NormalOrder<A> {
    _alpha_rename: PhantomData<A>,
}

impl<A> BetaReduce for NormalOrder<A>
where
    A: AlphaRename,
{
    fn reduce_inspected(mut expr: Term, inspect: &mut impl Inspect) -> Term {
        Self::reduce_inspected_mut(&mut expr, inspect);
        expr
    }
}

impl<A> NormalOrder<A>
where
    A: AlphaRename,
{
    #[cfg(test)]
    fn reduce_rec(expr: &mut Term) {
        if let Some(subst_with) = match *expr {
            Lam(_, ref mut body) => {
                Self::reduce_rec(body);
                None
            },
            App(ref mut lhs, ref mut rhs) => {
                CallByName::<A>::reduce_rec(lhs);
                match **lhs {
                    Lam(_, _) => {
                        apply_mut::<A>(lhs, rhs);
                        Self::reduce_rec(lhs);
                        // defer actual substitution outside match expression
                        // because of the borrow checker
                        //TODO refactor when non-lexical-lifetimes are stabilized, see [issue 43234](https://github.com/rust-lang/rust/issues/43234)
                        Some(mem::replace(&mut **lhs, dummy_term()))
                    },
                    _ => {
                        Self::reduce_rec(lhs);
                        Self::reduce_rec(rhs);
                        None
                    },
                }
            },
            _ => None,
        } {
            *expr = subst_with;
        }
    }

    fn reduce_inspected_mut(expr: &mut Term, inspect: &mut impl Inspect) {
        let mut temp_term = dummy_term();
        let mut parents: Vec<Rc<RefCell<*mut Term>>> = Vec::with_capacity(8);
        let base_term: Rc<RefCell<*mut Term>> = Rc::new(RefCell::new(expr));
        unsafe {
            descend_left_and_body(base_term.clone(), &mut parents);
            while let Some(term) = parents.pop() {
                if Stop::Yes == match **term.borrow() {
                    App(ref lhs, _) => match **lhs {
                        Lam(_, _) => inspect.inspect(&**base_term.borrow()),
                        _ => Stop::No,
                    },
                    _ => Stop::No,
                } {
                    break;
                }
                let do_swap = match **term.borrow_mut() {
                    App(ref mut lhs, ref mut rhs) => {
                        CallByName::<A>::reduce_inspected_mut(lhs, inspect);
                        match **lhs {
                            Lam(_, _) => {
                                apply_mut::<A>(lhs, rhs);
                                // defer actual substitution outside match expression
                                // because of the borrow checker
                                //TODO refactor when non-lexical-lifetimes are stabilized, see [issue 43234](https://github.com/rust-lang/rust/issues/43234)
                                mem::swap(&mut temp_term, &mut **lhs);
                                true
                            },
                            _ => {
                                descend_left_and_right_and_body(
                                    Rc::new(RefCell::new(&mut **rhs)),
                                    &mut parents,
                                );
                                descend_left_and_right_and_body(
                                    Rc::new(RefCell::new(&mut **lhs)),
                                    &mut parents,
                                );
                                false
                            },
                        }
                    },
                    _ => false,
                };
                if do_swap {
                    term.borrow_mut().swap(&mut temp_term);
                    parents.push(term.clone());
                    descend_left_and_right_and_body(term, &mut parents);
                }
            }
        }
    }
}

/// Call-By-Value [β-reduction] to weak normal form.
///
/// * Reduces the leftmost innermost redex not inside a lambda abstraction
///   first.
/// * It treats free variables as strict data constructors.
/// * An argument e2 of an application (e1 e2) is reduced before contracting
///   the redex and before building an application term.
/// * No reduction is performed under abstractions.
///
/// This strategy is uniform as its definition involves no other reduction
/// strategy.
///
/// [β-reduction]: https://en.wikipedia.org/wiki/Lambda_calculus#%CE%B2-reduction
#[derive(Default, Debug, Clone, Copy, PartialEq)]
pub struct CallByValue<A> {
    _alpha_rename: PhantomData<A>,
}

impl<A> BetaReduce for CallByValue<A>
where
    A: AlphaRename,
{
    fn reduce_inspected(mut expr: Term, inspect: &mut impl Inspect) -> Term {
        Self::reduce_inspected_mut(&mut expr, inspect);
        expr
    }
}

impl<A> CallByValue<A>
where
    A: AlphaRename,
{
    #[cfg(test)]
    fn reduce_rec(expr: &mut Term) {
        if let Some(subst_with) = match *expr {
            App(ref mut lhs, ref mut rhs) => {
                Self::reduce_rec(lhs);
                Self::reduce_rec(rhs);
                match **lhs {
                    Lam(_, _) => {
                        apply_mut::<A>(lhs, rhs);
                        Self::reduce_rec(lhs);
                        // defer actual substitution outside match expression
                        // because of the borrow checker
                        //TODO refactor when non-lexical-lifetimes are stabilized, see [issue 43234](https://github.com/rust-lang/rust/issues/43234)
                        Some(mem::replace(&mut **lhs, dummy_term()))
                    },
                    _ => None,
                }
            },
            _ => None,
        } {
            *expr = subst_with;
        }
    }

    fn reduce_inspected_mut(expr: &mut Term, inspect: &mut impl Inspect) {
        let mut temp_term = dummy_term();
        let mut parents: Vec<Rc<RefCell<*mut Term>>> = Vec::with_capacity(8);
        let base_term: Rc<RefCell<*mut Term>> = Rc::new(RefCell::new(expr));
        unsafe {
            descend_left_and_right(base_term.clone(), &mut parents);
            while let Some(term) = parents.pop() {
                if Stop::Yes == match **term.borrow() {
                    App(ref lhs, _) => match **lhs {
                        Lam(_, _) => inspect.inspect(&**base_term.borrow()),
                        _ => Stop::No,
                    },
                    _ => Stop::No,
                } {
                    break;
                }
                let do_swap = match **term.borrow_mut() {
                    App(ref mut lhs, ref mut rhs) => match **lhs {
                        Lam(_, _) => {
                            apply_mut::<A>(lhs, rhs);
                            // defer actual substitution outside match expression
                            // because of the borrow checker
                            //TODO refactor when non-lexical-lifetimes are stabilized, see [issue 43234](https://github.com/rust-lang/rust/issues/43234)
                            mem::swap(&mut temp_term, &mut **lhs);
                            true
                        },
                        _ => false,
                    },
                    _ => false,
                };
                if do_swap {
                    term.borrow_mut().swap(&mut temp_term);
                    parents.push(term.clone());
                    descend_left_and_right(term.clone(), &mut parents);
                }
            }
        }
    }
}

unsafe fn descend_left_and_right(
    term: Rc<RefCell<*mut Term>>,
    parents: &mut Vec<Rc<RefCell<*mut Term>>>,
) {
    let mut to_check: Vec<Rc<RefCell<*mut Term>>> = Vec::with_capacity(2);
    to_check.push(term);
    while let Some(term) = to_check.pop() {
        if let App(ref mut lhs, ref mut rhs) = **term.borrow_mut() {
            parents.push(term.clone());
            if let App(_, _) = **rhs {
                to_check.push(Rc::new(RefCell::new(&mut **rhs)));
            }
            if let App(_, _) = **lhs {
                parents.push(term.clone());
                to_check.push(Rc::new(RefCell::new(&mut **lhs)));
            }
        }
    }
}

/// Applicative-Order [β-reduction] to normal form.
///
/// * Reduces the leftmost innermost redex first.
/// * It treats free variables as strict data constructors.
/// * An argument e2 of an application (e1 e2) is reduced before contracting
///   the redex and before building an application term.
/// * Reductions are performed also under lambda abstractions.
///
/// This strategy is uniform as its definition involves no other reduction
/// strategy.
///
/// [β-reduction]: https://en.wikipedia.org/wiki/Lambda_calculus#%CE%B2-reduction
#[derive(Default, Debug, Clone, Copy, PartialEq)]
pub struct ApplicativeOrder<A> {
    _alpha_rename: PhantomData<A>,
}

impl<A> BetaReduce for ApplicativeOrder<A>
where
    A: AlphaRename,
{
    fn reduce_inspected(mut expr: Term, inspect: &mut impl Inspect) -> Term {
        Self::reduce_inspected_mut(&mut expr, inspect);
        expr
    }
}

impl<A> ApplicativeOrder<A>
where
    A: AlphaRename,
{
    #[cfg(test)]
    fn reduce_rec(expr: &mut Term) {
        if let Some(subst_with) = match *expr {
            Lam(_, ref mut body) => {
                Self::reduce_rec(body);
                None
            },
            App(ref mut lhs, ref mut rhs) => {
                Self::reduce_rec(lhs);
                Self::reduce_rec(rhs);
                match **lhs {
                    Lam(_, _) => {
                        apply_mut::<A>(lhs, rhs);
                        Self::reduce_rec(lhs);
                        // defer actual substitution outside match expression
                        // because of the borrow checker
                        //TODO refactor when non-lexical-lifetimes are stabilized, see [issue 43234](https://github.com/rust-lang/rust/issues/43234)
                        Some(mem::replace(&mut **lhs, dummy_term()))
                    },
                    _ => None,
                }
            },
            _ => None,
        } {
            *expr = subst_with;
        }
    }

    fn reduce_inspected_mut(expr: &mut Term, inspect: &mut impl Inspect) {
        let mut temp_term = dummy_term();
        let mut parents: Vec<Rc<RefCell<*mut Term>>> = Vec::with_capacity(8);
        let base_term: Rc<RefCell<*mut Term>> = Rc::new(RefCell::new(expr));
        unsafe {
            descend_left_and_right_and_body(base_term.clone(), &mut parents);
            while let Some(term) = parents.pop() {
                if Stop::Yes == match **term.borrow() {
                    App(ref lhs, _) => match **lhs {
                        Lam(_, _) => inspect.inspect(&**base_term.borrow()),
                        _ => Stop::No,
                    },
                    _ => Stop::No,
                } {
                    break;
                }
                let do_swap = match **term.borrow_mut() {
                    App(ref mut lhs, ref rhs) => match **lhs {
                        Lam(_, _) => {
                            apply_mut::<A>(lhs, rhs);
                            // defer actual substitution outside match expression
                            // because of the borrow checker
                            //TODO refactor when non-lexical-lifetimes are stabilized, see [issue 43234](https://github.com/rust-lang/rust/issues/43234)
                            mem::swap(&mut temp_term, &mut **lhs);
                            true
                        },
                        _ => false,
                    },
                    _ => false,
                };
                if do_swap {
                    term.borrow_mut().swap(&mut temp_term);
                    parents.push(term.clone());
                    descend_left_and_right_and_body(term, &mut parents);
                }
            }
        }
    }
}

unsafe fn descend_left_and_right_and_body(
    term: Rc<RefCell<*mut Term>>,
    parents: &mut Vec<Rc<RefCell<*mut Term>>>,
) {
    let mut to_check: Vec<Rc<RefCell<*mut Term>>> = Vec::with_capacity(2);
    to_check.push(term);
    while let Some(term) = to_check.pop() {
        match **term.borrow_mut() {
            Lam(_, ref mut body) => {
                to_check.push(Rc::new(RefCell::new(&mut **body)));
            },
            App(ref mut lhs, ref mut rhs) => {
                parents.push(term.clone());
                match **rhs {
                    App(_, _) => {
                        to_check.push(Rc::new(RefCell::new(&mut **rhs)));
                    },
                    Lam(_, _) => {
                        to_check.push(Rc::new(RefCell::new(&mut **rhs)));
                    },
                    _ => {},
                }
                match **lhs {
                    App(_, _) => {
                        parents.push(term.clone());
                        to_check.push(Rc::new(RefCell::new(&mut **lhs)));
                    },
                    Lam(_, _) => {
                        to_check.push(Rc::new(RefCell::new(&mut **lhs)));
                    },
                    _ => {},
                }
            },
            _ => {},
        }
    }
}

/// Hybrid-Applicative-Order [β-reduction] to normal form.
///
/// * A hybrid of call-by-value and applicative-order reduction.
/// * Reduces to normal form, but reduces under lambda abstractions only in
///   argument positions.
/// * Normalizes more terms than applicative-order reduction, while using fewer
///   reduction steps than normal order reduction.
///
/// The hybrid applicative order strategy relates to call-by-value in the
/// same way that the normal order strategy relates to call-by-name.
///
/// This strategy is a hybrid as it uses call-by-value for the reduction of the
/// expression e1 in function position in applications (e1 e2).
///
/// [β-reduction]: https://en.wikipedia.org/wiki/Lambda_calculus#%CE%B2-reduction
#[derive(Default, Debug, Clone, Copy, PartialEq)]
pub struct HybridApplicativeOrder<A> {
    _alpha_rename: PhantomData<A>,
}

impl<A> BetaReduce for HybridApplicativeOrder<A>
where
    A: AlphaRename,
{
    fn reduce_inspected(mut expr: Term, inspect: &mut impl Inspect) -> Term {
        Self::reduce_inspected_mut(&mut expr, inspect);
        expr
    }
}

impl<A> HybridApplicativeOrder<A>
where
    A: AlphaRename,
{
    #[cfg(test)]
    fn reduce_rec(expr: &mut Term) {
        if let Some(subst_with) = match *expr {
            Lam(_, ref mut body) => {
                Self::reduce_rec(body);
                None
            },
            App(ref mut lhs, ref mut rhs) => {
                CallByValue::<A>::reduce_rec(lhs);
                Self::reduce_rec(rhs);
                match **lhs {
                    Lam(_, _) => {
                        apply_mut::<A>(lhs, rhs);
                        Self::reduce_rec(lhs);
                        // defer actual substitution outside match expression
                        // because of the borrow checker
                        //TODO refactor when non-lexical-lifetimes are stabilized, see [issue 43234](https://github.com/rust-lang/rust/issues/43234)
                        Some(mem::replace(&mut **lhs, dummy_term()))
                    },
                    _ => {
                        Self::reduce_rec(lhs);
                        None
                    },
                }
            },
            _ => None,
        } {
            *expr = subst_with;
        }
    }

    fn reduce_inspected_mut(expr: &mut Term, inspect: &mut impl Inspect) {
        let mut temp_term = dummy_term();
        let mut parents: Vec<Rc<RefCell<*mut Term>>> = Vec::with_capacity(8);
        let base_term: Rc<RefCell<*mut Term>> = Rc::new(RefCell::new(expr));
        unsafe {
            descend_right_and_body(base_term.clone(), &mut parents);
            while let Some(term) = parents.pop() {
                if Stop::Yes == match **term.borrow() {
                    App(ref lhs, _) => match **lhs {
                        Lam(_, _) => inspect.inspect(&**base_term.borrow()),
                        _ => Stop::No,
                    },
                    _ => Stop::No,
                } {
                    break;
                }
                let do_swap = match **term.borrow_mut() {
                    App(ref mut lhs, ref rhs) => {
                        CallByValue::<A>::reduce_inspected_mut(lhs, inspect);
                        match **lhs {
                            Lam(_, _) => {
                                apply_mut::<A>(lhs, rhs);
                                // defer actual substitution outside match expression
                                // because of the borrow checker
                                //TODO refactor when non-lexical-lifetimes are stabilized, see [issue 43234](https://github.com/rust-lang/rust/issues/43234)
                                mem::swap(&mut temp_term, &mut **lhs);
                                true
                            },
                            _ => false,
                        }
                    },
                    _ => false,
                };
                if do_swap {
                    term.borrow_mut().swap(&mut temp_term);
                    parents.push(term.clone());
                    descend_right_and_body(term, &mut parents);
                }
            }
        }
    }
}

unsafe fn descend_right_and_body(
    term: Rc<RefCell<*mut Term>>,
    parents: &mut Vec<Rc<RefCell<*mut Term>>>,
) {
    let mut to_check: Vec<Rc<RefCell<*mut Term>>> = Vec::with_capacity(1);
    to_check.push(term);
    while let Some(term) = to_check.pop() {
        match **term.borrow_mut() {
            Lam(_, ref mut body) => {
                to_check.push(Rc::new(RefCell::new(&mut **body)));
            },
            App(_, ref mut rhs) => {
                parents.push(term.clone());
                match **rhs {
                    App(_, _) => {
                        to_check.push(Rc::new(RefCell::new(&mut **rhs)));
                    },
                    Lam(_, _) => {
                        to_check.push(Rc::new(RefCell::new(&mut **rhs)));
                    },
                    _ => break,
                }
            },
            _ => break,
        }
    }
}

/// Head-Spine [β-reduction] to head normal form.
///
/// * Reduces the leftmost outermost redex first.
/// * Performs reductions inside lambda abstractions, but only in head position.
///
/// This strategy is uniform as its definition involves no other reduction
/// strategy.
///
/// [β-reduction]: https://en.wikipedia.org/wiki/Lambda_calculus#%CE%B2-reduction
#[derive(Default, Debug, Clone, Copy, PartialEq)]
pub struct HeadSpine<A> {
    _alpha_rename: PhantomData<A>,
}

impl<A> BetaReduce for HeadSpine<A>
where
    A: AlphaRename,
{
    fn reduce_inspected(mut expr: Term, inspect: &mut impl Inspect) -> Term {
        Self::reduce_inspected_mut(&mut expr, inspect);
        expr
    }
}

impl<A> HeadSpine<A>
where
    A: AlphaRename,
{
    #[cfg(test)]
    fn reduce_rec(expr: &mut Term) {
        if let Some(subst_with) = match *expr {
            Lam(_, ref mut body) => {
                Self::reduce_rec(body);
                None
            },
            App(ref mut lhs, ref rhs) => {
                Self::reduce_rec(lhs);
                match **lhs {
                    Lam(_, _) => {
                        apply_mut::<A>(lhs, rhs);
                        Self::reduce_rec(lhs);
                        // defer actual substitution outside match expression
                        // because of the borrow checker
                        //TODO refactor when non-lexical-lifetimes are stabilized, see [issue 43234](https://github.com/rust-lang/rust/issues/43234)
                        Some(mem::replace(&mut **lhs, dummy_term()))
                    },
                    _ => None,
                }
            },
            _ => None,
        } {
            *expr = subst_with;
        }
    }

    fn reduce_inspected_mut(expr: &mut Term, inspect: &mut impl Inspect) {
        let mut temp_term = dummy_term();
        let mut parents: Vec<Rc<RefCell<*mut Term>>> = Vec::with_capacity(8);
        let base_term: Rc<RefCell<*mut Term>> = Rc::new(RefCell::new(expr));
        unsafe {
            descend_left_and_body(base_term.clone(), &mut parents);
            while let Some(term) = parents.pop() {
                if Stop::Yes == match **term.borrow() {
                    App(ref lhs, _) => match **lhs {
                        Lam(_, _) => inspect.inspect(&**base_term.borrow()),
                        _ => Stop::No,
                    },
                    _ => Stop::No,
                } {
                    break;
                }
                let do_swap = match **term.borrow_mut() {
                    App(ref mut lhs, ref rhs) => match **lhs {
                        Lam(_, _) => {
                            apply_mut::<A>(lhs, rhs);
                            // defer actual substitution outside match expression
                            // because of the borrow checker
                            //TODO refactor when non-lexical-lifetimes are stabilized, see [issue 43234](https://github.com/rust-lang/rust/issues/43234)
                            mem::swap(&mut temp_term, &mut **lhs);
                            true
                        },
                        _ => false,
                    },
                    _ => false,
                };
                if do_swap {
                    term.borrow_mut().swap(&mut temp_term);
                    parents.push(term.clone());
                    descend_left_and_body(term, &mut parents);
                }
            }
        }
    }
}

unsafe fn descend_left_and_body(
    term: Rc<RefCell<*mut Term>>,
    parents: &mut Vec<Rc<RefCell<*mut Term>>>,
) {
    let mut to_check: Vec<Rc<RefCell<*mut Term>>> = Vec::with_capacity(1);
    to_check.push(term);
    while let Some(term) = to_check.pop() {
        match **term.borrow_mut() {
            Lam(_, ref mut body) => {
                to_check.push(Rc::new(RefCell::new(&mut **body)));
            },
            App(ref mut lhs, _) => {
                parents.push(term.clone());
                to_check.push(Rc::new(RefCell::new(&mut **lhs)));
            },
            _ => break,
        }
    }
}

/// Hybrid-Normal-Order [β-reduction] to normal form.
///
/// * A hybrid of head-spine and normal-order reduction.
/// * Reduces the leftmost outermost redex first.
/// * In an application (e1 e2) the function term e1 is reduced using the
///   head-spine strategy ([`HeadSpine`](struct.HeadSpine.html)).
/// * Any redex that is contracted is the leftmost one not contained in any
///   other redex.
/// * Reductions are performed also under lambda abstractions.
///
/// This strategy is a hybrid as it uses head-spine for the reduction of the
/// expression e1 in function position in applications (e1 e2).
///
/// [β-reduction]: https://en.wikipedia.org/wiki/Lambda_calculus#%CE%B2-reduction
#[derive(Default, Debug, Clone, Copy, PartialEq)]
pub struct HybridNormalOrder<A> {
    _alpha_rename: PhantomData<A>,
}

impl<A> BetaReduce for HybridNormalOrder<A>
where
    A: AlphaRename,
{
    fn reduce_inspected(mut expr: Term, inspect: &mut impl Inspect) -> Term {
        Self::reduce_inspected_mut(&mut expr, inspect);
        expr
    }
}

impl<A> HybridNormalOrder<A>
where
    A: AlphaRename,
{
    #[cfg(test)]
    fn reduce_rec(expr: &mut Term) {
        if let Some(subst_with) = match *expr {
            Lam(_, ref mut body) => {
                Self::reduce_rec(body);
                None
            },
            App(ref mut lhs, ref mut rhs) => {
                HeadSpine::<A>::reduce_rec(lhs);
                match **lhs {
                    Lam(_, _) => {
                        apply_mut::<A>(lhs, rhs);
                        Self::reduce_rec(lhs);
                        // defer actual substitution outside match expression
                        // because of the borrow checker
                        //TODO refactor when non-lexical-lifetimes are stabilized, see [issue 43234](https://github.com/rust-lang/rust/issues/43234)
                        Some(mem::replace(&mut **lhs, dummy_term()))
                    },
                    _ => {
                        Self::reduce_rec(lhs);
                        Self::reduce_rec(rhs);
                        None
                    },
                }
            },
            _ => None,
        } {
            *expr = subst_with;
        }
    }

    fn reduce_inspected_mut(expr: &mut Term, inspect: &mut impl Inspect) {
        let mut temp_term = dummy_term();
        let mut parents: Vec<Rc<RefCell<*mut Term>>> = Vec::with_capacity(8);
        let base_term: Rc<RefCell<*mut Term>> = Rc::new(RefCell::new(expr));
        unsafe {
            descend_left_and_body(base_term.clone(), &mut parents);
            while let Some(term) = parents.pop() {
                if Stop::Yes == match **term.borrow() {
                    App(ref lhs, _) => match **lhs {
                        Lam(_, _) => inspect.inspect(&**base_term.borrow()),
                        _ => Stop::No,
                    },
                    _ => Stop::No,
                } {
                    break;
                }
                let do_swap = match **term.borrow_mut() {
                    App(ref mut lhs, ref mut rhs) => {
                        HeadSpine::<A>::reduce_inspected_mut(lhs, inspect);
                        match **lhs {
                            Lam(_, _) => {
                                apply_mut::<A>(lhs, rhs);
                                // defer actual substitution outside match expression
                                // because of the borrow checker
                                //TODO refactor when non-lexical-lifetimes are stabilized, see [issue 43234](https://github.com/rust-lang/rust/issues/43234)
                                mem::swap(&mut temp_term, &mut **lhs);
                                true
                            },
                            _ => {
                                descend_left_and_right_and_body(
                                    Rc::new(RefCell::new(&mut **rhs)),
                                    &mut parents,
                                );
                                descend_left_and_right_and_body(
                                    Rc::new(RefCell::new(&mut **lhs)),
                                    &mut parents,
                                );
                                false
                            },
                        }
                    },
                    _ => false,
                };
                if do_swap {
                    term.borrow_mut().swap(&mut temp_term);
                    parents.push(term.clone());
                    descend_left_and_right_and_body(term, &mut parents);
                }
            }
        }
    }
}

#[cfg(test)]
mod tests;