forked from JetBrains/Grammar-Kit
-
Notifications
You must be signed in to change notification settings - Fork 1
/
GeneratedParserUtilBase.java
executable file
·1285 lines (1143 loc) · 47.1 KB
/
GeneratedParserUtilBase.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 2011-2016 Gregory Shrago
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.intellij.grammar.parser;
import com.intellij.codeInsight.completion.impl.CamelHumpMatcher;
import com.intellij.lang.*;
import com.intellij.lang.impl.PsiBuilderAdapter;
import com.intellij.lang.impl.PsiBuilderImpl;
import com.intellij.lexer.Lexer;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringHash;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiReference;
import com.intellij.psi.TokenType;
import com.intellij.psi.impl.source.resolve.FileContextUtil;
import com.intellij.psi.impl.source.tree.CompositePsiElement;
import com.intellij.psi.tree.ICompositeElementType;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import com.intellij.util.Function;
import com.intellij.util.PairProcessor;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.LimitedPool;
import org.intellij.grammar.config.Options;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
/**
* This class is a runtime engine for parsers generated by <a href="https://github.com/JetBrains/Grammar-Kit">Grammar-Kit</a>.
* <br/>
* Here is the original <a href="https://github.com/JetBrains/Grammar-Kit/blob/master/support/org/intellij/grammar/parser/GeneratedParserUtilBase.java">
* GeneratedParserUtilBase</a> code.
* <br/>
* <br/>
*
* @author gregsh
*/
public class GeneratedParserUtilBase {
private static final Logger LOG = Logger.getInstance("org.intellij.grammar.parser.GeneratedParserUtilBase");
private static final int MAX_RECURSION_LEVEL = Options.GPUB_MAX_LEVEL.get();
private static final int MAX_VARIANTS_SIZE = 10000;
private static final int MAX_VARIANTS_TO_DISPLAY = 50;
private static final int INITIAL_VARIANTS_SIZE = 1000;
private static final int VARIANTS_POOL_SIZE = 10000;
private static final int FRAMES_POOL_SIZE = 500;
public static final IElementType DUMMY_BLOCK = new DummyBlockElementType();
public interface Parser {
boolean parse(PsiBuilder builder, int level);
}
public static final Parser TOKEN_ADVANCER = new Parser() {
@Override
public boolean parse(PsiBuilder builder, int level) {
if (builder.eof()) return false;
builder.advanceLexer();
return true;
}
};
public static final Parser TRUE_CONDITION = new Parser() {
@Override
public boolean parse(PsiBuilder builder, int level) {
return true;
}
};
public interface Hook<T> {
@Contract("_,null,_->null")
PsiBuilder.Marker run(PsiBuilder builder, PsiBuilder.Marker marker, T param);
}
public static final Hook<WhitespacesAndCommentsBinder> LEFT_BINDER =
new Hook<WhitespacesAndCommentsBinder>() {
@Override
public PsiBuilder.Marker run(PsiBuilder builder,
PsiBuilder.Marker marker,
WhitespacesAndCommentsBinder param) {
if (marker != null) marker.setCustomEdgeTokenBinders(param, null);
return marker;
}
};
public static final Hook<WhitespacesAndCommentsBinder> RIGHT_BINDER =
new Hook<WhitespacesAndCommentsBinder>() {
@Override
public PsiBuilder.Marker run(PsiBuilder builder,
PsiBuilder.Marker marker,
WhitespacesAndCommentsBinder param) {
if (marker != null) marker.setCustomEdgeTokenBinders(null, param);
return marker;
}
};
public static final Hook<WhitespacesAndCommentsBinder[]> WS_BINDERS =
new Hook<WhitespacesAndCommentsBinder[]>() {
@Override
public PsiBuilder.Marker run(PsiBuilder builder,
PsiBuilder.Marker marker,
WhitespacesAndCommentsBinder[] param) {
if (marker != null) marker.setCustomEdgeTokenBinders(param[0], param[1]);
return marker;
}
};
public static final Hook<String> LOG_HOOK = new Hook<String>() {
@Override
public PsiBuilder.Marker run(PsiBuilder builder, PsiBuilder.Marker marker, String param) {
PsiBuilderImpl.ProductionMarker m = (PsiBuilderImpl.ProductionMarker)marker;
int start = m == null ? builder.getCurrentOffset() : m.getStartOffset();
int end = m == null ? start : m.getEndOffset();
String prefix = "[" + start + ", " + end + "]" + (m == null ? "" : " " + m.getTokenType());
builder.mark().error(prefix + ": " + param);
return marker;
}
};
public static boolean eof(PsiBuilder builder, int level) {
return builder.eof();
}
public static int current_position_(PsiBuilder builder) {
return builder.rawTokenIndex();
}
public static boolean recursion_guard_(PsiBuilder builder, int level, String funcName) {
if (level > MAX_RECURSION_LEVEL) {
builder.error("Maximum recursion level (" + MAX_RECURSION_LEVEL + ") reached in '" + funcName + "'");
return false;
}
return true;
}
public static boolean empty_element_parsed_guard_(PsiBuilder builder, String funcName, int pos) {
if (pos == current_position_(builder)) {
builder.error("Empty element parsed in '" + funcName + "' at offset " + builder.getCurrentOffset());
return false;
}
return true;
}
public static boolean invalid_left_marker_guard_(PsiBuilder builder, PsiBuilder.Marker marker, String funcName) {
//builder.error("Invalid left marker encountered in " + funcName_ +" at offset " + builder.getCurrentOffset());
boolean goodMarker = marker != null; // && ((LighterASTNode)marker).getTokenType() != TokenType.ERROR_ELEMENT;
if (!goodMarker) return false;
ErrorState state = ErrorState.get(builder);
return state.currentFrame != null;
}
public static TokenSet create_token_set_(IElementType... tokenTypes) {
return TokenSet.create(tokenTypes);
}
public static boolean leftMarkerIs(PsiBuilder builder, IElementType type) {
LighterASTNode marker = builder.getLatestDoneMarker();
return marker != null && marker.getTokenType() == type;
}
private static boolean consumeTokens(PsiBuilder builder, boolean smart, int pin, IElementType... tokens) {
ErrorState state = ErrorState.get(builder);
if (state.completionState != null && state.predicateSign) {
addCompletionVariant(builder, state.completionState, tokens);
}
// suppress single token completion
CompletionState completionState = state.completionState;
state.completionState = null;
boolean result = true;
boolean pinned = false;
for (int i = 0, tokensLength = tokens.length; i < tokensLength; i++) {
if (pin > 0 && i == pin) pinned = result;
if (result || pinned) {
boolean fast = smart && i == 0;
if (!(fast ? consumeTokenFast(builder, tokens[i]) : consumeToken(builder, tokens[i]))) {
result = false;
if (pin < 0 || pinned) report_error_(builder, state, false);
}
}
}
state.completionState = completionState;
return pinned || result;
}
public static boolean consumeTokens(PsiBuilder builder, int pin, IElementType... token) {
return consumeTokens(builder, false, pin, token);
}
public static boolean consumeTokensSmart(PsiBuilder builder, int pin, IElementType... token) {
return consumeTokens(builder, true, pin, token);
}
public static boolean parseTokens(PsiBuilder builder, int pin, IElementType... tokens) {
return parseTokens(builder, false, pin, tokens);
}
public static boolean parseTokensSmart(PsiBuilder builder, int pin, IElementType... tokens) {
return parseTokens(builder, true, pin, tokens);
}
public static boolean parseTokens(PsiBuilder builder, boolean smart, int pin, IElementType... tokens) {
PsiBuilder.Marker marker = builder.mark();
boolean result = consumeTokens(builder, smart, pin, tokens);
if (!result) {
marker.rollbackTo();
}
else {
marker.drop();
}
return result;
}
public static boolean consumeTokenSmart(PsiBuilder builder, IElementType token) {
addCompletionVariantSmart(builder, token);
return consumeTokenFast(builder, token);
}
public static boolean consumeTokenSmart(PsiBuilder builder, String token) {
addCompletionVariantSmart(builder, token);
return consumeTokenFast(builder, token);
}
public static boolean consumeToken(PsiBuilder builder, IElementType token) {
addVariantSmart(builder, token, true);
if (nextTokenIsFast(builder, token)) {
builder.advanceLexer();
return true;
}
return false;
}
public static boolean consumeTokenFast(PsiBuilder builder, IElementType token) {
if (nextTokenIsFast(builder, token)) {
builder.advanceLexer();
return true;
}
return false;
}
public static boolean consumeToken(PsiBuilder builder, String text) {
return consumeToken(builder, text, ErrorState.get(builder).caseSensitive);
}
public static boolean consumeToken(PsiBuilder builder, String text, boolean caseSensitive) {
addVariantSmart(builder, text, true);
int count = nextTokenIsFast(builder, text, caseSensitive);
if (count > 0) {
while (count-- > 0) builder.advanceLexer();
return true;
}
return false;
}
public static boolean consumeTokenFast(PsiBuilder builder, String text) {
int count = nextTokenIsFast(builder, text, ErrorState.get(builder).caseSensitive);
if (count > 0) {
while (count-- > 0) builder.advanceLexer();
return true;
}
return false;
}
public static boolean nextTokenIsFast(PsiBuilder builder, IElementType token) {
return builder.getTokenType() == token;
}
public static boolean nextTokenIsFast(PsiBuilder builder, IElementType... tokens) {
IElementType tokenType = builder.getTokenType();
for (IElementType token : tokens) {
if (token == tokenType) return true;
}
return false;
}
public static boolean nextTokenIsSmart(PsiBuilder builder, IElementType token) {
return nextTokenIsFast(builder, token) || ErrorState.get(builder).completionState != null;
}
public static boolean nextTokenIsSmart(PsiBuilder builder, IElementType... tokens) {
return nextTokenIsFast(builder, tokens) || ErrorState.get(builder).completionState != null;
}
public static boolean nextTokenIs(PsiBuilder builder, String frameName, IElementType... tokens) {
ErrorState state = ErrorState.get(builder);
if (state.completionState != null) return true;
boolean track = !state.suppressErrors && state.predicateCount < 2 && state.predicateSign;
if (!track) return nextTokenIsFast(builder, tokens);
IElementType tokenType = builder.getTokenType();
if (StringUtil.isNotEmpty(frameName)) {
addVariantInner(state, builder.rawTokenIndex(), frameName);
}
else {
for (IElementType token : tokens) {
addVariant(builder, state, token);
}
}
if (tokenType == null) return false;
for (IElementType token : tokens) {
if (tokenType == token) return true;
}
return false;
}
public static boolean nextTokenIs(PsiBuilder builder, IElementType token) {
if (!addVariantSmart(builder, token, false)) return true;
return nextTokenIsFast(builder, token);
}
public static boolean nextTokenIs(PsiBuilder builder, String tokenText) {
if (!addVariantSmart(builder, tokenText, false)) return true;
return nextTokenIsFast(builder, tokenText, ErrorState.get(builder).caseSensitive) > 0;
}
public static boolean nextTokenIsFast(PsiBuilder builder, String tokenText) {
return nextTokenIsFast(builder, tokenText, ErrorState.get(builder).caseSensitive) > 0;
}
public static int nextTokenIsFast(PsiBuilder builder, String tokenText, boolean caseSensitive) {
CharSequence sequence = builder.getOriginalText();
int offset = builder.getCurrentOffset();
int endOffset = offset + tokenText.length();
CharSequence subSequence = sequence.subSequence(offset, Math.min(endOffset, sequence.length()));
if (!Comparing.equal(subSequence, tokenText, caseSensitive)) return 0;
int count = 0;
while (true) {
int nextOffset = builder.rawTokenTypeStart(++count);
if (nextOffset > endOffset) {
return -count;
}
else if (nextOffset == endOffset) {
break;
}
}
return count;
}
private static void addCompletionVariantSmart(PsiBuilder builder, Object token) {
ErrorState state = ErrorState.get(builder);
CompletionState completionState = state.completionState;
if (completionState != null && state.predicateSign) {
addCompletionVariant(builder, completionState, token);
}
}
private static boolean addVariantSmart(PsiBuilder builder, Object token, boolean force) {
ErrorState state = ErrorState.get(builder);
// skip FIRST check in completion mode
if (state.completionState != null && !force) return false;
builder.eof();
if (!state.suppressErrors && state.predicateCount < 2) {
addVariant(builder, state, token);
}
return true;
}
public static void addVariant(PsiBuilder builder, String text) {
addVariant(builder, ErrorState.get(builder), text);
}
private static void addVariant(PsiBuilder builder, ErrorState state, Object o) {
builder.eof(); // skip whitespaces
addVariantInner(state, builder.rawTokenIndex(), o);
CompletionState completionState = state.completionState;
if (completionState != null && state.predicateSign) {
addCompletionVariant(builder, completionState, o);
}
}
private static void addVariantInner(ErrorState state, int pos, Object o) {
Variant variant = state.VARIANTS.alloc().init(pos, o);
if (state.predicateSign) {
state.variants.add(variant);
if (state.lastExpectedVariantPos < variant.position) {
state.lastExpectedVariantPos = variant.position;
}
}
else {
state.unexpected.add(variant);
}
}
private static void addCompletionVariant(@NotNull PsiBuilder builder, @NotNull CompletionState completionState, Object o) {
int offset = builder.getCurrentOffset();
if (!builder.eof() && offset == builder.rawTokenTypeStart(1)) return; // suppress for zero-length tokens
String text = completionState.convertItem(o);
int length = text == null? 0 : text.length();
boolean add = length != 0 && completionState.prefixMatches(builder, text);
add = add && length > 1 && !(text.charAt(0) == '<' && text.charAt(length - 1) == '>') &&
!(text.charAt(0) == '\'' && text.charAt(length - 1) == '\'' && length < 5);
if (add) {
completionState.addItem(builder, text);
}
}
public static boolean isWhitespaceOrComment(@NotNull PsiBuilder builder, @Nullable IElementType type) {
return ((PsiBuilderImpl)((Builder)builder).getDelegate()).whitespaceOrComment(type);
}
// here's the new section API for compact parsers & less IntelliJ platform API exposure
public static final int _NONE_ = 0x0;
public static final int _COLLAPSE_ = 0x1;
public static final int _LEFT_ = 0x2;
public static final int _LEFT_INNER_ = 0x4;
public static final int _AND_ = 0x8;
public static final int _NOT_ = 0x10;
public static final int _UPPER_ = 0x20;
// simple enter/exit methods pair that doesn't require frame object
public static PsiBuilder.Marker enter_section_(PsiBuilder builder) {
ErrorState.get(builder).level++;
return builder.mark();
}
public static void exit_section_(PsiBuilder builder,
PsiBuilder.Marker marker,
@Nullable IElementType elementType,
boolean result) {
ErrorState state = ErrorState.get(builder);
close_marker_impl_(state.currentFrame, marker, elementType, result);
run_hooks_impl_(builder, state, result ? elementType : null);
state.level--;
}
// complex enter/exit methods pair with frame object
public static PsiBuilder.Marker enter_section_(PsiBuilder builder, int level, int modifiers, String frameName) {
return enter_section_(builder, level, modifiers, null, frameName);
}
public static PsiBuilder.Marker enter_section_(PsiBuilder builder, int level, int modifiers) {
return enter_section_(builder, level, modifiers, null, null);
}
public static PsiBuilder.Marker enter_section_(PsiBuilder builder, int level, int modifiers, IElementType elementType, String frameName) {
PsiBuilder.Marker marker = builder.mark();
enter_section_impl_(builder, level, modifiers, elementType, frameName);
return marker;
}
private static void enter_section_impl_(PsiBuilder builder, int level, int modifiers, IElementType elementType, String frameName) {
ErrorState state = ErrorState.get(builder);
state.level++;
Frame frame = state.FRAMES.alloc().init(builder, state, level, modifiers, elementType, frameName);
Frame prevFrame = state.currentFrame;
if (prevFrame != null && prevFrame.errorReportedAt > frame.position) {
// report error for previous unsuccessful frame
reportError(builder, state, frame, null, true, false);
}
if (((frame.modifiers & _LEFT_) | (frame.modifiers & _LEFT_INNER_)) != 0) {
PsiBuilder.Marker left = (PsiBuilder.Marker)builder.getLatestDoneMarker();
if (invalid_left_marker_guard_(builder, left, frameName)) {
frame.leftMarker = left;
}
}
state.currentFrame = frame;
if ((modifiers & _AND_) != 0) {
if (state.predicateCount == 0 && !state.predicateSign) {
throw new AssertionError("Incorrect false predicate sign");
}
state.predicateCount++;
}
else if ((modifiers & _NOT_) != 0) {
state.predicateSign = state.predicateCount != 0 && !state.predicateSign;
state.predicateCount++;
}
}
public static void exit_section_(PsiBuilder builder,
int level,
PsiBuilder.Marker marker,
boolean result,
boolean pinned,
@Nullable Parser eatMore) {
exit_section_(builder, level, marker, null, result, pinned, eatMore);
}
public static void exit_section_(PsiBuilder builder,
int level,
PsiBuilder.Marker marker,
@Nullable IElementType elementType,
boolean result,
boolean pinned,
@Nullable Parser eatMore) {
ErrorState state = ErrorState.get(builder);
Frame frame = state.currentFrame;
state.currentFrame = frame == null ? null : frame.parentFrame;
if (frame != null && frame.elementType != null) elementType = frame.elementType;
if (frame == null || level != frame.level) {
LOG.error("Unbalanced error section: got " + frame + ", expected level " + level);
if (frame != null) state.FRAMES.recycle(frame);
close_marker_impl_(frame, marker, elementType, result);
return;
}
if (((frame.modifiers & _AND_) | (frame.modifiers & _NOT_)) != 0) {
close_marker_impl_(frame, marker, null, false);
replace_variants_with_name_(state, frame, builder, result, pinned);
state.predicateCount--;
if ((frame.modifiers & _NOT_) != 0) state.predicateSign = !state.predicateSign;
}
else {
close_frame_impl_(state, frame, builder, marker, elementType, result, pinned);
exit_section_impl_(state, frame, builder, elementType, result, pinned, eatMore);
}
run_hooks_impl_(builder, state, pinned || result ? elementType : null);
state.FRAMES.recycle(frame);
state.level--;
}
public static <T> void register_hook_(PsiBuilder builder, Hook<T> hook, T param) {
ErrorState state = ErrorState.get(builder);
state.hooks = Hooks.concat(hook, param, state.level, state.hooks);
}
public static <T> void register_hook_(PsiBuilder builder, Hook<T[]> hook, T... param) {
ErrorState state = ErrorState.get(builder);
state.hooks = Hooks.concat(hook, param, state.level, state.hooks);
}
private static void run_hooks_impl_(PsiBuilder builder, ErrorState state, @Nullable IElementType elementType) {
if (state.hooks == null) return;
PsiBuilder.Marker marker = elementType == null ? null : (PsiBuilder.Marker)builder.getLatestDoneMarker();
if (elementType != null && marker == null) {
builder.error("No expected done marker at offset " + builder.getCurrentOffset());
}
while (state.hooks != null && state.hooks.level >= state.level) {
if (state.hooks.level == state.level) {
marker = ((Hook<Object>)state.hooks.hook).run(builder, marker, state.hooks.param);
}
state.hooks = state.hooks.next;
}
}
private static void exit_section_impl_(ErrorState state,
Frame frame,
PsiBuilder builder,
@Nullable IElementType elementType,
boolean result,
boolean pinned,
@Nullable Parser eatMore) {
int initialPos = builder.rawTokenIndex();
boolean willFail = !result && !pinned;
replace_variants_with_name_(state, frame, builder, result, pinned);
int lastErrorPos = getLastVariantPos(state, initialPos);
if (!state.suppressErrors && eatMore != null) {
state.suppressErrors = true;
final boolean eatMoreFlagOnce = !builder.eof() && eatMore.parse(builder, frame.level + 1);
boolean eatMoreFlag = eatMoreFlagOnce || !result && frame.position == initialPos && lastErrorPos > frame.position;
PsiBuilderImpl.ProductionMarker latestDoneMarker =
(pinned || result) && (state.altMode || elementType != null) &&
eatMoreFlagOnce ? (PsiBuilderImpl.ProductionMarker)builder.getLatestDoneMarker() : null;
PsiBuilder.Marker extensionMarker = null;
IElementType extensionTokenType = null;
// whitespace prefix makes the very first frame offset bigger than marker start offset which is always 0
if (latestDoneMarker != null &&
frame.position >= latestDoneMarker.getStartIndex() &&
frame.position <= latestDoneMarker.getEndIndex()) {
extensionMarker = ((PsiBuilder.Marker)latestDoneMarker).precede();
extensionTokenType = latestDoneMarker.getTokenType();
((PsiBuilder.Marker)latestDoneMarker).drop();
}
// advance to the last error pos
// skip tokens until lastErrorPos. parseAsTree might look better here...
int parenCount = 0;
while ((eatMoreFlag || parenCount > 0) && builder.rawTokenIndex() < lastErrorPos) {
IElementType tokenType = builder.getTokenType();
if (state.braces != null) {
if (tokenType == state.braces[0].getLeftBraceType()) parenCount ++;
else if (tokenType == state.braces[0].getRightBraceType()) parenCount --;
}
if (!(builder.rawTokenIndex() < lastErrorPos)) break;
builder.advanceLexer();
eatMoreFlag = eatMore.parse(builder, frame.level + 1);
}
boolean errorReported = frame.errorReportedAt == initialPos || !result && frame.errorReportedAt >= frame.position;
if (errorReported) {
if (eatMoreFlag) {
builder.advanceLexer();
parseAsTree(state, builder, frame.level + 1, DUMMY_BLOCK, true, TOKEN_ADVANCER, eatMore);
}
}
else if (eatMoreFlag) {
errorReported = reportError(builder, state, frame, null, true, true);
parseAsTree(state, builder, frame.level + 1, DUMMY_BLOCK, true, TOKEN_ADVANCER, eatMore);
}
else if (eatMoreFlagOnce || (!result && frame.position != builder.rawTokenIndex()) || frame.errorReportedAt > initialPos) {
errorReported = reportError(builder, state, frame, null, true, false);
}
else if (!result && pinned && frame.errorReportedAt < 0) {
errorReported = reportError(builder, state, frame, elementType, false, false);
}
if (extensionMarker != null) {
extensionMarker.done(extensionTokenType);
}
state.suppressErrors = false;
if (errorReported || result) {
state.clearVariants(true, 0);
state.clearVariants(false, 0);
state.lastExpectedVariantPos = -1;
}
}
else if (!result && pinned && frame.errorReportedAt < 0) {
// do not report if there are errors beyond current position
if (lastErrorPos == initialPos) {
// do not force, inner recoverRoot might have skipped some tokens
reportError(builder, state, frame, elementType, false, false);
}
else if (lastErrorPos > initialPos) {
// set error pos here as if it is reported for future reference
frame.errorReportedAt = lastErrorPos;
}
}
// propagate errorReportedAt up the stack to avoid duplicate reporting
Frame prevFrame = willFail && eatMore == null ? null : state.currentFrame;
if (prevFrame != null && prevFrame.errorReportedAt < frame.errorReportedAt) {
prevFrame.errorReportedAt = frame.errorReportedAt;
}
}
private static void close_frame_impl_(ErrorState state,
Frame frame,
PsiBuilder builder,
PsiBuilder.Marker marker,
IElementType elementType,
boolean result,
boolean pinned) {
if (elementType != null && marker != null) {
if ((frame.modifiers & _COLLAPSE_) != 0) {
PsiBuilderImpl.ProductionMarker last = result || pinned? (PsiBuilderImpl.ProductionMarker)builder.getLatestDoneMarker() : null;
if (last != null && last.getStartIndex() == frame.position &&
state.typeExtends(last.getTokenType(), elementType)) {
IElementType resultType = last.getTokenType();
((PsiBuilder.Marker)last).drop();
marker.done(resultType);
return;
}
}
if (result || pinned) {
if ((frame.modifiers & _UPPER_) != 0) {
marker.drop();
for (Frame f = frame.parentFrame; f != null; f = f.parentFrame) {
if (f.elementType == null) continue;
f.elementType = elementType;
break;
}
}
else if ((frame.modifiers & _LEFT_INNER_) != 0 && frame.leftMarker != null) {
marker.done(elementType);
frame.leftMarker.precede().done(((LighterASTNode)frame.leftMarker).getTokenType());
frame.leftMarker.drop();
}
else if ((frame.modifiers & _LEFT_) != 0 && frame.leftMarker != null) {
marker.drop();
frame.leftMarker.precede().done(elementType);
}
else {
if (frame.level == 0) builder.eof(); // skip whitespaces
marker.done(elementType);
}
}
else {
close_marker_impl_(frame, marker, null, false);
}
}
else if (result || pinned) {
if (marker != null) marker.drop();
if ((frame.modifiers & _LEFT_INNER_) != 0 && frame.leftMarker != null) {
frame.leftMarker.precede().done(((LighterASTNode)frame.leftMarker).getTokenType());
frame.leftMarker.drop();
}
}
else {
close_marker_impl_(frame, marker, null, false);
}
}
private static void close_marker_impl_(Frame frame, PsiBuilder.Marker marker, IElementType elementType, boolean result) {
if (marker == null) return;
if (result) {
if (elementType != null) {
marker.done(elementType);
}
else {
marker.drop();
}
}
else {
if (frame != null) {
int position = ((PsiBuilderImpl.ProductionMarker)marker).getStartIndex();
if (frame.errorReportedAt > position && frame.parentFrame != null) {
frame.errorReportedAt = frame.parentFrame.errorReportedAt;
}
}
marker.rollbackTo();
}
}
private static void replace_variants_with_name_(ErrorState state,
Frame frame,
PsiBuilder builder,
boolean result,
boolean pinned) {
int initialPos = builder.rawTokenIndex();
boolean willFail = !result && !pinned;
if (willFail && initialPos == frame.position && state.lastExpectedVariantPos == frame.position &&
frame.name != null && state.variants.size() - frame.variantCount > 1) {
state.clearVariants(true, frame.variantCount);
addVariantInner(state, initialPos, frame.name);
}
}
public static boolean report_error_(PsiBuilder builder, boolean result) {
if (!result) report_error_(builder, ErrorState.get(builder), false);
return result;
}
public static void report_error_(PsiBuilder builder, ErrorState state, boolean advance) {
Frame frame = state.currentFrame;
if (frame == null) {
LOG.error("unbalanced enter/exit section call: got null");
return;
}
int position = builder.rawTokenIndex();
if (frame.errorReportedAt < position && getLastVariantPos(state, position + 1) <= position) {
reportError(builder, state, frame, null, true, advance);
}
}
private static int getLastVariantPos(ErrorState state, int defValue) {
return state.lastExpectedVariantPos < 0? defValue : state.lastExpectedVariantPos;
}
private static boolean reportError(PsiBuilder builder,
ErrorState state,
Frame frame,
IElementType elementType,
boolean force,
boolean advance) {
String expectedText = state.getExpectedText(builder);
boolean notEmpty = StringUtil.isNotEmpty(expectedText);
if (!(force || notEmpty || advance)) return false;
String gotText = builder.eof() ? "unexpected end of file" :
notEmpty? "got '" + builder.getTokenText() +"'" :
"'" + builder.getTokenText() +"' unexpected";
String message = expectedText + gotText;
if (advance) {
PsiBuilder.Marker mark = builder.mark();
builder.advanceLexer();
mark.error(message);
}
else if (!force) {
PsiBuilder.Marker extensionMarker = null;
IElementType extensionTokenType = null;
PsiBuilderImpl.ProductionMarker latestDoneMarker = elementType == null ? null : (PsiBuilderImpl.ProductionMarker)builder.getLatestDoneMarker();
if (latestDoneMarker != null &&
frame.position >= latestDoneMarker.getStartIndex() &&
frame.position <= latestDoneMarker.getEndIndex()) {
extensionMarker = ((PsiBuilder.Marker)latestDoneMarker).precede();
extensionTokenType = latestDoneMarker.getTokenType();
((PsiBuilder.Marker)latestDoneMarker).drop();
}
builder.error(message);
if (extensionMarker != null) extensionMarker.done(extensionTokenType);
}
else {
builder.error(message);
}
builder.eof(); // skip whitespaces
frame.errorReportedAt = builder.rawTokenIndex();
return true;
}
public static final Key<CompletionState> COMPLETION_STATE_KEY = Key.create("COMPLETION_STATE_KEY");
public static class CompletionState implements Function<Object, String> {
public final int offset;
public final Collection<String> items = ContainerUtil.newTroveSet();
public CompletionState(int offset_) {
offset = offset_;
}
@Nullable
public String convertItem(Object o) {
return o instanceof Object[] ? StringUtil.join((Object[]) o, this, " ") : o.toString();
}
@Override
public String fun(Object o) {
return o.toString();
}
public void addItem(@NotNull PsiBuilder builder, @NotNull String text) {
items.add(text);
}
public boolean prefixMatches(@NotNull PsiBuilder builder, @NotNull String text) {
int builderOffset = builder.getCurrentOffset();
int diff = offset - builderOffset;
int length = text.length();
if (diff == 0) {
return true;
}
else if (diff > 0 && diff <= length) {
CharSequence fragment = builder.getOriginalText().subSequence(builderOffset, offset);
return prefixMatches(fragment.toString(), text);
}
else if (diff < 0) {
for (int i=-1; ; i--) {
IElementType type = builder.rawLookup(i);
int tokenStart = builder.rawTokenTypeStart(i);
if (isWhitespaceOrComment(builder, type)) {
diff = offset - tokenStart;
}
else if (type != null && tokenStart < offset) {
CharSequence fragment = builder.getOriginalText().subSequence(tokenStart, offset);
if (prefixMatches(fragment.toString(), text)) {
diff = offset - tokenStart;
}
break;
}
else break;
}
return diff >= 0 && diff < length;
}
return false;
}
public boolean prefixMatches(@NotNull String prefix, @NotNull String variant) {
boolean matches = new CamelHumpMatcher(prefix, false).prefixMatches(variant.replace(' ', '_'));
if (matches && StringUtil.isWhiteSpace(prefix.charAt(prefix.length() - 1))) {
return StringUtil.startsWithIgnoreCase(variant, prefix);
}
return matches;
}
}
public static class Builder extends PsiBuilderAdapter {
public final ErrorState state;
public final PsiParser parser;
public Builder(PsiBuilder builder, ErrorState state_, PsiParser parser_) {
super(builder);
state = state_;
parser = parser_;
}
public Lexer getLexer() {
return ((PsiBuilderImpl)myDelegate).getLexer();
}
}
public static PsiBuilder adapt_builder_(IElementType root, PsiBuilder builder, PsiParser parser) {
return adapt_builder_(root, builder, parser, null);
}
public static PsiBuilder adapt_builder_(IElementType root, PsiBuilder builder, PsiParser parser, TokenSet[] extendsSets) {
ErrorState state = new ErrorState();
ErrorState.initState(state, builder, root, extendsSets);
return new Builder(builder, state, parser);
}
public static class ErrorState {
TokenSet[] extendsSets;
public PairProcessor<IElementType, IElementType> altExtendsChecker;
int predicateCount;
int level;
boolean predicateSign = true;
boolean suppressErrors;
Hooks<?> hooks;
public Frame currentFrame;
public CompletionState completionState;
private boolean caseSensitive;
public BracePair[] braces;
public boolean altMode;
int lastExpectedVariantPos = -1;
MyList<Variant> variants = new MyList<Variant>(INITIAL_VARIANTS_SIZE);
MyList<Variant> unexpected = new MyList<Variant>(INITIAL_VARIANTS_SIZE / 10);
final LimitedPool<Variant> VARIANTS = new LimitedPool<Variant>(VARIANTS_POOL_SIZE, new LimitedPool.ObjectFactory<Variant>() {
@NotNull
@Override
public Variant create() {
return new Variant();
}
@Override
public void cleanup(@NotNull Variant o) {
}
});
final LimitedPool<Frame> FRAMES = new LimitedPool<Frame>(FRAMES_POOL_SIZE, new LimitedPool.ObjectFactory<Frame>() {
@NotNull
@Override
public Frame create() {
return new Frame();
}
@Override
public void cleanup(@NotNull Frame o) {
}
});
public static ErrorState get(PsiBuilder builder) {
return ((Builder)builder).state;
}
public static void initState(ErrorState state, PsiBuilder builder, IElementType root, TokenSet[] extendsSets) {
state.extendsSets = extendsSets;
PsiFile file = builder.getUserDataUnprotected(FileContextUtil.CONTAINING_FILE_KEY);
state.completionState = file == null? null: file.getUserData(COMPLETION_STATE_KEY);
Language language = file == null? root.getLanguage() : file.getLanguage();
state.caseSensitive = language.isCaseSensitive();
PairedBraceMatcher matcher = LanguageBraceMatching.INSTANCE.forLanguage(language);
state.braces = matcher == null ? null : matcher.getPairs();
if (state.braces != null && state.braces.length == 0) state.braces = null;
}
public String getExpectedText(PsiBuilder builder) {
int position = builder.rawTokenIndex();
StringBuilder sb = new StringBuilder();
if (addExpected(sb, position, true)) {
sb.append(" expected, ");
}
return sb.toString();
}
private boolean addExpected(StringBuilder sb, int position, boolean expected) {
MyList<Variant> list = expected ? variants : unexpected;
String[] strings = new String[list.size()];
long[] hashes = new long[strings.length];
Arrays.fill(strings, "");
int count = 0;
loop: for (Variant variant : list) {
if (position == variant.position) {
String text = variant.object.toString();
long hash = StringHash.calc(text);
for (int i=0; i<count; i++) {
if (hashes[i] == hash) continue loop;
}
hashes[count] = hash;
strings[count] = text;
count++;
}
}
Arrays.sort(strings);
count = 0;
for (String s : strings) {
if (s.length() == 0) continue;
if (count++ > 0) {
if (count > MAX_VARIANTS_TO_DISPLAY) {
sb.append(" and ...");
break;
}
else {
sb.append(", ");
}
}
char c = s.charAt(0);
String displayText = c == '<' || StringUtil.isJavaIdentifierStart(c) ? s : '\'' + s + '\'';
sb.append(displayText);
}