Parser

///
///
///
///
import Foundation
///
/// This field maps from the serialized ATN string to the deserialized _org.antlr.v4.runtime.atn.ATN_ with
/// bypass alternatives.
///
/// - SeeAlso: `ATNDeserializationOptions.generateRuleBypassTransitions`
///
private var bypassAltsAtnCache : ATN? = nil
///
/// mutex for bypassAltsAtnCache updates
///
private let bypassAltsAtnCacheMutex = Mutex()
///
/// This is all the parsing support code essentially; most of it is error recovery stuff.
///
open class Parser: Recognizer<ParserATNSimulator> {
    public static let EOF = -1
    public static var ConsoleError = true
    public class TraceListener: ParseTreeListener {
        var host: Parser
        init(_ host: Parser) {
            self.host = host
        }
        public func enterEveryRule(_ ctx: ParserRuleContext) throws {
            let ruleName = host.getRuleNames()[ctx.getRuleIndex()]
            let lt1 = try host._input.LT(1)!.getText()!
            print("enter   \(ruleName), LT(1)=\(lt1)")
        }
        public func visitTerminal(_ node: TerminalNode) {
            print("consume \(String(describing: node.getSymbol())) rule \(host.getRuleNames()[host._ctx!.getRuleIndex()])")
        }
        public func visitErrorNode(_ node: ErrorNode) {
        }
        public func exitEveryRule(_ ctx: ParserRuleContext) throws {
            let ruleName = host.getRuleNames()[ctx.getRuleIndex()]
            let lt1 = try host._input.LT(1)!.getText()!
            print("exit    \(ruleName), LT(1)=\(lt1)")
        }
    }
    public class TrimToSizeListener: ParseTreeListener {
        public static let INSTANCE = TrimToSizeListener()
        public func enterEveryRule(_ ctx: ParserRuleContext) {
        }
        public func visitTerminal(_ node: TerminalNode) {
        }
        public func visitErrorNode(_ node: ErrorNode) {
        }
        public func exitEveryRule(_ ctx: ParserRuleContext) {
            // TODO: Print exit info.
        }
    }

