do_not_use_antlr_rust/
parser_atn_simulator.rs

1//! Base parser implementation
2use std::borrow::Borrow;
3use std::cell::Cell;
4use std::collections::{HashMap, HashSet};
5
6use std::marker::PhantomData;
7use std::ops::{Deref, DerefMut};
8use std::rc::Rc;
9use std::sync::Arc;
10use std::{ptr, usize};
11
12use bit_set::BitSet;
13
14use crate::atn::{ATN, INVALID_ALT};
15use crate::atn_config::ATNConfig;
16use crate::atn_config_set::ATNConfigSet;
17use crate::atn_simulator::{BaseATNSimulator, IATNSimulator};
18use crate::atn_state::ATNStateType::RuleStopState;
19use crate::atn_state::{ATNDecisionState, ATNState, ATNStateRef, ATNStateType, ATNSTATE_BLOCK_END};
20use crate::dfa::{ScopeExt, DFA};
21use crate::dfa_state::{DFAState, DFAStateRef, PredPrediction};
22use crate::errors::{ANTLRError, NoViableAltError};
23use crate::int_stream::EOF;
24use crate::interval_set::IntervalSet;
25use crate::lexer_atn_simulator::ERROR_DFA_STATE_REF;
26use crate::parser::{Parser, ParserNodeType};
27
28use crate::prediction_context::{
29    MurmurHasherBuilder, PredictionContext, PredictionContextCache, EMPTY_PREDICTION_CONTEXT,
30    PREDICTION_CONTEXT_EMPTY_RETURN_STATE,
31};
32use crate::prediction_mode::*;
33use crate::semantic_context::SemanticContext;
34use crate::token::{Token, TOKEN_EOF, TOKEN_EPSILON};
35
36use crate::token_stream::TokenStream;
37use crate::transition::{
38    ActionTransition, EpsilonTransition, PrecedencePredicateTransition, PredicateTransition,
39    RuleTransition, Transition, TransitionType,
40};
41use parking_lot::{RwLock, RwLockUpgradableReadGuard, RwLockWriteGuard};
42
43/// ### The embodiment of the adaptive LL(*), ALL(*), parsing strategy.
44///
45/// <p>
46/// The basic complexity of the adaptive strategy makes it harder to understand.
47/// We begin with ATN simulation to build paths in a DFA. Subsequent prediction
48/// requests go through the DFA first. If they reach a state without an edge for
49/// the current symbol, the algorithm fails over to the ATN simulation to
50/// complete the DFA path for the current input (until it finds a conflict state
51/// or uniquely predicting state).</p>
52///
53/// <p>
54/// All of that is done without using the outer context because we want to create
55/// a DFA that is not dependent upon the rule invocation stack when we do a
56/// prediction. One DFA works in all contexts. We avoid using context not
57/// necessarily because it's slower, although it can be, but because of the DFA
58/// caching problem. The closure routine only considers the rule invocation stack
59/// created during prediction beginning in the decision rule. For example, if
60/// prediction occurs without invoking another rule's ATN, there are no context
61/// stacks in the configurations. When lack of context leads to a conflict, we
62/// don't know if it's an ambiguity or a weakness in the strong LL(*) parsing
63/// strategy (versus full LL(*)).</p>
64///
65/// <p>
66/// When SLL yields a configuration set with conflict, we rewind the input and
67/// retry the ATN simulation, this time using full outer context without adding
68/// to the DFA. Configuration context stacks will be the full invocation stacks
69/// from the start rule. If we get a conflict using full context, then we can
70/// definitively say we have a true ambiguity for that input sequence. If we
71/// don't get a conflict, it implies that the decision is sensitive to the outer
72/// context. (It is not context-sensitive in the sense of context-sensitive
73/// grammars.)</p>
74///
75/// <p>
76/// The next time we reach this DFA state with an SLL conflict, through DFA
77/// simulation, we will again retry the ATN simulation using full context mode.
78/// This is slow because we can't save the results and have to "interpret" the
79/// ATN each time we get that input.</p>
80///
81/// **For more info see Java version**
82#[derive(Debug)]
83pub struct ParserATNSimulator {
84    base: BaseATNSimulator,
85    prediction_mode: Cell<PredictionMode>,
86    start_index: Cell<isize>,
87    // pd:PhantomData<P>
88}
89
90/// Just a local helper structure to spoil function parameters as little as possible
91struct Local<'a, 'input, T: Parser<'input>> {
92    outer_context: Rc<<T::Node as ParserNodeType<'input>>::Type>,
93    dfa: Option<RwLockUpgradableReadGuard<'a, DFA>>,
94    dfa_mut: Option<RwLockWriteGuard<'a, DFA>>,
95    merge_cache: &'a mut MergeCache,
96    precedence: isize,
97    parser: &'a mut T,
98    pd: PhantomData<Box<dyn TokenStream<'input, TF = T::TF>>>,
99}
100
101impl<'a, 'input, T: Parser<'input> + 'a> Local<'a, 'input, T> {
102    fn dfa(&self) -> &DFA { self.dfa.as_deref().unwrap() }
103    fn dfa_mut(&mut self) -> &mut DFA { self.dfa_mut.as_mut().unwrap().deref_mut() }
104    fn upgrade_lock(&mut self) {
105        let lock = self.dfa.take().unwrap();
106        self.dfa_mut = Some(RwLockUpgradableReadGuard::upgrade(lock));
107    }
108    fn downgrade_lock(&mut self) {
109        let lock = self.dfa_mut.take().unwrap();
110        self.dfa = Some(RwLockWriteGuard::downgrade_to_upgradable(lock));
111    }
112    fn input(&mut self) -> &mut dyn TokenStream<'input, TF = T::TF> {
113        self.parser.get_input_stream_mut()
114    }
115    // fn seek(&mut self, i: isize) { self.input().seek(i) }
116    fn outer_context(&self) -> &<T::Node as ParserNodeType<'input>>::Type {
117        self.outer_context.deref()
118    }
119}
120
121pub(crate) type MergeCache = HashMap<
122    (Arc<PredictionContext>, Arc<PredictionContext>),
123    Arc<PredictionContext>,
124    MurmurHasherBuilder,
125>;
126
127impl ParserATNSimulator {
128    /// creates new `ParserATNSimulator`
129    pub fn new(
130        atn: Arc<ATN>,
131        decision_to_dfa: Arc<Vec<RwLock<DFA>>>,
132        shared_context_cache: Arc<PredictionContextCache>,
133    ) -> ParserATNSimulator {
134        ParserATNSimulator {
135            base: BaseATNSimulator::new_base_atnsimulator(
136                atn,
137                decision_to_dfa,
138                shared_context_cache,
139            ),
140            prediction_mode: Cell::new(PredictionMode::LL),
141            start_index: Cell::new(0),
142        }
143    }
144
145    /// Returns current prediction mode
146    pub fn get_prediction_mode(&self) -> PredictionMode { self.prediction_mode.get() }
147
148    /// Sets current prediction mode
149    pub fn set_prediction_mode(&self, v: PredictionMode) { self.prediction_mode.set(v) }
150
151    // fn reset(&self) { unimplemented!() }
152
153    /// Called by generated parser to choose an alternative when LL(1) parsing is not enough
154    pub fn adaptive_predict<'a, T: Parser<'a>>(
155        &self,
156        decision: isize,
157        parser: &mut T,
158    ) -> Result<isize, ANTLRError> {
159        self.start_index.set(parser.get_input_stream_mut().index());
160        let mut merge_cache: MergeCache = HashMap::with_hasher(MurmurHasherBuilder {});
161        let mut local = Local {
162            outer_context: parser.get_parser_rule_context().clone(),
163            dfa: self.decision_to_dfa()[decision as usize]
164                .upgradable_read()
165                .into(),
166            dfa_mut: None,
167            merge_cache: &mut merge_cache,
168            precedence: parser.get_precedence(),
169            parser,
170            pd: PhantomData,
171        };
172        //        4!("adaptive_predict decision {}, is_prec {}",decision,local.dfa.is_precedence_dfa());
173
174        let m = local.input().mark();
175
176        let result = {
177            let s0 = if local.dfa().is_precedence_dfa() {
178                local
179                    .dfa()
180                    .get_precedence_start_state(local.precedence /*parser.get_precedence()*/)
181            } else {
182                local.dfa().s0
183            };
184
185            let s0 = s0.unwrap_or_else(|| {
186                let s0_closure = self.compute_start_state(
187                    local.dfa().atn_start_state,
188                    // PredictionContext::from_rule_context::<'a,T::Node>(self.atn(), empty_ctx::<T::Node>().as_ref()),
189                    EMPTY_PREDICTION_CONTEXT.clone(),
190                    false,
191                    &mut local,
192                );
193                local.upgrade_lock();
194                let mut s0;
195                if local.dfa_mut().is_precedence_dfa() {
196                    s0 = local.dfa_mut().s0.unwrap();
197                    let s0_closure_updated = self.apply_precedence_filter(&s0_closure, &mut local);
198                    local.dfa_mut().states[s0].configs = Box::new(s0_closure);
199
200                    s0 = self.add_dfastate(
201                        local.dfa_mut(),
202                        DFAState::new_dfastate(0, Box::new(s0_closure_updated)),
203                    );
204
205                    local
206                        .dfa_mut
207                        .as_mut()
208                        .unwrap()
209                        .set_precedence_start_state(local.precedence, s0);
210                } else {
211                    s0 = self.add_dfastate(
212                        local.dfa_mut(),
213                        DFAState::new_dfastate(0, Box::new(s0_closure)),
214                    );
215                    local.dfa_mut().s0.replace(s0);
216                }
217                local.downgrade_lock();
218                s0
219            });
220
221            self.exec_atn(&mut local, s0)?
222        };
223
224        local.input().seek(self.start_index.get());
225        local.input().release(m);
226        //        println!("result = {}", result);
227        Ok(result)
228    }
229
230    #[allow(non_snake_case)]
231    fn exec_atn<'a, T: Parser<'a>>(
232        &self,
233        local: &mut Local<'_, 'a, T>,
234        s0: DFAStateRef,
235    ) -> Result<isize, ANTLRError> {
236        let mut previousD = s0;
237
238        let mut token = local.input().la(1);
239
240        loop {
241            //            println!("exec atn loop previous D {}",previousD as isize -1);
242            let D = Self::get_existing_target_state(local.dfa(), previousD, token)
243                .unwrap_or_else(|| self.compute_target_state(previousD, token, local));
244            debug_assert!(D > 0);
245
246            let dfa = local.dfa.take().unwrap();
247            let states = &dfa.states;
248            if D == ERROR_DFA_STATE_REF {
249                let previousDstate = &states[previousD];
250                let err = self.no_viable_alt(
251                    local,
252                    previousDstate.configs.as_ref(),
253                    self.start_index.get(),
254                );
255                local.input().seek(self.start_index.get());
256                let alt = self.get_syn_valid_or_sem_invalid_alt_that_finished_decision_entry_rule(
257                    previousDstate.configs.as_ref(),
258                    local,
259                );
260                if alt != INVALID_ALT {
261                    return Ok(alt);
262                }
263                return Err(err);
264            }
265
266            let Dstate = &states[D];
267            if Dstate.requires_full_context && self.prediction_mode.get() != PredictionMode::SLL {
268                let mut conflicting_alts = Dstate.configs.conflicting_alts.clone(); //todo get rid of clone?
269                if !Dstate.predicates.is_empty() {
270                    let conflict_index = local.input().index();
271                    if conflict_index != self.start_index.get() {
272                        local.input().seek(self.start_index.get())
273                    }
274
275                    conflicting_alts = self.eval_semantic_context(local, &Dstate.predicates, true);
276                    //                    println!("conflicting_alts {:?}",&conflicting_alts);
277                    if conflicting_alts.len() == 1 {
278                        return Ok(conflicting_alts.iter().next().unwrap() as isize);
279                    }
280
281                    if conflict_index != self.start_index.get() {
282                        local.input().seek(conflict_index)
283                    }
284                }
285
286                self.report_attempting_full_context(
287                    &dfa,
288                    &conflicting_alts,
289                    Dstate.configs.as_ref(),
290                    self.start_index.get(),
291                    local.input().index(),
292                    local.parser,
293                );
294                local.dfa = Some(dfa);
295
296                let s0_closure = self.compute_start_state(
297                    local.dfa().atn_start_state,
298                    PredictionContext::from_rule_context::<T::Node>(
299                        self.atn(),
300                        local.outer_context(),
301                    ),
302                    true,
303                    local,
304                );
305
306                return self.exec_atn_with_full_context(local, s0_closure);
307            }
308
309            if Dstate.is_accept_state {
310                if Dstate.predicates.is_empty() {
311                    //                    println!("prediction !!{}",Dstate.prediction);
312                    return Ok(Dstate.prediction);
313                }
314
315                let stop_index = local.input().index();
316                local.input().seek(self.start_index.get());
317
318                let alts = self.eval_semantic_context(local, &Dstate.predicates, true);
319                match alts.len() {
320                    0 => {
321                        return Err(self.no_viable_alt(
322                            local,
323                            Dstate.configs.as_ref(),
324                            self.start_index.get(),
325                        ))
326                    }
327                    1 => return Ok(alts.iter().next().unwrap() as isize),
328                    _ => {
329                        self.report_ambiguity(
330                            &dfa,
331                            self.start_index.get(),
332                            stop_index,
333                            false,
334                            &alts,
335                            Dstate.configs.as_ref(),
336                            local.parser,
337                        );
338                        return Ok(alts.iter().next().unwrap() as isize);
339                    }
340                }
341            }
342            previousD = D;
343
344            if token != EOF {
345                local.input().consume();
346                token = local.input().la(1);
347            }
348            local.dfa = Some(dfa);
349        }
350    }
351
352    #[allow(non_snake_case)]
353    fn get_existing_target_state(
354        dfa: &DFA,
355        previousD: DFAStateRef,
356        t: isize,
357    ) -> Option<DFAStateRef> {
358        dfa.states[previousD]
359            .edges
360            .get((t + 1) as usize)
361            .and_then(|x| match *x {
362                0 => None,
363                x => Some(x),
364            })
365    }
366
367    #[allow(non_snake_case)]
368    fn compute_target_state<'a, T: Parser<'a>>(
369        &self,
370        // dfa: &mut DFA,
371        previousD: DFAStateRef,
372        t: isize,
373        local: &mut Local<'_, 'a, T>,
374    ) -> DFAStateRef {
375        //        println!("source config {:?}",dfa.states.read()[previousD].configs.as_ref());
376        let reach = {
377            let closure = RwLockUpgradableReadGuard::rwlock(local.dfa.as_ref().unwrap()).read();
378            let closure = closure.states[previousD].configs.as_ref();
379            self.compute_reach_set(closure, t, false, local)
380        };
381        local.upgrade_lock();
382        let dfa = local.dfa_mut();
383        let reach = match reach {
384            None => {
385                self.add_dfaedge(&mut dfa.states[previousD], t, ERROR_DFA_STATE_REF);
386                local.downgrade_lock();
387                return ERROR_DFA_STATE_REF;
388            }
389            Some(x) => x,
390        };
391
392        let predicted_alt = self.get_unique_alt(&reach);
393        //        println!("predicted_alt {}",predicted_alt);
394
395        let mut D = DFAState::new_dfastate(0, reach.into());
396        let reach = D.configs.as_ref();
397
398        if predicted_alt != INVALID_ALT {
399            D.is_accept_state = true;
400            D.configs.set_unique_alt(predicted_alt);
401            D.prediction = predicted_alt
402        } else if self.all_configs_in_rule_stop_state(reach)
403            || has_sll_conflict_terminating_prediction(self.prediction_mode.get(), reach)
404        {
405            let alts = self.get_conflicting_alts(reach);
406            D.prediction = alts.iter().next().unwrap() as isize;
407            D.configs.conflicting_alts = alts;
408            D.requires_full_context = true;
409            D.is_accept_state = true;
410        }
411
412        //        println!("target config {:?}",&D.configs);
413        if D.is_accept_state && D.configs.has_semantic_context() {
414            let decision_state = self.atn().decision_to_state[dfa.decision as usize];
415            self.predicate_dfa_state(&mut D, self.atn().states[decision_state].deref());
416            //            println!("predicates compute target {:?}",&D.predicates);
417            if !D.predicates.is_empty() {
418                D.prediction = INVALID_ALT
419            }
420        }
421
422        let D = self.add_dfastate(dfa, D);
423        self.add_dfaedge(&mut dfa.states[previousD], t, D);
424        local.downgrade_lock();
425        D
426    }
427
428    fn predicate_dfa_state(&self, dfa_state: &mut DFAState, decision_state: &dyn ATNState) {
429        let nalts = decision_state.get_transitions().len();
430        let alts_to_collect_preds_from =
431            self.get_conflicting_alts_or_unique_alt(dfa_state.configs.as_ref());
432        let alt_to_pred = self.get_preds_for_ambig_alts(
433            &alts_to_collect_preds_from,
434            dfa_state.configs.as_ref(),
435            nalts,
436        );
437        if let Some(alt_to_pred) = alt_to_pred {
438            dfa_state.predicates =
439                self.get_predicate_predictions(&alts_to_collect_preds_from, alt_to_pred);
440            dfa_state.prediction = INVALID_ALT;
441        } else {
442            dfa_state.prediction = alts_to_collect_preds_from
443                .iter()
444                .next()
445                .unwrap_or(0 /*in java it is -1 but looks like 0 is good enough*/)
446                as isize;
447        }
448    }
449
450    fn exec_atn_with_full_context<'a, T: Parser<'a>>(
451        &self,
452        local: &mut Local<'_, 'a, T>,
453        // _D: &DFAState,
454        s0: ATNConfigSet,
455    ) -> Result<isize, ANTLRError> {
456        //println!("exec_atn_with_full_context");
457        let full_ctx = true;
458        let mut found_exact_ambig = false;
459        let mut prev = s0;
460        local.input().seek(self.start_index.get());
461        let mut t = local.input().la(1);
462        let mut predicted_alt;
463        // local.upgrade_lock();
464        loop {
465            //            println!("full_ctx loop");
466
467            let reach = self.compute_reach_set(&prev, t, full_ctx, local);
468            prev = match reach {
469                None => {
470                    local.input().seek(self.start_index.get());
471                    let alt = self
472                        .get_syn_valid_or_sem_invalid_alt_that_finished_decision_entry_rule(
473                            &prev, local,
474                        );
475                    if alt != INVALID_ALT {
476                        return Ok(alt);
477                    }
478                    return Err(self.no_viable_alt(local, &prev, self.start_index.get()));
479                }
480                Some(x) => x,
481            };
482
483            let alt_sub_sets = get_conflicting_alt_subsets(&prev);
484            prev.set_unique_alt(self.get_unique_alt(&prev));
485            if prev.get_unique_alt() != INVALID_ALT {
486                predicted_alt = prev.get_unique_alt();
487                break;
488            }
489            if self.prediction_mode.get() != PredictionMode::LL_EXACT_AMBIG_DETECTION {
490                predicted_alt = resolves_to_just_one_viable_alt(&alt_sub_sets);
491                if predicted_alt != INVALID_ALT {
492                    break;
493                }
494            } else if all_subsets_conflict(&alt_sub_sets) && all_subsets_equal(&alt_sub_sets) {
495                found_exact_ambig = true;
496                predicted_alt = get_single_viable_alt(&alt_sub_sets);
497                break;
498            }
499
500            if t != TOKEN_EOF {
501                local.input().consume();
502                t = local.input().la(1);
503            }
504        }
505
506        // local.downgrade_lock();
507        let dfa = local.dfa.take().unwrap();
508        if prev.get_unique_alt() != INVALID_ALT {
509            self.report_context_sensitivity(
510                &dfa,
511                predicted_alt,
512                &prev,
513                self.start_index.get(),
514                local.input().index(),
515                local.parser,
516            );
517            return Ok(predicted_alt);
518        }
519        self.report_ambiguity(
520            &dfa,
521            self.start_index.get(),
522            local.input().index(),
523            found_exact_ambig,
524            &prev.get_alts(),
525            &prev,
526            local.parser,
527        );
528
529        Ok(predicted_alt)
530    }
531
532    // ATNConfigSet is pretty big so should be boxed to move it cheaper
533    fn compute_reach_set<'a, T: Parser<'a>>(
534        &self,
535        closure: &ATNConfigSet,
536        t: isize,
537        full_ctx: bool,
538        local: &mut Local<'_, 'a, T>,
539    ) -> Option<ATNConfigSet> {
540        //        println!("in computeReachSet, starting closure: {:?}",closure);
541        let mut intermediate = ATNConfigSet::new_base_atnconfig_set(full_ctx);
542
543        let mut skipped_stop_states = Vec::<&ATNConfig>::new();
544
545        for c in closure.get_items() {
546            let state = self.atn().states[c.get_state()].as_ref();
547            if let RuleStopState = state.get_state_type() {
548                assert!(c.get_context().unwrap().is_empty());
549                if full_ctx || t == TOKEN_EOF {
550                    skipped_stop_states.push(c);
551                }
552                continue;
553            }
554
555            for tr in state.get_transitions() {
556                self.get_reachable_target(tr.as_ref(), t).map(|target| {
557                    let added = Box::new(c.cloned(self.atn().states[target].as_ref()));
558                    intermediate.add_cached(added, Some(local.merge_cache))
559                });
560            }
561        }
562        //        println!("intermediate {:?}",intermediate);
563
564        let mut look_to_end_of_rule = false;
565        let mut reach = if skipped_stop_states.is_empty()
566            && t != TOKEN_EOF
567            && (intermediate.length() == 1 || self.get_unique_alt(&intermediate) != INVALID_ALT)
568        {
569            look_to_end_of_rule = true;
570            intermediate
571        } else {
572            let mut reach = ATNConfigSet::new_base_atnconfig_set(full_ctx);
573            let mut closure_busy = HashSet::new();
574            //            println!("calc reach {:?}",intermediate.length());
575
576            for c in intermediate.configs {
577                let treat_eofas_epsilon = t == TOKEN_EOF;
578                self.closure(
579                    *c,
580                    &mut reach,
581                    &mut closure_busy,
582                    false,
583                    full_ctx,
584                    treat_eofas_epsilon,
585                    local,
586                );
587            }
588            //            println!("calc reach {:?}",reach);
589            reach
590        };
591
592        if t == TOKEN_EOF {
593            reach = self.remove_all_configs_not_in_rule_stop_state(
594                reach,
595                look_to_end_of_rule,
596                local.merge_cache,
597            );
598        }
599
600        if !skipped_stop_states.is_empty()
601            && (!full_ctx || !self.has_config_in_rule_stop_state(&reach))
602        {
603            for c in skipped_stop_states {
604                reach.add_cached(c.clone().into(), Some(local.merge_cache));
605            }
606        }
607        //        println!("result?");
608        if reach.is_empty() {
609            return None;
610        }
611
612        //        println!("result {:?}",&reach);
613        return Some(reach);
614    }
615
616    fn has_config_in_rule_stop_state(&self, configs: &ATNConfigSet) -> bool {
617        for c in configs.get_items() {
618            if let RuleStopState = self.atn().states[c.get_state()].get_state_type() {
619                return true;
620            }
621        }
622        return false;
623    }
624
625    fn all_configs_in_rule_stop_state(&self, configs: &ATNConfigSet) -> bool {
626        for c in configs.get_items() {
627            if let RuleStopState = self.atn().states[c.get_state()].get_state_type() {
628            } else {
629                return false;
630            }
631        }
632        return true;
633    }
634
635    fn remove_all_configs_not_in_rule_stop_state(
636        &self,
637        configs: ATNConfigSet,
638        look_to_end_of_rule: bool,
639        merge_cache: &mut MergeCache,
640    ) -> ATNConfigSet {
641        if self.all_configs_in_rule_stop_state(&configs) {
642            return configs;
643        }
644
645        // can just remove instead of creating new instance because we own configs
646        // it significantly differs from java version though
647        let mut result = ATNConfigSet::new_base_atnconfig_set(configs.full_context());
648        for c in configs.configs {
649            let state = self.atn().states[c.get_state()].as_ref();
650            if let RuleStopState = state.get_state_type() {
651                result.add_cached(c, Some(merge_cache));
652                continue;
653            }
654
655            if look_to_end_of_rule && state.has_epsilon_only_transitions() {
656                let next_tokens = self.atn().next_tokens(state);
657                if next_tokens.contains(TOKEN_EPSILON) {
658                    let end_of_rule_state = self.atn().rule_to_stop_state[state.get_rule_index()];
659                    result.add_cached(
660                        c.cloned(self.atn().states[end_of_rule_state].as_ref())
661                            .into(),
662                        Some(merge_cache),
663                    );
664                }
665            }
666        }
667
668        result
669    }
670
671    fn compute_start_state<'a, T: Parser<'a>>(
672        &self,
673        a: ATNStateRef,
674        initial_ctx: Arc<PredictionContext>,
675        full_ctx: bool,
676        local: &mut Local<'_, 'a, T>,
677    ) -> ATNConfigSet {
678        //        let initial_ctx = PredictionContext::prediction_context_from_rule_context(self.atn(),ctx);
679        let mut configs = ATNConfigSet::new_base_atnconfig_set(full_ctx);
680        //        println!("initial {:?}",initial_ctx);
681        //        println!("initial state {:?}",a);
682
683        let atn_states = &self.atn().states;
684        for (i, tr) in atn_states[a].get_transitions().iter().enumerate() {
685            let target = &atn_states[tr.get_target()];
686            let c = ATNConfig::new(
687                target.get_state_number(),
688                (i + 1) as isize,
689                Some(initial_ctx.clone()),
690            );
691            let mut closure_busy = HashSet::new();
692            self.closure(
693                c,
694                &mut configs,
695                &mut closure_busy,
696                true,
697                full_ctx,
698                false,
699                local,
700            );
701        }
702        //        println!("start state {:?}",configs);
703
704        configs
705    }
706
707    fn apply_precedence_filter<'a, T: Parser<'a>>(
708        &self,
709        configs: &ATNConfigSet,
710        local: &mut Local<'_, 'a, T>,
711    ) -> ATNConfigSet {
712        //println!("apply_precedence_filter");
713        let mut states_from_alt1 = HashMap::new();
714        let mut config_set = ATNConfigSet::new_base_atnconfig_set(configs.full_context());
715
716        for config in configs.get_items() {
717            if config.get_alt() != 1 {
718                continue;
719            }
720
721            let updated_sem_ctx = config
722                .semantic_context
723                .eval_precedence(local.parser, local.outer_context());
724
725            if let Some(updated_sem_ctx) = updated_sem_ctx.as_deref() {
726                states_from_alt1.insert(config.get_state(), config.get_context());
727
728                if *updated_sem_ctx != *config.semantic_context {
729                    config_set.add_cached(
730                        Box::new(ATNConfig::new_with_semantic(
731                            config.get_state(),
732                            config.get_alt(),
733                            config.get_context().cloned(),
734                            Box::new(updated_sem_ctx.clone()),
735                        )),
736                        Some(local.merge_cache),
737                    );
738                } else {
739                    config_set.add_cached(Box::new(config.clone()), Some(local.merge_cache));
740                }
741            }
742        }
743
744        for config in configs.get_items() {
745            if config.get_alt() == 1 {
746                continue;
747            }
748            if !config.is_precedence_filter_suppressed() {
749                if let Some(context) = states_from_alt1.get(&config.get_state()) {
750                    if *context == config.get_context() {
751                        continue;
752                    }
753                }
754            }
755            config_set.add(Box::new(config.clone()));
756        }
757
758        config_set
759    }
760
761    fn get_reachable_target(&self, trans: &dyn Transition, ttype: isize) -> Option<ATNStateRef> {
762        if trans.matches(ttype, 0, self.atn().max_token_type) {
763            return Some(trans.get_target());
764        }
765        None
766    }
767
768    fn get_preds_for_ambig_alts(
769        &self,
770        ambig_alts: &BitSet,
771        configs: &ATNConfigSet,
772        nalts: usize,
773    ) -> Option<Vec<SemanticContext>> {
774        let mut alt_to_pred = Vec::with_capacity(nalts + 1);
775        alt_to_pred.resize_with(nalts + 1, || None);
776        for c in configs.configs.iter() {
777            let alt = c.get_alt() as usize;
778            if ambig_alts.contains(alt) {
779                alt_to_pred[alt] = Some(SemanticContext::or(
780                    alt_to_pred[alt].as_ref(),
781                    Some(&*c.semantic_context),
782                ));
783            }
784        }
785
786        let alt_to_pred: Vec<SemanticContext> = alt_to_pred
787            .into_iter()
788            .map(|it| {
789                if let Some(inner) = it {
790                    inner
791                } else {
792                    SemanticContext::NONE
793                }
794            })
795            .collect();
796
797        let npred_alts = alt_to_pred
798            .iter()
799            .filter(|it| **it != SemanticContext::NONE)
800            .count();
801
802        if npred_alts == 0 {
803            return None;
804        }
805        return Some(alt_to_pred);
806    }
807
808    fn get_predicate_predictions(
809        &self,
810        ambig_alts: &BitSet,
811        alt_to_pred: Vec<SemanticContext>,
812    ) -> Vec<PredPrediction> {
813        let mut pairs = vec![];
814        let mut contains_predicate = false;
815        for (i, pred) in alt_to_pred.into_iter().enumerate().skip(1) {
816            if pred != SemanticContext::NONE {
817                contains_predicate = true
818            }
819
820            if ambig_alts.contains(i) {
821                pairs.push(PredPrediction {
822                    alt: i as isize,
823                    pred,
824                })
825            }
826        }
827        if !contains_predicate {
828            return Vec::new();
829        }
830
831        pairs
832    }
833
834    fn get_syn_valid_or_sem_invalid_alt_that_finished_decision_entry_rule<'a, T: Parser<'a>>(
835        &self,
836        configs: &ATNConfigSet,
837        local: &mut Local<'_, 'a, T>,
838    ) -> isize {
839        let (sem_valid_configs, sem_invalid_configs) =
840            self.split_according_to_semantic_validity(configs, local);
841
842        let alt = self.get_alt_that_finished_decision_entry_rule(&sem_valid_configs);
843        if alt != INVALID_ALT {
844            return alt;
845        }
846
847        if !sem_invalid_configs.is_empty() {
848            let alt = self.get_alt_that_finished_decision_entry_rule(&sem_invalid_configs);
849            if alt != INVALID_ALT {
850                return alt;
851            }
852        }
853
854        INVALID_ALT
855    }
856
857    fn split_according_to_semantic_validity<'a, T: Parser<'a>>(
858        &self,
859        configs: &ATNConfigSet,
860        local: &mut Local<'_, 'a, T>,
861    ) -> (ATNConfigSet, ATNConfigSet) {
862        let mut succeeded = ATNConfigSet::new_base_atnconfig_set(configs.full_context());
863        let mut failed = ATNConfigSet::new_base_atnconfig_set(configs.full_context());
864        for c in configs.get_items() {
865            let clone = Box::new(c.clone());
866            if *c.semantic_context != SemanticContext::NONE {
867                let predicate_eval_result = self.eval_predicate(
868                    local,
869                    &*c.semantic_context,
870                    c.get_alt(),
871                    configs.full_context(),
872                );
873                if predicate_eval_result {
874                    succeeded.add(clone);
875                } else {
876                    failed.add(clone);
877                }
878            } else {
879                succeeded.add(clone);
880            }
881        }
882        (succeeded, failed)
883    }
884
885    fn get_alt_that_finished_decision_entry_rule(&self, configs: &ATNConfigSet) -> isize {
886        let mut alts = IntervalSet::new();
887        for c in configs.get_items() {
888            let has_empty_path = c.get_context().map(|x| x.has_empty_path()) == Some(true);
889            let is_stop = self.atn().states[c.get_state()].get_state_type() == &RuleStopState;
890            if c.get_reaches_into_outer_context() > 0 || (is_stop && has_empty_path) {
891                alts.add_one(c.get_alt())
892            }
893        }
894
895        return alts.get_min().unwrap_or(INVALID_ALT);
896    }
897
898    fn eval_semantic_context<'a, T: Parser<'a>>(
899        &self,
900        local: &mut Local<'_, 'a, T>,
901        pred_predictions: &Vec<PredPrediction>,
902        complete: bool,
903    ) -> BitSet {
904        let mut predictions = BitSet::new();
905        for pred in pred_predictions {
906            if pred.pred == SemanticContext::NONE {
907                predictions.insert(pred.alt as usize);
908
909                if !complete {
910                    break;
911                }
912                continue;
913            }
914
915            let full_ctx = false;
916            let predicate_evaluation_result =
917                self.eval_predicate(local, &pred.pred, pred.alt, full_ctx);
918
919            if predicate_evaluation_result {
920                predictions.insert(pred.alt as usize);
921                if !complete {
922                    break;
923                }
924            }
925        }
926        predictions
927    }
928
929    fn eval_predicate<'a, T: Parser<'a>>(
930        &self,
931        local: &mut Local<'_, 'a, T>,
932        pred: impl Borrow<SemanticContext>,
933        _alt: isize,
934        _full_ctx: bool,
935    ) -> bool {
936        pred.borrow().evaluate(local.parser, &*local.outer_context)
937    }
938
939    fn closure<'a, T: Parser<'a>>(
940        &self,
941        config: ATNConfig,
942        configs: &mut ATNConfigSet,
943        closure_busy: &mut HashSet<ATNConfig>,
944        collect_predicates: bool,
945        full_ctx: bool,
946        treat_eofas_epsilon: bool,
947        local: &mut Local<'_, 'a, T>,
948    ) {
949        //        println!("cl{}", config.get_state());
950        let initial_depth = 0;
951        //        local.merge_cache.clear();
952
953        self.closure_checking_stop_state(
954            config,
955            configs,
956            closure_busy,
957            collect_predicates,
958            full_ctx,
959            initial_depth,
960            treat_eofas_epsilon,
961            local,
962        );
963        assert!(!full_ctx || !configs.get_dips_into_outer_context())
964    }
965
966    fn closure_checking_stop_state<'a, T: Parser<'a>>(
967        &self,
968        mut config: ATNConfig,
969        configs: &mut ATNConfigSet,
970        closure_busy: &mut HashSet<ATNConfig>,
971        collect_predicates: bool,
972        full_ctx: bool,
973        depth: isize,
974        treat_eofas_epsilon: bool,
975        local: &mut Local<'_, 'a, T>,
976    ) {
977        //        println!("closure({:?})",config);
978        if let RuleStopState = self.atn().states[config.get_state()].get_state_type() {
979            if !config.get_context().unwrap().is_empty() {
980                config.get_context().unwrap().run(|temp| {
981                    if temp.get_return_state(temp.length() - 1)
982                        == PREDICTION_CONTEXT_EMPTY_RETURN_STATE
983                    {
984                        if full_ctx {
985                            let new_config = config.cloned_with_new_ctx(
986                                self.atn().states[config.get_state()].as_ref(),
987                                Some(EMPTY_PREDICTION_CONTEXT.clone()),
988                            );
989                            configs.add_cached(Box::new(new_config), Some(local.merge_cache));
990                        } else {
991                            self.closure_work(
992                                config.clone(),
993                                configs,
994                                closure_busy,
995                                collect_predicates,
996                                full_ctx,
997                                depth,
998                                treat_eofas_epsilon,
999                                local,
1000                            )
1001                        }
1002                    }
1003                });
1004                let context = config.take_context();
1005                for i in 0..context.length() {
1006                    if context.get_return_state(i) == PREDICTION_CONTEXT_EMPTY_RETURN_STATE {
1007                        if i != context.length() - 1 {
1008                            panic!("EMPTY_RETURN_STATE is not last for some reason, please report error")
1009                        }
1010                        continue;
1011                    }
1012                    let return_state = context.get_return_state(i) as ATNStateRef;
1013                    //                    let new_ctx = context.take_parent(i).unwrap();
1014                    let new_ctx = context.get_parent(i).cloned();
1015                    let mut c = ATNConfig::new_with_semantic(
1016                        return_state,
1017                        config.get_alt(),
1018                        new_ctx,
1019                        config.semantic_context.clone(),
1020                    );
1021                    c.set_reaches_into_outer_context(config.get_reaches_into_outer_context());
1022                    assert!(depth > isize::min_value());
1023                    self.closure_checking_stop_state(
1024                        c,
1025                        configs,
1026                        closure_busy,
1027                        collect_predicates,
1028                        full_ctx,
1029                        depth - 1,
1030                        treat_eofas_epsilon,
1031                        local,
1032                    )
1033                }
1034                return;
1035            } else if full_ctx {
1036                configs.add_cached(Box::new(config), Some(local.merge_cache));
1037                return;
1038            } else {
1039            }
1040        }
1041        self.closure_work(
1042            config,
1043            configs,
1044            closure_busy,
1045            collect_predicates,
1046            full_ctx,
1047            depth,
1048            treat_eofas_epsilon,
1049            local,
1050        )
1051    }
1052
1053    fn closure_work<'a, T: Parser<'a>>(
1054        &self,
1055        config: ATNConfig,
1056        configs: &mut ATNConfigSet,
1057        closure_busy: &mut HashSet<ATNConfig>,
1058        collect_predicates: bool,
1059        full_ctx: bool,
1060        depth: isize,
1061        treat_eofas_epsilon: bool,
1062        local: &mut Local<'_, 'a, T>,
1063    ) {
1064        //println!("depth {}",depth);
1065        //        println!("closure_work started {:?}",config);
1066        let p = self.atn().states[config.get_state()].as_ref();
1067        if !p.has_epsilon_only_transitions() {
1068            configs.add_cached(Box::new(config.clone()), Some(local.merge_cache));
1069        }
1070
1071        for (i, tr) in p.get_transitions().iter().enumerate() {
1072            if i == 0 && self.can_drop_loop_entry_edge_in_left_recursive_rule(&config) {
1073                continue;
1074            }
1075
1076            let continue_collecting = tr.get_serialization_type()
1077                != TransitionType::TRANSITION_ACTION
1078                && collect_predicates;
1079            let c = self.get_epsilon_target(
1080                &config,
1081                tr.as_ref(),
1082                continue_collecting,
1083                depth == 0,
1084                full_ctx,
1085                treat_eofas_epsilon,
1086                local,
1087            );
1088            if let Some(mut c) = c {
1089                let mut new_depth = depth;
1090                if let RuleStopState = self.atn().states[config.get_state()].get_state_type() {
1091                    assert!(!full_ctx);
1092
1093                    if local.dfa().is_precedence_dfa() {
1094                        let outermost_precedence_return = tr
1095                            .as_ref()
1096                            .cast::<EpsilonTransition>()
1097                            .outermost_precedence_return;
1098                        let atn_start_state =
1099                            self.atn().states[local.dfa().atn_start_state].as_ref();
1100                        if outermost_precedence_return == atn_start_state.get_rule_index() as isize
1101                        {
1102                            c.set_precedence_filter_suppressed(true);
1103                        }
1104                    }
1105
1106                    c.reaches_into_outer_context += 1;
1107                    if !closure_busy.insert(c.clone()) {
1108                        continue;
1109                    }
1110                    configs.set_dips_into_outer_context(true);
1111                    assert!(new_depth > isize::min_value());
1112                    new_depth -= 1;
1113                } else {
1114                    if !tr.is_epsilon() && !closure_busy.insert(c.clone()) {
1115                        continue;
1116                    }
1117
1118                    if tr.get_serialization_type() == TransitionType::TRANSITION_RULE {
1119                        if new_depth >= 0 {
1120                            new_depth += 1
1121                        }
1122                    }
1123                }
1124
1125                self.closure_checking_stop_state(
1126                    c,
1127                    configs,
1128                    closure_busy,
1129                    continue_collecting,
1130                    full_ctx,
1131                    new_depth,
1132                    treat_eofas_epsilon,
1133                    local,
1134                )
1135            };
1136        }
1137        //        println!("closure_work ended {:?}",config);
1138    }
1139
1140    fn can_drop_loop_entry_edge_in_left_recursive_rule(&self, _config: &ATNConfig) -> bool {
1141        //        if std::env::var("TURN_OFF_LR_LOOP_ENTRY_BRANCH_OPT").ok()
1142        //            .and_then(|it|str::parse::<bool>(&it).ok()) == Some(true)
1143        //        { return false }
1144
1145        let state = self.atn().states[_config.get_state()].as_ref();
1146
1147        if let ATNStateType::DecisionState {
1148            state: ATNDecisionState::StarLoopEntry { is_precedence, .. },
1149            ..
1150        } = state.get_state_type()
1151        {
1152            if !*is_precedence
1153                || _config.get_context().unwrap().is_empty()
1154                || _config.get_context().unwrap().has_empty_path()
1155            {
1156                return false;
1157            }
1158        } else {
1159            return false;
1160        }
1161
1162        let pred_ctx = _config.get_context().unwrap();
1163        let ctx_len = pred_ctx.length();
1164        for i in 0..ctx_len {
1165            let return_state = self.atn().states[pred_ctx.get_return_state(i) as usize].as_ref();
1166            if return_state.get_rule_index() != state.get_rule_index() {
1167                return false;
1168            }
1169        }
1170
1171        let decision_start_state = state.get_transitions()[0].get_target();
1172        let decision_start_state = self.atn().states[decision_start_state].as_ref();
1173        let block_end_state_num = if let ATNStateType::DecisionState {
1174            state: ATNDecisionState::BlockStartState { end_state, .. },
1175            ..
1176        } = decision_start_state.get_state_type()
1177        {
1178            *end_state
1179        } else {
1180            unreachable!("cast error")
1181        };
1182
1183        for i in 0..ctx_len {
1184            let return_state = self.atn().states[pred_ctx.get_return_state(i) as usize].as_ref();
1185            if return_state.get_transitions().len() != 1
1186                || !return_state.get_transitions()[0].is_epsilon()
1187            {
1188                //                println!("test1");
1189                return false;
1190            }
1191            let return_state_target =
1192                self.atn().states[return_state.get_transitions()[0].get_target()].as_ref();
1193            if return_state.get_state_type_id() == ATNSTATE_BLOCK_END
1194                && ptr::eq(return_state_target, state)
1195            {
1196                continue;
1197            }
1198            if return_state.get_state_number() == block_end_state_num {
1199                continue;
1200            }
1201            if return_state_target.get_state_number() == block_end_state_num {
1202                continue;
1203            }
1204
1205            if return_state_target.get_state_type_id() == ATNSTATE_BLOCK_END
1206                && return_state_target.get_transitions().len() == 1
1207                && return_state_target.get_transitions()[0].is_epsilon()
1208                && return_state_target.get_transitions()[0].get_target() == state.get_state_number()
1209            {
1210                continue;
1211            }
1212            //            println!("test2");
1213            return false;
1214        }
1215        //        println!("dropping on state {} ", state.get_state_number());
1216
1217        return true;
1218    }
1219    //
1220    //    fn get_rule_name(&self, index: isize) -> String { unimplemented!() }
1221
1222    fn get_epsilon_target<'a, T: Parser<'a>>(
1223        &self,
1224        config: &ATNConfig,
1225        t: &dyn Transition,
1226        collect_predicates: bool,
1227        in_context: bool,
1228        full_ctx: bool,
1229        treat_eofas_epsilon: bool,
1230        local: &mut Local<'_, 'a, T>,
1231    ) -> Option<ATNConfig> {
1232        match t.get_serialization_type() {
1233            TransitionType::TRANSITION_EPSILON => {
1234                Some(config.cloned(self.atn().states[t.get_target()].as_ref()))
1235            }
1236            TransitionType::TRANSITION_RULE => {
1237                Some(self.rule_transition(config, t.cast::<RuleTransition>()))
1238            }
1239            TransitionType::TRANSITION_PREDICATE => self.pred_transition(
1240                config,
1241                t.cast::<PredicateTransition>(),
1242                collect_predicates,
1243                in_context,
1244                full_ctx,
1245                local,
1246            ),
1247            TransitionType::TRANSITION_ACTION => {
1248                Some(self.action_transition(config, t.cast::<ActionTransition>()))
1249            }
1250            TransitionType::TRANSITION_PRECEDENCE => self.precedence_transition(
1251                config,
1252                t.cast::<PrecedencePredicateTransition>(),
1253                collect_predicates,
1254                in_context,
1255                full_ctx,
1256                local,
1257            ),
1258            TransitionType::TRANSITION_ATOM
1259            | TransitionType::TRANSITION_SET
1260            | TransitionType::TRANSITION_RANGE => {
1261                if treat_eofas_epsilon && t.matches(TOKEN_EOF, 0, 1) {
1262                    Some(config.cloned(self.atn().states[t.get_target()].as_ref()))
1263                } else {
1264                    None
1265                }
1266            }
1267            TransitionType::TRANSITION_NOTSET | TransitionType::TRANSITION_WILDCARD => None,
1268        }
1269    }
1270
1271    fn action_transition(&self, config: &ATNConfig, t: &ActionTransition) -> ATNConfig {
1272        config.cloned(self.atn().states[t.target].as_ref())
1273    }
1274
1275    fn precedence_transition<'a, T: Parser<'a>>(
1276        &self,
1277        config: &ATNConfig,
1278        pt: &PrecedencePredicateTransition,
1279        collect_predicates: bool,
1280        in_context: bool,
1281        full_ctx: bool,
1282        local: &mut Local<'_, 'a, T>,
1283    ) -> Option<ATNConfig> {
1284        let target = self.atn().states[pt.target].deref();
1285        if collect_predicates && in_context {
1286            if full_ctx {
1287                let curr_pos = local.input().index();
1288                local.input().seek(self.start_index.get());
1289                let prec_succeeds = self.eval_predicate(
1290                    local,
1291                    pt.get_predicate().unwrap(),
1292                    config.get_alt(),
1293                    full_ctx,
1294                );
1295                local.input().seek(curr_pos);
1296                if prec_succeeds {
1297                    return Some(config.cloned(target));
1298                }
1299            } else {
1300                let new_sem_ctx =
1301                    SemanticContext::and(Some(&*config.semantic_context), pt.get_predicate());
1302                return Some(config.cloned_with_new_semantic(target, Box::new(new_sem_ctx)));
1303            }
1304        } else {
1305            return Some(config.cloned(target));
1306        }
1307
1308        None
1309    }
1310
1311    fn pred_transition<'a, T: Parser<'a>>(
1312        &self,
1313        config: &ATNConfig,
1314        pt: &PredicateTransition,
1315        collect_predicates: bool,
1316        in_context: bool,
1317        full_ctx: bool,
1318        local: &mut Local<'_, 'a, T>,
1319    ) -> Option<ATNConfig> {
1320        let target = self.atn().states[pt.target].deref();
1321        if collect_predicates && (!pt.is_ctx_dependent || (pt.is_ctx_dependent && in_context)) {
1322            if full_ctx {
1323                let curr_pos = local.input().index();
1324                local.input().seek(self.start_index.get());
1325                let prec_succeeds = self.eval_predicate(
1326                    local,
1327                    pt.get_predicate().unwrap(),
1328                    config.get_alt(),
1329                    full_ctx,
1330                );
1331                local.input().seek(curr_pos);
1332                if prec_succeeds {
1333                    return Some(config.cloned(target));
1334                }
1335            } else {
1336                let new_sem_ctx =
1337                    SemanticContext::and(Some(&*config.semantic_context), pt.get_predicate());
1338                return Some(config.cloned_with_new_semantic(target, Box::new(new_sem_ctx)));
1339            }
1340        } else {
1341            return Some(config.cloned(target));
1342        }
1343
1344        None
1345    }
1346
1347    fn rule_transition(&self, config: &ATNConfig, t: &RuleTransition) -> ATNConfig {
1348        assert!(config.get_context().is_some());
1349        let new_ctx = PredictionContext::new_singleton(
1350            config.get_context().cloned(),
1351            t.follow_state as isize,
1352        );
1353        config.cloned_with_new_ctx(self.atn().states[t.target].as_ref(), Some(new_ctx.into()))
1354    }
1355
1356    fn get_conflicting_alts(&self, configs: &ATNConfigSet) -> BitSet {
1357        let altsets = get_conflicting_alt_subsets(configs);
1358        get_alts(&altsets)
1359    }
1360
1361    //todo can return Cow
1362    fn get_conflicting_alts_or_unique_alt(&self, configs: &ATNConfigSet) -> BitSet {
1363        return if configs.get_unique_alt() != INVALID_ALT {
1364            BitSet::new().modify_with(|it| {
1365                it.insert(configs.get_unique_alt() as usize);
1366            })
1367        } else {
1368            configs.conflicting_alts.clone()
1369        };
1370    }
1371    //
1372    //    fn get_token_name(&self, t: isize) -> String { unimplemented!() }
1373    //
1374    //    fn get_lookahead_name(&self, input: TokenStream) -> String { unimplemented!() }
1375    //
1376    //    fn dump_dead_end_configs(&self, nvae: * NoViableAltError) { unimplemented!() }
1377    //
1378    fn no_viable_alt<'a, T: Parser<'a>>(
1379        &self,
1380        local: &mut Local<'_, 'a, T>,
1381        _configs: &ATNConfigSet,
1382        start_index: isize,
1383    ) -> ANTLRError {
1384        let start_token = local.parser.get_input_stream().get(start_index).borrow();
1385        let start_token = Token::to_owned(start_token);
1386        let offending_token = local.input().lt(1).unwrap().borrow();
1387        let offending_token = Token::to_owned(offending_token);
1388        ANTLRError::NoAltError(NoViableAltError::new_full(
1389            local.parser,
1390            start_token,
1391            offending_token,
1392        ))
1393    }
1394
1395    fn get_unique_alt(&self, configs: &ATNConfigSet) -> isize {
1396        let mut alt = INVALID_ALT;
1397        for c in configs.get_items() {
1398            if alt == INVALID_ALT {
1399                alt = c.get_alt()
1400            } else if c.get_alt() != alt {
1401                return INVALID_ALT;
1402            }
1403        }
1404
1405        alt
1406    }
1407
1408    fn add_dfaedge(&self, from: &mut DFAState, t: isize, to: DFAStateRef) -> DFAStateRef {
1409        if t < -1 || t > self.atn().max_token_type {
1410            return to;
1411        }
1412        if from.edges.is_empty() {
1413            from.edges.resize(self.atn().max_token_type as usize + 2, 0);
1414        }
1415        from.edges[(t + 1) as usize] = to;
1416
1417        to
1418    }
1419
1420    fn add_dfastate(&self, dfa: &mut DFA, mut dfastate: DFAState) -> DFAStateRef {
1421        if dfastate.state_number == ERROR_DFA_STATE_REF {
1422            return ERROR_DFA_STATE_REF;
1423        }
1424        let states = &mut dfa.states;
1425
1426        let state_number = states.len();
1427        dfastate.state_number = state_number;
1428
1429        let key = dfastate.default_hash();
1430        //let mut new_hash = key;
1431        if let Some(st) = dfa.states_map.get_mut(&key) {
1432            if let Some(&st) = st.iter().find(|&&it| states[it] == dfastate) {
1433                return st;
1434            }
1435        }
1436
1437        if !dfastate.configs.read_only() {
1438            dfastate.configs.optimize_configs(self);
1439            dfastate.configs.set_read_only(true);
1440            //    new_hash = dfastate.default_hash();
1441        }
1442
1443        states.push(dfastate);
1444
1445        //        if key != new_hash {
1446        dfa.states_map
1447            .entry(key)
1448            .or_insert(Vec::new())
1449            .push(state_number);
1450        //        }
1451        state_number
1452    }
1453
1454    fn report_attempting_full_context<'a, T: Parser<'a>>(
1455        &self,
1456        dfa: &DFA,
1457        conflicting_alts: &BitSet,
1458        configs: &ATNConfigSet,
1459        start_index: isize,
1460        stop_index: isize,
1461        parser: &mut T,
1462    ) {
1463        //        let ambig_index = parser.get_current_token().get_token_index();
1464        parser
1465            .get_error_lister_dispatch()
1466            .report_attempting_full_context(
1467                parser,
1468                dfa,
1469                start_index,
1470                stop_index,
1471                conflicting_alts,
1472                configs,
1473            )
1474    }
1475
1476    fn report_context_sensitivity<'a, T: Parser<'a>>(
1477        &self,
1478        dfa: &DFA,
1479        prediction: isize,
1480        configs: &ATNConfigSet,
1481        start_index: isize,
1482        stop_index: isize,
1483        parser: &mut T,
1484    ) {
1485        parser
1486            .get_error_lister_dispatch()
1487            .report_context_sensitivity(parser, dfa, start_index, stop_index, prediction, configs)
1488    }
1489
1490    fn report_ambiguity<'a, T: Parser<'a>>(
1491        &self,
1492        dfa: &DFA,
1493        start_index: isize,
1494        stop_index: isize,
1495        exact: bool,
1496        ambig_alts: &BitSet,
1497        configs: &ATNConfigSet,
1498        parser: &mut T,
1499    ) {
1500        parser.get_error_lister_dispatch().report_ambiguity(
1501            parser,
1502            dfa,
1503            start_index,
1504            stop_index,
1505            exact,
1506            ambig_alts,
1507            configs,
1508        )
1509    }
1510}
1511
1512impl IATNSimulator for ParserATNSimulator {
1513    fn shared_context_cache(&self) -> &PredictionContextCache { self.base.shared_context_cache() }
1514
1515    fn atn(&self) -> &ATN { self.base.atn() }
1516
1517    fn decision_to_dfa(&self) -> &Vec<RwLock<DFA>> { self.base.decision_to_dfa() }
1518}