-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.d
executable file
·1554 lines (1318 loc) · 31.8 KB
/
main.d
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
/// LLVM Kaleidoscope Tutorial in D
/// Converted by Michaël Larouche <[email protected]>
module test.llvmKaleidoscope;
import llvm.c.Analysis;
import llvm.c.Core;
import llvm.c.ExecutionEngine;
import llvm.c.Initialization;
import llvm.c.transforms.Scalar;
import llvm.c.Target;
import std.ascii;
import std.conv;
import std.stdio;
import std.string;
import std.typecons;
import std.c.stdio;
//===----------------------------------------------------------------------===//
// Lexer
//===----------------------------------------------------------------------===//
// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
// of these for known things.
enum Token
{
tok_eof = -1,
tok_def = -2, tok_extern = -3,
tok_identifier = -4, tok_number = -5,
tok_if = -6, tok_then = -7, tok_else = -8,
tok_for = -9, tok_in = -10,
tok_binary = -11, tok_unary = -12,
tok_var = -13
}
string IdentifierStr; // Filled in if tok_identifier
double NumVal; // Filled in if tok_number
int readChar()
{
return getchar();
}
/// gettok - Return the next token from standard input.
int gettok()
{
static int LastChar = ' ';
// Skip any whitespace
while(isWhite(LastChar))
{
LastChar = readChar();
}
// identifier: [a-zA-Z][a-zA-Z0-9]*
if(isAlpha(LastChar))
{
IdentifierStr = "";
IdentifierStr ~= LastChar;
LastChar = readChar();
while(isAlphaNum(LastChar))
{
IdentifierStr ~= LastChar;
LastChar = readChar();
}
switch(IdentifierStr)
{
case "def":
return Token.tok_def;
case "extern":
return Token.tok_extern;
case "if":
return Token.tok_if;
case "then":
return Token.tok_then;
case "else":
return Token.tok_else;
case "for":
return Token.tok_for;
case "in":
return Token.tok_in;
case "binary":
return Token.tok_binary;
case "unary":
return Token.tok_unary;
case "var":
return Token.tok_var;
default:
return Token.tok_identifier;
}
}
// Number: [0-9.]+
if(isDigit(LastChar) || LastChar == '.')
{
string NumStr;
do
{
NumStr ~= LastChar;
LastChar = readChar();
}
while(isDigit(LastChar) || LastChar == '.');
NumVal = to!double(NumStr);
return Token.tok_number;
}
// Comment until end of line.
if(LastChar == '#')
{
do
{
LastChar = readChar();
}
while(LastChar != EOF && LastChar != '\n' && LastChar != '\r');
if(LastChar != EOF)
{
return gettok();
}
}
// Check for end of file. Don't eat the EOF.
if(LastChar == EOF)
{
return Token.tok_eof;
}
// Otherwise, just return the character as its ascii value.
int ThisChar = LastChar;
LastChar = readChar();
return cast(int)ThisChar;
}
LLVMValueRef CreateEntryBlockAlloca(LLVMValueRef theFunction, string varName)
{
auto backupCurrentBlock = LLVMGetInsertBlock(Builder);
LLVMPositionBuilderAtEnd(Builder, LLVMGetFirstBasicBlock(theFunction));
auto allocaValue = LLVMBuildAlloca(Builder, LLVMDoubleType(), varName.toStringz());
LLVMPositionBuilderAtEnd(Builder, backupCurrentBlock);
return allocaValue;
}
//===----------------------------------------------------------------------===//
// Abstract Syntax Tree (aka Parse Tree)
// Code generation
//===----------------------------------------------------------------------===//
LLVMModuleRef TheModule;
LLVMValueRef[string] NamedValues;
LLVMBuilderRef Builder;
LLVMPassManagerRef TheFPM;
/// ExprAST - Base class for all expression nodes.
class ExprAST
{
LLVMValueRef Codegen()
{
return null;
}
}
/// NumberExprAST - Expression class for numeric literals like "1.0".
class NumberExprAST : ExprAST
{
public:
this(double val)
{
Val = val;
}
LLVMValueRef Codegen()
{
return LLVMConstReal(LLVMDoubleType(), Val);
}
private:
double Val;
}
/// VariableExprAST - Expression class for referencing a variable, like "a".
class VariableExprAST : ExprAST
{
public:
this(string name)
{
Name = name;
}
LLVMValueRef Codegen()
{
// Loop this variable in the function
if(Name in NamedValues)
{
auto v = NamedValues[Name];
// Load the value.
return LLVMBuildLoad(Builder, v, Name.toStringz());
}
else
{
return ErrorV("Unknown variable name");
}
}
string getName()
{
return Name;
}
private:
string Name;
}
/// BinaryExprAST - Expression class for a binary operator.
class BinaryExprAST : ExprAST
{
public:
this(char op, ExprAST lhs, ExprAST rhs)
{
Op = op;
LHS = lhs;
RHS = rhs;
}
LLVMValueRef Codegen()
{
// Special case '=' because we don't want to emit the LHS as an expression.
if(Op == '=')
{
// Asignment requires the LHS to be an identifier.
if(cast(VariableExprAST)LHS)
{
VariableExprAST lhse = cast(VariableExprAST)LHS;
// Codegen the RHS.
auto val = RHS.Codegen();
// Look up the variable.
if(lhse.getName() !in NamedValues)
{
return ErrorV("Unknown variable in assignment.");
}
auto variable = NamedValues[lhse.getName()];
LLVMBuildStore(Builder, val, variable);
return val;
}
else
{
return ErrorV("destination of '=' must be a variable");
}
}
auto l = LHS.Codegen();
auto r = RHS.Codegen();
if(l is null || r is null)
{
return null;
}
switch(Op)
{
case '+':
return LLVMBuildFAdd(Builder, l, r, "addtmp");
case '-':
return LLVMBuildFSub(Builder, l, r, "subtmp");
case '*':
return LLVMBuildFMul(Builder, l, r, "multmp");
case '/':
return LLVMBuildFDiv(Builder, l, r, "divtmp");
case '<':
l = LLVMBuildFCmp(Builder, LLVMRealPredicate.ULT, l, r, "cmp");
// Convert bool 0/1 to double 0.0 or 1.0
return LLVMBuildUIToFP(Builder, l, LLVMDoubleType(), "booltmp");
// If it wasn't a builtin binary operator, it must be a user defined one. Emit
// a call to it.
default:
string operatorFunctionName = "binary" ~ Op;
auto f = LLVMGetNamedFunction(TheModule, operatorFunctionName.toStringz());
assert(f, "binary operator not found !");
LLVMValueRef[2] ops = [l, r];
return LLVMBuildCall(Builder, f, ops.ptr, cast(uint)ops.length, "binop");
}
}
private:
char Op;
ExprAST LHS;
ExprAST RHS;
}
/// CallExprAST - Expression class for function calls.
class CallExprAST : ExprAST
{
public:
this(string callee, ExprAST[] args)
{
Callee = callee;
Args = args;
}
LLVMValueRef Codegen()
{
// Look up the name in the global module table.
LLVMValueRef calleeF = LLVMGetNamedFunction(TheModule, Callee.toStringz());
if(calleeF is null)
{
return ErrorV("Unknow function referenced");
}
// If argument mismatch error.
if(LLVMCountParams(calleeF) != Args.length)
{
return ErrorV("Incorrect number of arguments passed");
}
LLVMValueRef[] argsV;
foreach(arg; Args)
{
auto generatedValue = arg.Codegen();
if(generatedValue is null)
{
return null;
}
argsV ~= generatedValue;
}
return LLVMBuildCall(Builder, calleeF, argsV.ptr, cast(uint)argsV.length, "calltmp");
}
private:
string Callee;
ExprAST[] Args;
}
/// PrototypeAST - This class represents the "prototype" for a function,
/// which captures its name, and its argument names (thus implicitly the number
/// of arguments the function takes), as well as if it is an operator.
class PrototypeAST
{
public:
this(string name, string[] args, bool _isOperator = false, uint _precedence = 0)
{
Name = name;
Args = args;
isOperator = _isOperator;
Precedence = _precedence;
}
@property bool isUnaryOp()
{
return isOperator && Args.length == 1;
}
@property bool isBinaryOp()
{
return isOperator && Args.length == 2;
}
@property char operatorName()
{
assert(isUnaryOp() || isBinaryOp());
return Name[$-1];
}
@property uint binaryPrecedence()
{
return Precedence;
}
/// CreateArgumentAllocas - Create an alloca for each argument and register the
/// argument in the symbol table so that references to it will succeed.
void CreateArgumentAllocas(LLVMValueRef f)
{
LLVMValueRef[] params;
params.length = LLVMCountParams(f);
LLVMGetParams(f, params.ptr);
foreach(index, arg; params)
{
// Create an alloca for this variable.
auto alloca = CreateEntryBlockAlloca(f, Args[index]);
// Store the initial value into the alloca.
LLVMBuildStore(Builder, arg, alloca);
// Add arguments to variable symbol table.
NamedValues[Args[index]] = alloca;
}
}
LLVMValueRef Codegen()
{
// Make the function type: double(double,double) etc.
LLVMTypeRef[] argTypes;
foreach(arg; Args)
{
argTypes ~= LLVMDoubleType();
}
auto ft = LLVMFunctionType(LLVMDoubleType(), argTypes.ptr, cast(uint)argTypes.length, false);
auto f = LLVMAddFunction(TheModule, Name.toStringz(), ft);
// If F conflicted, there was already something named 'Name'. If it has a
// body, don't allow redefinition or reextern.
if(to!string(LLVMGetValueName(f)) != Name)
{
// Delete the one we just made and get the existing one.
LLVMDeleteFunction(f);
f = LLVMGetNamedFunction(TheModule, Name.toStringz());
// If F already has a body, reject this.
if(LLVMCountBasicBlocks(f) > 0)
{
return ErrorV("Redefinition of function");
}
// If F took a different number of args, reject.
if(LLVMCountParams(f) != Args.length)
{
return ErrorV("Redefinition of function with differents number of arguments");
}
}
// Set names for all arguments
LLVMValueRef[] params;
params.length = LLVMCountParams(f);
LLVMGetParams(f, params.ptr);
foreach(index, arg; params)
{
LLVMSetValueName(arg, Args[index].toStringz());
}
return f;
}
private:
string Name;
string[] Args;
bool isOperator;
uint Precedence;
}
/// FunctionAST - This class represents a function definition itself.
class FunctionAST
{
public:
this(PrototypeAST proto, ExprAST _body)
{
Proto = proto;
Body = _body;
}
LLVMValueRef Codegen()
{
NamedValues.clear();
auto theFunction = Proto.Codegen();
if(theFunction is null)
{
return null;
}
// If this is an operator, install it.
if(Proto.isBinaryOp)
{
BinopPrecedence[cast(int)Proto.operatorName] = Proto.binaryPrecedence;
}
// Create a new basic block to start insertion into.
auto basicBlock = LLVMAppendBasicBlock(theFunction, "entry");
LLVMPositionBuilderAtEnd(Builder, basicBlock);
// Add all arguments to the symbol table and create their allocas.
Proto.CreateArgumentAllocas(theFunction);
auto returnValue = Body.Codegen();
if(returnValue)
{
//LLVMVerifyFunction(returnValue, LLVMVerifierFailureAction.PrintMessage);
// Finish off the function.
LLVMBuildRet(Builder, returnValue);
// Valide the generated code, checking for consistency.
LLVMVerifyFunction(theFunction, LLVMVerifierFailureAction.PrintMessage);
// Optimize the function.
LLVMRunFunctionPassManager(TheFPM, theFunction);
return theFunction;
}
// Error reading body, remove function.
LLVMDeleteFunction(theFunction);
if (Proto.isBinaryOp)
{
BinopPrecedence.remove(cast(int)Proto.operatorName);
}
return null;
}
private:
PrototypeAST Proto;
ExprAST Body;
}
/// IfExprAST - Expression class for if/then/else.
class IfExprAST : ExprAST
{
public:
this(ExprAST cond, ExprAST then, ExprAST _else)
{
Cond = cond;
Then = then;
Else = _else;
}
LLVMValueRef Codegen()
{
auto condV = Cond.Codegen();
if(condV is null)
{
return null;
}
// Convert condition to a bool by comparing equal to 0.0.
condV = LLVMBuildFCmp(Builder, LLVMRealPredicate.ONE, condV, LLVMConstReal(LLVMDoubleType(), 0.0), "ifcond");
auto theFunction = LLVMGetBasicBlockParent(LLVMGetInsertBlock(Builder));
// Create blocks for the then and else cases. Insert the 'then' block at the
// end of the function.
auto thenBB = LLVMAppendBasicBlock(theFunction, "then");
auto elseBB = LLVMAppendBasicBlock(theFunction, "else");
auto mergeBB = LLVMAppendBasicBlock(theFunction, "ifcont");
LLVMBuildCondBr(Builder, condV, thenBB, elseBB);
// Emit then value
LLVMPositionBuilderAtEnd(Builder, thenBB);
auto thenV = Then.Codegen();
if(thenV is null)
{
return null;
}
LLVMBuildBr(Builder, mergeBB);
// Codegen of 'Then' can change the current block, update thenBB for the PHI.
thenBB = LLVMGetInsertBlock(Builder);
// Emit else block
auto lastFunctionBlock = LLVMGetLastBasicBlock(theFunction);
LLVMMoveBasicBlockAfter(elseBB, lastFunctionBlock);
LLVMPositionBuilderAtEnd(Builder, elseBB);
auto elseV = Else.Codegen();
if(elseV is null)
{
return null;
}
LLVMBuildBr(Builder, mergeBB);
// Codegen of 'Else' can change the current block, update ElseBB for the PHI.
elseBB = LLVMGetInsertBlock(Builder);
// Emit merge block
lastFunctionBlock = LLVMGetLastBasicBlock(theFunction);
LLVMMoveBasicBlockAfter(mergeBB, lastFunctionBlock);
LLVMPositionBuilderAtEnd(Builder, mergeBB);
auto phiNode = LLVMBuildPhi(Builder, LLVMDoubleType(), "iftmp");
LLVMValueRef[2] incomingValues;
incomingValues[0] = thenV;
incomingValues[1] = elseV;
LLVMBasicBlockRef[2] incomingBlocks;
incomingBlocks[0] = thenBB;
incomingBlocks[1] = elseBB;
LLVMAddIncoming(phiNode, incomingValues.ptr, incomingBlocks.ptr, incomingValues.length);
return phiNode;
}
private:
ExprAST Cond, Then, Else;
}
/// ForExprAST - Expression class for for/in.
class ForExprAST : ExprAST
{
public:
this(string varName, ExprAST start, ExprAST end, ExprAST step, ExprAST _body)
{
VarName = varName;
Start = start;
End = end;
Step = step;
Body = _body;
}
LLVMValueRef Codegen()
{
// Output this as:
// var = alloca double
// ...
// start = startexpr
// store start -> var
// goto loop
// loop:
// ...
// bodyexpr
// ...
// loopend:
// step = stepexpr
// endcond = endexpr
//
// curvar = load var
// nextvar = curvar + step
// store nextvar -> var
// br endcond, loop, endloop
// outloop:
// Make the new basic block for the loop header, inserting after current block.
auto theFunction = LLVMGetBasicBlockParent(LLVMGetInsertBlock(Builder));
// Create an alloca for the variable in the entry block
auto alloca = CreateEntryBlockAlloca(theFunction, VarName);
// Emit the start code first, without 'variable in scope
auto startVal = Start.Codegen();
if(startVal is null)
{
return null;
}
// Store the value into the alloca
LLVMBuildStore(Builder, startVal, alloca);
// Make the new basic block for the loop header, inserting after current
// block.
auto loopBB = LLVMAppendBasicBlock(theFunction, "loop");
// Insert an explicit fall through from the current block to the loopBB
LLVMBuildBr(Builder, loopBB);
// Start insertion in loopBB
LLVMPositionBuilderAtEnd(Builder, loopBB);
// Within the loop, the variable is definied equal to the PHI node.
// If it shadows an existing variable, we have to restore it, so save it now.
LLVMValueRef oldVal = null;
if(VarName in NamedValues)
{
oldVal = NamedValues[VarName];
}
NamedValues[VarName] = alloca;
// Emit the body of the loop. This, like any other expr, can change the current BB.
// Note that we ignore the value computed by the body, but don't allow an error.
if(Body.Codegen() is null)
{
return null;
}
// Emit the step value.
LLVMValueRef stepVal;
if(Step)
{
stepVal = Step.Codegen();
if(stepVal)
{
return null;
}
}
else
{
stepVal = LLVMConstReal(LLVMDoubleType(), 1.0);
}
// Compute the end condition.
auto endCond = End.Codegen();
if(endCond is null)
{
return null;
}
// Reload, increment, and restore the alloca.
// This handles the case where the body of the loop mutates the variable.
auto curVar = LLVMBuildLoad(Builder, alloca, "curvar");
auto nextVar = LLVMBuildFAdd(Builder, curVar, stepVal, "nextvar");
LLVMBuildStore(Builder, nextVar, alloca);
// Convert condition to a bool by comparing equal to 0.0.
endCond = LLVMBuildFCmp(Builder, LLVMRealPredicate.ONE, endCond, LLVMConstReal(LLVMDoubleType(), 0.0), "loopcond");
// Create the "after loop" block and insert it.
auto afterBB = LLVMAppendBasicBlock(theFunction, "afterloop");
// Insert the conditional branch into the end of loopEndBB
LLVMBuildCondBr(Builder, endCond, loopBB, afterBB);
// Any new code will be inserted in afterBB
LLVMPositionBuilderAtEnd(Builder, afterBB);
// Restore the unshadowed variable.
if(oldVal)
{
NamedValues[VarName] = oldVal;
}
else
{
NamedValues.remove(VarName);
}
// For expr always returns 0.0
return LLVMConstReal(LLVMDoubleType(), 0.0);
}
private:
string VarName;
ExprAST Start, End, Step, Body;
}
/// UnaryExprAST - Expression class for a unary operator.
class UnaryExprAST : ExprAST
{
public:
this(char opcode, ExprAST operand)
{
Opcode = opcode;
Operand = operand;
}
LLVMValueRef Codegen()
{
auto operandV = Operand.Codegen();
string functionName = "unary" ~ Opcode;
auto f = LLVMGetNamedFunction(TheModule, functionName.toStringz());
if(f)
{
LLVMValueRef[] args;
return LLVMBuildCall(Builder, f, args.ptr, 0, "unop");
}
return ErrorV("Unknown unary operator");
}
private:
char Opcode;
ExprAST Operand;
}
alias Tuple!(string, ExprAST) VarExprTuple;
/// VarExprAST - Expression class for var/in
class VarExprAST : ExprAST
{
public:
this(VarExprTuple[] varNames, ExprAST _body)
{
VarNames = varNames;
Body = _body;
}
LLVMValueRef Codegen()
{
LLVMValueRef[string] oldBindings;
auto theFunction = LLVMGetBasicBlockParent(LLVMGetInsertBlock(Builder));
// Register all variable and emit their initializer
foreach(varExpr; VarNames)
{
string varName = varExpr[0];
ExprAST init = varExpr[1];
// Emit the initializer before adding the variable to scope, this prevents
// the initializer from referencing the variable itself, and permits stuff
// like this:
// var a = 1 in
// var a = a in ... # refers to outer 'a'
LLVMValueRef initVal;
if(init)
{
initVal = init.Codegen();
if(initVal is null)
{
return null;
}
}
else
{
initVal = LLVMConstReal(LLVMDoubleType(), 0.0);
}
auto alloca = CreateEntryBlockAlloca(theFunction, varName);
LLVMBuildStore(Builder, initVal, alloca);
// Remember the old variable binding so that we can restore the binding when
// we unrecurse.
if(varName in NamedValues)
{
oldBindings[varName] = NamedValues[varName];
}
// Remember this binding
NamedValues[varName] = alloca;
}
// Codegen the body, now that all vars in scope.
auto bodyVal = Body.Codegen();
if(bodyVal is null)
{
return null;
}
// Pop all our variables from scope
foreach(varExpr; VarNames)
{
string varName = varExpr[0];
if(varName in oldBindings)
{
NamedValues[varName] = oldBindings[varName];
}
}
// Return the body computation.
return bodyVal;
}
private:
VarExprTuple[] VarNames;
ExprAST Body;
}
//===----------------------------------------------------------------------===//
// Parser
//===----------------------------------------------------------------------===//
/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
/// token the parser is looking at. getNextToken reads another token from the
/// lexer and updates CurTok with its results.
int CurTok;
int getNextToken()
{
CurTok = gettok();
return CurTok;
}
/// BinopPrecedence - This holds the precedence for each binary operator that is
/// defined.
int[int] BinopPrecedence;
/// GetTokPrecedence - Get the precedence of the pending binary operator token.
int GetTokPrecedence()
{
if(!isASCII(CurTok))
{
return -1;
}
if(!(CurTok in BinopPrecedence))
{
return -1;
}
// Make sure it's a declared binop.
int tokPrec = BinopPrecedence[CurTok];
if (tokPrec <= 0)
{
return -1;
}
return tokPrec;
}
/// Error* - These are little helper functions for error handling.
ExprAST Error(string str)
{
writeln("Error: ", str);
return null;
}
PrototypeAST ErrorP(string str)
{
Error(str);
return null;
}
FunctionAST ErrorF(string str)
{
Error(str);
return null;
}
LLVMValueRef ErrorV(string str)
{
Error(str);
return null;
}
/// numberexpr ::= number
ExprAST ParseNumberExpr()
{
ExprAST result = new NumberExprAST(NumVal);
getNextToken(); // consume the number
return result;
}
/// parenexpr ::= '(' expression ')'
ExprAST ParseParenExpr()
{
getNextToken(); // Eat (
ExprAST v = ParseExpression();
if(v is null)
{
return null;
}
if(CurTok != ')')
{
return Error("expected )");
}
getNextToken(); // Eat )
return v;
}
/// identifierexpr
/// ::= identifier
/// ::= identifier '(' expression* ')'
ExprAST ParseIdentifierExpr()
{
string IdName = IdentifierStr;
getNextToken(); // Eat identifier
if(CurTok != '(')
{
return new VariableExprAST(IdName);
}
// Call
getNextToken(); // eat (
ExprAST[] args;
if(CurTok != ')')
{
while(1)
{
ExprAST arg = ParseExpression();
if(arg is null)
{
return null;
}
args ~= arg;
if(CurTok == ')')
break;
if(CurTok != ',')
{
return Error("Expected ) or , in argument list");
}
getNextToken();
}
}
// Eat the )
getNextToken();
return new CallExprAST(IdName, args);
}
/// primary
/// ::= identifierexpr
/// ::= numberexpr
/// ::= parenexpr
/// ::= ifexpr
/// ::= forexpr
/// ::= varexpr
ExprAST ParsePrimary()
{
switch(CurTok)
{
case Token.tok_identifier:
return ParseIdentifierExpr();