    ///
    /// The error handling strategy for the parser. The default value is a new
    /// instance of _org.antlr.v4.runtime.DefaultErrorStrategy_.
    ///
    /// - SeeAlso: #getErrorHandler
    /// - SeeAlso: #setErrorHandler
    ///
    public var _errHandler: ANTLRErrorStrategy = DefaultErrorStrategy()
    ///
    /// The input stream.
    ///
    /// - SeeAlso: #getInputStream
    /// - SeeAlso: #setInputStream
    ///
    public var _input: TokenStream!
    internal var _precedenceStack: Stack<Int> = {
        var precedenceStack = Stack<Int>()
        precedenceStack.push(0)
        return precedenceStack
    }()
    ///
    /// The _org.antlr.v4.runtime.ParserRuleContext_ object for the currently executing rule.
    /// This is always non-null during the parsing process.
    ///
    public var _ctx: ParserRuleContext? = nil
    ///
    /// Specifies whether or not the parser should construct a parse tree during
    /// the parsing process. The default value is `true`.
    ///
    /// - SeeAlso: #getBuildParseTree
    /// - SeeAlso: #setBuildParseTree
    ///
    internal var _buildParseTrees: Bool = true
    ///
    /// When _#setTrace_`(true)` is called, a reference to the
    /// _org.antlr.v4.runtime.Parser.TraceListener_ is stored here so it can be easily removed in a
    /// later call to _#setTrace_`(false)`. The listener itself is
    /// implemented as a parser listener so this field is not directly used by
    /// other parser methods.
    ///
    private var _tracer: TraceListener?
    ///
    /// The list of _org.antlr.v4.runtime.tree.ParseTreeListener_ listeners registered to receive
    /// events during the parse.
    ///
    /// - SeeAlso: #addParseListener
    ///
    public var _parseListeners: Array<ParseTreeListener>?
    ///
    /// The number of syntax errors reported during parsing. This value is
    /// incremented each time _#notifyErrorListeners_ is called.
    ///
    internal var _syntaxErrors: Int = 0
    public init(_ input: TokenStream) throws {
        self._input = input
        super.init()
        try setInputStream(input)
    }
    /// reset the parser's state
    public func reset() throws {
        try getInputStream()?.seek(0)
        _errHandler.reset(self)
        _ctx = nil
        _syntaxErrors = 0
        setTrace(false)
        _precedenceStack.clear()
        _precedenceStack.push(0)
        //  getInterpreter();
        if let interpreter = _interp {
            interpreter.reset()
        }
    }
    ///
    /// Match current input symbol against `ttype`. If the symbol type
    /// matches, _org.antlr.v4.runtime.ANTLRErrorStrategy#reportMatch_ and _#consume_ are
    /// called to complete the match process.
    ///
    /// If the symbol type does not match,
    /// _org.antlr.v4.runtime.ANTLRErrorStrategy#recoverInline_ is called on the current error
    /// strategy to attempt recovery. If _#getBuildParseTree_ is
    /// `true` and the token index of the symbol returned by
    /// _org.antlr.v4.runtime.ANTLRErrorStrategy#recoverInline_ is -1, the symbol is added to
    /// the parse tree by calling _#createErrorNode(ParserRuleContext, Token)_ then
    /// _ParserRuleContext#addErrorNode(ErrorNode)_.
    ///
    /// - Parameter ttype: the token type to match
    /// - Throws: org.antlr.v4.runtime.RecognitionException if the current input symbol did not match
    /// `ttype` and the error strategy could not recover from the
    /// mismatched symbol
    /// - Returns: the matched symbol
    ///
    public func match(_ ttype: Int) throws -> Token {
        var t = try getCurrentToken()
        if t.getType() == ttype {
            _errHandler.reportMatch(self)
            try consume()
        } else {
            t = try _errHandler.recoverInline(self)
            if _buildParseTrees && t.getTokenIndex() == -1 {
                // we must have conjured up a new token during single token insertion
                // if it's not the current symbol
                _ctx!.addErrorNode(createErrorNode(parent: _ctx!, t: t))
            }
        }
        return t
    }
    ///
    /// Match current input symbol as a wildcard. If the symbol type matches
    /// (i.e. has a value greater than 0), _org.antlr.v4.runtime.ANTLRErrorStrategy#reportMatch_
    /// and _#consume_ are called to complete the match process.
    ///
    /// If the symbol type does not match,
    /// _org.antlr.v4.runtime.ANTLRErrorStrategy#recoverInline_ is called on the current error
    /// strategy to attempt recovery. If _#getBuildParseTree_ is
    /// `true` and the token index of the symbol returned by
    /// _org.antlr.v4.runtime.ANTLRErrorStrategy#recoverInline_ is -1, the symbol is added to
    /// the parse tree by calling _#createErrorNode(ParserRuleContext, Token)_ then
    /// _ParserRuleContext#addErrorNode(ErrorNode)_.
    ///
    /// - Throws: org.antlr.v4.runtime.RecognitionException if the current input symbol did not match
    /// a wildcard and the error strategy could not recover from the mismatched
    /// symbol
    /// - Returns: the matched symbol
    ///
    public func matchWildcard() throws -> Token {
        var t = try getCurrentToken()
        if t.getType() > 0 {
            _errHandler.reportMatch(self)
            try consume()
        } else {
            t = try _errHandler.recoverInline(self)
            if _buildParseTrees && t.getTokenIndex() == -1 {
                // we must have conjured up a new token during single token insertion
                // if it's not the current symbol
                _ctx!.addErrorNode(createErrorNode(parent: _ctx!, t: t))
            }
        }
        return t
    }
    ///
    /// Track the _org.antlr.v4.runtime.ParserRuleContext_ objects during the parse and hook
    /// them up using the _org.antlr.v4.runtime.ParserRuleContext#children_ list so that it
    /// forms a parse tree. The _org.antlr.v4.runtime.ParserRuleContext_ returned from the start
    /// rule represents the root of the parse tree.
    ///
    /// Note that if we are not building parse trees, rule contexts only point
    /// upwards. When a rule exits, it returns the context but that gets garbage
    /// collected if nobody holds a reference. It points upwards but nobody
    /// points at it.
    ///
    /// When we build parse trees, we are adding all of these contexts to
    /// _org.antlr.v4.runtime.ParserRuleContext#children_ list. Contexts are then not candidates
    /// for garbage collection.
    ///
    public func setBuildParseTree(_ buildParseTrees: Bool) {
        self._buildParseTrees = buildParseTrees
    }
    ///
    /// Gets whether or not a complete parse tree will be constructed while
    /// parsing. This property is `true` for a newly constructed parser.
    ///
    /// - Returns: `true` if a complete parse tree will be constructed while
    /// parsing, otherwise `false`
    ///
    public func getBuildParseTree() -> Bool {
        return _buildParseTrees
    }
    ///
    /// Trim the internal lists of the parse tree during parsing to conserve memory.
    /// This property is set to `false` by default for a newly constructed parser.
    ///
    /// - Parameter trimParseTrees: `true` to trim the capacity of the _org.antlr.v4.runtime.ParserRuleContext#children_
    /// list to its size after a rule is parsed.
    ///
    public func setTrimParseTree(_ trimParseTrees: Bool) {
        if trimParseTrees {
            if getTrimParseTree() {
                return
            }
            addParseListener(TrimToSizeListener.INSTANCE)
        } else {
            removeParseListener(TrimToSizeListener.INSTANCE)
        }
    }
    ///
    /// - Returns: `true` if the _org.antlr.v4.runtime.ParserRuleContext#children_ list is trimmed
    /// using the default _org.antlr.v4.runtime.Parser.TrimToSizeListener_ during the parse process.
    ///
    public func getTrimParseTree() -> Bool {
        return !getParseListeners().filter({ $0 === TrimToSizeListener.INSTANCE }).isEmpty
    }
    public func getParseListeners() -> [ParseTreeListener] {
        return _parseListeners ?? [ParseTreeListener]()
    }
    ///
    /// Registers `listener` to receive events during the parsing process.
    ///
    /// To support output-preserving grammar transformations (including but not
    /// limited to left-recursion removal, automated left-factoring, and
    /// optimized code generation), calls to listener methods during the parse
    /// may differ substantially from calls made by
    /// _org.antlr.v4.runtime.tree.ParseTreeWalker#DEFAULT_ used after the parse is complete. In
    /// particular, rule entry and exit events may occur in a different order
    /// during the parse than after the parser. In addition, calls to certain
    /// rule entry methods may be omitted.
    ///
    /// With the following specific exceptions, calls to listener events are
    /// __deterministic__, i.e. for identical input the calls to listener
    /// methods will be the same.
    ///
    /// * Alterations to the grammar used to generate code may change the
    /// behavior of the listener calls.
    /// * Alterations to the command line options passed to ANTLR 4 when
    /// generating the parser may change the behavior of the listener calls.
    /// * Changing the version of the ANTLR Tool used to generate the parser
    /// may change the behavior of the listener calls.
    ///
    /// - Parameter listener: the listener to add
    ///
    public func addParseListener(_ listener: ParseTreeListener) {
        if _parseListeners == nil {
            _parseListeners = [ParseTreeListener]()
        }
        _parseListeners!.append(listener)
    }
    ///
    /// Remove `listener` from the list of parse listeners.
    ///
    /// If `listener` is `null` or has not been added as a parse
    /// listener, this method does nothing.
    ///
    /// - SeeAlso: #addParseListener
    ///
    /// - Parameter listener: the listener to remove
    ///
    public func removeParseListener(_ listener: ParseTreeListener?) {
        if _parseListeners != nil {
            if !_parseListeners!.filter({ $0 === listener }).isEmpty {
                _parseListeners = _parseListeners!.filter({
                    $0 !== listener
                })
                if _parseListeners!.isEmpty {
                    _parseListeners = nil
                }
            }
        }
    }
    ///
    /// Remove all parse listeners.
    ///
    /// - SeeAlso: #addParseListener
    ///
    public func removeParseListeners() {
        _parseListeners = nil
    }
    ///
    /// Notify any parse listeners of an enter rule event.
    ///
    /// - SeeAlso: #addParseListener
    ///
    public func triggerEnterRuleEvent() throws {
        if let _parseListeners = _parseListeners, let _ctx = _ctx {
            for listener: ParseTreeListener in _parseListeners {
                try listener.enterEveryRule(_ctx)
                _ctx.enterRule(listener)
            }
        }
    }
    ///
    /// Notify any parse listeners of an exit rule event.
    ///
    /// - SeeAlso: #addParseListener
    ///
    public func triggerExitRuleEvent() throws {
        // reverse order walk of listeners
        if let _parseListeners = _parseListeners, let _ctx = _ctx {
            for listener in _parseListeners.reversed() {
                _ctx.exitRule(listener)
                try listener.exitEveryRule(_ctx)
            }
        }
    }
    ///
    /// Gets the number of syntax errors reported during parsing. This value is
    /// incremented each time _#notifyErrorListeners_ is called.
    ///
    /// - SeeAlso: #notifyErrorListeners
    ///
    public func getNumberOfSyntaxErrors() -> Int {
        return _syntaxErrors
    }
    override
    open func getTokenFactory() -> TokenFactory {
        return _input.getTokenSource().getTokenFactory()
    }
    /// Tell our token source and error strategy about a new way to create tokens.
    override
    open func setTokenFactory(_ factory: TokenFactory) {
        _input.getTokenSource().setTokenFactory(factory)
    }
    ///
    /// The ATN with bypass alternatives is expensive to create so we create it
    /// lazily.
    ///
    public func getATNWithBypassAlts() -> ATN {
        let serializedAtn = getSerializedATN()
        return bypassAltsAtnCacheMutex.synchronized {
            if let cachedResult = bypassAltsAtnCache {
                return cachedResult
            }
            var opts = ATNDeserializationOptions()
            opts.generateRuleBypassTransitions = true
            let result = try! ATNDeserializer(opts).deserialize(serializedAtn)
            bypassAltsAtnCache = result
            return bypassAltsAtnCache!
        }
    }
    ///
    /// The preferred method of getting a tree pattern. For example, here's a
    /// sample use:
    ///
    ///
    /// ParseTree t = parser.expr();
    /// ParseTreePattern p = parser.compileParseTreePattern("<ID>+0", MyParser.RULE_expr);
    /// ParseTreeMatch m = p.match(t);
    /// String id = m.get("ID");
    ///
    ///
    public func compileParseTreePattern(_ pattern: String, _ patternRuleIndex: Int) throws -> ParseTreePattern {
        if let tokenStream = getTokenStream() {
            let tokenSource = tokenStream.getTokenSource()
            if let lexer = tokenSource as? Lexer {
                return try compileParseTreePattern(pattern, patternRuleIndex, lexer)
            }
        }
        throw ANTLRError.unsupportedOperation(msg: "Parser can't discover a lexer to use")
    }
    ///
    /// The same as _#compileParseTreePattern(String, int)_ but specify a
    /// _org.antlr.v4.runtime.Lexer_ rather than trying to deduce it from this parser.
    ///
    public func compileParseTreePattern(_ pattern: String, _ patternRuleIndex: Int,
                                        _ lexer: Lexer) throws -> ParseTreePattern {
        let m = ParseTreePatternMatcher(lexer, self)
        return try m.compile(pattern, patternRuleIndex)
    }
    public func getErrorHandler() -> ANTLRErrorStrategy {
        return _errHandler
    }
    public func setErrorHandler(_ handler: ANTLRErrorStrategy) {
        self._errHandler = handler
    }
    override
    open func getInputStream() -> IntStream? {
        return getTokenStream()
    }
    override
    public final func setInputStream(_ input: IntStream) throws {
        try setTokenStream(input as! TokenStream)
    }
    public func getTokenStream() -> TokenStream? {
        return _input
    }
    /// Set the token stream and reset the parser.
    public func setTokenStream(_ input: TokenStream) throws {
        //TODO self._input = nil;
        self._input = nil;
        try reset()
        self._input = input
    }
    /// Match needs to return the current input symbol, which gets put
    /// into the label for the associated token ref; e.g., x=ID.
    ///
    public func getCurrentToken() throws -> Token {
        return try _input.LT(1)!
    }
    public final func notifyErrorListeners(_ msg: String) {
        let token = try? getCurrentToken()
        notifyErrorListeners(token, msg, nil)
    }
    public func notifyErrorListeners(_ offendingToken: Token?, _ msg: String, _ e: AnyObject?) {
        _syntaxErrors += 1
        var line = -1
        var charPositionInLine = -1
        if let offendingToken = offendingToken {
            line = offendingToken.getLine()
            charPositionInLine = offendingToken.getCharPositionInLine()
        }
        let listener = getErrorListenerDispatch()
        listener.syntaxError(self, offendingToken, line, charPositionInLine, msg, e)
    }
    ///
    /// Consume and return the |: #getCurrentToken current symbol:|.
    ///
    /// E.g., given the following input with `A` being the current
    /// lookahead symbol, this function moves the cursor to `B` and returns
    /// `A`.
    ///
    ///
    /// A B
    /// ^
    ///
    ///
    /// If the parser is not in error recovery mode, the consumed symbol is added
    /// to the parse tree using _ParserRuleContext#addChild(TerminalNode)_, and
    /// _org.antlr.v4.runtime.tree.ParseTreeListener#visitTerminal_ is called on any parse listeners.
    /// If the parser __is__ in error recovery mode, the consumed symbol is
    /// added to the parse tree using _#createErrorNode(ParserRuleContext, Token)_ then
    /// _ParserRuleContext#addErrorNode(ErrorNode)_ and
    /// _org.antlr.v4.runtime.tree.ParseTreeListener#visitErrorNode_ is called on any parse
    /// listeners.
    ///
    public func consume() throws -> Token {
        let o = try getCurrentToken()
        if o.getType() != Parser.EOF {
            try getInputStream()!.consume()
        }
        guard let _ctx = _ctx else {
            return o
        }
        let hasListener = _parseListeners != nil && !_parseListeners!.isEmpty
        if _buildParseTrees || hasListener {
            if _errHandler.inErrorRecoveryMode(self) {
                let node = createErrorNode(parent: _ctx, t: o)
                _ctx.addErrorNode(node)
                if let _parseListeners = _parseListeners {
                    for listener in _parseListeners {
                        listener.visitErrorNode(node)
                    }
                }
            } else {
                let node = createTerminalNode(parent: _ctx, t: o)
                _ctx.addChild(node)
                if let _parseListeners = _parseListeners {
                    for listener in _parseListeners {
                        listener.visitTerminal(node)
                    }
                }
            }
        }
        return o
    }
    /// How to create a token leaf node associated with a parent.
    /// Typically, the terminal node to create is not a function of the parent.
    ///
    /// - Since: 4.7
    ///
    public func createTerminalNode(parent: ParserRuleContext, t: Token) -> TerminalNode {
        return TerminalNodeImpl(t)
    }
    /// How to create an error node, given a token, associated with a parent.
    /// Typically, the error node to create is not a function of the parent.
    ///
    /// - Since: 4.7
    ///
    public func createErrorNode(parent: ParserRuleContext, t: Token) -> ErrorNode {
        return ErrorNode(t)
    }
    internal func addContextToParseTree() {
        // add current context to parent if we have a parent
        if let parent = _ctx?.parent as? ParserRuleContext {
            parent.addChild(_ctx!)
        }
    }
    ///
    /// Always called by generated parsers upon entry to a rule. Access field
    /// _#_ctx_ get the current context.
    ///
    public func enterRule(_ localctx: ParserRuleContext, _ state: Int, _ ruleIndex: Int) throws {
        setState(state)
        _ctx = localctx
        _ctx!.start = try _input.LT(1)
        if _buildParseTrees {
            addContextToParseTree()
        }
    }
    public func exitRule() throws {
        guard let ctx = _ctx else {
            return
        }
        ctx.stop = try _input.LT(-1)
        // trigger event on _ctx, before it reverts to parent
        if _parseListeners != nil {
            try triggerExitRuleEvent()
        }
        setState(ctx.invokingState)
        _ctx = ctx.parent as? ParserRuleContext
    }
    public func enterOuterAlt(_ localctx: ParserRuleContext, _ altNum: Int) throws {
        localctx.setAltNumber(altNum)
        // if we have new localctx, make sure we replace existing ctx
        // that is previous child of parse tree
        if _buildParseTrees && _ctx! !== localctx {
            if let parent = _ctx?.parent as? ParserRuleContext {
                parent.removeLastChild()
                parent.addChild(localctx)
            }
        }
        _ctx = localctx
        if _parseListeners != nil {
            try triggerEnterRuleEvent()
        }
    }
    ///
    /// Get the precedence level for the top-most precedence rule.
    ///
    /// - Returns: The precedence level for the top-most precedence rule, or -1 if
    /// the parser context is not nested within a precedence rule.
    ///
    public final func getPrecedence() -> Int {
        if _precedenceStack.isEmpty {
            return -1
        }
        return _precedenceStack.peek() ?? -1
    }
    ///
    /// Use
    /// _#enterRecursionRule(org.antlr.v4.runtime.ParserRuleContext, int, int, int)_ instead.
    ///
    ///
    ///
    public func enterRecursionRule(_ localctx: ParserRuleContext, _ ruleIndex: Int) throws {
        try enterRecursionRule(localctx, getATN().ruleToStartState[ruleIndex].stateNumber, ruleIndex, 0)
    }
    public func enterRecursionRule(_ localctx: ParserRuleContext, _ state: Int, _ ruleIndex: Int, _ precedence: Int) throws {
        setState(state)
        _precedenceStack.push(precedence)
        _ctx = localctx
        _ctx!.start = try _input.LT(1)
        if _parseListeners != nil {
            try triggerEnterRuleEvent() // simulates rule entry for left-recursive rules
        }
    }
    /// Like _#enterRule_ but for recursive rules.
    /// Make the current context the child of the incoming localctx.
    ///
    public func pushNewRecursionContext(_ localctx: ParserRuleContext, _ state: Int, _ ruleIndex: Int) throws {
        let previous = _ctx!
        previous.parent = localctx
        previous.invokingState = state
        previous.stop = try _input.LT(-1)
        _ctx = localctx
        _ctx!.start = previous.start
        if _buildParseTrees {
            _ctx!.addChild(previous)
        }
        if _parseListeners != nil {
            try triggerEnterRuleEvent() // simulates rule entry for left-recursive rules
        }
    }
    public func unrollRecursionContexts(_ _parentctx: ParserRuleContext?) throws {
        _precedenceStack.pop()
        _ctx!.stop = try _input.LT(-1)
        let retctx = _ctx! // save current ctx (return value)
        // unroll so _ctx is as it was before call to recursive method
        if _parseListeners != nil {
            while let ctxWrap = _ctx, ctxWrap !== _parentctx {
                try triggerExitRuleEvent()
                _ctx = ctxWrap.parent as? ParserRuleContext
            }
        } else {
            _ctx = _parentctx
        }
        // hook into tree
        retctx.parent = _parentctx
        if _buildParseTrees && _parentctx != nil {
            // add return ctx into invoking rule's tree
            _parentctx!.addChild(retctx)
        }
    }
    public func getInvokingContext(_ ruleIndex: Int) -> ParserRuleContext? {
        var p = _ctx
        while let pWrap = p {
            if pWrap.getRuleIndex() == ruleIndex {
                return pWrap
            }
            p = pWrap.parent as? ParserRuleContext
        }
        return nil
    }
    public func getContext() -> ParserRuleContext? {
        return _ctx
    }
    public func setContext(_ ctx: ParserRuleContext) {
        _ctx = ctx
    }
    override
    open func precpred(_ localctx: RuleContext?, _ precedence: Int) -> Bool {
        return precedence >= _precedenceStack.peek()!
    }
    public func inContext(_ context: String) -> Bool {
        // TODO: useful in parser?
        return false
    }
    /// Given an AmbiguityInfo object that contains information about an
    /// ambiguous decision event, return the list of ambiguous parse trees.
    /// An ambiguity occurs when a specific token sequence can be recognized
    /// in more than one way by the grammar. These ambiguities are detected only
    /// at decision points.
    ///
    /// The list of trees includes the actual interpretation (that for
    /// the minimum alternative number) and all ambiguous alternatives.
    /// The actual interpretation is always first.
    ///
    /// This method reuses the same physical input token stream used to
    /// detect the ambiguity by the original parser in the first place.
    /// This method resets/seeks within but does not alter originalParser.
    /// The input position is restored upon exit from this method.
    /// Parsers using a _org.antlr.v4.runtime.UnbufferedTokenStream_ may not be able to
    /// perform the necessary save index() / seek(saved_index) operation.
    ///
    /// The trees are rooted at the node whose start..stop token indices
    /// include the start and stop indices of this ambiguity event. That is,
    /// the trees returns will always include the complete ambiguous subphrase
    /// identified by the ambiguity event.
    ///
    /// Be aware that this method does NOT notify error or parse listeners as
    /// it would trigger duplicate or otherwise unwanted events.
    ///
    /// This uses a temporary ParserATNSimulator and a ParserInterpreter
    /// so we don't mess up any statistics, event lists, etc...
    /// The parse tree constructed while identifying/making ambiguityInfo is
    /// not affected by this method as it creates a new parser interp to
    /// get the ambiguous interpretations.
    ///
    /// Nodes in the returned ambig trees are independent of the original parse
    /// tree (constructed while identifying/creating ambiguityInfo).
    ///
    /// - Since: 4.5.1
    ///
    /// - Parameter originalParser: The parser used to create ambiguityInfo; it
    /// is not modified by this routine and can be either
    /// a generated or interpreted parser. It's token
    /// stream *is* reset/seek()'d.
    /// - Parameter ambiguityInfo:  The information about an ambiguous decision event
    /// for which you want ambiguous parse trees.
    /// - Parameter startRuleIndex: The start rule for the entire grammar, not
    /// the ambiguous decision. We re-parse the entire input
    /// and so we need the original start rule.
    ///
    /// - Throws: org.antlr.v4.runtime.RecognitionException Throws upon syntax error while matching
    /// ambig input.
    /// - Returns:               The list of all possible interpretations of
    /// the input for the decision in ambiguityInfo.
    /// The actual interpretation chosen by the parser
    /// is always given first because this method
    /// retests the input in alternative order and
    /// ANTLR always resolves ambiguities by choosing
    /// the first alternative that matches the input.
    ///
    ///
//	public class func getAmbiguousParseTrees(originalParser : Parser,
//																 _ ambiguityInfo : AmbiguityInfo,
//																 _ startRuleIndex : Int) throws -> Array<ParserRuleContext>  //; RecognitionException
//	{
//		var trees : Array<ParserRuleContext> = Array<ParserRuleContext>();
//		var saveTokenInputPosition : Int = originalParser.getTokenStream().index();
//		//try {
//			// Create a new parser interpreter to parse the ambiguous subphrase
//			var parser : ParserInterpreter;
//			if ( originalParser is ParserInterpreter ) {
//				parser = ParserInterpreter( originalParser as! ParserInterpreter);
//			}
//			else {
//				var serializedAtn : [Character] = ATNSerializer.getSerializedAsChars(originalParser.getATN());
//				var deserialized : ATN = ATNDeserializer().deserialize(serializedAtn);
//				parser = ParserInterpreter(originalParser.getGrammarFileName(),
//											   originalParser.getVocabulary(),
//											    originalParser.getRuleNames() ,
//											   deserialized,
//											   originalParser.getTokenStream());
//			}
//
//			// Make sure that we don't get any error messages from using this temporary parser
//			parser.removeErrorListeners();
//			parser.removeParseListeners();
//			parser.getInterpreter()!.setPredictionMode(PredictionMode.LL_EXACT_AMBIG_DETECTION);
//
//			// get ambig trees
//			var alt : Int = ambiguityInfo.ambigAlts.firstSetBit();
//			while  alt>=0  {
//				// re-parse entire input for all ambiguous alternatives
//				// (don't have to do first as it's been parsed, but do again for simplicity
//				//  using this temp parser.)
//				parser.reset();
//				parser.getTokenStream().seek(0); // rewind the input all the way for re-parsing
//				parser.overrideDecision = ambiguityInfo.decision;
//				parser.overrideDecisionInputIndex = ambiguityInfo.startIndex;
//				parser.overrideDecisionAlt = alt;
//				var t : ParserRuleContext = parser.parse(startRuleIndex);
//				var ambigSubTree : ParserRuleContext =
//					Trees.getRootOfSubtreeEnclosingRegion(t, ambiguityInfo.startIndex, ambiguityInfo.stopIndex)!;
//				trees.append(ambigSubTree);
//				alt = ambiguityInfo.ambigAlts.nextSetBit(alt+1);
//			}
//		//}
//		defer {
//			originalParser.getTokenStream().seek(saveTokenInputPosition);
//		}
//
//		return trees;
//	}
    ///
    /// Checks whether or not `symbol` can follow the current state in the
    /// ATN. The behavior of this method is equivalent to the following, but is
    /// implemented such that the complete context-sensitive follow set does not
    /// need to be explicitly constructed.
    ///
    ///
    /// return getExpectedTokens().contains(symbol);
    ///
    ///
    /// - Parameter symbol: the symbol type to check
    /// - Returns: `true` if `symbol` can follow the current state in
    /// the ATN, otherwise `false`.
    ///
    public func isExpectedToken(_ symbol: Int) -> Bool {
        let atn = getInterpreter().atn
        var ctx: ParserRuleContext? = _ctx
        let s = atn.states[getState()]!
        var following = atn.nextTokens(s)
        if following.contains(symbol) {
            return true
        }
//        System.out.println("following "+s+"="+following);
        if !following.contains(CommonToken.EPSILON) {
            return false
        }
        while let ctxWrap = ctx, ctxWrap.invokingState >= 0 && following.contains(CommonToken.EPSILON) {
            let invokingState = atn.states[ctxWrap.invokingState]!
            let rt = invokingState.transition(0) as! RuleTransition
            following = atn.nextTokens(rt.followState)
            if following.contains(symbol) {
                return true
            }
            ctx = ctxWrap.parent as? ParserRuleContext
        }
        if following.contains(CommonToken.EPSILON) && symbol == CommonToken.EOF {
            return true
        }
        return false
    }
    ///
    /// Computes the set of input symbols which could follow the current parser
    /// state and context, as given by _#getState_ and _#getContext_,
    /// respectively.
    ///
    /// - SeeAlso: org.antlr.v4.runtime.atn.ATN#getExpectedTokens(int, org.antlr.v4.runtime.RuleContext)
    ///
    public func getExpectedTokens() throws -> IntervalSet {
        return try getATN().getExpectedTokens(getState(), getContext()!)
    }
    public func getExpectedTokensWithinCurrentRule() -> IntervalSet {
        let atn = getInterpreter().atn
        let s = atn.states[getState()]!
        return atn.nextTokens(s)
    }
    /// Get a rule's index (i.e., `RULE_ruleName` field) or -1 if not found.
    public func getRuleIndex(_ ruleName: String) -> Int {
        return getRuleIndexMap()[ruleName] ?? -1
    }
    public func getRuleContext() -> ParserRuleContext? {
        return _ctx
    }
    /// Return List<String> of the rule names in your parser instance
    /// leading up to a call to the current rule.  You could override if
    /// you want more details such as the file/line info of where
    /// in the ATN a rule is invoked.
    ///
    /// This is very useful for error messages.
    ///
    public func getRuleInvocationStack() -> [String] {
        return getRuleInvocationStack(_ctx)
    }
    public func getRuleInvocationStack(_ p: RuleContext?) -> [String] {
        var p = p
        let ruleNames = getRuleNames()
        var stack = [String]()
        while let pWrap = p {
            // compute what follows who invoked us
            let ruleIndex = pWrap.getRuleIndex()
            if ruleIndex < 0 {
                stack.append("n/a")
            } else {
                stack.append(ruleNames[ruleIndex])
            }
            p = pWrap.parent
        }
        return stack
    }
    /// For debugging and other purposes.
    public func getDFAStrings() -> [String] {
        guard let _interp = _interp else {
            return []
        }
        let vocab = getVocabulary()
        return _interp.decisionToDFA.map {
            $0.toString(vocab)
        }
    }
    /// For debugging and other purposes.
    public func dumpDFA() {
        guard let _interp = _interp else {
            return
        }
        var seenOne = false
        let vocab = getVocabulary()
        for dfa in _interp.decisionToDFA {
            if !dfa.states.isEmpty {
                if seenOne {
                    print("")
                }
                print("Decision \(dfa.decision):")
                print(dfa.toString(vocab), terminator: "")
                seenOne = true
            }
        }
    }
    public func getSourceName() -> String {
        return _input.getSourceName()
    }
    override
    open func getParseInfo() -> ParseInfo? {
        let interp = getInterpreter()
        if let interp = interp as? ProfilingATNSimulator {
            return ParseInfo(interp)
        }
        return nil
    }
    ///
    /// - Since: 4.3
    ///
    public func setProfile(_ profile: Bool) {
        let interp = getInterpreter()
        let saveMode = interp.getPredictionMode()
        if profile {
            if !(interp is ProfilingATNSimulator) {
                setInterpreter(ProfilingATNSimulator(self))
            }
        }
        else if interp is ProfilingATNSimulator {
            let sim = ParserATNSimulator(self, getATN(), interp.decisionToDFA, interp.getSharedContextCache())
            setInterpreter(sim)
        }
        getInterpreter().setPredictionMode(saveMode)
    }
    /// During a parse is sometimes useful to listen in on the rule entry and exit
    /// events as well as token matches. This is for quick and dirty debugging.
    ///
    public func setTrace(_ trace: Bool) {
        if !trace {
            removeParseListener(_tracer)
            _tracer = nil
        } else {
            if let _tracer = _tracer {
                removeParseListener(_tracer)
            } else {
                _tracer = TraceListener(self)
            }
            addParseListener(_tracer!)
        }
    }
    ///
    /// Gets whether a _org.antlr.v4.runtime.Parser.TraceListener_ is registered as a parse listener
    /// for the parser.
    ///
    /// - SeeAlso: #setTrace(boolean)
    ///
    public func isTrace() -> Bool {
        return _tracer != nil
    }
}


