@ysharp_design/

Hindley-Milner type inference over (Lisp-ish) S-expressions

C#

No description

fork
loading
Files
  • main.cs
main.cs
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
/*
Copyright (c) 2017 Cyril Jandia

http://www.cjandia.com/

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
``Software''), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL CYRIL JANDIA BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name of Cyril Jandia shall
not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization
from Cyril Jandia.

Inquiries : ysharp {dot} design {at} gmail {dot} com
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;

namespace System.Language.SExpressions
{
    public delegate object Acceptor(Token token, string match);

    public class Symbol
    {
        public Symbol(string id) { Id = id ?? Guid.NewGuid().ToString("P"); }
        public override string ToString() => Id;
        public string Id { get; private set; }
    }

    public class Token : Symbol
    {
        internal Token(string id) : base(id) { }
        public Token(string id, Acceptor acceptor) : this(id, acceptor, false) { }
        public Token(string id, Acceptor acceptor, bool priority) : this(id, id, acceptor, priority) { }
        public Token(string id, string pattern, Acceptor acceptor) : this(id, pattern, acceptor, false) { }
        public Token(string id, string pattern, Acceptor acceptor, bool priority) : base(id) { Regex = new Regex(string.Format("^({0})", !string.IsNullOrEmpty(Pattern = pattern) ? Pattern : ".*"), RegexOptions.Compiled); ValueOf = acceptor; HasPriority = priority; }
        public string Pattern { get; private set; }
        public Regex Regex { get; private set; }
        public Acceptor ValueOf { get; private set; }
        public bool HasPriority { get; private set; }
    }

    public class Syntax
    {
        private static readonly Token Space = Token("s+", Echo, 1);
        private static readonly Token Open = Token("(", Echo);
        private static readonly Token Close = Token(")", Echo);
        private static object Echo(Token token, string match) => new Token(token.Id);
        private Token comment;
        private Token quote;
        private Token @params;
        private Token @this;

        private Tuple<Token, string, object> Read(ref string input)
        {
            if (!string.IsNullOrEmpty(input))
            {
                var found = null as Match;
                var sofar = input;
                var tuple = Lexicon.FirstOrDefault(current => (found = current.Item2.Regex.Match(sofar)).Success && (found.Length > 0));
                var token = tuple != null ? tuple.Item2 : null;
                var match = token != null ? found.Value : null;
                input = match != null ? input.Substring(match.Length) : input;
                return token != null ? Tuple.Create(token, match, token.ValueOf(token, match)) : null;
            }
            return null;
        }

        private Tuple<Token, string, object> Next(ref string input)
        {
            Tuple<Token, string, object> read;
            while (((read = Read(ref input)) != null) && ((read.Item1 == Comment) || (read.Item1 == Space))) ;
            return read;
        }

        public object Parse(ref string input, Tuple<Token, string, object> next)
        {
            var value = null as object;
            if (next != null)
            {
                var token = next.Item1;
                if (token == Open)
                {
                    var list = new List<object>();
                    while (((next = Next(ref input)) != null) && (next.Item1 != Close))
                    {
                        list.Add(Parse(ref input, next));
                    }
                    if (next == null)
                    {
                        throw Language.Error("unexpected EOF");
                    }
                    value = list.ToArray();
                }
                else if (token == Quote)
                {
                    var quote = next.Item3;
                    next = Next(ref input);
                    if (next == null)
                    {
                        throw Language.Error("unexpected EOF");
                    }
                    value = new[] { quote, Parse(ref input, next) };
                }
                else
                {
                    value = next.Item3;
                }
            }
            else
            {
                throw Language.Error("unexpected EOF");
            }
            return value;
        }

        protected Token TokenOf(Acceptor acceptor)
        {
            var optional = new Acceptor[] { Commenting, Parameters, Self };
            var found = Lexicon.FirstOrDefault(pair => pair.Item2.ValueOf == acceptor);
            var token = found != null ? found.Item2 : null;
            if ((token == null) && !Optional.Contains(acceptor))
            {
                throw Language.Error("missing required token definition: {0}", acceptor.Method.Name);
            }
            return token;
        }

        protected virtual Syntax Validate()
        {
            Required.Select(acceptor => TokenOf(acceptor)).Count();
            return this;
        }

        protected IList<Tuple<string, Token>> Lexicon { get; private set; }
        protected HashSet<Acceptor> Required { get; set; }
        protected HashSet<Acceptor> Optional { get; set; }

        public static Symbol Symbol(object value) => value as Symbol;
        public static string Identifier(object value) => Symbol(value) != null ? Symbol(value).Id : null;
        public static string Escape(string pattern) => Escape(pattern, -1);

        public static string Escape(string pattern, int count)
        {
            count = count < 0 ? pattern.Length : count;
            return pattern.Aggregate(new StringBuilder(), (escaped, character) => escaped.AppendFormat("{0}{1}", count-- > 0 ? "\\" : string.Empty, character)).ToString();
        }

        public static object Commenting(Token token, string match) => Echo(token, match);
        public static object NewSymbol(Token token, string match) => new Symbol(match);
        public static object Quoting(Token token, string match) => NewSymbol(token, match);
        public static object Parameters(Token token, string match) => NewSymbol(token, match);
        public static object Self(Token token, string match) => NewSymbol(token, match);
        public static Token Token(string pattern, Acceptor acceptor) => Token(pattern, acceptor, -1);
        public static Token Token(string pattern, Acceptor acceptor, int escapeCount) => Token(pattern, acceptor, escapeCount, false);
        public static Token Token(string pattern, Acceptor acceptor, bool hasPriority) => Token(pattern, acceptor, -1, hasPriority);
        public static Token Token(string pattern, Acceptor acceptor, int escapeCount, bool hasPriority) => new Token(pattern, Escape(pattern, escapeCount), acceptor, hasPriority);
        public static Token Lexical(string pattern, Acceptor acceptor) => Token(pattern, acceptor, 0);
        public static Token Lexical(string pattern, Acceptor acceptor, bool hasPriority) => Token(pattern, acceptor, 0, hasPriority);

        public static string ToString(object value)
        {
            return
                value is object[] ?
                ((object[])value).Length > 0 ? ((object[])value).Aggregate(new StringBuilder("("), (result, obj) => result.AppendFormat(" {0}", ToString(obj))).Append(" )").ToString() : "( )"
                :
                (value != null ? (value is string ? string.Concat('"', (string)value, '"') : (value is bool ? value.ToString().ToLower() : value.ToString())).Replace("\\\r\n", "\r\n").Replace("\\\n", "\n").Replace("\\t", "\t").Replace("\\n", "\n").Replace("\\r", "\r").Replace("\\\"", "\"") : null) ?? "(null)";
        }

        public Syntax()
        {
            Lexicon = new List<Tuple<string, Token>>();
            Required = new HashSet<Acceptor>(new Acceptor[] { NewSymbol, Quoting });
            Optional = new HashSet<Acceptor>(new Acceptor[] { Commenting, Parameters, Self });
            Include(Space, Open, Close);
        }

        public Syntax Include(Token token)
        {
            if (Lexicon.FirstOrDefault(pair => pair.Item1 == token.Pattern) == null)
            {
                if (token.HasPriority)
                {
                    Lexicon.Insert(0, Tuple.Create(token.Pattern, token));
                }
                else
                {
                    Lexicon.Add(Tuple.Create(token.Pattern, token));
                }
            }
            return this;
        }

        public Syntax Include(params Token[] tokens) => tokens.Aggregate(this, (syntax, token) => syntax.Include(token));

        public object Parse(string input)
        {
            Validate();
            var next = Next(ref input);
            var value = Parse(ref input, next);
            if ((next = Next(ref input)) != null)
            {
                throw Language.Error("unexpected ", next.Item1);
            }
            return value;
        }

        public Token Comment { get { return comment = comment ?? TokenOf(Commenting); } }
        public Token Quote { get { return quote = quote ?? TokenOf(Quoting); } }
        public Token Params { get { return @params = @params ?? TokenOf(Parameters); } }
        public Token This { get { return @this = @this ?? TokenOf(Self); } }
    }

    public class SemanticAttribute : Attribute
    {
        protected SemanticAttribute(string id) { Id = id; }
        public string Id { get; private set; }
    }

    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Method | AttributeTargets.Field, AllowMultiple = false, Inherited = false)]
    public class BuiltinAttribute : SemanticAttribute
    {
        public BuiltinAttribute(string id) : base(id) { }
    }

    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
    public class KeywordAttribute : SemanticAttribute
    {
        public KeywordAttribute(string id) : this(id, false) { }
        public KeywordAttribute(string id, bool isInfix) : base(id) { IsInfix = isInfix; }
        public bool IsInfix { get; private set; }
    }

    public class Callable : Symbol
    {
        protected Callable(int length) : this(null, length) { }
        protected Callable(string id, int length) : base(id) { Length = length; }
        protected int Count(object[] arguments) { return arguments != null ? arguments.Length : 0; }
        public virtual object Invoke(params object[] arguments) { throw Language.Error("not implemented"); }
        public Delegate Delegate { get; protected set; }
        public bool Variadic { get; protected set; }
        public int Length { get; private set; }
    }

    public delegate object Semantic(Environment environment, object expression);

    public class Builtin : Callable
    {
        protected Builtin(string id, int length) : base(id, length) { }
    }

    public class Keyword : Builtin
    {
        public Keyword(string id, Semantic semantic) : this(id, semantic, false) { }
        public Keyword(string id, Semantic semantic, bool isInfix) : base(id, -1) { Delegate = semantic; IsInfix = isInfix; }
        public Semantic Semantic { get { return (Semantic)Delegate; } }
        public bool IsInfix { get; private set; }
    }

    public class Builtin<TResult> : Builtin
    {
        public Builtin(string id, Func<Environment, TResult> function) : base(id, 0) { Delegate = (Function = function); }
        public override object Invoke(params object[] arguments) { var count = Count(arguments); return Function(count > 0 ? (Environment)arguments[0] : null); }
        public Func<Environment, TResult> Function { get; private set; }
    }

    public class Builtin<T1, TResult> : Builtin
    {
        public Builtin(string id, Func<Environment, T1, TResult> function) : base(id, 1) { Delegate = (Function = function); var arg1 = Function.Method.GetParameters()[1]; Variadic = (typeof(T1) == typeof(object[])) && (arg1.GetCustomAttributes(false).FirstOrDefault(attribute => attribute is ParamArrayAttribute) != null); }
        public override object Invoke(params object[] arguments) { var count = Count(arguments); return Function(count > 0 ? (Environment)arguments[0] : null, count > 1 ? (T1)arguments[1] : default(T1)); }
        public Func<Environment, T1, TResult> Function { get; private set; }
    }

    public class Builtin<T1, T2, TResult> : Builtin
    {
        public Builtin(string id, Func<Environment, T1, T2, TResult> function) : base(id, 2) { Delegate = (Function = function); }
        public override object Invoke(params object[] arguments) { var count = Count(arguments); return Function(count > 0 ? (Environment)arguments[0] : null, count > 1 ? (T1)arguments[1] : default(T1), count > 2 ? (T2)arguments[2] : default(T2)); }
        public Func<Environment, T1, T2, TResult> Function { get; private set; }
    }

    public class Builtin<T1, T2, T3, TResult> : Builtin
    {
        public Builtin(string id, Func<Environment, T1, T2, T3, TResult> function) : base(id, 3) { Delegate = (Function = function); }
        public override object Invoke(params object[] arguments) { var count = Count(arguments); return Function(count > 0 ? (Environment)arguments[0] : null, count > 1 ? (T1)arguments[1] : default(T1), count > 2 ? (T2)arguments[2] : default(T2), count > 3 ? (T3)arguments[3] : default(T3)); }
        public Func<Environment, T1, T2, T3, TResult> Function { get; private set; }
    }

    public class Builtin<T1, T2, T3, T4, TResult> : Builtin
    {
        public Builtin(string id, Func<Environment, T1, T2, T3, T4, TResult> function) : base(id, 4) { Delegate = (Function = function); }
        public override object Invoke(params object[] arguments) { var count = Count(arguments); return Function(count > 0 ? (Environment)arguments[0] : null, count > 1 ? (T1)arguments[1] : default(T1), count > 2 ? (T2)arguments[2] : default(T2), count > 3 ? (T3)arguments[3] : default(T3), count > 4 ? (T4)arguments[4] : default(T4)); }
        public Func<Environment, T1, T2, T3, T4, TResult> Function { get; private set; }
    }

    public class Builtin<T1, T2, T3, T4, T5, TResult> : Builtin
    {
        public Builtin(string id, Func<Environment, T1, T2, T3, T4, T5, TResult> function) : base(id, 4) { Delegate = (Function = function); }
        public override object Invoke(params object[] arguments) { var count = Count(arguments); return Function(count > 0 ? (Environment)arguments[0] : null, count > 1 ? (T1)arguments[1] : default(T1), count > 2 ? (T2)arguments[2] : default(T2), count > 3 ? (T3)arguments[3] : default(T3), count > 4 ? (T4)arguments[4] : default(T4), count > 5 ? (T5)arguments[5] : default(T5)); }
        public Func<Environment, T1, T2, T3, T4, T5, TResult> Function { get; private set; }
    }

    public class Lambda : Callable
    {
        public Lambda(object definition, Func<object[], object> closure, int length) : base(length) { Definition = definition; Delegate = (Closure = closure); }
        public override string ToString() { var pair = (object[])Definition; return string.Concat(Syntax.ToString(pair[0]), " => ", Syntax.ToString(pair[1])); }
        public override object Invoke(params object[] arguments) { return Closure(arguments); }
        public Func<object[], object> Closure { get; private set; }
        public object Definition { get; private set; }
    }

    public class Environment : Dictionary<string, object>
    {
        private object[] GetBindings() { var bindings = this.Where(pair => !Equals(pair.Key, string.Empty)).Select(pair => new[] { pair.Key, pair.Value }); var keyed = new HashSet<object>(bindings.Select(pair => pair[0])); var bound = (Outer != null ? Outer.Bindings.Where(pair => !keyed.Contains(((object[])pair)[0])).Concat(bindings) : bindings).ToArray(); return bound; }
        private bool TryGet(string id, ref object value) { if (id != null) { if (!ContainsKey(id)) { return Outer != null ? Outer.TryGet(id, ref value) : false; } else { value = id.Length > 0 ? this[id] : Bindings; return true; } } else return false; }
        private object[] Bindings { get { return GetBindings(); } }
        public Environment(Language evaluator, Environment outer) : this(evaluator, null as IDictionary<string, object>) { Outer = outer; }
        public Environment(Language evaluator, IDictionary<string, object> builtins) { Language = evaluator; if (builtins != null) { builtins.Aggregate(this, (scope, pair) => { scope.Add(pair.Key, pair.Value); return scope; }); } }
        public object Invoke(string id, params object[] arguments) { return Invoke(Get(id), arguments); }
        public object Invoke(object target, params object[] arguments) { var callable = Language.Require(target as Callable); var argv = new object[arguments != null ? arguments.Length + 1 : 1]; var argc = argv.Length; if (argc > 1) { Array.Copy(arguments, 0, argv, 1, argc - 1); } argv[0] = this; return callable.Invoke(argv); }
        public object Get(string id) { object value = null; if (!TryGet(id, ref value)) { throw Language.Error("undefined {0}", Syntax.ToString(id)); } return value; }
        public bool Knows(Symbol symbol) { object value = null; return TryGet(Language.Require(symbol).Id, ref value); }
        public Language Language { get; private set; }
        public Environment Outer { get; private set; }
        public IDictionary<string, object> Bound { get { return Bindings.Cast<object[]>().ToDictionary(binding => (string)binding[0], binding => binding[1]); } }
    }

    public delegate object Evaluator(Environment environment, object expression);

    public class Language
    {
        private Keyword eval;
        private Keyword apply;
        private Keyword quote;
        private Keyword cons;
        private Keyword let;
        private Keyword lambda;
        private Keyword test;

        private Type[] GetSignature(MethodInfo method)
        {
            var parameters = method.GetParameters();
            var length = parameters.Length;
            return parameters.Select(parameter => parameter.ParameterType).Concat(new[] { method.ReturnType }).ToArray();
        }

        private Type GetDelegateType(Type[] signature)
        {
            var delegateTypes = new[] { null, typeof(Func<,>), typeof(Func<,,>), typeof(Func<,,,>), typeof(Func<,,,,>), typeof(Func<,,,,,>), typeof(Func<,,,,,,>) };
            return delegateTypes[signature.Length - 1].MakeGenericType(signature);
        }

        private Type GetBuiltinType(Type[] signature)
        {
            var builtinTypes = new[] { null, typeof(Builtin<>), typeof(Builtin<,>), typeof(Builtin<,,>), typeof(Builtin<,,,>), typeof(Builtin<,,,,>), typeof(Builtin<,,,,,>) };
            return builtinTypes[signature.Length - 1].MakeGenericType(signature.Skip(1).ToArray());
        }

        private IDictionary<string, object> GetReflectedSemantics()
        {
            return
                GetType().
                GetMembers().
                Aggregate
                (
                    new Dictionary<string, object>(),
                    (reflected, member) =>
                    {
                        var attribute = member.GetCustomAttribute<SemanticAttribute>(false);
                        string id;
                        if ((attribute != null) && ((id = attribute.Id) != null))
                        {
                            var property = member as PropertyInfo;
                            var method = member as MethodInfo;
                            var field = member as FieldInfo;
                            object semantic;
                            if (property != null)
                            {
                                if ((property.GetSetMethod() == null) || !property.GetSetMethod().IsPublic)
                                {
                                    semantic = property.GetValue(this);
                                }
                                else
                                {
                                    throw Error("semantic definition property {0} must be read-only", property.Name);
                                }
                            }
                            else if (method != null)
                            {
                                if (attribute is BuiltinAttribute)
                                {
                                    var signature = GetSignature(method);
                                    var delegateType = GetDelegateType(signature);
                                    var builtinType = GetBuiltinType(signature);
                                    var @delegate = Delegate.CreateDelegate(delegateType, this, method);
                                    semantic = Activator.CreateInstance(builtinType, id, @delegate);
                                }
                                else if (attribute is KeywordAttribute)
                                {
                                    var isInfix = ((KeywordAttribute)attribute).IsInfix;
                                    semantic = Activator.CreateInstance(typeof(Keyword), id, Delegate.CreateDelegate(typeof(Semantic), this, method), isInfix);
                                }
                                else
                                {
                                    throw Error("unsupported semantic definition attribute {0}", attribute.GetType());
                                }
                            }
                            else
                            {
                                if (field.IsInitOnly)
                                {
                                    semantic = field.GetValue(this);
                                }
                                else
                                {
                                    throw Error("semantic definition field {0} must be read-only", field.Name);
                                }
                            }
                            AddSemantic(reflected, id, semantic);
                        }
                        return reflected;
                    }
                );
        }

        internal void AddSemantic(IDictionary<string, object> semantics, string id, object semantic) => semantics.Add(id, semantic);

        protected Keyword KeywordOf(Semantic semantic)
        {
            var defined = Require(semantic);
            var keyword = Semantics.Values.FirstOrDefault(builtin => (builtin is Keyword) && Equals(((Keyword)builtin).Semantic, defined)) as Keyword;
            if (keyword == null)
            {
                throw Error("missing reserved keyword definition: {0}", defined.Method.Name);
            }
            return keyword;
        }

        protected virtual Language Validate()
        {
            Reserved.Where(semantic => semantic != Evaluation).Select(semantic => KeywordOf(semantic)).Count();
            return this;
        }

        protected virtual object Evaluation(Environment environment, object expression, bool topLevel)
        {
            var list = expression as object[];
            var symbol = Syntax.Symbol(expression);
            if (environment == null)
            {
                return Validate().Evaluation(new Environment(this, Semantics), expression);
            }
            else if (list != null)
            {
                Keyword keyword;
                if ((list.Length > 1) && ((symbol = Syntax.Symbol(list[1])) != null) && ((keyword = Keyword(symbol.Id)) != null))
                {
                    if (keyword.IsInfix)
                    {
                        var head = Syntax.Symbol(list[0]);
                        var lead = head != null ? Keyword(head.Id) : null;
                        if ((lead == null) || !IsReserved(lead))
                        {
                            return keyword.Semantic(environment, new[] { list[0] }.Concat(list.Skip(2)).ToArray());
                        }
                        throw Error("infix keyword {0} not allowed after reserved keyword {1}", keyword, lead);
                    }
                    throw Error("not an infix keyword at position 2: {0}", keyword);
                }
                if ((list.Length > 0) && ((symbol = Syntax.Symbol(list[0])) != null) && ((keyword = Keyword(symbol.Id)) != null))
                {
                    return keyword.Semantic(environment, list.Skip(1).ToArray());
                }
                else
                {
                    int length;
                    list = list.Select(item => Evaluation(environment, item)).ToArray();
                    if (((length = list.Length) > 0) && ((symbol = Syntax.Symbol(list[0])) != null) && (symbol is Callable))
                    {
                        var callable = (Callable)symbol;
                        var variadic = callable.Variadic;
                        var arguments = new object[variadic ? length - 1 : length];
                        if (length > 1)
                        {
                            Array.Copy(list, 1, arguments, variadic ? 0 : 1, length - 1);
                        }
                        if (variadic)
                        {
                            return callable.Invoke(environment, arguments);
                        }
                        else
                        {
                            arguments[0] = environment;
                            return callable.Invoke(arguments);
                        }
                    }
                    else
                    {
                        return list;
                    }
                }
            }
            else if (symbol != null)
            {
                return (Delegator != null ? Delegator(environment, symbol) : null) ?? environment.Get(symbol.Id);
            }
            else
            {
                return (Delegator != null ? Delegator(environment, expression) : null) ?? expression;
            }
        }

        protected bool IsReserved(Keyword keyword) => Reserved.Contains(keyword.Semantic);
        protected IDictionary<string, object> Semantics { get; private set; }
        protected HashSet<Semantic> Reserved { get; set; }
        protected Keyword Eval { get { return eval = eval ?? KeywordOf(Evaluate); } }
        protected Keyword Apply { get { return apply = apply ?? KeywordOf(Application); } }
        protected Keyword Quote { get { return quote = quote ?? KeywordOf(Quoting); } }
        protected Keyword Cons { get { return cons = cons ?? KeywordOf(Construction); } }
        protected Keyword Let { get { return let = let ?? KeywordOf(Letting); } }
        protected Keyword Lambda { get { return lambda = lambda ?? KeywordOf(Abstraction); } }
        protected Keyword Test { get { return test = test ?? KeywordOf(Testing); } }

        public static T Require<T>(T value)
            where T : class
        {
            if (value != null)
            {
                return value;
            }
            throw Error("value must be a {0}", typeof(T));
        }

        public static KeyValuePair<string, object> Keyword(string id, Semantic semantic) => Keyword(id, semantic, false);
        public static KeyValuePair<string, object> Keyword(string id, Semantic semantic, bool isInfix) => new KeyValuePair<string, object>(id, new Keyword(id, semantic, isInfix));
        public static KeyValuePair<string, object> Builtin(string id, object value) => new KeyValuePair<string, object>(id, value);
        public static KeyValuePair<string, object> Builtin<TResult>(string id, Func<Environment, TResult> function) => new KeyValuePair<string, object>(id, new Builtin<TResult>(id, function));
        public static KeyValuePair<string, object> Builtin<T1, TResult>(string id, Func<Environment, T1, TResult> function) => new KeyValuePair<string, object>(id, new Builtin<T1, TResult>(id, function));
        public static KeyValuePair<string, object> Builtin<T1, T2, TResult>(string id, Func<Environment, T1, T2, TResult> function) => new KeyValuePair<string, object>(id, new Builtin<T1, T2, TResult>(id, function));
        public static KeyValuePair<string, object> Builtin<T1, T2, T3, TResult>(string id, Func<Environment, T1, T2, T3, TResult> function) => new KeyValuePair<string, object>(id, new Builtin<T1, T2, T3, TResult>(id, function));
        public static KeyValuePair<string, object> Builtin<T1, T2, T3, T4, TResult>(string id, Func<Environment, T1, T2, T3, T4, TResult> function) => new KeyValuePair<string, object>(id, new Builtin<T1, T2, T3, T4, TResult>(id, function));
        public static KeyValuePair<string, object> Builtin<T1, T2, T3, T4, T5, TResult>(string id, Func<Environment, T1, T2, T3, T4, T5, TResult> function) => new KeyValuePair<string, object>(id, new Builtin<T1, T2, T3, T4, T5, TResult>(id, function));
        public static Exception Error(string message, params object[] arguments) => new Exception(string.Format(message, arguments));

        public Language()
            : this(null)
        {
        }

        public Language(Syntax syntax)
        {
            Syntax = syntax ?? new Syntax();
            Semantics = new Dictionary<string, object>(GetReflectedSemantics());
            Reserved = new HashSet<Semantic>(new Semantic[] { Evaluation, Application, Quoting, Construction, Letting, Abstraction, Testing });
        }

        public Keyword Keyword(string token) => Semantics.ContainsKey(token) ? Semantics[token] as Keyword : null;
        public Language Include(params KeyValuePair<string, object>[] semanticDefinitions) => semanticDefinitions.Aggregate(this, (language, semanticDefinition) => { language.AddSemantic(Semantics, semanticDefinition.Key, semanticDefinition.Value); return language; });

        public object Evaluate(string input) => Evaluate(null as Environment, new object[] { input });
        public object Evaluate(string input, params object[] arguments) => Evaluate((arguments != null) && (arguments.Length > 0) ? string.Format(input, arguments) : input);
        public object Evaluate(Environment environment, object expression) => Evaluation(environment, Syntax.Parse((string)(expression as object[])[0]), true);

        public object Evaluation(Environment environment, object expression) => Evaluation(environment, expression, false);

        public object Application(Environment environment, object expression)
        {
            var list = Require(expression as object[]);
            if (list.Length == 2)
            {
                return Evaluation(environment, new[] { list[0] }.Concat(Evaluation(environment, list[1]) as object[]).ToArray());
            }
            throw Error("list must be a pair");
        }

        public object Quoting(Environment environment, object expression)
        {
            var list = Require(expression as object[]);
            if (list.Length == 1)
            {
                return list[0];
            }
            throw Error("list must be a singleton");
        }

        public object Construction(Environment environment, object expression)
        {
            var list = Require(expression as object[]);
            if (list.Length == 2)
            {
                return new[] { Evaluation(environment, list[0]) }.Concat(Require(Evaluation(environment, list[1]) as object[])).ToArray();
            }
            throw Error("list must be a pair");
        }

        public object Letting(Environment environment, object expression)
        {
            var list = Require(expression as object[]);
            if (list.Length == 2)
            {
                var inner = new Environment(this, environment);
                var assignments = Require(list[0] as object[]);
                for (var i = 0; i < assignments.Length; i++)
                {
                    var assignment = Require(assignments[i] as object[]);
                    if (assignment.Length == 2)
                    {
                        var symbol = Require(assignment[0] as Symbol);
                        var maybeReserved = Keyword(symbol.Id);
                        if ((maybeReserved != null) && IsReserved(maybeReserved))
                        {
                            throw Error("cannot overload reserved keyword: {0}", maybeReserved);
                        }
                        inner[symbol.Id] = Evaluation(environment, assignment[1]);
                    }
                    else
                    {
                        throw Error("list must be a pair");
                    }
                }
                return Evaluation(inner, list[1]);
            }
            throw Error("list must be a pair");
        }

        public object Abstraction(Environment environment, object expression)
        {
            var list = Require(expression as object[]);
            var @params = Syntax.Params;
            var @this = Syntax.This;
            if (list.Length == 2)
            {
                var definition = (object[])list.Clone();
                var arguments = Require(list[0] as object[]);
                var length = arguments.Length;
                var formals = new Symbol[length];
                for (var i = 0; i < length; i++)
                {
                    formals[i] = Require(arguments[i] as Symbol);
                }
                var lambda = null as Lambda;
                lambda =
                    new Lambda
                    (
                        definition,
                        delegate (object[] args)
                        {
                            var inner = new Environment(this, environment);
                            var count = Require(args).Length;
                            var i = 0;
                            if (count > 0)
                            {
                                while (i < length)
                                {
                                    var formal = formals[i++];
                                    if (i < count)
                                    {
                                        inner[formal.Id] = args[i];
                                    }
                                }
                                if (@params != null)
                                {
                                    inner[@params.Id] = args.Skip(1).ToArray();
                                }
                                if (@this != null)
                                {
                                    inner[@this.Id] = lambda;
                                }
                                inner[lambda.Id] = lambda;
                                return Evaluation(inner, definition[1]);
                            }
                            throw Error("invalid invocation");
                        },
                        length
                    );
                return lambda;
            }
            throw Error("list must be a pair");
        }

        public object Testing(Environment environment, object expression)
        {
            var list = Require(expression as object[]);
            if (list.Length == 3)
            {
                return (bool)Evaluation(environment, list[0]) ? Evaluation(environment, list[1]) : Evaluation(environment, list[2]);
            }
            else if (list.Length == 2)
            {
                return Evaluation(environment, new[] { Test, new[] { Test, list[0] }, list[0], list[1] });
            }
            else if (list.Length == 1)
            {
                return environment.Knows(Require(list[0] as Symbol));
            }
            else
            {
                throw Error("list must be a singleton, a pair, or a triple");
            }
        }

        public Evaluator Delegator { get; protected set; }
        public Syntax Syntax { get; private set; }
    }
}

namespace System.Language.TypeInference
{
    #region Abstract syntax tree
    public abstract class Node
    {
        public static Const Const(object value) => new Const { Spec = value != null ? (!(value is IType) ? value.GetType().FullName : value) : typeof(void).FullName };
        public static Var Var(string name) => Var(name, null);
        public static Var Var(string name, object type) => new Var { Spec = name, Type = type };
        public static Apply Apply(Node expr, Node[] args) => Apply(expr, args, null);
        public static Apply Apply(Node expr, Node[] args, bool isAnnotation) => Apply(expr, args, null, isAnnotation);
        public static Apply Apply(Node expr, Node[] args, object ctor) => Apply(expr, args, ctor, false);
        public static Apply Apply(Node expr, Node[] args, object ctor, bool isAnnotation) => new Apply { Spec = expr, Args = args, Type = ctor, IsAnnotation = isAnnotation };
        public static Abstract Abstract(Node[] args, Node body) => Abstract(args, null, body);
        public static Abstract Abstract(Node[] args, object type, Node body) => new Abstract { Args = args, Body = body, Type = type };
        public static Define Define(Var var, Node body) => new Define { Spec = var, Body = (body as Node) ?? Const(body) };
        public static Let Let(Define[] defs, Node body) => new Let { Args = defs, Body = body };
        public abstract IType Infer(ITypeSystem system, IEnvironment env, IList<IType> types);
        public object Spec { get; private set; }
        public Node[] Args { get; private set; }
        public Node Body { get; private set; }
        public object Type { get; private set; }
        public bool IsAnnotation { get; private set; }
    }

    public class Const : Node
    {
        public override string ToString() => string.Concat("{", Spec, "}");
        public override IType Infer(ITypeSystem system, IEnvironment env, IList<IType> types) => !(Spec is IType) ? system.Const(env, (string)Spec) : (IType)Spec;
    }

    public class Var : Node
    {
        public override string ToString() => Id;
        public override IType Infer(ITypeSystem system, IEnvironment env, IList<IType> types) => system.Fresh(env[Id], types.ToArray());
        public string Id => (string)Spec;
        public bool IsConstructor => (Type is IType) && ((IType)Type).IsConstructor;
    }

    public class Abstract : Node
    {
        public override string ToString() => string.Format("( {0}){2} => {1}", Args.Length > 0 ? string.Concat(string.Join(" ", Args.Select(arg => arg.ToString()).ToArray()), " ") : string.Empty, Body, Type != null ? string.Concat(" : ", Type) : string.Empty);
        public override IType Infer(ITypeSystem system, IEnvironment env, IList<IType> types)
        {
            var scope = env.Local(system);
            var known = new List<IType>(types);
            var args = new List<IType>();
            foreach (var arg in Args)
            {
                IType type;
                Var var;
                if (!(arg is Define))
                {
                    var = (Var)arg;
                    if (var.Type != null)
                    {
                        type = !(var.Type is IType) ? system.Const(scope, (string)var.Type) : (IType)var.Type;
                    }
                    else
                    {
                        type = system.NewGeneric();
                        known.Add(type);
                    }
                    scope[var.Id] = type;
                }
                else
                {
                    var spec = ((Define)arg).Body;
                    var = (Var)((Define)arg).Spec;
                    type = system.NewGeneric();
                    system.Unify(type, system.Infer(scope, spec, known));
                    scope[var.Id] = type;
                    known.Add(type);
                }
                args.Add(type);
                if (!type.Value.IsConstructor)
                {
                    type.Value.Bind(var.Id);
                }
            }
            args.Add(system.Infer(scope, Body is Let ? Body.Args[Body.Args.Length - 1] : Body, known));
            if (Type != null)
            {
                system.Unify(args[args.Count - 1], !(Type is IType) ? system.Const(scope, (string)Type) : (IType)Type);
            }
            return system.NewType(TypeSystem.Function, args.ToArray());
        }
    }

    public class Apply : Node
    {
        private bool IsFunction(IType type) => type != null ? (type.Constructor != null ? type.Constructor == TypeSystem.Function : IsFunction(type.Self)) : false;
        private Node ToFormal(ITypeSystem system, IEnvironment env, IList<IType> types, Node arg)
        {
            Func<Var, IType> typed =
                var =>
                    IsAnnotation && !env.ContainsKey(var.Id) ? env[var.Id] = system.NewGeneric() : env[var.Id];
            var formal =
                IsAnnotation ?
                (
                    arg is Apply ?
                    Define((Var)arg.Args[0], Const(system.Infer(env, (Node)arg.Spec, types)))
                    :
                    arg is Var ? Define((Var)arg, Const(typed((Var)arg))) : arg
                )
                :
                arg is Var ? Define((Var)arg, Const(typed((Var)arg))) : arg;
            return formal;
        }
        private IType AsAnnotationType(ITypeSystem system, IEnvironment env, IList<IType> types)
        {
            IType ctor;
            if
            (
                (Spec is Node) &&
                (((ctor = ((Node)Spec).Type as IType)) != null) &&
                (!IsFunction(ctor) || IsAnnotation)
            )
            {
                Args.Select
                    (
                        (arg, i) =>
                            arg is Var ?
                            system.Infer(env, Define((Var)arg, Const(ctor[i])), types)
                            :
                            null
                    ).
                    ToArray();
                var type = system.NewType(ctor, Args.Select(arg => system.Infer(env, ToFormal(system, env, types, arg), types)).ToArray());
                return type;
            }
            else
            {
                return null;
            }
        }
        public override string ToString() => string.Format("( {0} {1})", Spec, Args.Length > 0 ? string.Concat(string.Join(" ", Args.Select(arg => arg.ToString()).ToArray()), " ") : string.Empty);
        public override IType Infer(ITypeSystem system, IEnvironment env, IList<IType> types)
        {
            if (Type == null)
            {
                var annotation = AsAnnotationType(system, env, types);
                if (annotation != null)
                {
                    return annotation;
                }
            }
            var args = Args.Select(arg => system.Infer(env, ToFormal(system, env, types, arg), types)).ToList();
            var expr = (Node)Spec;
            var self = system.Infer(env, expr, types);
            IType @out;
            if (Type != null)
            {
                var ctor = !(Type is IType) ? system.Const(env, (string)Type) : (IType)Type;
                @out = system.Infer(env, Apply(Var(ctor.Id, ctor), args.Select(arg => Const(arg)).ToArray(), IsAnnotation), types);
            }
            else
            {
                @out = system.NewGeneric();
                args.Add(@out);
                system.Unify(system.NewType(TypeSystem.Function, args.ToArray()), self);
            }
            return @out;
        }
    }

    public class Define : Node
    {
        public override string ToString() => string.Format("( {0} = {1} )", Spec, Body);
        public override IType Infer(ITypeSystem system, IEnvironment env, IList<IType> types)
        {
            var known = new List<IType>(types);
            var type = system.NewGeneric();
            var var = (Var)Spec;
            var scope = Body.IsAnnotation ? env.Local(system) : env;
            env[var.Id] = type;
            known.Add(type);
            system.Unify(type, system.Infer(scope, Body, known));
            return env[var.Id] = !type.Value.IsConstructor ? type.Value.Bind(var.Id) : type.Value;
        }
    }

    public class Let : Node
    {
        public override string ToString() => string.Format("( ( {0}) {1} )", Args.Length > 0 ? string.Concat(string.Join(" ", Args.Select(arg => arg.ToString()).ToArray()), " ") : string.Empty, Body);
        public override IType Infer(ITypeSystem system, IEnvironment env, IList<IType> types)
        {
            env = env.Local(system);
            return Args.Select(define => system.Infer(env, define, types)).Concat(new[] { system.Infer(env, Body, types) }).Last();
        }
    }
    #endregion

    #region Type schemes
    public interface IType
    {
        IType Bind(string name);
        IType Constructor { get; }
        string Id { get; }
        IType[] Args { get; }
        IType Self { get; }
        Var Name { get; }
        IType Value { get; }
        bool IsConstructor { get; }
        object Metadata { get; }
        IType this[int index] { get; }
    }
    #endregion

    #region Environment
    public interface IEnvironment : IDictionary<string, IType>
    {
        IEnvironment Local(ITypeSystem system);
    }

    public class Environment : Dictionary<string, IType>, IEnvironment
    {
        protected virtual IType Get(string id)
        {
            if (id == null)
            {
                throw new ArgumentNullException("id", "cannot be null");
            }
            if (!ContainsKey(id))
            {
                throw new InvalidOperationException(string.Format("undefined {0}", id));
            }
            return base[id];
        }
        protected virtual void Set(string id, IType type)
        {
            if (id == null)
            {
                throw new ArgumentNullException("id", "cannot be null");
            }
            base[id] = type;
        }

        public Environment() : this(null) { }
        public Environment(IDictionary<string, IType> outer) : base(outer ?? new Dictionary<string, IType>()) { }
        public IEnvironment Local(ITypeSystem system) => system.NewEnvironment(this);
        public new IType this[string id] { get { return Get(id); } set { Set(id, value); } }
    }
    #endregion

    #region Type system
    public interface ITypeSystem
    {
        IEnvironment NewEnvironment();
        IEnvironment NewEnvironment(IDictionary<string, IType> outer);
        IType Fresh(IType t, IType[] types);
        IType Const(IEnvironment env, string ctor);
        IType NewGeneric();
        IType NewType(string id, IType[] args);
        IType NewType(string id, IType[] args, object meta);
        IType NewType(IType constructor, IType[] args);
        IType NewType(IType constructor, IType[] args, object meta);
        IType NewType(IType constructor, string id, IType[] args);
        IType NewType(IType constructor, string id, IType[] args, object meta);
        void Unify(IType t, IType s);
        IType Infer(IEnvironment env, Node node);
        IType Infer(IEnvironment env, Node node, IList<IType> types);
    }

    public class TypeSystem : ITypeSystem
    {
        internal abstract class Scheme : IType
        {
            protected Scheme(string id) { if ((this is Type) && (id == null)) { throw new ArgumentNullException("id", "cannot be null"); } Bind(Id = id); }
            protected Scheme(string id, IType[] args) : this(id) { Args = args ?? new IType[0]; }
            public override string ToString() => Id;
            public IType Bind(string name) { Name = Node.Var(name, this); return this; }
            public IType Constructor { get; protected set; }
            public virtual string Id { get; protected set; }
            public IType[] Args { get; private set; }
            public IType Self { get; internal set; }
            public Var Name { get; private set; }
            public IType Value => Self != null ? Self.Value : this;
            public bool IsConstructor => Constructor == this;
            public object Metadata { get; protected set; }
            public IType this[int index] => Args[index];
        }

        internal class Generic : Scheme
        {
            private string alpha;
            private string Alpha() { var id = Uid; var sb = new StringBuilder(); while (id-- > 0) { var r = id % 26; var c = (char)(r + 97); sb.Insert(0, c); id = (id - r) / 26; } return sb.ToString(); }
            private string GetName() => Self != null ? Self.Id : string.Concat('`', alpha ?? (alpha = Alpha()));
            internal Generic(TypeSystem system) : base(null) { Uid = system.NewId(); }
            internal readonly int Uid;
            public override string ToString() => Self != null ? Self.ToString() : base.ToString();
            public override string Id { get { return GetName(); } protected set { } }
        }

        internal class Type : Scheme
        {
            internal Type(IType constructor, string id, IType[] args, object meta) : base(id, args) { Constructor = constructor ?? this; Metadata = meta; }
            public override string ToString() { var id = Args.Length > 0 ? Id : base.ToString(); return (Args.Length > 0 ? string.Format("{0}<{1}>", id, string.Concat(string.Join(", ", Args.Take(Args.Length - 1).Select(arg => arg.ToString())), (Args.Length > 1 ? ", " : string.Empty), Args[Args.Length - 1].ToString())) : id); }
        }

        private static IType Create(IType constructor, string id, IType[] args, object meta) => new Type(constructor, id, args, meta);
        private static IType Prune(IType t)
        {
            Generic var = t as Generic;
            return (var != null) && (var.Self != null) ? (var.Self = Prune(var.Self)) : t;
        }
        private static bool OccursIn(IType t, IType s) => ((s = Prune(s)) != t) ? (s is Type ? OccursIn(t, s.Args) : false) : true;
        private static bool OccursIn(IType t, IType[] types) => types.Any(type => OccursIn(t, type));
        private IType Fresh(IType t, IType[] types, IDictionary<int, IType> vars)
        {
            vars = vars ?? new Dictionary<int, IType>();
            t = Prune(t);
            var var = t as Generic;
            var type = t as Type;
            if (var != null)
            {
                if (!OccursIn(t, types))
                {
                    if (!vars.ContainsKey(var.Uid))
                    {
                        vars[var.Uid] = NewGeneric();
                    }
                    return vars[var.Uid];
                }
                else
                {
                    return t;
                }
            }
            else if (type != null)
            {
                return NewType(type.Constructor, type.Id, type.Args.Select(arg => Fresh(arg, types, vars)).ToArray());
            }
            else
            {
                throw new InvalidOperationException(string.Format("unsupported {0}", t.GetType()));
            }
        }
        private int id;
        internal int NewId() => ++id;

        public static readonly IType Function = Create(null, "Func", null, null);

        #region ITypeSystem
        public virtual IEnvironment NewEnvironment() => NewEnvironment(null);
        public virtual IEnvironment NewEnvironment(IDictionary<string, IType> outer) => new Environment(outer);
        public IType Fresh(IType t, IType[] types) => Fresh(t, types, null);
        public IType Const(IEnvironment env, string ctor) => env[ctor];
        public IType NewGeneric() => new Generic(this);
        public IType NewType(string id, IType[] args) => NewType(id, args, null);
        public IType NewType(string id, IType[] args, object meta) => NewType(null, id, args, meta);
        public IType NewType(IType constructor, IType[] args) => NewType(constructor, args, null);
        public IType NewType(IType constructor, IType[] args, object meta) => NewType(constructor, constructor.Id, args, meta);
        public IType NewType(IType constructor, string id, IType[] args) => NewType(constructor, id, args, null);
        public IType NewType(IType constructor, string id, IType[] args, object meta) => Create(constructor, id, args, meta);
        public void Unify(IType t, IType s)
        {
            t = Prune(t);
            s = Prune(s);
            if (t is Generic)
            {
                if (t != s)
                {
                    if (OccursIn(t, s))
                    {
                        throw new InvalidOperationException(string.Format("recursive unification of {0} in {1}", t, s));
                    }
                    ((Generic)t).Self = s;
                }
            }
            else if ((t is Type) && (s is Generic))
            {
                Unify(s, t);
            }
            else if ((t is Type) && (s is Type))
            {
                var t_type = (Type)t;
                var s_type = (Type)s;
                if ((t_type.Constructor.Id != s_type.Constructor.Id) || (t_type.Args.Length != s_type.Args.Length))
                {
                    throw new InvalidOperationException(string.Format("{0} incompatible with {1}", t_type, s_type));
                }
                for (var i = 0; i < t_type.Args.Length; i++)
                {
                    Unify(t_type.Args[i], s_type.Args[i]);
                }
            }
            else
            {
                throw new InvalidOperationException(string.Format("undecided unification for {0} and {1}", t, s));
            }
        }
        public IType Infer(IEnvironment env, Node node) => Infer(env, node, null);
        public IType Infer(IEnvironment env, Node node, IList<IType> types) => node.Infer(this, env, types ?? new List<IType>());
        #endregion
    }
    #endregion
}

namespace Test
{
    using System.Language.SExpressions;
    using System.Language.TypeInference;
    
    class Program
    {
        public class CtorInfo
        {
            public readonly string Cons;
            public readonly int Arity;
            public CtorInfo(string cons, int arity) { Cons = cons; Arity = arity; }
            public IType GetType(IEnvironment env) =>
                env.
                Values.
                FirstOrDefault
                (
                    type =>
                        (type.Metadata != null) &&
                        (((CtorInfo)type.Metadata).Cons == Cons) &&
                        (
                            (((CtorInfo)type.Metadata).Arity == Arity) ||
                            (((CtorInfo)type.Metadata).Arity < 0) ||
                            (Arity < 0)
                        )
                );
        }

        static void Main(string[] args)
        {
            var syntax =
                new Syntax().
                Include
                (
                    // Required
                    Syntax.Lexical("'", Syntax.Quoting),

                    // Not-quite-Lisp-indeed; just stolen from our host, C#, as-is
                    Syntax.Lexical("\\/\\/.*", Syntax.Commenting),
                    Syntax.Lexical("false", (token, match) => false),
                    Syntax.Lexical("true", (token, match) => true),
                    Syntax.Lexical("null", (token, match) => null),

                    // Integers (unsigned)
                    Syntax.Lexical("[0-9]+", (token, match) => int.Parse(match)),

                    // String literals
                    Syntax.Lexical("\\\"(\\\\\\n|\\\\t|\\\\n|\\\\r|\\\\\\\"|[^\\\"])*\\\"", (token, match) => match.Substring(1, match.Length - 2)),

                    // For identifiers...
                    Syntax.Lexical("[\\$_A-Za-z][\\$_0-9A-Za-z\\-\\.\\`]*", Syntax.NewSymbol),

                    // ... and such
                    Syntax.Lexical("[\\!\\&\\|\\<\\=\\>\\+\\-\\*\\/\\%\\,\\:@]", Syntax.NewSymbol),
                    Syntax.Lexical("\\&\\&", Syntax.NewSymbol, true),
                    Syntax.Lexical("\\|\\|", Syntax.NewSymbol, true),
                    Syntax.Lexical("\\<\\=", Syntax.NewSymbol, true),
                    Syntax.Lexical("\\>\\=", Syntax.NewSymbol, true),
                    Syntax.Lexical("\\!\\=", Syntax.NewSymbol, true),
                    Syntax.Lexical("\\=\\=", Syntax.NewSymbol, true),
                    Syntax.Lexical("\\=\\>", Syntax.NewSymbol, true),
                    Syntax.Lexical("\\-\\>", Syntax.NewSymbol, true)
                );

            var system = new TypeSystem();
            var env = system.NewEnvironment();

            // Classic
            var @bool = system.NewType(typeof(bool).FullName, null);
            var @int = system.NewType(typeof(int).FullName, null);
            var @string = system.NewType(typeof(string).FullName, null);

            var SignatureType = system.NewType(TypeSystem.Function, null, new CtorInfo("->", -1));

            // Generic list type of some `item' type : List<item>;
            // syntax for lists:
            // <list-sexpr> ::= '(' <sexpr> ':' <list-sexpr> ')' | '(' ')'
            // (where "( )" is the empty list)
            var ListType = system.NewType("List", new[] { system.NewGeneric() }, new CtorInfo(":", 2));

            // Generic tuple types of some `item1', `item2', ... types : Tuple<item1, item2, ...>
            // syntax for tuples:
            // <tuple-sexpr> ::= '(' <sexpr> ',' ... ')' | '(' ',' ')'
            // (where "( , )" is the empty tuple and "( , <sexpr> )" or "( <sexpr> , )" the unary tuple)
            var Tuple00Type = system.NewType("Tuple`0", null, new CtorInfo(",", 0));
            var Tuple01Type = system.NewType("Tuple`1", new[] { system.NewGeneric() }, new CtorInfo(",", 1));
            var Tuple02Type = system.NewType("Tuple`2", new[] { system.NewGeneric(), system.NewGeneric() }, new CtorInfo(",", 2));
            var Tuple03Type = system.NewType("Tuple`3", new[] { system.NewGeneric(), system.NewGeneric(), system.NewGeneric() }, new CtorInfo(",", 3));
            var Tuple04Type = system.NewType("Tuple`4", new[] { system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric() }, new CtorInfo(",", 4));
            var Tuple05Type = system.NewType("Tuple`5", new[] { system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric() }, new CtorInfo(",", 5));
            var Tuple06Type = system.NewType("Tuple`6", new[] { system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric() }, new CtorInfo(",", 6));
            var Tuple07Type = system.NewType("Tuple`7", new[] { system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric() }, new CtorInfo(",", 7));
            var Tuple08Type = system.NewType("Tuple`8", new[] { system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric() }, new CtorInfo(",", 8));
            var Tuple09Type = system.NewType("Tuple`9", new[] { system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric() }, new CtorInfo(",", 9));
            var Tuple10Type = system.NewType("Tuple`10", new[] { system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric() }, new CtorInfo(",", 10));
            var Tuple11Type = system.NewType("Tuple`11", new[] { system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric() }, new CtorInfo(",", 11));
            var Tuple12Type = system.NewType("Tuple`12", new[] { system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric() }, new CtorInfo(",", 12));
            var Tuple13Type = system.NewType("Tuple`13", new[] { system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric() }, new CtorInfo(",", 13));
            var Tuple14Type = system.NewType("Tuple`14", new[] { system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric() }, new CtorInfo(",", 14));
            var Tuple15Type = system.NewType("Tuple`15", new[] { system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric(), system.NewGeneric() }, new CtorInfo(",", 15));

            // Populate the top level typing environment
            env["bool"] = env[@bool.Id] = @bool;
            env["int"] = env[@int.Id] = @int;
            env["string"] = env[@string.Id] = @string;
            env[SignatureType.Id] = SignatureType;
            env[ListType.Id] = ListType;
            new[]
            {
                Tuple00Type, Tuple01Type, Tuple02Type, Tuple03Type,
                Tuple04Type, Tuple05Type, Tuple06Type, Tuple07Type,
                Tuple08Type, Tuple09Type, Tuple10Type, Tuple11Type,
                Tuple12Type, Tuple13Type, Tuple14Type, Tuple15Type
            }.
            Aggregate(env, (e, t) => { e[t.Id] = t; return e; });

            // Bake some operator function types (to have something to infer about in familiar expressions)
            var binary1 = system.NewGeneric();
            var binary2 = system.NewGeneric();
            var binary3 = system.NewGeneric();
            var binary4 = system.NewGeneric();
            var binary5 = system.NewGeneric();
            var binary6 = system.NewGeneric();
            var binary7 = system.NewGeneric();
            var binary8 = system.NewGeneric();
            var binary9 = system.NewGeneric();
            var binary10 = system.NewGeneric();
            var binary11 = system.NewGeneric();

            // boolean operators ( bool -> bool ) and ( bool -> bool -> bool )
            // (e.g., "( ! ( empty ( 0 : ( ) ) ) )")
            system.Infer(env, Node.Define(Node.Var("!"), Node.Abstract(new[] { Node.Var("expr", @bool) }, @bool, Node.Const(@bool))));
            system.Infer(env, Node.Define(Node.Var("&&"), Node.Abstract(new[] { Node.Var("left", @bool), Node.Var("right", @bool) }, @bool, Node.Const(@bool))));
            system.Infer(env, Node.Define(Node.Var("||"), Node.Abstract(new[] { Node.Var("left", @bool), Node.Var("right", @bool) }, @bool, Node.Const(@bool))));

            // Polymorphic operator types
            system.Infer(env, Node.Define(Node.Var("+"), Node.Abstract(new[] { Node.Var("left", binary1), Node.Var("right", binary1) }, binary1, Node.Var("left"))));
            system.Infer(env, Node.Define(Node.Var("-"), Node.Abstract(new[] { Node.Var("left", binary2), Node.Var("right", binary2) }, binary2, Node.Var("left"))));
            system.Infer(env, Node.Define(Node.Var("*"), Node.Abstract(new[] { Node.Var("left", binary3), Node.Var("right", binary3) }, binary3, Node.Var("left"))));
            system.Infer(env, Node.Define(Node.Var("/"), Node.Abstract(new[] { Node.Var("left", binary4), Node.Var("right", binary4) }, binary4, Node.Var("left"))));
            system.Infer(env, Node.Define(Node.Var("%"), Node.Abstract(new[] { Node.Var("left", binary5), Node.Var("right", binary5) }, binary5, Node.Var("left"))));
            system.Infer(env, Node.Define(Node.Var(">"), Node.Abstract(new[] { Node.Var("left", binary6), Node.Var("right", binary6) }, @bool, Node.Const(@bool))));
            system.Infer(env, Node.Define(Node.Var(">="), Node.Abstract(new[] { Node.Var("left", binary7), Node.Var("right", binary7) }, @bool, Node.Const(@bool))));
            system.Infer(env, Node.Define(Node.Var("<"), Node.Abstract(new[] { Node.Var("left", binary8), Node.Var("right", binary8) }, @bool, Node.Const(@bool))));
            system.Infer(env, Node.Define(Node.Var("<="), Node.Abstract(new[] { Node.Var("left", binary9), Node.Var("right", binary9) }, @bool, Node.Const(@bool))));
            system.Infer(env, Node.Define(Node.Var("=="), Node.Abstract(new[] { Node.Var("left", binary10), Node.Var("right", binary10) }, @bool, Node.Const(@bool))));
            system.Infer(env, Node.Define(Node.Var("!="), Node.Abstract(new[] { Node.Var("left", binary11), Node.Var("right", binary11) }, @bool, Node.Const(@bool))));

            // A ternary if-then-else will come in handy too
            var ifThenElse = system.NewGeneric();
            system.Infer(env, Node.Define(Node.Var("if"), Node.Abstract(new[] { Node.Var("condition", @bool), Node.Var("then", ifThenElse), Node.Var("else", ifThenElse) }, ifThenElse, Node.Var("then"))));

            system.Infer(env, Node.Define(Node.Var("first"), Node.Abstract(new[] { Node.Var("pair", Tuple02Type) }, Tuple02Type[0], Node.Const(Tuple02Type[0]))));
            system.Infer(env, Node.Define(Node.Var("second"), Node.Abstract(new[] { Node.Var("pair", Tuple02Type) }, Tuple02Type[1], Node.Const(Tuple02Type[1]))));
            system.Infer(env, Node.Define(Node.Var("count"), Node.Abstract(new[] { Node.Var("list", ListType) }, @int, Node.Const(@int))));
            system.Infer(env, Node.Define(Node.Var("empty"), Node.Abstract(new[] { Node.Var("list", ListType) }, @bool, Node.Const(@bool))));
            system.Infer(env, Node.Define(Node.Var("head"), Node.Abstract(new[] { Node.Var("list", ListType) }, ListType[0], Node.Const(ListType[0]))));
            system.Infer(env, Node.Define(Node.Var("tail"), Node.Abstract(new[] { Node.Var("list", ListType) }, ListType, Node.Const(ListType))));
            system.Infer(env, Node.Define(Node.Var("length"), Node.Abstract(new[] { Node.Var("string", @string) }, @int, Node.Const(@int))));
            system.Infer(env, Node.Define(Node.Var("escape"), Node.Abstract(new[] { Node.Var("string", @string) }, @string, Node.Const(@string))));
            system.Infer(env, Node.Define(Node.Var("toString"), Node.Abstract(new[] { Node.Var("value", system.NewGeneric()) }, @string, Node.Const(@string))));
            system.Infer(env, Node.Define(Node.Var("parseInt"), Node.Abstract(new[] { Node.Var("string", @string) }, @int, Node.Const(@int))));

            // DRY helpers
            var isFunction = null as Func<IType, bool>;
            isFunction = type => type != null ? (type.Constructor != null ? type.Constructor == TypeSystem.Function : isFunction(type.Self)) : false;
            Func<string, int, IType> @typeof = (id, arity) => id != null ? (new CtorInfo(id, arity).GetType(env) ?? (env.ContainsKey(id) && env[id].Value.Name.IsConstructor ? env[id].Value : null)) : null;
            Func<string, int, bool> isCtor = (id, arity) => @typeof(id, arity) != null;
            Func<object, bool> isArray = value => value is object[];
            Func<object, object[]> array = value => (object[])value;
            Func<object, bool> isNil = value => isArray(value) && (array(value).Length == 0);

            // A sort of poor man's visitor (over the S-expr) : just a bunch of lambdas
            Func<IEnvironment, string, Node> visitError = (scope, message) => { throw new InvalidOperationException(message); };
            Func<IEnvironment, object, bool, Node> visitSExpr = null;
            Func<IEnvironment, object, Let> visitLet = null;
            Func<IEnvironment, object, int, bool, Define> visitDefine = null;
            Func<IEnvironment, object, bool, Apply> visitApply = null;
            Func<IEnvironment, object, Abstract> visitAbstract = null;
            Func<IEnvironment, object, int, bool, Apply> visitCtor = null;
            Func<IEnvironment, object, Var> visitVar = null;
            Func<IEnvironment, object, Const> visitConst = null;
            Func<IEnvironment, object, Node> visit;

            visitSExpr =
                (scope, sexpr, inType) =>
                {
                    var arity = (isArray(sexpr) ? array(sexpr).Length : 0) - 1;
                    var node =
                        isArray(sexpr) ?
                        (
                            // ( let / | / sexpr ... )
                            array(sexpr).Length > 1 ?
                            (
                                (Syntax.Identifier(array(sexpr)[0]) == null) || (Syntax.Identifier(array(sexpr)[0]) != "let") ?
                                (
                                    // ( <ctor> / sexpr ... )
                                    Syntax.Identifier(array(sexpr)[1]) != "=>" ?
                                    (
                                        // ( sexpr ... )
                                        !isCtor(Syntax.Identifier(array(sexpr)[0]), arity) ?
                                        (
                                            !isCtor(Syntax.Identifier(array(sexpr)[1]), arity) ?
                                            // ( sexpr ... )
                                            visitApply(scope, sexpr, inType)
                                            :
                                            // ( sexpr <ctor> ... )
                                            visitCtor(scope, sexpr, 1, inType)
                                        )
                                        :
                                        // ( <ctor> ... )
                                        visitCtor(scope, sexpr, 0, inType)
                                    )
                                    :
                                    // ( ... => ... )
                                    !inType ? visitAbstract(scope, sexpr) : visitError(scope, "'=>' not allowed in type annotation")
                                )
                                :
                                // ( let ... )
                                !inType ? visitLet(scope, sexpr) : visitError(scope, "'let' not allowed in type annotation")
                            )
                            :
                            (
                                // ( id / sexpr )
                                !isNil(sexpr) ?
                                (
                                    !isCtor(Syntax.Identifier(array(sexpr)[0]), 0) ?
                                    // ( sexpr )
                                    (Node)visitApply(scope, sexpr, inType)
                                    :
                                    // ( <ctor> )
                                    visitCtor(scope, sexpr, 0, inType)
                                )
                                :
                                // ( )
                                visitConst(scope, ListType)
                            )
                        )
                        :
                        // id / const
                        Syntax.Identifier(sexpr) != null ? (Node)visitVar(scope, sexpr) : visitConst(scope, sexpr);
                    return node;
                };

            visitLet =
                (scope, sexpr) =>
                {
                    var let = Node.Let(array(array(sexpr)[1]).Select(item => visitDefine(scope, item, 0, false)).ToArray(), visitSExpr(scope, array(sexpr)[2], false));
                    return let;
                };

            visitDefine =
                (scope, sexpr, at, inType) =>
                {
                    var left = array(sexpr)[0];
                    Var identifier;
                    Node definition;
                    if (!inType && isArray(left) && (array(left).Length == 1))
                    {
                        var right = array(sexpr)[1];
                        var arity = (isArray(right) ? array(right).Length : 0) - 1;
                        identifier = visitVar(scope, array(left)[0]);
                        definition =
                            isArray(right) ?
                            (
                                array(right).Length > 1 ?
                                (
                                    !isCtor(Syntax.Identifier(array(right)[1]), arity) ?
                                    (
                                        !isCtor(Syntax.Identifier(array(right)[0]), arity) ?
                                        visitApply(scope, right, true)
                                        :
                                        visitCtor(scope, right, 0, true)
                                    )
                                    :
                                    visitCtor(scope, right, 1, true)
                                )
                                :
                                (
                                    !isNil(right) ?
                                    (
                                        !isCtor(Syntax.Identifier(array(right)[0]), 0) ?
                                        (Node)visitApply(scope, right, inType)
                                        :
                                        visitCtor(scope, right, 0, true)
                                    )
                                    :
                                    visitConst(scope, ListType)
                                )
                            )
                            :
                            Syntax.Identifier(right) != null ? (Node)visitVar(scope, right) : visitConst(scope, right);
                    }
                    else
                    {
                        identifier = visitVar(scope, array(sexpr)[at]);
                        definition = visitSExpr(scope, array(sexpr)[1 - at], inType);
                    }
                    var define = Node.Define(identifier, definition);
                    return define;
                };

            visitApply =
                (scope, sexpr, inType) =>
                {
                    Func<IType[], IType> newFunction = signature => system.NewType(TypeSystem.Function, signature);
                    Apply apply;
                    string id;
                    if (((id = Syntax.Identifier(array(sexpr)[0])) != null) && (!env.ContainsKey(id) || isFunction(env[id])))
                    {
                        var fn = Node.Var(id, !env.ContainsKey(id) ? env[id] = newFunction(array(sexpr).Skip(1).Select(arg => system.NewGeneric()).Concat(new[] { system.NewGeneric() }).ToArray()) : env[id]);
                        apply = Node.Apply(fn, array(sexpr).Skip(1).Select(arg => visitSExpr(scope, arg, false)).ToArray());
                    }
                    else
                    {
                        apply =
                            Node.Apply
                            (
                                visitSExpr(scope, array(sexpr)[0], inType),
                                array(sexpr).Skip(1).Select(arg => visitSExpr(scope, arg, inType)).ToArray(),
                                id != null ? env[id] : null,
                                inType
                            );
                    }
                    return apply;
                };

            visitAbstract =
                (scope, sexpr) =>
                {
                    Abstract lambda;
                    lambda =
                        Node.Abstract
                        (
                            array(array(sexpr)[0]).Select(arg => isArray(arg) ? (Node)visitDefine(scope, arg, 1, true) : visitVar(scope, arg)).ToArray(),
                            visitSExpr(scope, array(sexpr)[2], false)
                        );
                    return lambda;
                };

            visitCtor =
                (scope, sexpr, at, inType) =>
                {
                    var identifier = Syntax.Identifier(array(sexpr)[at]);
                    var isList = identifier == ((CtorInfo)ListType.Metadata).Cons;
                    var arity = at > 0 ? (array(sexpr).Length + 1) / 2 : array(sexpr).Length - 1;
                    var type = @typeof(identifier, arity);
                    var argv =
                        at > 0 ?
                        array(sexpr).Where((arg, i) => (i % 2) == 0).Select(arg => visitSExpr(scope, arg, inType)).Take(isList ? arity - 1 : arity).ToArray()
                        :
                        array(sexpr).Skip(1).Select(arg => visitSExpr(scope, arg, inType)).Take(isList ? arity - 1 : arity).ToArray();
                    var ctor = Node.Apply(Node.Var(type.Id), argv, isFunction(type) ? TypeSystem.Function : type, inType);
                    return ctor;
                };

            visitVar =
                (scope, sexpr) =>
                {
                    var var = Node.Var(Syntax.Identifier(sexpr));
                    return var;
                };

            visitConst =
                (scope, sexpr) =>
                {
                    var @const = Node.Const(sexpr);
                    return @const;
                };

            visit =
                (scope, sexpr) =>
                {
                    var root = visitSExpr(scope, sexpr, false);
                    return root;
                };

            Action<Node> analyze =
                root =>
                {
                    Func<Node, IType> tryInfer =
                        node =>
                        {
                            try
                            {
                                return system.Infer(env, node);
                            }
                            catch (Exception ex)
                            {
                                return system.NewType(string.Format("Type error: {0}", ex.Message), null);
                            }
                        };
                    var sw = new System.Diagnostics.Stopwatch();
                    sw.Start();
                    foreach (var node in root.Args)
                    {
                        Console.WriteLine();
                        Console.WriteLine(node.Spec is Node ? string.Format("{0}:\r\n\t{1}", (Node)node.Spec, tryInfer(node).Value) : tryInfer(node).Value.ToString());
                    }
                    sw.Stop();
                    Console.WriteLine();
                    Console.WriteLine(string.Format("{0}:\r\n\t{1}", root.Body, tryInfer(root.Body)));
                    Console.WriteLine();
                    Console.WriteLine("... Done (in {0} ms)", sw.ElapsedMilliseconds);
                    Console.WriteLine();
                };

            // Parse some S-expr's from string representation
            // (single-line comments start with "//" and end on their line)
            var parsed =
                syntax.
                Parse
                (@"
                    ( let
                        (
                            ( id ( ( x ) => x ) )

                            ( factorial ( ( n ) => ( if ( > n 0 ) ( * n ( factorial ( - n 1 ) ) ) 1 ) ) )

                            ( f_o_g ( ( f g ) => ( ( x ) => ( f ( g x ) ) ) ) )

                            // See http://lambda-the-ultimate.org/node/5408
                            ( f ( ( x ) => ( ( g true ) , x ) ) )                 // ML-ish: f x = (g True, x)

                            ( g ( ( b ) =>
                                ( if b
                                    0                                             // ML-ish: g True = 0
                                    ( + ( first ( f ""a"" ) ) ( first ( f 0 ) ) ) // ML-ish: g False = fst (f 'a') + fst (f 0)
                                )
                            ) )

                            // See (page 3)
                            // [Fritz Henglein] http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.388.430&rep=rep1&type=pdf

                            ( fmap (
                                ( f l ) =>
                                ( if ( ! ( empty l ) )
                                    ( ( f ( head l ) ) : ( fmap f ( tail l ) ) )
                                    ( )
                                )
                            ) )

                            // See (page 3, examples ""Double"", ""Mycroft"", ""Sum List"", ""Composition""...)
                            // [Hallett & Kfoury] http://itrs04.di.unito.it/papers/hk.pdf

                            // Double
                            ( double ( ( f ) => ( ( x ) => ( f ( f x ) ) ) ) )
                            ( foo ( ( n ) => ( ( double ( ( num ) => ( + num 1 ) ) ) n ) ) )
                            ( bar ( ( s ) => ( ( double escape ) s ) ) )

                            // Mycroft
                            ( sqList ( ( l ) => ( fmap ( ( x ) => ( * ( + x 0 ) x ) ) l ) ) )
                            ( compList ( ( l ) => ( fmap ! l ) ) )

                            // Sum List
                            ( sumList ( ( l ) =>
                                ( if ( empty l )
                                    0
                                    ( + ( id ( head l ) ) ( sumList ( id ( tail l ) ) ) )
                                )
                            ) )

                            // Isomorphic Compositions
                            ( createList ( ( x ) => ( x : ( ) ) ) )
                            ( removeList ( ( l ) => ( head l ) ) )
                            ( comp ( ( f g ) => ( f_o_g f g ) ) )
                            ( appComp ( ( v1 v2 ) =>
                                ( ==
                                    ( ( comp removeList createList ) v1 )
                                    ( head ( ( comp createList removeList ) v2 ) )
                                )
                            ) )

                            ( threeValuesToAListOfTriples (
                                ( a b c ) => ( ( a , b , c ) : ( ) )
                            ) )
                            ( twoValuesToAPairOfLists (
                                ( a b ) => ( ( a : ( ) ) , ( b : ( ) ) )
                            ) )

                            // demonstrates type annotations
                            ( ( Pair ) ( a -> b -> ( ( a , b ) this ) ) ) // ( Pair a b ) just an alias for ( Tuple`2 a b )
                            
                            ( ( Atoi ) ( string -> int ) ) // string to integer converter signature

                            // should be inferred as,
                            // atoiTest : ( string -> int ) -> ( List string ) -> ( List ( string , int ) )
                            ( atoiTest (
                                (
                                    ( Atoi convert ) // (the converter)
                                    l // (some list)
                                )
                                => ( ( ( head l ) , ( convert ( head l ) ) ) : ( atoiTest convert ( tail l ) ) )
                            ) )

                            ( ( Triples ) ( x -> y -> z -> ( ( ( ( x , y , z ) triple ) : ( ) ) this ) ) )
                            ( Cloud ( ( v ) => ( Triples v v v ) ) )
                            ( number-cloud ( Cloud 0 ) )
                            ( string-cloud ( Cloud """" ) )

                            // advanced / more interesting:
                            // demonstrates generic type annotations
                            // mixed with constructor syntax ...
                            ( moreInteresting (
                                (
                                    // (`f' takes an `a' and returns a pair of `a' and `b')
                                    ( ( a -> ( ( a , b ) p ) ) f )
                                    l
                                ) =>
                                // `l' will be inferred to inhabit `( List a )' ...
                                // ... and as for the result of moreInteresting,
                                // to inhabit `( List b )'
                                ( ( second ( f ( head l ) ) ) : ( ) )
                            ) )

                            ( testOutput1 ( threeValuesToAListOfTriples 1 ""a"" true ) )
                            ( testOutput2 ( twoValuesToAPairOfLists 1 ""a"" ) )                            

                            // moreInteresting which will typecheck
                            ( testOutput3 (
                                moreInteresting
                                ( ( s ) => ( s , ( parseInt s ) ) ) // ... that's for the formal `f' (a lambda)
                                ( ""1"" : ( ""2"" : ( ) ) ) // ... that's for the formal `l'
                            ) )
                            // moreInteresting which cannot typecheck
                            ( testOutput3CannotTypecheck (
                                moreInteresting
                                ( ( s ) => ( s , ( parseInt s ) ) )
                                ( 1 : ( 2 : ( ) ) )
                            ) )
                        )

                        // report type inference results thru a fat tuple in let's body
                        //( uncomment whatever you're interested in )
                        (
                            ( id ( 0 , ""1"", true ) )
                            //, ( fmap ( f_o_g factorial parseInt ) ( ""0"" : ( ""1"" : ( ""2"" : ( ""3"" : ( ) ) ) ) ) )
                            //, ( first ( f true ) )
                            //, ( foo 123 )
                            //, ( bar ""z"" )
                            //, ( sqList ( 0 : ( 1 : ( 2 : ( 3 : ( ) ) ) ) ) )
                            //, ( compList ( true : ( false : ( ) ) ) )
                            //, ( sumList ( 1 : ( 2 : ( 3 : ( ) ) ) ) )
                            //, ( appComp 5 ( 5 : ( ) ) )
                            , testOutput1
                            , testOutput2
                            , testOutput3
                            , testOutput3CannotTypecheck
                        )
                    )
                ");

            var ast = visit(env, parsed);

            Console.WriteLine();
            Console.WriteLine("Abstract syntax:");
            foreach (var node in ast.Args)
            {
                Console.WriteLine();
                Console.WriteLine(node);
            }

            Console.WriteLine();
            Console.WriteLine("Inferred types:");

            // Visit the parsed S-expr, turn it into an AST for H-M type inference
            // (see Node, et al, above), infer some types from the latter,
            // and report
            analyze(ast);
        }
    }
}