DefaultErrorStrategy

///
///
///
/// This is the default implementation of _org.antlr.v4.runtime.ANTLRErrorStrategy_ used for
/// error reporting and recovery in ANTLR parsers.
///
import Foundation
open class DefaultErrorStrategy: ANTLRErrorStrategy {
    ///
    /// Indicates whether the error strategy is currently "recovering from an
    /// error". This is used to suppress reporting multiple error messages while
    /// attempting to recover from a detected syntax error.
    ///
    /// - seealso: #inErrorRecoveryMode
    ///
    open var errorRecoveryMode = false
    ///
    /// The index into the input stream where the last error occurred.
    /// This is used to prevent infinite loops where an error is found
    /// but no token is consumed during recovery...another error is found,
    /// ad nauseum.  This is a failsafe mechanism to guarantee that at least
    /// one token/tree node is consumed for two errors.
    ///
    open var lastErrorIndex = -1
    open var lastErrorStates: IntervalSet?
    /**
     * This field is used to propagate information about the lookahead following
     * the previous match. Since prediction prefers completing the current rule
     * to error recovery efforts, error reporting may occur later than the
     * original point where it was discoverable. The original context is used to
     * compute the true expected sets as though the reporting occurred as early
     * as possible.
     */
    open var nextTokensContext: ParserRuleContext?
    /**
     */
    open var nextTokensState = ATNState.INVALID_STATE_NUMBER
    public init() {
    }
    ///
    /// The default implementation simply calls _#endErrorCondition_ to
    /// ensure that the handler is not in error recovery mode.
    ///
    open func reset(_ recognizer: Parser) {
        endErrorCondition(recognizer)
    }
    ///
    /// This method is called to enter error recovery mode when a recognition
    /// exception is reported.
    ///
    /// - parameter recognizer: the parser instance
    ///
    open func beginErrorCondition(_ recognizer: Parser) {
        errorRecoveryMode = true
    }
    open func inErrorRecoveryMode(_ recognizer: Parser) -> Bool {
        return errorRecoveryMode
    }
    ///
    /// This method is called to leave error recovery mode after recovering from
    /// a recognition exception.
    ///
    /// - parameter recognizer:
    ///
    open func endErrorCondition(_ recognizer: Parser) {
        errorRecoveryMode = false
        lastErrorStates = nil
        lastErrorIndex = -1
    }
    ///
    /// The default implementation simply calls _#endErrorCondition_.
    ///
    open func reportMatch(_ recognizer: Parser) {
        endErrorCondition(recognizer)
    }
    ///
    ///
    /// The default implementation returns immediately if the handler is already
    /// in error recovery mode. Otherwise, it calls _#beginErrorCondition_
    /// and dispatches the reporting task based on the runtime type of `e`
    /// according to the following table.
    ///
    /// * _org.antlr.v4.runtime.NoViableAltException_: Dispatches the call to
    /// _#reportNoViableAlternative_
    /// * _org.antlr.v4.runtime.InputMismatchException_: Dispatches the call to
    /// _#reportInputMismatch_
    /// * _org.antlr.v4.runtime.FailedPredicateException_: Dispatches the call to
    /// _#reportFailedPredicate_
    /// * All other types: calls _org.antlr.v4.runtime.Parser#notifyErrorListeners_ to report
    /// the exception
    ///
    open func reportError(_ recognizer: Parser, _ e: RecognitionException) {
        // if we've already reported an error and have not matched a token
        // yet successfully, don't report any errors.
        if inErrorRecoveryMode(recognizer) {
            return // don't report spurious errors
        }
        beginErrorCondition(recognizer)
        if let nvae = e as? NoViableAltException {
            reportNoViableAlternative(recognizer, nvae)
        }
        else if let ime = e as? InputMismatchException {
            reportInputMismatch(recognizer, ime)
        }
        else if let fpe = e as? FailedPredicateException {
            reportFailedPredicate(recognizer, fpe)
        }
        else {
            errPrint("unknown recognition error type: " + String(describing: type(of: e)))
            recognizer.notifyErrorListeners(e.getOffendingToken(), e.message ?? "", e)
        }
    }
    ///
    /// The default implementation resynchronizes the parser by consuming tokens
    /// until we find one in the resynchronization set--loosely the set of tokens
    /// that can follow the current rule.
    ///
    open func recover(_ recognizer: Parser, _ e: RecognitionException) throws {
//		print("recover in "+recognizer.getRuleInvocationStack()+
//						   " index="+getTokenStream(recognizer).index()+
//						   ", lastErrorIndex="+
//						   lastErrorIndex+
//						   ", states="+lastErrorStates);
        if let lastErrorStates = lastErrorStates ,
          lastErrorIndex == getTokenStream(recognizer).index() &&
          lastErrorStates.contains(recognizer.getState()) {
            // uh oh, another error at same token index and previously-visited
            // state in ATN; must be a case where LT(1) is in the recovery
            // token set so nothing got consumed. Consume a single token
            // at least to prevent an infinite loop; this is a failsafe.
//			errPrint("seen error condition before index="+
//							   lastErrorIndex+", states="+lastErrorStates);
//			errPrint("FAILSAFE consumes "+recognizer.getTokenNames()[getTokenStream(recognizer).LA(1)]);
            try recognizer.consume()
        }
        lastErrorIndex = getTokenStream(recognizer).index()
        if lastErrorStates == nil {
            lastErrorStates = IntervalSet()
        }
        try lastErrorStates!.add(recognizer.getState())
        let followSet = getErrorRecoverySet(recognizer)
        try consumeUntil(recognizer, followSet)
    }
    ///
    /// The default implementation of _org.antlr.v4.runtime.ANTLRErrorStrategy#sync_ makes sure
    /// that the current lookahead symbol is consistent with what were expecting
    /// at this point in the ATN. You can call this anytime but ANTLR only
    /// generates code to check before subrules/loops and each iteration.
    ///
    /// Implements Jim Idle's magic sync mechanism in closures and optional
    /// subrules. E.g.,
    ///
    ///
    /// a : sync ( stuff sync )* ;
    /// sync : {consume to what can follow sync} ;
    ///
    ///
    /// At the start of a sub rule upon error, _#sync_ performs single
    /// token deletion, if possible. If it can't do that, it bails on the current
    /// rule and uses the default error recovery, which consumes until the
    /// resynchronization set of the current rule.
    ///
    /// If the sub rule is optional (`(...)?`, `(...)*`, or block
    /// with an empty alternative), then the expected set includes what follows
    /// the subrule.
    ///
    /// During loop iteration, it consumes until it sees a token that can start a
    /// sub rule or what follows loop. Yes, that is pretty aggressive. We opt to
    /// stay in the loop as long as possible.
    ///
    /// __ORIGINS__
    ///
    /// Previous versions of ANTLR did a poor job of their recovery within loops.
    /// A single mismatch token or missing token would force the parser to bail
    /// out of the entire rules surrounding the loop. So, for rule
    ///
    ///
    /// classDef : 'class' ID '{' member* '}'
    ///
    ///
    /// input with an extra token between members would force the parser to
    /// consume until it found the next class definition rather than the next
    /// member definition of the current class.
    ///
    /// This functionality cost a little bit of effort because the parser has to
    /// compare token set at the start of the loop and at each iteration. If for
    /// some reason speed is suffering for you, you can turn off this
    /// functionality by simply overriding this method as a blank { }.
    ///
    open func sync(_ recognizer: Parser) throws {
        let s = recognizer.getInterpreter().atn.states[recognizer.getState()]!
        // If already recovering, don't try to sync
        if inErrorRecoveryMode(recognizer) {
            return
        }
        let tokens = getTokenStream(recognizer)
        let la = try tokens.LA(1)
        // try cheaper subset first; might get lucky. seems to shave a wee bit off
        let nextToks = recognizer.getATN().nextTokens(s)
        if nextToks.contains(la) {
            // We are sure the token matches
            nextTokensContext = nil
            nextTokensState = ATNState.INVALID_STATE_NUMBER
            return
        }
        if nextToks.contains(CommonToken.EPSILON) {
            if nextTokensContext == nil {
                    // It's possible the next token won't match; information tracked
                    // by sync is restricted for performance.
                    nextTokensContext = recognizer.getContext()
                    nextTokensState = recognizer.getState()
            }
            return
        }
        switch s.getStateType() {
        case ATNState.BLOCK_START: fallthrough
        case ATNState.STAR_BLOCK_START: fallthrough
        case ATNState.PLUS_BLOCK_START: fallthrough
        case ATNState.STAR_LOOP_ENTRY:
            // report error and recover if possible
            if try singleTokenDeletion(recognizer) != nil {
                return
            }
            throw ANTLRException.recognition(e: InputMismatchException(recognizer))
        case ATNState.PLUS_LOOP_BACK: fallthrough
        case ATNState.STAR_LOOP_BACK:
//			errPrint("at loop back: "+s.getClass().getSimpleName());
            reportUnwantedToken(recognizer)
            let expecting = try recognizer.getExpectedTokens()
            let whatFollowsLoopIterationOrRule = expecting.or(getErrorRecoverySet(recognizer)) as! IntervalSet
            try consumeUntil(recognizer, whatFollowsLoopIterationOrRule)
            break
        default:
            // do nothing if we can't identify the exact kind of ATN state
            break
        }
    }
    ///
    /// This is called by _#reportError_ when the exception is a
    /// _org.antlr.v4.runtime.NoViableAltException_.
    ///
    /// - seealso: #reportError
    ///
    /// - parameter recognizer: the parser instance
    /// - parameter e: the recognition exception
    ///
    open func reportNoViableAlternative(_ recognizer: Parser, _ e: NoViableAltException) {
        let tokens = getTokenStream(recognizer)
        var input: String
        if e.getStartToken().getType() == CommonToken.EOF {
            input = "<EOF>"
        }
        else {
            do {
                input = try tokens.getText(e.getStartToken(), e.getOffendingToken())
            }
            catch {
                input = "<unknown>"
            }
        }
        let msg = "no viable alternative at input " + escapeWSAndQuote(input)
        recognizer.notifyErrorListeners(e.getOffendingToken(), msg, e)
    }
    ///
    /// This is called by _#reportError_ when the exception is an
    /// _org.antlr.v4.runtime.InputMismatchException_.
    ///
    /// - seealso: #reportError
    ///
    /// - parameter recognizer: the parser instance
    /// - parameter e: the recognition exception
    ///
    open func reportInputMismatch(_ recognizer: Parser, _ e: InputMismatchException) {
        let tok = getTokenErrorDisplay(e.getOffendingToken())
        let expected = e.getExpectedTokens()?.toString(recognizer.getVocabulary()) ?? "<missing>"
        let msg = "mismatched input \(tok) expecting \(expected)"
        recognizer.notifyErrorListeners(e.getOffendingToken(), msg, e)
    }
    ///
    /// This is called by _#reportError_ when the exception is a
    /// _org.antlr.v4.runtime.FailedPredicateException_.
    ///
    /// - seealso: #reportError
    ///
    /// - parameter recognizer: the parser instance
    /// - parameter e: the recognition exception
    ///
    open func reportFailedPredicate(_ recognizer: Parser, _ e: FailedPredicateException) {
        let ruleName = recognizer.getRuleNames()[recognizer._ctx!.getRuleIndex()]
        let msg = "rule \(ruleName) \(e.message!)"
        recognizer.notifyErrorListeners(e.getOffendingToken(), msg, e)
    }
    ///
    /// This method is called to report a syntax error which requires the removal
    /// of a token from the input stream. At the time this method is called, the
    /// erroneous symbol is current `LT(1)` symbol and has not yet been
    /// removed from the input stream. When this method returns,
    /// `recognizer` is in error recovery mode.
    ///
    /// This method is called when _#singleTokenDeletion_ identifies
    /// single-token deletion as a viable recovery strategy for a mismatched
    /// input error.
    ///
    /// The default implementation simply returns if the handler is already in
    /// error recovery mode. Otherwise, it calls _#beginErrorCondition_ to
    /// enter error recovery mode, followed by calling
    /// _org.antlr.v4.runtime.Parser#notifyErrorListeners_.
    ///
    /// - parameter recognizer: the parser instance
    ///
    open func reportUnwantedToken(_ recognizer: Parser) {
        if inErrorRecoveryMode(recognizer) {
            return
        }
        beginErrorCondition(recognizer)
        let t = try? recognizer.getCurrentToken()
        let tokenName = getTokenErrorDisplay(t)
        let expecting = (try? getExpectedTokens(recognizer)) ?? IntervalSet.EMPTY_SET
        let msg = "extraneous input \(tokenName) expecting \(expecting.toString(recognizer.getVocabulary()))"
        recognizer.notifyErrorListeners(t, msg, nil)
    }
    ///
    /// This method is called to report a syntax error which requires the
    /// insertion of a missing token into the input stream. At the time this
    /// method is called, the missing token has not yet been inserted. When this
    /// method returns, `recognizer` is in error recovery mode.
    ///
    /// This method is called when _#singleTokenInsertion_ identifies
    /// single-token insertion as a viable recovery strategy for a mismatched
    /// input error.
    ///
    /// The default implementation simply returns if the handler is already in
    /// error recovery mode. Otherwise, it calls _#beginErrorCondition_ to
    /// enter error recovery mode, followed by calling
    /// _org.antlr.v4.runtime.Parser#notifyErrorListeners_.
    ///
    /// - parameter recognizer: the parser instance
    ///
    open func reportMissingToken(_ recognizer: Parser) {
        if inErrorRecoveryMode(recognizer) {
            return
        }
        beginErrorCondition(recognizer)
        let t = try? recognizer.getCurrentToken()
        let expecting = (try? getExpectedTokens(recognizer)) ?? IntervalSet.EMPTY_SET
        let msg = "missing \(expecting.toString(recognizer.getVocabulary())) at \(getTokenErrorDisplay(t))"
        recognizer.notifyErrorListeners(t, msg, nil)
    }
    ///
    ///
    ///
    /// The default implementation attempts to recover from the mismatched input
    /// by using single token insertion and deletion as described below. If the
    /// recovery attempt fails, this method throws an
    /// _org.antlr.v4.runtime.InputMismatchException_.
    ///
    /// __EXTRA TOKEN__ (single token deletion)
    ///
    /// `LA(1)` is not what we are looking for. If `LA(2)` has the
    /// right token, however, then assume `LA(1)` is some extra spurious
    /// token and delete it. Then consume and return the next token (which was
    /// the `LA(2)` token) as the successful result of the match operation.
    ///
    /// This recovery strategy is implemented by _#singleTokenDeletion_.
    ///
    /// __MISSING TOKEN__ (single token insertion)
    ///
    /// If current token (at `LA(1)`) is consistent with what could come
    /// after the expected `LA(1)` token, then assume the token is missing
    /// and use the parser's _org.antlr.v4.runtime.TokenFactory_ to create it on the fly. The
    /// "insertion" is performed by returning the created token as the successful
    /// result of the match operation.
    ///
    /// This recovery strategy is implemented by _#singleTokenInsertion_.
    ///
    /// __EXAMPLE__
    ///
    /// For example, Input `i=(3;` is clearly missing the `')'`. When
    /// the parser returns from the nested call to `expr`, it will have
    /// call chain:
    ///
    ///
    /// stat → expr → atom
    ///
    ///
    /// and it will be trying to match the `')'` at this point in the
    /// derivation:
    ///
    ///
    /// => ID '=' '(' INT ')' ('+' atom)* ';'
    /// ^
    ///
    ///
    /// The attempt to match `')'` will fail when it sees `';'` and
    /// call _#recoverInline_. To recover, it sees that `LA(1)==';'`
    /// is in the set of tokens that can follow the `')'` token reference
    /// in rule `atom`. It can assume that you forgot the `')'`.
    ///
    open func recoverInline(_ recognizer: Parser) throws -> Token {
        // SINGLE TOKEN DELETION
        let matchedSymbol = try singleTokenDeletion(recognizer)
        if let matchedSymbol = matchedSymbol {
            // we have deleted the extra token.
            // now, move past ttype token as if all were ok
            try recognizer.consume()
            return matchedSymbol
        }
        // SINGLE TOKEN INSERTION
        if try singleTokenInsertion(recognizer) {
            return try getMissingSymbol(recognizer)
        }
        // even that didn't work; must throw the exception
        let exn = InputMismatchException(recognizer, state: nextTokensState, ctx: nextTokensContext)
        throw ANTLRException.recognition(e: exn)
    }
    ///
    /// This method implements the single-token insertion inline error recovery
    /// strategy. It is called by _#recoverInline_ if the single-token
    /// deletion strategy fails to recover from the mismatched input. If this
    /// method returns `true`, `recognizer` will be in error recovery
    /// mode.
    ///
    /// This method determines whether or not single-token insertion is viable by
    /// checking if the `LA(1)` input symbol could be successfully matched
    /// if it were instead the `LA(2)` symbol. If this method returns
    /// `true`, the caller is responsible for creating and inserting a
    /// token with the correct type to produce this behavior.
    ///
    /// - parameter recognizer: the parser instance
    /// - returns: `true` if single-token insertion is a viable recovery
    /// strategy for the current mismatched input, otherwise `false`
    ///
    open func singleTokenInsertion(_ recognizer: Parser) throws -> Bool {
        let currentSymbolType = try getTokenStream(recognizer).LA(1)
        // if current token is consistent with what could come after current
        // ATN state, then we know we're missing a token; error recovery
        // is free to conjure up and insert the missing token
        let currentState = recognizer.getInterpreter().atn.states[recognizer.getState()]!
        let next = currentState.transition(0).target
        let atn = recognizer.getInterpreter().atn
        let expectingAtLL2 = atn.nextTokens(next, recognizer._ctx)
//		print("LT(2) set="+expectingAtLL2.toString(recognizer.getTokenNames()));
        if expectingAtLL2.contains(currentSymbolType) {
            reportMissingToken(recognizer)
            return true
        }
        return false
    }
    ///
    /// This method implements the single-token deletion inline error recovery
    /// strategy. It is called by _#recoverInline_ to attempt to recover
    /// from mismatched input. If this method returns null, the parser and error
    /// handler state will not have changed. If this method returns non-null,
    /// `recognizer` will __not__ be in error recovery mode since the
    /// returned token was a successful match.
    ///
    /// If the single-token deletion is successful, this method calls
    /// _#reportUnwantedToken_ to report the error, followed by
    /// _org.antlr.v4.runtime.Parser#consume_ to actually "delete" the extraneous token. Then,
    /// before returning _#reportMatch_ is called to signal a successful
    /// match.
    ///
    /// - parameter recognizer: the parser instance
    /// - returns: the successfully matched _org.antlr.v4.runtime.Token_ instance if single-token
    /// deletion successfully recovers from the mismatched input, otherwise
    /// `null`
    ///
    open func singleTokenDeletion(_ recognizer: Parser) throws -> Token? {
        let nextTokenType = try getTokenStream(recognizer).LA(2)
        let expecting = try getExpectedTokens(recognizer)
        if expecting.contains(nextTokenType) {
            reportUnwantedToken(recognizer)
            ///
            /// errPrint("recoverFromMismatchedToken deleting "+
            /// ((TokenStream)getTokenStream(recognizer)).LT(1)+
            /// " since "+((TokenStream)getTokenStream(recognizer)).LT(2)+
            /// " is what we want");
            ///
            try recognizer.consume() // simply delete extra token
            // we want to return the token we're actually matching
            let matchedSymbol = try recognizer.getCurrentToken()
            reportMatch(recognizer)  // we know current token is correct
            return matchedSymbol
        }
        return nil
    }
    ///
    /// Conjure up a missing token during error recovery.
    ///
    /// The recognizer attempts to recover from single missing
    /// symbols. But, actions might refer to that missing symbol.
    /// For example, x=ID {f($x);}. The action clearly assumes
    /// that there has been an identifier matched previously and that
    /// $x points at that token. If that token is missing, but
    /// the next token in the stream is what we want we assume that
    /// this token is missing and we keep going. Because we
    /// have to return some token to replace the missing token,
    /// we have to conjure one up. This method gives the user control
    /// over the tokens returned for missing tokens. Mostly,
    /// you will want to create something special for identifier
    /// tokens. For literals such as '{' and ',', the default
    /// action in the parser or tree parser works. It simply creates
    /// a CommonToken of the appropriate type. The text will be the token.
    /// If you change what tokens must be created by the lexer,
    /// override this method to create the appropriate tokens.
    ///
    open func getTokenStream(_ recognizer: Parser) -> TokenStream {
        return recognizer.getInputStream() as! TokenStream
    }
    open func getMissingSymbol(_ recognizer: Parser) throws -> Token {
        let currentSymbol = try recognizer.getCurrentToken()
        let expecting = try getExpectedTokens(recognizer)
        let expectedTokenType = expecting.getMinElement() // get any element
        var tokenText: String
        if expectedTokenType == CommonToken.EOF {
            tokenText = "<missing EOF>"
        } else {
            tokenText = "<missing " + recognizer.getVocabulary().getDisplayName(expectedTokenType) + ">"
        }
        var current = currentSymbol
        let lookback = try getTokenStream(recognizer).LT(-1)
        if current.getType() == CommonToken.EOF && lookback != nil {
            current = lookback!
        }
        let token = recognizer.getTokenFactory().create(
            current.getTokenSourceAndStream(),
            expectedTokenType, tokenText,
            CommonToken.DEFAULT_CHANNEL,
            -1, -1,
            current.getLine(), current.getCharPositionInLine())
        return token
    }
    open func getExpectedTokens(_ recognizer: Parser) throws -> IntervalSet {
        return try recognizer.getExpectedTokens()
    }
    ///
    /// How should a token be displayed in an error message? The default
    /// is to display just the text, but during development you might
    /// want to have a lot of information spit out.  Override in that case
    /// to use t.toString() (which, for CommonToken, dumps everything about
    /// the token). This is better than forcing you to override a method in
    /// your token objects because you don't have to go modify your lexer
    /// so that it creates a new Java type.
    ///
    open func getTokenErrorDisplay(_ t: Token?) -> String {
        guard let t = t else {
            return "<no token>"
        }
        var s = getSymbolText(t)
        if s == nil {
            if getSymbolType(t) == CommonToken.EOF {
                s = "<EOF>"
            } else {
                s = "<\(getSymbolType(t))>"
            }
        }
        return escapeWSAndQuote(s!)
    }
    open func getSymbolText(_ symbol: Token) -> String? {
        return symbol.getText()
    }
    open func getSymbolType(_ symbol: Token) -> Int {
        return symbol.getType()
    }
    open func escapeWSAndQuote(_ s: String) -> String {
        var s = s
        s = s.replacingOccurrences(of: "\n", with: "\\n")
        s = s.replacingOccurrences(of: "\r", with: "\\r")
        s = s.replacingOccurrences(of: "\t", with: "\\t")
        return "'" + s + "'"
    }
    ///
    /// Compute the error recovery set for the current rule.  During
    /// rule invocation, the parser pushes the set of tokens that can
    /// follow that rule reference on the stack; this amounts to
    /// computing FIRST of what follows the rule reference in the
    /// enclosing rule. See LinearApproximator.FIRST().
    /// This local follow set only includes tokens
    /// from within the rule; i.e., the FIRST computation done by
    /// ANTLR stops at the end of a rule.
    ///
    /// EXAMPLE
    ///
    /// When you find a "no viable alt exception", the input is not
    /// consistent with any of the alternatives for rule r.  The best
    /// thing to do is to consume tokens until you see something that
    /// can legally follow a call to r *or* any rule that called r.
    /// You don't want the exact set of viable next tokens because the
    /// input might just be missing a token--you might consume the
    /// rest of the input looking for one of the missing tokens.
    ///
    /// Consider grammar:
    ///
    /// a : '[' b ']'
    /// | '(' b ')'
    /// ;
    /// b : c '^' INT ;
    /// c : ID
    /// | INT
    /// ;
    ///
    /// At each rule invocation, the set of tokens that could follow
    /// that rule is pushed on a stack.  Here are the various
    /// context-sensitive follow sets:
    ///
    /// FOLLOW(b1_in_a) = FIRST(']') = ']'
    /// FOLLOW(b2_in_a) = FIRST(')') = ')'
    /// FOLLOW(c_in_b) = FIRST('^') = '^'
    ///
    /// Upon erroneous input "[]", the call chain is
    ///
    /// a -> b -> c
    ///
    /// and, hence, the follow context stack is:
    ///
    /// depth     follow set       start of rule execution
    /// 0         <EOF>                    a (from main())
    /// 1          ']'                     b
    /// 2          '^'                     c
    ///
    /// Notice that ')' is not included, because b would have to have
    /// been called from a different context in rule a for ')' to be
    /// included.
    ///
    /// we resync'd to that token, we'd consume until EOF.  We need to
    /// sync to context-sensitive FOLLOWs for a, b, and c: {']','^'}.
    /// In this case, for input "[]", LA(1) is ']' and in the set, so we would
    /// not consume anything. After printing an error, rule c would
    /// return normally.  Rule b would not find the required '^' though.
    /// At this point, it gets a mismatched token error and throws an
    /// exception (since LA(1) is not in the viable following token
    /// set).  The rule exception handler tries to recover, but finds
    /// the same recovery set and doesn't consume anything.  Rule b
    /// exits normally returning to rule a.  Now it finds the ']' (and
    /// with the successful match exits errorRecovery mode).
    ///
    /// So, you can see that the parser walks up the call chain looking
    /// for the token that was a member of the recovery set.
    ///
    /// Errors are not generated in errorRecovery mode.
    ///
    /// ANTLR's error recovery mechanism is based upon original ideas:
    ///
    /// "Algorithms + Data Structures = Programs" by Niklaus Wirth
    ///
    /// and
    ///
    /// "A note on error recovery in recursive descent parsers":
    /// http://portal.acm.org/citation.cfm?id=947902.947905
    ///
    /// Later, Josef Grosch had some good ideas:
    ///
    /// "Efficient and Comfortable Error Recovery in Recursive Descent
    /// Parsers":
    /// ftp://www.cocolab.com/products/cocktail/doca4.ps/ell.ps.zip
    ///
    /// Like Grosch I implement context-sensitive FOLLOW sets that are combined
    /// at run-time upon error to avoid overhead during parsing.
    ///
    open func getErrorRecoverySet(_ recognizer: Parser) -> IntervalSet {
        let atn = recognizer.getInterpreter().atn
        var ctx: RuleContext? = recognizer._ctx
        let recoverSet = IntervalSet()
        while let ctxWrap = ctx, ctxWrap.invokingState >= 0 {
            // compute what follows who invoked us
            let invokingState = atn.states[ctxWrap.invokingState]!
            let rt = invokingState.transition(0) as! RuleTransition
            let follow = atn.nextTokens(rt.followState)
            try! recoverSet.addAll(follow)
            ctx = ctxWrap.parent
        }
        try! recoverSet.remove(CommonToken.EPSILON)
//		print("recover set "+recoverSet.toString(recognizer.getTokenNames()));
        return recoverSet
    }
    ///
    /// Consume tokens until one matches the given token set.
    ///
    open func consumeUntil(_ recognizer: Parser, _ set: IntervalSet) throws {
//		errPrint("consumeUntil("+set.toString(recognizer.getTokenNames())+")");
        var ttype = try getTokenStream(recognizer).LA(1)
        while ttype != CommonToken.EOF && !set.contains(ttype) {
            //print("consume during recover LA(1)="+getTokenNames()[input.LA(1)]);
            try recognizer.consume()
            ttype = try getTokenStream(recognizer).LA(1)
        }
    }
}


