ParseInfo

///
///
///
/// This class provides access to specific and aggregate statistics gathered
/// during profiling of a parser.
///
/// -  4.3
///
public class ParseInfo {
    internal let atnSimulator: ProfilingATNSimulator
    public init(_ atnSimulator: ProfilingATNSimulator) {
        self.atnSimulator = atnSimulator
    }
    ///
    /// Gets an array of _org.antlr.v4.runtime.atn.DecisionInfo_ instances containing the profiling
    /// information gathered for each decision in the ATN.
    ///
    /// - returns: An array of _org.antlr.v4.runtime.atn.DecisionInfo_ instances, indexed by decision
    /// number.
    ///
    public func getDecisionInfo() -> [DecisionInfo] {
        return atnSimulator.getDecisionInfo()
    }
    ///
    /// Gets the decision numbers for decisions that required one or more
    /// full-context predictions during parsing. These are decisions for which
    /// _org.antlr.v4.runtime.atn.DecisionInfo#LL_Fallback_ is non-zero.
    ///
    /// - returns: A list of decision numbers which required one or more
    /// full-context predictions during parsing.
    ///
    public func getLLDecisions() -> Array<Int> {
        let decisions: [DecisionInfo] = atnSimulator.getDecisionInfo()
        var LL: Array<Int> = Array<Int>()
        let length = decisions.count
        for i in 0..<length {
            let fallBack: Int64 = decisions[i].LL_Fallback
            if fallBack > 0 {
                LL.append(i)
                // LL.add(i);
            }
        }
        return LL
    }
    ///
    /// Gets the total time spent during prediction across all decisions made
    /// during parsing. This value is the sum of
    /// _org.antlr.v4.runtime.atn.DecisionInfo#timeInPrediction_ for all decisions.
    ///
    public func getTotalTimeInPrediction() -> Int64 {
        let decisions: [DecisionInfo] = atnSimulator.getDecisionInfo()
        var t: Int64 = 0
        for d in decisions {
            t += d.timeInPrediction
        }
        return t
    }
    ///
    /// Gets the total number of SLL lookahead operations across all decisions
    /// made during parsing. This value is the sum of
    /// _org.antlr.v4.runtime.atn.DecisionInfo#SLL_TotalLook_ for all decisions.
    ///
    public func getTotalSLLLookaheadOps() -> Int64 {
        let decisions: [DecisionInfo] = atnSimulator.getDecisionInfo()
        var k: Int64 = 0
        for d in decisions {
            k += d.SLL_TotalLook
        }
        return k
    }
    ///
    /// Gets the total number of LL lookahead operations across all decisions
    /// made during parsing. This value is the sum of
    /// _org.antlr.v4.runtime.atn.DecisionInfo#LL_TotalLook_ for all decisions.
    ///
    public func getTotalLLLookaheadOps() -> Int64 {
        let decisions: [DecisionInfo] = atnSimulator.getDecisionInfo()
        var k: Int64 = 0
        for d in decisions {
            k += d.LL_TotalLook
        }
        return k
    }
    ///
    /// Gets the total number of ATN lookahead operations for SLL prediction
    /// across all decisions made during parsing.
    ///
    public func getTotalSLLATNLookaheadOps() -> Int64 {
        let decisions: [DecisionInfo] = atnSimulator.getDecisionInfo()
        var k: Int64 = 0
        for d in decisions {
            k += d.SLL_ATNTransitions
        }
        return k
    }
    ///
    /// Gets the total number of ATN lookahead operations for LL prediction
    /// across all decisions made during parsing.
    ///
    public func getTotalLLATNLookaheadOps() -> Int64 {
        let decisions: [DecisionInfo] = atnSimulator.getDecisionInfo()
        var k: Int64 = 0
        for d in decisions {
            k += d.LL_ATNTransitions
        }
        return k
    }
    ///
    /// Gets the total number of ATN lookahead operations for SLL and LL
    /// prediction across all decisions made during parsing.
    ///
    ///
    /// This value is the sum of _#getTotalSLLATNLookaheadOps_ and
    /// _#getTotalLLATNLookaheadOps_.
    ///
    public func getTotalATNLookaheadOps() -> Int64 {
        let decisions: [DecisionInfo] = atnSimulator.getDecisionInfo()
        var k: Int64 = 0
        for d in decisions {
            k += d.SLL_ATNTransitions
            k += d.LL_ATNTransitions
        }
        return k
    }
    ///
    /// Gets the total number of DFA states stored in the DFA cache for all
    /// decisions in the ATN.
    ///
    public func getDFASize() -> Int {
        var n: Int = 0
        let decisionToDFA: [DFA] = atnSimulator.decisionToDFA
        let length = decisionToDFA.count
        for i in 0..<length {
            n += getDFASize(i)
        }
        return n
    }
    ///
    /// Gets the total number of DFA states stored in the DFA cache for a
    /// particular decision.
    ///
    public func getDFASize(_ decision: Int) -> Int {
        let decisionToDFA: DFA = atnSimulator.decisionToDFA[decision]
        return decisionToDFA.states.count
    }
}


EpsilonTransition

///
///
public final class EpsilonTransition: Transition, CustomStringConvertible {
    private let outermostPrecedenceReturnInside: Int
    public convenience override init(_ target: ATNState) {
        self.init(target, -1)
    }
    public init(_ target: ATNState, _ outermostPrecedenceReturn: Int) {
        self.outermostPrecedenceReturnInside = outermostPrecedenceReturn
        super.init(target)
    }
    ///
    /// - returns: the rule index of a precedence rule for which this transition is
    /// returning from, where the precedence value is 0; otherwise, -1.
    ///
    /// - seealso: org.antlr.v4.runtime.atn.ATNConfig#isPrecedenceFilterSuppressed()
    /// - seealso: org.antlr.v4.runtime.atn.ParserATNSimulator#applyPrecedenceFilter(org.antlr.v4.runtime.atn.ATNConfigSet)
    /// -  4.4.1
    ///
    public func outermostPrecedenceReturn() -> Int {
        return outermostPrecedenceReturnInside
    }
    override
    public func getSerializationType() -> Int {
        return Transition.EPSILON
    }
    override
    public func isEpsilon() -> Bool {
        return true
    }
    override
    public func matches(_ symbol: Int, _ minVocabSymbol: Int, _ maxVocabSymbol: Int) -> Bool {
        return false
    }
    public var description: String {
        return "epsilon"
    }
}