VocabularySingle

 */
///
/// This class provides a default implementation of the _org.antlr.v4.runtime.Vocabulary_
/// interface.
///
/// - Author: Sam Harwell
///
public class Vocabulary: Hashable {
    private static let EMPTY_NAMES: [String?] = [String?](repeating: "", count: 1)
    ///
    /// Gets an empty _org.antlr.v4.runtime.Vocabulary_ instance.
    ///
    ///
    /// No literal or symbol names are assigned to token types, so
    /// _#getDisplayName(int)_ returns the numeric value for all tokens
    /// except _org.antlr.v4.runtime.Token#EOF_.
    ///
    public static let EMPTY_VOCABULARY: Vocabulary = Vocabulary(EMPTY_NAMES, EMPTY_NAMES, EMPTY_NAMES)
    private let literalNames: [String?]
    private let symbolicNames: [String?]
    private let displayNames: [String?]
    ///
    /// Constructs a new instance of _org.antlr.v4.runtime.Vocabulary_ from the specified
    /// literal and symbolic token names.
    ///
    /// - SeeAlso: #getLiteralName(int)
    /// - SeeAlso: #getSymbolicName(int)
    /// - Parameter literalNames: The literal names assigned to tokens, or `null`
    /// if no literal names are assigned.
    /// - Parameter symbolicNames: The symbolic names assigned to tokens, or
    /// `null` if no symbolic names are assigned.
    ///
    ///
    public convenience init(_ literalNames: [String?], _ symbolicNames: [String?]) {
        self.init(literalNames, symbolicNames, nil)
    }
    ///
    /// Constructs a new instance of _org.antlr.v4.runtime.Vocabulary_ from the specified
    /// literal, symbolic, and display token names.
    ///
    /// - SeeAlso: #getLiteralName(int)
    /// - SeeAlso: #getSymbolicName(int)
    /// - SeeAlso: #getDisplayName(int)
    /// - Parameter literalNames: The literal names assigned to tokens, or `null`
    /// if no literal names are assigned.
    /// - Parameter symbolicNames: The symbolic names assigned to tokens, or
    /// `null` if no symbolic names are assigned.
    /// - Parameter displayNames: The display names assigned to tokens, or `null`
    /// to use the values in `literalNames` and `symbolicNames` as
    /// the source of display names, as described in
    /// _#getDisplayName(int)_.
    ///
    ///
    public init(_ literalNames: [String?]?, _ symbolicNames: [String?]?, _ displayNames: [String?]?) {
        self.literalNames = literalNames ?? Vocabulary.EMPTY_NAMES
        self.symbolicNames = symbolicNames ?? Vocabulary.EMPTY_NAMES
        self.displayNames = displayNames ?? Vocabulary.EMPTY_NAMES
    }
    ///
    /// Returns a _org.antlr.v4.runtime.Vocabulary_ instance from the specified set of token
    /// names. This method acts as a compatibility layer for the single
    /// `tokenNames` array generated by previous releases of ANTLR.
    ///
    /// The resulting vocabulary instance returns `null` for
    /// _#getLiteralName(int)_ and _#getSymbolicName(int)_, and the
    /// value from `tokenNames` for the display names.
    ///
    /// - Parameter tokenNames: The token names, or `null` if no token names are
    /// available.
    /// - Returns: A _org.antlr.v4.runtime.Vocabulary_ instance which uses `tokenNames` for
    /// the display names of tokens.
    ///
    public static func fromTokenNames(_ tokenNames: [String?]?) -> Vocabulary {
        guard let tokenNames = tokenNames, tokenNames.count > 0 else {
            return EMPTY_VOCABULARY
        }
        var literalNames = tokenNames
        var symbolicNames = tokenNames
        let length = tokenNames.count
        for i in 0..<length {
            guard let tokenName = tokenNames[i] else {
                continue
            }
            if let firstChar = tokenName.first {
                if firstChar == "\'" {
                    symbolicNames[i] = nil
                    continue
                }
                else if String(firstChar).uppercased() != String(firstChar) {
                    literalNames[i] = nil
                    continue
                }
            }
            // wasn't a literal or symbolic name
            literalNames[i] = nil
            symbolicNames[i] = nil
        }
        return Vocabulary(literalNames, symbolicNames, tokenNames)
    }
    public func getLiteralName(_ tokenType: Int) -> String? {
        if tokenType >= 0 && tokenType < literalNames.count {
            return literalNames[tokenType]
        }
        return nil
    }
    public func getSymbolicName(_ tokenType: Int) -> String? {
        if tokenType >= 0 && tokenType < symbolicNames.count {
            return symbolicNames[tokenType]
        }
        if tokenType == CommonToken.EOF {
            return "EOF"
        }
        return nil
    }
    public func getDisplayName(_ tokenType: Int) -> String {
        if tokenType >= 0 && tokenType < displayNames.count {
            if let displayName = displayNames[tokenType] {
                return displayName
            }
        }
        if let literalName = getLiteralName(tokenType) {
            return literalName
        }
        if let symbolicName = getSymbolicName(tokenType) {
            return symbolicName
        }
        return String(tokenType)
    }
    public func hash(into hasher: inout Hasher) {
        hasher.combine(ObjectIdentifier(self))
    }
}
public func ==(lhs: Vocabulary, rhs: Vocabulary) -> Bool {
    return lhs === rhs
}