InputMismatchException

///
///
///
/// This signifies any kind of mismatched input exceptions such as
/// when the current input does not match the expected token.
///
public class InputMismatchException: RecognitionException {
    public init(_ recognizer: Parser, state: Int = ATNState.INVALID_STATE_NUMBER, ctx: ParserRuleContext? = nil) {
        let bestCtx = ctx ?? recognizer._ctx
        super.init(recognizer, recognizer.getInputStream()!, bestCtx)
        if let token = try? recognizer.getCurrentToken() {
            setOffendingToken(token)
        }
        if (state != ATNState.INVALID_STATE_NUMBER) {
            setOffendingState(state)
        }
    }
}


ANTLRInputStream

///
///
///
/// Vacuum all input from a _java.io.Reader_/_java.io.InputStream_ and then treat it
/// like a `char[]` buffer. Can also pass in a _String_ or
/// `char[]` to use.
///
/// If you need encoding, pass in stream/reader with correct encoding.
///
public class ANTLRInputStream: CharStream {
    ///
    /// The data being scanned
    ///
    internal let data: [UnicodeScalar]
    ///
    /// How many unicode scalars are actually in the buffer
    ///
    internal var n: Int
    ///
    /// 0...n-1 index into string of next char
    ///
    internal var p = 0
    ///
    /// What is name or source of this char stream?
    ///
    public var name: String?
    public init() {
        n = 0
        data = []
    }
    ///
    /// Copy data in string to a local char array
    ///
    public init(_ input: String) {
        self.data = Array(input.unicodeScalars)
        self.n = data.count
    }
    ///
    /// This is the preferred constructor for strings as no data is copied
    ///
    public init(_ data: [UnicodeScalar], _ numberOfActualUnicodeScalarsInArray: Int) {
        self.data = data
        self.n = numberOfActualUnicodeScalarsInArray
    }
    ///
    /// This is only for backward compatibility that accepts array of `Character`.
    /// Use `init(_ data: [UnicodeScalar], _ numberOfActualUnicodeScalarsInArray: Int)` instead.
    ///
    public init(_ data: [Character], _ numberOfActualUnicodeScalarsInArray: Int) {
        let string = String(data)
        self.data = Array(string.unicodeScalars)
        self.n = numberOfActualUnicodeScalarsInArray
    }
    public func reset() {
        p = 0
    }
    public func consume() throws {
        if p >= n {
            assert(LA(1) == ANTLRInputStream.EOF, "Expected: LA(1)==IntStream.EOF")
            throw ANTLRError.illegalState(msg: "cannot consume EOF")
        }
        // print("prev p="+p+", c="+(char)data[p]);
        if p < n {
            p += 1
            //print("p moves to "+p+" (c='"+(char)data[p]+"')");
        }
    }
    public func LA(_ i: Int) -> Int {
        var i = i
        if i == 0 {
            return 0 // undefined
        }
        if i < 0 {
            i += 1 // e.g., translate LA(-1) to use offset i=0; then data[p+0-1]
            if (p + i - 1) < 0 {
                return ANTLRInputStream.EOF// invalid; no char before first char
            }
        }
        if (p + i - 1) >= n {
            //print("char LA("+i+")=EOF; p="+p);
            return ANTLRInputStream.EOF
        }
        //print("char LA("+i+")="+(char)data[p+i-1]+"; p="+p);
        //print("LA("+i+"); p="+p+" n="+n+" data.length="+data.length);
        return Int(data[p + i - 1].value)
    }
    public func LT(_ i: Int) -> Int {
        return LA(i)
    }
    ///
    /// Return the current input symbol index 0...n where n indicates the
    /// last symbol has been read.  The index is the index of char to
    /// be returned from LA(1).
    ///
    public func index() -> Int {
        return p
    }
    public func size() -> Int {
        return n
    }
    ///
    /// mark/release do nothing; we have entire buffer
    ///
    public func mark() -> Int {
        return -1
    }
    public func release(_ marker: Int) {
    }
    ///
    /// consume() ahead until p==index; can't just set p=index as we must
    /// update line and charPositionInLine. If we seek backwards, just set p
    ///
    public func seek(_ index: Int) throws {
        var index = index
        if index <= p {
            p = index // just jump; don't update stream state (line, ...)
            return
        }
        // seek forward, consume until p hits index or n (whichever comes first)
        index = min(index, n)
        while p < index {
            try consume()
        }
    }
    public func getText(_ interval: Interval) -> String {
        let start = interval.a
        if start >= n {
            return ""
        }
        let stop = min(n, interval.b + 1)
        var unicodeScalarView = String.UnicodeScalarView()
        unicodeScalarView.append(contentsOf: data[start ..< stop])
        return String(unicodeScalarView)
    }
    public func getSourceName() -> String {
        return name ?? ANTLRInputStream.UNKNOWN_SOURCE_NAME
    }
    public func toString() -> String {
        var unicodeScalarView = String.UnicodeScalarView()
        unicodeScalarView.append(contentsOf: data)
        return String(unicodeScalarView)
    }
}


