-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCatParser.cs
875 lines (761 loc) · 24.6 KB
/
CatParser.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
/// Dedicated to the public domain by Christopher Diggins
/// http://creativecommons.org/licenses/publicdomain/
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Globalization;
using System.Diagnostics;
using Peg;
namespace Cat
{
/// <summary>
/// The CatParser constructs a typed AST representing Cat source code.
/// This library is based on the PEG parsing library
/// </summary>
class CatParser
{
public static List<CatAstNode> Parse(string s)
{
Peg.Parser parser = new Peg.Parser(s);
try
{
bool bResult = parser.Parse(CatGrammar.CatProgram());
if (!bResult)
throw new Exception("failed to parse input");
}
catch (Exception e)
{
Output.WriteLine("Parsing error occured with message: " + e.Message);
Output.WriteLine(parser.ParserPosition);
throw e;
}
AstProgram tmp = new AstProgram(parser.GetAst());
return tmp.mStatements;
}
}
/// <summary>
/// Used to identify / switch on the different types of nodes
/// </summary>
public enum AstLabel
{
AstRoot,
Def,
Decl,
Name,
Param,
Lambda,
Quote,
Char,
String,
Float,
Int,
Bin,
Hex,
Stack,
FxnType,
Arrow,
TypeName,
TypeVar,
StackVar,
MacroRule,
MacroProp,
MacroPattern,
MacroQuote,
MacroTypeVar,
MacroStackVar,
MacroTypeVarName,
MacroStackVarName,
MacroName,
MetaDataContent,
MetaDataLabel,
MetaDataBlock,
Unknown
}
/// <summary>
/// An AstNode is used as a base class for a typed abstract syntax tree for Cat programs.
/// CatAstNodes are created from a Peg.Ast. Apart from being typed, the big difference
/// is the a CatAstNode can be modified. This makes rewriting algorithms much easier.
/// </summary>
public abstract class CatAstNode
{
string msText;
AstLabel mLabel;
public CatAstNode(PegAstNode node)
{
if (node.GetLabel() != null)
mLabel = (AstLabel)node.GetLabel();
else
mLabel = AstLabel.AstRoot;
msText = node.ToString();
}
public CatAstNode(AstLabel label, string sText)
{
mLabel = label;
msText = sText;
}
public static CatAstNode Create(PegAstNode node)
{
AstLabel label = (AstLabel)node.GetLabel();
switch (label)
{
case AstLabel.AstRoot:
return new AstRoot(node);
case AstLabel.Def:
return new AstDef(node);
case AstLabel.Name:
return new AstName(node);
case AstLabel.Param:
return new AstParam(node);
case AstLabel.Lambda:
return new AstLambda(node);
case AstLabel.Quote:
return new AstQuote(node);
case AstLabel.Char:
return new AstChar(node);
case AstLabel.String:
return new AstString(node);
case AstLabel.Float:
return new AstFloat(node);
case AstLabel.Int:
return new AstInt(node);
case AstLabel.Bin:
return new AstBin(node);
case AstLabel.Hex:
return new AstHex(node);
case AstLabel.Stack:
return new AstStack(node);
case AstLabel.FxnType:
return new AstFxnType(node);
case AstLabel.TypeVar:
return new AstTypeVar(node);
case AstLabel.TypeName:
return new AstSimpleType(node);
case AstLabel.StackVar:
return new AstStackVar(node);
case AstLabel.MacroRule:
return new AstMacro(node);
case AstLabel.MacroProp:
return new AstMacro(node);
case AstLabel.MacroPattern:
return new AstMacroPattern(node);
case AstLabel.MacroQuote:
return new AstMacroQuote(node);
case AstLabel.MacroTypeVar:
return new AstMacroTypeVar(node);
case AstLabel.MacroStackVar:
return new AstMacroStackVar(node);
case AstLabel.MacroName:
return new AstMacroName(node);
case AstLabel.MetaDataContent:
return new AstMetaDataContent(node);
case AstLabel.MetaDataLabel:
return new AstMetaDataLabel(node);
case AstLabel.MetaDataBlock:
return new AstMetaDataBlock(node);
default:
throw new Exception("unrecognized node type in AST tree: " + label);
}
}
public void CheckIsLeaf(PegAstNode node)
{
CheckChildCount(node, 0);
}
public void CheckLabel(AstLabel label)
{
if (!GetLabel().Equals(label))
throw new Exception("Expected label " + label.ToString() + " but instead have label " + GetLabel().ToString());
}
public void CheckChildCount(PegAstNode node, int n)
{
if (node.GetNumChildren() != n)
throw new Exception("expected " + n.ToString() + " children, instead found " + node.GetNumChildren().ToString());
}
public AstLabel GetLabel()
{
return mLabel;
}
public override string ToString()
{
return msText;
}
public void SetText(string s)
{
msText = s;
}
public string IndentedString(int nIndent, string s)
{
if (nIndent > 0)
return new String('\t', nIndent) + s; else
return s;
}
public virtual void Output(TextWriter writer, int nIndent)
{
writer.Write(ToString());
}
}
public class AstRoot : CatAstNode
{
public List<AstDef> Defs = new List<AstDef>();
public AstRoot(PegAstNode node)
: base(node)
{
foreach (PegAstNode child in node.GetChildren())
Defs.Add(new AstDef(child));
}
public override void Output(TextWriter writer, int nIndent)
{
foreach (AstDef d in Defs)
d.Output(writer, nIndent);
}
}
public class AstExpr : CatAstNode
{
public AstExpr(PegAstNode node) : base(node) { }
public AstExpr(AstLabel label, string sText) : base(label, sText) { }
public override void Output(TextWriter writer, int nIndent)
{
string sLine = ToString();
writer.WriteLine(IndentedString(nIndent, sLine));
}
}
public class AstDef : CatAstNode
{
public string mName;
public AstFxnType mType;
public AstMetaDataBlock mpMetaData;
public List<AstParam> mParams = new List<AstParam>();
public List<CatAstNode> mTerms = new List<CatAstNode>();
public List<AstDef> mLocals = new List<AstDef>();
public AstDef(PegAstNode node)
: base(node)
{
CheckLabel(AstLabel.Def);
if (node.GetNumChildren() == 0)
throw new Exception("invalid function definition node");
AstName name = new AstName(node.GetChild(0));
mName = name.ToString();
int n = 1;
// Look to see if a type is defined
if ((node.GetNumChildren() >= 2) && (node.GetChild(1).GetLabel().Equals(AstLabel.FxnType)))
{
mType = new AstFxnType(node.GetChild(1));
++n;
}
while (n < node.GetNumChildren())
{
PegAstNode child = node.GetChild(n);
if (!child.GetLabel().Equals(AstLabel.Param))
break;
mParams.Add(new AstParam(child));
n++;
}
while (n < node.GetNumChildren())
{
PegAstNode child = node.GetChild(n);
if (!child.GetLabel().Equals(AstLabel.Param))
break;
mParams.Add(new AstParam(child));
n++;
}
while (n < node.GetNumChildren())
{
PegAstNode child = node.GetChild(n);
if (!child.GetLabel().Equals(AstLabel.MetaDataBlock))
break;
mpMetaData = new AstMetaDataBlock(child);
n++;
}
while (n < node.GetNumChildren())
{
PegAstNode child = node.GetChild(n);
if (!child.GetLabel().Equals(AstLabel.Def))
break;
mLocals.Add(new AstDef(child));
n++;
}
while (n < node.GetNumChildren())
{
PegAstNode child = node.GetChild(n);
CatAstNode expr = Create(child);
if (!(expr is AstExpr))
throw new Exception("expected expression node");
mTerms.Add(expr as AstExpr);
n++;
}
}
public override void Output(TextWriter writer, int nIndent)
{
string s = "define " + mName;
if (mType != null)
{
s += " : " + mType.ToString();
}
if (mParams.Count > 0)
{
s += " // ( ";
foreach (AstParam p in mParams)
s += p.ToString() + " ";
s += ")";
}
writer.WriteLine(IndentedString(nIndent, s));
writer.WriteLine(IndentedString(nIndent, "{"));
foreach (AstExpr x in mTerms)
x.Output(writer, nIndent + 1);
writer.WriteLine(IndentedString(nIndent, "}"));
}
}
public class AstName : AstExpr
{
public AstName(PegAstNode node)
: base(node)
{
CheckLabel(AstLabel.Name);
CheckIsLeaf(node);
}
public AstName(string sOp)
: base(AstLabel.Name, sOp)
{
}
}
public class AstParam : CatAstNode
{
public AstParam(PegAstNode node)
: base(node)
{
CheckLabel(AstLabel.Param);
CheckIsLeaf(node);
}
public override void Output(TextWriter writer, int nIndent)
{
throw new Exception("The method or operation is not implemented.");
}
}
public class AstLiteral : AstExpr
{
public AstLiteral(PegAstNode node)
: base(node)
{ }
public AstLiteral(AstLabel label, string sText)
: base(label, sText)
{ }
public Object value;
}
public class AstLambda : AstLiteral
{
public List<string> mIdentifiers = new List<string>();
public List<CatAstNode> mTerms = new List<CatAstNode>();
public AstLambda(PegAstNode node)
: base(node)
{
CheckLabel(AstLabel.Lambda);
CheckChildCount(node, 2);
AstParam name = new AstParam(node.GetChild(0));
mIdentifiers.Add(name.ToString());
CatAstNode tmp = Create(node.GetChild(1));
// lambda nodes either contain quotes or other lambda nodes
if (!(tmp is AstQuote))
{
if (!(tmp is AstLambda))
throw new Exception("expected lambda expression or quotation");
AstLambda lambda = tmp as AstLambda;
mIdentifiers.AddRange(lambda.mIdentifiers);
// Take ownership of the terms from the child lambda expression
mTerms = lambda.mTerms;
}
else
{
AstQuote q = tmp as AstQuote;
// Take ownership of the terms from the quote
mTerms = q.mTerms;
}
}
public List<CatAstNode> GetTerms()
{
return mTerms;
}
}
public class AstQuote : AstLiteral
{
public List<CatAstNode> mTerms = new List<CatAstNode>();
public AstQuote(PegAstNode node)
: base(node)
{
CheckLabel(AstLabel.Quote);
foreach (PegAstNode child in node.GetChildren())
{
CatAstNode tmp = CatAstNode.Create(child);
if (!(tmp is AstExpr))
throw new Exception("invalid child node " + child.ToString() + ", expected an expression node");
mTerms.Add(tmp as AstExpr);
}
}
public AstQuote(AstExpr expr)
: base(AstLabel.Quote, "")
{
mTerms.Add(expr);
}
public AstQuote(List<CatAstNode> expr)
: base(AstLabel.Quote, "")
{
mTerms.AddRange(expr);
}
public override void Output(TextWriter writer, int nIndent)
{
writer.WriteLine(IndentedString(nIndent, "["));
foreach (AstExpr x in mTerms)
x.Output(writer, nIndent + 1);
writer.WriteLine(IndentedString(nIndent, "]"));
}
public List<CatAstNode> GetTerms()
{
return mTerms;
}
}
public class AstInt : AstLiteral
{
public AstInt(PegAstNode node)
: base(node)
{
CheckLabel(AstLabel.Int);
CheckIsLeaf(node);
value = int.Parse(ToString());
}
public AstInt(int n)
: base(AstLabel.Int, n.ToString())
{
value = n;
}
public int GetValue()
{
return (int)value;
}
}
public class AstBin : AstLiteral
{
public AstBin(PegAstNode node)
: base(node)
{
CheckLabel(AstLabel.Bin);
CheckIsLeaf(node);
string s = ToString();
int n = 0;
int place = 1;
for (int i = s.Length; i > 0; --i)
{
if (s[i - 1] == '1')
{
n += place;
}
else
{
if (s[i - 1] != '0')
throw new Exception("Invalid binary number");
}
place *= 2;
}
value = n;
}
public int GetValue()
{
return (int)value;
}
}
public class AstHex : AstLiteral
{
public AstHex(PegAstNode node)
: base(node)
{
CheckLabel(AstLabel.Hex);
CheckIsLeaf(node);
value = int.Parse(ToString(), NumberStyles.AllowHexSpecifier);
}
public int GetValue()
{
return (int)value;
}
}
public class AstChar : AstLiteral
{
public AstChar(PegAstNode node)
: base(node)
{
CheckLabel(AstLabel.Char);
CheckIsLeaf(node);
string s = ToString();
s = s.Substring(1, s.Length - 2);
switch (s)
{
case "\\t": value = '\t'; break;
case "\\n": value = '\n'; break;
case "\\'": value = '\''; break;
case "\\\"": value = '\"'; break;
case "\\r": value = '\r'; break;
default: value = char.Parse(s); break;
}
}
public char GetValue()
{
return (char)value;
}
}
public class AstString : AstLiteral
{
public AstString(PegAstNode node)
: base(node)
{
CheckLabel(AstLabel.String);
CheckIsLeaf(node);
// strip quotes
string s = ToString();
value = s.Substring(1, s.Length - 2);
}
public string GetValue()
{
return (string)value;
}
}
public class AstFloat : AstLiteral
{
public AstFloat(PegAstNode node)
: base(node)
{
CheckLabel(AstLabel.Float);
CheckIsLeaf(node);
value = double.Parse(ToString());
}
public double GetValue()
{
return (double)value;
}
}
public class AstType : CatAstNode
{
public AstType(PegAstNode node)
: base(node)
{
}
}
public class AstStack : CatAstNode
{
public List<AstType> mTypes = new List<AstType>();
public AstStack(PegAstNode node)
: base(node)
{
CheckLabel(AstLabel.Stack);
foreach (PegAstNode child in node.GetChildren())
{
CatAstNode tmp = Create(child);
if (!(tmp is AstType))
throw new Exception("stack AST node should only have type AST nodes as children");
mTypes.Add(tmp as AstType);
}
}
}
public class AstTypeVar : AstType
{
public AstTypeVar(PegAstNode node)
: base(node)
{
CheckLabel(AstLabel.TypeVar);
CheckChildCount(node, 0);
}
}
public class AstSimpleType : AstType
{
public AstSimpleType(PegAstNode node)
: base(node)
{
CheckLabel(AstLabel.TypeName);
CheckChildCount(node, 0);
}
}
public class AstStackVar : AstType
{
public AstStackVar(PegAstNode node)
: base(node)
{
CheckLabel(AstLabel.StackVar);
CheckChildCount(node, 0);
}
}
public class AstFxnType : AstType
{
public AstStack mProd;
public AstStack mCons;
bool mbSideEffects;
public AstFxnType(PegAstNode node)
: base(node)
{
CheckLabel(AstLabel.FxnType);
CheckChildCount(node, 3);
mCons = new AstStack(node.GetChild(0));
mbSideEffects = node.GetChild(1).ToString().Equals("~>");
mProd = new AstStack(node.GetChild(2));
}
public bool HasSideEffects()
{
return mbSideEffects;
}
}
public class AstMacro : CatAstNode
{
public AstMacroPattern mSrc;
public AstMacroPattern mDest;
public AstMacro(PegAstNode node)
: base(node)
{
CheckChildCount(node, 2);
CheckLabel(AstLabel.MacroRule);
mSrc = new AstMacroPattern(node.GetChild(0));
mDest = new AstMacroPattern(node.GetChild(1));
}
}
public class AstMacroProperty : AstMacro
{
public AstMacroProperty(PegAstNode node)
: base(node)
{
}
}
public class AstMacroPattern : CatAstNode
{
public List<AstMacroTerm> mPattern = new List<AstMacroTerm>();
public AstMacroPattern(PegAstNode node)
: base(node)
{
CheckLabel(AstLabel.MacroPattern);
foreach (PegAstNode child in node.GetChildren())
{
AstMacroTerm tmp = CatAstNode.Create(child) as AstMacroTerm;
if (tmp == null)
throw new Exception("invalid grammar: only macro terms can be children of an ast macro mPattern");
mPattern.Add(tmp);
}
}
}
public class AstMacroTerm : CatAstNode
{
public AstMacroTerm(PegAstNode node)
: base(node)
{
}
}
public class AstMacroQuote : AstMacroTerm
{
public List<AstMacroTerm> mTerms = new List<AstMacroTerm>();
public AstMacroQuote(PegAstNode node)
: base(node)
{
CheckLabel(AstLabel.MacroQuote);
foreach (PegAstNode child in node.GetChildren())
{
AstMacroTerm term = Create(child) as AstMacroTerm;
if (term == null)
throw new Exception("internal grammar error: macro quotations can only contain macro terms");
mTerms.Add(term);
}
}
}
public class AstMacroTypeVar : AstMacroTerm
{
public string msName;
public AstMacroTypeVar(PegAstNode node)
: base(node)
{
CheckChildCount(node, 1);
msName = node.GetChild(0).ToString();
CheckLabel(AstLabel.MacroTypeVar);
}
}
public class AstMacroStackVar : AstMacroTerm
{
public CatFxnType mType = null;
public string msName;
public AstMacroStackVar(PegAstNode node)
: base(node)
{
if (node.GetNumChildren() < 1)
throw new Exception("invalid macro stack variable");
if (node.GetNumChildren() > 2)
throw new Exception("invalid macro stack variable");
msName = node.GetChild(0).ToString();
if (node.GetNumChildren() == 2)
{
AstFxnType typeNode = new AstFxnType(node.GetChild(1));
mType = CatFxnType.Create(typeNode) as CatFxnType;
if (mType == null) throw new Exception("expected function type " + typeNode.ToString());
}
CheckLabel(AstLabel.MacroStackVar);
}
}
public class AstMacroName : AstMacroTerm
{
public AstMacroName(PegAstNode node)
: base(node)
{
CheckChildCount(node, 0);
CheckLabel(AstLabel.MacroName);
}
}
#region AST nodes for representing meta data
public class AstMetaData : CatAstNode
{
public List<AstMetaData> children = new List<AstMetaData>();
public AstMetaData(PegAstNode node)
: base(node)
{
foreach (PegAstNode child in node.GetChildren())
{
AstMetaData x = Create(child) as AstMetaData;
if (x == null)
throw new Exception("Meta data-nodes can only have meta-data nodes as children");
children.Add(x);
}
}
}
public class AstMetaDataContent : AstMetaData
{
public AstMetaDataContent(PegAstNode node)
: base(node)
{
CheckLabel(AstLabel.MetaDataContent);
}
}
public class AstMetaDataLabel : AstMetaData
{
public AstMetaDataLabel(PegAstNode node)
: base(node)
{
CheckLabel(AstLabel.MetaDataLabel);
CheckIsLeaf(node);
Trace.Assert(children.Count == 0);
}
}
public class AstMetaDataBlock : AstMetaData
{
public AstMetaDataBlock(PegAstNode node)
: base(node)
{
CheckLabel(AstLabel.MetaDataBlock);
}
}
/// <summary>
/// A program consists of a sequence of statements
/// TODO: reintroduce declarations and macros
/// </summary>
public class AstProgram : CatAstNode
{
public List<CatAstNode> mStatements = new List<CatAstNode>();
public AstProgram(Peg.PegAstNode node)
: base(node)
{
foreach (Peg.PegAstNode child in node.GetChildren())
{
CatAstNode statement = CatAstNode.Create(child);
mStatements.Add(statement);
}
}
}
#endregion
}