ParserRuleContext

 */
/// A rule invocation record for parsing.
///
/// Contains all of the information about the current rule not stored in the
/// RuleContext. It handles parse tree children list, Any ATN state
/// tracing, and the default values available for rule invocations:
/// start, stop, rule index, current alt number.
///
/// Subclasses made for each rule and grammar track the parameters,
/// return values, locals, and labels specific to that rule. These
/// are the objects that are returned from rules.
///
/// Note text is not an actual field of a rule return value; it is computed
/// from start and stop using the input stream's toString() method.  I
/// could add a ctor to this so that we can pass in and store the input
/// stream, but I'm not sure we want to do that.  It would seem to be undefined
/// to get the .text property anyway if the rule matches tokens from multiple
/// input streams.
///
/// I do not use getters for fields of objects that are used simply to
/// group values such as this aggregate.  The getters/setters are there to
/// satisfy the superclass interface.
///
open class ParserRuleContext: RuleContext {
    public static let EMPTY = ParserRuleContext()
    public var visited = false
    /// If we are debugging or building a parse tree for a visitor,
    /// we need to track all of the tokens and rule invocations associated
    /// with this rule's context. This is empty for parsing w/o tree constr.
    /// operation because we don't the need to track the details about
    /// how we parse this rule.
    ///
    public var children: [ParseTree]?
    /// For debugging/tracing purposes, we want to track all of the nodes in
    /// the ATN traversed by the parser for a particular rule.
    /// This list indicates the sequence of ATN nodes used to match
    /// the elements of the children list. This list does not include
    /// ATN nodes and other rules used to match rule invocations. It
    /// traces the rule invocation node itself but nothing inside that
    /// other rule's ATN submachine.
    ///
    /// There is NOT a one-to-one correspondence between the children and
    /// states list. There are typically many nodes in the ATN traversed
    /// for each element in the children list. For example, for a rule
    /// invocation there is the invoking state and the following state.
    ///
    /// The parser setState() method updates field s and adds it to this list
    /// if we are debugging/tracing.
    ///
    /// This does not trace states visited during prediction.
    ///
    public var start: Token?, stop: Token?
    ///
    /// The exception that forced this rule to return. If the rule successfully
    /// completed, this is `null`.
    ///
    public var exception: RecognitionException?
    public override init() {
        super.init()
    }
    public init(_ parent: ParserRuleContext?, _ invokingStateNumber: Int) {
        super.init(parent, invokingStateNumber)
    }
    /// COPY a ctx (I'm deliberately not using copy constructor) to avoid
    /// confusion with creating node with parent. Does not copy children.
    ///
    /// This is used in the generated parser code to flip a generic XContext
    /// node for rule X to a YContext for alt label Y. In that sense, it is
    /// not really a generic copy function.
    ///
    /// If we do an error sync() at start of a rule, we might add error nodes
    /// to the generic XContext so this function must copy those nodes to
    /// the YContext as well else they are lost!
    ///
    open func copyFrom(_ ctx: ParserRuleContext) {
        self.parent = ctx.parent
        self.invokingState = ctx.invokingState
        self.start = ctx.start
        self.stop = ctx.stop
        // copy any error nodes to alt label node
        if let ctxChildren = ctx.children {
            self.children = [ParseTree]()
            // reset parent pointer for any error nodes
            for child in ctxChildren {
                if let errNode = child as? ErrorNode {
                    addChild(errNode)
                }
            }
        }
    }
    // Double dispatch methods for listeners
    open func enterRule(_ listener: ParseTreeListener) {
    }
    open func exitRule(_ listener: ParseTreeListener) {
    }
    /// Add a parse tree node to this as a child.  Works for
    /// internal and leaf nodes. Does not set parent link;
    /// other add methods must do that. Other addChild methods
    /// call this.
    ///
    /// We cannot set the parent pointer of the incoming node
    /// because the existing interfaces do not have a setParent()
    /// method and I don't want to break backward compatibility for this.
    ///
    /// - Since: 4.7
    ///
    open func addAnyChild(_ t: ParseTree) {
        if children == nil {
            children = [ParseTree]()
        }
        children!.append(t)
    }
    open func addChild(_ ruleInvocation: RuleContext) {
        addAnyChild(ruleInvocation)
    }
    /// Add a token leaf node child and force its parent to be this node.
    open func addChild(_ t: TerminalNode) {
        t.setParent(self)
        addAnyChild(t)
    }
    /// Add an error node child and force its parent to be this node.
    open func addErrorNode(_ errorNode: ErrorNode) {
        errorNode.setParent(self)
        addAnyChild(errorNode)
    }
    /// Used by enterOuterAlt to toss out a RuleContext previously added as
    /// we entered a rule. If we have # label, we will need to remove
    /// generic ruleContext object.
    ///
    open func removeLastChild() {
        children?.removeLast()
    }
    override
    open func getChild(_ i: Int) -> Tree? {
        guard let children = children, i >= 0 && i < children.count else {
            return nil
        }
        return children[i]
    }
    open func getChild<T: ParseTree>(_ ctxType: T.Type, i: Int) -> T? {
        guard let children = children, i >= 0 && i < children.count else {
            return nil
        }
        var j = -1 // what element have we found with ctxType?
        for o in children {
            if let o = o as? T {
                j += 1
                if j == i {
                    return o
                }
            }
        }
        return nil
    }
    open func getToken(_ ttype: Int, _ i: Int) -> TerminalNode? {
        guard let children = children, i >= 0 && i < children.count else {
            return nil
        }
        var j = -1 // what token with ttype have we found?
        for o in children {
            if let tnode = o as? TerminalNode {
                let symbol = tnode.getSymbol()!
                if symbol.getType() == ttype {
                    j += 1
                    if j == i {
                        return tnode
                    }
                }
            }
        }
        return nil
    }
    open func getTokens(_ ttype: Int) -> [TerminalNode] {
        guard let children = children else {
            return [TerminalNode]()
        }
        return children.compactMap {
            if let tnode = $0 as? TerminalNode, let symbol = tnode.getSymbol(), symbol.getType() == ttype {
                return tnode
            }
            else {
                return nil
            }
        }
    }
    open func getRuleContext<T: ParserRuleContext>(_ ctxType: T.Type, _ i: Int) -> T? {
        return getChild(ctxType, i: i)
    }
    open func getRuleContexts<T: ParserRuleContext>(_ ctxType: T.Type) -> [T] {
        guard let children = children else {
            return [T]()
        }
        return children.compactMap { $0 as? T }
    }
    override
    open func getChildCount() -> Int {
        return children?.count ?? 0
    }
    override
    open subscript(index: Int) -> ParseTree {
        return children![index]
    }
    override
    open func getSourceInterval() -> Interval {
        guard let start = start, let stop = stop else {
             return Interval.INVALID
        }
        return Interval.of(start.getTokenIndex(), stop.getTokenIndex())
    }
    ///
    /// Get the initial token in this context.
    /// Note that the range from start to stop is inclusive, so for rules that do not consume anything
    /// (for example, zero length or error productions) this token may exceed stop.
    ///
    open func getStart() -> Token? {
        return start
    }
    ///
    /// Get the final token in this context.
    /// Note that the range from start to stop is inclusive, so for rules that do not consume anything
    /// (for example, zero length or error productions) this token may precede start.
    ///
    open func getStop() -> Token? {
        return stop
    }
    /// Used for rule context info debugging during parse-time, not so much for ATN debugging
    open func toInfoString(_ recognizer: Parser) -> String {
        let rules = Array(recognizer.getRuleInvocationStack(self).reversed())
        let startStr = start?.description ?? "<unknown>"
        let stopStr = stop?.description ?? "<unknown>"
        return "ParserRuleContext\(rules){start=\(startStr)), stop=\(stopStr)}"
    }
}