ATNState

///
///
///
///
/// The following images show the relation of states and
/// _org.antlr.v4.runtime.atn.ATNState#transitions_ for various grammar constructs.
///
///
/// * Solid edges marked with an ε indicate a required
/// _org.antlr.v4.runtime.atn.EpsilonTransition_.
///
/// * Dashed edges indicate locations where any transition derived from
/// _org.antlr.v4.runtime.atn.Transition_ might appear.
///
/// * Dashed nodes are place holders for either a sequence of linked
/// _org.antlr.v4.runtime.atn.BasicState_ states or the inclusion of a block representing a nested
/// construct in one of the forms below.
///
/// * Nodes showing multiple outgoing alternatives with a `...` support
/// any number of alternatives (one or more). Nodes without the `...` only
/// support the exact number of alternatives shown in the diagram.
///
///
/// ## Basic Blocks
///
/// ### Rule
///
///
///
/// ## Block of 1 or more alternatives
///
///
///
/// ## Greedy Loops
///
/// ### Greedy Closure: `(...)*`
///
///
///
/// ### Greedy Positive Closure: `(...)+`
///
///
///
/// ### Greedy Optional: `(...)?`
///
///
///
/// ## Non-Greedy Loops
///
/// ### Non-Greedy Closure: `(...)*?`
///
///
///
/// ### Non-Greedy Positive Closure: `(...)+?`
///
///
///
/// ### Non-Greedy Optional: `(...)??`
///
///
///
///
public class ATNState: Hashable, CustomStringConvertible {
    // constants for serialization
    public static let INVALID_TYPE: Int = 0
    public static let BASIC: Int = 1
    public static let RULE_START: Int = 2
    public static let BLOCK_START: Int = 3
    public static let PLUS_BLOCK_START: Int = 4
    public static let STAR_BLOCK_START: Int = 5
    public static let TOKEN_START: Int = 6
    public static let RULE_STOP: Int = 7
    public static let BLOCK_END: Int = 8
    public static let STAR_LOOP_BACK: Int = 9
    public static let STAR_LOOP_ENTRY: Int = 10
    public static let PLUS_LOOP_BACK: Int = 11
    public static let LOOP_END: Int = 12
    public static let serializationNames: Array<String> =
    ["INVALID",
        "BASIC",
        "RULE_START",
        "BLOCK_START",
        "PLUS_BLOCK_START",
        "STAR_BLOCK_START",
        "TOKEN_START",
        "RULE_STOP",
        "BLOCK_END",
        "STAR_LOOP_BACK",
        "STAR_LOOP_ENTRY",
        "PLUS_LOOP_BACK",
        "LOOP_END"]
    public static let INVALID_STATE_NUMBER: Int = -1
    ///
    /// Which ATN are we in?
    ///
    public final var atn: ATN? = nil
    public internal(set) final var stateNumber: Int = INVALID_STATE_NUMBER
    public internal(set) final var ruleIndex: Int?
    // at runtime, we don't have Rule objects
    public private(set) final var epsilonOnlyTransitions: Bool = false
    ///
    /// Track the transitions emanating from this ATN state.
    ///
    internal private(set) final var transitions = [Transition]()
    ///
    /// Used to cache lookahead during parsing, not used during construction
    ///
    public internal(set) final var nextTokenWithinRule: IntervalSet?
    public func hash(into hasher: inout Hasher) {
        hasher.combine(stateNumber)
    }
    public func isNonGreedyExitState() -> Bool {
        return false
    }
    public var description: String {
        //return "MyClass \(string)"
        return String(stateNumber)
    }
    public final func getTransitions() -> [Transition] {
        return transitions
    }
    public final func getNumberOfTransitions() -> Int {
        return transitions.count
    }
    public final func addTransition(_ e: Transition) {
        if transitions.isEmpty {
            epsilonOnlyTransitions = e.isEpsilon()
        }
        else if epsilonOnlyTransitions != e.isEpsilon() {
            print("ATN state %d has both epsilon and non-epsilon transitions.\n", String(stateNumber))
            epsilonOnlyTransitions = false
        }
        var alreadyPresent = false
        for t in transitions {
            if t.target.stateNumber == e.target.stateNumber {
                if let tLabel = t.labelIntervalSet(), let eLabel = e.labelIntervalSet(), tLabel == eLabel {
//                    print("Repeated transition upon \(eLabel) from \(stateNumber)->\(t.target.stateNumber)")
                    alreadyPresent = true
                    break
                }
                else if t.isEpsilon() && e.isEpsilon() {
//                    print("Repeated epsilon transition from \(stateNumber)->\(t.target.stateNumber)")
                    alreadyPresent = true
                    break
                }
            }
        }
        if !alreadyPresent {
            transitions.append(e)
        }
    }
    public final func transition(_ i: Int) -> Transition {
        return transitions[i]
    }
    public final func setTransition(_ i: Int, _ e: Transition) {
        transitions[i] = e
    }
    public final func removeTransition(_ index: Int) -> Transition {
        return transitions.remove(at: index)
    }
    public func getStateType() -> Int {
        fatalError(#function + " must be overridden")
    }
    public final func onlyHasEpsilonTransitions() -> Bool {
        return epsilonOnlyTransitions
    }
    public final func setRuleIndex(_ ruleIndex: Int) {
        self.ruleIndex = ruleIndex
    }
}
public func ==(lhs: ATNState, rhs: ATNState) -> Bool {
    if lhs === rhs {
        return true
    }
    // are these states same object?
    return lhs.stateNumber == rhs.stateNumber
}


WildcardTransition

///
///
final public class WildcardTransition: Transition, CustomStringConvertible {
    public override init(_ target: ATNState) {
        super.init(target)
    }
    override
    public func getSerializationType() -> Int {
        return Transition.WILDCARD
    }
    override
    public func matches(_ symbol: Int, _ minVocabSymbol: Int, _ maxVocabSymbol: Int) -> Bool {
        return symbol >= minVocabSymbol && symbol <= maxVocabSymbol
    }
    public var description: String {
        return "."
    }
}


LexerActionType

///
///
///
/// Represents the serialization type of a _org.antlr.v4.runtime.atn.LexerAction_.
///
/// -  Sam Harwell
/// -  4.2
///
public enum LexerActionType: Int {
    ///
    /// The type of a _org.antlr.v4.runtime.atn.LexerChannelAction_ action.
    ///
    case channel = 0
    ///
    /// The type of a _org.antlr.v4.runtime.atn.LexerCustomAction_ action.
    ///
    case custom
    ///
    /// The type of a _org.antlr.v4.runtime.atn.LexerModeAction_ action.
    ///
    case mode
    ///
    /// The type of a _org.antlr.v4.runtime.atn.LexerMoreAction_ action.
    ///
    case more
    ///
    /// The type of a _org.antlr.v4.runtime.atn.LexerPopModeAction_ action.
    ///
    case popMode
    ///
    /// The type of a _org.antlr.v4.runtime.atn.LexerPushModeAction_ action.
    ///
    case pushMode
    ///
    /// The type of a _org.antlr.v4.runtime.atn.LexerSkipAction_ action.
    ///
    case skip
    ///
    /// The type of a _org.antlr.v4.runtime.atn.LexerTypeAction_ action.
    ///
    case type
}


LexerSkipAction

///
///
///
/// Implements the `skip` lexer action by calling _org.antlr.v4.runtime.Lexer#skip_.
///
/// The `skip` command does not have any parameters, so this action is
/// implemented as a singleton instance exposed by _#INSTANCE_.
///
/// -  Sam Harwell
/// -  4.2
///
public final class LexerSkipAction: LexerAction, CustomStringConvertible {
    ///
    /// Provides a singleton instance of this parameterless lexer action.
    ///
    public static let INSTANCE: LexerSkipAction = LexerSkipAction()
    ///
    /// Constructs the singleton instance of the lexer `skip` command.
    ///
    private override init() {
    }
    ///
    ///
    /// - returns: This method returns _org.antlr.v4.runtime.atn.LexerActionType#SKIP_.
    ///
    override
    public func getActionType() -> LexerActionType {
        return LexerActionType.skip
    }
    ///
    ///
    /// - returns: This method returns `false`.
    ///
    override
    public func isPositionDependent() -> Bool {
        return false
    }
    ///
    ///
    ///
    /// This action is implemented by calling _org.antlr.v4.runtime.Lexer#skip_.
    ///
    override
    public func execute(_ lexer: Lexer) {
        lexer.skip()
    }
    public override func hash(into hasher: inout Hasher) {
        hasher.combine(ObjectIdentifier(self))
    }
    public var description: String {
        return "skip"
    }
}
public func ==(lhs: LexerSkipAction, rhs: LexerSkipAction) -> Bool {
    return lhs === rhs
}


LoopEndState

///
///
///
/// Mark the end of a * or + loop.
///
public final class LoopEndState: ATNState {
    public var loopBackState: ATNState?
    override
    public func getStateType() -> Int {
        return ATNState.LOOP_END
    }
}


DefaultATNConfig

///
///
//
//  DefaultATNConfig.swift
//  antlr.swift
//
//  Created by janyou on 15/9/14.
//
import Foundation
//public struct DefaultATNConfig: ATNConfig {
//    public var state: ATNState
//    public var alt: Int
//    public var context: PredictionContext?
//    public var semanticContext: SemanticContext
//    public var hashValue: Int {
//
//        var hashCode: Int = 7
//        hashCode = 31 * hashCode + state.stateNumber
//        hashCode = 31 * hashCode + alt
//        hashCode = 31 * hashCode + semanticContext.hashValue
//        return hashCode
//
//    }
//
//
//}
//
//public func ==(lhs: DefaultATNConfig, rhs: DefaultATNConfig) -> Bool {
//
//    if lhs === rhs {
//        return true
//    }
//
//    let same: Bool =
//    lhs.state.stateNumber == rhs.state.stateNumber &&
//            lhs.alt == rhs.alt &&
//            lhs.semanticContext == rhs.semanticContext
//
//    return same
//
//}
//public class DefaultATNConfig: ATNConfig {
//
//    override
//    public var hashValue: Int {
//
//        var hashCode: Int = 7
//        hashCode = 31 * hashCode + state.stateNumber
//        hashCode = 31 * hashCode + alt
//        hashCode = 31 * hashCode + semanticContext.hashValue
//        return hashCode
//
//    }
//
//
//}
//
//public func ==(lhs: DefaultATNConfig, rhs: DefaultATNConfig) -> Bool {
//
//    if lhs === rhs {
//        return true
//    }
//
//    let same: Bool =
//    lhs.state.stateNumber == rhs.state.stateNumber &&
//            lhs.alt == rhs.alt &&
//            lhs.semanticContext == rhs.semanticContext
//
//    return same
//
//}


RuleTransition

///
///
public final class RuleTransition: Transition {
    ///
    /// Ptr to the rule definition object for this rule ref
    ///
    public let ruleIndex: Int
    // no Rule object at runtime
    public let precedence: Int
    ///
    /// What node to begin computations following ref to rule
    ///
    public let followState: ATNState
    public init(_ ruleStart: RuleStartState,
                _ ruleIndex: Int,
                _ precedence: Int,
                _ followState: ATNState) {
        self.ruleIndex = ruleIndex
        self.precedence = precedence
        self.followState = followState
        super.init(ruleStart)
    }
    override
    public func getSerializationType() -> Int {
        return Transition.RULE
    }
    override
    public func isEpsilon() -> Bool {
        return true
    }
    override
    public func matches(_ symbol: Int, _ minVocabSymbol: Int, _ maxVocabSymbol: Int) -> Bool {
        return false
    }
}


StarLoopEntryState

///
///
public final class StarLoopEntryState: DecisionState {
    public var loopBackState: StarLoopbackState?
    ///
    /// Indicates whether this state can benefit from a precedence DFA during SLL
    /// decision making.
    ///
    /// This is a computed property that is calculated during ATN deserialization
    /// and stored for use in _org.antlr.v4.runtime.atn.ParserATNSimulator_ and
    /// _org.antlr.v4.runtime.ParserInterpreter_.
    ///
    /// - seealso: org.antlr.v4.runtime.dfa.DFA#isPrecedenceDfa()
    ///
    public var precedenceRuleDecision: Bool = false
    override
    public func getStateType() -> Int {
        return ATNState.STAR_LOOP_ENTRY
    }
}


LexerChannelAction

///
///
///
/// Implements the `channel` lexer action by calling
/// _org.antlr.v4.runtime.Lexer#setChannel_ with the assigned channel.
///
/// -  Sam Harwell
/// -  4.2
///
public final class LexerChannelAction: LexerAction, CustomStringConvertible {
    fileprivate let channel: Int
    ///
    /// Constructs a new `channel` action with the specified channel value.
    /// - parameter channel: The channel value to pass to _org.antlr.v4.runtime.Lexer#setChannel_.
    ///
    public init(_ channel: Int) {
        self.channel = channel
    }
    ///
    /// Gets the channel to use for the _org.antlr.v4.runtime.Token_ created by the lexer.
    ///
    /// - returns: The channel to use for the _org.antlr.v4.runtime.Token_ created by the lexer.
    ///
    public func getChannel() -> Int {
        return channel
    }
    ///
    ///
    /// - returns: This method returns _org.antlr.v4.runtime.atn.LexerActionType#CHANNEL_.
    ///
    public override func getActionType() -> LexerActionType {
        return LexerActionType.channel
    }
    ///
    ///
    /// - returns: This method returns `false`.
    ///
    public override func isPositionDependent() -> Bool {
        return false
    }
    ///
    ///
    ///
    /// This action is implemented by calling _org.antlr.v4.runtime.Lexer#setChannel_ with the
    /// value provided by _#getChannel_.
    ///
    public override func execute(_ lexer: Lexer) {
        lexer.setChannel(channel)
    }
    public override func hash(into hasher: inout Hasher) {
        hasher.combine(getActionType())
        hasher.combine(channel)
    }
    public var description: String {
        return "channel\(channel)"
    }
}
public func ==(lhs: LexerChannelAction, rhs: LexerChannelAction) -> Bool {
    if lhs === rhs {
        return true
    }
    return lhs.channel == rhs.channel
}


PlusBlockStartState

///
///
///
/// Start of `(A|B|...)+` loop. Technically a decision state, but
/// we don't use for code generation; somebody might need it, so I'm defining
/// it for completeness. In reality, the _org.antlr.v4.runtime.atn.PlusLoopbackState_ node is the
/// real decision-making note for `A+`.
///
public final class PlusBlockStartState: BlockStartState {
    public var loopBackState: PlusLoopbackState?
    override
    public func getStateType() -> Int {
        return ATNState.PLUS_BLOCK_START
    }
}


RangeTransition

///
///
public final class RangeTransition: Transition, CustomStringConvertible {
    public let from: Int
    public let to: Int
    public init(_ target: ATNState, _ from: Int, _ to: Int) {
        self.from = from
        self.to = to
        super.init(target)
    }
    override
    public func getSerializationType() -> Int {
        return Transition.RANGE
    }
    override
    public func labelIntervalSet() -> IntervalSet? {
        return IntervalSet.of(from, to)
    }
    override
    public func matches(_ symbol: Int, _ minVocabSymbol: Int, _ maxVocabSymbol: Int) -> Bool {
        return symbol >= from && symbol <= to
    }
    public var description: String {
        return "'" + String(from) + "'..'" + String(to) + "'"
    }
}


ContextSensitivityInfo

///
///
///
/// This class represents profiling event information for a context sensitivity.
/// Context sensitivities are decisions where a particular input resulted in an
/// SLL conflict, but LL prediction produced a single unique alternative.
///
///
/// In some cases, the unique alternative identified by LL prediction is not
/// equal to the minimum represented alternative in the conflicting SLL
/// configuration set. Grammars and inputs which result in this scenario are
/// unable to use _org.antlr.v4.runtime.atn.PredictionMode#SLL_, which in turn means they cannot use
/// the two-stage parsing strategy to improve parsing performance for that
/// input.
///
/// - seealso: org.antlr.v4.runtime.atn.ParserATNSimulator#reportContextSensitivity
/// - seealso: org.antlr.v4.runtime.ANTLRErrorListener#reportContextSensitivity
///
/// -  4.3
///
public class ContextSensitivityInfo: DecisionEventInfo {
    ///
    /// Constructs a new instance of the _org.antlr.v4.runtime.atn.ContextSensitivityInfo_ class
    /// with the specified detailed context sensitivity information.
    ///
    /// - parameter decision: The decision number
    /// - parameter configs: The final configuration set containing the unique
    /// alternative identified by full-context prediction
    /// - parameter input: The input token stream
    /// - parameter startIndex: The start index for the current prediction
    /// - parameter stopIndex: The index at which the context sensitivity was
    /// identified during full-context prediction
    ///
    public init(_ decision: Int,
                _ configs: ATNConfigSet,
                _ input: TokenStream, _ startIndex: Int, _ stopIndex: Int) {
        super.init(decision, configs, input, startIndex, stopIndex, true)
    }
}


DecisionState

///
///
public class DecisionState: ATNState {
    public var decision: Int = -1
    public var nonGreedy: Bool = false
}


StarBlockStartState

///
///
///
/// The block that begins a closure loop.
///
public final class StarBlockStartState: BlockStartState {
    override
    public func getStateType() -> Int {
        return ATNState.STAR_BLOCK_START
    }
}


RuleStopState

///
///
///
/// The last node in the ATN for a rule, unless that rule is the start symbol.
/// In that case, there is one transition to EOF. Later, we might encode
/// references to all calls to this rule to compute FOLLOW sets for
/// error handling.
///
public final class RuleStopState: ATNState {
    override
    public func getStateType() -> Int {
        return ATNState.RULE_STOP
    }
}


RuleStartState

///
///
public final class RuleStartState: ATNState {
    public var stopState: RuleStopState?
    public var isPrecedenceRule: Bool = false
    //Synonymous with rule being left recursive; consider renaming.
    override
    public func getStateType() -> Int {
        return ATNState.RULE_START
    }
}


EmptyPredictionContext

///
///
public class EmptyPredictionContext: SingletonPredictionContext {
    ///
    /// Represents `$` in local context prediction, which means wildcard.
    /// `+x = *`.
    ///
    public static let Instance = EmptyPredictionContext()
    public init() {
        super.init(nil, PredictionContext.EMPTY_RETURN_STATE)
    }
    override
    public func isEmpty() -> Bool {
        return true
    }
    override
    public func size() -> Int {
        return 1
    }
    override
    public func getParent(_ index: Int) -> PredictionContext? {
        return nil
    }
    override
    public func getReturnState(_ index: Int) -> Int {
        return returnState
    }
    override
    public var description: String {
        return "$"
    }
}
public func ==(lhs: EmptyPredictionContext, rhs: EmptyPredictionContext) -> Bool {
    if lhs === rhs {
        return true
    }
    return false
}


LookaheadEventInfo

///
///
///
/// This class represents profiling event information for tracking the lookahead
/// depth required in order to make a prediction.
///
/// -  4.3
///
public class LookaheadEventInfo: DecisionEventInfo {
    ///
    /// Constructs a new instance of the _org.antlr.v4.runtime.atn.LookaheadEventInfo_ class with
    /// the specified detailed lookahead information.
    ///
    /// - parameter decision: The decision number
    /// - parameter configs: The final configuration set containing the necessary
    /// information to determine the result of a prediction, or `null` if
    /// the final configuration set is not available
    /// - parameter input: The input token stream
    /// - parameter startIndex: The start index for the current prediction
    /// - parameter stopIndex: The index at which the prediction was finally made
    /// - parameter fullCtx: `true` if the current lookahead is part of an LL
    /// prediction; otherwise, `false` if the current lookahead is part of
    /// an SLL prediction
    ///
    public override init(_ decision: Int,
                         _ configs: ATNConfigSet?,
                         _ input: TokenStream, _ startIndex: Int, _ stopIndex: Int,
                         _ fullCtx: Bool) {
        super.init(decision, configs, input, startIndex, stopIndex, fullCtx)
    }
}


NotSetTransition

///
///
public final class NotSetTransition: SetTransition {
//	public override init(_ target : ATNState, inout _ set : IntervalSet?) {
//		super.init(target, &set);
//	}
    override
    public func getSerializationType() -> Int {
        return Transition.NOT_SET
    }
    override
    public func matches(_ symbol: Int, _ minVocabSymbol: Int, _ maxVocabSymbol: Int) -> Bool {
        return symbol >= minVocabSymbol
                && symbol <= maxVocabSymbol
                && !super.matches(symbol, minVocabSymbol, maxVocabSymbol)
    }
    override
    public var description: String {
        return "~" + super.description
    }
}


LexerIndexedCustomAction

///
///
///
/// This implementation of _org.antlr.v4.runtime.atn.LexerAction_ is used for tracking input offsets
/// for position-dependent actions within a _org.antlr.v4.runtime.atn.LexerActionExecutor_.
///
/// This action is not serialized as part of the ATN, and is only required for
/// position-dependent lexer actions which appear at a location other than the
/// end of a rule. For more information about DFA optimizations employed for
/// lexer actions, see _org.antlr.v4.runtime.atn.LexerActionExecutor#append_ and
/// _org.antlr.v4.runtime.atn.LexerActionExecutor#fixOffsetBeforeMatch_.
///
/// -  Sam Harwell
/// -  4.2
///
public final class LexerIndexedCustomAction: LexerAction {
    fileprivate let offset: Int
    fileprivate let action: LexerAction
    ///
    /// Constructs a new indexed custom action by associating a character offset
    /// with a _org.antlr.v4.runtime.atn.LexerAction_.
    ///
    /// Note: This class is only required for lexer actions for which
    /// _org.antlr.v4.runtime.atn.LexerAction#isPositionDependent_ returns `true`.
    ///
    /// - parameter offset: The offset into the input _org.antlr.v4.runtime.CharStream_, relative to
    /// the token start index, at which the specified lexer action should be
    /// executed.
    /// - parameter action: The lexer action to execute at a particular offset in the
    /// input _org.antlr.v4.runtime.CharStream_.
    ///
    public init(_ offset: Int, _ action: LexerAction) {
        self.offset = offset
        self.action = action
    }
    ///
    /// Gets the location in the input _org.antlr.v4.runtime.CharStream_ at which the lexer
    /// action should be executed. The value is interpreted as an offset relative
    /// to the token start index.
    ///
    /// - returns: The location in the input _org.antlr.v4.runtime.CharStream_ at which the lexer
    /// action should be executed.
    ///
    public func getOffset() -> Int {
        return offset
    }
    ///
    /// Gets the lexer action to execute.
    ///
    /// - returns: A _org.antlr.v4.runtime.atn.LexerAction_ object which executes the lexer action.
    ///
    public func getAction() -> LexerAction {
        return action
    }
    ///
    ///
    ///
    /// - returns: This method returns the result of calling _#getActionType_
    /// on the _org.antlr.v4.runtime.atn.LexerAction_ returned by _#getAction_.
    ///
    public override func getActionType() -> LexerActionType {
        return action.getActionType()
    }
    ///
    ///
    /// - returns: This method returns `true`.
    ///
    public override func isPositionDependent() -> Bool {
        return true
    }
    ///
    ///
    ///
    /// This method calls _#execute_ on the result of _#getAction_
    /// using the provided `lexer`.
    ///
    public override func execute(_ lexer: Lexer) throws {
        // assume the input stream position was properly set by the calling code
        try action.execute(lexer)
    }
    public override func hash(into hasher: inout Hasher) {
        hasher.combine(offset)
        hasher.combine(action)
    }
}
public func ==(lhs: LexerIndexedCustomAction, rhs: LexerIndexedCustomAction) -> Bool {
    if lhs === rhs {
        return true
    }
    return lhs.offset == rhs.offset
            && lhs.action == rhs.action
}


LookupDictionary

///
///
//
//  LookupDictionary.swift
//   antlr.swift
//
//  Created by janyou on 15/9/23.
//
import Foundation
public enum LookupDictionaryType: Int {
    case lookup = 0
    case ordered
}
public struct LookupDictionary {
    private let type: LookupDictionaryType
    private var cache = [Int: ATNConfig]()
    public init(type: LookupDictionaryType = LookupDictionaryType.lookup) {
        self.type = type
    }
    private func hash(_ config: ATNConfig) -> Int {
        if type == LookupDictionaryType.lookup {
            /* migrating to XCode 12.3/Swift 5.3 introduced a very weird bug
             where reading hashValue from a SemanticContext.AND instance woul:
                call the AND empty constructor
                NOT call AND.hash(into)
             Could it be a Swift compiler bug ?
             All tests pass when using Hasher.combine()
             Keeping the old code for reference:

                var hashCode: Int = 7
                hashCode = 31 * hashCode + config.state.stateNumber
                hashCode = 31 * hashCode + config.alt
                hashCode = 31 * hashCode + config.semanticContext.hashValue // <- the crash would occur here
                return hashCode

            */
            var hasher = Hasher()
            hasher.combine(7)
            hasher.combine(config.state.stateNumber)
            hasher.combine(config.alt)
            hasher.combine(config.semanticContext)
            return hasher.finalize()
        } else {
            //Ordered
            return config.hashValue
        }
    }
    private func equal(_ lhs: ATNConfig, _ rhs: ATNConfig) -> Bool {
        if type == LookupDictionaryType.lookup {
            if lhs === rhs {
                return true
            }
            return
                lhs.state.stateNumber == rhs.state.stateNumber &&
                    lhs.alt == rhs.alt &&
                    lhs.semanticContext == rhs.semanticContext
        }
        else {
            //Ordered
            return lhs == rhs
        }
    }
    public mutating func getOrAdd(_ config: ATNConfig) -> ATNConfig {
        let h = hash(config)
        if let configList = cache[h] {
            return configList
        }
        else {
            cache[h] = config
        }
        return config
    }
    public var isEmpty: Bool {
        return cache.isEmpty
    }
    public func contains(_ config: ATNConfig) -> Bool {
        let h = hash(config)
        return cache[h] != nil
    }
    public mutating func removeAll() {
        cache.removeAll()
    }
}


StarLoopbackState

///
///
public final class StarLoopbackState: ATNState {
    public func getLoopEntryState() -> StarLoopEntryState {
        return transition(0).target as! StarLoopEntryState
    }
    override
    public func getStateType() -> Int {
        return ATNState.STAR_LOOP_BACK
    }
}


ATNType

///
///
///
/// Represents the type of recognizer an ATN applies to.
///
/// -  Sam Harwell
///
public enum ATNType: Int {
    ///
    /// A lexer grammar.
    ///
    case lexer = 0
    ///
    /// A parser grammar.
    ///
    case parser
}


SemanticContext

///
///
///
/// A tree structure used to record the semantic context in which
/// an ATN configuration is valid.  It's either a single predicate,
/// a conjunction `p1&&p2`, or a sum of products `p1||p2`.
///
/// I have scoped the _org.antlr.v4.runtime.atn.SemanticContext.AND_, _org.antlr.v4.runtime.atn.SemanticContext.OR_, and _org.antlr.v4.runtime.atn.SemanticContext.Predicate_ subclasses of
/// _org.antlr.v4.runtime.atn.SemanticContext_ within the scope of this outer class.
///
import Foundation
public class SemanticContext: Hashable, CustomStringConvertible {
    ///
    /// For context independent predicates, we evaluate them without a local
    /// context (i.e., null context). That way, we can evaluate them without
    /// having to create proper rule-specific context during prediction (as
    /// opposed to the parser, which creates them naturally). In a practical
    /// sense, this avoids a cast exception from RuleContext to myruleContext.
    ///
    /// For context dependent predicates, we must pass in a local context so that
    /// references such as $arg evaluate properly as _localctx.arg. We only
    /// capture context dependent predicates in the context in which we begin
    /// prediction, so we passed in the outer context here in case of context
    /// dependent predicate evaluation.
    ///
    public func eval<T>(_ parser: Recognizer<T>, _ parserCallStack: RuleContext) throws -> Bool {
        fatalError(#function + " must be overridden")
    }
    ///
    /// Evaluate the precedence predicates for the context and reduce the result.
    ///
    /// - parameter parser: The parser instance.
    /// - parameter parserCallStack:
    /// - returns: The simplified semantic context after precedence predicates are
    /// evaluated, which will be one of the following values.
    /// * _#NONE_: if the predicate simplifies to `true` after
    /// precedence predicates are evaluated.
    /// * `null`: if the predicate simplifies to `false` after
    /// precedence predicates are evaluated.
    /// * `this`: if the semantic context is not changed as a result of
    /// precedence predicate evaluation.
    /// * A non-`null` _org.antlr.v4.runtime.atn.SemanticContext_: the new simplified
    /// semantic context after precedence predicates are evaluated.
    ///
    public func evalPrecedence<T>(_ parser: Recognizer<T>, _ parserCallStack: RuleContext) throws -> SemanticContext? {
        return self
    }
    public func hash(into hasher: inout Hasher) {
        fatalError(#function + " must be overridden")
    }
    public var description: String {
        fatalError(#function + " must be overridden")
    }
    public class Empty: SemanticContext {
        //
        /// The default _org.antlr.v4.runtime.atn.SemanticContext_, which is semantically equivalent to
        /// a predicate of the form `{true?}.
        ///
        public static let Instance: Empty = Empty()
        public override func hash(into hasher: inout Hasher) {
        }
        override
        public var description: String {
            return "{true}?"
        }
    }
    public class Predicate: SemanticContext {
        public let ruleIndex: Int
        public let predIndex: Int
        public let isCtxDependent: Bool
        // e.g., $i ref in pred
        override
        public init() {
            self.ruleIndex = -1
            self.predIndex = -1
            self.isCtxDependent = false
        }
        public init(_ ruleIndex: Int, _ predIndex: Int, _ isCtxDependent: Bool) {
            self.ruleIndex = ruleIndex
            self.predIndex = predIndex
            self.isCtxDependent = isCtxDependent
        }
        override
        public func eval<T>(_ parser: Recognizer<T>, _ parserCallStack: RuleContext) throws -> Bool {
            let localctx = isCtxDependent ? parserCallStack : nil
            return try parser.sempred(localctx, ruleIndex, predIndex)
        }
        public override func hash(into hasher: inout Hasher) {
            hasher.combine(ruleIndex)
            hasher.combine(predIndex)
            hasher.combine(isCtxDependent)
        }
        override
        public var description: String {
            return "{\(ruleIndex):\(predIndex)}?"
        }
    }
    public class PrecedencePredicate: SemanticContext {
        public let precedence: Int
        override
        init() {
            self.precedence = 0
        }
        public init(_ precedence: Int) {
            self.precedence = precedence
        }
        override
        public func eval<T>(_ parser: Recognizer<T>, _ parserCallStack: RuleContext) throws -> Bool {
            return parser.precpred(parserCallStack, precedence)
        }
        override
        public func evalPrecedence<T>(_ parser: Recognizer<T>, _ parserCallStack: RuleContext) throws -> SemanticContext? {
            if parser.precpred(parserCallStack, precedence) {
                return SemanticContext.Empty.Instance
            } else {
                return nil
            }
        }
        public override func hash(into hasher: inout Hasher) {
            hasher.combine(precedence)
        }
        override
        public var description: String {
            return "{" + String(precedence) + ">=prec}?"
        }
    }
    ///
    /// This is the base class for semantic context "operators", which operate on
    /// a collection of semantic context "operands".
    ///
    /// -  4.3
    ///
    public class Operator: SemanticContext {
        ///
        /// Gets the operands for the semantic context operator.
        ///
        /// - returns: a collection of _org.antlr.v4.runtime.atn.SemanticContext_ operands for the
        /// operator.
        ///
        /// -  4.3
        ///
        public func getOperands() -> Array<SemanticContext> {
            fatalError(#function + " must be overridden")
        }
    }
    ///
    /// A semantic context which is true whenever none of the contained contexts
    /// is false.
    ///
    public class AND: Operator {
        public let opnds: [SemanticContext]
        public init(_ a: SemanticContext, _ b: SemanticContext) {
            var operands = Set<SemanticContext>()
            if let aAnd = a as? AND {
                operands.formUnion(aAnd.opnds)
            } else {
                operands.insert(a)
            }
            if let bAnd = b as? AND {
                operands.formUnion(bAnd.opnds)
            } else {
                operands.insert(b)
            }
            let precedencePredicates = SemanticContext.filterPrecedencePredicates(&operands)
            if !precedencePredicates.isEmpty {
                // interested in the transition with the lowest precedence
                let reduced = precedencePredicates.sorted {
                    $0.precedence < $1.precedence
                }
                operands.insert(reduced[0])
            }
            opnds = Array(operands)
        }
        override
        public func getOperands() -> [SemanticContext] {
            return opnds
        }
        public override func hash(into hasher: inout Hasher) {
            hasher.combine(opnds)
        }
        ///
        ///
        ///
        ///
        /// The evaluation of predicates by this context is short-circuiting, but
        /// unordered.
        ///
        override
        public func eval<T>(_ parser: Recognizer<T>, _ parserCallStack: RuleContext) throws -> Bool {
            for opnd in opnds {
                if try !opnd.eval(parser, parserCallStack) {
                    return false
                }
            }
            return true
        }
        override
        public func evalPrecedence<T>(_ parser: Recognizer<T>, _ parserCallStack: RuleContext) throws -> SemanticContext? {
            var differs = false
            var operands = [SemanticContext]()
            for context in opnds {
                let evaluated = try context.evalPrecedence(parser, parserCallStack)
                //TODO differs |= (evaluated != context)
                //differs |= (evaluated != context);
                differs = differs || (evaluated != context)
                if evaluated == nil {
                    // The AND context is false if any element is false
                    return nil
                }
                else if evaluated != SemanticContext.Empty.Instance {
                    // Reduce the result by skipping true elements
                    operands.append(evaluated!)
                }
            }
            if !differs {
                return self
            }
            return operands.reduce(SemanticContext.Empty.Instance, SemanticContext.and)
        }
        override
        public var description: String {
            return opnds.map({ $0.description }).joined(separator: "&&")
        }
    }
    ///
    /// A semantic context which is true whenever at least one of the contained
    /// contexts is true.
    ///
    public class OR: Operator {
        public final var opnds: [SemanticContext]
        public init(_ a: SemanticContext, _ b: SemanticContext) {
            var operands: Set<SemanticContext> = Set<SemanticContext>()
            if let aOr = a as? OR {
                operands.formUnion(aOr.opnds)
            } else {
                operands.insert(a)
            }
            if let bOr = b as? OR {
                operands.formUnion(bOr.opnds)
            } else {
                operands.insert(b)
            }
            let precedencePredicates = SemanticContext.filterPrecedencePredicates(&operands)
            if !precedencePredicates.isEmpty {
                // interested in the transition with the highest precedence
                let reduced = precedencePredicates.sorted {
                    $0.precedence > $1.precedence
                }
                operands.insert(reduced[0])
            }
            self.opnds = Array(operands)
        }
        override
        public func getOperands() -> [SemanticContext] {
            return opnds
        }
        public override func hash(into hasher: inout Hasher) {
            hasher.combine(opnds)
        }
        ///
        ///
        ///
        ///
        /// The evaluation of predicates by this context is short-circuiting, but
        /// unordered.
        ///
        override
        public func eval<T>(_ parser: Recognizer<T>, _ parserCallStack: RuleContext) throws -> Bool {
            for opnd in opnds {
                if try opnd.eval(parser, parserCallStack) {
                    return true
                }
            }
            return false
        }
        override
        public func evalPrecedence<T>(_ parser: Recognizer<T>, _ parserCallStack: RuleContext) throws -> SemanticContext? {
            var differs = false
            var operands = [SemanticContext]()
            for context in opnds {
                let evaluated = try context.evalPrecedence(parser, parserCallStack)
                differs = differs || (evaluated != context)
                if evaluated == SemanticContext.Empty.Instance {
                    // The OR context is true if any element is true
                    return SemanticContext.Empty.Instance
                }
                else if let evaluated = evaluated {
                    // Reduce the result by skipping false elements
                    operands.append(evaluated)
                }
            }
            if !differs {
                return self
            }
            return operands.reduce(nil, SemanticContext.or)
        }
        override
        public var description: String {
            return opnds.map({ $0.description }).joined(separator: "||")
        }
    }
    public static func and(_ a: SemanticContext?, _ b: SemanticContext?) -> SemanticContext {
        if a == nil || a == SemanticContext.Empty.Instance {
            return b!
        }
        if b == nil || b == SemanticContext.Empty.Instance {
            return a!
        }
        let result: AND = AND(a!, b!)
        if result.opnds.count == 1 {
            return result.opnds[0]
        }
        return result
    }
    ///
    ///
    /// - seealso: org.antlr.v4.runtime.atn.ParserATNSimulator#getPredsForAmbigAlts
    ///
    public static func or(_ a: SemanticContext?, _ b: SemanticContext?) -> SemanticContext {
        if a == nil {
            return b!
        }
        if b == nil {
            return a!
        }
        if a == SemanticContext.Empty.Instance || b == SemanticContext.Empty.Instance {
            return SemanticContext.Empty.Instance
        }
        let result: OR = OR(a!, b!)
        if result.opnds.count == 1 {
            return result.opnds[0]
        }
        return result
    }
    private static func filterPrecedencePredicates(_ collection: inout Set<SemanticContext>) -> [PrecedencePredicate] {
        let result = collection.compactMap {
            $0 as? PrecedencePredicate
        }
        collection = Set<SemanticContext>(collection.filter {
            !($0 is PrecedencePredicate)
        })
        return result
    }
}
public func ==(lhs: SemanticContext, rhs: SemanticContext) -> Bool {
    if lhs === rhs {
        return true
    }
    if (lhs is SemanticContext.Predicate) && (rhs is SemanticContext.Predicate) {
        return (lhs as! SemanticContext.Predicate) == (rhs as! SemanticContext.Predicate)
    }
    if (lhs is SemanticContext.PrecedencePredicate) && (rhs is SemanticContext.PrecedencePredicate) {
        return (lhs as! SemanticContext.PrecedencePredicate) == (rhs as! SemanticContext.PrecedencePredicate)
    }
    if (lhs is SemanticContext.AND) && (rhs is SemanticContext.AND) {
        return (lhs as! SemanticContext.AND) == (rhs as! SemanticContext.AND)
    }
    if (lhs is SemanticContext.OR) && (rhs is SemanticContext.OR) {
        return (lhs as! SemanticContext.OR) == (rhs as! SemanticContext.OR)
    }
    return false
}
public func ==(lhs: SemanticContext.Predicate, rhs: SemanticContext.Predicate) -> Bool {
    if lhs === rhs {
        return true
    }
    return lhs.ruleIndex == rhs.ruleIndex &&
            lhs.predIndex == rhs.predIndex &&
            lhs.isCtxDependent == rhs.isCtxDependent
}
public func ==(lhs: SemanticContext.PrecedencePredicate, rhs: SemanticContext.PrecedencePredicate) -> Bool {
    if lhs === rhs {
        return true
    }
    return lhs.precedence == rhs.precedence
}
public func ==(lhs: SemanticContext.AND, rhs: SemanticContext.AND) -> Bool {
    if lhs === rhs {
        return true
    }
    return lhs.opnds == rhs.opnds
}
public func ==(lhs: SemanticContext.OR, rhs: SemanticContext.OR) -> Bool {
    if lhs === rhs {
        return true
    }
    return lhs.opnds == rhs.opnds
}


LookupATNConfig

///
///
//
//  LookupATNConfig.swift
//  objc2swiftwithswith
//
//  Created by janyou on 15/9/22.
//
import Foundation
public class LookupATNConfig: Hashable {
    public let config: ATNConfig
    public init(_ old: ATNConfig) {
        // dup
        config = old
    }
    public func hash(into hasher: inout Hasher) {
        hasher.combine(config.state.stateNumber)
        hasher.combine(config.alt)
        hasher.combine(config.semanticContext)
    }
}
public func ==(lhs: LookupATNConfig, rhs: LookupATNConfig) -> Bool {
    if lhs.config === rhs.config {
        return true
    }
    return lhs.config.state.stateNumber == rhs.config.state.stateNumber &&
            lhs.config.alt == rhs.config.alt &&
            lhs.config.semanticContext == rhs.config.semanticContext
}