-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathbytecode.cpp
2155 lines (1853 loc) · 66.2 KB
/
bytecode.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
// ****************************************************************************
// bytecode.cpp Tao project
// ****************************************************************************
//
// File Description:
//
// Implementation of a bytecode to evaluate ELFE programs faster
// without the need to generate machine code directly
//
//
//
//
//
//
//
// ****************************************************************************
// (C) 2015 Christophe de Dinechin <[email protected]>
// (C) 2015 Taodyne SAS
// ****************************************************************************
#include "bytecode.h"
#include "interpreter.h"
#include "save.h"
#include "errors.h"
#include "basics.h"
#include <algorithm>
#include <sstream>
ELFE_BEGIN
// ============================================================================
//
// Main entry point
//
// ============================================================================
Tree *EvaluateWithBytecode(Context *ctx, Tree *what)
// ----------------------------------------------------------------------------
// Compile bytecode and then evaluate it
// ----------------------------------------------------------------------------
{
TreeIDs noParms;
TreeList captured;
Function *function = CompileToBytecode(ctx, what, NULL, noParms, captured);
Tree_p result = what;
if (function)
{
ELFE_ASSERT(function->Inputs() == 0);
uint size = captured.size();
Scope *scope = ctx->CurrentScope();
captured.push_back(what);
captured.push_back(scope);
Data data = &captured[size];
Op *op = function;
while(op)
op = op->Run(data);
result = DataResult(data);
}
return result;
}
Function *CompileToBytecode(Context *ctx, Tree *what, Tree *type,
TreeIDs &parms, TreeList &captured)
// ----------------------------------------------------------------------------
// Compile a tree to bytecode
// ----------------------------------------------------------------------------
{
CodeBuilder builder(captured);
Function *function = builder.Compile(ctx, what, parms, type);
return function;
}
// ============================================================================
//
// Opcodes we use in this translation
//
// ============================================================================
struct FailOp : Op
// ----------------------------------------------------------------------------
// Any op that has a fail exit
// ----------------------------------------------------------------------------
{
FailOp(Op *fx): Op(), fail(fx) {}
Op *fail;
virtual Op * Fail() { return fail; }
virtual kstring OpID() { return "fail"; }
};
struct LabelOp : Op
// ----------------------------------------------------------------------------
// The target of a jump
// ----------------------------------------------------------------------------
{
LabelOp(kstring name): name(name) {}
virtual kstring OpID() { return name; }
virtual void Dump(std::ostream &out)
{
out << OpID() << "\t" << (void *) this;
}
kstring name;
};
struct ConstOp : Op
// ----------------------------------------------------------------------------
// Evaluates a constant
// ----------------------------------------------------------------------------
{
ConstOp(Tree *value): value(value) {}
Tree_p value;
virtual Op * Run(Data data)
{
DataResult(data, value);
return success;
}
virtual kstring OpID() { return "const"; }
virtual void Dump(std::ostream &out)
{
kstring kinds[] = { "integer", "real", "text", "name",
"block", "prefix", "postfix", "infix" };
out << OpID() << "\t" << kinds[value->Kind()] << "\t" << value;
}
};
struct SelfOp : Op
// ----------------------------------------------------------------------------
// Evaluate self
// ----------------------------------------------------------------------------
{
virtual kstring OpID() { return "self"; }
};
struct EvalOp : FailOp
// ----------------------------------------------------------------------------
// Evaluate the given tree once and only once
// ----------------------------------------------------------------------------
{
EvalOp(int id, Op *ops, Op *fail)
: FailOp(fail), ops(ops), id(id) {}
Op *ops;
int id;
virtual Op * Run(Data data)
{
Tree *result = data[id];
if (result)
{
DataResult(data, result);
return success;
}
// Complete evaluation of the bytecode we were given
Op *op = ops;
while (op)
op = op->Run(data);
// Save the result if evaluation was successful
if (Tree *result = DataResult(data))
{
data[id] = result;
return success;
}
// Otherwise, go to the fail bytecode
return fail;
}
virtual kstring OpID() { return "eval"; }
virtual void Dump(std::ostream &out)
{
out << OpID() << "\t" << id << "\t"
<< Code::Ref(ops, "\t", "code", "null");
}
};
struct ArgEvalOp : FailOp
// ----------------------------------------------------------------------------
// Evaluate the given tree once and only once
// ----------------------------------------------------------------------------
{
ArgEvalOp(Context *context, int argId, int id, Op *fail)
: FailOp(fail), context(context), argId(argId), id(id) {}
Context_p context;
int argId, id;
virtual Op * Run(Data data)
{
Tree *result = data[id];
if (result)
{
DataResult(data, result);
return success;
}
// Evaluate in place
Tree *self = data[argId];
if (Tree *inside = IsClosure(self, &context))
self = inside;
Context *ctx = context;
if (self->IsConstant())
result = self;
else
result = EvaluateWithBytecode(ctx, self);
if (result)
{
result = MakeClosure(ctx, result);
data[id] = result;
return success;
}
// Otherwise, go to the fail bytecode
return fail;
}
virtual kstring OpID() { return "arg"; }
virtual void Dump(std::ostream &out)
{
out << OpID() << "\t" << id << "=" << argId
<< " @" << (void *) context->CurrentScope();
}
};
struct ClearOp : Op
// ----------------------------------------------------------------------------
// Clear a range of eval entries after a complete evaluation
// ----------------------------------------------------------------------------
{
ClearOp(int lo, int hi): lo(lo), hi(hi) {}
int lo, hi;
virtual Op * Run(Data data)
{
for (int v = lo; v <= hi; v++)
data[v] = NULL;
return success;
}
virtual kstring OpID() { return "clear"; }
virtual void Dump(std::ostream &out)
{
out << OpID() << "\t" << lo << ".." << hi;
}
};
struct ClosureOp : Op
// ----------------------------------------------------------------------------
// Create a closure with the result
// ----------------------------------------------------------------------------
{
ClosureOp(Context *ctx): context(ctx) {}
Context_p context;
virtual Op * Run(Data data)
{
Tree *result = DataResult(data);
result = MakeClosure(context, result);
DataResult(data, result);
return success;
}
virtual kstring OpID() { return "closure"; }
virtual void Dump(std::ostream &out)
{
out << OpID();
}
};
struct ValueOp : Op
// ----------------------------------------------------------------------------
// Return a tree that we know was already evaluated
// ----------------------------------------------------------------------------
{
ValueOp(int id): id(id) {}
int id;
virtual Op * Run(Data data)
{
DataResult(data, data[id]);
return success;
}
virtual kstring OpID() { return "value"; }
virtual void Dump(std::ostream &out)
{
out << OpID() << "\t" << id;
}
};
struct StoreOp : Op
// ----------------------------------------------------------------------------
// Store result in some other ID
// ----------------------------------------------------------------------------
{
StoreOp(int id): id(id) {}
int id;
virtual Op * Run(Data data)
{
data[id] = DataResult(data);
return success;
}
virtual kstring OpID() { return "store"; }
virtual void Dump(std::ostream &out)
{
out << OpID() << "\t" << id;
}
};
struct CallOp : Op
// ----------------------------------------------------------------------------
// Call a subroutine using the given inputs
// ----------------------------------------------------------------------------
{
CallOp(Code *target, uint outId, ParmOrder &parms)
: target(target), outId(outId), parms(parms) {}
Code * target;
int outId;
ParmOrder parms;
virtual Op *Run(Data data)
{
uint sz = parms.size();
Data out = data + outId;
// Copy result and scope
DataResult(out, DataResult(data));
DataScope (out, DataScope (data));
// Copy all parameters
for (uint p = 0; p < sz; p++)
{
int parmId = parms[p];
out[~p] = data[parmId];
}
Op *remaining = target->Run(out);
ELFE_ASSERT(!remaining);
if (remaining)
return remaining;
DataResult(data, out[0]);
return success;
}
virtual kstring OpID() { return "call"; }
virtual void Dump(std::ostream &out)
{
out << OpID() << "\t" << Code::Ref(target, "\t", "code", "null")
<< "\t(";
for (uint a = 0; a < parms.size(); a++)
out << (a ? "," : "") << parms[a];
out << ") @ " << outId;
}
};
struct TypeCheckOp : FailOp
// ----------------------------------------------------------------------------
// Check if a type matches the given type
// ----------------------------------------------------------------------------
{
TypeCheckOp(int value, int type, Op *fail)
: FailOp(fail), value(value), type(type) {}
int value;
int type;
virtual Op * Run(Data data)
{
Context_p context = new Context(DataScope(data));
Tree *cast = TypeCheck(context, data[type], data[value]);
if (!cast)
return fail;
DataResult(data, cast);
return success;
}
virtual kstring OpID() { return "typechk"; }
virtual void Dump(std::ostream &out)
{
out << OpID() << "\t" << value << ":" << type;
}
};
struct IndexOp : FailOp
// ----------------------------------------------------------------------------
// Index operation, i.e. unknown prefix
// ----------------------------------------------------------------------------
{
IndexOp(int left, int right, Op *fail)
: FailOp(fail), left(left), right(right) {}
int left, right;
virtual Op * Run(Data data)
{
Tree *callee = data[left];
Tree *arg = data[right];
Scope_p scope = DataScope(data);
// If the declaration was compiled, evaluate the code
if (Code *code = callee->GetInfo<Code>())
{
uint inputs = code->Inputs();
if (inputs == 0)
{
// If no arguments, evaluate as new callee
Tree_p args[2] = { data[0], data[1] };
Op *remaining = code->Run(args);
ELFE_ASSERT(!remaining);
if (remaining)
return remaining;
callee = DataResult(args);
}
else if (inputs == 1)
{
// Looks like a prefix, use it as an argument
Tree_p args[3] = { arg, data[0], data[1] };
Op *remaining = code->Run(&args[1]);
ELFE_ASSERT(!remaining);
if (remaining)
return remaining;
return success;
}
else
{
Ooops ("Invalid prefix code for $1, had $2 arguments", callee)
.Arg(inputs);
return fail;
}
}
// Check if we have a closure
Context_p context = new Context(scope);
if (Tree *inside = IsClosure(callee, &context))
{
scope = context->CurrentScope();
callee = inside;
DataScope(data, scope);
}
// Eliminate blocks on the callee side
while (Block *blk = callee->AsBlock())
callee = blk->child;
// If we have an infix on the left, check if it's a single rewrite
if (Infix *lifx = callee->AsInfix())
{
// Check if we have a function definition
if (lifx->name == "->")
{
// If we have a single name on the left, like (X->X+1)
// interpret that as a lambda function
Tree *result = NULL;
if (Name *lfname = lifx->left->AsName())
{
// Case like '(X->X+1) Arg':
// Bind arg in new context and evaluate body
context = new Context(context);
context->Define(lfname, arg);
result = context->Evaluate(lifx->right);
}
else
{
// Otherwise, enter declaration and retry, e.g.
// '(X,Y->X+Y) (2,3)' should evaluate as 5
context = new Context(context);
context->Define(lifx->left, lifx->right);
result = context->Evaluate(arg);
}
DataResult(data, result);
return success;
}
}
// Try to lookup in the callee's context
if (Tree *found = context->Bound(arg))
{
DataResult(data, found);
return success;
}
// Other cases: go to 'fail' exit
return fail;
}
};
struct FormErrorOp : Op
// ----------------------------------------------------------------------------
// When we fail with all candidates, report an error
// ----------------------------------------------------------------------------
{
FormErrorOp(Tree *self): self(self) {}
Tree_p self;
virtual Op * Run(Data data)
{
Ooops("No form matches $1", self);
return success;
}
virtual kstring OpID() { return "error"; };
};
struct PrefixFormErrorOp : FormErrorOp
// ----------------------------------------------------------------------------
// When we fail with all prefix candidates, report an error
// ----------------------------------------------------------------------------
{
PrefixFormErrorOp(Tree *self): FormErrorOp(self) {}
virtual Op * Run(Data data)
{
Ooops("No prefix matches $1", self);
return success;
}
virtual kstring OpID() { return "pfxerror"; };
};
// ============================================================================
//
// Evaluating a code sequence
//
// ============================================================================
Code::Code(Context *ctx, Tree *self)
// ----------------------------------------------------------------------------
// Create a new code from the given ops
// ----------------------------------------------------------------------------
: context(ctx), self(self), ops(NULL), instrs()
{}
Code::Code(Context *context, Tree *self, Op *ops)
// ----------------------------------------------------------------------------
// Create a new code from the given ops
// ----------------------------------------------------------------------------
: context(context), self(self), ops(ops), instrs()
{
for (Op *op = ops; op; op = op->success)
instrs.push_back(op);
}
Code::~Code()
// ----------------------------------------------------------------------------
// Delete the ops we own
// ----------------------------------------------------------------------------
{
for (Ops::iterator o = instrs.begin(); o != instrs.end(); o++)
delete *o;
instrs.clear();
}
void Code::SetOps(Op **newOps, Ops *instrsToTakeOver, uint outId)
// ----------------------------------------------------------------------------
// Take over the given code
// ----------------------------------------------------------------------------
{
ops = *newOps;
*newOps = NULL;
ELFE_ASSERT(instrs.size() == 0);
std::swap(instrs, *instrsToTakeOver);
// A few post-generation optimizations:
uint max = instrs.size();
for (uint i = 0; i < max; i++)
{
Op *op = instrs[i];
// Make sure calls all use the same out area
if (CallOp *call = dynamic_cast<CallOp *>(op))
call->outId = outId;
// Remove labels, since they execute as no-ops
while (LabelOp *label = dynamic_cast<LabelOp *>(op->success))
op->success = label->success;
if (FailOp *fop = dynamic_cast<FailOp *>(op))
while (LabelOp *label = dynamic_cast<LabelOp *>(fop->fail))
fop->fail = label->success;
}
for (uint i = 0; i < max; i++)
{
Op *op = instrs[i];
if (LabelOp *label = dynamic_cast<LabelOp *>(op))
{
instrs.erase(instrs.begin() + i);
--i;
--max;
delete label;
}
}
}
Op *Code::Run(Data data)
// ----------------------------------------------------------------------------
// Run all instructions in the sequence
// ----------------------------------------------------------------------------
{
// Running in-place in the same context
Scope *scope = context->CurrentScope();
data[0] = self;
data[1] = scope;
// Run all instructions we have in that code
Op *op = ops;
while (op)
op = op->Run(data);
// We were successful
return success;
}
void Code::Dump(std::ostream &out)
// ----------------------------------------------------------------------------
// Dump all the instructions
// ----------------------------------------------------------------------------
{
out << OpID() << "\t" << (void *) (Op *) this
<< "\tentry\t" << (void *) ops
<< "\t" << self << "\n";
out << "\talloc"
<< "\tI" << Inputs() << " L" << Locals() << "\n";
Dump(out, ops, instrs);
}
static Ops *currentDump = NULL;
void Code::Dump(std::ostream &out, Op *ops, Ops &instrs)
// ----------------------------------------------------------------------------
// Dump an instruction list
// ----------------------------------------------------------------------------
{
Save<Ops *> saveCurrentDump(currentDump, &instrs);
uint max = instrs.size();
for (uint i = 0; i < max; i++)
{
Op *op = instrs[i];
Op *fail = op->Fail();
if (op == ops)
out << i << "=>\t" << op;
else
out << i << "\t" << op;
if (fail)
out << Ref(fail, "\t", "fail", "nofail");
if (i + 1 < max)
{
Op *next = instrs[i]->success;
if (next != instrs[i+1])
out << Ref(next, "\n\t", "goto", "return");
}
out << "\n";
}
}
text Code::Ref(Op *op, text sep, text set, text null)
// ----------------------------------------------------------------------------
// Return the reference for an op in the current list
// ----------------------------------------------------------------------------
{
std::ostringstream out;
bool found = false;
uint max = currentDump ? currentDump->size() : 0;
if (op == NULL)
found = bool(out << sep << null);
for (uint o = 0; o < max; o++)
if ((*currentDump)[o] == op)
found = bool(out << sep << set << "\t#" << o);
if (!found)
out << sep << set << "\t" << (void *) op;
return out.str();
}
Function::Function(Context *context, Tree *self, uint nInputs, uint nLocals)
// ----------------------------------------------------------------------------
// Create a function
// ----------------------------------------------------------------------------
: Code(context, self), nInputs(nInputs), nLocals(nLocals)
{}
Function::Function(Function *original, Data data, ParmOrder &capture)
// ----------------------------------------------------------------------------
// Copy constructor used for closures
// ----------------------------------------------------------------------------
: Code(original->context, original->self),
nInputs(original->nInputs), nLocals(original->nLocals),
captured()
{
// We have no instrs, so we don't "own" the instructions
ops = original->ops;
// Copy data in the closure from current data
uint max = capture.size();
captured.reserve(max);
for (uint p = 0; p < max; p++)
{
int id = capture[p];
Tree *arg = data[id];
captured.push_back(arg);
}
}
Function::~Function()
// ----------------------------------------------------------------------------
// Destructor for functions
// ----------------------------------------------------------------------------
{}
Op *Function::Run(Data data)
// ----------------------------------------------------------------------------
// Create a new scope and run all instructions in the sequence
// ----------------------------------------------------------------------------
{
Scope *scope = context->CurrentScope();
uint frameSize = FrameSize();
uint offset = OffsetSize();
Data frame = new Tree_p[frameSize];
Data newData = frame + offset;
// Initialize self and scope
newData[0] = self;
newData[1] = scope;
// Copy input arguments
uint inputs = Inputs();
Data oarg = &newData[-1];
Data iarg = &data[-1];
for (uint a = 0; a < inputs; a++)
*oarg-- = *iarg--;
// Copy closure data if any
uint closures = Closures();
if (closures)
{
Data carg = ClosureData();
for (uint c = 0; c < closures; c++)
*oarg-- = *carg++;
}
// Execute the following instructions in the newly created data context
Op *op = ops;
while (op)
op = op->Run(newData);
// Copy result and current context to the old data
Tree *result = DataResult(newData);
DataResult(data, result);
// Destroy the frame, we no longer need it
delete[] frame;
// Evaluate next instruction
return success;
}
void Function::Dump(std::ostream &out)
// ----------------------------------------------------------------------------
// Dump all the instructions
// ----------------------------------------------------------------------------
{
out << OpID() << "\t" << (void *) (Op *) this
<< "\tentry\t" << (void *) ops
<< "\t" << self << "\n";
out << "\talloc"
<< "\tI" << Inputs() << " L" << Locals() << " C" << Closures() << "\n";
Code::Dump(out, ops, instrs);
}
// ============================================================================
//
// Building a code sequence and variants
//
// ============================================================================
CodeBuilder::CodeBuilder(TreeList &captured)
// ----------------------------------------------------------------------------
// Create a code builder
// ----------------------------------------------------------------------------
: ops(NULL), lastOp(&ops),
inputs(), values(), captured(captured),
nEvals(0), nParms(0), candidates(0),
test(NULL), resultType(NULL),
context(NULL), parmsCtx(NULL), argsCtx(NULL),
failOp(NULL), successOp(NULL),
instrs(), subexprs(), parms(), defer(false)
{}
CodeBuilder::~CodeBuilder()
// ----------------------------------------------------------------------------
// Delete all instructions if the list was not transferred
// ----------------------------------------------------------------------------
{
for (Ops::iterator o = instrs.begin(); o != instrs.end(); o++)
delete *o;
instrs.clear();
}
CodeBuilder::depth CodeBuilder::ScopeDepth(Scope *scope)
// ----------------------------------------------------------------------------
// Return true if the given scope is local to the current function
// ----------------------------------------------------------------------------
{
Scope *parmsScope = parmsCtx->CurrentScope();
Scope *globalScope = MAIN->context->CurrentScope();
uint count = 0;
// Loop on scope, looking for either current parm scope or global scope
while (scope)
{
if (scope == parmsScope)
return count ? LOCAL : PARAMETER;
if (scope == globalScope)
return count ? ENCLOSING : GLOBAL;
scope = ScopeParent(scope);
count++;
}
// If we reached the end without seeing the current global scope,
// this means this is a global scope (probably some other file)
return GLOBAL;
}
void CodeBuilder::Add(Op *op)
// ----------------------------------------------------------------------------
// Add an instruction in the generated code
// ----------------------------------------------------------------------------
{
ELFE_ASSERT(count(instrs.begin(), instrs.end(), op) == 0);
instrs.push_back(op);
*lastOp = op;
lastOp = &op->success;
ELFE_ASSERT(!op->success && "Adding an instruction that has kids");
}
void CodeBuilder::AddEval(int id, Op *op)
// ----------------------------------------------------------------------------
// Add an evaluation in the generated code, simplify if 'Quick'
// ----------------------------------------------------------------------------
{
Add(new EvalOp(id, op, failOp));
}
void CodeBuilder::AddTypeCheck(Context *context, Tree *what, Tree *type)
// ----------------------------------------------------------------------------
// Add type check if necessary
// ----------------------------------------------------------------------------
{
if (type)
if (Name *name = type->AsName())
if (Tree *original = context->Bound(name))
type = original;
if (resultType)
if (Name *name = resultType->AsName())
if (Tree *original = context->Bound(name))
resultType = original;
// Unify form for 'catch-all' type
if (!type)
type = tree_type;
if (!resultType)
resultType = tree_type;
if (resultType == tree_type)
return;
// Check if we have some static match
if (what->IsConstant())
if (TypeCheck(context, type, what))
return;
// Check if types match statically
if (type == resultType)
return;
// Otherwise, we need to generate a dynamic match
int valueID = ValueID(what);
int typeID = Evaluate(context, type);
Add(new TypeCheckOp(valueID, typeID, failOp));
}
void CodeBuilder::Success()
// ----------------------------------------------------------------------------
// Success at the end of a declaration
// ----------------------------------------------------------------------------
{
ELFE_ASSERT(successOp && failOp);
ELFE_ASSERT(count(instrs.begin(), instrs.end(), failOp) == 0);
IFTRACE(compile)
std::cerr << "SUCCESS:\t" << successOp << "\n"
<< "FAIL:\t" << failOp << "\n";
// End current stream to the success exit, restart code gen at failure exit
*lastOp = successOp;
ELFE_ASSERT(failOp && "Success without a failure exit");
lastOp = &failOp->success;
instrs.push_back(failOp);
failOp = NULL;
ELFE_ASSERT(!*lastOp);
}
void CodeBuilder::InstructionsSuccess(uint neOld)
// ----------------------------------------------------------------------------
// At end of an instruction, mark success by recording number of evals
// ----------------------------------------------------------------------------
{
uint ne = values.size();
if (nEvals < ne)
nEvals = ne;
if (ne > neOld)
Add(new ClearOp(neOld+2, ne+1));
if (defer)
Add(new ClosureOp(context));
}
// ============================================================================
//
// Compilation of the tree
//
// ============================================================================
//
// The 'Instructions' function evaluates candidates in the symbol table.
// Each specific declaration causes an invokation of compileLookup.
//
// Consider the following code:
//
// foo X:integer, Y:integer -> foo1
// foo A:integer, B -> foo2
// foo U, V
// write "Toto"
//
// The generated code will look like this
// ;; Evaluate foo1 candidate
//
// ;; Match U against X:integer
// Evaluate U or goto fail1.1 (EvalOp)
// Evaluate integer or goto fail1.1 (EvalOp)
// TypeCheck U : integer or goto fail1.1 (TypeCheckOp)
//
// ;; Match V against Y:integer
// Evaluate V or goto fail1.1 (EvalOp)
// Evaluate integer or goto fail1.1 (EvalOp - SaveLeft)
// TypeCheck V : integer or goto fail1.1 (TypeCheckOp)
//
// ;; Call foo1
// Call foo1 (id(U), id(V)) @ parmSize (CallOp)
//
// ;; Done, successful evaluation, goto is in 'success' field
// goto success1
//
// fail1.1: (LabelOp)
// Evaluate U or goto fail1.2 (EvalOp)
// Evaluate integer or goto fail1.2 (EvalOp)
// ...
// Call foo2 (CallOp)
// goto success1
//
// fail1.2: (LabelOp)
// FormError (FormErrorOp)
//
// success1: (LabelOp)
// ;; Same thing for write "Toto"