Token

 */
/// A token has properties: text, type, line, character position in the line
/// (so we can ignore tabs), token channel, index, and source from which
/// we obtained this token.
///
public protocol Token: AnyObject, CustomStringConvertible {
    //let INVALID_TYPE : Int = 0;
    /// During lookahead operations, this "token" signifies we hit rule end ATN state
    /// and did not follow it despite needing to.
    ///
    //let EPSILON : Int = -2;
    //let MIN_USER_TOKEN_TYPE : Int = 1;
    //let EOF : Int = IntStream.EOF;
    /// All tokens go to the parser (unless skip() is called in that rule)
    /// on a particular "channel".  The parser tunes to a particular channel
    /// so that whitespace etc... can go to the parser on a "hidden" channel.
    ///
    //let DEFAULT_CHANNEL : Int = 0;
    /// Anything on different channel than DEFAULT_CHANNEL is not parsed
    /// by parser.
    ///
    //let HIDDEN_CHANNEL : Int = 1;
    ///
    /// This is the minimum constant value which can be assigned to a
    /// user-defined token channel.
    ///
    ///
    /// The non-negative numbers less than _#MIN_USER_CHANNEL_VALUE_ are
    /// assigned to the predefined channels _#DEFAULT_CHANNEL_ and
    /// _#HIDDEN_CHANNEL_.
    ///
    /// - SeeAlso: org.antlr.v4.runtime.Token#getChannel()
    ///
    //let MIN_USER_CHANNEL_VALUE : Int = 2;
    ///
    /// Get the text of the token.
    ///
    func getText() -> String?
    /// Get the token type of the token
    func getType() -> Int
    /// The line number on which the 1st character of this token was matched,
    /// line=1..n
    ///
    func getLine() -> Int
    /// The index of the first character of this token relative to the
    /// beginning of the line at which it occurs, 0..n-1
    ///
    func getCharPositionInLine() -> Int
    /// Return the channel this token. Each token can arrive at the parser
    /// on a different channel, but the parser only "tunes" to a single channel.
    /// The parser ignores everything not on DEFAULT_CHANNEL.
    ///
    func getChannel() -> Int
    /// An index from 0..n-1 of the token object in the input stream.
    /// This must be valid in order to print token streams and
    /// use TokenRewriteStream.
    ///
    /// Return -1 to indicate that this token was conjured up since
    /// it doesn't have a valid index.
    ///
    func getTokenIndex() -> Int
    /// The starting character index of the token
    /// This method is optional; return -1 if not implemented.
    ///
    func getStartIndex() -> Int
    /// The last character index of the token.
    /// This method is optional; return -1 if not implemented.
    ///
    func getStopIndex() -> Int
    /// Gets the _org.antlr.v4.runtime.TokenSource_ which created this token.
    ///
    func getTokenSource() -> TokenSource?
    ///
    /// Gets the _org.antlr.v4.runtime.CharStream_ from which this token was derived.
    ///
    func getInputStream() -> CharStream?
    func getTokenSourceAndStream() -> TokenSourceAndStream
    var visited: Bool { get set }
}


IntStream

///
///
///
/// A simple stream of symbols whose values are represented as integers. This
/// interface provides __marked ranges__ with support for a minimum level
/// of buffering necessary to implement arbitrary lookahead during prediction.
/// For more information on marked ranges, see _#mark_.
///
/// __Initializing Methods:__ Some methods in this interface have
/// unspecified behavior if no call to an initializing method has occurred after
/// the stream was constructed. The following is a list of initializing methods:
///
/// * _#LA_
/// * _#consume_
/// * _#size_
///
public protocol IntStream: AnyObject {
    ///
    /// Consumes the current symbol in the stream. This method has the following
    /// effects:
    ///
    /// * __Forward movement:__ The value of _#index index()_
    /// before calling this method is less than the value of `index()`
    /// after calling this method.
    /// * __Ordered lookahead:__ The value of `LA(1)` before
    /// calling this method becomes the value of `LA(-1)` after calling
    /// this method.
    ///
    /// Note that calling this method does not guarantee that `index()` is
    /// incremented by exactly 1, as that would preclude the ability to implement
    /// filtering streams (e.g. _org.antlr.v4.runtime.CommonTokenStream_ which distinguishes
    /// between "on-channel" and "off-channel" tokens).
    ///
    /// - throws: _ANTLRError.illegalState_ if an attempt is made to consume the the
    /// end of the stream (i.e. if `LA(1)==`_#EOF EOF_ before calling
    /// `consume`).
    ///
    func consume() throws
    ///
    /// Gets the value of the symbol at offset `i` from the current
    /// position. When `i==1`, this method returns the value of the current
    /// symbol in the stream (which is the next symbol to be consumed). When
    /// `i==-1`, this method returns the value of the previously read
    /// symbol in the stream. It is not valid to call this method with
    /// `i==0`, but the specific behavior is unspecified because this
    /// method is frequently called from performance-critical code.
    ///
    /// This method is guaranteed to succeed if any of the following are true:
    ///
    /// * `i>0`
    /// * `i==-1` and _#index index()_ returns a value greater
    /// than the value of `index()` after the stream was constructed
    /// and `LA(1)` was called in that order. Specifying the current
    /// `index()` relative to the index after the stream was created
    /// allows for filtering implementations that do not return every symbol
    /// from the underlying source. Specifying the call to `LA(1)`
    /// allows for lazily initialized streams.
    /// * `LA(i)` refers to a symbol consumed within a marked region
    /// that has not yet been released.
    ///
    /// If `i` represents a position at or beyond the end of the stream,
    /// this method returns _#EOF_.
    ///
    /// The return value is unspecified if `i<0` and fewer than `-i`
    /// calls to _#consume consume()_ have occurred from the beginning of
    /// the stream before calling this method.
    ///
    /// - throws: _ANTLRError.unsupportedOperation_ if the stream does not support
    /// retrieving the value of the specified symbol
    ///
    func LA(_ i: Int) throws -> Int
    ///
    /// A mark provides a guarantee that _#seek seek()_ operations will be
    /// valid over a "marked range" extending from the index where `mark()`
    /// was called to the current _#index index()_. This allows the use of
    /// streaming input sources by specifying the minimum buffering requirements
    /// to support arbitrary lookahead during prediction.
    ///
    /// The returned mark is an opaque handle (type `int`) which is passed
    /// to _#release release()_ when the guarantees provided by the marked
    /// range are no longer necessary. When calls to
    /// `mark()`/`release()` are nested, the marks must be released
    /// in reverse order of which they were obtained. Since marked regions are
    /// used during performance-critical sections of prediction, the specific
    /// behavior of invalid usage is unspecified (i.e. a mark is not released, or
    /// a mark is released twice, or marks are not released in reverse order from
    /// which they were created).
    ///
    /// The behavior of this method is unspecified if no call to an
    /// _org.antlr.v4.runtime.IntStream initializing method_ has occurred after this stream was
    /// constructed.
    ///
    /// This method does not change the current position in the input stream.
    ///
    /// The following example shows the use of _#mark mark()_,
    /// _#release release(mark)_, _#index index()_, and
    /// _#seek seek(index)_ as part of an operation to safely work within a
    /// marked region, then restore the stream position to its original value and
    /// release the mark.
    ///
    /// IntStream stream = ...;
    /// int index = -1;
    /// int mark = stream.mark();
    /// try {
    /// index = stream.index();
    /// // perform work here...
    /// } finally {
    /// if (index != -1) {
    /// stream.seek(index);
    /// }
    /// stream.release(mark);
    /// }
    ///
    ///
    /// - returns: An opaque marker which should be passed to
    /// _#release release()_ when the marked range is no longer required.
    ///
    func mark() -> Int
    ///
    /// This method releases a marked range created by a call to
    /// _#mark mark()_. Calls to `release()` must appear in the
    /// reverse order of the corresponding calls to `mark()`. If a mark is
    /// released twice, or if marks are not released in reverse order of the
    /// corresponding calls to `mark()`, the behavior is unspecified.
    ///
    /// For more information and an example, see _#mark_.
    ///
    /// - parameter marker: A marker returned by a call to `mark()`.
    /// - seealso: #mark
    ///
    func release(_ marker: Int) throws
    ///
    /// Return the index into the stream of the input symbol referred to by
    /// `LA(1)`.
    ///
    /// The behavior of this method is unspecified if no call to an
    /// _org.antlr.v4.runtime.IntStream initializing method_ has occurred after this stream was
    /// constructed.
    ///
    func index() -> Int
    ///
    /// Set the input cursor to the position indicated by `index`. If the
    /// specified index lies past the end of the stream, the operation behaves as
    /// though `index` was the index of the EOF symbol. After this method
    /// returns without throwing an exception, then at least one of the following
    /// will be true.
    ///
    /// * _#index index()_ will return the index of the first symbol
    /// appearing at or after the specified `index`. Specifically,
    /// implementations which filter their sources should automatically
    /// adjust `index` forward the minimum amount required for the
    /// operation to target a non-ignored symbol.
    /// * `LA(1)` returns _#EOF_
    ///
    /// This operation is guaranteed to not throw an exception if `index`
    /// lies within a marked region. For more information on marked regions, see
    /// _#mark_. The behavior of this method is unspecified if no call to
    /// an _org.antlr.v4.runtime.IntStream initializing method_ has occurred after this stream
    /// was constructed.
    ///
    /// - parameter index: The absolute index to seek to.
    ///
    /// - throws: _ANTLRError.illegalArgument_ if `index` is less than 0
    /// - throws: _ANTLRError.unsupportedOperation_ if the stream does not support
    /// seeking to the specified index
    ///
    func seek(_ index: Int) throws
    ///
    /// Returns the total number of symbols in the stream, including a single EOF
    /// symbol.
    ///
    /// - throws: _ANTLRError.unsupportedOperation_ if the size of the stream is
    /// unknown.
    ///
    func size() -> Int
    ///
    /// Gets the name of the underlying symbol source. This method returns a
    /// non-null, non-empty string. If such a name is not known, this method
    /// returns _#UNKNOWN_SOURCE_NAME_.
    ///
    func getSourceName() -> String
}


DecisionInfo