CommonToken

///
///
public class CommonToken: WritableToken {
    ///
    /// This is the backing field for _#getType_ and _#setType_.
    ///
    internal var type: Int
    ///
    /// This is the backing field for _#getLine_ and _#setLine_.
    ///
    internal var line = 0
    ///
    /// This is the backing field for _#getCharPositionInLine_ and
    /// _#setCharPositionInLine_.
    ///
    internal var charPositionInLine = -1
    // set to invalid position
    ///
    /// This is the backing field for _#getChannel_ and
    /// _#setChannel_.
    ///
    internal var channel = DEFAULT_CHANNEL
    ///
    /// This is the backing field for _#getTokenSource_ and
    /// _#getInputStream_.
    ///
    ///
    /// These properties share a field to reduce the memory footprint of
    /// _org.antlr.v4.runtime.CommonToken_. Tokens created by a _org.antlr.v4.runtime.CommonTokenFactory_ from
    /// the same source and input stream share a reference to the same
    /// _org.antlr.v4.runtime.misc.Pair_ containing these values.
    ///
    internal let source: TokenSourceAndStream
    ///
    /// This is the backing field for _#getText_ when the token text is
    /// explicitly set in the constructor or via _#setText_.
    ///
    /// - seealso: #getText()
    ///
    internal var text: String?
    ///
    /// This is the backing field for _#getTokenIndex_ and
    /// _#setTokenIndex_.
    ///
    internal var index = -1
    ///
    /// This is the backing field for _#getStartIndex_ and
    /// _#setStartIndex_.
    ///
    internal var start = 0
    ///
    /// This is the backing field for _#getStopIndex_ and
    /// _#setStopIndex_.
    ///
    internal var stop = 0
    ///
    /// Constructs a new _org.antlr.v4.runtime.CommonToken_ with the specified token type.
    ///
    /// - parameter type: The token type.
    ///
    private var _visited: Bool = false
    public init(_ type: Int) {
        self.type = type
        self.source = TokenSourceAndStream.EMPTY
    }
    public init(_ source: TokenSourceAndStream, _ type: Int, _ channel: Int, _ start: Int, _ stop: Int) {
        self.source = source
        self.type = type
        self.channel = channel
        self.start = start
        self.stop = stop
        if let tsource = source.tokenSource {
            self.line = tsource.getLine()
            self.charPositionInLine = tsource.getCharPositionInLine()
        }
    }
    ///
    /// Constructs a new _org.antlr.v4.runtime.CommonToken_ with the specified token type and
    /// text.
    ///
    /// - parameter type: The token type.
    /// - parameter text: The text of the token.
    ///
    public init(_ type: Int, _ text: String?) {
        self.type = type
        self.channel = CommonToken.DEFAULT_CHANNEL
        self.text = text
        self.source = TokenSourceAndStream.EMPTY
    }
    ///
    /// Constructs a new _org.antlr.v4.runtime.CommonToken_ as a copy of another _org.antlr.v4.runtime.Token_.
    ///
    /// - parameter oldToken: The token to copy.
    ///
    public init(_ oldToken: Token) {
        type = oldToken.getType()
        line = oldToken.getLine()
        index = oldToken.getTokenIndex()
        charPositionInLine = oldToken.getCharPositionInLine()
        channel = oldToken.getChannel()
        start = oldToken.getStartIndex()
        stop = oldToken.getStopIndex()
        text = oldToken.getText()
        source = oldToken.getTokenSourceAndStream()
    }
    public func getType() -> Int {
        return type
    }
    public func setLine(_ line: Int) {
        self.line = line
    }
    public func getText() -> String? {
        if let text = text {
            return text
        }
        if let input = getInputStream() {
            let n = input.size()
            if start < n && stop < n {
                do {
                    return try input.getText(Interval.of(start, stop))
                }
                catch {
                    return nil
                }
            } else {
                return "<EOF>"
            }
        }
        return nil
    }
    ///
    /// Explicitly set the text for this token. If {code text} is not
    /// `null`, then _#getText_ will return this value rather than
    /// extracting the text from the input.
    ///
    /// - parameter text: The explicit text of the token, or `null` if the text
    /// should be obtained from the input along with the start and stop indexes
    /// of the token.
    ///
    public func setText(_ text: String) {
        self.text = text
    }
    public func getLine() -> Int {
        return line
    }
    public func getCharPositionInLine() -> Int {
        return charPositionInLine
    }
    public func setCharPositionInLine(_ charPositionInLine: Int) {
        self.charPositionInLine = charPositionInLine
    }
    public func getChannel() -> Int {
        return channel
    }
    public func setChannel(_ channel: Int) {
        self.channel = channel
    }
    public func setType(_ type: Int) {
        self.type = type
    }
    public func getStartIndex() -> Int {
        return start
    }
    public func setStartIndex(_ start: Int) {
        self.start = start
    }
    public func getStopIndex() -> Int {
        return stop
    }
    public func setStopIndex(_ stop: Int) {
        self.stop = stop
    }
    public func getTokenIndex() -> Int {
        return index
    }
    public func setTokenIndex(_ index: Int) {
        self.index = index
    }
    public func getTokenSource() -> TokenSource? {
        return source.tokenSource
    }
    public func getInputStream() -> CharStream? {
        return source.stream
    }
    public func getTokenSourceAndStream() -> TokenSourceAndStream {
        return source
    }
    public var description: String {
        return toString(nil)
    }
    public func toString(_ r: Recognizer<ATNSimulator>?) -> String {
        let channelStr = (channel > 0 ? ",channel=\(channel)" : "")
        var txt: String
        if let tokenText = getText() {
            txt = tokenText.replacingOccurrences(of: "\n", with: "\\n")
            txt = txt.replacingOccurrences(of: "\r", with: "\\r")
            txt = txt.replacingOccurrences(of: "\t", with: "\\t")
        } else {
            txt = "<no text>"
        }
        let typeString: String
        if let r = r {
            typeString = r.getVocabulary().getDisplayName(type)
        }
        else {
            typeString = "\(type)"
        }
    }
    public var visited: Bool {
        get {
            return _visited
        }
        set {
            _visited = newValue
        }
    }
}


