-
Notifications
You must be signed in to change notification settings - Fork 0
/
CatFxnType.cs
667 lines (588 loc) · 21 KB
/
CatFxnType.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
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
namespace Cat
{
public class CatFxnType : CatTypeKind
{
#region fields
protected CatTypeVector mProd;
protected CatTypeVector mCons;
bool mbSideEffects;
CatFxnType mpParent;
CatTypeVarList mpFreeVars = new CatTypeVarList();
protected int mnId = gnId++;
#endregion
#region static functions
public static CatFxnType PushSomethingType = Create("( -> 'a)");
public static CatFxnType AnyFxnType = Create("('A -> 'B)");
public static CatFxnType PushAnythingType = Create("( -> 'A)");
public static CatFxnType Create(string sType)
{
if (sType.Length == 0)
return null;
Peg.Parser p = new Peg.Parser(sType);
try
{
if (!p.Parse(CatGrammar.FxnType()))
throw new Exception("no additional information");
}
catch (Exception e)
{
throw new Exception(sType + " is not a valid function type ", e);
}
Peg.PegAstNode ast = p.GetAst();
if (ast.GetNumChildren() != 1)
throw new Exception("invalid number of children in abstract syntax tree");
AstFxnType node = new AstFxnType(ast.GetChild(0));
CatFxnType ret = new CatFxnType(node);
return ret;
}
public static CatFxnType ComposeFxnTypes(CatFxnType f, CatFxnType g)
{
CatFxnType ft = CatTypeReconstructor.ComposeTypes(f, g);
return ft;
}
public static CatFxnType Unquote(CatFxnType ft)
{
if (ft == null)
return null;
if (ft.GetCons().GetKinds().Count > 0)
throw new Exception("Can't unquote a function type with a consumption size greater than zero");
if (ft.GetProd().GetKinds().Count != 1)
throw new Exception("Can't unquote a function type which does not produce a single function");
CatKind k = ft.GetProd().GetKinds()[0];
if (!(k is CatFxnType))
throw new Exception("Can't unquote a function type which does not produce a single function");
return k as CatFxnType;
}
#endregion
#region constructors
public CatFxnType(CatTypeVector cons, CatTypeVector prod, bool bSideEffects)
{
mCons = new CatTypeVector(cons);
mProd = new CatTypeVector(prod);
mbSideEffects = bSideEffects;
SetChildFxnParents();
ComputeFreeVars();
}
public CatFxnType()
{
mbSideEffects = false;
mCons = new CatTypeVector();
mProd = new CatTypeVector();
SetChildFxnParents();
ComputeFreeVars();
}
public CatFxnType(AstFxnType node)
{
mbSideEffects = node.HasSideEffects();
mCons = new CatTypeVector(node.mCons);
mProd = new CatTypeVector(node.mProd);
SetChildFxnParents();
ComputeFreeVars();
}
#endregion
#region variable functions
private CatTypeVector AddImplicitRhoVariables(CatTypeVector v)
{
CatTypeVector ret = new CatTypeVector();
foreach (CatKind k in v.GetKinds())
{
if (k is CatFxnType)
ret.Add((k as CatFxnType).AddImplicitRhoVariables());
else if (k is CatTypeVector)
ret.Add(AddImplicitRhoVariables(k as CatTypeVector));
else
ret.Add(k);
}
return ret;
}
public virtual CatFxnType AddImplicitRhoVariables()
{
CatTypeVector cons = AddImplicitRhoVariables(GetCons());
CatTypeVector prod = AddImplicitRhoVariables(GetProd());
if (!(cons.GetBottom() is CatStackVar))
{
CatStackVar rho = CatStackVar.CreateUnique();
cons.PushKindBottom(rho);
prod.PushKindBottom(rho);
}
return new CatFxnType(cons, prod, HasSideEffects());
}
public void RemoveImplicitRhoVariables()
{
// TEMP: TODO: figure out whether or not to remove this.
// RemoveImplicitRhoVariables(this);
}
/// <summary>
/// This function modifies the function
/// </summary>
public void RemoveImplicitRhoVariables(CatFxnType ft)
{
foreach (CatKind k in ft.GetChildKinds())
if (k is CatFxnType)
RemoveImplicitRhoVariables(k as CatFxnType);
if (!ft.GetCons().IsEmpty() && !ft.GetProd().IsEmpty())
{
CatKind k1 = ft.GetCons().GetBottom();
CatKind k2 = ft.GetProd().GetBottom();
// Does both consumption and production share the same
// stack variable at the bottom, if so, then we might have
// an implicit Rho variables
if (k1 is CatStackVar && k1.Equals(k2))
{
// try removing the stack variable
ft.GetCons().GetKinds().RemoveAt(0);
ft.GetProd().GetKinds().RemoveAt(0);
// is the variable used anywhere else?
// if so, then we have to restore it
// otherwise we leave it taken away
if (DoesVarExist(k1))
{
ft.GetCons().GetKinds().Insert(0, k1);
ft.GetProd().GetKinds().Insert(0, k2);
}
}
}
}
public bool DoesVarExist(CatKind k)
{
Trace.Assert(k.IsKindVar());
foreach (CatKind tmp in GetDescendantKinds())
if (tmp.Equals(k))
return true;
return false;
}
public CatTypeVarList GetAllVars()
{
CatTypeVarList ret = new CatTypeVarList();
GetAllVars(ret);
return ret;
}
private void GetAllVars(CatTypeVarList vars)
{
foreach (CatKind k in GetChildKinds())
{
if (k is CatFxnType)
{
(k as CatFxnType).GetAllVars(vars);
}
else if (k.IsKindVar())
{
vars.Add(k);
}
}
}
/* TODO: LOWPRI: remove
private CatTypeVarList GetVarsExcept(CatFxnType except)
{
CatTypeVarList ret = new CatTypeVarList();
GetVarsExcept(except, ret);
return ret;
}
private void GetVarsExcept(CatFxnType except, CatTypeVarList vars)
{
foreach (CatKind k in GetChildKinds())
{
if (k is CatFxnType)
{
CatFxnType ft = k as CatFxnType;
if (ft != except)
ft.GetVarsExcept(except, vars);
}
else
{
if (k.IsKindVar())
vars.Add(k);
}
}
}
*/
/// <summary>
/// Every kind variable has a scope in which it is free.
/// This allows us to compute whether a variable is free or bound.
/// The purpose of figuring whether a variable is free or bound, is so
/// that when we copy a function, we can make sure that any free variables
/// are given new unique names. Basically we want to make new names,
/// but we can't always do that.
/// </summary>
/// <param name="scopes"></param>
private void ComputeVarScopes(CatVarScopes scopes, Stack<CatFxnType> visited)
{
if (visited.Contains(this))
return;
foreach (CatKind k in GetChildKinds())
{
if (k.IsKindVar())
{
scopes.Add(k, this);
}
else if (k is CatFxnType)
{
CatFxnType ft = k as CatFxnType;
visited.Push(ft);
ft.ComputeVarScopes(scopes, visited);
visited.Pop();
}
}
}
private CatVarScopes ComputeVarScopes()
{
CatVarScopes scopes = new CatVarScopes();
ComputeVarScopes(scopes, new Stack<CatFxnType>());
return scopes;
}
private void ComputeFreeVars()
{
CatVarScopes scopes = ComputeVarScopes();
SetFreeVars(scopes, new Stack<CatFxnType>());
// TODO:
// Use the scopes to find out if a function type is well-formed or not.
// i.e. CheckIsWellFormed(scopes);
}
private bool IsFreeVar(CatKind k, CatVarScopes scopes)
{
return scopes.IsFreeVar(this, k);
}
private void SetFreeVars(CatVarScopes scopes, Stack<CatFxnType> visited)
{
if (visited.Contains(this))
return;
foreach (CatKind k in GetDescendantKinds())
{
// iterate over the values
if (IsFreeVar(k, scopes))
mpFreeVars.Add(k);
else if (k is CatFxnType)
{
visited.Push(this);
(k as CatFxnType).SetFreeVars(scopes, visited);
visited.Pop();
}
}
}
public bool IsFreeVar(CatKind var)
{
if (!var.IsKindVar())
return false;
return mpFreeVars.ContainsKey(var.ToString());
}
#endregion
#region production and consumption
public int GetMaxProduction()
{
int nCnt = 0;
List<CatKind> list = mProd.GetKinds();
for (int i = list.Count - 1; i >= 0; --i)
{
CatKind k = list[i];
if (k is CatStackVar)
{
if ((i == 0) && k.Equals(mCons.GetBottom()))
return nCnt;
else
return -1;
}
nCnt++;
}
return nCnt;
}
public int GetMaxConsumption()
{
int nCnt = 0;
List<CatKind> list = mCons.GetKinds();
for (int i = list.Count - 1; i >= 0; --i)
{
CatKind k = list[i];
if (k is CatStackVar)
{
if ((i == 0) && k.Equals(mProd.GetBottom()))
return nCnt;
else
return -1;
}
nCnt++;
}
return nCnt;
}
public CatTypeVector GetProd()
{
return mProd;
}
public CatTypeVector GetCons()
{
return mCons;
}
#endregion
#region string formatting
public override string ToString()
{
if (mbSideEffects)
return "(" + GetCons().ToString() + " ~> " + GetProd().ToString() + ")"; else
return "(" + GetCons().ToString() + " -> " + GetProd().ToString() + ")";
}
public override string ToIdString()
{
string ret = "";
if (mbSideEffects)
ret = "(" + GetCons().ToIdString() + " ~> " + GetProd().ToIdString() + ")"; else
ret = "(" + GetCons().ToIdString() + " -> " + GetProd().ToIdString() + ")";
ret += "_" + mnId.ToString();
return ret;
}
public static string IntToPrettyString(int n)
{
string s = "";
if (n > 26)
s += IntToPrettyString(n / 26);
char c = 'a';
c += (char)(n % 26);
s += c.ToString();
return "'" + s;
}
public static string ToPrettyString(CatTypeVector vec, Dictionary<string, string> dic)
{
string s = "";
for (int i=0; i < vec.GetKinds().Count; ++i)
{
if (i > 0) s += " ";
CatKind k = vec.GetKinds()[i];
if (k.IsKindVar())
{
if (!dic.ContainsKey(k.ToString()))
{
string sNew = IntToPrettyString(dic.Count);
if (k is CatStackVar)
sNew = sNew.ToUpper();
dic.Add(k.ToString(), sNew);
}
s += dic[k.ToString()];
}
else if (k is CatFxnType)
{
s += "(" + ToPrettyString(k as CatFxnType, dic) + ")";
}
else if (k is CatTypeVector)
{
s += ToPrettyString(k as CatFxnType, dic);
}
else
{
s += k.ToString();
}
}
return s;
}
public virtual string ToPrettyString()
{
return "(" + ToPrettyString(this, new Dictionary<string, string>()) + ")";
}
public static string ToPrettyString(CatFxnType ft, Dictionary<string, string> dic)
{
// remove rho variables
ft = ft.Clone();
ft.RemoveImplicitRhoVariables();
string s = ToPrettyString(ft.GetCons(), dic);
if (ft.HasSideEffects())
s += " ~> ";
else
s += " -> ";
s += ToPrettyString(ft.GetProd(), dic);
return s;
}
#endregion
#region comparison functions
/// <summary>
/// This is a raw equivalency check: no normalization is done.
/// To comparse function type normally you would use CompareFxnTypes,
/// which in turn calls this function.
/// </summary>
public override bool Equals(CatKind k)
{
if (!(k is CatFxnType)) return false;
CatFxnType f = k as CatFxnType;
return (GetCons().Equals(f.GetCons()) && GetProd().Equals(f.GetProd())
&& HasSideEffects() == f.HasSideEffects());
}
public override bool IsSubtypeOf(CatKind k)
{
if (k.IsAny() || k.IsDynFxn())
return IsRuntimePolymorphic();
if (k is CatTypeVar)
return true;
if (!(k is CatFxnType))
return false;
CatFxnType f = k as CatFxnType;
bool ret = GetCons().IsSubtypeOf(f.GetCons()) && GetProd().IsSubtypeOf(f.GetProd());
if (HasSideEffects())
ret = ret && f.HasSideEffects();
return ret;
}
/// <summary>
/// Compares two function types, by first normalizing so that they each have
/// names of variables that correspond to the locations in the function
/// </summary>
public static bool CompareFxnTypes(CatFxnType f, CatFxnType g)
{
CatFxnType f2 = CatVarRenamer.RenameVars(f.AddImplicitRhoVariables());
CatFxnType g2 = CatVarRenamer.RenameVars(g.AddImplicitRhoVariables());
return f2.IsSubtypeOf(g2);
}
#endregion
#region verifications
public bool IsValidChildFxn(List<string> varNames, CatFxnType ft)
{
foreach (CatKind k in ft.GetCons().GetKinds())
{
if (k.IsKindVar())
varNames.Add(k.ToString());
}
return IsValidProduction(varNames, ft.GetProd());
}
public void GetConsVarNames(List<string> varNames, CatFxnType ft)
{
foreach (CatKind k in ft.GetCons().GetKinds())
{
if (k.IsKindVar())
varNames.Add(k.ToString());
if (k is CatFxnType)
GetConsVarNames(varNames, k as CatFxnType);
}
}
public bool IsValidProduction(List<string> varNames, CatTypeVector prod)
{
foreach (CatKind k in prod.GetKinds())
if (k is CatFxnType)
GetConsVarNames(varNames, k as CatFxnType);
foreach (CatKind k in prod.GetKinds())
if (k.IsKindVar())
if (!varNames.Contains(k.ToString()))
return false;
return true;
}
public bool IsValid()
{
// TODO : rewrite this function
return true;
/*
// TODO: check that if pure, none of the child functions are impure.
if (!GetCons().IsValid())
return false;
if (!GetProd().IsValid())
return false;
List<string> varNames = new List<string>();
foreach (CatKind k in GetCons().GetDescendantKinds())
{
if (k.IsKindVar())
{
string s = k.ToString();
if (!varNames.Contains(s))
varNames.Add(s);
}
}
if (!IsValidProduction(varNames, GetProd()))
return false;
return true;
*/
}
#endregion
#region utility functions
public CatFxnType Clone()
{
return new CatFxnType(mCons, mProd, mbSideEffects);
}
public bool HasSideEffects()
{
return mbSideEffects;
}
/// <summary>
/// Returns true if this function can be converted to either "any" or a "fxn".
/// </summary>
public bool IsRuntimePolymorphic()
{
return (GetCons().GetKinds().Count == 1) && (GetProd().GetKinds().Count == 1);
}
#endregion
#region parent / child functions
public CatFxnType GetParent()
{
return mpParent;
}
public CatFxnType GetAncestor()
{
if (mpParent == null)
return this;
return mpParent.GetAncestor();
}
public bool DescendentOf(CatFxnType ft)
{
if (this == ft)
return true;
if (mpParent == null)
return false;
return mpParent.DescendentOf(ft);
}
public void SetParent(CatFxnType parent)
{
mpParent = parent;
}
private void SetChildFxnParents()
{
foreach (CatKind k in GetChildKinds())
{
if (k is CatFxnType)
{
CatFxnType ft = k as CatFxnType;
ft.SetChildFxnParents();
ft.SetParent(this);
}
}
}
public override IEnumerable<CatKind> GetChildKinds()
{
foreach (CatKind k in mCons.GetChildKinds())
yield return k;
foreach (CatKind k in mProd.GetChildKinds())
yield return k;
}
public override IEnumerable<CatKind> GetDescendantKinds()
{
foreach (CatKind k in mCons.GetDescendantKinds())
yield return k;
foreach (CatKind k in mProd.GetDescendantKinds())
yield return k;
}
#endregion
}
public class CatQuotedType : CatFxnType
{
public CatQuotedType(CatKind k)
{
GetProd().Add(k);
}
}
public class CatRecursiveType : CatKind
{
public CatRecursiveType()
{
}
public override string ToString()
{
return "self";
}
public override bool Equals(CatKind k)
{
return k is CatRecursiveType;
}
public override IEnumerable<CatKind> GetChildKinds()
{
return new List<CatKind>();
}
public override IEnumerable<CatKind> GetDescendantKinds()
{
return new List<CatKind>();
}
}
}