///
///
///
/// This class contains profiling gathered for a particular decision.
///
///
/// Parsing performance in ANTLR 4 is heavily influenced by both static factors
/// (e.g. the form of the rules in the grammar) and dynamic factors (e.g. the
/// choice of input and the state of the DFA cache at the time profiling
/// operations are started). For best results, gather and use aggregate
/// statistics from a large sample of inputs representing the inputs expected in
/// production before using the results to make changes in the grammar.
///
/// -  4.3
///
public class DecisionInfo: CustomStringConvertible {
    ///
    /// The decision number, which is an index into _org.antlr.v4.runtime.atn.ATN#decisionToState_.
    ///
    public private(set) final var decision: Int
    ///
    /// The total number of times _org.antlr.v4.runtime.atn.ParserATNSimulator#adaptivePredict_ was
    /// invoked for this decision.
    ///
    public var invocations: Int64 = 0
    ///
    /// The total time spent in _org.antlr.v4.runtime.atn.ParserATNSimulator#adaptivePredict_ for
    /// this decision, in nanoseconds.
    ///
    ///
    /// The value of this field contains the sum of differential results obtained
    /// by _System#nanoTime()_, and is not adjusted to compensate for JIT
    /// and/or garbage collection overhead. For best accuracy, use a modern JVM
    /// implementation that provides precise results from
    /// _System#nanoTime()_, and perform profiling in a separate process
    /// which is warmed up by parsing the input prior to profiling. If desired,
    /// call _org.antlr.v4.runtime.atn.ATNSimulator#clearDFA_ to reset the DFA cache to its initial
    /// state before starting the profiling measurement pass.
    ///
    public var timeInPrediction: Int64 = 0
    ///
    /// The sum of the lookahead required for SLL prediction for this decision.
    /// Note that SLL prediction is used before LL prediction for performance
    /// reasons even when _org.antlr.v4.runtime.atn.PredictionMode#LL_ or
    /// _org.antlr.v4.runtime.atn.PredictionMode#LL_EXACT_AMBIG_DETECTION_ is used.
    ///
    public var SLL_TotalLook: Int64 = 0
    ///
    /// Gets the minimum lookahead required for any single SLL prediction to
    /// complete for this decision, by reaching a unique prediction, reaching an
    /// SLL conflict state, or encountering a syntax error.
    ///
    public var SLL_MinLook: Int64 = 0
    ///
    /// Gets the maximum lookahead required for any single SLL prediction to
    /// complete for this decision, by reaching a unique prediction, reaching an
    /// SLL conflict state, or encountering a syntax error.
    ///
    public var SLL_MaxLook: Int64 = 0
    ///
    /// Gets the _org.antlr.v4.runtime.atn.LookaheadEventInfo_ associated with the event where the
    /// _#SLL_MaxLook_ value was set.
    ///
    public var SLL_MaxLookEvent: LookaheadEventInfo!
    ///
    /// The sum of the lookahead required for LL prediction for this decision.
    /// Note that LL prediction is only used when SLL prediction reaches a
    /// conflict state.
    ///
    public var LL_TotalLook: Int64 = 0
    ///
    /// Gets the minimum lookahead required for any single LL prediction to
    /// complete for this decision. An LL prediction completes when the algorithm
    /// reaches a unique prediction, a conflict state (for
    /// _org.antlr.v4.runtime.atn.PredictionMode#LL_, an ambiguity state (for
    /// _org.antlr.v4.runtime.atn.PredictionMode#LL_EXACT_AMBIG_DETECTION_, or a syntax error.
    ///
    public var LL_MinLook: Int64 = 0
    ///
    /// Gets the maximum lookahead required for any single LL prediction to
    /// complete for this decision. An LL prediction completes when the algorithm
    /// reaches a unique prediction, a conflict state (for
    /// _org.antlr.v4.runtime.atn.PredictionMode#LL_, an ambiguity state (for
    /// _org.antlr.v4.runtime.atn.PredictionMode#LL_EXACT_AMBIG_DETECTION_, or a syntax error.
    ///
    public var LL_MaxLook: Int64 = 0
    ///
    /// Gets the _org.antlr.v4.runtime.atn.LookaheadEventInfo_ associated with the event where the
    /// _#LL_MaxLook_ value was set.
    ///
    public var LL_MaxLookEvent: LookaheadEventInfo!
    ///
    /// A collection of _org.antlr.v4.runtime.atn.ContextSensitivityInfo_ instances describing the
    /// context sensitivities encountered during LL prediction for this decision.
    ///
    /// - seealso: org.antlr.v4.runtime.atn.ContextSensitivityInfo
    ///
    public final var contextSensitivities: Array<ContextSensitivityInfo> = Array<ContextSensitivityInfo>()
    ///
    /// A collection of _org.antlr.v4.runtime.atn.ErrorInfo_ instances describing the parse errors
    /// identified during calls to _org.antlr.v4.runtime.atn.ParserATNSimulator#adaptivePredict_ for
    /// this decision.
    ///
    /// - seealso: org.antlr.v4.runtime.atn.ErrorInfo
    ///
    public final var errors: Array<ErrorInfo> = Array<ErrorInfo>()
    ///
    /// A collection of _org.antlr.v4.runtime.atn.AmbiguityInfo_ instances describing the
    /// ambiguities encountered during LL prediction for this decision.
    ///
    /// - seealso: org.antlr.v4.runtime.atn.AmbiguityInfo
    ///
    public final var ambiguities: Array<AmbiguityInfo> = Array<AmbiguityInfo>()
    ///
    /// A collection of _org.antlr.v4.runtime.atn.PredicateEvalInfo_ instances describing the
    /// results of evaluating individual predicates during prediction for this
    /// decision.
    ///
    /// - seealso: org.antlr.v4.runtime.atn.PredicateEvalInfo
    ///
    public final var predicateEvals: Array<PredicateEvalInfo> = Array<PredicateEvalInfo>()
    ///
    /// The total number of ATN transitions required during SLL prediction for
    /// this decision. An ATN transition is determined by the number of times the
    /// DFA does not contain an edge that is required for prediction, resulting
    /// in on-the-fly computation of that edge.
    ///
    ///
    /// If DFA caching of SLL transitions is employed by the implementation, ATN
    /// computation may cache the computed edge for efficient lookup during
    /// future parsing of this decision. Otherwise, the SLL parsing algorithm
    /// will use ATN transitions exclusively.
    ///
    /// - seealso: #SLL_ATNTransitions
    /// - seealso: org.antlr.v4.runtime.atn.ParserATNSimulator#computeTargetState
    /// - seealso: org.antlr.v4.runtime.atn.LexerATNSimulator#computeTargetState
    ///
    public var SLL_ATNTransitions: Int64 = 0
    ///
    /// The total number of DFA transitions required during SLL prediction for
    /// this decision.
    ///
    /// If the ATN simulator implementation does not use DFA caching for SLL
    /// transitions, this value will be 0.
    ///
    /// - seealso: org.antlr.v4.runtime.atn.ParserATNSimulator#getExistingTargetState
    /// - seealso: org.antlr.v4.runtime.atn.LexerATNSimulator#getExistingTargetState
    ///
    public var SLL_DFATransitions: Int64 = 0
    ///
    /// Gets the total number of times SLL prediction completed in a conflict
    /// state, resulting in fallback to LL prediction.
    ///
    /// Note that this value is not related to whether or not
    /// _org.antlr.v4.runtime.atn.PredictionMode#SLL_ may be used successfully with a particular
    /// grammar. If the ambiguity resolution algorithm applied to the SLL
    /// conflicts for this decision produce the same result as LL prediction for
    /// this decision, _org.antlr.v4.runtime.atn.PredictionMode#SLL_ would produce the same overall
    /// parsing result as _org.antlr.v4.runtime.atn.PredictionMode#LL_.
    ///
    public var LL_Fallback: Int64 = 0
    ///
    /// The total number of ATN transitions required during LL prediction for
    /// this decision. An ATN transition is determined by the number of times the
    /// DFA does not contain an edge that is required for prediction, resulting
    /// in on-the-fly computation of that edge.
    ///
    ///
    /// If DFA caching of LL transitions is employed by the implementation, ATN
    /// computation may cache the computed edge for efficient lookup during
    /// future parsing of this decision. Otherwise, the LL parsing algorithm will
    /// use ATN transitions exclusively.
    ///
    /// - seealso: #LL_DFATransitions
    /// - seealso: org.antlr.v4.runtime.atn.ParserATNSimulator#computeTargetState
    /// - seealso: org.antlr.v4.runtime.atn.LexerATNSimulator#computeTargetState
    ///
    public var LL_ATNTransitions: Int64 = 0
    ///
    /// The total number of DFA transitions required during LL prediction for
    /// this decision.
    ///
    /// If the ATN simulator implementation does not use DFA caching for LL
    /// transitions, this value will be 0.
    ///
    /// - seealso: org.antlr.v4.runtime.atn.ParserATNSimulator#getExistingTargetState
    /// - seealso: org.antlr.v4.runtime.atn.LexerATNSimulator#getExistingTargetState
    ///
    public var LL_DFATransitions: Int64 = 0
    ///
    /// Constructs a new instance of the _org.antlr.v4.runtime.atn.DecisionInfo_ class to contain
    /// statistics for a particular decision.
    ///
    /// - parameter decision: The decision number
    ///
    public init(_ decision: Int) {
        self.decision = decision
    }
    public var description: String {
        var desc = ""
        desc += "{"
        desc += "decision=\(decision)"
        desc += ", contextSensitivities=\(contextSensitivities.count)"
        desc += ", errors=\(errors.count)"
        desc += ", ambiguities=\(ambiguities.count)"
        desc += ", SLL_lookahead=\(SLL_TotalLook)"
        desc += ", SLL_ATNTransitions=\(SLL_ATNTransitions)"
        desc += ", SLL_DFATransitions=\(SLL_DFATransitions)"
        desc += ", LL_Fallback=\(LL_Fallback)"
        desc += ", LL_lookahead=\(LL_TotalLook)"
        desc += ", LL_ATNTransitions=\(LL_ATNTransitions)"
        desc += "}"
        return desc
    }
}


AbstractPredicateTransition

///
///
///
///
/// -  Sam Harwell
///
public class AbstractPredicateTransition: Transition {
    /*public  override init(_ target : ATNState) {
        super.init(target);
    }*/
}


PredictionContextCache

///
///
///
/// Used to cache _org.antlr.v4.runtime.atn.PredictionContext_ objects. Its used for the shared
/// context cash associated with contexts in DFA states. This cache
/// can be used for both lexers and parsers.
///
public final class PredictionContextCache {
    private var cache = [PredictionContext: PredictionContext]()
    public init() {
    }
    ///
    /// Add a context to the cache and return it. If the context already exists,
    /// return that one instead and do not add a new context to the cache.
    /// Protect shared cache from unsafe thread access.
    ///
    public func add(_ ctx: PredictionContext) -> PredictionContext {
        if ctx === EmptyPredictionContext.Instance {
            return EmptyPredictionContext.Instance
        }
        if let existing = cache[ctx] {
//			print(name+" reuses "+existing);
            return existing
        }
        cache[ctx] = ctx
        return ctx
    }
    public func get(_ ctx: PredictionContext) -> PredictionContext? {
        return cache[ctx]
    }
    public func size() -> Int {
        return cache.count
    }
}


Transition