UnbufferedCharStream

/*
 */
import Foundation
/** Do not buffer up the entire char stream. It does keep a small buffer
 *  for efficiency and also buffers while a mark exists (set by the
 *  lookahead prediction in parser). "Unbuffered" here refers to fact
 *  that it doesn't buffer all data, not that's it's on demand loading of char.
 *
 *  Before 4.7, this class used the default environment encoding to convert
 *  bytes to UTF-16, and held the UTF-16 bytes in the buffer as chars.
 *
 *  As of 4.7, the class uses UTF-8 by default, and the buffer holds Unicode
 *  code points in the buffer as ints.
 */
open class UnbufferedCharStream: CharStream {
    private let bufferSize: Int
    /**
     * A moving window buffer of the data being scanned. While there's a marker,
     * out of buffered characters.

     */
    internal var p = 0
    /**
     * entire stream, although the stream size is unknown before the end is
     * reached.
     */
    internal var currentCharIndex = 0
    internal let input: InputStream
    private var unicodeIterator: UnicodeScalarStreamIterator
    /** The name or source of this char stream. */
    public var name: String = ""
    public init(_ input: InputStream, _ bufferSize: Int = 256) {
        self.input = input
        self.bufferSize = bufferSize
        self.data = [Int](repeating: 0, count: bufferSize)
        let si = UInt8StreamIterator(input)
        self.unicodeIterator = UnicodeScalarStreamIterator(si)
    }
    public func consume() throws {
        if try LA(1) == CommonToken.EOF {
            throw ANTLRError.illegalState(msg: "cannot consume EOF")
        }
        // buf always has at least data[p==0] in this method due to ctor
        lastChar = data[p]   // track last char for LA(-1)
        if p == n - 1 && numMarkers == 0 {
            n = 0
            p = -1 // p++ will leave this at 0
            lastCharBufferStart = lastChar
        }
        p += 1
        currentCharIndex += 1
        sync(1)
    }
    /**
        for i in 0 ..< toAdd {
            if n > 0 && data[n - 1] == CommonToken.EOF {
                return i
            }
            guard let c = nextChar() else {
                return i
            }
     */
    internal func nextChar() -> Int? {
        if let next = unicodeIterator.next() {
            return Int(next.value)
        }
        else if unicodeIterator.hasErrorOccurred {
            return nil
        }
        else {
            return nil
        }
    }
    internal func add(_ c: Int) {
        if n >= data.count {
            data += [Int](repeating: 0, count: data.count)
        }
        data[n] = c
        n += 1
    }
    public func LA(_ i: Int) throws -> Int {
        if i == -1 {
            return lastChar // special case
        }
        sync(i)
        let index = p + i - 1
        if index < 0 {
            throw ANTLRError.indexOutOfBounds(msg: "")
        }
        if index >= n {
            return CommonToken.EOF
        }
        return data[index]
    }
    /**
     * Return a marker that we can release later.
     *
     *
The specific marker value used for this class allows for some level of
     */
    public func release(_ marker: Int) throws {
        let expectedMark = -numMarkers
        if marker != expectedMark {
            preconditionFailure("release() called with an invalid marker.")
        }
        numMarkers -= 1
        if numMarkers == 0 && p > 0 {
            // release buffer when we can, but don't do unnecessary work
            // Copy data[p]..data[n-1] to data[0]..data[(n-1)-p], reset ptrs
            // p is last valid char; move nothing if p==n as we have no valid char
            if p == n {
                if data.count != bufferSize {
                    data = [Int](repeating: 0, count: bufferSize)
                }
                n = 0
            }
            else {
                data = Array(data[p ..< n])
                n -= p
            }
            p = 0
            lastCharBufferStart = lastChar
        }
    }
    public func index() -> Int {
        return currentCharIndex
    }
    /** Seek to absolute character index, which might not be in the current
     */
    public func seek(_ index_: Int) throws {
        var index = index_
        if index == currentCharIndex {
            return
        }
        if index > currentCharIndex {
            sync(index - currentCharIndex)
            index = min(index, getBufferStartIndex() + n - 1)
        }
        // index == to bufferStartIndex should set p to 0
        let i = index - getBufferStartIndex()
        if i < 0 {
            throw ANTLRError.illegalArgument(msg: "cannot seek to negative index \(index)")
        }
        else if i >= n {
            let si = getBufferStartIndex()
            let ei = si + n
            let msg = "seek to index outside buffer: \(index) not in \(si)..\(ei)"
            throw ANTLRError.unsupportedOperation(msg: msg)
        }
        p = i
        currentCharIndex = index
        if p == 0 {
            lastChar = lastCharBufferStart
        }
        else {
            lastChar = data[p - 1]
        }
    }
    public func size() -> Int {
        preconditionFailure("Unbuffered stream cannot know its size")
    }
    public func getSourceName() -> String {
        return name
    }
    public func getText(_ interval: Interval) throws -> String {
        if interval.a < 0 || interval.b < interval.a - 1 {
            throw ANTLRError.illegalArgument(msg: "invalid interval")
        }
        let bufferStartIndex = getBufferStartIndex()
        if n > 0 &&
            data[n - 1] == CommonToken.EOF &&
            interval.a + interval.length() > bufferStartIndex + n {
            throw ANTLRError.illegalArgument(msg: "the interval extends past the end of the stream")
        }
        if interval.a < bufferStartIndex || interval.b >= bufferStartIndex + n {
            let msg = "interval \(interval) outside buffer: \(bufferStartIndex)...\(bufferStartIndex + n - 1)"
            throw ANTLRError.unsupportedOperation(msg: msg)
        }
        if interval.b < interval.a {
            // The EOF token.
            return ""
        }
        // convert from absolute to local index
        let i = interval.a - bufferStartIndex
        let j = interval.b - bufferStartIndex
        // Convert from Int codepoints to a String.
        let codepoints = data[i ... j].map { Character(Unicode.Scalar($0)!) }
        return String(codepoints)
    }
    internal func getBufferStartIndex() -> Int {
        return currentCharIndex - p
    }
}
fileprivate struct UInt8StreamIterator: IteratorProtocol {
    private static let bufferSize = 1024
    private let stream: InputStream
    private var buffer = [UInt8](repeating: 0, count: UInt8StreamIterator.bufferSize)
    private var buffGen: IndexingIterator<ArraySlice<UInt8>>
    var hasErrorOccurred = false
    init(_ stream: InputStream) {
        self.stream = stream
        self.buffGen = buffer[0..<0].makeIterator()
    }
    mutating func next() -> UInt8? {
        if let result = buffGen.next() {
            return result
        }
        if hasErrorOccurred {
            return nil
        }
        switch stream.streamStatus {
            case .notOpen, .writing, .closed:
                preconditionFailure()
            case .atEnd:
                return nil
            case .error:
                hasErrorOccurred = true
                return nil
            case .opening, .open, .reading:
                break
        }
        let count = stream.read(&buffer, maxLength: buffer.count)
        if count < 0 {
            hasErrorOccurred = true
            return nil
        }
        else if count == 0 {
            return nil
        }
        buffGen = buffer.prefix(count).makeIterator()
        return buffGen.next()
    }
}
fileprivate struct UnicodeScalarStreamIterator: IteratorProtocol {
    private var streamIterator: UInt8StreamIterator
    private var codec = Unicode.UTF8()
    var hasErrorOccurred = false
    init(_ streamIterator: UInt8StreamIterator) {
        self.streamIterator = streamIterator
    }
    mutating func next() -> Unicode.Scalar? {
        if streamIterator.hasErrorOccurred {
            hasErrorOccurred = true
            return nil
        }
        switch codec.decode(&streamIterator) {
        case .scalarValue(let scalar):
            return scalar
        case .emptyInput:
            return nil
        case .error:
            hasErrorOccurred = true
            return nil
        }
    }
}


