forked from dlang-community/libdparse
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.d
More file actions
9512 lines (9077 loc) · 308 KB
/
parser.d
File metadata and controls
9512 lines (9077 loc) · 308 KB
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
// Written in the D programming language
module dparse.parser;
import dparse.ast;
import dparse.lexer;
import dparse.rollback_allocator;
import dparse.stack_buffer;
import std.algorithm;
import std.array;
import std.conv;
import std.experimental.allocator;
import std.experimental.allocator.mallocator;
import std.string : format;
// Uncomment this if you want ALL THE OUTPUT
// Caution: generates 180 megabytes of logging for std.datetime
//version = dparse_verbose;
/**
* Prototype for a custom parser message function or delegate.
* Parameters passed are a file name, a line, a column, a message and a `bool`
* that indicates if the message is a warning (`false`) or a if it's an error (`true`).
*/
alias MessageFunction = void function(string fileName , size_t line, size_t column, string message, bool isError);
/// ditto
alias MessageDelegate = void delegate(string, size_t, size_t, string, bool);
/**
* Parser configuration struct
*/
struct ParserConfig
{
/// The tokens parsed by dparse.lexer.
const(Token)[] tokens;
/// The name of the file being parsed
string fileName;
/// A pointer to a rollback allocator.
RollbackAllocator* allocator;
/// An optional function used to handle warnings and errors.
MessageFunction messageFunction;
/// An optional delegate used to handle warnings and errors.
/// Set either this one or messageFunction, not both.
MessageDelegate messageDelegate;
/// An optional pointer to a variable receiving the error count.
uint* errorCount;
/// An optional pointer to a variable receiving the warning count.
uint* warningCount;
}
/**
* Params:
* parserConfig = a parser configuration.
* Returns:
* The parsed module.
*/
Module parseModule()(auto ref ParserConfig parserConfig)
{
auto parser = new Parser();
with (parserConfig)
{
parser.fileName = fileName;
parser.tokens = tokens;
parser.messageFunction = messageFunction;
parser.messageDelegate = messageDelegate;
parser.allocator = allocator;
}
Module mod = parser.parseModule();
with (parserConfig)
{
if (warningCount !is null)
*warningCount = parser.warningCount;
if (errorCount !is null)
*errorCount = parser.errorCount;
}
return mod;
}
/**
* Params:
* tokens = The tokens parsed by dparse.lexer.
* fileName = The name of the file being parsed.
* allocator = A pointer to a rollback allocator.
* messageFuncOrDg = Either a function or a delegate that receives the parser messages.
* errorCount = An optional pointer to a variable receiving the error count.
* warningCount = An optional pointer to a variable receiving the warning count.
* Returns:
* The parsed module.
*/
Module parseModule(F)(const(Token)[] tokens, string fileName, RollbackAllocator* allocator,
F messageFuncOrDg = null, uint* errorCount = null, uint* warningCount = null)
{
static if (is(F))
{
static if (is(F : MessageFunction))
return ParserConfig(tokens, fileName, allocator, messageFuncOrDg, null,
errorCount, warningCount).parseModule();
else static if (is(F : MessageDelegate))
return ParserConfig(tokens, fileName, allocator, null, messageFuncOrDg,
errorCount, warningCount).parseModule();
else static assert(0, "F must be a MessageFunction or a MessageDelegate");
}
else
{
return ParserConfig(tokens, fileName, allocator, null, null, null, null).parseModule();
}
}
/**
* D Parser.
*
* It is sometimes useful to sub-class Parser to skip over things that are not
* interesting. For example, DCD skips over function bodies when caching symbols
* from imported files.
*/
class Parser
{
/**
* Parses an AddExpression.
*
* $(GRAMMAR $(RULEDEF addExpression):
* $(RULE mulExpression)
* | $(RULE addExpression) $(LPAREN)$(LITERAL '+') | $(LITERAL'-') | $(LITERAL'~')$(RPAREN) $(RULE mulExpression)
* ;)
*/
ExpressionNode parseAddExpression()
{
pragma(inline, true);
mixin(traceEnterAndExit!(__FUNCTION__));
return parseLeftAssocBinaryExpression!(AddExpression, MulExpression,
tok!"+", tok!"-", tok!"~")();
}
/**
* Parses an AliasDeclaration.
*
* $(GRAMMAR $(RULEDEF aliasDeclaration):
* $(LITERAL 'alias') $(RULE aliasInitializer) $(LPAREN)$(LITERAL ',') $(RULE aliasInitializer)$(RPAREN)* $(LITERAL ';')
* | $(LITERAL 'alias') $(RULE storageClass)* $(RULE type) $(RULE declaratorIdentifierList) $(LITERAL ';')
* | $(LITERAL 'alias') $(RULE storageClass)* $(RULE type) $(RULE identifier) $(LITERAL '(') $(RULE parameters) $(LITERAL ')') $(memberFunctionAttribute)* $(LITERAL ';')
* ;)
*/
AliasDeclaration parseAliasDeclaration()
{
mixin(traceEnterAndExit!(__FUNCTION__));
auto startIndex = index;
auto node = allocator.make!AliasDeclaration;
mixin(tokenCheck!"alias");
node.comment = comment;
comment = null;
if (startsWith(tok!"identifier", tok!"=") || startsWith(tok!"identifier", tok!"("))
{
StackBuffer initializers;
do
{
if (!initializers.put(parseAliasInitializer()))
return null;
if (currentIs(tok!","))
advance();
else
break;
}
while (moreTokens());
ownArray(node.initializers, initializers);
}
else
{
StackBuffer storageClasses;
while (moreTokens() && isStorageClass())
if (!storageClasses.put(parseStorageClass()))
return null;
ownArray(node.storageClasses, storageClasses);
mixin (parseNodeQ!(`node.type`, `Type`));
mixin (parseNodeQ!(`node.declaratorIdentifierList`, `DeclaratorIdentifierList`));
if (currentIs(tok!"("))
{
mixin(parseNodeQ!(`node.parameters`, `Parameters`));
alias memberFunctionAttributes = storageClasses;
memberFunctionAttributes.clear();
while (moreTokens() && currentIsMemberFunctionAttribute())
if (!memberFunctionAttributes.put(parseMemberFunctionAttribute()))
return null;
ownArray(node.memberFunctionAttributes, memberFunctionAttributes);
}
}
return attachCommentFromSemicolon(node, startIndex);
}
/**
* Parses an AliasAssign.
*
* $(GRAMMAR $(RULEDEF aliasAssign):
* $(LITERAL Identifier) $(LITERAL '=') $(RULE type)
* ;)
*/
AliasAssign parseAliasAssign()
{
mixin(traceEnterAndExit!(__FUNCTION__));
auto startIndex = index;
auto node = allocator.make!AliasAssign;
node.comment = comment;
comment = null;
mixin(tokenCheck!(`node.identifier`, "identifier"));
mixin(tokenCheck!"=");
mixin(parseNodeQ!(`node.type`, `Type`));
return attachCommentFromSemicolon(node, startIndex);
}
/**
* Parses an AliasInitializer.
*
* $(GRAMMAR $(RULEDEF aliasInitializer):
* $(LITERAL Identifier) $(RULE templateParameters)? $(LITERAL '=') $(RULE storageClass)* $(RULE type)
* | $(LITERAL Identifier) $(RULE templateParameters)? $(LITERAL '=') $(RULE storageClass)* $(RULE type) $(RULE parameters) $(RULE memberFunctionAttribute)*
* | $(LITERAL Identifier) $(RULE templateParameters)? $(LITERAL '=') $(RULE functionLiteralExpression)
* ;)
*/
AliasInitializer parseAliasInitializer()
{
mixin(traceEnterAndExit!(__FUNCTION__));
auto startIndex = index;
auto node = allocator.make!AliasInitializer;
mixin (tokenCheck!(`node.name`, "identifier"));
if (currentIs(tok!"("))
mixin (parseNodeQ!(`node.templateParameters`, `TemplateParameters`));
mixin(tokenCheck!"=");
bool isFunction()
{
if (currentIsOneOf(tok!"function", tok!"delegate", tok!"{"))
return true;
if (startsWith(tok!"identifier", tok!"=>"))
return true;
const b = setBookmark();
scope(exit)
goToBookmark(b);
if (currentIs(tok!"(") || currentIs(tok!"ref") && peekIs(tok!"("))
{
if (currentIs(tok!"ref"))
advance();
const t = peekPastParens();
if (t !is null)
{
if (t.type == tok!"=>" || t.type == tok!"{"
|| isMemberFunctionAttribute(t.type))
return true;
}
}
return false;
}
if (isFunction)
mixin (parseNodeQ!(`node.functionLiteralExpression`, `FunctionLiteralExpression`));
else
{
StackBuffer storageClasses;
while (moreTokens() && isStorageClass())
if (!storageClasses.put(parseStorageClass()))
return null;
ownArray(node.storageClasses, storageClasses);
mixin (parseNodeQ!(`node.type`, `Type`));
if (currentIs(tok!"("))
{
mixin (parseNodeQ!(`node.parameters`, `Parameters`));
alias memberFunctionAttributes = storageClasses;
memberFunctionAttributes.clear();
while (moreTokens() && currentIsMemberFunctionAttribute())
if (!memberFunctionAttributes.put(parseMemberFunctionAttribute()))
return null;
ownArray(node.memberFunctionAttributes, memberFunctionAttributes);
}
}
node.tokens = tokens[startIndex .. index];
return node;
}
/**
* Parses an AliasThisDeclaration.
*
* $(GRAMMAR $(RULEDEF aliasThisDeclaration):
* $(LITERAL 'alias') $(LITERAL Identifier) $(LITERAL 'this') $(LITERAL ';')
* ;)
*/
AliasThisDeclaration parseAliasThisDeclaration()
{
mixin(traceEnterAndExit!(__FUNCTION__));
auto startIndex = index;
auto node = allocator.make!AliasThisDeclaration;
mixin(tokenCheck!"alias");
mixin(tokenCheck!(`node.identifier`, "identifier"));
mixin(tokenCheck!"this");
return attachCommentFromSemicolon(node, startIndex);
}
/**
* Parses an AlignAttribute.
*
* $(GRAMMAR $(RULEDEF alignAttribute):
* $(LITERAL 'align') ($(LITERAL '$(LPAREN)') $(RULE assignExpression) $(LITERAL '$(RPAREN)'))?
* ;)
*/
AlignAttribute parseAlignAttribute()
{
mixin(traceEnterAndExit!(__FUNCTION__));
auto startIndex = index;
auto node = allocator.make!AlignAttribute;
mixin(tokenCheck!"align");
if (currentIs(tok!"("))
{
mixin(tokenCheck!"(");
mixin(parseNodeQ!("node.assignExpression", "AssignExpression"));
mixin(tokenCheck!")");
}
node.tokens = tokens[startIndex .. index];
return node;
}
/**
* Parses an AndAndExpression.
*
* $(GRAMMAR $(RULEDEF andAndExpression):
* $(RULE orExpression)
* | $(RULE andAndExpression) $(LITERAL '&&') $(RULE orExpression)
* ;)
*/
ExpressionNode parseAndAndExpression()
{
pragma(inline, true);
mixin(traceEnterAndExit!(__FUNCTION__));
return parseLeftAssocBinaryExpression!(AndAndExpression, OrExpression,
tok!"&&")();
}
/**
* Parses an AndExpression.
*
* $(GRAMMAR $(RULEDEF andExpression):
* $(RULE cmpExpression)
* | $(RULE andExpression) $(LITERAL '&') $(RULE cmpExpression)
* ;)
*/
ExpressionNode parseAndExpression()
{
pragma(inline, true);
mixin(traceEnterAndExit!(__FUNCTION__));
return parseLeftAssocBinaryExpression!(AndExpression, CmpExpression,
tok!"&")();
}
/**
* Parses a NamedArgument.
*
* $(GRAMMAR $(RULEDEF namedArgument):
* ($(RULE identifer) $(LITERAL ':'))? $(RULE assignExpression)
* ;)
*/
NamedArgument parseNamedArgument()
{
mixin(traceEnterAndExit!(__FUNCTION__));
const startIndex = index;
auto node = allocator.make!NamedArgument;
const c = current();
node.startLocation = c.index;
if (startsWith(tok!"identifier", tok!":"))
{
// named argument
node.name = c;
advance(); // identifier
advance(); // :
}
mixin(parseNodeQ!("node.assignExpression", "AssignExpression"));
if (moreTokens) node.endLocation = current().index;
node.tokens = tokens[startIndex .. index];
return node;
}
/**
* Parses a NamedArgumentList.
*
* $(GRAMMAR $(RULEDEF namedArgumentList):
* $(RULE namedArgument) ($(LITERAL ',') $(RULE namedArgument)?)*
* ;)
*/
NamedArgumentList parseNamedArgumentList()
{
mixin(traceEnterAndExit!(__FUNCTION__));
auto startIndex = index;
if (!moreTokens)
{
error("argument list expected instead of EOF");
return null;
}
size_t startLocation = current().index;
auto node = parseCommaSeparatedRule!(NamedArgumentList, NamedArgument)(true);
mixin (nullCheck!`node`);
node.startLocation = startLocation;
if (moreTokens) node.endLocation = current().index;
node.tokens = tokens[startIndex .. index];
return node;
}
/**
* Parses an ArgumentList.
*
* $(GRAMMAR $(RULEDEF argumentList):
* $(RULE assignExpression) ($(LITERAL ',') $(RULE assignExpression)?)* $(LITERAL ',')?
* ;)
*/
ArgumentList parseArgumentList()
{
mixin(traceEnterAndExit!(__FUNCTION__));
auto startIndex = index;
if (!moreTokens)
{
error("argument list expected instead of EOF");
return null;
}
size_t startLocation = current().index;
auto node = parseCommaSeparatedRule!(ArgumentList, AssignExpression)(true);
mixin (nullCheck!`node`);
node.startLocation = startLocation;
if (moreTokens) node.endLocation = current().index;
node.tokens = tokens[startIndex .. index];
return node;
}
/**
* Parses Arguments.
*
* $(GRAMMAR $(RULEDEF arguments):
* $(LITERAL '$(LPAREN)') $(RULE namedArgumentList)? $(LITERAL '$(RPAREN)')
* ;)
*/
Arguments parseArguments()
{
mixin(traceEnterAndExit!(__FUNCTION__));
auto startIndex = index;
auto node = allocator.make!Arguments;
mixin(tokenCheck!"(");
if (!currentIs(tok!")"))
mixin (parseNodeQ!(`node.namedArgumentList`, `NamedArgumentList`));
mixin(tokenCheck!")");
node.tokens = tokens[startIndex .. index];
return node;
}
/**
* Parses an ArrayInitializer.
*
* $(GRAMMAR $(RULEDEF arrayInitializer):
* $(LITERAL '[') $(LITERAL ']')
* | $(LITERAL '[') $(RULE arrayMemberInitialization) ($(LITERAL ',') $(RULE arrayMemberInitialization)?)* $(LITERAL ']')
* ;)
*/
ArrayInitializer parseArrayInitializer()
{
mixin(traceEnterAndExit!(__FUNCTION__));
auto startIndex = index;
auto node = allocator.make!ArrayInitializer;
const open = expect(tok!"[");
mixin (nullCheck!`open`);
node.startLocation = open.index;
StackBuffer arrayMemberInitializations;
while (moreTokens())
{
if (currentIs(tok!"]"))
break;
if (!arrayMemberInitializations.put(parseArrayMemberInitialization()))
return null;
if (currentIs(tok!","))
advance();
else
break;
}
ownArray(node.arrayMemberInitializations, arrayMemberInitializations);
const close = expect(tok!"]");
mixin (nullCheck!`close`);
node.endLocation = close.index;
node.tokens = tokens[startIndex .. index];
return node;
}
/**
* Parses an ArrayLiteral.
*
* $(GRAMMAR $(RULEDEF arrayLiteral):
* $(LITERAL '[') $(RULE argumentList)? $(LITERAL ']')
* ;)
*/
ArrayLiteral parseArrayLiteral()
{
mixin(traceEnterAndExit!(__FUNCTION__));
auto startIndex = index;
auto node = allocator.make!ArrayLiteral;
mixin(tokenCheck!"[");
if (!currentIs(tok!"]"))
mixin (parseNodeQ!(`node.argumentList`, `ArgumentList`));
mixin(tokenCheck!"]");
node.tokens = tokens[startIndex .. index];
return node;
}
/**
* Parses an ArrayMemberInitialization.
*
* $(GRAMMAR $(RULEDEF arrayMemberInitialization):
* ($(RULE assignExpression) $(LITERAL ':'))? $(RULE nonVoidInitializer)
* ;)
*/
ArrayMemberInitialization parseArrayMemberInitialization()
{
mixin(traceEnterAndExit!(__FUNCTION__));
auto startIndex = index;
auto node = allocator.make!ArrayMemberInitialization;
switch (current.type)
{
case tok!"[":
immutable b = setBookmark();
skipBrackets();
if (currentIs(tok!":"))
{
goToBookmark(b);
mixin (parseNodeQ!(`node.assignExpression`, `AssignExpression`));
advance(); // :
mixin (parseNodeQ!(`node.nonVoidInitializer`, `NonVoidInitializer`));
break;
}
else
{
goToBookmark(b);
goto case;
}
case tok!"{":
mixin (parseNodeQ!(`node.nonVoidInitializer`, `NonVoidInitializer`));
break;
default:
auto assignExpression = parseAssignExpression();
mixin (nullCheck!`assignExpression`);
if (currentIs(tok!":"))
{
node.assignExpression = assignExpression;
advance();
mixin(parseNodeQ!(`node.nonVoidInitializer`, `NonVoidInitializer`));
}
else
{
node.nonVoidInitializer = allocator.make!NonVoidInitializer;
node.nonVoidInitializer.assignExpression = assignExpression;
node.nonVoidInitializer.tokens = assignExpression.tokens;
}
}
node.tokens = tokens[startIndex .. index];
return node;
}
/**
* Parses an AsmAddExp
*
* $(GRAMMAR $(RULEDEF asmAddExp):
* $(RULE asmMulExp)
* | $(RULE asmAddExp) ($(LITERAL '+') | $(LITERAL '-')) $(RULE asmMulExp)
* ;)
*/
ExpressionNode parseAsmAddExp()
{
pragma(inline, true);
mixin (traceEnterAndExit!(__FUNCTION__));
return parseLeftAssocBinaryExpression!(AsmAddExp, AsmMulExp,
tok!"+", tok!"-")();
}
/**
* Parses an AsmAndExp
*
* $(GRAMMAR $(RULEDEF asmAndExp):
* $(RULE asmEqualExp)
* | $(RULE asmAndExp) $(LITERAL '&') $(RULE asmEqualExp)
* ;)
*/
ExpressionNode parseAsmAndExp()
{
pragma(inline, true);
mixin (traceEnterAndExit!(__FUNCTION__));
return parseLeftAssocBinaryExpression!(AsmAndExp, AsmEqualExp, tok!"&");
}
/**
* Parses an AsmBrExp
*
* $(GRAMMAR $(RULEDEF asmBrExp):
* $(RULE asmUnaExp)
* | $(RULE asmBrExp)? $(LITERAL '[') $(RULE asmExp) $(LITERAL ']')
* ;)
*/
AsmBrExp parseAsmBrExp()
{
mixin(traceEnterAndExit!(__FUNCTION__));
auto startIndex = index;
if (!moreTokens)
{
error("Found end-of-file when expecting an AsmBrExp", false);
return null;
}
AsmBrExp node = allocator.make!AsmBrExp();
size_t line = current.line;
size_t column = current.column;
if (currentIs(tok!"["))
{
advance(); // [
mixin (parseNodeQ!(`node.asmExp`, `AsmExp`));
mixin(tokenCheck!"]");
if (currentIs(tok!"["))
goto brLoop;
}
else
{
mixin(parseNodeQ!(`node.asmUnaExp`, `AsmUnaExp`));
brLoop: while (currentIs(tok!"["))
{
AsmBrExp br = allocator.make!AsmBrExp(); // huehuehuehue
node.tokens = tokens[startIndex .. index];
br.asmBrExp = node;
br.line = current().line;
br.column = current().column;
node = br;
node.line = line;
node.column = column;
advance(); // [
mixin(parseNodeQ!(`node.asmExp`, `AsmExp`));
mixin(tokenCheck!"]");
}
}
node.tokens = tokens[startIndex .. index];
return node;
}
/**
* Parses an AsmEqualExp
*
* $(GRAMMAR $(RULEDEF asmEqualExp):
* $(RULE asmRelExp)
* | $(RULE asmEqualExp) ('==' | '!=') $(RULE asmRelExp)
* ;)
*/
ExpressionNode parseAsmEqualExp()
{
pragma(inline, true);
mixin(traceEnterAndExit!(__FUNCTION__));
return parseLeftAssocBinaryExpression!(AsmEqualExp, AsmRelExp, tok!"==", tok!"!=")();
}
/**
* Parses an AsmExp
*
* $(GRAMMAR $(RULEDEF asmExp):
* $(RULE asmLogOrExp) ($(LITERAL '?') $(RULE asmExp) $(LITERAL ':') $(RULE asmExp))?
* ;)
*/
ExpressionNode parseAsmExp()
{
mixin(traceEnterAndExit!(__FUNCTION__));
auto startIndex = index;
AsmExp node = allocator.make!AsmExp;
mixin(parseNodeQ!(`node.left`, `AsmLogOrExp`));
if (currentIs(tok!"?"))
{
advance();
mixin(parseNodeQ!(`node.middle`, `AsmExp`));
mixin(tokenCheck!":");
mixin(parseNodeQ!(`node.right`, `AsmExp`));
}
node.tokens = tokens[startIndex .. index];
return node;
}
/**
* Parses an AsmInstruction
*
* $(GRAMMAR $(RULEDEF asmInstruction):
* $(LITERAL Identifier)
* | $(LITERAL 'align') $(LITERAL IntegerLiteral)
* | $(LITERAL 'align') $(LITERAL Identifier)
* | $(LITERAL Identifier) $(LITERAL ':') $(RULE asmInstruction)
* | $(LITERAL Identifier) $(RULE operands)
* | $(LITERAL 'in') $(RULE operands)
* | $(LITERAL 'out') $(RULE operands)
* | $(LITERAL 'int') $(RULE operands)
* | $(LITERAL ';')
* ;)
*/
AsmInstruction parseAsmInstruction(ref bool maybeGccASm)
{
mixin (traceEnterAndExit!(__FUNCTION__));
auto startIndex = index;
AsmInstruction node = allocator.make!AsmInstruction;
if (currentIs(tok!";"))
{
warn("Empty asm instruction");
node.tokens = tokens[startIndex .. index];
return node;
}
if (currentIs(tok!"align"))
{
advance(); // align
node.hasAlign = true;
if (currentIsOneOf(tok!"intLiteral", tok!"identifier"))
{
node.identifierOrIntegerOrOpcode = advance();
if (!currentIs(tok!";"))
{
error("`;` expected after ASM align instruction.", true, true);
return null;
}
}
else
{
error("Identifier or integer literal expected.", true, true);
return null;
}
}
else if (currentIsOneOf(tok!"identifier", tok!"in", tok!"out", tok!"int"))
{
node.identifierOrIntegerOrOpcode = advance();
if (node.identifierOrIntegerOrOpcode == tok!"identifier" && currentIs(tok!":"))
{
advance(); // :
node.isLabel = true;
if (currentIs(tok!";"))
{
node.tokens = tokens[startIndex .. index];
return node;
}
node.asmInstruction = parseAsmInstruction(maybeGccASm);
if (node.asmInstruction is null) return null;
}
else if (!currentIs(tok!";"))
mixin(parseNodeQ!(`node.operands`, `Operands`));
}
else
{
maybeGccASm = true;
return null;
}
node.tokens = tokens[startIndex .. index];
return node;
}
/**
* Parses an AsmLogAndExp
*
* $(GRAMMAR $(RULEDEF asmLogAndExp):
* $(RULE asmOrExp)
* $(RULE asmLogAndExp) $(LITERAL '&&') $(RULE asmOrExp)
* ;)
*/
ExpressionNode parseAsmLogAndExp()
{
pragma(inline, true);
mixin (traceEnterAndExit!(__FUNCTION__));
return parseLeftAssocBinaryExpression!(AsmLogAndExp, AsmOrExp, tok!"&&");
}
/**
* Parses an AsmLogOrExp
*
* $(GRAMMAR $(RULEDEF asmLogOrExp):
* $(RULE asmLogAndExp)
* | $(RULE asmLogOrExp) '||' $(RULE asmLogAndExp)
* ;)
*/
ExpressionNode parseAsmLogOrExp()
{
pragma(inline, true);
mixin(traceEnterAndExit!(__FUNCTION__));
return parseLeftAssocBinaryExpression!(AsmLogOrExp, AsmLogAndExp, tok!"||")();
}
/**
* Parses an AsmMulExp
*
* $(GRAMMAR $(RULEDEF asmMulExp):
* $(RULE asmBrExp)
* | $(RULE asmMulExp) ($(LITERAL '*') | $(LITERAL '/') | $(LITERAL '%')) $(RULE asmBrExp)
* ;)
*/
ExpressionNode parseAsmMulExp()
{
pragma(inline, true);
mixin(traceEnterAndExit!(__FUNCTION__));
return parseLeftAssocBinaryExpression!(AsmMulExp, AsmBrExp, tok!"*", tok!"/", tok!"%")();
}
/**
* Parses an AsmOrExp
*
* $(GRAMMAR $(RULEDEF asmOrExp):
* $(RULE asmXorExp)
* | $(RULE asmOrExp) $(LITERAL '|') $(RULE asmXorExp)
* ;)
*/
ExpressionNode parseAsmOrExp()
{
pragma(inline, true);
mixin (traceEnterAndExit!(__FUNCTION__));
return parseLeftAssocBinaryExpression!(AsmOrExp, AsmXorExp, tok!"|")();
}
/**
* Parses an AsmPrimaryExp
*
* $(GRAMMAR $(RULEDEF asmPrimaryExp):
* $(LITERAL IntegerLiteral)
* | $(LITERAL FloatLiteral)
* | $(LITERAL StringLiteral)
* | $(RULE register)
* | $(RULE register : AsmExp)
* | $(RULE identifierChain)
* | $(LITERAL '$')
* | $(LITERAL 'this')
* | $(LITERAL '__LOCAL_SIZE')
* ;)
*/
AsmPrimaryExp parseAsmPrimaryExp()
{
import std.range : assumeSorted;
mixin (traceEnterAndExit!(__FUNCTION__));
auto startIndex = index;
AsmPrimaryExp node = allocator.make!AsmPrimaryExp();
switch (current().type)
{
foreach (NL; NumberLiterals) {case NL:}
case tok!"stringLiteral":
case tok!"$":
case tok!"this":
node.token = advance();
break;
case tok!"identifier":
if (assumeSorted(REGISTER_NAMES).equalRange(current().text).length > 0)
{
trace("Found register");
mixin (nullCheck!`(node.register = parseRegister())`);
if (currentIs(tok!":"))
{
advance();
mixin(parseNodeQ!(`node.segmentOverrideSuffix`, `AsmExp`));
}
}
else
mixin(parseNodeQ!(`node.identifierChain`, `IdentifierChain`));
break;
default:
error("Float literal, integer literal, `$`, `this` or identifier expected.", true, true);
return null;
}
node.tokens = tokens[startIndex .. index];
return node;
}
/**
* Parses an AsmRelExp
*
* $(GRAMMAR $(RULEDEF asmRelExp):
* $(RULE asmShiftExp)
* | $(RULE asmRelExp) (($(LITERAL '<') | $(LITERAL '<=') | $(LITERAL '>') | $(LITERAL '>=')) $(RULE asmShiftExp))?
* ;)
*/
ExpressionNode parseAsmRelExp()
{
pragma(inline, true);
mixin (traceEnterAndExit!(__FUNCTION__));
return parseLeftAssocBinaryExpression!(AsmRelExp, AsmShiftExp, tok!"<",
tok!"<=", tok!">", tok!">=")();
}
/**
* Parses an AsmShiftExp
*
* $(GRAMMAR $(RULEDEF asmShiftExp):
* $(RULE asmAddExp)
* $(RULE asmShiftExp) ($(LITERAL '<<') | $(LITERAL '>>') | $(LITERAL '>>>')) $(RULE asmAddExp)
* ;)
*/
ExpressionNode parseAsmShiftExp()
{
pragma(inline, true);
mixin (traceEnterAndExit!(__FUNCTION__));
return parseLeftAssocBinaryExpression!(AsmShiftExp, AsmAddExp, tok!"<<",
tok!">>", tok!">>>");
}
/**
* Parses an AsmStatement
*
* $(GRAMMAR $(RULEDEF asmStatement):
* $(LITERAL 'asm') $(RULE functionAttributes)? $(LITERAL '{') ( $(RULE asmInstruction)+ | $(RULE gccAsmInstruction)+ ) $(LITERAL '}')
* ;)
*/
AsmStatement parseAsmStatement()
{
mixin (traceEnterAndExit!(__FUNCTION__));
auto startIndex = index;
AsmStatement node = allocator.make!AsmStatement;
advance(); // asm
StackBuffer functionAttributes;
while (isAttribute())
{
if (!functionAttributes.put(parseFunctionAttribute()))
{
error("Function attribute or `{` expected", true, true);
return null;
}
}
ownArray(node.functionAttributes, functionAttributes);
mixin(tokenCheck!"{");
// DMD-style and GCC-style assembly might look identical in the beginning.
// Try DMD style first and restart with GCC if it fails because of GCC elements
bool maybeGccStyle;
const instrStart = allocator.setCheckpoint();
const instrStartIdx = index;
alias instructions = functionAttributes;
instructions.clear();
while (moreTokens() && !currentIs(tok!"}"))
{
auto c = allocator.setCheckpoint();
if (!instructions.put(parseAsmInstruction(maybeGccStyle)))
{
if (maybeGccStyle)
break;
allocator.rollback(c);
}
else
mixin(tokenCheck!";");
}
if (!maybeGccStyle)
{
ownArray(node.asmInstructions, instructions);
}
else
{
// Revert to the beginning of the first instruction
destroy(instructions);
allocator.rollback(instrStart);
index = instrStartIdx;
while (moreTokens() && !currentIs(tok!"}"))
{
auto c = allocator.setCheckpoint();
if (!instructions.put(parseGccAsmInstruction()))
allocator.rollback(c);
else
mixin(tokenCheck!";");
}
ownArray(node.gccAsmInstructions, instructions);
}
mixin(tokenCheck!"}");
node.tokens = tokens[startIndex .. index];
return node;
}
/**
* Parses an AsmTypePrefix
*
* Note that in the following grammar definition the first identifier must
* be "near", "far", "word", "dword", or "qword". The second identifier must
* be "ptr".
*
* $(GRAMMAR $(RULEDEF asmTypePrefix):
* $(LITERAL Identifier) $(LITERAL Identifier)?
* | $(LITERAL 'byte') $(LITERAL Identifier)?
* | $(LITERAL 'short') $(LITERAL Identifier)?
* | $(LITERAL 'int') $(LITERAL Identifier)?
* | $(LITERAL 'float') $(LITERAL Identifier)?
* | $(LITERAL 'double') $(LITERAL Identifier)?
* | $(LITERAL 'real') $(LITERAL Identifier)?
* ;)
*/
AsmTypePrefix parseAsmTypePrefix()
{
mixin (traceEnterAndExit!(__FUNCTION__));
auto startIndex = index;
switch (current().type)
{
case tok!"identifier":
case tok!"byte":
case tok!"short":
case tok!"int":
case tok!"float":
case tok!"double":
case tok!"real":