-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathwnt_LangParser.cpp
1971 lines (1517 loc) · 50.5 KB
/
wnt_LangParser.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
/*=====================================================================
LangParser.cpp
--------------
Copyright Glare Technologies Limited 2016 -
File created by ClassTemplate on Wed Jun 11 02:56:20 2008
=====================================================================*/
#include "wnt_LangParser.h"
#include "wnt_Lexer.h"
#include "wnt_ASTNode.h"
#include "wnt_FunctionExpression.h"
#include "wnt_IfExpression.h"
#include "wnt_Diagnostics.h"
#include "wnt_VectorLiteral.h"
#include "wnt_ArrayLiteral.h"
#include "wnt_TupleLiteral.h"
#include "wnt_VArrayLiteral.h"
#include "wnt_Variable.h"
#include "wnt_LetASTNode.h"
#include "wnt_LetBlock.h"
#include "BuiltInFunctionImpl.h"
#include "utils/TestUtils.h"
#include "maths/mathstypes.h"
#include "utils/StringUtils.h"
#include "utils/ContainerUtils.h"
#include "utils/Parser.h"
#include "utils/ConPrint.h"
#include <assert.h>
#include <map>
using std::vector;
using std::string;
namespace Winter
{
LangParser::LangParser(bool floating_point_literals_default_to_double_, bool real_is_double_)
: floating_point_literals_default_to_double(floating_point_literals_default_to_double_),
real_is_double(real_is_double_)
{
comparison_tokens.push_back(DOUBLE_EQUALS_TOKEN);
comparison_tokens.push_back(NOT_EQUALS_TOKEN);
comparison_tokens.push_back(LEFT_ANGLE_BRACKET_TOKEN);
comparison_tokens.push_back(RIGHT_ANGLE_BRACKET_TOKEN);
comparison_tokens.push_back(LESS_EQUAL_TOKEN);
comparison_tokens.push_back(GREATER_EQUAL_TOKEN);
}
LangParser::~LangParser()
{
}
static const SrcLocation locationForParseInfo(ParseInfo& p)
{
if(p.i >= p.tokens.size())
return SrcLocation::invalidLocation();
return SrcLocation(p.tokens[p.i]->char_index, p.tokens[p.i]->num_chars, p.text_buffer);
}
static const SrcLocation prevTokenLoc(ParseInfo& p)
{
return SrcLocation(p.tokens[p.i - 1]->char_index, p.tokens[p.i - 1]->num_chars, p.text_buffer);
}
Reference<BufferRoot> LangParser::parseBuffer(const std::vector<Reference<TokenBase> >& tokens,
const SourceBufferRef& source_buffer,
bool check_structures_exist,
std::map<std::string, TypeVRef>& named_types,
std::vector<TypeVRef>& named_types_ordered_out,
int& order_num)
{
Reference<BufferRoot> root = new BufferRoot(SrcLocation(0, 0, source_buffer.getPointer()));
ParseInfo parseinfo(tokens, named_types, root->top_level_defs, order_num, check_structures_exist);
parseinfo.text_buffer = source_buffer.getPointer();
// NEW: go through buffer and see if there is a 'else' token
/*for(size_t z=0; z<tokens.size(); ++z)
if(tokens[z]->getType() == IDENTIFIER_TOKEN && tokens[z]->getIdentifierValue() == "else")
{
parseinfo.else_token_present = true;
break;
}*/
while(parseinfo.i < tokens.size())
{
if(tokens[parseinfo.i]->isIdentifier() && tokens[parseinfo.i]->getIdentifierValue() == "def")
{
root->top_level_defs.push_back(parseFunctionDefinition(parseinfo));
parseinfo.generic_type_params.clear();
parseinfo.order_num++;
}
else if(tokens[parseinfo.i]->isIdentifier() && tokens[parseinfo.i]->getIdentifierValue() == "struct")
{
const size_t struct_char_position = tokens[parseinfo.i]->char_index;
const size_t struct_num_chars = tokens[parseinfo.i]->num_chars;
VRef<StructureType> t = parseStructType(parseinfo);
if(named_types.find(t->name) != named_types.end())
throw LangParserExcep("struct with name '" + t->name + "' already defined: ", errorPosition(*parseinfo.text_buffer, struct_char_position, struct_num_chars));
named_types.insert(std::make_pair(t->name, t));
named_types_ordered_out.push_back(t);
// Make constructor function for this structure
vector<FunctionDefinition::FunctionArg> args;
args.reserve(t->component_types.size());
for(unsigned int z=0; z<t->component_types.size(); ++z)
args.push_back(FunctionDefinition::FunctionArg(t->component_types[z], t->component_names[z]));
FunctionDefinitionRef cons = new FunctionDefinition(
SrcLocation::invalidLocation(),
parseinfo.order_num, // order number
t->name, // name
args, // arguments
ASTNodeRef(), // body expr
t, // declard return type
new Constructor(t) // built in func impl.
);
root->top_level_defs.push_back(cons);
// Make field access functions
vector<FunctionDefinition::FunctionArg> getfield_args;
getfield_args.push_back(FunctionDefinition::FunctionArg(t, "s"));
for(unsigned int z=0; z<t->component_types.size(); ++z)
{
FunctionDefinitionRef def = new FunctionDefinition(
SrcLocation::invalidLocation(),
parseinfo.order_num, // order number
t->component_names[z], // name
getfield_args, // args
ASTNodeRef(), // body expr
t->component_types[z], // return type
new GetField(t, z) // impl
);
root->top_level_defs.push_back(def);
}
parseinfo.order_num++;
}
else if(tokens[parseinfo.i]->isIdentifier())
{
// Parse named constant, e.g. "DOZEN = 12"
root->top_level_defs.push_back(parseNamedConstant(parseinfo));
parseinfo.order_num++;
}
else
throw LangParserExcep("Expected 'def'.", errorPosition(parseinfo));
}
// Update order_num
order_num = parseinfo.order_num;
return root;
}
const std::string LangParser::parseIdentifier(const std::string& id_type, ParseInfo& p)
{
if(p.i >= p.tokens.size())
throw LangParserExcep("End of buffer before " + id_type + " identifier.", errorPosition(p));
if(!p.tokens[p.i]->isIdentifier())
throw LangParserExcep("Expected " + id_type + " identifier.", errorPosition(p));
return p.tokens[p.i++]->getIdentifierValue();
}
void LangParser::parseAndCheckIdentifier(const std::string& target_id, ParseInfo& p)
{
if(p.i >= p.tokens.size())
throw LangParserExcep("End of buffer before " + target_id + " identifier.", errorPosition(p));
if(!p.tokens[p.i]->isIdentifier())
throw LangParserExcep("Expected identifier '" + target_id + "'.", errorPosition(p));
if(p.tokens[p.i]->getIdentifierValue() != target_id)
throw LangParserExcep("Expected identifier '" + target_id + "'.", errorPosition(p));
p.i++;
}
// TODO: this should probably be a virtual method on TokenBase.
static const std::string tokenDescription(const Reference<TokenBase>& token)
{
switch(token->getType())
{
case FLOAT_LITERAL_TOKEN:
return "float literal '" + toString(token->getFloatLiteralValue()) + "'";
case INT_LITERAL_TOKEN:
return "int literal '" + toString(token->getIntLiteralValue()) + "'";
case BOOL_LITERAL_TOKEN:
return "bool literal '" + boolToString(token->getBoolLiteralValue()) + "'";
case STRING_LITERAL_TOKEN:
return "string literal '" + token->getStringLiteralValue() + "'";
case CHAR_LITERAL_TOKEN:
return "char literal '" + token->getCharLiteralValue() + "'";
case IDENTIFIER_TOKEN:
return "identifier '" + token->getIdentifierValue() + "'";
default:
return tokenName(token->getType());
};
}
void LangParser::parseToken(unsigned int token_type, ParseInfo& p)
{
if(p.i >= p.tokens.size())
throw LangParserExcep("End of buffer before " + tokenName(token_type) + " token.", errorPosition(p));
if(p.tokens[p.i]->getType() != token_type)
throw LangParserExcep("Expected " + tokenName(token_type) + ", found " + tokenDescription(p.tokens[p.i]) + ".", errorPosition(p));
p.i++;
}
static inline bool isTokenCurrent(unsigned int token_type, ParseInfo& p)
{
return p.i < p.tokens.size() && p.tokens[p.i]->getType() == token_type;
}
static inline void skipExpectedToken(unsigned int token_type, ParseInfo& p)
{
assert(isTokenCurrent(token_type, p));
p.i++;
}
/*ASTNodeRef LangParser::parseFieldExpression(ParseInfo& p)
{
ASTNodeRef left = parseArraySubscriptExpression(p);
while(isTokenCurrent(DOT_TOKEN, p))
{
SrcLocation src_loc = locationForParseInfo(p);
parseToken(DOT_TOKEN, p);
const std::string field_name = parseIdentifier("field name", p);
FunctionExpressionRef func_expr = new FunctionExpression(src_loc);
func_expr->function_name = field_name;
func_expr->argument_expressions.push_back(left);
left = func_expr;
}
return left;
}*/
#if 0
ASTNodeRef LangParser::parseFieldExpression(ParseInfo& p)
{
if(p.i >= p.tokens.size())
throw LangParserExcep("End of buffer while parsing field expression.");
ASTNodeRef var_expression;
if(p.tokens[p.i]->getType() == IDENTIFIER_TOKEN && p.tokens[p.i]->getIdentifierValue() == "if")
{
var_expression = parseIfExpression(p);
}
else
{
// If next token is a '(', then this is a function expression
if(p.i + 1 < p.tokens.size() && p.tokens[p.i+1]->getType() == OPEN_PARENTHESIS_TOKEN)
var_expression = parseFunctionExpression(p);
else
{
var_expression = parseVariableExpression(p);
}
}
while(isTokenCurrent(DOT_TOKEN, p))
{
SrcLocation src_loc = locationForParseInfo(p);
skipExpectedToken(DOT_TOKEN, p);
const std::string field_name = parseIdentifier("field name", p);
FunctionExpressionRef func_expr = new FunctionExpression(src_loc);
func_expr->function_name = field_name;
func_expr->argument_expressions.push_back(var_expression);
var_expression = func_expr;
}
/*
a.b.c
->
c(b(a))
->
c
|
b
|
a
*/
return var_expression;
}
#endif
/*
There are several forms of if to parse:
New form with optional 'then':
if a then b else c
if a b else c
old form:
if(a, b, c)
New form may also happen to have parens at the start of condition expression:
if (x < 5) then b else c
if (x * 2) < 5 then b else c
*/
ASTNodeRef LangParser::parseIfExpression(ParseInfo& p)
{
const SrcLocation loc = locationForParseInfo(p);
parseAndCheckIdentifier("if", p);
if(p.i >= p.tokens.size())
throw LangParserExcep("End of buffer while parsing if expression.", errorPosition(p));
if(p.tokens[p.i]->getType() == OPEN_PARENTHESIS_TOKEN)
{
unsigned int open_paren_pos = p.i;
skipExpectedToken(OPEN_PARENTHESIS_TOKEN, p);
// We are either parsing an old form of if: 'if(a, b, c)', or the new form with the condition expression in parens: 'if (a) then b else c' or 'if (a_0) binop a_1 then b else c'
// We can distinguish the two by parsing the condition 'a', then seeing if the next token is ','.
// Parse condition
ASTNodeRef condition = parseExpression(p);
if(p.i >= p.tokens.size())
throw LangParserExcep("End of buffer while parsing if expression.", errorPosition(p));
if(p.tokens[p.i]->getType() == COMMA_TOKEN)
{
// We are parsing the old form of if.
skipExpectedToken(COMMA_TOKEN, p);
// Parse then expression
ASTNodeRef then_expr = parseExpression(p);
parseToken(COMMA_TOKEN, p);
// Parse else expression
ASTNodeRef else_expr = parseExpression(p);
parseToken(CLOSE_PARENTHESIS_TOKEN, p);
return new IfExpression(loc, condition, then_expr, else_expr);
}
else
{
// We are parsing the new form of if.
// Go back and parse condition expression again.
p.i = open_paren_pos;
assert(p.tokens[p.i]->getType() == OPEN_PARENTHESIS_TOKEN);
// Parse condition
condition = parseExpression(p);
// Parse optional 'then'
if(p.i < p.tokens.size() && p.tokens[p.i]->isIdentifier() && p.tokens[p.i]->getIdentifierValue() == "then")
parseAndCheckIdentifier("then", p);
// Parse then expression
ASTNodeRef then_expr = parseExpression(p);
// Parse mandatory 'else'
parseAndCheckIdentifier("else", p);
// Parse else expression
ASTNodeRef else_expr = parseExpression(p);
return new IfExpression(loc, condition, then_expr, else_expr);
}
}
else
{
// No opening '(', so we are parsing the new form of if.
// Parse condition
ASTNodeRef condition = parseExpression(p);
// Parse optional 'then'
if(p.i < p.tokens.size() && p.tokens[p.i]->isIdentifier() && p.tokens[p.i]->getIdentifierValue() == "then")
parseAndCheckIdentifier("then", p);
// Parse then expression
ASTNodeRef then_expr = parseExpression(p);
// Parse mandatory 'else'
parseAndCheckIdentifier("else", p);
// Parse else expression
ASTNodeRef else_expr = parseExpression(p);
return new IfExpression(loc, condition, then_expr, else_expr);
}
}
ASTNodeRef LangParser::parseVariableExpression(ParseInfo& p)
{
const SrcLocation loc = locationForParseInfo(p);
const std::string name = parseIdentifier("variable name", p);
if(isKeyword(name))
throw LangParserExcep("Cannot call a variable '" + name + "' - is a keyword. ", errorPositionPrevToken(p));
return new Variable(name, loc);
}
bool LangParser::isKeyword(const std::string& name)
{
return
name == "let" ||
name == "def" ||
name == "in" ||
name == "fn";
// TODO: finish
}
Reference<FunctionDefinition> LangParser::parseFunctionDefinition(ParseInfo& p)
{
parseAndCheckIdentifier("def", p);
const std::string function_name = parseIdentifier("function name", p);
return parseFunctionDefinitionGivenName(function_name, p, /*is_lambda=*/false);
}
FunctionDefinitionRef LangParser::parseFunctionDefinitionGivenName(const std::string& func_name, ParseInfo& p, bool is_lambda)
{
try
{
SrcLocation loc = prevTokenLoc(p);
// Parse generic parameters, if present
std::vector<std::string> generic_type_param_names;
p.generic_type_params.resize(0);
if(isTokenCurrent(LEFT_ANGLE_BRACKET_TOKEN, p))
{
skipExpectedToken(LEFT_ANGLE_BRACKET_TOKEN, p);
const std::string type_param_name = parseIdentifier("type parameter", p);
generic_type_param_names.push_back(type_param_name);
p.generic_type_params.push_back(type_param_name);
while(isTokenCurrent(COMMA_TOKEN, p))
{
skipExpectedToken(COMMA_TOKEN, p);
const std::string type_param_name2 = parseIdentifier("type parameter", p);
generic_type_param_names.push_back(type_param_name2);
p.generic_type_params.push_back(type_param_name2);
}
parseToken(RIGHT_ANGLE_BRACKET_TOKEN, p);
}
// Parse parameter list
std::vector<FunctionDefinition::FunctionArg> args;
parseParameterList(p, args);
// Fill in generic_type_param_index for all generic types
//for(unsigned int i=0; i<args.size(); ++i)
// for(unsigned int z=0; z<generic_type_params.size(); ++z)
// if(generic_type_params[z] == args[i].
//parseToken(tokens, text_buffer, Token::RIGHT_ARROW, i);
// Parse function attributes.
bool noinline = false;
bool opencl_noinline = false;
if(isTokenCurrent(EXCLAMATION_MARK_TOKEN, p))
{
skipExpectedToken(EXCLAMATION_MARK_TOKEN, p);
const std::string attribute = parseIdentifier("attribute", p);
if(attribute == "noinline")
noinline = true;
else if(attribute == "opencl_noinline")
opencl_noinline = true;
else
throw LangParserExcep("Error occurred while parsing function '" + func_name + "': unknown attribute '" + attribute + "'", errorPosition(p));
}
// Parse optional return type
TypeRef return_type(NULL);
if(is_lambda)
{
// Both ':' and '->' are acceptable after the arg list
if(!(isTokenCurrent(COLON_TOKEN, p) || isTokenCurrent(RIGHT_ARROW_TOKEN, p)))
return_type = parseType(p);
if(isTokenCurrent(COLON_TOKEN, p))
skipExpectedToken(COLON_TOKEN, p);
else if(isTokenCurrent(RIGHT_ARROW_TOKEN, p))
skipExpectedToken(RIGHT_ARROW_TOKEN, p);
else
throw LangParserExcep("Error occurred while parsing anon function: expected ':' or '->'", errorPosition(p));
}
else
{
if(!isTokenCurrent(COLON_TOKEN, p))
return_type = parseType(p);
parseToken(COLON_TOKEN, p);
}
// Parse function body
ASTNodeRef body = parseExpression(p);
Reference<FunctionDefinition> def = new FunctionDefinition(
loc,
p.order_num,
func_name,
args,
body,
return_type, // declared return type
NULL // built in func impl
);
def->generic_type_param_names = generic_type_param_names;
def->noinline = noinline;
def->opencl_noinline = opencl_noinline;
return def;
}
catch(LangParserExcep& e)
{
throw LangParserExcep("Error occurred while parsing function '" + func_name + "': " + e.what(), e.pos());
}
}
NamedConstantRef LangParser::parseNamedConstant(ParseInfo& p)
{
const SrcLocation src_loc = locationForParseInfo(p);
const unsigned int initial_pos = p.i;
std::string name = parseIdentifier("name", p);
TypeRef declared_type;
if(!isTokenCurrent(EQUALS_TOKEN, p))
{
// Then assume what we parsed was the optional type. So backtrack and re-parse
p.i = initial_pos; // backtrack
declared_type = parseType(p);
name = parseIdentifier("variable name", p);
}
parseToken(EQUALS_TOKEN, p);
const ASTNodeRef value_expr = parseExpression(p);
return new NamedConstant(declared_type, name, value_expr, src_loc, p.order_num);
}
/*Reference<ASTNode> LangParser::parseFunctionExpression(ParseInfo& p)
{
SrcLocation src_loc = locationForParseInfo(p);
const std::string func_name = parseIdentifier("function name", p);
// Parse parameter list
parseToken(OPEN_PARENTHESIS_TOKEN, p);
if(p.i == p.tokens.size())
throw LangParserExcep("Expected ')'");
std::vector<Reference<ASTNode> > arg_expressions;
FunctionExpressionRef expr = new FunctionExpression(src_loc);
if(p.tokens[p.i]->getType() != CLOSE_PARENTHESIS_TOKEN)
{
arg_expressions.push_back(parseExpression(p));
}
while(p.i < p.tokens.size() && p.tokens[p.i]->getType() != CLOSE_PARENTHESIS_TOKEN)//isTokenCurrent(CLOSE_PARENTHESIS_TOKEN, p)) //p.tokens[p.i]->getType() != CLOSE_PARENTHESIS_TOKEN)
{
parseToken(COMMA_TOKEN, p);
arg_expressions.push_back(parseExpression(p));
}
parseToken(CLOSE_PARENTHESIS_TOKEN, p);
expr->argument_expressions = arg_expressions;
expr->function_name = func_name;
return expr;
}*/
/*
Reference<ASTNode> LangParser::parseFunctionDeclaration(const std::vector<Reference<TokenBase> >& tokens, const char* text_buffer, unsigned int& i)
{
Reference<ASTNode> node( new ASTNode(ASTNode::FUNCTION_DECLARATION) );
parseIdentifier("declare", tokens, text_buffer, i);
node->function_def_name = parseIdentifier("function name", tokens, text_buffer, i);
// Parse parameter list
parseToken(tokens, text_buffer, OPEN_PARENTHESIS_TOKEN, i);
while(1)
{
const std::string param_type = parseIdentifier("parameter type", tokens, text_buffer, i);
const std::string param_name = parseIdentifier("parameter name", tokens, text_buffer, i);
node->function_def_args.push_back(Argument());
node->function_def_args.back().type = param_type;
node->function_def_args.back().name = param_name;
if(i >= tokens.size())
{
throw LangParserExcep("End of buffer before end of parameter list.");
}
else if(tokens[i].type == Token::CLOSE_PARENTHESIS)
{
i++;
break;
}
else if(tokens[i].type == Token::COMMA)
{
i++;
}
else
{
throw LangParserExcep("Expected ',' or ')' while parsing parameter list of function '" + node->function_def_name + "'" + errorPosition(text_buffer, tokens[i].char_index));
}
}
//parseToken(tokens, text_buffer, Token::RIGHT_ARROW, i);
// Parse return type
node->function_def_return_type = parseIdentifier("return type", tokens, text_buffer, i);
return node;
}*/
ASTNodeRef LangParser::parseLiteral(ParseInfo& p)
{
SrcLocation loc = locationForParseInfo(p);
if(p.i >= p.tokens.size())
throw LangParserExcep("End of buffer while parsing literal.", errorPosition(p));
if(p.tokens[p.i]->getType() == INT_LITERAL_TOKEN)
{
const IntLiteralToken* token = static_cast<const IntLiteralToken*>(p.tokens[p.i].getPointer());
ASTNodeRef n = new IntLiteral(token->getIntLiteralValue(), token->num_bits, token->is_signed, loc);
p.i++;
return n;
}
else if(p.tokens[p.i]->getType() == FLOAT_LITERAL_TOKEN)
{
if(static_cast<FloatLiteralToken*>(p.tokens[p.i].getPointer())->suffix == 'f')
return new FloatLiteral((float)p.tokens[p.i++]->getFloatLiteralValue(), loc);
else if(static_cast<FloatLiteralToken*>(p.tokens[p.i].getPointer())->suffix == 'd')
return new DoubleLiteral(p.tokens[p.i++]->getFloatLiteralValue(), loc);
else
{
// no suffix:
if(floating_point_literals_default_to_double)
return new DoubleLiteral(p.tokens[p.i++]->getFloatLiteralValue(), loc);
else
return new FloatLiteral((float)p.tokens[p.i++]->getFloatLiteralValue(), loc);
}
}
else if(p.tokens[p.i]->getType() == STRING_LITERAL_TOKEN)
{
return new StringLiteral(p.tokens[p.i++]->getStringLiteralValue(), loc);
}
else if(p.tokens[p.i]->getType() == CHAR_LITERAL_TOKEN)
{
return new CharLiteral(p.tokens[p.i++]->getCharLiteralValue(), loc);
}
else if(p.tokens[p.i]->getType() == BOOL_LITERAL_TOKEN)
{
return new BoolLiteral(p.tokens[p.i++]->getBoolLiteralValue(), loc);
}
else
{
throw LangParserExcep("token is not a literal", errorPosition(p));
}
}
Reference<IntLiteral> LangParser::parseIntLiteral(ParseInfo& p)
{
SrcLocation loc = locationForParseInfo(p);
if(p.i >= p.tokens.size())
throw LangParserExcep("End of buffer while parsing int literal.", errorPosition(p));
if(p.tokens[p.i]->getType() == INT_LITERAL_TOKEN)
{
const IntLiteralToken* token = static_cast<const IntLiteralToken*>(p.tokens[p.i].getPointer());
Reference<IntLiteral> n = new IntLiteral(token->getIntLiteralValue(), token->num_bits, token->is_signed, loc);
p.i++;
return n;
}
else
{
throw LangParserExcep("token is not an integer literal.", errorPosition(p));
}
}
Reference<ASTNode> LangParser::parseLetBlock(ParseInfo& p)
{
if(p.i < p.tokens.size() && p.tokens[p.i]->isIdentifier() && p.tokens[p.i]->getIdentifierValue() == "let")
{
SrcLocation loc = locationForParseInfo(p);
p.i++;
vector<Reference<LetASTNode> > lets;
while(p.i < p.tokens.size() && !(p.tokens[p.i]->isIdentifier() && p.tokens[p.i]->getIdentifierValue() == "in"))
{
const unsigned int let_token_i = p.i;
Reference<LetASTNode> let = parseLet(p);
// Before we add it, go back over the other lets in the let block to make sure this name is unique.
for(size_t z=0; z<lets.size(); ++z)
for(size_t w=0; w<let->vars.size(); ++w)
for(size_t t=0; t<lets[z]->vars.size(); ++t)
if(lets[z]->vars[t].name == let->vars[w].name)
throw LangParserExcep("Let with the name '" + lets[z]->vars[t].name + "' already defined in let block.", errorPosition(*p.text_buffer, p.tokens[let_token_i]->char_index, p.tokens[let_token_i]->num_chars));
lets.push_back(let);
}
parseAndCheckIdentifier("in", p);
ASTNodeRef main_expr = parseExpression(p);
return new LetBlock(main_expr, lets, loc);
}
return parseTernaryConditionalExpression(p);
}
ASTNodeRef LangParser::parseExpression(ParseInfo& p)
{
return parseLetBlock(p);
}
// A basic expression is a literal, or a variable, or an if expression
ASTNodeRef LangParser::parseBasicExpression(ParseInfo& p)
{
if(p.i >= p.tokens.size())
throw LangParserExcep("End of buffer while parsing basic expression.", errorPosition(p));
SrcLocation loc = locationForParseInfo(p);
if(isTokenCurrent(OPEN_PARENTHESIS_TOKEN, p))
{
// Parse parenthesised expression
skipExpectedToken(OPEN_PARENTHESIS_TOKEN, p);
if(isTokenCurrent(CLOSE_PARENTHESIS_TOKEN, p))
{
// Then this is an empty tuple, which we won't allow
throw LangParserExcep("Empty tuples not allowed.", errorPosition(p));
}
const ASTNodeRef e = parseExpression(p);
if(isTokenCurrent(COMMA_TOKEN, p)) // If there is a comma here, we are parsing a tuple, e.g. "(1, 2)"
{
skipExpectedToken(COMMA_TOKEN, p);
vector<ASTNodeRef> tuple_elems(1, e);
while(1)
{
tuple_elems.push_back(parseExpression(p));
if(isTokenCurrent(CLOSE_PARENTHESIS_TOKEN, p))
{
// done.
skipExpectedToken(CLOSE_PARENTHESIS_TOKEN, p);
return new TupleLiteral(tuple_elems, loc);
}
else if(isTokenCurrent(COMMA_TOKEN, p))
{
skipExpectedToken(COMMA_TOKEN, p);
}
else
throw LangParserExcep("Unexpected token while parsing tuple.", errorPosition(p));
}
}
parseToken(CLOSE_PARENTHESIS_TOKEN, p);
return e;
}
else if(p.tokens[p.i]->isLiteral())
{
return parseLiteral(p);
}
else if(p.tokens[p.i]->isIdentifier())
{
if(p.tokens[p.i]->getIdentifierValue() == "if")
return parseIfExpression(p);
else
return parseVariableExpression(p);
}
/*TEMP else if(p.tokens[p.i]->getType() == OPEN_BRACE_TOKEN)
{
return parseMapLiteralExpression(p);
}*/
else if(p.tokens[p.i]->getType() == OPEN_SQUARE_BRACKET_TOKEN)
{
return parseArrayOrVectorOrTupleLiteral(p);
}
else if(p.tokens[p.i]->getType() == BACK_SLASH_TOKEN)
{
return parseAnonFunction(p);
}
else
{
throw LangParserExcep("Expected literal or identifier in expression.", errorPosition(p));
}
}
TypeVRef LangParser::parseSumType(ParseInfo& p)
{
TypeVRef t = parseElementaryType(p);
if(!isTokenCurrent(OR_TOKEN, p))
return t;
vector<TypeVRef> types(1, t);
while(isTokenCurrent(OR_TOKEN, p))
{
skipExpectedToken(OR_TOKEN, p);
types.push_back(parseElementaryType(p));
}
return new SumType(types);
}
TypeVRef LangParser::parseType(ParseInfo& p)
{
return parseSumType(p);
}
TypeVRef LangParser::parseElementaryType(ParseInfo& p)
{
std::string t = parseIdentifier("type", p);
// Handle optional address space qualifier for type.
std::string address_space;
if(t == "constant" || t == "global" || t == "__constant" || t == "__global")
{
address_space = t;
t = parseIdentifier("type", p);
}
if(t == "float")
return new Float();
else if(t == "double")
return new Double();
else if(t == "real")
{
if(real_is_double)
return new Double();
else
return new Float();
}
else if(t == "int")
return new Int(32);
else if(t == "int16")
return new Int(16);
else if(t == "int32")
return new Int(32);
else if(t == "int64")
return new Int(64);
else if(t == "uint")
return new Int(32, /*signed=*/false);
else if(t == "uint16")
return new Int(16, /*signed=*/false);
else if(t == "uint32")
return new Int(32, /*signed=*/false);
else if(t == "uint64")
return new Int(64, /*signed=*/false);
else if(t == "string")
return new String();
else if(t == "char")
return new CharType();
else if(t == "opaque" || t == "voidptr")
{
TypeVRef the_type = new OpaqueType();
the_type->address_space = address_space;
return the_type;
}
else if(t == "bool")
return new Bool();
//else if(t == "error")
// return new ErrorType();
else if(t == "map")
return parseMapType(p);
else if(t == "array")
{
TypeVRef the_type = parseArrayType(p);
the_type->address_space = address_space;
return the_type;
}
else if(t == "varray")
return parseVArrayType(p);
else if(t == "function")
return parseFunctionType(p);
else if(t == "vector")
return parseVectorType(p);
else if(t == "tuple")
return parseTupleType(p);
else
{
// Then this might be the name of a named type.
// So look up the named type map
std::map<std::string, TypeVRef>::const_iterator res = p.named_types.find(t);
if(res == p.named_types.end())
{
// Not a named type, maybe it is a type parameter
for(unsigned int i=0; i<p.generic_type_params.size(); ++i)
if(t == p.generic_type_params[i])
return new GenericType(t, i);
// If it wasn't a generic type, then it's completely unknown, like a rolling stone.
if(p.check_structures_exist)
throw LangParserExcep("Unknown type '" + t + "'.", errorPositionPrevToken(p));
else
{
//TypeVRef the_type = new OpaqueStructureType(t);
//the_type->address_space = address_space;
//return the_type;
TypeVRef the_type = new StructureType(t, std::vector<TypeVRef>(), std::vector<std::string>());
the_type->address_space = address_space;
return the_type;
}
}
else
{
// Type found, return it
(*res).second->address_space = address_space; // TEMP HACK