RuleContext

 */
/// A rule context is a record of a single rule invocation.
///
/// We form a stack of these context objects using the parent
/// pointer. A parent pointer of null indicates that the current
/// context is the bottom of the stack. The ParserRuleContext subclass
/// as a children list so that we can turn this data structure into a
/// tree.
///
/// The root node always has a null pointer and invokingState of ATNState.INVALID_STATE_NUMBER.
///
/// Upon entry to parsing, the first invoked rule function creates a
/// context object (asubclass specialized for that rule such as
/// SContext) and makes it the root of a parse tree, recorded by field
/// Parser._ctx.
///
/// public final SContext s() throws RecognitionException {
/// SContext _localctx = new SContext(_ctx, getState()); <-- create new node
/// enterRule(_localctx, 0, RULE_s);                     <-- push it
/// ...
/// exitRule();                                          <-- pop back to _localctx
/// return _localctx;
/// }
///
/// A subsequent rule invocation of r from the start rule s pushes a
/// new context object for r whose parent points at s and use invoking
/// state is the state with r emanating as edge label.
///
/// The invokingState fields from a context object to the root
/// together form a stack of rule indication states where the root
/// (bottom of the stack) has a -1 sentinel value. If we invoke start
/// symbol s then call r1, which calls r2, the  would look like
/// this:
///
/// SContext[-1]   <- root node (bottom of the stack)
/// R1Context[p]   <- p in rule s called r1
/// R2Context[q]   <- q in rule r1 called r2
///
/// So the top of the stack, _ctx, represents a call to the current
/// rule and it holds the return address from another rule that invoke
/// to this rule. To invoke a rule, we must always have a current context.
///
/// The parent contexts are useful for computing lookahead sets and
/// getting error information.
///
/// These objects are used during parsing and prediction.
/// For the special case of parsers, we use the subclass
/// ParserRuleContext.
///
/// - SeeAlso: org.antlr.v4.runtime.ParserRuleContext
///
open class RuleContext: RuleNode {
    /// What context invoked this rule?
    public weak var parent: RuleContext?
    /// What state invoked the rule associated with this context?
    /// The "return address" is the followState of invokingState
    /// If parent is null, this should be ATNState.INVALID_STATE_NUMBER
    /// this context object represents the start rule.
    ///
    public var invokingState = ATNState.INVALID_STATE_NUMBER
    public init() {
    }
    public init(_ parent: RuleContext?, _ invokingState: Int) {
        self.parent = parent
        //if ( parent!=null ) { print("invoke "+stateNumber+" from "+parent)}
        self.invokingState = invokingState
    }
    open func depth() -> Int {
        var n = 0
        var p: RuleContext? = self
        while let pWrap = p {
            p = pWrap.parent
            n += 1
        }
        return n
    }
    /// A context is empty if there is no invoking state; meaning nobody called
    /// current context.
    ///
    open func isEmpty() -> Bool {
        return invokingState == ATNState.INVALID_STATE_NUMBER
    }
    // satisfy the ParseTree / SyntaxTree interface
    open func getSourceInterval() -> Interval {
        return Interval.INVALID
    }
    open func getRuleContext() -> RuleContext {
        return self
    }
    open func getParent() -> Tree? {
        return parent
    }
    open func setParent(_ parent: RuleContext) {
        self.parent = parent
    }
    open func getPayload() -> AnyObject {
        return self
    }
    /// Return the combined text of all child nodes. This method only considers
    /// tokens which have been added to the parse tree.
    ///
    /// Since tokens on hidden channels (e.g. whitespace or comments) are not
    /// added to the parse trees, they will not appear in the output of this
    /// method.
    ///
    open func getText() -> String {
        let length = getChildCount()
        if length == 0 {
            return ""
        }
        var builder = ""
        for i in 0..<length {
            builder += self[i].getText()
        }
        return builder
    }
    open func getRuleIndex() -> Int {
        return -1
    }
    open func getAltNumber() -> Int { return ATN.INVALID_ALT_NUMBER }
    open func setAltNumber(_ altNumber: Int) { }
    open func getChild(_ i: Int) -> Tree? {
        return nil
    }
    open func getChildCount() -> Int {
        return 0
    }
    open subscript(index: Int) -> ParseTree {
        preconditionFailure("Index out of range (RuleContext never has children, though its subclasses may).")
    }
    open func accept<T>(_ visitor: ParseTreeVisitor<T>) -> T? {
        return visitor.visitChildren(self)
    }
    /// Print out a whole tree, not just a node, in LISP format
    /// (root child1 .. childN). Print just a node if this is a leaf.
    /// We have to know the recognizer so we can get rule names.
    ///
    open func toStringTree(_ recog: Parser) -> String {
        return Trees.toStringTree(self, recog)
    }
    /// Print out a whole tree, not just a node, in LISP format
    /// (root child1 .. childN). Print just a node if this is a leaf.
    ///
    public func toStringTree(_ ruleNames: [String]?) -> String {
        return Trees.toStringTree(self, ruleNames)
    }
    open func toStringTree() -> String {
        return toStringTree(nil)
    }
    open var description: String {
        return toString(nil, nil)
    }
     open var debugDescription: String {
         return description
    }
    public final func toString<T>(_ recog: Recognizer<T>) -> String {
        return toString(recog, ParserRuleContext.EMPTY)
    }
    public final func toString(_ ruleNames: [String]) -> String {
        return toString(ruleNames, nil)
    }
    // recog null unless ParserRuleContext, in which case we use subclass toString(...)
    open func toString<T>(_ recog: Recognizer<T>?, _ stop: RuleContext) -> String {
        let ruleNames = recog?.getRuleNames()
        return toString(ruleNames, stop)
    }
    open func toString(_ ruleNames: [String]?, _ stop: RuleContext?) -> String {
        var buf = ""
        var p: RuleContext? = self
        buf += "["
        while let pWrap = p, pWrap !== stop {
            if let ruleNames = ruleNames {
                let ruleIndex = pWrap.getRuleIndex()
                let ruleIndexInRange = (ruleIndex >= 0 && ruleIndex < ruleNames.count)
                let ruleName = (ruleIndexInRange ? ruleNames[ruleIndex] : String(ruleIndex))
                buf += ruleName
            }
            else {
                if !pWrap.isEmpty() {
                    buf += String(pWrap.invokingState)
                }
            }
            if let pWp = pWrap.parent, (ruleNames != nil || !pWp.isEmpty()) {
                buf += " "
            }
            p = pWrap.parent
        }
        buf += "]"
        return buf
    }
    open func castdown<T>(_ subType: T.Type) -> T {
        return self as! T
    }
}


