-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathtypes.cpp
1465 lines (1256 loc) · 44.6 KB
/
types.cpp
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
// ****************************************************************************
// types.cpp ELFE project
// ****************************************************************************
//
// File Description:
//
// The type system in ELFE
//
//
//
//
//
//
//
//
// ****************************************************************************
// This document is released under the GNU General Public License, with the
// following clarification and exception.
//
// Linking this library statically or dynamically with other modules is making
// a combined work based on this library. Thus, the terms and conditions of the
// GNU General Public License cover the whole combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent modules,
// and to copy and distribute the resulting executable under terms of your
// choice, provided that you also meet, for each linked independent module,
// the terms and conditions of the license of that module. An independent
// module is a module which is not derived from or based on this library.
// If you modify this library, you may extend this exception to your version
// of the library, but you are not obliged to do so. If you do not wish to
// do so, delete this exception statement from your version.
//
// See http://www.gnu.org/copyleft/gpl.html and Matthew 25:22 for details
// (C) 1992-2010 Christophe de Dinechin <[email protected]>
// (C) 2010 Taodyne SAS
// ****************************************************************************
#include "types.h"
#include "tree.h"
#include "runtime.h"
#include "errors.h"
#include "options.h"
#include "save.h"
#include "args.h"
#include "cdecls.h"
#include "renderer.h"
#include "basics.h"
#include <iostream>
ELFE_BEGIN
// ============================================================================
//
// Type allocation and unification algorithms (hacked Damas-Hilney-Milner)
//
// ============================================================================
ulong Types::id = 0;
Types::Types(Context *context)
// ----------------------------------------------------------------------------
// Constructor for top-level type inferences
// ----------------------------------------------------------------------------
: context(context),
types(),
unifications(),
rcalls(),
left(NULL), right(NULL),
prototyping(false), matching(false)
{}
Types::Types(Context *context, Types *parent)
// ----------------------------------------------------------------------------
// Constructor for "child" type inferences, i.e. done within a parent
// ----------------------------------------------------------------------------
: context(context),
types(parent->types),
unifications(parent->unifications),
rcalls(parent->rcalls),
left(parent->left), right(parent->right),
prototyping(false), matching(false)
{}
Types::~Types()
// ----------------------------------------------------------------------------
// Destructor - Nothing to explicitly delete, but useful for debugging
// ----------------------------------------------------------------------------
{}
bool Types::TypeCheck(Tree *program)
// ----------------------------------------------------------------------------
// Perform all the steps of type inference on the given program
// ----------------------------------------------------------------------------
{
// Once this is done, record all type information for the program
bool result = program->Do(this);
// Dump debug information if approriate
IFTRACE(typecheck)
{
std::cout << "TYPE CHECK FOR " << ShortTreeForm(program) << "\n";
std::cout << "TYPES:\n"; debugt(this);
std::cout << "UNIFICATIONS:\n"; debugu(this);
}
IFTRACE(types)
{
std::cout << "CALLS FOR " << ShortTreeForm(program) << ":\n";
debugr(this);
}
return result;
}
Tree *Types::Type(Tree *expr)
// ----------------------------------------------------------------------------
// Return the base type associated with a given expression
// ----------------------------------------------------------------------------
{
Tree *type = types[expr];
if (!type)
{
if (expr->Kind() == NAME)
{
if (expr == elfe_true || expr == elfe_false)
AssignType(expr, boolean_type);
else
AssignType(expr);
}
else if (!expr->Do(this))
{
Ooops("Unable to assign type to $1", expr);
if (!types[expr])
AssignType(expr);
}
type = types[expr];
}
return Base(type);
}
bool Types::DoInteger(Integer *what)
// ----------------------------------------------------------------------------
// Annotate an integer tree with its value
// ----------------------------------------------------------------------------
{
return DoConstant(what);
}
bool Types::DoReal(Real *what)
// ----------------------------------------------------------------------------
// Annotate a real tree with its value
// ----------------------------------------------------------------------------
{
return DoConstant(what);
}
bool Types::DoText(Text *what)
// ----------------------------------------------------------------------------
// Annotate a text tree with its own value
// ----------------------------------------------------------------------------
{
return DoConstant(what);
}
bool Types::DoConstant(Tree *what)
// ----------------------------------------------------------------------------
// All constants have themselves as type, and evaluate normally
// ----------------------------------------------------------------------------
{
Tree *canon = CanonicalType(what);
bool result = AssignType(what, canon);
result = Evaluate(what);
return result;
}
bool Types::DoName(Name *what)
// ----------------------------------------------------------------------------
// Assign an unknown type to a name
// ----------------------------------------------------------------------------
{
if (!AssignType(what))
return false;
return Evaluate(what);
}
bool Types::DoPrefix(Prefix *what)
// ----------------------------------------------------------------------------
// Assign an unknown type to a prefix and then to its children
// ----------------------------------------------------------------------------
{
if (!AssignType(what))
return false;
// Skip bizarre declarations
if (Name *name = what->left->AsName())
{
if (name->value == "data")
return AssignType(what, declaration_type) && Data(what->right);
else if (name->value == "extern")
return AssignType(what, declaration_type) && Extern(what->right);
}
// What really matters is if we can evaluate the top-level expression
return Evaluate(what);
}
bool Types::DoPostfix(Postfix *what)
// ----------------------------------------------------------------------------
// Assign an unknown type to a postfix and then to its children
// ----------------------------------------------------------------------------
{
if (!AssignType(what))
return false;
// What really matters is if we can evaluate the top-level expression
return Evaluate(what);
}
bool Types::DoInfix(Infix *what)
// ----------------------------------------------------------------------------
// Special treatment for the special infix forms
// ----------------------------------------------------------------------------
{
// For a sequence, both sub-expressions must succeed individually.
// The type of the sequence is the type of the last statement
if (what->name == "\n" || what->name == ";")
{
// Assign types to left and right
if (!AssignType(what))
return false;
return Statements(what, what->left, what->right);
}
// Case of 'X : T' : Set type of X to T and unify X:T with X
if (what->name == ":" || what->name == "as")
return (AssignType(what->left, what->right) &&
what->left->Do(this) &&
AssignType(what) &&
UnifyExpressionTypes(what, what->left));
// Case of 'X -> Y': Analyze type of X and Y, unify them, set type of result
if (what->name == "->")
return Rewrite(what);
// For other cases, we assign types to left and right
if (!AssignType(what))
return false;
// Success depends on successful evaluation of the complete form
return Evaluate(what);
}
bool Types::DoBlock(Block *what)
// ----------------------------------------------------------------------------
// A block has the same type as its children, except if child alone fails
// ----------------------------------------------------------------------------
{
// Assign a type to the block
if (!AssignType(what))
return false;
// If child succeeds, the block and its child have the same type
if (what->child->Do(this))
return UnifyExpressionTypes(what, what->child);
// Otherwise, try to find a matching form
return Evaluate(what);
}
bool Types::AssignType(Tree *expr, Tree *type)
// ----------------------------------------------------------------------------
// Assign a type to a given tree
// ----------------------------------------------------------------------------
{
// Check if we already have a type
if (Tree *existing = types[expr])
{
// If no type given, that's it
if (!type || existing == type)
return true;
// We have two types specified for that entity, need to unify
return Unify(existing, type, expr, expr);
}
// Generate a unique type name if nothing is given
if (type == NULL)
{
if (expr == elfe_true || expr == elfe_false)
type = boolean_type;
else
type = NewTypeName(expr->Position());
}
// Record the type for that tree
types[expr] = type;
// Success
return true;
}
bool Types::Rewrite(Infix *what)
// ----------------------------------------------------------------------------
// Assign a type to a rewrite
// ----------------------------------------------------------------------------
{
// Create a context for the rewrite parameters
Context *childContext = new Context(context);
Save<Context_p> saveContext(context, childContext);
// Assign types on the left of the rewrite
Save<bool> proto(prototyping, true);
if (!what->left->Do(this))
{
Ooops("Malformed rewrite pattern $1", what->left);
return false;
}
// The rewrite itself is an infix (in case we have to manage it)
Tree *formType = Type(what->left);
Tree *valueType = Type(what->right);
if (!AssignType(what, declaration_type))
return false;
// We need to be able to unify pattern and definition types
if (!Unify(valueType, formType, what->right, what->left))
return false;
// The type of the definition is a pattern type, perform unification
if (Infix *infix = what->left->AsInfix())
{
if (infix->name == ":" || what->name == "as")
{
// Explicit type declaration
if (!Unify(valueType, infix->right, what->right, infix->right))
return false;
}
}
// Well done, success!
return true;
}
bool Types::Data(Tree *what)
// ----------------------------------------------------------------------------
// Use the structure type associated to the data form
// ----------------------------------------------------------------------------
{
return AssignType(what, CanonicalType(what));
}
bool Types::Extern(Tree *what)
// ----------------------------------------------------------------------------
// Recover the transformed rewrite and enter that
// ----------------------------------------------------------------------------
{
CDeclaration *cdecl = what->GetInfo<CDeclaration>();
if (!cdecl)
return false;
return Rewrite(cdecl->rewrite);
}
bool Types::Statements(Tree *expr, Tree *left, Tree *right)
// ----------------------------------------------------------------------------
// Return the type of a combo statement, skipping declarations
// ----------------------------------------------------------------------------
{
if (!left->Do(this))
return false;
if (!right->Do(this))
return false;
// Check if right term is a declaration, otherwise return that
Tree *t2 = Type(right);
if (t2 != declaration_type)
return t2;
return Type(left);
}
static Tree *lookupRewriteCalls(Scope *evalScope, Scope *sc,
Tree *what, Infix *entry, void *i)
// ----------------------------------------------------------------------------
// Used to check if RewriteCalls pass
// ----------------------------------------------------------------------------
{
RewriteCalls *rc = (RewriteCalls *) i;
return rc->Check(sc, what, entry);
}
bool Types::Evaluate(Tree *what)
// ----------------------------------------------------------------------------
// Find candidates for the given expression and infer types from that
// ----------------------------------------------------------------------------
{
// We don't evaluate expressions while prototyping a pattern
if (prototyping)
return true;
// Record if we are matching patterns
bool matchingPattern = matching;
matching = false;
// Look directly inside blocks
while (Block *block = what->AsBlock())
what = block->child;
// Test if we are already trying to evaluate this particular form
rcall_map::iterator found = rcalls.find(what);
bool recursive = found != rcalls.end();
if (recursive)
return true;
// Identify all candidate rewrites in the current context
RewriteCalls_p rc = new RewriteCalls(this);
rcalls[what] = rc;
uint count = 0;
Errors errors;
errors.Log (Error("Unable to evaluate '$1':", what), true);
context->Lookup(what, lookupRewriteCalls, rc);
// If we have no candidate, this is a failure
count = rc->candidates.size();
if (count == 0)
{
if (what->IsConstant())
{
Tree *wtype = Type(what);
return Unify(wtype, what, what, what);
}
if (matchingPattern && what->Kind() > KIND_LEAF_LAST)
{
Tree *wtype = Type(what);
return Unify(wtype, what, what, what);
}
Ooops("No form matches $1", what);
return false;
}
errors.Clear();
errors.Log(Error("Unable to check types in $1 because", what), true);
// The resulting type is the union of all candidates
Tree *type = Base(rc->candidates[0].type);
Tree *wtype = Type(what);
for (uint i = 1; i < count; i++)
{
Tree *ctype = rc->candidates[i].type;
ctype = Base(ctype);
if (IsGeneric(ctype) && IsGeneric(wtype))
{
// foo:#A rewritten as bar:#B and another type
// Join types instead of performing a union
if (!Join(ctype, type))
return false;
if (!Join(wtype, type))
return false;
continue;
}
type = UnionType(context, type, ctype);
}
// Perform type unification
return Unify(type, wtype, what, what, DECLARATION);
}
bool Types::UnifyExpressionTypes(Tree *expr1, Tree *expr2)
// ----------------------------------------------------------------------------
// Indicates that the two trees must have identical types
// ----------------------------------------------------------------------------
{
Tree *t1 = Type(expr1);
Tree *t2 = Type(expr2);
// If already unified, we are done
if (t1 == t2)
return true;
return Unify(t1, t2, expr1, expr2);
}
bool Types::Unify(Tree *t1, Tree *t2,
Tree *x1, Tree *x2,
unify_mode mode)
// ----------------------------------------------------------------------------
// Unification with expressions
// ----------------------------------------------------------------------------
{
Save<Tree_p> saveLeft(left, x1);
Save<Tree_p> saveRight(right, x2);
return Unify(t1, t2, mode);
}
bool Types::Unify(Tree *t1, Tree *t2, unify_mode mode)
// ----------------------------------------------------------------------------
// Unify two type forms
// ----------------------------------------------------------------------------
// A type form in ELFE can be:
// - A type name integer
// - A generic type name #ABC
// - A litteral value 0 1.5 "Hello"
// - A block for precedence (real)
// - The type of a pattern type (X:integer, Y:integer)
//
// Unification happens almost as "usual" for Algorithm W, except for how
// we deal with ELFE "shape-based" type constructors, e.g. type(P)
{
// Make sure we have the canonical form
t1 = Base(t1);
t2 = Base(t2);
if (t1 == t2)
return true; // Already unified
// Strip out blocks in type specification
if (Block *b1 = t1->AsBlock())
if (Unify(b1->child, t2))
return Join(b1, t2);
if (Block *b2 = t2->AsBlock())
if (Unify(t1, b2->child))
return Join(t1, b2);
// Lookup type names, replace them with their value
t1 = LookupTypeName(t1);
t2 = LookupTypeName(t2);
if (t1 == t2)
return true; // This may have been enough for unifiation
// If either is a generic, unify with the other
if (IsGeneric(t1))
return Join(t1, t2);
if (IsGeneric(t2))
return Join(t1, t2);
// In declaration mode, we have success if t2 covers t1
if (mode == DECLARATION && TypeCoversType(context, t2, t1, false))
return true;
// If we have a type name at this stage, this is a failure
if (IsTypeName(t1))
{
if (JoinConstant((Name *) t1, t2))
return true;
return TypeError(t1, t2);
}
if (IsTypeName(t2))
{
if (JoinConstant((Name *) t2, t1))
return true;
return TypeError(t1, t2);
}
// Check prefix constructor types
if (Tree *pat1 = TypePattern(t1))
{
// If we have two type patterns, they must be structurally identical
if (Tree *pat2 = TypePattern(t2))
{
if (UnifyPatterns(pat1, pat2))
return Join(t1, t2);
return TypeError(t1, t2);
}
// Match a type pattern with another value
return UnifyPatternAndValue(pat1, t2);
}
if (Tree *pat2 = TypePattern(t2))
return UnifyPatternAndValue(pat2, t1);
// None of the above: fail
return TypeError(t1, t2);
}
Tree *Types::Base(Tree *type)
// ----------------------------------------------------------------------------
// Return the base type for a given type, i.e. after all substitutions
// ----------------------------------------------------------------------------
{
Tree *chain = type;
// If we had some unification, find the reference type
TreeMap::iterator found = unifications.find(type);
while (found != unifications.end())
{
type = (*found).second;
found = unifications.find(type);
assert(type != chain || !"Circularity in unification chain");
}
// Make all elements in chain point to correct type for performance
while (chain != type)
{
Tree_p &u = unifications[chain];
chain = u;
u = type;
}
return type;
}
Tree *Types::TypePattern(Tree *type)
// ----------------------------------------------------------------------------
// Check if type is a type pattern, i.e. type ( ... )
// ----------------------------------------------------------------------------
{
if (Prefix *pfx = type->AsPrefix())
if (Name *tname = pfx->left->AsName())
if (tname->value == "type")
return pfx->right;
return NULL;
}
bool Types::Join(Tree *base, Tree *other, bool knownGood)
// ----------------------------------------------------------------------------
// Use 'base' as the prototype for the other type
// ----------------------------------------------------------------------------
{
if (!knownGood)
{
// If we have a type name, prefer that to a more complex form
// in order to keep error messages more readable
if (IsTypeName(other) && !IsTypeName(base))
std::swap(other, base);
// If what we want to use as a base is a generic and other isn't, swap
// (otherwise we could later unify through that variable)
else if (IsGeneric(base))
std::swap(other, base);
}
// Connext the base type classes
base = Base(base);
other = Base(other);
if (other != base)
unifications[other] = base;
return true;
}
bool Types::JoinConstant(Name *type, Tree *cst)
// ----------------------------------------------------------------------------
// Join a constant with a type name
// ----------------------------------------------------------------------------
{
// Check if we match against some sized type, otherwise force type
switch (cst->Kind())
{
case INTEGER:
if (type == integer_type || type == unsigned_type ||
type == integer8_type || type == unsigned8_type ||
type == integer16_type || type == unsigned16_type ||
type == integer32_type || type == unsigned32_type ||
type == integer64_type || type == unsigned64_type)
return Join(type, cst, true);
return Unify(integer_type, type) && Join(cst, integer_type);
case REAL:
if (type == real_type ||
type == real64_type ||
type == real32_type)
return Join(type, cst, true);
return Unify(real_type, type) && Join(cst, real_type);
case TEXT:
{
Text *text = (Text *) cst;
if (text->IsCharacter())
{
if (type == character_type)
return Join(type, cst, true);
return Join(type, character_type) && Join(cst, character_type);
}
if (type == text_type)
return Join(type, cst, true);
return Unify(text_type, type) && Join(cst, text_type);
}
default:
{
Tree *canon = CanonicalType(cst);
return type == canon;
}
}
return false;
}
bool Types::UnifyPatterns(Tree *t1, Tree *t2)
// ----------------------------------------------------------------------------
// Check if two patterns describe the same tree shape
// ----------------------------------------------------------------------------
{
if (t1 == t2)
return true;
switch(t1->Kind())
{
case INTEGER:
if (Integer *x1 = t1->AsInteger())
if (Integer *x2 = t2->AsInteger())
return x1->value == x2->value;
return false;
case REAL:
if (Real *x1 = t1->AsReal())
if (Real *x2 = t2->AsReal())
return x1->value == x2->value;
return false;
case TEXT:
if (Text *x1 = t1->AsText())
if (Text *x2 = t2->AsText())
return x1->value == x2->value;
return false;
case NAME:
// We don't attempt to allow renames. Names must match, it's simpler.
if (Name *x1 = t1->AsName())
if (Name *x2 = t2->AsName())
return x1->value == x2->value;
return false;
case INFIX:
if (Infix *x1 = t1->AsInfix())
if (Infix *x2 = t2->AsInfix())
return
x1->name == x2->name &&
UnifyPatterns(x1->left, x2->left) &&
UnifyPatterns(x1->right, x2->right);
return false;
case PREFIX:
if (Prefix *x1 = t1->AsPrefix())
if (Prefix *x2 = t2->AsPrefix())
return
UnifyPatterns(x1->left, x2->left) &&
UnifyPatterns(x1->right, x2->right);
return false;
case POSTFIX:
if (Postfix *x1 = t1->AsPostfix())
if (Postfix *x2 = t2->AsPostfix())
return
UnifyPatterns(x1->left, x2->left) &&
UnifyPatterns(x1->right, x2->right);
return false;
case BLOCK:
if (Block *x1 = t1->AsBlock())
if (Block *x2 = t2->AsBlock())
return
x1->opening == x2->opening &&
x1->closing == x2->closing &&
UnifyPatterns(x1->child, x2->child);
return false;
}
return false;
}
bool Types::UnifyPatternAndValue(Tree *pat, Tree *val)
// ----------------------------------------------------------------------------
// Check if two patterns describe the same tree shape
// ----------------------------------------------------------------------------
{
switch(pat->Kind())
{
case INTEGER:
if (Integer *x1 = pat->AsInteger())
if (Integer *x2 = val->AsInteger())
return x1->value == x2->value;
return false;
case REAL:
if (Real *x1 = pat->AsReal())
if (Real *x2 = val->AsReal())
return x1->value == x2->value;
return false;
case TEXT:
if (Text *x1 = pat->AsText())
if (Text *x2 = val->AsText())
return x1->value == x2->value;
return false;
case NAME:
// A name at that stage is a variable, so we match
// PROBLEM: matching X+X will match twice?
return UnifyExpressionTypes(pat, val);
case INFIX:
if (Infix *x1 = pat->AsInfix())
{
// Check if the pattern is a type declaration
if (x1->name == ":")
return Unify(x1->right, val);
if (Infix *x2 = val->AsInfix())
return
x1->name == x2->name &&
UnifyPatternAndValue(x1->left, x2->left) &&
UnifyPatternAndValue(x1->right, x2->right);
}
return false;
case PREFIX:
if (Prefix *x1 = pat->AsPrefix())
if (Prefix *x2 = val->AsPrefix())
return
UnifyPatterns(x1->left, x2->left) &&
UnifyPatternAndValue(x1->right, x2->right);
return false;
case POSTFIX:
if (Postfix *x1 = pat->AsPostfix())
if (Postfix *x2 = val->AsPostfix())
return
UnifyPatternAndValue(x1->left, x2->left) &&
UnifyPatterns(x1->right, x2->right);
return false;
case BLOCK:
if (Block *x1 = pat->AsBlock())
if (Block *x2 = val->AsBlock())
return
x1->opening == x2->opening &&
x1->closing == x2->closing &&
UnifyPatternAndValue(x1->child, x2->child);
return false;
}
return false;
}
bool Types::Commit(Types *child)
// ----------------------------------------------------------------------------
// Commit all the inferences from 'child' into the current
// ----------------------------------------------------------------------------
{
rcall_map &rmap = rcalls;
for (rcall_map::iterator r = rmap.begin(); r != rmap.end(); r++)
{
Tree *expr = (*r).first;
Tree *type = child->Type(expr);
if (!AssignType(expr, type))
return false;
}
return true;
}
Name * Types::NewTypeName(TreePosition pos)
// ----------------------------------------------------------------------------
// Automatically generate new type names
// ----------------------------------------------------------------------------
{
ulong v = id++;
text name;
do
{
name = char('A' + v % 26) + name;
v /= 26;
} while (v);
return new Name("#" + name, pos);
}
Tree *Types::LookupTypeName(Tree *type)
// ----------------------------------------------------------------------------
// If we have a type name, lookup its definition
// ----------------------------------------------------------------------------
{
if (Name *name = type->AsName())
{
// Don't lookup type variables (generic names such as #A)
if (IsGeneric(name->value))
return name;
// Check if we have a type definition. If so, use it
Tree *definition = context->Bound(name);
if (definition && definition != name)
{
Join(definition, name);
return Base(definition);
}
}
// Otherwise, simply return input type
return type;
}
bool Types::TypeError(Tree *t1, Tree *t2)
// ----------------------------------------------------------------------------
// Show type matching errors
// ----------------------------------------------------------------------------
{
assert(left && right);
if (left == right)
{
Ooops("Type of $1 cannot be both $2 and $3", left, t1, t2);
}
else
{
Ooops("Cannot unify type $2 of $1", left, t1);
Ooops("with type $2 of $1", right, t2);
}
return false;
}
// ============================================================================
//
// High-level type functions
//
// ============================================================================
Tree *ValueMatchesType(Context *ctx, Tree *type, Tree *value, bool convert)
// ----------------------------------------------------------------------------
// Checks if a value matches a type, return value or NULL if no match
// ----------------------------------------------------------------------------
{
// Check if we match some of the built-in leaf types
if (type == integer_type)
if (Integer *iv = value->AsInteger())
return iv;
if (type == real_type)
{
if (Real *rv = value->AsReal())
return rv;
if (convert)
{
if (Integer *iv = value->AsInteger())
{
Tree *result = new Real(iv->value);
return result;
}
}
}
if (type == text_type)
if (Text *tv = value->AsText())
if (tv->IsText())
return tv;
if (type == character_type)
if (Text *cv = value->AsText())
if (cv->IsCharacter())
return cv;
if (type == boolean_type)
if (Name *nv = value->AsName())
if (nv->IsBoolean())
return nv;
if (IsTreeType(type))
return value;
if (type == symbol_type)
if (Name *nv = value->AsName())
return nv;