///
///
///
/// An ATN transition between any two ATN states.  Subclasses define
/// atom, set, epsilon, action, predicate, rule transitions.
///
/// This is a one way link.  It emanates from a state (usually via a list of
/// transitions) and has a target state.
///
/// Since we never have to change the ATN transitions once we construct it,
/// we can fix these transitions as specific classes. The DFA transitions
/// on the other hand need to update the labels as it adds transitions to
/// the states. We'll use the term Edge for the DFA to distinguish them from
/// ATN transitions.
///
import Foundation
public class Transition {
    // constants for serialization
    public static let EPSILON: Int = 1
    public static let RANGE: Int = 2
    public static let RULE: Int = 3
    public static let PREDICATE: Int = 4
    // e.g., {isType(input.LT(1))}?
    public static let ATOM: Int = 5
    public static let ACTION: Int = 6
    public static let SET: Int = 7
    // ~(A|B) or ~atom, wildcard, which convert to next 2
    public static let NOT_SET: Int = 8
    public static let WILDCARD: Int = 9
    public static let PRECEDENCE: Int = 10
    public let serializationNames: Array<String> =
    ["INVALID",
     "EPSILON",
     "RANGE",
     "RULE",
     "PREDICATE",
     "ATOM",
     "ACTION",
     "SET",
     "NOT_SET",
     "WILDCARD",
     "PRECEDENCE"]
    public static let serializationTypes: Dictionary<String, Int> = [
            String(describing: EpsilonTransition.self): EPSILON,
            String(describing: RangeTransition.self): RANGE,
            String(describing: RuleTransition.self): RULE,
            String(describing: PredicateTransition.self): PREDICATE,
            String(describing: AtomTransition.self): ATOM,
            String(describing: ActionTransition.self): ACTION,
            String(describing: SetTransition.self): SET,
            String(describing: NotSetTransition.self): NOT_SET,
            String(describing: WildcardTransition.self): WILDCARD,
            String(describing: PrecedencePredicateTransition.self): PRECEDENCE,
    ]
    ///
    /// The target of this transition.
    ///
    public internal(set) final var target: ATNState
    init(_ target: ATNState) {
        self.target = target
    }
    public func getSerializationType() -> Int {
        fatalError(#function + " must be overridden")
    }
    ///
    /// Determines if the transition is an "epsilon" transition.
    ///
    /// The default implementation returns `false`.
    ///
    /// - returns: `true` if traversing this transition in the ATN does not
    /// consume an input symbol; otherwise, `false` if traversing this
    /// transition consumes (matches) an input symbol.
    ///
    public func isEpsilon() -> Bool {
        return false
    }
    public func labelIntervalSet() -> IntervalSet? {
        return nil
    }
    public func matches(_ symbol: Int, _ minVocabSymbol: Int, _ maxVocabSymbol: Int) -> Bool {
        fatalError(#function + " must be overridden")
    }
}


ATN

///
///
public class ATN {
    public static let INVALID_ALT_NUMBER = 0
    public private(set) final var states = [ATNState?]()
    ///
    /// Each subrule/rule is a decision point and we must track them so we
    /// can go back later and build DFA predictors for them.  This includes
    /// all the rules, subrules, optional blocks, ()+, ()* etc...
    ///
    public private(set) final var decisionToState = [DecisionState]()
    ///
    /// Maps from rule index to starting state number.
    ///
    public internal(set) final var ruleToStartState: [RuleStartState]!
    ///
    /// Maps from rule index to stop state number.
    ///
    public internal(set) final var ruleToStopState: [RuleStopState]!
    ///
    /// The type of the ATN.
    ///
    public let grammarType: ATNType
    ///
    /// The maximum value for any symbol recognized by a transition in the ATN.
    ///
    public let maxTokenType: Int
    ///
    /// For lexer ATNs, this maps the rule index to the resulting token type.
    /// For parser ATNs, this maps the rule index to the generated bypass token
    /// type if the `ATNDeserializationOptions.generateRuleBypassTransitions`
    /// deserialization option was specified; otherwise, this is `null`.
    ///
    public internal(set) final var ruleToTokenType: [Int]!
    ///
    /// For lexer ATNs, this is an array of _org.antlr.v4.runtime.atn.LexerAction_ objects which may
    /// be referenced by action transitions in the ATN.
    ///
    public internal(set) final var lexerActions: [LexerAction]!
    public internal(set) final var modeToStartState = [TokensStartState]()
    ///
    /// Used for runtime deserialization of ATNs from strings
    ///
    public init(_ grammarType: ATNType, _ maxTokenType: Int) {
        self.grammarType = grammarType
        self.maxTokenType = maxTokenType
    }
    ///
    /// Compute the set of valid tokens that can occur starting in state `s`.
    /// If `ctx` is null, the set of tokens will not include what can follow
    /// the rule surrounding `s`. In other words, the set will be
    /// restricted to tokens reachable staying within `s`'s rule.
    ///
    public func nextTokens(_ s: ATNState, _ ctx: RuleContext?) -> IntervalSet {
        let anal = LL1Analyzer(self)
        let next = anal.LOOK(s, ctx)
        return next
    }
    ///
    /// Compute the set of valid tokens that can occur starting in `s` and
    /// staying in same rule. _org.antlr.v4.runtime.Token#EPSILON_ is in set if we reach end of
    /// rule.
    ///
    public func nextTokens(_ s: ATNState) -> IntervalSet {
        if let nextTokenWithinRule = s.nextTokenWithinRule {
            return nextTokenWithinRule
        }
        let intervalSet = nextTokens(s, nil)
        s.nextTokenWithinRule = intervalSet
        intervalSet.makeReadonly()
        return intervalSet
    }
    public func addState(_ state: ATNState?) {
        if let state = state {
            state.atn = self
            state.stateNumber = states.count
        }
        states.append(state)
    }
    public func removeState(_ state: ATNState) {
        states[state.stateNumber] = nil
        //states.set(state.stateNumber, nil); // just free mem, don't shift states in list
    }
    public func defineDecisionState(_ s: DecisionState) -> Int {
        decisionToState.append(s)
        s.decision = decisionToState.count-1
        return s.decision
    }
    public func getDecisionState(_ decision: Int) -> DecisionState? {
        if  !decisionToState.isEmpty  {
            return decisionToState[decision]
        }
        return nil
    }
    public func getNumberOfDecisions() -> Int {
        return decisionToState.count
    }
    ///
    /// Computes the set of input symbols which could follow ATN state number
    /// `stateNumber` in the specified full `context`. This method
    /// considers the complete parser context, but does not evaluate semantic
    /// predicates (i.e. all predicates encountered during the calculation are
    /// assumed true). If a path in the ATN exists from the starting state to the
    /// _org.antlr.v4.runtime.atn.RuleStopState_ of the outermost context without matching any
    /// symbols, _org.antlr.v4.runtime.Token#EOF_ is added to the returned set.
    ///
    /// If `context` is `null`, it is treated as
    /// _org.antlr.v4.runtime.ParserRuleContext#EMPTY_.
    ///
    /// - parameter stateNumber: the ATN state number
    /// - parameter context: the full parse context
    /// - returns: The set of potentially valid input symbols which could follow the
    /// specified state in the specified context.
    /// - throws: _ANTLRError.illegalArgument_ if the ATN does not contain a state with
    /// number `stateNumber`
    ///
    public func getExpectedTokens(_ stateNumber: Int, _ context: RuleContext) throws -> IntervalSet {
        guard states.indices.contains(stateNumber) else {
            throw ANTLRError.illegalArgument(msg: "Invalid state number.")
        }
        var ctx: RuleContext? = context
        let s = states[stateNumber]!
        var following = nextTokens(s)
        if !following.contains(CommonToken.EPSILON) {
            return following
        }
        let expected = IntervalSet()
        try! expected.addAll(following)
        try! expected.remove(CommonToken.EPSILON)
        while let ctxWrap = ctx, ctxWrap.invokingState >= 0 && following.contains(CommonToken.EPSILON) {
            let invokingState = states[ctxWrap.invokingState]!
            let rt = invokingState.transition(0) as! RuleTransition
            following = nextTokens(rt.followState)
            try! expected.addAll(following)
            try! expected.remove(CommonToken.EPSILON)
            ctx = ctxWrap.parent
        }
        if following.contains(CommonToken.EPSILON) {
            try! expected.add(CommonToken.EOF)
        }
        return expected
    }
    public final func appendDecisionToState(_ state: DecisionState) {
        decisionToState.append(state)
    }
    public final func appendModeToStartState(_ state: TokensStartState) {
        modeToStartState.append(state)
    }
}


LexerTypeAction

///
///
///
/// Implements the `type` lexer action by calling _org.antlr.v4.runtime.Lexer#setType_
/// with the assigned type.
///
/// -  Sam Harwell
/// -  4.2
///
public class LexerTypeAction: LexerAction, CustomStringConvertible {
    fileprivate let type: Int
    ///
    /// Constructs a new `type` action with the specified token type value.
    /// - parameter type: The type to assign to the token using _org.antlr.v4.runtime.Lexer#setType_.
    ///
    public init(_ type: Int) {
        self.type = type
    }
    ///
    /// Gets the type to assign to a token created by the lexer.
    /// - returns: The type to assign to a token created by the lexer.
    ///
    public func getType() -> Int {
        return type
    }
    ///
    ///
    /// - returns: This method returns _org.antlr.v4.runtime.atn.LexerActionType#TYPE_.
    ///
    public override func getActionType() -> LexerActionType {
        return LexerActionType.type
    }
    ///
    ///
    /// - returns: This method returns `false`.
    ///
    override
    public func isPositionDependent() -> Bool {
        return false
    }
    ///
    ///
    ///
    /// This action is implemented by calling _org.antlr.v4.runtime.Lexer#setType_ with the
    /// value provided by _#getType_.
    ///
    public override func execute(_ lexer: Lexer) {
        lexer.setType(type)
    }
    public override func hash(into hasher: inout Hasher) {
        hasher.combine(type)
    }
    public var description: String {
        return "type(\(type))"
    }
}
public func ==(lhs: LexerTypeAction, rhs: LexerTypeAction) -> Bool {
    if lhs === rhs {
        return true
    }
    return lhs.type == rhs.type
}


PredicateEvalInfo

///
///
///
/// This class represents profiling event information for semantic predicate
/// evaluations which occur during prediction.
///
/// - seealso: org.antlr.v4.runtime.atn.ParserATNSimulator#evalSemanticContext
///
/// -  4.3
///
public class PredicateEvalInfo: DecisionEventInfo {
    ///
    /// The semantic context which was evaluated.
    ///
    public private(set) var semctx: SemanticContext
    ///
    /// The alternative number for the decision which is guarded by the semantic
    /// context _#semctx_. Note that other ATN
    /// configurations may predict the same alternative which are guarded by
    /// other semantic contexts and/or _org.antlr.v4.runtime.atn.SemanticContext#NONE_.
    ///
    public private(set) var predictedAlt: Int
    ///
    /// The result of evaluating the semantic context _#semctx_.
    ///
    public private(set) var evalResult: Bool
    ///
    /// Constructs a new instance of the _org.antlr.v4.runtime.atn.PredicateEvalInfo_ class with the
    /// specified detailed predicate evaluation information.
    ///
    /// - parameter decision: The decision number
    /// - parameter input: The input token stream
    /// - parameter startIndex: The start index for the current prediction
    /// - parameter stopIndex: The index at which the predicate evaluation was
    /// triggered. Note that the input stream may be reset to other positions for
    /// the actual evaluation of individual predicates.
    /// - parameter semctx: The semantic context which was evaluated
    /// - parameter evalResult: The results of evaluating the semantic context
    /// - parameter predictedAlt: The alternative number for the decision which is
    /// guarded by the semantic context `semctx`. See _#predictedAlt_
    /// for more information.
    /// - parameter fullCtx: `true` if the semantic context was
    /// evaluated during LL prediction; otherwise, `false` if the semantic
    /// context was evaluated during SLL prediction
    ///
    /// - seealso: org.antlr.v4.runtime.atn.ParserATNSimulator#evalSemanticContext(org.antlr.v4.runtime.atn.SemanticContext, org.antlr.v4.runtime.ParserRuleContext, int, boolean)
    /// - seealso: org.antlr.v4.runtime.atn.SemanticContext#eval(org.antlr.v4.runtime.Recognizer, org.antlr.v4.runtime.RuleContext)
    ///
    public init(_ decision: Int,
                _ input: TokenStream,
                _ startIndex: Int,
                _ stopIndex: Int,
                _ semctx: SemanticContext,
                _ evalResult: Bool,
                _ predictedAlt: Int,
                _ fullCtx: Bool) {
        self.semctx = semctx
        self.evalResult = evalResult
        self.predictedAlt = predictedAlt
        super.init(decision, ATNConfigSet(), input, startIndex, stopIndex, fullCtx)
    }
}


BlockStartState

///
///
///
/// The start of a regular `(...)` block.
///
public class BlockStartState: DecisionState {
    public var endState: BlockEndState?
}


LexerATNConfig

///
///
public class LexerATNConfig: ATNConfig {
    ///
    /// This is the backing field for _#getLexerActionExecutor_.
    ///
    private let lexerActionExecutor: LexerActionExecutor?
    fileprivate let passedThroughNonGreedyDecision: Bool
    public init(_ state: ATNState,
                _ alt: Int,
                _ context: PredictionContext) {
        self.passedThroughNonGreedyDecision = false
        self.lexerActionExecutor = nil
        super.init(state, alt, context, SemanticContext.Empty.Instance)
    }
    public init(_ state: ATNState,
                _ alt: Int,
                _ context: PredictionContext,
                _ lexerActionExecutor: LexerActionExecutor?) {
        self.lexerActionExecutor = lexerActionExecutor
        self.passedThroughNonGreedyDecision = false
        super.init(state, alt, context, SemanticContext.Empty.Instance)
    }
    public init(_ c: LexerATNConfig, _ state: ATNState) {
        self.lexerActionExecutor = c.lexerActionExecutor
        self.passedThroughNonGreedyDecision = LexerATNConfig.checkNonGreedyDecision(c, state)
        super.init(c, state, c.context, c.semanticContext)
    }
    public init(_ c: LexerATNConfig, _ state: ATNState,
                _ lexerActionExecutor: LexerActionExecutor?) {
        self.lexerActionExecutor = lexerActionExecutor
        self.passedThroughNonGreedyDecision = LexerATNConfig.checkNonGreedyDecision(c, state)
        super.init(c, state, c.context, c.semanticContext)
    }
    public init(_ c: LexerATNConfig, _ state: ATNState,
                _ context: PredictionContext) {
        self.lexerActionExecutor = c.lexerActionExecutor
        self.passedThroughNonGreedyDecision = LexerATNConfig.checkNonGreedyDecision(c, state)
        super.init(c, state, context, c.semanticContext)
    }
    private static func checkNonGreedyDecision(_ source: LexerATNConfig, _ target: ATNState) -> Bool {
        return source.passedThroughNonGreedyDecision
                || target is DecisionState && (target as! DecisionState).nonGreedy
    }
    ///
    /// Gets the _org.antlr.v4.runtime.atn.LexerActionExecutor_ capable of executing the embedded
    /// action(s) for the current configuration.
    ///
    public final func getLexerActionExecutor() -> LexerActionExecutor? {
        return lexerActionExecutor
    }
    public final func hasPassedThroughNonGreedyDecision() -> Bool {
        return passedThroughNonGreedyDecision
    }
    public override func hash(into hasher: inout Hasher) {
        hasher.combine(state.stateNumber)
        hasher.combine(alt)
        hasher.combine(context)
        hasher.combine(semanticContext)
        hasher.combine(passedThroughNonGreedyDecision)
        hasher.combine(lexerActionExecutor)
    }
}
//useless
public func ==(lhs: LexerATNConfig, rhs: LexerATNConfig) -> Bool {
    if lhs === rhs {
        return true
    }
    //let lexerOther : LexerATNConfig = rhs  // as! LexerATNConfig;
    if lhs.passedThroughNonGreedyDecision != rhs.passedThroughNonGreedyDecision {
        return false
    }
    if lhs.state.stateNumber != rhs.state.stateNumber {
        return false
    }
    if lhs.alt != rhs.alt {
        return false
    }
    if lhs.isPrecedenceFilterSuppressed() != rhs.isPrecedenceFilterSuppressed() {
        return false
    }
    if lhs.getLexerActionExecutor() != rhs.getLexerActionExecutor() {
        return false
    }
    if lhs.context != rhs.context {
        return false
    }
    return  lhs.semanticContext == rhs.semanticContext
}


LexerPushModeAction

///
///
///
/// Implements the `pushMode` lexer action by calling
/// _org.antlr.v4.runtime.Lexer#pushMode_ with the assigned mode.
///
/// -  Sam Harwell
/// -  4.2
///
public final class LexerPushModeAction: LexerAction, CustomStringConvertible {
    fileprivate let mode: Int
    ///
    /// Constructs a new `pushMode` action with the specified mode value.
    /// - parameter mode: The mode value to pass to _org.antlr.v4.runtime.Lexer#pushMode_.
    ///
    public init(_ mode: Int) {
        self.mode = mode
    }
    ///
    /// Get the lexer mode this action should transition the lexer to.
    ///
    /// - returns: The lexer mode for this `pushMode` command.
    ///
    public func getMode() -> Int {
        return mode
    }
    ///
    ///
    /// - returns: This method returns _org.antlr.v4.runtime.atn.LexerActionType#pushMode_.
    ///
    public override func getActionType() -> LexerActionType {
        return LexerActionType.pushMode
    }
    ///
    ///
    /// - returns: This method returns `false`.
    ///
    public override func isPositionDependent() -> Bool {
        return false
    }
    ///
    ///
    ///
    /// This action is implemented by calling _org.antlr.v4.runtime.Lexer#pushMode_ with the
    /// value provided by _#getMode_.
    ///
    override
    public func execute(_ lexer: Lexer) {
        lexer.pushMode(mode)
    }
    public override func hash(into hasher: inout Hasher) {
        hasher.combine(mode)
    }
    public var description: String {
        return "pushMode(\(mode))"
    }
}
public func ==(lhs: LexerPushModeAction, rhs: LexerPushModeAction) -> Bool {
    if lhs === rhs {
        return true
    }
    return lhs.mode == rhs.mode
}


DecisionEventInfo

///
///
///
/// This is the base class for gathering detailed information about prediction
/// events which occur during parsing.
///
/// Note that we could record the parser call stack at the time this event
/// occurred but in the presence of left recursive rules, the stack is kind of
/// meaningless. It's better to look at the individual configurations for their
/// individual stacks. Of course that is a _org.antlr.v4.runtime.atn.PredictionContext_ object
/// not a parse tree node and so it does not have information about the extent
/// (start...stop) of the various subtrees. Examining the stack tops of all
/// configurations provide the return states for the rule invocations.
/// From there you can get the enclosing rule.
///
/// -  4.3
///
public class DecisionEventInfo {
    ///
    /// The invoked decision number which this event is related to.
    ///
    /// - seealso: org.antlr.v4.runtime.atn.ATN#decisionToState
    ///
    public let decision: Int
    ///
    /// The configuration set containing additional information relevant to the
    /// prediction state when the current event occurred, or `null` if no
    /// additional information is relevant or available.
    ///
    public let configs: ATNConfigSet?
    ///
    /// The input token stream which is being parsed.
    ///
    public let input: TokenStream
    ///
    /// The token index in the input stream at which the current prediction was
    /// originally invoked.
    ///
    public let startIndex: Int
    ///
    /// The token index in the input stream at which the current event occurred.
    ///
    public let stopIndex: Int
    ///
    /// `true` if the current event occurred during LL prediction;
    /// otherwise, `false` if the input occurred during SLL prediction.
    ///
    public let fullCtx: Bool
    public init(_ decision: Int,
                _ configs: ATNConfigSet?,
                _ input: TokenStream,
                _ startIndex: Int,
                _ stopIndex: Int,
                _ fullCtx: Bool) {
        self.decision = decision
        self.fullCtx = fullCtx
        self.stopIndex = stopIndex
        self.input = input
        self.startIndex = startIndex
        self.configs = configs
    }
}


LexerModeAction

///
///
///
/// Implements the `mode` lexer action by calling _org.antlr.v4.runtime.Lexer#mode_ with
/// the assigned mode.
///
/// -  Sam Harwell
/// -  4.2
///
public final class LexerModeAction: LexerAction, CustomStringConvertible {
    fileprivate let mode: Int
    ///
    /// Constructs a new `mode` action with the specified mode value.
    /// - parameter mode: The mode value to pass to _org.antlr.v4.runtime.Lexer#mode_.
    ///
    public init(_ mode: Int) {
        self.mode = mode
    }
    ///
    /// Get the lexer mode this action should transition the lexer to.
    ///
    /// - returns: The lexer mode for this `mode` command.
    ///
    public func getMode() -> Int {
        return mode
    }
    ///
    ///
    /// - returns: This method returns _org.antlr.v4.runtime.atn.LexerActionType#MODE_.
    ///
    public override func getActionType() -> LexerActionType {
        return LexerActionType.mode
    }
    ///
    ///
    /// - returns: This method returns `false`.
    ///
    public override func isPositionDependent() -> Bool {
        return false
    }
    ///
    ///
    ///
    /// This action is implemented by calling _org.antlr.v4.runtime.Lexer#mode_ with the
    /// value provided by _#getMode_.
    ///
    override
    public func execute(_ lexer: Lexer) {
        lexer.mode(mode)
    }
    public override func hash(into hasher: inout Hasher) {
        hasher.combine(mode)
    }
    public var description: String {
        return "mode(\(mode))"
    }
}
public func ==(lhs: LexerModeAction, rhs: LexerModeAction) -> Bool {
    if lhs === rhs {
        return true
    }
    return lhs.mode == rhs.mode
}


PredicateTransition

///
///
///
/// TODO: this is old comment:
/// A tree of semantic predicates from the grammar AST if label==SEMPRED.
/// In the ATN, labels will always be exactly one predicate, but the DFA
/// may have to combine a bunch of them as it collects predicates from
/// multiple ATN configurations into a single DFA state.
///
public final class PredicateTransition: AbstractPredicateTransition, CustomStringConvertible {
    public let ruleIndex: Int
    public let predIndex: Int
    public let isCtxDependent: Bool
    // e.g., $i ref in pred
    public init(_ target: ATNState, _ ruleIndex: Int, _ predIndex: Int, _ isCtxDependent: Bool) {
        self.ruleIndex = ruleIndex
        self.predIndex = predIndex
        self.isCtxDependent = isCtxDependent
        super.init(target)
    }
    override
    public func getSerializationType() -> Int {
        return PredicateTransition.PREDICATE
    }
    override
    public func isEpsilon() -> Bool {
        return true
    }
    override
    public func matches(_ symbol: Int, _ minVocabSymbol: Int, _ maxVocabSymbol: Int) -> Bool {
        return false
    }
    public func getPredicate() -> SemanticContext.Predicate {
        return SemanticContext.Predicate(ruleIndex, predIndex, isCtxDependent)
    }
    public var description: String {
        return "pred_\(ruleIndex):\(predIndex)"
    }
}