UnbufferedTokenStream

 */
public class UnbufferedTokenStream: TokenStream {
    internal var tokenSource: TokenSource
    ///
    /// A moving window buffer of the data being scanned. While there's a marker,
    /// we keep adding to buffer. Otherwise, _#consume consume()_ resets so
    /// we start filling at index 0 again.
    ///
    internal var tokens = [Token]()
    ///
    /// The number of tokens currently in `self.tokens`.
    ///
    /// This is not the buffer capacity, that's `self.tokens.count`.
    ///
    internal var n = 0
    ///
    /// `0...n-1` index into `self.tokens` of next token.
    ///
    /// The `LT(1)` token is `tokens[p]`. If `p == n`, we are
    /// out of buffered tokens.
    ///
    internal var p = 0
    ///
    /// Count up with _#mark mark()_ and down with
    /// _#release release()_. When we `release()` the last mark,
    /// `numMarkers` reaches 0 and we reset the buffer. Copy
    /// `tokens[p]..tokens[n-1]` to `tokens[0]..tokens[(n-1)-p]`.
    ///
    internal var numMarkers = 0
    ///
    /// This is the `LT(-1)` token for the current position.
    ///
    internal var lastToken: Token!
    ///
    /// When `numMarkers > 0`, this is the `LT(-1)` token for the
    /// first token in _#tokens_. Otherwise, this is `null`.
    ///
    internal var lastTokenBufferStart: Token!
    ///
    /// Absolute token index. It's the index of the token about to be read via
    /// `LT(1)`. Goes from 0 to the number of tokens in the entire stream,
    /// although the stream size is unknown before the end is reached.
    ///
    /// This value is used to set the token indexes if the stream provides tokens
    /// that implement _org.antlr.v4.runtime.WritableToken_.
    ///
    internal var currentTokenIndex = 0
    public init(_ tokenSource: TokenSource) throws {
        self.tokenSource = tokenSource
        try fill(1) // prime the pump
    }
    public func get(_ i: Int) throws -> Token {
        // get absolute index
        let bufferStartIndex = getBufferStartIndex()
        if i < bufferStartIndex || i >= bufferStartIndex + n {
            throw ANTLRError.indexOutOfBounds(msg: "get(\(i)) outside buffer: \(bufferStartIndex)..\(bufferStartIndex + n)")
        }
        return tokens[i - bufferStartIndex]
    }
    public func LT(_ i: Int) throws -> Token? {
        if i == -1 {
            return lastToken
        }
        try sync(i)
        let index: Int = p + i - 1
        if index < 0 {
            throw ANTLRError.indexOutOfBounds(msg: "LT(\(i) gives negative index")
        }
        if index >= n {
            //Token.EOF
            assert(n > 0 && tokens[n - 1].getType() == CommonToken.EOF, "Expected: n>0&&tokens[n-1].getType()==Token.EOF")
            return tokens[n - 1]
        }
        return tokens[index]
    }
    public func LA(_ i: Int) throws -> Int {
        return try LT(i)!.getType()
    }
    public func getTokenSource() -> TokenSource {
        return tokenSource
    }
    public func getText() -> String {
        return ""
    }
    public func getText(_ ctx: RuleContext) throws -> String {
        return try getText(ctx.getSourceInterval())
    }
    public func getText(_ start: Token?, _ stop: Token?) throws -> String {
        return try getText(Interval.of(start!.getTokenIndex(), stop!.getTokenIndex()))
    }
    public func consume() throws {
        //Token.EOF
        if try  LA(1) == CommonToken.EOF {
            throw ANTLRError.illegalState(msg: "cannot consume EOF")
        }
        // buf always has at least tokens[p==0] in this method due to ctor
        lastToken = tokens[p]   // track last token for LT(-1)
        // if we're at last token and no markers, opportunity to flush buffer
        if p == n - 1 && numMarkers == 0 {
            n = 0
            p = -1 // p++ will leave this at 0
            lastTokenBufferStart = lastToken
        }
        p += 1
        currentTokenIndex += 1
        try sync(1)
    }
    /// Make sure we have 'need' elements from current position _#p p_. Last valid
    /// `p` index is `tokens.length-1`.  `p+need-1` is the tokens index 'need' elements
    /// ahead.  If we need 1 element, `(p+1-1)==p` must be less than `tokens.length`.
    ///
    internal func sync(_ want: Int) throws {
        let need: Int = (p + want - 1) - n + 1 // how many more elements we need?
        if need > 0 {
            try fill(need)
        }
    }
    ///
    /// Add `n` elements to the buffer. Returns the number of tokens
    /// actually added to the buffer. If the return value is less than `n`,
    /// then EOF was reached before `n` tokens could be added.
    ///
    internal func fill(_ n: Int) throws -> Int {
        for i in 0..<n {
            if self.n > 0 && tokens[self.n - 1].getType() == CommonToken.EOF {
                return i
            }
            let t: Token = try tokenSource.nextToken()
            add(t)
        }
        return n
    }
    internal func add(_ t: Token) {
        if n >= tokens.count {
            //TODO: array count buffer size
            //tokens = Arrays.copyOf(tokens, tokens.length * 2);
        }
        if let wt = t as? WritableToken {
            wt.setTokenIndex(getBufferStartIndex() + n)
        }
        tokens[n] = t
        n += 1
    }
    ///
    /// Return a marker that we can release later.
    ///
    /// The specific marker value used for this class allows for some level of
    /// protection against misuse where `seek()` is called on a mark or
    /// `release()` is called in the wrong order.
    ///
    public func mark() -> Int {
        if numMarkers == 0 {
            lastTokenBufferStart = lastToken
        }
        let mark = -numMarkers - 1
        numMarkers += 1
        return mark
    }
    public func release(_ marker: Int) throws {
        let expectedMark = -numMarkers
        if marker != expectedMark {
            throw ANTLRError.illegalState(msg: "release() called with an invalid marker.")
        }
        numMarkers -= 1
        if numMarkers == 0 {
            // can we release buffer?
            if p > 0 {
                // Copy tokens[p]..tokens[n-1] to tokens[0]..tokens[(n-1)-p], reset ptrs
                // p is last valid token; move nothing if p==n as we have no valid char
                tokens = Array(tokens[p ... n - 1])
                n = n - p
                p = 0
            }
            lastTokenBufferStart = lastToken
        }
    }
    public func index() -> Int {
        return currentTokenIndex
    }
    public func seek(_ index: Int) throws {
        var index = index
        // seek to absolute index
        if index == currentTokenIndex {
            return
        }
        if index > currentTokenIndex {
            try sync(index - currentTokenIndex)
            index = min(index, getBufferStartIndex() + n - 1)
        }
        let bufferStartIndex = getBufferStartIndex()
        let i = index - bufferStartIndex
        if i < 0 {
            throw ANTLRError.illegalState(msg: "cannot seek to negative index \(index)")
        }
        else if i >= n {
            throw ANTLRError.unsupportedOperation(msg: "seek to index outside buffer: \(index) not in \(bufferStartIndex)..<\(bufferStartIndex + n)")
        }
        p = i
        currentTokenIndex = index
        if p == 0 {
            lastToken = lastTokenBufferStart
        } else {
            lastToken = tokens[p - 1]
        }
    }
    public func size() -> Int {
        fatalError("Unbuffered stream cannot know its size")
    }
    public func getSourceName() -> String {
        return tokenSource.getSourceName()
    }
    public func getText(_ interval: Interval) throws -> String {
        let bufferStartIndex = getBufferStartIndex()
        let bufferStopIndex = bufferStartIndex + tokens.count - 1
        let start = interval.a
        let stop = interval.b
        if start < bufferStartIndex || stop > bufferStopIndex {
            throw ANTLRError.unsupportedOperation(msg: "interval \(interval) not in token buffer window: \(bufferStartIndex)...\(bufferStopIndex)")
        }
        let a = start - bufferStartIndex
        let b = stop - bufferStartIndex
        var buf = ""
        for t in tokens[a...b] {
            buf += t.getText()!
        }
        return buf
    }
    internal final func getBufferStartIndex() -> Int {
        return currentTokenIndex - p
    }
}


TokenStreamRewriter

 */
