-
Notifications
You must be signed in to change notification settings - Fork 187
/
AbstractGNUSourceCodeParser.java
2939 lines (2609 loc) · 92 KB
/
AbstractGNUSourceCodeParser.java
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
/*******************************************************************************
* Copyright (c) 2005, 2015 IBM Corporation and others.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* John Camelon (IBM Rational Software) - Initial API and implementation
* Markus Schorn (Wind River Systems)
* Ed Swartz (Nokia)
* Mike Kucera (IBM) - bug #206952
* Sergey Prigogin (Google)
* Thomas Corbat (IFS)
* Anders Dahlberg (Ericsson) - bug 84144
* Alexander Nyßen (itemis AG) - bug 475908
*******************************************************************************/
package org.eclipse.cdt.internal.core.dom.parser;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.cdt.core.dom.ast.ASTCompletionNode;
import org.eclipse.cdt.core.dom.ast.ASTGenericVisitor;
import org.eclipse.cdt.core.dom.ast.ASTVisitor;
import org.eclipse.cdt.core.dom.ast.IASTASMDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTAlignmentSpecifier;
import org.eclipse.cdt.core.dom.ast.IASTAttribute;
import org.eclipse.cdt.core.dom.ast.IASTAttributeList;
import org.eclipse.cdt.core.dom.ast.IASTAttributeOwner;
import org.eclipse.cdt.core.dom.ast.IASTAttributeSpecifier;
import org.eclipse.cdt.core.dom.ast.IASTBinaryExpression;
import org.eclipse.cdt.core.dom.ast.IASTBreakStatement;
import org.eclipse.cdt.core.dom.ast.IASTCaseStatement;
import org.eclipse.cdt.core.dom.ast.IASTCastExpression;
import org.eclipse.cdt.core.dom.ast.IASTCompletionNode;
import org.eclipse.cdt.core.dom.ast.IASTCompositeTypeSpecifier;
import org.eclipse.cdt.core.dom.ast.IASTCompoundStatement;
import org.eclipse.cdt.core.dom.ast.IASTConditionalExpression;
import org.eclipse.cdt.core.dom.ast.IASTContinueStatement;
import org.eclipse.cdt.core.dom.ast.IASTDeclSpecifier;
import org.eclipse.cdt.core.dom.ast.IASTDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTDeclarationListOwner;
import org.eclipse.cdt.core.dom.ast.IASTDeclarationStatement;
import org.eclipse.cdt.core.dom.ast.IASTDeclarator;
import org.eclipse.cdt.core.dom.ast.IASTDefaultStatement;
import org.eclipse.cdt.core.dom.ast.IASTDoStatement;
import org.eclipse.cdt.core.dom.ast.IASTElaboratedTypeSpecifier;
import org.eclipse.cdt.core.dom.ast.IASTEnumerationSpecifier;
import org.eclipse.cdt.core.dom.ast.IASTEnumerationSpecifier.IASTEnumerator;
import org.eclipse.cdt.core.dom.ast.IASTExpression;
import org.eclipse.cdt.core.dom.ast.IASTExpressionList;
import org.eclipse.cdt.core.dom.ast.IASTExpressionStatement;
import org.eclipse.cdt.core.dom.ast.IASTFileLocation;
import org.eclipse.cdt.core.dom.ast.IASTFunctionCallExpression;
import org.eclipse.cdt.core.dom.ast.IASTFunctionDeclarator;
import org.eclipse.cdt.core.dom.ast.IASTFunctionDefinition;
import org.eclipse.cdt.core.dom.ast.IASTIfStatement;
import org.eclipse.cdt.core.dom.ast.IASTInitializer;
import org.eclipse.cdt.core.dom.ast.IASTInitializerClause;
import org.eclipse.cdt.core.dom.ast.IASTLabelStatement;
import org.eclipse.cdt.core.dom.ast.IASTLiteralExpression;
import org.eclipse.cdt.core.dom.ast.IASTName;
import org.eclipse.cdt.core.dom.ast.IASTNamedTypeSpecifier;
import org.eclipse.cdt.core.dom.ast.IASTNode;
import org.eclipse.cdt.core.dom.ast.IASTNullStatement;
import org.eclipse.cdt.core.dom.ast.IASTProblem;
import org.eclipse.cdt.core.dom.ast.IASTProblemDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTProblemExpression;
import org.eclipse.cdt.core.dom.ast.IASTProblemStatement;
import org.eclipse.cdt.core.dom.ast.IASTSimpleDeclSpecifier;
import org.eclipse.cdt.core.dom.ast.IASTSimpleDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTStatement;
import org.eclipse.cdt.core.dom.ast.IASTToken;
import org.eclipse.cdt.core.dom.ast.IASTTokenList;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
import org.eclipse.cdt.core.dom.ast.IASTTypeId;
import org.eclipse.cdt.core.dom.ast.IASTTypeIdExpression;
import org.eclipse.cdt.core.dom.ast.IASTUnaryExpression;
import org.eclipse.cdt.core.dom.ast.IASTWhileStatement;
import org.eclipse.cdt.core.dom.ast.INodeFactory;
import org.eclipse.cdt.core.dom.ast.IType;
import org.eclipse.cdt.core.dom.ast.gnu.IGNUASTCompoundStatementExpression;
import org.eclipse.cdt.core.dom.parser.IBuiltinBindingsProvider;
import org.eclipse.cdt.core.dom.parser.IExtensionToken;
import org.eclipse.cdt.core.dom.parser.ISourceCodeParser;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.core.parser.AbstractParserLogService;
import org.eclipse.cdt.core.parser.EndOfFileException;
import org.eclipse.cdt.core.parser.IGCCToken;
import org.eclipse.cdt.core.parser.IInactiveCodeToken;
import org.eclipse.cdt.core.parser.IParserLogService;
import org.eclipse.cdt.core.parser.IProblem;
import org.eclipse.cdt.core.parser.IScanner;
import org.eclipse.cdt.core.parser.IToken;
import org.eclipse.cdt.core.parser.OffsetLimitReachedException;
import org.eclipse.cdt.core.parser.ParseError;
import org.eclipse.cdt.core.parser.ParserMode;
import org.eclipse.cdt.core.parser.util.CharArrayUtils;
import org.eclipse.cdt.internal.core.parser.scanner.ILocationResolver;
/**
* Base class for the c- and c++ parser.
*/
public abstract class AbstractGNUSourceCodeParser implements ISourceCodeParser {
// See TemplateIdStrategy for an explanation of what this does.
public interface ITemplateIdStrategy {
boolean shallParseAsTemplateID(IASTName name);
}
protected static class FoundAggregateInitializer extends Exception {
public final IASTDeclarator fDeclarator;
public final IASTDeclSpecifier fDeclSpec;
public FoundAggregateInitializer(IASTDeclSpecifier declSpec, IASTDeclarator d) {
fDeclSpec = declSpec;
fDeclarator = d;
}
}
protected static class Decl {
public Decl() {
}
public IASTDeclSpecifier fDeclSpec1;
public IASTDeclSpecifier fDeclSpec2;
public IASTDeclarator fDtor1;
public IASTDeclarator fDtor2;
public IToken fDtorToken1;
public boolean isAtStartOfStructuredBinding = false;
public Decl set(IASTDeclSpecifier declspec, IASTDeclarator dtor, IToken dtorToken) {
fDeclSpec1 = declspec;
fDtor1 = dtor;
fDtorToken1 = dtorToken;
fDeclSpec2 = null;
fDtor2 = null;
return this;
}
public Decl set(IASTDeclSpecifier declspec1, IASTDeclarator dtor1, IASTDeclSpecifier declspec2,
IASTDeclarator dtor2) {
fDeclSpec1 = declspec1;
fDtor1 = dtor1;
fDtorToken1 = null;
fDeclSpec2 = declspec2;
fDtor2 = dtor2;
return this;
}
}
private static final ASTVisitor MARK_INACTIVE = new ASTGenericVisitor(true) {
{
shouldVisitAmbiguousNodes = true;
}
@Override
protected int genericVisit(IASTNode node) {
((ASTNode) node).setInactive();
return PROCESS_CONTINUE;
}
@Override
public int visit(ASTAmbiguousNode node) {
node.setInactive();
IASTNode[] alternatives = node.getNodes();
for (IASTNode alt : alternatives) {
if (!alt.accept(this))
return PROCESS_ABORT;
}
return PROCESS_CONTINUE;
}
};
/**
* Information about the context in which a cast-expression is parsed:
* in a binary expression, in a binary expression in a template-id, or elsewhere.
*/
protected static enum CastExprCtx {
eDirectlyInBExpr, eInBExpr, eNotInBExpr
}
protected static enum ExprKind {
eExpression, eAssignment, eConstant
}
protected static final int DEFAULT_DESIGNATOR_LIST_SIZE = 4;
protected final AbstractParserLogService log;
protected final IScanner scanner;
protected final ParserMode mode;
protected final boolean supportStatementsInExpressions;
protected final boolean supportTypeOfUnaries;
protected final boolean supportAlignOfUnaries;
protected final boolean supportKnRC;
protected final boolean supportAttributeSpecifiers;
protected final boolean supportDeclspecSpecifiers;
protected boolean supportParameterInfoBlock;
protected boolean supportFunctionStyleAsm;
protected boolean supportExtendedSizeofOperator;
protected final IBuiltinBindingsProvider builtinBindingsProvider;
protected boolean functionCallCanBeLValue;
protected int maximumTrivialExpressionsInAggregateInitializers = Integer.MAX_VALUE;
/**
* Marks the beginning of the current declaration. It is important to clear the mark whenever we
* enter a nested declaration, in order to avoid holding on to all the tokens.
*/
protected IToken declarationMark;
protected IToken nextToken;
protected IToken lastToken;
protected IToken lastTokenFromScanner;
protected boolean isCancelled = false;
protected boolean parsePassed = true;
protected int backtrackCount = 0;
protected BacktrackException backtrack = new BacktrackException();
protected ASTCompletionNode completionNode;
private final INodeFactory nodeFactory;
private boolean fActiveCode = true;
protected AbstractGNUSourceCodeParser(IScanner scanner, IParserLogService logService, ParserMode parserMode,
INodeFactory nodeFactory, boolean supportStatementsInExpressions, boolean supportTypeOfUnaries,
boolean supportAlignOfUnaries, boolean supportKnRC, boolean supportAttributeSpecifiers,
boolean supportDeclspecSpecifiers, IBuiltinBindingsProvider builtinBindingsProvider) {
this.scanner = scanner;
this.log = wrapLogService(logService);
this.mode = parserMode;
this.supportStatementsInExpressions = supportStatementsInExpressions;
this.supportTypeOfUnaries = supportTypeOfUnaries;
this.supportAlignOfUnaries = supportAlignOfUnaries;
this.supportKnRC = supportKnRC;
this.supportAttributeSpecifiers = supportAttributeSpecifiers;
this.supportDeclspecSpecifiers = supportDeclspecSpecifiers;
this.builtinBindingsProvider = builtinBindingsProvider;
this.nodeFactory = nodeFactory;
}
/**
* Instructs the parser not to create AST nodes for expressions within aggregate initializers
* when they do not contain names beyond the given limit.
*/
public void setMaximumTrivialExpressionsInAggregateInitializers(int limit) {
maximumTrivialExpressionsInAggregateInitializers = limit;
}
private AbstractParserLogService wrapLogService(IParserLogService logService) {
if (logService instanceof AbstractParserLogService) {
return (AbstractParserLogService) logService;
}
return new ParserLogServiceWrapper(logService);
}
protected final void throwBacktrack(int offset, int length) throws BacktrackException {
++backtrackCount;
backtrack.initialize(offset, length < 0 ? 0 : length);
throw backtrack;
}
protected INodeFactory getNodeFactory() {
return nodeFactory;
}
@Override
public IASTCompletionNode getCompletionNode() {
return completionNode;
}
// Use to create the completion node
protected ASTCompletionNode createCompletionNode(IToken token) {
// the preprocessor may deliver tokens for literals or header-names.
if (completionNode == null && token != null && token.getType() == IToken.tCOMPLETION) {
completionNode = new ASTCompletionNode(token, getTranslationUnit());
}
return completionNode;
}
/**
* Fetches the next token from the scanner.
*/
private final IToken fetchToken(boolean skipInactive) throws EndOfFileException {
try {
IToken t = scanner.nextToken();
if (skipInactive) {
while (t.getType() == IToken.tINACTIVE_CODE_START) {
scanner.skipInactiveCode();
t = scanner.nextToken();
}
}
if (lastTokenFromScanner != null)
lastTokenFromScanner.setNext(t);
lastTokenFromScanner = t;
return t;
} catch (OffsetLimitReachedException olre) {
if (mode != ParserMode.COMPLETION_PARSE)
throw new EndOfFileException(olre.getEndOffset());
IToken completionToken = olre.getFinalToken();
createCompletionNode(completionToken);
if (olre.getOriginator() == OffsetLimitReachedException.ORIGIN_INACTIVE_CODE) {
// If completion is invoked inside inactive code, there is no AST from which
// to give the completion node a completion name, so we invent a name.
// The invented name is not hooked up to the AST, but does have an offset
// and length, so it can provide an accurate point of reference in
// declaredBefore().
IASTName completionName = nodeFactory.newInactiveCompletionName(completionToken.getCharImage(),
getTranslationUnit());
((ASTNode) completionName).setOffsetAndLength(completionToken.getOffset(), completionToken.getLength());
completionNode.addName(completionName);
// Consume the completion token so we don't try to parse an AST fragment from it.
consume();
}
throw olre;
}
}
private final IToken nextToken(boolean skipInactive) throws EndOfFileException {
final IToken t = nextToken;
if (t != null)
return t;
final IToken tn = fetchToken(skipInactive);
nextToken = tn;
return tn;
}
private final IToken lookaheadToken(int i, boolean skipInactive) throws EndOfFileException {
assert i >= 0;
if (isCancelled) {
throw new ParseError(ParseError.ParseErrorKind.TIMEOUT_OR_CANCELLED);
}
IToken t = nextToken(skipInactive);
for (; i > 1; --i) {
t = t.getNext();
if (t == null)
t = fetchToken(skipInactive);
}
return t;
}
/**
* Returns the next token without advancing. Same as {@code LA(1)}.
*/
protected final IToken LA() throws EndOfFileException {
IToken t = nextToken(true);
checkForEOI(t);
return t;
}
/**
* Returns one of the next tokens. With {@code i == 1}, the next token is returned.
* @param i number of tokens to look ahead, must be greater than 0.
*/
protected final IToken LA(int i) throws EndOfFileException {
IToken t = lookaheadToken(i, true);
checkForEOI(t);
return t;
}
/**
* Consumes and returns the next token available.
*/
protected final IToken consume() throws EndOfFileException {
IToken t = nextToken(true);
checkForEOI(t);
nextToken = t.getNext();
return t;
}
/**
* Tests whether we are looking at a change from active to inactive code at this point. If so, the change
* is accepted.
*
* @param nesting
* the nesting level of the code branch we have to stay within
* @return <code>false</code> if an inactive code branch was rejected because of its nesting level,
* <code>true</code>, otherwise.
*/
protected final boolean acceptInactiveCodeBoundary(int nesting) {
try {
while (true) {
IToken t = nextToken(false);
switch (t.getType()) {
case IToken.tINACTIVE_CODE_START:
case IToken.tINACTIVE_CODE_SEPARATOR:
IInactiveCodeToken it = (IInactiveCodeToken) t;
if (it.getNewNesting() < nesting
|| (it.getNewNesting() == nesting && it.getOldNesting() == nesting)) {
return false;
}
fActiveCode = false;
nextToken = t.getNext(); // consume the token
continue;
case IToken.tINACTIVE_CODE_END:
it = (IInactiveCodeToken) t;
if (it.getNewNesting() < nesting
|| (it.getNewNesting() == nesting && it.getOldNesting() == nesting)) {
return false;
}
fActiveCode = true;
nextToken = t.getNext(); // consume the token
continue;
default:
return true;
}
}
} catch (EndOfFileException e) {
}
return true;
}
protected final void skipInactiveCode() throws OffsetLimitReachedException {
IToken t = nextToken;
if (fActiveCode && (t == null || t.getType() != IToken.tINACTIVE_CODE_START))
return;
try {
fActiveCode = true;
while (t != null && t.getType() != IToken.tINACTIVE_CODE_END) {
t = t.getNext();
}
if (t != null) {
nextToken = t.getNext();
} else {
nextToken = null;
scanner.skipInactiveCode();
}
} catch (OffsetLimitReachedException olre) {
if (mode == ParserMode.COMPLETION_PARSE) {
createCompletionNode(olre.getFinalToken());
throw olre;
}
}
}
protected final boolean isActiveCode() {
return fActiveCode;
}
protected final int getCodeBranchNesting() {
return scanner.getCodeBranchNesting();
}
/**
* Returns the next token, which can be used to reset the input back to
* this point in the stream.
*/
protected final IToken mark() throws EndOfFileException {
return LA();
}
/**
* Roll back to a previous point, reseting the queue of tokens.
* @param mark a token previously obtained via {@link #mark()}.
*/
protected final void backup(IToken mark) {
nextToken = mark;
}
private final void checkForEOI(IToken t) throws EndOfFileException {
final int lt = t.getType();
if (lt == IToken.tINACTIVE_CODE_SEPARATOR || lt == IToken.tINACTIVE_CODE_END)
throw new EndOfFileException(t.getOffset(), true);
}
/**
* Same as {@link #LA(int)}, but returns <code>null</code> when eof is reached.
*/
protected final IToken LAcatchEOF(int i) {
try {
return LA(i);
} catch (EndOfFileException e) {
return null;
}
}
/**
* Look ahead in the token list and return the token type.
* @param i number of tokens to look ahead, must be greater or equal to 0.
* @return The type of that token
*/
protected final int LT(int i) throws EndOfFileException {
return LA(i).getType();
}
/**
* Same as {@link #LT(int)}, but returns <code>0</code> when eof is reached.
*/
protected final int LTcatchEOF(int i) {
try {
return LT(i);
} catch (EndOfFileException e) {
return 0;
}
}
/**
* The next token is consumed. Afterwards its type is checked and a {@link BacktrackException}
* is thrown if the type does not match the expected one.
* @param type the expected type of the next token.
*/
protected final IToken consume(int type) throws EndOfFileException, BacktrackException {
final IToken result = consume();
if (result.getType() != type)
throwBacktrack(result);
return result;
}
/**
* The next token is consumed. Afterwards its type is checked and a {@link BacktrackException}
* is thrown if the type neither matches <code>type1</code> nor <code>type2</code>.
*/
protected final IToken consume(int type1, int type2) throws EndOfFileException, BacktrackException {
final IToken result = consume();
final int lt1 = result.getType();
if (lt1 != type1 && lt1 != type2)
throwBacktrack(result);
return result;
}
/**
* Consume the next token available only if the type is as specified. In case we reached
* the end of completion, no token is consumed and the eoc-token returned.
*
* @param type
* The type of token that you are expecting.
* @return the token that was consumed and removed from our buffer.
* @throws BacktrackException
* if LT(1) != type
*/
protected IToken consumeOrEOC(int type) throws EndOfFileException, BacktrackException {
final IToken la1 = LA(1);
final int lt1 = la1.getType();
if (lt1 != type) {
if (lt1 == IToken.tEOC)
return la1;
throwBacktrack(la1);
}
return consume();
}
protected final boolean isOnSameLine(int offset1, int offset2) {
ILocationResolver lr = getTranslationUnit().getAdapter(ILocationResolver.class);
IASTFileLocation floc = lr.getMappedFileLocation(offset1, offset2 - offset1 + 1);
return floc.getFileName().equals(lr.getContainingFilePath(offset1))
&& floc.getStartingLineNumber() == floc.getEndingLineNumber();
}
protected final int calculateEndOffset(IASTNode n) {
ASTNode node = (ASTNode) n;
return node.getOffset() + node.getLength();
}
protected final <T extends IASTNode> T setRange(T n, IASTNode from) {
((ASTNode) n).setOffsetAndLength((ASTNode) from);
return n;
}
protected final <T extends IASTNode> T setRange(T n, IASTNode from, int endOffset) {
final int offset = ((ASTNode) from).getOffset();
((ASTNode) n).setOffsetAndLength(offset, endOffset - offset);
return n;
}
protected final <T extends IASTNode> T setRange(T n, int offset, int endOffset) {
((ASTNode) n).setOffsetAndLength(offset, endOffset - offset);
return n;
}
protected final void adjustLength(IASTNode n, IASTNode endNode) {
final int endOffset = calculateEndOffset(endNode);
adjustEndOffset(n, endOffset);
}
protected final <T extends IASTNode> T adjustEndOffset(T n, final int endOffset) {
final ASTNode node = (ASTNode) n;
node.setLength(endOffset - node.getOffset());
return n;
}
protected final int getEndOffset() {
if (lastTokenFromScanner == null)
return 0;
return lastTokenFromScanner.getEndOffset();
}
/**
* This is the single entry point for setting parsePassed to false
*/
protected void failParse() {
parsePassed = false;
}
@Override
public synchronized void cancel() {
isCancelled = true;
}
/**
* Parses an identifier.
*
* @throws BacktrackException request a backtrack
*/
protected abstract IASTName identifier() throws EndOfFileException, BacktrackException;
/**
* @return Returns the backtrackCount.
*/
public final int getBacktrackCount() {
return backtrackCount;
}
protected IASTProblem createProblem(BacktrackException bt) {
IASTProblem result = bt.getProblem();
if (result == null) {
result = createProblem(IProblem.SYNTAX_ERROR, bt.getOffset(), bt.getLength());
}
return result;
}
protected final IASTProblem createProblem(int signal, int offset, int length) {
IASTProblem result = nodeFactory.newProblem(signal, CharArrayUtils.EMPTY, true);
((ASTNode) result).setOffsetAndLength(offset, length);
return result;
}
protected void logThrowable(String methodName, Throwable e) {
if (e != null) {
if (log.isTracing()) {
String message = String.format("Parser: Unexpected throwable in %s:%s::%s. w/%s", //$NON-NLS-1$
methodName, e.getClass().getName(), e.getMessage(), scanner);
log.traceLog(message);
}
log.traceException(e);
}
}
@Override
public String toString() {
return scanner.toString();
}
/**
* @param methodName
* @param e
*/
protected void logException(String methodName, Exception e) {
if (!(e instanceof EndOfFileException) && e != null) {
if (log.isTracing()) {
String message = String.format("Parser: Unexpected exception in %s:%s::%s. w/%s", //$NON-NLS-1$
methodName, e.getClass().getName(), e.getMessage(), scanner);
log.traceLog(message);
}
log.traceException(e);
}
}
protected final void throwBacktrack(IASTProblem problem, IASTNode node) throws BacktrackException {
++backtrackCount;
backtrack.initialize(problem, node);
throw backtrack;
}
protected final void throwBacktrack(IASTProblem problem) throws BacktrackException {
++backtrackCount;
backtrack.initialize(problem);
throw backtrack;
}
protected final void throwBacktrack(IASTNode node) throws BacktrackException {
final ASTNode n = (ASTNode) node;
throwBacktrack(n.getOffset(), n.getLength());
}
@Override
public IASTTranslationUnit parse() {
long t0 = log.isTracing() ? System.currentTimeMillis() : 0;
translationUnit();
long t1 = log.isTracing() ? System.currentTimeMillis() : 0;
resolveAmbiguities();
IASTTranslationUnit ast = getTranslationUnit();
if (log.isTracing()) {
ITranslationUnit tu = ast.getOriginatingTranslationUnit();
String name = tu == null ? "<unknown>" : tu.getElementName(); //$NON-NLS-1$
String message = String.format("Parsed %s: %d ms%s. Ambiguity resolution: %d ms", //$NON-NLS-1$
name, t1 - t0, parsePassed ? "" : " - parse failure", System.currentTimeMillis() - t1); //$NON-NLS-1$//$NON-NLS-2$
log.traceLog(message);
}
nullifyTranslationUnit();
ast.freeze(); // Make the AST immutable.
return ast;
}
protected void resolveAmbiguities() {
final IASTTranslationUnit translationUnit = getTranslationUnit();
if (translationUnit instanceof ASTTranslationUnit) {
((ASTTranslationUnit) translationUnit).resolveAmbiguities();
}
}
protected abstract ASTVisitor createAmbiguityNodeVisitor();
protected abstract void nullifyTranslationUnit();
protected IToken skipOverCompoundStatement(boolean hasSkippedNodes) throws BacktrackException, EndOfFileException {
// speed up the parser by skipping the body, simply look for matching brace and return
if (hasSkippedNodes)
getTranslationUnit().setHasNodesOmitted(true);
final boolean isActive = isActiveCode();
final int codeBranchNesting = getCodeBranchNesting();
consume(IToken.tLBRACE);
IToken result = null;
int depth = 1;
while (depth > 0) {
if (!isActive) {
IToken t = lookaheadToken(1, false);
final int lt = t.getType();
if (lt == IToken.tINACTIVE_CODE_SEPARATOR || lt == IToken.tINACTIVE_CODE_END
|| lt == IToken.tINACTIVE_CODE_START) {
if (!acceptInactiveCodeBoundary(codeBranchNesting))
throw new EndOfFileException(t.getOffset(), true);
}
}
result = consume();
switch (result.getType()) {
case IToken.tRBRACE:
--depth;
break;
case IToken.tLBRACE:
++depth;
break;
case IToken.tEOC:
throw new EndOfFileException(result.getOffset());
}
}
return result;
}
protected IASTProblemDeclaration skipProblemDeclaration(int offset) {
return skipProblemDeclaration(offset, null);
}
protected IASTProblemDeclaration skipProblemDeclaration(int offset, IASTProblem origProblem) {
failParse();
declarationMark = null;
int endOffset = skipToSemiOrClosingBrace(offset, false);
IASTProblem problem = createProblem(IProblem.SYNTAX_ERROR, offset, endOffset - offset);
if (origProblem != null && origProblem.getID() != IProblem.SYNTAX_ERROR) {
problem.setOriginalProblem(origProblem);
}
return buildProblemDeclaration(problem);
}
protected IASTProblemStatement skipProblemStatement(int offset) {
failParse();
declarationMark = null;
int endOffset = skipToSemiOrClosingBrace(offset, false);
IASTProblem problem = createProblem(IProblem.SYNTAX_ERROR, offset, endOffset - offset);
return buildProblemStatement(problem);
}
private IASTProblem skipProblemEnumerator(int offset) {
failParse();
final int endOffset = skipToSemiOrClosingBrace(offset, true);
return createProblem(IProblem.SYNTAX_ERROR, offset, endOffset - offset);
}
private int skipToSemiOrClosingBrace(int offset, boolean eatBrace) {
failParse();
declarationMark = null;
int depth = 0;
int endOffset;
loop: try {
endOffset = LA(1).getOffset();
while (true) {
switch (LT(1)) {
case IToken.tEOC:
endOffset = getEndOffset();
break loop;
case IToken.tSEMI:
if (depth == 0) {
endOffset = consume().getEndOffset();
break loop;
}
break;
case IToken.tLBRACE:
++depth;
break;
case IToken.tRBRACE:
if (--depth <= 0) {
if (depth == 0 || offset == endOffset || eatBrace) {
endOffset = consume().getEndOffset(); // consume closing brace
}
if (LTcatchEOF(1) == IToken.tSEMI) {
endOffset = consume().getEndOffset();
}
break loop;
}
break;
}
endOffset = consume().getEndOffset();
}
} catch (EndOfFileException e) {
endOffset = getEndOffset();
}
return endOffset;
}
protected IASTProblemExpression skipProblemConditionInParenthesis(int offset) {
failParse();
int compExpr = 0;
int depth = 0;
int endOffset = offset;
loop: try {
while (true) {
switch (LT(1)) {
case IToken.tEOC:
endOffset = getEndOffset();
break loop;
case IToken.tSEMI:
case IToken.tLBRACE:
if (compExpr == 0) {
break loop;
}
break;
case IToken.tLPAREN:
depth++;
if (LTcatchEOF(2) == IToken.tLBRACE) {
if (compExpr == 0) {
compExpr = depth;
}
consume();
}
break;
case IToken.tRPAREN:
if (--depth < 0) {
break loop;
}
if (depth < compExpr) {
compExpr = 0;
}
break;
}
endOffset = consume().getEndOffset();
}
} catch (EndOfFileException e) {
endOffset = getEndOffset();
}
IASTProblem problem = createProblem(IProblem.SYNTAX_ERROR, offset, endOffset - offset);
return buildProblemExpression(problem);
}
protected IASTCompoundStatement compoundStatement() throws EndOfFileException, BacktrackException {
IASTCompoundStatement result = nodeFactory.newCompoundStatement();
if (LT(1) == IToken.tEOC)
return result;
final int offset = LA(1).getOffset();
int endOffset = consume(IToken.tLBRACE).getOffset();
int stmtOffset = -1;
while (true) {
IToken next = LAcatchEOF(1);
if (next == null) {
((ASTNode) result).setOffsetAndLength(offset, endOffset - offset);
throwBacktrack(createProblem(IProblem.SYNTAX_ERROR, endOffset, 0), result);
return null; // To make Java compiler happy.
}
try {
if (next.getType() == IToken.tEOC)
break;
if (next.getType() == IToken.tRBRACE) {
endOffset = consume().getEndOffset();
break;
}
final int nextOffset = next.getOffset();
declarationMark = next;
next = null; // Don't hold on to the token while parsing namespaces, class bodies, etc.
IASTStatement stmt;
if (stmtOffset == nextOffset) {
// no progress
stmt = skipProblemStatement(stmtOffset);
} else {
stmtOffset = nextOffset;
stmt = statement();
}
result.addStatement(stmt);
endOffset = calculateEndOffset(stmt);
} catch (BacktrackException bt) {
final IASTNode beforeProblem = bt.getNodeBeforeProblem();
final IASTProblem problem = bt.getProblem();
if (problem != null && beforeProblem instanceof IASTStatement) {
result.addStatement((IASTStatement) beforeProblem);
result.addStatement(buildProblemStatement(problem));
endOffset = calculateEndOffset(beforeProblem);
} else {
IASTStatement stmt = skipProblemStatement(stmtOffset);
result.addStatement(stmt);
endOffset = calculateEndOffset(stmt);
}
} catch (EndOfFileException e) {
IASTStatement stmt = skipProblemStatement(stmtOffset);
result.addStatement(stmt);
endOffset = calculateEndOffset(stmt);
break;
} finally {
declarationMark = null;
}
}
((ASTNode) result).setOffsetAndLength(offset, endOffset - offset);
return result;
}
private IASTProblemDeclaration buildProblemDeclaration(IASTProblem problem) {
IASTProblemDeclaration pd = nodeFactory.newProblemDeclaration(problem);
((ASTNode) pd).setOffsetAndLength(((ASTNode) problem));
return pd;
}
private IASTProblemStatement buildProblemStatement(IASTProblem problem) {
IASTProblemStatement pstmt = nodeFactory.newProblemStatement(problem);
((ASTNode) pstmt).setOffsetAndLength(((ASTNode) problem));
return pstmt;
}
private IASTProblemExpression buildProblemExpression(IASTProblem problem) {
IASTProblemExpression pexpr = nodeFactory.newProblemExpression(problem);
((ASTNode) pexpr).setOffsetAndLength(((ASTNode) problem));
return pexpr;
}
protected IASTExpression compoundStatementExpression() throws EndOfFileException, BacktrackException {
int startingOffset = consume().getOffset(); // tLPAREN always
IASTCompoundStatement compoundStatement = null;
if (mode == ParserMode.QUICK_PARSE || mode == ParserMode.STRUCTURAL_PARSE || !isActiveCode()) {
skipOverCompoundStatement(true);
} else if (mode == ParserMode.COMPLETION_PARSE || mode == ParserMode.SELECTION_PARSE) {
if (scanner.isOnTopContext()) {
compoundStatement();
} else {
skipOverCompoundStatement(true);
}
} else if (mode == ParserMode.COMPLETE_PARSE) {
compoundStatement = compoundStatement();
}
int lastOffset = consume(IToken.tRPAREN).getEndOffset();
IGNUASTCompoundStatementExpression resultExpression = nodeFactory
.newGNUCompoundStatementExpression(compoundStatement);
((ASTNode) resultExpression).setOffsetAndLength(startingOffset, lastOffset - startingOffset);
return resultExpression;
}
/**
* Models a cast expression followed by an operator. Can be linked into a chain.
* This is done right to left, such that a tree of variants can be built.
*/
public static class BinaryOperator {
final int fOperatorToken;
final int fLeftPrecedence;
final int fRightPrecedence;
BinaryOperator fNext;
IASTInitializerClause fExpression;
final CastAmbiguityMarker fAmbiguityMarker;
public BinaryOperator(BinaryOperator nextOp, IASTInitializerClause expression, int operatorToken,
int leftPrecedence, int rightPrecedence) {
fNext = nextOp;
fOperatorToken = operatorToken;
fLeftPrecedence = leftPrecedence;
fRightPrecedence = rightPrecedence;
if (expression instanceof CastAmbiguityMarker) {
fAmbiguityMarker = (CastAmbiguityMarker) expression;
fExpression = fAmbiguityMarker.fExpression;
fAmbiguityMarker.fExpression = null;
} else {
fExpression = expression;
fAmbiguityMarker = null;
}
}
public IASTInitializerClause exchange(IASTInitializerClause expr) {
IASTInitializerClause e = fExpression;
fExpression = expr;
return e;
}