forked from antlr/antlr4
/
ParserATNSimulator.java
executable file
·1771 lines (1569 loc) · 65.9 KB
/
ParserATNSimulator.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
/*
[The "BSD license"]
Copyright (c) 2011 Terence Parr
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.antlr.v4.runtime.atn;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.dfa.DFA;
import org.antlr.v4.runtime.dfa.DFAState;
import org.antlr.v4.runtime.misc.IntervalSet;
import org.antlr.v4.runtime.misc.NotNull;
import org.antlr.v4.runtime.misc.Nullable;
import org.antlr.v4.runtime.misc.Utils;
import org.stringtemplate.v4.misc.MultiMap;
import java.util.*;
/**
The embodiment of the adaptive LL(*) parsing strategy.
The basic complexity of the adaptive strategy makes it harder to
understand. We begin with ATN simulation to build paths in a
DFA. Subsequent prediction requests go through the DFA first. If
they reach a state without an edge for the current symbol, the
algorithm fails over to the ATN simulation to complete the DFA
path for the current input (until it finds a conflict state or
uniquely predicting state).
All of that is done without using the outer context because we
want to create a DFA that is not dependent upon the rule
invocation stack when we do a prediction. One DFA works in all
contexts. We avoid using context not necessarily because it
slower, although it can be, but because of the DFA caching
problem. The closure routine only considers the rule invocation
stack created during prediction beginning in the entry rule. For
example, if prediction occurs without invoking another rule's
ATN, there are no context stacks in the configurations. When this
leads to a conflict, we don't know if it's an ambiguity or a
weakness in the strong LL(*) parsing strategy (versus full
LL(*)).
So, we simply retry the ATN simulation again, this time
using full outer context and filling a dummy DFA (to avoid
polluting the context insensitive DFA). Configuration context
stacks will be the full invocation stack from the start rule. If
we get a conflict using full context, then we can definitively
say we have a true ambiguity for that input sequence. If we don't
get a conflict, it implies that the decision is sensitive to the
outer context. (It is not context-sensitive in the sense of
context sensitive grammars.) We create a special DFA accept state
that maps rule context to a predicted alternative. That is the
only modification needed to handle full LL(*) prediction. In
general, full context prediction will use more lookahead than
necessary, but it pays to share the same DFA. For a schedule
proof that full context prediction uses that most the same amount
of lookahead as a context insensitive prediction, see the comment
on method retryWithContext().
So, the strategy is complex because we bounce back and forth from
the ATN to the DFA, simultaneously performing predictions and
extending the DFA according to previously unseen input
sequences. The retry with full context is a recursive call to the
same function naturally because it does the same thing, just with
a different initial context. The problem is, that we need to pass
in a "full context mode" parameter so that it knows to report
conflicts differently. It also knows not to do a retry, to avoid
infinite recursion, if it is already using full context.
Retry a simulation using full outer context.
*
* One of the key assumptions here is that using full context
* can use at most the same amount of input as a simulation
* that is not useful context (i.e., it uses all possible contexts
* that could invoke our entry rule. I believe that this is true
* and the proof might go like this.
*
* THEOREM: The amount of input consumed during a full context
* simulation is at most the amount of input consumed during a
* non full context simulation.
*
* PROOF: Let D be the DFA state at which non-context simulation
* terminated. That means that D does not have a configuration for
* which we can legally pursue more input. (It is legal to work only
* on configurations for which there is no conflict with another
* configuration.) Now we restrict ourselves to following ATN edges
* associated with a single context. Choose any DFA state D' along
* the path (same input) to D. That state has either the same number
* of configurations or fewer. (If the number of configurations is
* the same, then we have degenerated to the non-context case.) Now
* imagine that we restrict to following edges associated with
* another single context and that we reach DFA state D'' for the
* same amount of input as D'. The non-context simulation merges D'
* and D''. The union of the configuration sets either has the same
* number of configurations as both D' and D'' or it has more. If it
* has the same number, we are no worse off and the merge does not
* force us to look for more input than we would otherwise have to
* do. If the union has more configurations, it can introduce
* conflicts but not new alternatives--we cannot conjure up alternatives
* by computing closure on the DFA state. Here are the cases for
* D' union D'':
*
* 1. No increase in configurations, D' = D''
* 2. Add configuration that introduces a new alternative number.
* This cannot happen because no new alternatives are introduced
* while computing closure, even during start state computation.
* 3. D'' adds a configuration that does not conflict with any
* configuration in D'. Simulating without context would then have
* forced us to use more lookahead than D' (full context) alone.
* 3. D'' adds a configuration that introduces a conflict with a
* configuration in D'. There are 2 cases:
* a. The conflict does not cause termination (D' union D''
* is added to the work list). Again no context simulation requires
* more input.
* b. The conflict does cause termination, but this cannot happen.
* By definition, we know that with ALL contexts merged we
* don't terminate until D and D' uses less input than D. Therefore
* no context simulation requires more input than full context
* simulation.
*
* We have covered all the cases and there is never a situation where
* a single, full context simulation requires more input than a
* no context simulation.
I spent a bunch of time thinking about this problem after finding
a case where context-sensitive ATN simulation looks beyond what they
no context simulation uses. the no context simulation for if then else
stops at the else whereas full context scans through to the end of the
statement to decide that the "else statement" clause is ambiguous. And
sometimes it is not ambiguous! Ok, I made an untrue assumption in my
proof which I won't bother going to. the important thing is what I'm
going to do about it. I thought I had a simple answer, but nope. It
turns out that the if then else case is perfect example of something
that has the following characteristics:
* no context conflicts at k=1
* full context at k=(1 + length of statement) can be both ambiguous and not
ambiguous depending on the input, though I think from different contexts.
But, the good news is that the k=1 case is a special case in that
SLL(1) and LL(1) have exactly the same power so we can conclude that
conflicts at k=1 are true ambiguities and we do not need to pursue
context-sensitive parsing. That covers a huge number of cases
including the if then else clause and the predicated precedence
parsing mechanism. whew! because that could be extremely expensive if
we had to do context.
Further, there is no point in doing full context if none of the
configurations dip into the outer context. This nicely handles cases
such as super constructor calls versus function calls. One grammar
might look like this:
ctorBody : '{' superCall? stat* '}' ;
Or, you might see something like
stat : superCall ';' | expression ';' | ... ;
In both cases I believe that no closure operations will dip into the
outer context. In the first case ctorBody in the worst case will stop
at the '}'. In the 2nd case it should stop at the ';'. Both cases
should stay within the entry rule and not dip into the outer context.
So, we now cover what I hope is the vast majority of the cases (in
particular the very important precedence parsing case). Anything that
needs k>1 and dips into the outer context requires a full context
retry. In this case, I'm going to start out with a brain-dead solution
which is to mark the DFA state as context-sensitive when I get a
conflict. Any further DFA simulation that reaches that state will
launch an ATN simulation to get the prediction, without updating the
DFA or storing any context information. Later, I can make this more
efficient, but at least in this case I can guarantee that it will
always do the right thing. We are not making any assumptions about
lookahead depth.
Ok, writing this up so I can put in a comment.
Upon conflict in the no context simulation:
* if k=1, report ambiguity and resolve to the minimum conflicting alternative
* if k=1 and predicates, no report and include the predicate to
predicted alternative map in the DFA state
* if k=* and we did not dip into the outer context, report ambiguity
and resolve to minimum conflicting alternative
* if k>1 and we dip into outer context, retry with full context
* if conflict, report ambiguity and resolve to minimum conflicting
alternative, mark DFA as context-sensitive
* If no conflict, report ctx sensitivity and mark DFA as context-sensitive
* Technically, if full context k is less than no context k, we can
reuse the conflicting DFA state so we don't have to create special
DFA paths branching from context, but we can leave that for
optimization later if necessary.
* if non-greedy, no report and resolve to the exit alternative
*
* By default we do full context-sensitive LL(*) parsing not
* Strong LL(*) parsing. If we fail with Strong LL(*) we
* try full LL(*). That means we rewind and use context information
* when closure operations fall off the end of the rule that
* holds the decision were evaluating
*/
public class ParserATNSimulator<Symbol extends Token> extends ATNSimulator {
public static boolean debug = false;
public static boolean dfa_debug = false;
public static boolean retry_debug = false;
public boolean disable_global_context = false;
public boolean force_global_context = false;
public boolean always_try_local_context = true;
public boolean optimize_ll1 = true;
public static boolean optimize_closure_busy = true;
public static int ATN_failover = 0;
public static int predict_calls = 0;
public static int retry_with_context = 0;
public static int retry_with_context_indicates_no_conflict = 0;
@Nullable
protected final Parser parser;
@NotNull
public final DFA[] decisionToDFA;
/** By default we do full context-sensitive LL(*) parsing not
* Strong LL(*) parsing. If we fail with Strong LL(*) we
* try full LL(*). That means we rewind and use context information
* when closure operations fall off the end of the rule that
* holds the decision were evaluating.
*/
protected boolean userWantsCtxSensitive = true;
protected final Map<Integer, Integer> LL1Table = new HashMap<Integer, Integer>();
/** Testing only! */
public ParserATNSimulator(@NotNull ATN atn) {
this(null, atn);
}
public ParserATNSimulator(@Nullable Parser parser, @NotNull ATN atn) {
super(atn);
this.parser = parser;
// ctxToDFAs = new HashMap<RuleContext, DFA[]>();
// TODO (sam): why distinguish on parser != null?
decisionToDFA = new DFA[atn.getNumberOfDecisions() + (parser != null ? 1 : 0)];
// DOTGenerator dot = new DOTGenerator(null);
// System.out.println(dot.getDOT(atn.rules.get(0), parser.getRuleNames()));
// System.out.println(dot.getDOT(atn.rules.get(1), parser.getRuleNames()));
}
@Override
public void reset() {
}
public int adaptivePredict(@NotNull SymbolStream<? extends Symbol> input, int decision,
@Nullable ParserRuleContext<?> outerContext)
{
return adaptivePredict(input, decision, outerContext, false);
}
public int adaptivePredict(@NotNull SymbolStream<? extends Symbol> input,
int decision,
@Nullable ParserRuleContext<?> outerContext,
boolean useContext)
{
predict_calls++;
DFA dfa = decisionToDFA[decision];
if (optimize_ll1 && dfa != null) {
int ll_1 = input.LA(1);
if (ll_1 >= 0 && ll_1 <= Short.MAX_VALUE) {
int key = (decision << 16) + ll_1;
Integer alt = LL1Table.get(key);
if (alt != null) {
return alt;
}
}
}
if (force_global_context) {
useContext = true;
}
else if (!always_try_local_context) {
useContext |= dfa != null && dfa.isContextSensitive();
}
userWantsCtxSensitive = useContext || (!disable_global_context && (outerContext != null));
if (outerContext == null) {
outerContext = ParserRuleContext.EMPTY;
}
SimulatorState state = null;
if (dfa != null) {
state = getStartState(dfa, input, outerContext, useContext);
}
if ( state==null ) {
if ( dfa==null ) {
DecisionState startState = atn.decisionToState.get(decision);
decisionToDFA[decision] = dfa = new DFA(startState, decision);
}
return predictATN(dfa, input, outerContext, useContext);
}
else {
//dump(dfa);
// start with the DFA
int m = input.mark();
int index = input.index();
try {
int alt = execDFA(dfa, input, index, state);
return alt;
}
finally {
input.seek(index);
input.release(m);
}
}
}
public SimulatorState getStartState(@NotNull DFA dfa,
@NotNull SymbolStream<?> input,
@NotNull ParserRuleContext<?> outerContext,
boolean useContext) {
if (!useContext) {
if (dfa.s0 == null) {
return null;
}
return new SimulatorState(outerContext, dfa.s0, false, outerContext);
}
RuleContext remainingContext = outerContext;
assert outerContext != null;
DFAState s0 = dfa.s0;
while (remainingContext != null && s0 != null && s0.isCtxSensitive) {
s0 = s0.getContextTarget(remainingContext.invokingState);
remainingContext = remainingContext.parent;
}
if (s0 == null) {
return null;
}
return new SimulatorState(outerContext, s0, useContext, (ParserRuleContext<?>)remainingContext);
}
public int predictATN(@NotNull DFA dfa, @NotNull SymbolStream<? extends Symbol> input,
@Nullable ParserRuleContext<?> outerContext,
boolean useContext)
{
if ( outerContext==null ) outerContext = ParserRuleContext.EMPTY;
if ( debug ) System.out.println("ATN decision "+dfa.decision+
" exec LA(1)=="+ getLookaheadName(input) +
", outerContext="+outerContext.toString(parser));
int alt = 0;
int m = input.mark();
int index = input.index();
try {
SimulatorState state = computeStartState(dfa, outerContext, useContext);
alt = execATN(dfa, input, index, state);
}
catch (NoViableAltException nvae) {
if ( debug ) dumpDeadEndConfigs(nvae);
throw nvae;
}
finally {
input.seek(index);
input.release(m);
}
if ( debug ) System.out.println("DFA after predictATN: "+dfa.toString(parser.getTokenNames(), parser.getRuleNames()));
return alt;
}
public int execDFA(@NotNull DFA dfa,
@NotNull SymbolStream<? extends Symbol> input, int startIndex,
@NotNull SimulatorState state)
{
ParserRuleContext<?> outerContext = state.outerContext;
if ( dfa_debug ) System.out.println("DFA decision "+dfa.decision+
" exec LA(1)=="+ getLookaheadName(input) +
", outerContext="+outerContext.toString(parser));
if ( dfa_debug ) System.out.print(dfa.toString(parser.getTokenNames(), parser.getRuleNames()));
DFAState acceptState = null;
DFAState s = state.s0;
int t = input.LA(1);
ParserRuleContext<?> remainingOuterContext = (ParserRuleContext<?>)state.remainingOuterContext;
loop:
while ( true ) {
if ( dfa_debug ) System.out.println("DFA state "+s.stateNumber+" LA(1)=="+getLookaheadName(input));
if ( state.useContext ) {
while ( s.isCtxSensitive && s.contextSymbols.contains(t) ) {
DFAState next = s.getContextTarget(remainingOuterContext.invokingState);
if ( next == null ) {
// fail over to ATN
SimulatorState initialState = new SimulatorState(state.outerContext, s, state.useContext, remainingOuterContext);
return execATN(dfa, input, startIndex, initialState);
}
remainingOuterContext = (ParserRuleContext<?>)remainingOuterContext.parent;
s = next;
}
}
if ( s.isAcceptState ) {
if ( s.predicates!=null ) {
if ( dfa_debug ) System.out.println("accept "+s);
}
else {
if ( dfa_debug ) System.out.println("accept; predict "+s.prediction +" in state "+s.stateNumber);
}
acceptState = s;
// keep going unless we're at EOF or state only has one alt number
// mentioned in configs; check if something else could match
// TODO: don't we always stop? only lexer would keep going
// TODO: v3 dfa don't do this.
break;
}
// if no edge, pop over to ATN interpreter, update DFA and return
DFAState target = s.getTarget(t);
if ( target == null ) {
if ( dfa_debug && t>=0 ) System.out.println("no edge for "+parser.getTokenNames()[t]);
int alt;
if ( dfa_debug ) {
System.out.println("ATN exec upon "+
parser.getInputString(startIndex) +
" at DFA state "+s.stateNumber);
}
SimulatorState initialState = new SimulatorState(outerContext, s, state.useContext, remainingOuterContext);
alt = execATN(dfa, input, startIndex, initialState);
// this adds edge even if next state is accept for
// same alt; e.g., s0-A->:s1=>2-B->:s2=>2
// TODO: This next stuff kills edge, but extra states remain. :(
if ( s.isAcceptState && alt!=-1 ) {
DFAState d = s.getTarget(input.LA(1));
if ( d.isAcceptState && d.prediction==s.prediction ) {
// we can carve it out.
s.setTarget(input.LA(1), ERROR); // IGNORE really not error
}
}
if ( dfa_debug ) {
System.out.println("back from DFA update, alt="+alt+", dfa=\n"+dfa.toString(parser.getTokenNames(), parser.getRuleNames()));
//dump(dfa);
}
// action already executed
if ( dfa_debug ) System.out.println("DFA decision "+dfa.decision+
" predicts "+alt);
return alt; // we've updated DFA, exec'd action, and have our deepest answer
}
else if ( target == ERROR ) {
throw noViableAlt(input, outerContext, s.configset, startIndex);
}
s = target;
if ( dfa_debug ) {
if (s.isAcceptState && (!state.useContext || !s.isCtxSensitive)) {
System.out.println("TODO (performance): consumed an unnecessary symbol in execDFA" +
" - make sure to update k below when this is fixed.");
}
}
input.consume();
t = input.LA(1);
}
// if ( acceptState==null ) {
// if ( debug ) System.out.println("!!! no viable alt in dfa");
// return -1;
// }
if ( acceptState.configset.getConflictingAlts()!=null ) {
if ( dfa.atnStartState instanceof DecisionState && ((DecisionState)dfa.atnStartState).isGreedy ) {
// formula for k here is different than execATN because the loop above
int k = input.index() - startIndex; // how much input we used
if ( k == 1 || // SLL(1) == LL(1)
!userWantsCtxSensitive ||
!acceptState.configset.getDipsIntoOuterContext() )
{
// we don't report the ambiguity again
//if ( !acceptState.configset.hasSemanticContext() ) {
// reportAmbiguity(dfa, acceptState, startIndex, input.index(), acceptState.configset.getConflictingAlts(), acceptState.configset);
//}
}
else {
assert !state.useContext;
// Before attempting full context prediction, check to see if there are
// disambiguating or validating predicates to evaluate which allow an
// immediate decision
if ( acceptState.predicates!=null ) {
// rewind input so pred's LT(i) calls make sense
input.seek(startIndex);
int predictedAlt = evalSemanticContext(s.predicates, outerContext, true);
if ( predictedAlt!=ATN.INVALID_ALT_NUMBER ) {
return predictedAlt;
}
}
input.seek(startIndex);
dfa.setContextSensitive(true);
return adaptivePredict(input, dfa.decision, outerContext, true);
}
}
}
// Before jumping to prediction, check to see if there are
// disambiguating or validating predicates to evaluate
if ( s.predicates!=null ) {
// rewind input so pred's LT(i) calls make sense
input.seek(startIndex);
int predictedAlt = evalSemanticContext(s.predicates, outerContext, false);
if ( predictedAlt!=ATN.INVALID_ALT_NUMBER ) {
return predictedAlt;
}
throw noViableAlt(input, outerContext, s.configset, startIndex);
}
if ( dfa_debug ) System.out.println("DFA decision "+dfa.decision+
" predicts "+acceptState.prediction);
return acceptState.prediction;
}
/** Performs ATN simulation to compute a predicted alternative based
* upon the remaining input, but also updates the DFA cache to avoid
* having to traverse the ATN again for the same input sequence.
There are some key conditions we're looking for after computing a new
set of ATN configs (proposed DFA state):
* if the set is empty, there is no viable alternative for current symbol
* does the state uniquely predict an alternative?
* does the state have a conflict that would prevent us from
putting it on the work list?
* if in non-greedy decision is there a config at a rule stop state?
We also have some key operations to do:
* add an edge from previous DFA state to potentially new DFA state, D,
upon current symbol but only if adding to work list, which means in all
cases except no viable alternative (and possibly non-greedy decisions?)
* collecting predicates and adding semantic context to DFA accept states
* adding rule context to context-sensitive DFA accept states
* consuming an input symbol
* reporting a conflict
* reporting an ambiguity
* reporting a context sensitivity
* reporting insufficient predicates
We should isolate those operations, which are side-effecting, to the
main work loop. We can isolate lots of code into other functions, but
they should be side effect free. They can return package that
indicates whether we should report something, whether we need to add a
DFA edge, whether we need to augment accept state with semantic
context or rule invocation context. Actually, it seems like we always
add predicates if they exist, so that can simply be done in the main
loop for any accept state creation or modification request.
cover these cases:
dead end
single alt
single alt + preds
conflict
conflict + preds
TODO: greedy + those
*/
public int execATN(@NotNull DFA dfa,
@NotNull SymbolStream<? extends Symbol> input, int startIndex,
@NotNull SimulatorState initialState)
{
if ( debug ) System.out.println("execATN decision "+dfa.decision+" exec LA(1)=="+ getLookaheadName(input));
ATN_failover++;
final ParserRuleContext<?> outerContext = initialState.outerContext;
final boolean useContext = initialState.useContext;
int t = input.LA(1);
DecisionState decState = atn.getDecisionState(dfa.decision);
boolean greedy = decState.isGreedy;
SimulatorState previous = initialState;
PredictionContextCache contextCache = new PredictionContextCache(dfa.isContextSensitive());
while (true) { // while more work
SimulatorState nextState = computeReachSet(dfa, previous, t, greedy, contextCache);
if (nextState == null) throw noViableAlt(input, outerContext, previous.s0.configset, startIndex);
DFAState D = nextState.s0;
ATNConfigSet reach = nextState.s0.configset;
int predictedAlt = getUniqueAlt(reach);
if ( predictedAlt!=ATN.INVALID_ALT_NUMBER ) {
D.isAcceptState = true;
D.prediction = predictedAlt;
if (optimize_ll1
&& input.index() == startIndex
&& nextState.outerContext == nextState.remainingOuterContext
&& dfa.decision >= 0
&& greedy
&& !D.configset.hasSemanticContext())
{
if (t >= 0 && t <= Short.MAX_VALUE) {
int key = (dfa.decision << 16) + t;
LL1Table.put(key, predictedAlt);
}
}
if (useContext && always_try_local_context) {
retry_with_context_indicates_no_conflict++;
reportContextSensitivity(dfa, nextState, startIndex, input.index());
}
}
else {
D.configset.setConflictingAlts(getConflictingAlts(reach));
if ( D.configset.getConflictingAlts()!=null ) {
if ( greedy ) {
D.isAcceptState = true;
D.prediction = predictedAlt = resolveToMinAlt(D, D.configset.getConflictingAlts());
int k = input.index() - startIndex + 1; // how much input we used
// System.out.println("used k="+k);
if ( k == 1 || // SLL(1) == LL(1)
!userWantsCtxSensitive ||
!D.configset.getDipsIntoOuterContext() )
{
if ( !D.configset.hasSemanticContext() ) {
reportAmbiguity(dfa, D, startIndex, input.index(), D.configset.getConflictingAlts(), D.configset);
}
}
else {
int ambigIndex = input.index();
if ( D.isAcceptState && D.configset.hasSemanticContext() ) {
int nalts = decState.getNumberOfTransitions();
List<DFAState.PredPrediction> predPredictions =
predicateDFAState(D, D.configset, outerContext, nalts);
if (predPredictions != null) {
IntervalSet conflictingAlts = getConflictingAltsFromConfigSet(D.configset);
if ( D.predicates.size() < conflictingAlts.size() ) {
reportInsufficientPredicates(dfa, startIndex, ambigIndex,
conflictingAlts,
decState,
getPredsForAmbigAlts(conflictingAlts, D.configset, nalts),
D.configset,
false);
}
input.seek(startIndex);
predictedAlt = evalSemanticContext(predPredictions, outerContext, true);
if ( predictedAlt!=ATN.INVALID_ALT_NUMBER ) {
return predictedAlt;
}
}
}
if ( debug ) System.out.println("RETRY with outerContext="+outerContext);
dfa.setContextSensitive(true);
SimulatorState fullContextState = computeStartState(dfa, outerContext, true);
reportAttemptingFullContext(dfa, fullContextState, startIndex, ambigIndex);
input.seek(startIndex);
return execATN(dfa, input, startIndex, fullContextState);
}
}
else {
// upon ambiguity for nongreedy, default to exit branch to avoid inf loop
// this handles case where we find ambiguity that stops DFA construction
// before a config hits rule stop state. Was leaving prediction blank.
int exitAlt = 2;
D.isAcceptState = true; // when ambig or ctx sens or nongreedy or .* loop hitting rule stop
D.prediction = predictedAlt = exitAlt;
}
}
}
if ( !greedy ) {
int exitAlt = 2;
if ( predictedAlt != ATN.INVALID_ALT_NUMBER && configWithAltAtStopState(reach, 1) ) {
if ( debug ) System.out.println("nongreedy loop but unique alt "+D.configset.getUniqueAlt()+" at "+reach);
// reaches end via .* means nothing after.
D.isAcceptState = true;
D.prediction = predictedAlt = exitAlt;
}
else {// if we reached end of rule via exit branch and decision nongreedy, we matched
if ( configWithAltAtStopState(reach, exitAlt) ) {
if ( debug ) System.out.println("nongreedy at stop state for exit branch");
D.isAcceptState = true;
D.prediction = predictedAlt = exitAlt;
}
}
}
if ( D.isAcceptState && D.configset.hasSemanticContext() ) {
int nalts = decState.getNumberOfTransitions();
List<DFAState.PredPrediction> predPredictions =
predicateDFAState(D, D.configset, outerContext, nalts);
if ( predPredictions!=null ) {
IntervalSet conflictingAlts = getConflictingAltsFromConfigSet(D.configset);
if ( D.predicates.size() < conflictingAlts.size() ) {
reportInsufficientPredicates(dfa, startIndex, input.index(),
conflictingAlts,
decState,
getPredsForAmbigAlts(conflictingAlts, D.configset, nalts),
D.configset,
false);
}
input.seek(startIndex);
predictedAlt = evalSemanticContext(predPredictions, outerContext, false);
if ( predictedAlt!=ATN.INVALID_ALT_NUMBER ) {
return predictedAlt;
}
}
if (D.prediction == ATN.INVALID_ALT_NUMBER) {
throw noViableAlt(input, outerContext, D.configset, startIndex);
}
predictedAlt = D.prediction;
}
if ( D.isAcceptState ) return predictedAlt;
previous = nextState;
input.consume();
t = input.LA(1);
}
}
protected SimulatorState computeReachSet(DFA dfa, SimulatorState previous, int t, boolean greedy, PredictionContextCache contextCache) {
final boolean useContext = previous.useContext;
RuleContext remainingGlobalContext = previous.remainingOuterContext;
List<ATNConfig> closureConfigs = new ArrayList<ATNConfig>(previous.s0.configset);
List<Integer> contextElements = null;
ATNConfigSet reach = new ATNConfigSet(!useContext);
boolean stepIntoGlobal;
do {
boolean hasMoreContext = !useContext || remainingGlobalContext != null;
ATNConfigSet reachIntermediate = new ATNConfigSet(!useContext);
int ncl = closureConfigs.size();
for (int ci=0; ci<ncl; ci++) { // TODO: foreach
ATNConfig c = closureConfigs.get(ci);
if ( debug ) System.out.println("testing "+getTokenName(t)+" at "+c.toString());
int n = c.state.getNumberOfTransitions();
for (int ti=0; ti<n; ti++) { // for each transition
Transition trans = c.state.transition(ti);
ATNState target = getReachableTarget(trans, t);
if ( target!=null ) {
reachIntermediate.add(new ATNConfig(c, target));
}
}
}
final boolean collectPredicates = false;
stepIntoGlobal = closure(reachIntermediate, reach, collectPredicates, dfa.isContextSensitive(), greedy, contextCache.isContextSensitive(), hasMoreContext, contextCache);
if (previous.useContext && stepIntoGlobal) {
reach.clear();
int nextContextElement = remainingGlobalContext.isEmpty() ? PredictionContext.EMPTY_STATE_KEY : remainingGlobalContext.invokingState;
if (contextElements == null) {
contextElements = new ArrayList<Integer>();
}
if (remainingGlobalContext.isEmpty()) {
remainingGlobalContext = null;
} else {
remainingGlobalContext = remainingGlobalContext.parent;
}
contextElements.add(nextContextElement);
if (nextContextElement != PredictionContext.EMPTY_STATE_KEY) {
for (int i = 0; i < closureConfigs.size(); i++) {
closureConfigs.set(i, closureConfigs.get(i).appendContext(nextContextElement));
}
}
}
} while (useContext && stepIntoGlobal);
if (reach.isEmpty()) {
return null;
}
DFAState dfaState = null;
if (previous.s0 != null) {
dfaState = addDFAEdge(dfa, previous.s0.configset, t, contextElements, reach);
}
return new SimulatorState(previous.outerContext, dfaState, useContext, (ParserRuleContext<?>)remainingGlobalContext);
}
@NotNull
public SimulatorState computeStartState(DFA dfa,
ParserRuleContext<?> globalContext,
boolean useContext)
{
DFAState s0 = dfa.s0;
if (s0 != null) {
if (!useContext) {
return new SimulatorState(globalContext, s0, useContext, globalContext);
}
s0.setContextSensitive(atn);
}
final int decision = dfa.decision;
@NotNull
final ATNState p = dfa.atnStartState;
int previousContext = 0;
RuleContext remainingGlobalContext = globalContext;
PredictionContext initialContext = PredictionContext.EMPTY; // always at least the implicit call to start rule
if (useContext) {
while (s0 != null && s0.isCtxSensitive && remainingGlobalContext != null) {
DFAState next;
if (remainingGlobalContext.isEmpty()) {
next = s0.getContextTarget(PredictionContext.EMPTY_STATE_KEY);
previousContext = PredictionContext.EMPTY_STATE_KEY;
remainingGlobalContext = null;
}
else {
next = s0.getContextTarget(remainingGlobalContext.invokingState);
previousContext = remainingGlobalContext.invokingState;
initialContext = initialContext.appendContext(remainingGlobalContext.invokingState);
remainingGlobalContext = remainingGlobalContext.parent;
}
if (next == null) {
break;
}
s0 = next;
}
}
if (s0 != null && !s0.isCtxSensitive) {
return new SimulatorState(globalContext, s0, useContext, (ParserRuleContext<?>)remainingGlobalContext);
}
ATNConfigSet configs = new ATNConfigSet(!useContext);
DecisionState decState = null;
if ( atn.decisionToState.size()>0 ) {
decState = atn.decisionToState.get(decision);
}
PredictionContextCache contextCache = new PredictionContextCache(dfa.isContextSensitive());
boolean greedy = decState == null || decState.isGreedy;
while (true) {
ATNConfigSet reachIntermediate = new ATNConfigSet(!useContext);
int n = p.getNumberOfTransitions();
for (int ti=0; ti<n; ti++) {
// for each transition
ATNState target = p.transition(ti).target;
reachIntermediate.add(new ATNConfig(target, ti + 1, initialContext));
}
boolean hasMoreContext = remainingGlobalContext != null;
final boolean collectPredicates = true;
boolean stepIntoGlobal = closure(reachIntermediate, configs, collectPredicates, dfa.isContextSensitive(), greedy, contextCache.isContextSensitive(), hasMoreContext, contextCache);
DFAState next = addDFAState(dfa, configs);
if (s0 == null) {
dfa.s0 = next;
}
else {
s0.setContextTarget(previousContext, next);
}
s0 = next;
if (!useContext || !stepIntoGlobal) {
break;
}
// TODO: make sure it distinguishes empty stack states
next.setContextSensitive(atn);
configs.clear();
int nextContextElement = remainingGlobalContext.isEmpty() ? PredictionContext.EMPTY_STATE_KEY : remainingGlobalContext.invokingState;
if (remainingGlobalContext.isEmpty()) {
remainingGlobalContext = null;
} else {
remainingGlobalContext = remainingGlobalContext.parent;
}
if (nextContextElement != PredictionContext.EMPTY_STATE_KEY) {
initialContext = initialContext.appendContext(nextContextElement);
}
previousContext = nextContextElement;
}
return new SimulatorState(globalContext, s0, useContext, (ParserRuleContext<?>)remainingGlobalContext);
}
@Nullable
public ATNState getReachableTarget(@NotNull Transition trans, int ttype) {
if ( trans instanceof AtomTransition ) {
AtomTransition at = (AtomTransition)trans;
if ( at.label == ttype ) {
return at.target;
}
}
else if ( trans instanceof SetTransition ) {
SetTransition st = (SetTransition)trans;
boolean not = trans instanceof NotSetTransition;
if ( !not && st.set.contains(ttype) || not && !st.set.contains(ttype) ) {
return st.target;
}
}
else if ( trans instanceof RangeTransition ) {
RangeTransition rt = (RangeTransition)trans;
if ( ttype>=rt.from && ttype<=rt.to ) return rt.target;
}
else if ( trans instanceof WildcardTransition && ttype!=Token.EOF ) {
return trans.target;
}
return null;
}
/** collect and set D's semantic context */
public List<DFAState.PredPrediction> predicateDFAState(DFAState D,
ATNConfigSet configs,
RuleContext outerContext,
int nalts)
{
IntervalSet conflictingAlts = getConflictingAltsFromConfigSet(configs);
if ( debug ) System.out.println("predicateDFAState "+D);
SemanticContext[] altToPred = getPredsForAmbigAlts(conflictingAlts, configs, nalts);
// altToPred[uniqueAlt] is now our validating predicate (if any)
List<DFAState.PredPrediction> predPredictions = null;
if ( altToPred!=null ) {
// we have a validating predicate; test it
// Update DFA so reach becomes accept state with predicate
predPredictions = getPredicatePredictions(conflictingAlts, altToPred);
D.predicates = predPredictions;
D.prediction = ATN.INVALID_ALT_NUMBER; // make sure we use preds
}
return predPredictions;
}
public SemanticContext[] getPredsForAmbigAlts(@NotNull IntervalSet ambigAlts,
@NotNull ATNConfigSet configs,
int nalts)
{
// REACH=[1|1|[]|0:0, 1|2|[]|0:1]
SemanticContext[] altToPred = new SemanticContext[nalts +1];
int n = altToPred.length;
for (ATNConfig c : configs) {
if ( ambigAlts.contains(c.alt) ) {
altToPred[c.alt] = SemanticContext.or(altToPred[c.alt], c.semanticContext);
}
}
int nPredAlts = 0;
for (int i = 0; i < n; i++) {
if (altToPred[i] == null) {
altToPred[i] = SemanticContext.NONE;
}
else if (altToPred[i] != SemanticContext.NONE) {
nPredAlts++;
}
}
// Optimize away p||p and p&&p
for (int i = 0; i < altToPred.length; i++) {
if ( altToPred[i]!=null ) altToPred[i] = altToPred[i].optimize();
}
// nonambig alts are null in altToPred
if ( nPredAlts==0 ) altToPred = null;
if ( debug ) System.out.println("getPredsForAmbigAlts result "+Arrays.toString(altToPred));
return altToPred;
}