///
/// Useful for rewriting out a buffered input token stream after doing some
/// augmentation or other manipulations on it.
///
///
/// You can insert stuff, replace, and delete chunks. Note that the operations
/// are done lazily--only if you convert the buffer to a _String_ with
/// _org.antlr.v4.runtime.TokenStream#getText()_. This is very efficient because you are not
/// moving data around all the time. As the buffer of tokens is converted to
/// strings, the _#getText()_ method(s) scan the input token stream and
/// check to see if there is an operation at the current index. If so, the
/// operation is done and then normal _String_ rendering continues on the
/// buffer. This is like having multiple Turing machine instruction streams
/// (programs) operating on a single input tape. :)
///
///
/// This rewriter makes no modifications to the token stream. It does not ask the
/// stream to fill itself up nor does it advance the input cursor. The token
/// stream _org.antlr.v4.runtime.TokenStream#index()_ will return the same value before and
/// after any _#getText()_ call.
///
///
/// The rewriter only works on tokens that you have in the buffer and ignores the
/// current input cursor. If you are buffering tokens on-demand, calling
/// _#getText()_ halfway through the input will only do rewrites for those
/// tokens in the first half of the file.
///
///
/// Since the operations are done lazily at _#getText_-time, operations do
/// not screw up the token index values. That is, an insert operation at token
/// index `i` does not change the index values for tokens
/// `i`+1..n-1.
///
///
/// Because operations never actually alter the buffer, you may always get the
/// original token stream back without undoing anything. Since the instructions
/// are queued up, you can easily simulate transactions and roll back any changes
/// if there is an error just by removing instructions. For example,
///
///
/// CharStream input = new ANTLRFileStream("input");
/// TLexer lex = new TLexer(input);
/// CommonTokenStream tokens = new CommonTokenStream(lex);
/// T parser = new T(tokens);
/// TokenStreamRewriter rewriter = new TokenStreamRewriter(tokens);
/// parser.startRule();
///
///
///
/// Then in the rules, you can execute (assuming rewriter is visible):
///
///
/// Token t,u;
/// ...
/// rewriter.insertAfter(t, "text to put after t");}
/// rewriter.insertAfter(u, "text after u");}
/// System.out.println(rewriter.getText());
///
///
///
/// You can also have multiple "instruction streams" and get multiple rewrites
/// from a single pass over the input. Just name the instruction streams and use
/// that name again when printing the buffer. This could be useful for generating
/// a C file and also its header file--all from the same buffer:
///
///
/// rewriter.insertAfter("pass1", t, "text to put after t");}
/// rewriter.insertAfter("pass2", u, "text after u");}
/// System.out.println(rewriter.getText("pass1"));
/// System.out.println(rewriter.getText("pass2"));
///
///
///
/// If you don't use named rewrite streams, a "default" stream is used as the
/// first example shows.
///
import Foundation
public class TokenStreamRewriter {
    public let DEFAULT_PROGRAM_NAME = "default"
    public static let PROGRAM_INIT_SIZE = 100
    public static let MIN_TOKEN_INDEX = 0
    // Define the rewrite operation hierarchy
    public class RewriteOperation: CustomStringConvertible {
        /// What index into rewrites List are we?
        internal var instructionIndex = 0
        /// Token buffer index.
        internal var index: Int
        internal var text: String?
        internal var lastIndex = 0
        internal weak var tokens: TokenStream!
        init(_ index: Int, _ tokens: TokenStream) {
            self.index = index
            self.tokens = tokens
        }
        init(_ index: Int, _ text: String?, _ tokens: TokenStream) {
            self.index = index
            self.text = text
            self.tokens = tokens
        }
        /// Execute the rewrite operation by possibly adding to the buffer.
        /// Return the index of the next token to operate on.
        ///
        public func execute(_ buf: inout String) throws -> Int {
            return index
        }
        public var description: String {
            let opName = String(describing: type(of: self))
        }
    }
    public class InsertBeforeOp: RewriteOperation {
        override public func execute(_ buf: inout String) throws -> Int {
            if let text = text {
                buf.append(text)
            }
            let token = try tokens.get(index)
            if token.getType() != CommonToken.EOF {
                buf.append(token.getText()!)
            }
            return index + 1
        }
    }
    public class InsertAfterOp: InsertBeforeOp {
        public override init(_ index: Int, _ text: String?, _ tokens: TokenStream) {
            super.init(index + 1, text, tokens)
        }
    }
    /// I'm going to try replacing range from x..y with (y-x)+1 ReplaceOp
    /// instructions.
    ///
    public class ReplaceOp: RewriteOperation {
        public init(_ from: Int, _ to: Int, _ text: String?, _ tokens: TokenStream) {
            super.init(from, text, tokens)
            lastIndex = to
        }
        override
        public func execute(_ buf: inout String) -> Int {
            if let text = text {
                buf += text
            }
            return lastIndex + 1
        }
        override
        public var description: String {
            let token = try! tokens.get(index)
            let lastToken = try! tokens.get(lastIndex)
            if let text = text {
        }
    }
    public class RewriteOperationArray{
        private final var rewrites = [RewriteOperation?]()
        public init() {
            rewrites.reserveCapacity(TokenStreamRewriter.PROGRAM_INIT_SIZE)
        }
        final func append(_ op: RewriteOperation) {
            op.instructionIndex = rewrites.count
            rewrites.append(op)
        }
        final func rollback(_ instructionIndex: Int) {
            rewrites = Array(rewrites[TokenStreamRewriter.MIN_TOKEN_INDEX ..< instructionIndex])
        }
        final var count: Int {
            return rewrites.count
        }
        final var isEmpty: Bool {
            return rewrites.isEmpty
        }
        /// We need to combine operations and report invalid operations (like
        /// overlapping replaces that are not completed nested). Inserts to
        /// same index need to be combined etc...  Here are the cases:
        ///
        /// I.i.u I.j.v                             leave alone, nonoverlapping
        /// I.i.u I.i.v                             combine: Iivu
        ///
        /// R.i-j.u R.x-y.v | i-j in x-y            delete first R
        /// R.i-j.u R.i-j.v                         delete first R
        /// R.i-j.u R.x-y.v | x-y in i-j            ERROR
        /// R.i-j.u R.x-y.v | boundaries overlap    ERROR
        ///
        /// Delete special case of replace (text==null):
        /// D.i-j.u D.x-y.v | boundaries overlap    combine to max(min)..max(right)
        ///
        /// I.i.u R.x-y.v | i in (x+1)-y            delete I (since insert before
        /// we're not deleting i)
        /// I.i.u R.x-y.v | i not in (x+1)-y        leave alone, nonoverlapping
        /// R.x-y.v I.i.u | i in x-y                ERROR
        /// R.x-y.v I.x.u                           R.x-y.uv (combine, delete I)
        /// R.x-y.v I.i.u | i not in x-y            leave alone, nonoverlapping
        ///
        /// R.x-y.u = replace x-y indexed tokens with u
        ///
        /// First we need to examine replaces. For any replace op:
        ///
        /// 1. wipe out any insertions before op within that range.
        /// 2. Drop any replace op before that is contained completely within
        /// that range.
        /// 3. Throw exception upon boundary overlap with any previous replace.
        ///
        /// Then we can deal with inserts:
        ///
        /// 1. for any inserts to same index, combine even if not adjacent.
        /// 2. for any prior replace with same left boundary, combine this
        /// insert with replace and delete this replace.
        /// 3. throw exception if index in same range as previous replace
        ///
        /// Don't actually delete; make op null in list. Easier to walk list.
        /// Later we can throw as we add to index → op map.
        ///
        /// Note that I.2 R.2-2 will wipe out I.2 even though, technically, the
        /// inserted stuff would be before the replace range. But, if you
        /// add tokens in front of a method body '{' and then delete the method
        /// body, I think the stuff before the '{' you added should disappear too.
        ///
        /// Return a map from token index to operation.
        ///
        final func reduceToSingleOperationPerIndex() throws -> [Int: RewriteOperation] {
            let rewritesCount = rewrites.count
            // WALK REPLACES
            for i in 0..<rewritesCount {
                guard let rop = rewrites[i] as? ReplaceOp else {
                    continue
                }
                // Wipe prior inserts within range
                let inserts = getKindOfOps(&rewrites, InsertBeforeOp.self, i)
                for j in inserts {
                    if let iop = rewrites[j] {
                        if iop.index == rop.index {
                            // E.g., insert before 2, delete 2..2; update replace
                            // text to include insert before, kill insert
                            rewrites[iop.instructionIndex] = nil
                            rop.text = catOpText(iop.text, rop.text)
                        }
                        else if iop.index > rop.index && iop.index <= rop.lastIndex {
                            // delete insert as it's a no-op.
                            rewrites[iop.instructionIndex] = nil
                        }
                    }
                }
                // Drop any prior replaces contained within
                let prevRopIndexList = getKindOfOps(&rewrites, ReplaceOp.self, i)
                for j in prevRopIndexList {
                    if let prevRop = rewrites[j] {
                        if prevRop.index >= rop.index && prevRop.lastIndex <= rop.lastIndex {
                            // delete replace as it's a no-op.
                            rewrites[prevRop.instructionIndex] = nil
                            continue
                        }
                        // throw exception unless disjoint or identical
                        let disjoint: Bool =
                            prevRop.lastIndex < rop.index || prevRop.index > rop.lastIndex
                        // Delete special case of replace (text==null):
                        // D.i-j.u D.x-y.v  | boundaries overlap    combine to max(min)..max(right)
                        if prevRop.text == nil && rop.text == nil && !disjoint {
                            rewrites[prevRop.instructionIndex] = nil // kill first delete
                            rop.index = min(prevRop.index, rop.index)
                            rop.lastIndex = max(prevRop.lastIndex, rop.lastIndex)
                        } else if !disjoint {
                            throw ANTLRError.illegalArgument(msg: "replace op boundaries of \(rop.description) " +
                                "overlap with previous \(prevRop.description)")
                        }
                    }
                }
            }
            // WALK INSERTS
            for i in 0..<rewritesCount {
                guard let iop = rewrites[i] else {
                    continue
                }
                if !(iop is InsertBeforeOp) {
                    continue
                }
                // combine current insert with prior if any at same index
                let prevIopIndexList = getKindOfOps(&rewrites, InsertBeforeOp.self, i)
                for j in prevIopIndexList {
                    if let prevIop = rewrites[j] {
                        if prevIop.index == iop.index {
                            if prevIop is InsertAfterOp {
                                iop.text = catOpText(prevIop.text, iop.text)
                                rewrites[prevIop.instructionIndex] = nil
                            }
                            else if prevIop is InsertBeforeOp {
                                // convert to strings...we're in process of toString'ing
                                // whole token buffer so no lazy eval issue with any templates
                                iop.text = catOpText(iop.text, prevIop.text)
                                // delete redundant prior insert
                                rewrites[prevIop.instructionIndex] = nil
                            }
                        }
                    }
                }
                // look for replaces where iop.index is in range; error
                let ropIndexList = getKindOfOps(&rewrites, ReplaceOp.self, i)
                for j in ropIndexList  {
                    if let rop = rewrites[j] {
                        if iop.index == rop.index {
                            rop.text = catOpText(iop.text, rop.text)
                            rewrites[i] = nil    // delete current insert
                            continue
                        }
                        if iop.index >= rop.index && iop.index <= rop.lastIndex {
                            throw ANTLRError.illegalArgument(msg: "insert op \(iop.description) within" +
                                " boundaries of previous \(rop.description)")
                        }
                    }
                }
            }
            var m = [Int: RewriteOperation]()
            for i in 0..<rewritesCount {
                if let op = rewrites[i] {
                    if m[op.index] != nil {
                        throw ANTLRError.illegalArgument(msg: "should only be one op per index")
                    }
                    m[op.index] = op
                }
            }
            return m
        }
        final func catOpText(_ a: String?, _ b: String?) -> String {
            let x = a ?? ""
            let y = b ?? ""
            return x + y
        }
        /// Get all operations before an index of a particular kind
        final func getKindOfOps<T: RewriteOperation>(_ rewrites: inout [RewriteOperation?], _ kind: T.Type, _ before: Int ) -> [Int] {
            let length = min(before, rewrites.count)
            var op = [Int]()
            op.reserveCapacity(length)
            for i in 0..<length {
                if rewrites[i] is T {
                    op.append(i)
                }
            }
            return op
        }
    }
    /// Our source stream
    internal var tokens: TokenStream
    /// You may have multiple, named streams of rewrite operations.
    /// I'm calling these things "programs."
    /// Maps String (name) → rewrite (List)
    ///
    internal var programs = [String: RewriteOperationArray]()
    /// Map String (program name) → Integer index
    internal final var lastRewriteTokenIndexes: [String: Int]
    public init(_ tokens: TokenStream) {
        self.tokens = tokens
        programs[DEFAULT_PROGRAM_NAME] = RewriteOperationArray()
        lastRewriteTokenIndexes = Dictionary<String, Int>()
    }
    public final func getTokenStream() -> TokenStream {
        return tokens
    }
    public func rollback(_ instructionIndex: Int) {
        rollback(DEFAULT_PROGRAM_NAME, instructionIndex)
    }
    /// Rollback the instruction stream for a program so that
    /// the indicated instruction (via instructionIndex) is no
    /// longer in the stream. UNTESTED!
    ///
    public func rollback(_ programName: String, _ instructionIndex: Int) {
        if let program = programs[programName] {
            program.rollback(instructionIndex)
        }
    }
    public func deleteProgram() {
        deleteProgram(DEFAULT_PROGRAM_NAME)
    }
    /// Reset the program so that no instructions exist
    public func deleteProgram(_ programName: String) {
        rollback(programName, TokenStreamRewriter.MIN_TOKEN_INDEX)
    }
    public func insertAfter(_ t: Token, _ text: String) {
        insertAfter(DEFAULT_PROGRAM_NAME, t, text)
    }
    public func insertAfter(_ index: Int, _ text: String) {
        insertAfter(DEFAULT_PROGRAM_NAME, index, text)
    }
    public func insertAfter(_ programName: String, _ t: Token, _ text: String) {
        insertAfter(programName, t.getTokenIndex(), text)
    }
    public func insertAfter(_ programName: String, _ index: Int, _ text: String) {
        // to insert after, just insert before next index (even if past end)
        let op = InsertAfterOp(index, text, tokens)
        let rewrites = getProgram(programName)
        rewrites.append(op)
    }
    public func insertBefore(_ t: Token, _ text: String) {
        insertBefore(DEFAULT_PROGRAM_NAME, t, text)
    }
    public func insertBefore(_ index: Int, _ text: String) {
        insertBefore(DEFAULT_PROGRAM_NAME, index, text)
    }
    public func insertBefore(_ programName: String, _ t: Token, _ text: String) {
        insertBefore(programName, t.getTokenIndex(), text)
    }
    public func insertBefore(_ programName: String, _ index: Int, _ text: String) {
        let op = InsertBeforeOp(index, text, tokens)
        let rewrites = getProgram(programName)
        rewrites.append(op)
    }
    public func replace(_ index: Int, _ text: String) throws {
        try replace(DEFAULT_PROGRAM_NAME, index, index, text)
    }
    public func replace(_ from: Int, _ to: Int, _ text: String) throws {
        try replace(DEFAULT_PROGRAM_NAME, from, to, text)
    }
    public func replace(_ indexT: Token, _ text: String) throws {
        try replace(DEFAULT_PROGRAM_NAME, indexT, indexT, text)
    }
    public func replace(_ from: Token, _ to: Token, _ text: String) throws {
        try  replace(DEFAULT_PROGRAM_NAME, from, to, text)
    }
    public func replace(_ programName: String, _ from: Int, _ to: Int, _ text: String?) throws {
        if from > to || from < 0 || to < 0 || to >= tokens.size() {
            throw ANTLRError.illegalArgument(msg: "replace: range invalid: \(from)..\(to)(size=\(tokens.size()))")
        }
        let op = ReplaceOp(from, to, text, tokens)
        let rewritesArray = getProgram(programName)
        rewritesArray.append(op)
    }
    public func replace(_ programName: String, _ from: Token, _ to: Token, _ text: String?) throws {
        try replace(programName,
            from.getTokenIndex(),
            to.getTokenIndex(),
            text)
    }
    public func delete(_ index: Int) throws {
        try delete(DEFAULT_PROGRAM_NAME, index, index)
    }
    public func delete(_ from: Int, _ to: Int) throws {
        try delete(DEFAULT_PROGRAM_NAME, from, to)
    }
    public func delete(_ indexT: Token) throws {
        try delete(DEFAULT_PROGRAM_NAME, indexT, indexT)
    }
    public func delete(_ from: Token, _ to: Token) throws {
        try delete(DEFAULT_PROGRAM_NAME, from, to)
    }
    public func delete(_ programName: String, _ from: Int, _ to: Int) throws {
        try replace(programName, from, to, nil)
    }
    public func delete(_ programName: String, _ from: Token, _ to: Token) throws {
        try replace(programName, from, to, nil)
    }
    public func getLastRewriteTokenIndex() -> Int {
        return getLastRewriteTokenIndex(DEFAULT_PROGRAM_NAME)
    }
    internal func getLastRewriteTokenIndex(_ programName: String) -> Int {
        return lastRewriteTokenIndexes[programName] ?? -1
    }
    internal func setLastRewriteTokenIndex(_ programName: String, _ i: Int) {
        lastRewriteTokenIndexes[programName] = i
    }
    internal func getProgram(_ name: String) -> RewriteOperationArray {
        if let program = programs[name] {
            return program
        }
        else {
            return initializeProgram(name)
        }
    }
    private func initializeProgram(_ name: String) -> RewriteOperationArray {
        let program = RewriteOperationArray()
        programs[name] = program
        return program
    }
    /// Return the text from the original tokens altered per the
    /// instructions given to this rewriter.
    ///
    public func getText() throws -> String {
        return try getText(DEFAULT_PROGRAM_NAME, Interval.of(0, tokens.size() - 1))
    }
    /// Return the text from the original tokens altered per the
    /// instructions given to this rewriter in programName.
    ///
    public func getText(_ programName: String) throws -> String {
        return try getText(programName, Interval.of(0, tokens.size() - 1))
    }
    /// Return the text associated with the tokens in the interval from the
    /// original token stream but with the alterations given to this rewriter.
    /// The interval refers to the indexes in the original token stream.
    /// We do not alter the token stream in any way, so the indexes
    /// and intervals are still consistent. Includes any operations done
    /// to the first and last token in the interval. So, if you did an
    /// insertBefore on the first token, you would get that insertion.
    /// The same is true if you do an insertAfter the stop token.
    ///
    public func getText(_ interval: Interval) throws -> String {
        return try getText(DEFAULT_PROGRAM_NAME, interval)
    }
    public func getText(_ programName: String, _ interval: Interval) throws -> String {
        var start = interval.a
        var stop = interval.b
        // ensure start/end are in range
        if stop > tokens.size() - 1 {
            stop = tokens.size() - 1
        }
        if start < 0 {
            start = 0
        }
        guard let rewrites = programs[programName], !rewrites.isEmpty else {
             return try tokens.getText(interval) // no instructions to execute
        }
        var buf = ""
        // First, optimize instruction stream
        var indexToOp = try rewrites.reduceToSingleOperationPerIndex()
        // Walk buffer, executing instructions and emitting tokens
        var i = start
        while i <= stop && i < tokens.size() {
            let op = indexToOp[i]
            indexToOp.removeValue(forKey: i)  // remove so any left have index size-1
            let t = try tokens.get(i)
            if let op = op {
                i = try op.execute(&buf) // execute operation and skip
            }
            else {
                // no operation at that index, just dump token
                if t.getType() != CommonToken.EOF {
                    buf.append(t.getText()!)
                }
                i += 1 // move to next token
            }
        }
        // include stuff after end if it's last index in buffer
        // So, if they did an insertAfter(lastValidIndex, "foo"), include
        // foo if end==lastValidIndex.
        if stop == tokens.size() - 1 {
            // Scan any remaining operations after last token
            // should be included (they will be inserts).
            for op in indexToOp.values {
                if op.index >= tokens.size() - 1 {
                    buf += op.text!
                }
            }
        }
        return buf
    }
}


CharStream

///
///
///
/// A source of characters for an ANTLR lexer.
///
public protocol CharStream: IntStream {
    ///
    /// This method returns the text for a range of characters within this input
    /// stream. This method is guaranteed to not throw an exception if the
    /// specified `interval` lies entirely within a marked range. For more
    /// information about marked ranges, see _org.antlr.v4.runtime.IntStream#mark_.
    ///
    /// - parameter interval: an interval within the stream
    /// - returns: the text of the specified interval
    ///
    /// - throws: _ANTLRError.illegalArgument_ if `interval.a < 0`, or if
    /// `interval.b < interval.a - 1`, or if `interval.b` lies at or
    /// past the end of the stream
    /// - throws: _ANTLRError.unsupportedOperation_ if the stream does not support
    /// getting the text of the specified interval
    ///
    func getText(_ interval: Interval) throws -> String
}