Lexer

///
///
///
/// A lexer is recognizer that draws input symbols from a character stream.
/// lexer grammars result in a subclass of this object. A Lexer object
/// uses simplified match() and error recovery mechanisms in the interest
/// of speed.
///
import Foundation
open class Lexer: Recognizer<LexerATNSimulator>, TokenSource {
    public static let EOF = -1
    public static let DEFAULT_MODE = 0
    public static let MORE = -2
    public static let SKIP = -3
    public static let DEFAULT_TOKEN_CHANNEL = CommonToken.DEFAULT_CHANNEL
    public static let HIDDEN = CommonToken.HIDDEN_CHANNEL
    public static let MIN_CHAR_VALUE = Character.MIN_VALUE;
    public static let MAX_CHAR_VALUE = Character.MAX_VALUE;
    public var _input: CharStream?
    internal var _tokenFactorySourcePair: TokenSourceAndStream
    ///
    /// How to create token objects
    ///
    internal var _factory = CommonTokenFactory.DEFAULT
    ///
    /// The goal of all lexer rules/methods is to create a token object.
    /// This is an instance variable as multiple rules may collaborate to
    /// create a single token.  nextToken will return this object after
    /// matching lexer rule(s).  If you subclass to allow multiple token
    /// emissions, then set this to the last token to be matched or
    /// something nonnull so that the auto token emit mechanism will not
    /// emit another token.
    ///
    public var _token: Token?
    ///
    /// What character index in the stream did the current token start at?
    /// Needed, for example, to get the text for current token.  Set at
    /// the start of nextToken.
    ///
    public var _tokenStartCharIndex = -1
    ///
    /// The line on which the first character of the token resides
    ///
    public var _tokenStartLine = 0
    ///
    /// The character position of first character within the line
    ///
    public var _tokenStartCharPositionInLine = 0
    ///
    /// Once we see EOF on char stream, next token will be EOF.
    /// If you have DONE : EOF ; then you see DONE EOF.
    ///
    public var _hitEOF = false
    ///
    /// The channel number for the current token
    ///
    public var _channel = 0
    ///
    /// The token type for the current token
    ///
    public var _type = CommonToken.INVALID_TYPE
    public final var _modeStack = Stack<Int>()
    public var _mode = Lexer.DEFAULT_MODE
    ///
    /// You can set the text for the current token to override what is in
    /// the input char buffer.  Use setText() or can set this instance var.
    ///
    public var _text: String?
    public override init() {
        self._tokenFactorySourcePair = TokenSourceAndStream()
        super.init()
        self._tokenFactorySourcePair.tokenSource = self
    }
    public required init(_ input: CharStream) {
        self._input = input
        self._tokenFactorySourcePair = TokenSourceAndStream()
        super.init()
        self._tokenFactorySourcePair.tokenSource = self
        self._tokenFactorySourcePair.stream = input
    }
    open func reset() throws {
        // wack Lexer state variables
        if let _input = _input {
            try  _input.seek(0) // rewind the input
        }
        _token = nil
        _type = CommonToken.INVALID_TYPE
        _channel = CommonToken.DEFAULT_CHANNEL
        _tokenStartCharIndex = -1
        _tokenStartCharPositionInLine = -1
        _tokenStartLine = -1
        _text = nil
        _hitEOF = false
        _mode = Lexer.DEFAULT_MODE
        _modeStack.clear()
        getInterpreter().reset()
    }
    ///
    /// Return a token from this source; i.e., match a token on the char
    /// stream.
    ///
    open func nextToken() throws -> Token {
        guard let _input = _input else {
            throw ANTLRError.illegalState(msg: "nextToken requires a non-null input stream.")
        }
        // Mark start location in char stream so unbuffered streams are
        // guaranteed at least have text of current token
        let tokenStartMarker = _input.mark()
        defer {
            // make sure we release marker after match or
            // unbuffered char stream will keep buffering
            try! _input.release(tokenStartMarker)
        }
        do {
            outer:
            while true {
                if _hitEOF {
                    emitEOF()
                    return _token!
                }
                _token = nil
                _channel = CommonToken.DEFAULT_CHANNEL
                _tokenStartCharIndex = _input.index()
                _tokenStartCharPositionInLine = getInterpreter().getCharPositionInLine()
                _tokenStartLine = getInterpreter().getLine()
                _text = nil
                repeat {
                    _type = CommonToken.INVALID_TYPE
                    var ttype: Int
                    do {
                        ttype = try getInterpreter().match(_input, _mode)
                    }
                    catch  ANTLRException.recognition(let e) {
                        notifyListeners(e as! LexerNoViableAltException, recognizer: self)
                        try recover(e as! LexerNoViableAltException)
                        ttype = Lexer.SKIP
                    }
                    if try _input.LA(1) == BufferedTokenStream.EOF {
                        _hitEOF = true
                    }
                    if _type == CommonToken.INVALID_TYPE {
                        _type = ttype
                    }
                    if _type == Lexer.SKIP {
                        continue outer
                    }
                } while _type == Lexer.MORE
                if _token == nil {
                    emit()
                }
                return _token!
            }
        }
    }
    ///
    /// Instruct the lexer to skip creating a token for current lexer rule
    /// and look for another token.  nextToken() knows to keep looking when
    /// a lexer rule finishes with token set to SKIP_TOKEN.  Recall that
    /// if token==null at end of any token rule, it creates one for you
    /// and emits it.
    ///
    open func skip() {
        _type = Lexer.SKIP
    }
    open func more() {
        _type = Lexer.MORE
    }
    open func mode(_ m: Int) {
        _mode = m
    }
    open func pushMode(_ m: Int) {
        if LexerATNSimulator.debug {
            print("pushMode \(m)")
        }
        _modeStack.push(_mode)
        mode(m)
    }
    open func popMode() throws -> Int {
        if _modeStack.isEmpty {
            throw ANTLRError.unsupportedOperation(msg: " EmptyStackException")
        }
        if LexerATNSimulator.debug {
            print("popMode back to \(String(describing: _modeStack.peek()))")
        }
        mode(_modeStack.pop())
        return _mode
    }
    open override func setTokenFactory(_ factory: TokenFactory) {
        self._factory = factory
    }
    open override func getTokenFactory() -> TokenFactory {
        return _factory
    }
    ///
    /// Set the char stream and reset the lexer
    ///
    open override func setInputStream(_ input: IntStream) throws {
        self._input = nil
        self._tokenFactorySourcePair = makeTokenSourceAndStream()
        try reset()
        self._input = input as? CharStream
        self._tokenFactorySourcePair = makeTokenSourceAndStream()
    }
    open func getSourceName() -> String {
        return _input!.getSourceName()
    }
    open func getInputStream() -> CharStream? {
        return _input
    }
    ///
    /// By default does not support multiple emits per nextToken invocation
    /// for efficiency reasons.  Subclass and override this method, nextToken,
    /// and getToken (to push tokens into a list and pull from that list
    /// rather than a single variable as this implementation does).
    ///
    open func emit(_ token: Token) {
        //System.err.println("emit "+token);
        self._token = token
    }
    ///
    /// The standard method called to automatically emit a token at the
    /// outermost lexical rule.  The token object should point into the
    /// char buffer start..stop.  If there is a text override in 'text',
    /// use that to set the token's text.  Override this method to emit
    /// custom Token objects or provide a new factory.
    ///
    open func emitEOF() -> Token {
        let cpos = getCharPositionInLine()
        let line = getLine()
        let idx = _input!.index()
        let eof = _factory.create(
            _tokenFactorySourcePair,
            CommonToken.EOF,
            nil,
            CommonToken.DEFAULT_CHANNEL,
            idx,
            idx - 1,
            line,
            cpos)
        emit(eof)
        return eof
    }
    open func getLine() -> Int {
        return getInterpreter().getLine()
    }
    open func getCharPositionInLine() -> Int {
        return getInterpreter().getCharPositionInLine()
    }
    open func setLine(_ line: Int) {
        getInterpreter().setLine(line)
    }
    open func setCharPositionInLine(_ charPositionInLine: Int) {
        getInterpreter().setCharPositionInLine(charPositionInLine)
    }
    ///
    /// What is the index of the current character of lookahead?
    ///
    open func getCharIndex() -> Int {
        return _input!.index()
    }
    ///
    /// Return the text matched so far for the current token or any
    /// text override.
    ///
    open func getText() -> String {
        if _text != nil {
            return _text!
        }
        return getInterpreter().getText(_input!)
    }
    ///
    /// Set the complete text of this token; it wipes any previous
    /// changes to the text.
    ///
    open func setText(_ text: String) {
        self._text = text
    }
    ///
    /// Override if emitting multiple tokens.
    ///
    open func getToken() -> Token {
        return _token!
    }
    open func setToken(_ _token: Token) {
        self._token = _token
    }
    open func setType(_ ttype: Int) {
        _type = ttype
    }
    open func getType() -> Int {
        return _type
    }
    open func setChannel(_ channel: Int) {
        _channel = channel
    }
    open func getChannel() -> Int {
        return _channel
    }
    open func getChannelNames() -> [String]? {
        return nil
    }
    open func getModeNames() -> [String]? {
        return nil
    }
    ///
    /// Return a list of all Token objects in input char stream.
    /// Forces load of all tokens. Does not include EOF token.
    ///
    open func getAllTokens() throws -> [Token] {
        var tokens = [Token]()
        var t = try nextToken()
        while t.getType() != CommonToken.EOF {
            tokens.append(t)
            t = try nextToken()
        }
        return tokens
    }
    open func recover(_ e: LexerNoViableAltException) throws {
        if try _input!.LA(1) != BufferedTokenStream.EOF {
            // skip a char and try again
            try getInterpreter().consume(_input!)
        }
    }
    open func notifyListeners<T>(_ e: LexerNoViableAltException, recognizer: Recognizer<T>) {
        let text: String
        do {
            text = try _input!.getText(Interval.of(_tokenStartCharIndex, _input!.index()))
        }
        catch {
            text = "<unknown>"
        }
        let msg = "token recognition error at: '\(getErrorDisplay(text))'"
        let listener = getErrorListenerDispatch()
        listener.syntaxError(recognizer, nil, _tokenStartLine, _tokenStartCharPositionInLine, msg, e)
    }
    open func getErrorDisplay(_ s: String) -> String {
        var buf = ""
        for c in s {
        }
        return buf
    }
    open func getErrorDisplay(_ c: Character) -> String {
        if c.integerValue == CommonToken.EOF {
            return "<EOF>"
        }
        switch c {
        case "\n":
            return "\\n"
        case "\t":
            return "\\t"
        case "\r":
            return "\\r"
        default:
        return "'\(s)'"
    }
    ///
    /// Lexers can normally match any char in it's vocabulary after matching
    /// a token, so do the easy thing and just kill a character and hope
    /// it all works out.  You can instead use the rule invocation stack
    /// to do sophisticated error recovery if you are in a fragment rule.
    ///
    open func recover(_ re: AnyObject) throws {
        // TODO: Do we lose character or line position information?
        try _input!.consume()
    }
    internal func makeTokenSourceAndStream() -> TokenSourceAndStream {
        return TokenSourceAndStream(self, _input)
    }
}


DiagnosticErrorListener

///
///
///
/// This implementation of _org.antlr.v4.runtime.ANTLRErrorListener_ can be used to identify
/// certain potential correctness and performance problems in grammars. "Reports"
/// are made by calling _org.antlr.v4.runtime.Parser#notifyErrorListeners_ with the appropriate
/// message.
///
/// * __Ambiguities__: These are cases where more than one path through the
/// grammar can match the input.
/// * __Weak context sensitivity__: These are cases where full-context
/// prediction resolved an SLL conflict to a unique alternative which equaled the
/// minimum alternative of the SLL conflict.
/// * __Strong (forced) context sensitivity__: These are cases where the
/// full-context prediction resolved an SLL conflict to a unique alternative,
/// __and__ the minimum alternative of the SLL conflict was found to not be
/// a truly viable alternative. Two-stage parsing cannot be used for inputs where
/// this situation occurs.
///
/// -  Sam Harwell
///
import Foundation
public class DiagnosticErrorListener: BaseErrorListener {
    ///
    /// When `true`, only exactly known ambiguities are reported.
    ///
    internal final var exactOnly: Bool
    ///
    /// Initializes a new instance of _org.antlr.v4.runtime.DiagnosticErrorListener_ which only
    /// reports exact ambiguities.
    ///
    public convenience override init() {
        self.init(true)
    }
    ///
    /// Initializes a new instance of _org.antlr.v4.runtime.DiagnosticErrorListener_, specifying
    /// whether all ambiguities or only exact ambiguities are reported.
    ///
    /// - parameter exactOnly: `true` to report only exact ambiguities, otherwise
    /// `false` to report all ambiguities.
    ///
    public init(_ exactOnly: Bool) {
        self.exactOnly = exactOnly
    }
    override
    public func reportAmbiguity(_ recognizer: Parser,
        _ dfa: DFA,
        _ startIndex: Int,
        _ stopIndex: Int,
        _ exact: Bool,
        _ ambigAlts: BitSet,
        _ configs: ATNConfigSet) {
            if exactOnly && !exact {
                return
            }
            let decision = getDecisionDescription(recognizer, dfa)
            let conflictingAlts = getConflictingAlts(ambigAlts, configs)
            let text = getTextInInterval(recognizer, startIndex, stopIndex)
            let message = "reportAmbiguity d=\(decision): ambigAlts=\(conflictingAlts), input='\(text)'"
            recognizer.notifyErrorListeners(message)
    }
    override
    public func reportAttemptingFullContext(_ recognizer: Parser,
        _ dfa: DFA,
        _ startIndex: Int,
        _ stopIndex: Int,
        _ conflictingAlts: BitSet?,
        _ configs: ATNConfigSet) {
            let decision = getDecisionDescription(recognizer, dfa)
            let text = getTextInInterval(recognizer, startIndex, stopIndex)
            let message = "reportAttemptingFullContext d=\(decision), input='\(text)'"
            recognizer.notifyErrorListeners(message)
    }
    override
    public func reportContextSensitivity(_ recognizer: Parser,
        _ dfa: DFA,
        _ startIndex: Int,
        _ stopIndex: Int,
        _ prediction: Int,
        _ configs: ATNConfigSet) {
            let decision = getDecisionDescription(recognizer, dfa)
            let text = getTextInInterval(recognizer, startIndex, stopIndex)
            let message = "reportContextSensitivity d=\(decision), input='\(text)'"
            recognizer.notifyErrorListeners(message)
    }
    internal func getDecisionDescription(_ recognizer: Parser, _ dfa: DFA) -> String {
        let decision: Int = dfa.decision
        let ruleIndex: Int = dfa.atnStartState.ruleIndex!
        let ruleNames: [String] = recognizer.getRuleNames()
        guard ruleNames.indices.contains(ruleIndex) else {
            return String(decision)
        }
        let ruleName: String = ruleNames[ruleIndex]
        //if (ruleName == nil || ruleName.isEmpty()) {
        if ruleName.isEmpty {
            return String(decision)
        }
        return "\(decision) (\(ruleName))"
    }
    ///
    /// Computes the set of conflicting or ambiguous alternatives from a
    /// configuration set, if that information was not already provided by the
    /// parser.
    ///
    /// - parameter reportedAlts: The set of conflicting or ambiguous alternatives, as
    /// reported by the parser.
    /// - parameter configs: The conflicting or ambiguous configuration set.
    /// - returns: Returns `reportedAlts` if it is not `null`, otherwise
    /// returns the set of alternatives represented in `configs`.
    ///
    internal func getConflictingAlts(_ reportedAlts: BitSet?, _ configs: ATNConfigSet) -> BitSet {
        return reportedAlts ?? configs.getAltBitSet()
    }
}
fileprivate func getTextInInterval(_ recognizer: Parser, _ startIndex: Int, _ stopIndex: Int) -> String {
    do {
        return try recognizer.getTokenStream()?.getText(Interval.of(startIndex, stopIndex)) ?? "<unknown>"
    }
    catch {
        return "<unknown>"
    }
}


RecognitionException

 */
/// The root of the ANTLR exception hierarchy. In general, ANTLR tracks just
/// 3 kinds of errors: prediction errors, failed predicate errors, and
/// mismatched input errors. In each case, the parser knows where it is
/// in the input, where it is in the ATN, the rule invocation stack,
/// and what kind of problem occurred.
///
public class RecognitionException {
    ///
    /// The _org.antlr.v4.runtime.Recognizer_ where this exception originated.
    ///
    private final var recognizer: RecognizerProtocol?
    private final weak var ctx: RuleContext?
    private final var input: IntStream?
    ///
    /// The current _org.antlr.v4.runtime.Token_ when an error occurred. Since not all streams
    /// support accessing symbols by index, we have to track the _org.antlr.v4.runtime.Token_
    /// instance itself.
    ///
    private var offendingToken: Token!
    private var offendingState = ATNState.INVALID_STATE_NUMBER
    public var message: String?
    public init(_ recognizer: RecognizerProtocol?,
                _ input: IntStream,
                _ ctx: ParserRuleContext? = nil,
                _ message: String? = nil) {
        self.recognizer = recognizer
        self.input = input
        self.ctx = ctx
        self.message = message
        if let recognizer = recognizer {
            self.offendingState = recognizer.getState()
        }
    }
    ///
    /// Get the ATN state number the parser was in at the time the error
    /// occurred. For _org.antlr.v4.runtime.NoViableAltException_ and
    /// _org.antlr.v4.runtime.LexerNoViableAltException_ exceptions, this is the
    /// _org.antlr.v4.runtime.atn.DecisionState_ number. For others, it is the state whose outgoing
    /// edge we couldn't match.
    ///
    /// If the state number is not known, this method returns -1.
    ///
    public func getOffendingState() -> Int {
        return offendingState
    }
    internal final func setOffendingState(_ offendingState: Int) {
        self.offendingState = offendingState
    }
    ///
    /// Gets the set of input symbols which could potentially follow the
    /// previously matched symbol at the time this exception was thrown.
    ///
    /// If the set of expected tokens is not known and could not be computed,
    /// this method returns `null`.
    ///
    /// - Returns: The set of token types that could potentially follow the current
    /// state in the ATN, or `null` if the information is not available.
    ///
    public func getExpectedTokens() -> IntervalSet? {
        if let recognizer = recognizer {
            return try? recognizer.getATN().getExpectedTokens(offendingState, ctx!)
        }
        return nil
    }
    ///
    /// Gets the _org.antlr.v4.runtime.RuleContext_ at the time this exception was thrown.
    ///
    /// If the context is not available, this method returns `null`.
    ///
    /// - Returns: The _org.antlr.v4.runtime.RuleContext_ at the time this exception was thrown.
    /// If the context is not available, this method returns `null`.
    ///
    public func getCtx() -> RuleContext? {
        return ctx
    }
    ///
    /// Gets the input stream which is the symbol source for the recognizer where
    /// this exception was thrown.
    ///
    /// If the input stream is not available, this method returns `null`.
    ///
    /// - Returns: The input stream which is the symbol source for the recognizer
    /// where this exception was thrown, or `null` if the stream is not
    /// available.
    ///
    public func getInputStream() -> IntStream? {
        return input
    }
    public func clearInputStream() {
        input = nil
    }
    public func getOffendingToken() -> Token {
        return offendingToken
    }
    internal final func setOffendingToken(_ offendingToken: Token) {
        self.offendingToken = offendingToken
    }
    ///
    /// Gets the _org.antlr.v4.runtime.Recognizer_ where this exception occurred.
    ///
    /// If the recognizer is not available, this method returns `null`.
    ///
    /// - Returns: The recognizer where this exception occurred, or `null` if
    /// the recognizer is not available.
    ///
    public func getRecognizer() -> RecognizerProtocol? {
        return recognizer
    }
    public func clearRecognizer() {
        self.recognizer = nil
    }
}


FailedPredicateException

///
///
///
/// A semantic predicate failed during validation.  Validation of predicates
/// occurs when normally parsing the alternative just like matching a token.
/// Disambiguating predicate evaluation occurs when we test a predicate during
/// prediction.
///
public class FailedPredicateException: RecognitionException {
	private let ruleIndex: Int
	private let predicateIndex: Int
	private let predicate: String?
	public init(_ recognizer: Parser, _ predicate: String? = nil, _ message: String? = nil) {
		let s = recognizer.getInterpreter().atn.states[recognizer.getState()]!
		let trans = s.transition(0) as! AbstractPredicateTransition
		if let predex = trans as? PredicateTransition {
			self.ruleIndex = predex.ruleIndex
			self.predicateIndex = predex.predIndex
		}
		else {
			self.ruleIndex = 0
			self.predicateIndex = 0
		}
		self.predicate = predicate
        super.init(recognizer, recognizer.getInputStream()!, recognizer._ctx, FailedPredicateException.formatMessage(predicate, message))
        if let token = try? recognizer.getCurrentToken() {
            setOffendingToken(token)
        }
	}
	public func getRuleIndex() -> Int {
		return ruleIndex
	}
	public func getPredIndex() -> Int {
		return predicateIndex
	}
	public func getPredicate() -> String? {
		return predicate
	}
	private static func formatMessage(_ predicate: String?, _ message: String?) -> String {
		if let message = message {
			return message
		}
        let predstr = predicate ?? "<unknown>"
		return "failed predicate: {\(predstr)}?"
	}
}


ListTokenSource

///
///
///
/// Provides an implementation of _org.antlr.v4.runtime.TokenSource_ as a wrapper around a list
/// of _org.antlr.v4.runtime.Token_ objects.
///
/// If the final token in the list is an _org.antlr.v4.runtime.Token#EOF_ token, it will be used
/// as the EOF token for every call to _#nextToken_ after the end of the
/// list is reached. Otherwise, an EOF token will be created.
///
public class ListTokenSource: TokenSource {
    ///
    /// The wrapped collection of _org.antlr.v4.runtime.Token_ objects to return.
    ///
    internal let tokens: [Token]
    ///
    /// The name of the input source. If this value is `null`, a call to
    /// _#getSourceName_ should return the source name used to create the
    /// the next token in _#tokens_ (or the previous token if the end of
    /// the input has been reached).
    ///
    private let sourceName: String?
    ///
    /// The index into _#tokens_ of token to return by the next call to
    /// _#nextToken_. The end of the input is indicated by this value
    /// being greater than or equal to the number of items in _#tokens_.
    ///
    internal var i = 0
    ///
    /// This field caches the EOF token for the token source.
    ///
    internal var eofToken: Token?
    ///
    /// This is the backing field for _#getTokenFactory_ and
    /// _setTokenFactory_.
    ///
    private var _factory = CommonTokenFactory.DEFAULT
    ///
    /// Constructs a new _org.antlr.v4.runtime.ListTokenSource_ instance from the specified
    /// collection of _org.antlr.v4.runtime.Token_ objects.
    ///
    /// - parameter tokens: The collection of _org.antlr.v4.runtime.Token_ objects to provide as a
    /// _org.antlr.v4.runtime.TokenSource_.
    ///
    public convenience init(_ tokens: [Token]) {
        self.init(tokens, nil)
    }
    ///
    /// Constructs a new _org.antlr.v4.runtime.ListTokenSource_ instance from the specified
    /// collection of _org.antlr.v4.runtime.Token_ objects and source name.
    ///
    /// - parameter tokens: The collection of _org.antlr.v4.runtime.Token_ objects to provide as a
    /// _org.antlr.v4.runtime.TokenSource_.
    /// - parameter sourceName: The name of the _org.antlr.v4.runtime.TokenSource_. If this value is
    /// `null`, _#getSourceName_ will attempt to infer the name from
    /// the next _org.antlr.v4.runtime.Token_ (or the previous token if the end of the input has
    /// been reached).
    ///
    public init(_ tokens: [Token], _ sourceName: String?) {
        self.tokens = tokens
        self.sourceName = sourceName
    }
    public func getCharPositionInLine() -> Int {
        if i < tokens.count {
            return tokens[i].getCharPositionInLine()
        }
        else if let eofToken = eofToken {
            return eofToken.getCharPositionInLine()
        }
        else if !tokens.isEmpty {
            // have to calculate the result from the line/column of the previous
            // token, along with the text of the token.
            let lastToken = tokens.last!
            if let tokenText = lastToken.getText() {
                if let lastNewLine = tokenText.lastIndex(of: "\n") {
                    return tokenText.distance(from: lastNewLine, to: tokenText.endIndex) - 1
                }
            }
            return (lastToken.getCharPositionInLine() +
                    lastToken.getStopIndex() -
                    lastToken.getStartIndex() + 1)
        }
        else {
            // only reach this if tokens is empty, meaning EOF occurs at the first
            // position in the input
            return 0
        }
    }
    public func nextToken() -> Token {
        if i >= tokens.count {
            if eofToken == nil {
                var start = -1
                if tokens.count > 0 {
                    let previousStop = tokens[tokens.count - 1].getStopIndex()
                    if previousStop != -1 {
                        start = previousStop + 1
                    }
                }
                let stop = max(-1, start - 1)
                let source = TokenSourceAndStream(self, getInputStream())
                eofToken = _factory.create(source, CommonToken.EOF, "EOF", CommonToken.DEFAULT_CHANNEL, start, stop, getLine(), getCharPositionInLine())
            }
            return eofToken!
        }
        let t = tokens[i]
        if i == tokens.count - 1 && t.getType() == CommonToken.EOF {
            eofToken = t
        }
        i += 1
        return t
    }
    public func getLine() -> Int {
        if i < tokens.count {
            return tokens[i].getLine()
        }
        else if let eofToken = eofToken {
            return eofToken.getLine()
        }
        else if !tokens.isEmpty {
            // have to calculate the result from the line/column of the previous
            // token, along with the text of the token.
            let lastToken = tokens.last!
            var line = lastToken.getLine()
            if let tokenText = lastToken.getText() {
                for c in tokenText {
                    if c == "\n" {
                        line += 1
                    }
                }
            }
            // if no text is available, assume the token did not contain any newline characters.
            return line
        }
        else {
            // only reach this if tokens is empty, meaning EOF occurs at the first
            // position in the input
            return 1
        }
    }
    public func getInputStream() -> CharStream? {
        if i < tokens.count {
            return tokens[i].getInputStream()
        }
        else if let eofToken = eofToken {
            return eofToken.getInputStream()
        }
        else if !tokens.isEmpty {
            return tokens.last!.getInputStream()
        }
        // no input stream information is available
        return nil
    }
    public func getSourceName() -> String {
        if let sourceName = sourceName {
            return sourceName
        }
        if let inputStream = getInputStream() {
            return inputStream.getSourceName()
        }
        return "List"
    }
    public func setTokenFactory(_ factory: TokenFactory) {
        self._factory = factory
    }
    public func getTokenFactory() -> TokenFactory {
        return _factory
    }
}


NoViableAltException

 */
/// Indicates that the parser could not decide which of two or more paths
/// to take based upon the remaining input. It tracks the starting token
/// of the offending input and also knows where the parser was
/// in the various paths when the error. Reported by reportNoViableAlternative()
///
public class NoViableAltException: RecognitionException {
    /// Which configurations did we try at input.index() that couldn't match input.LT(1)?
    private let deadEndConfigs: ATNConfigSet?
    /// The token object at the start index; the input stream might
    /// not be buffering tokens so get a reference to it. (At the
    /// time the error occurred, of course the stream needs to keep a
    /// buffer all of the tokens but later we might not have access to those.)
    ///
    private let startToken: Token
    public convenience init(_ recognizer: Parser) {
        // LL(1) error
        let token = try! recognizer.getCurrentToken()
        self.init(recognizer,
                recognizer.getInputStream()!,
                token,
                token,
                nil,
                recognizer._ctx)
    }
    public init(_ recognizer: Parser?,
                _ input: IntStream,
                _ startToken: Token,
                _ offendingToken: Token?,
                _ deadEndConfigs: ATNConfigSet?,
                _ ctx: ParserRuleContext?) {
        self.deadEndConfigs = deadEndConfigs
        self.startToken = startToken
        super.init(recognizer, input, ctx)
        if let offendingToken = offendingToken {
            setOffendingToken(offendingToken)
        }
    }
    public func getStartToken() -> Token {
        return startToken
    }
    public func getDeadEndConfigs() -> ATNConfigSet? {
        return deadEndConfigs
    }
}


LexerNoViableAltException

///
///
public class LexerNoViableAltException: RecognitionException, CustomStringConvertible {
    ///
    /// Matching attempted at what input index?
    ///
    private let startIndex: Int
    ///
    /// Which configurations did we try at input.index() that couldn't match input.LA(1)?
    ///
    private let deadEndConfigs: ATNConfigSet
    public init(_ lexer: Lexer?,
                _ input: CharStream,
                _ startIndex: Int,
                _ deadEndConfigs: ATNConfigSet) {
        let ctx: ParserRuleContext? = nil
        self.startIndex = startIndex
        self.deadEndConfigs = deadEndConfigs
        super.init(lexer, input as IntStream, ctx)
    }
    public func getStartIndex() -> Int {
        return startIndex
    }
    public func getDeadEndConfigs() -> ATNConfigSet {
        return deadEndConfigs
    }
    public var description: String {
        var symbol = ""
        if let charStream = getInputStream() as? CharStream, startIndex >= 0 && startIndex < charStream.size() {
            let interval = Interval.of(startIndex, startIndex)
            symbol = try! charStream.getText(interval)
            symbol = Utils.escapeWhitespace(symbol, false)
        }
        return "\(LexerNoViableAltException.self)('\(symbol)')"
    }
}


ParserInterpreter

 */
/// A parser simulator that mimics what ANTLR's generated
/// parser code does. A ParserATNSimulator is used to make
/// predictions via adaptivePredict but this class moves a pointer through the
/// ATN to simulate parsing. ParserATNSimulator just
/// makes us efficient rather than having to backtrack, for example.
///
/// This properly creates parse trees even for left recursive rules.
///
/// We rely on the left recursive rule invocation and special predicate
/// transitions to make left recursive rules work.
///
/// See TestParserInterpreter for examples.
///
public class ParserInterpreter: Parser {
    internal let grammarFileName: String
    internal let atn: ATN
    /// This identifies StarLoopEntryState's that begin the (...)*
    /// precedence loops of left recursive rules.
    ///
    internal let statesNeedingLeftRecursionContext: BitSet
    internal final var decisionToDFA: [DFA]
    // not shared like it is for generated parsers
    internal let sharedContextCache = PredictionContextCache()
    internal let ruleNames: [String]
    private let vocabulary: Vocabulary
    /// Tracks LR rules for adjusting the contexts
    internal final var _parentContextStack: Array<(ParserRuleContext?, Int)> =
    Array<(ParserRuleContext?, Int)>()
    /// We need a map from (decision,inputIndex)->forced alt for computing ambiguous
    /// parse trees. For now, we allow exactly one override.
    ///
    internal var overrideDecision: Int = -1
    internal var overrideDecisionInputIndex: Int = -1
    internal var overrideDecisionAlt: Int = -1
    /// A copy constructor that creates a new parser interpreter by reusing
    /// the fields of a previous interpreter.
    ///
    /// - Since: 4.5.1
    ///
    /// - Parameter old: The interpreter to copy
    ///
    public init(_ old: ParserInterpreter) throws {
        self.atn = old.atn
        self.grammarFileName = old.grammarFileName
        self.statesNeedingLeftRecursionContext = old.statesNeedingLeftRecursionContext
        self.decisionToDFA = old.decisionToDFA
        self.ruleNames = old.ruleNames
        self.vocabulary = old.vocabulary
        try  super.init(old.getTokenStream()!)
        setInterpreter(ParserATNSimulator(self, atn,
                decisionToDFA,
                sharedContextCache))
    }
    public init(_ grammarFileName: String, _ vocabulary: Vocabulary,
                _ ruleNames: Array<String>, _ atn: ATN, _ input: TokenStream) throws {
        self.grammarFileName = grammarFileName
        self.atn = atn
        self.ruleNames = ruleNames
        self.vocabulary = vocabulary
        self.decisionToDFA = [DFA]()
        for i in 0 ..< atn.getNumberOfDecisions() {
            decisionToDFA.append(DFA(atn.getDecisionState(i)!, i))
        }
        // identify the ATN states where pushNewRecursionContext() must be called
        self.statesNeedingLeftRecursionContext = try! BitSet(atn.states.count)
        for  state in atn.states {
            if let state = state as? StarLoopEntryState {
                if state.precedenceRuleDecision {
                    try! self.statesNeedingLeftRecursionContext.set(state.stateNumber)
                }
            }
        }
        try super.init(input)
        // get atn simulator that knows how to do predictions
        setInterpreter(ParserATNSimulator(self, atn,
                decisionToDFA,
                sharedContextCache))
    }
    override
    public func getATN() -> ATN {
        return atn
    }
    override
    public func getVocabulary() -> Vocabulary {
        return vocabulary
    }
    override
    public func getRuleNames() -> [String] {
        return ruleNames
    }
    override
    public func getGrammarFileName() -> String {
        return grammarFileName
    }
    /// Begin parsing at startRuleIndex
    public func parse(_ startRuleIndex: Int) throws -> ParserRuleContext {
        let startRuleStartState = atn.ruleToStartState[startRuleIndex]
        let rootContext = InterpreterRuleContext(nil, ATNState.INVALID_STATE_NUMBER, startRuleIndex)
        if startRuleStartState.isPrecedenceRule {
            try enterRecursionRule(rootContext, startRuleStartState.stateNumber, startRuleIndex, 0)
        } else {
            try enterRule(rootContext, startRuleStartState.stateNumber, startRuleIndex)
        }
        while true {
            let p = getATNState()!
            switch p.getStateType() {
            case ATNState.RULE_STOP:
                // pop; return from rule
                if _ctx!.isEmpty() {
                    if startRuleStartState.isPrecedenceRule {
                        let result: ParserRuleContext = _ctx!
                        let parentContext: (ParserRuleContext?, Int) = _parentContextStack.pop()
                        try unrollRecursionContexts(parentContext.0!)
                        return result
                    } else {
                        try exitRule()
                        return rootContext
                    }
                }
                try visitRuleStopState(p)
                break
            default:
                do {
                    try self.visitState(p)
                }
                 catch ANTLRException.recognition(let e) {
                    setState(self.atn.ruleToStopState[p.ruleIndex!].stateNumber)
                    getContext()!.exception = e
                    getErrorHandler().reportError(self, e)
                    try getErrorHandler().recover(self, e)
                }
                break
            }
        }
    }
    override
    public func enterRecursionRule(_ localctx: ParserRuleContext, _ state: Int, _ ruleIndex: Int, _ precedence: Int) throws {
        let pair: (ParserRuleContext?, Int) = (_ctx, localctx.invokingState)
        _parentContextStack.push(pair)
        try super.enterRecursionRule(localctx, state, ruleIndex, precedence)
    }
    internal func getATNState() -> ATNState? {
        return atn.states[getState()]
    }
    internal func visitState(_ p: ATNState) throws {
        var altNum: Int
        if p.getNumberOfTransitions() > 1 {
            try getErrorHandler().sync(self)
            let decision = (p as! DecisionState).decision
            if decision == overrideDecision && _input.index() == overrideDecisionInputIndex {
                altNum = overrideDecisionAlt
            } else {
                altNum = try getInterpreter().adaptivePredict(_input, decision, _ctx)
            }
        } else {
            altNum = 1
        }
        let transition = p.transition(altNum - 1)
        switch transition.getSerializationType() {
        case Transition.EPSILON:
            if try statesNeedingLeftRecursionContext.get(p.stateNumber) &&
                    !(transition.target is LoopEndState) {
                // We are at the start of a left recursive rule's (...)* loop
                // but it's not the exit branch of loop.
                let ctx: InterpreterRuleContext = InterpreterRuleContext(
                _parentContextStack.last!.0, //peek()
                        _parentContextStack.last!.1, //peek()
                        _ctx!.getRuleIndex())
                try    pushNewRecursionContext(ctx, atn.ruleToStartState[p.ruleIndex!].stateNumber, _ctx!.getRuleIndex())
            }
            break
        case Transition.ATOM:
            try match((transition as! AtomTransition).label)
            break
        case Transition.RANGE: fallthrough
        case Transition.SET: fallthrough
        case Transition.NOT_SET:
            if !transition.matches(try _input.LA(1), CommonToken.MIN_USER_TOKEN_TYPE, 65535) {
                try _errHandler.recoverInline(self)
            }
            try matchWildcard()
            break
        case Transition.WILDCARD:
            try matchWildcard()
            break
        case Transition.RULE:
            let ruleStartState = transition.target as! RuleStartState
            let ruleIndex = ruleStartState.ruleIndex!
            let ctx = InterpreterRuleContext(_ctx, p.stateNumber, ruleIndex)
            if ruleStartState.isPrecedenceRule {
                try enterRecursionRule(ctx, ruleStartState.stateNumber, ruleIndex, (transition as! RuleTransition).precedence)
            } else {
                try enterRule(ctx, transition.target.stateNumber, ruleIndex)
            }
            break
        case Transition.PREDICATE:
            let predicateTransition = transition as! PredicateTransition
            if try !sempred(_ctx!, predicateTransition.ruleIndex, predicateTransition.predIndex) {
                throw ANTLRException.recognition(e: FailedPredicateException(self))
            }
            break
        case Transition.ACTION:
            let actionTransition = transition as! ActionTransition
            try action(_ctx, actionTransition.ruleIndex, actionTransition.actionIndex)
            break
        case Transition.PRECEDENCE:
            if !precpred(_ctx!, (transition as! PrecedencePredicateTransition).precedence) {
                throw ANTLRException.recognition(e: FailedPredicateException(self, "precpred(_ctx,\((transition as! PrecedencePredicateTransition).precedence))"))
            }
            break
        default:
            throw ANTLRError.unsupportedOperation(msg: "Unrecognized ATN transition type.")
        }
        setState(transition.target.stateNumber)
    }
    internal func visitRuleStopState(_ p: ATNState) throws {
        let ruleStartState = atn.ruleToStartState[p.ruleIndex!]
        if ruleStartState.isPrecedenceRule {
            let (parentContext, parentState) = _parentContextStack.pop()
            try unrollRecursionContexts(parentContext!)
            setState(parentState)
        } else {
            try exitRule()
        }
        let ruleTransition = atn.states[getState()]!.transition(0) as! RuleTransition
        setState(ruleTransition.followState.stateNumber)
    }
    /// Override this parser interpreters normal decision-making process
    /// at a particular decision and input token index. Instead of
    /// allowing the adaptive prediction mechanism to choose the
    /// first alternative within a block that leads to a successful parse,
    /// force it to take the alternative, 1..n for n alternatives.
    ///
    /// As an implementation limitation right now, you can only specify one
    /// override. This is sufficient to allow construction of different
    /// parse trees for ambiguous input. It means re-parsing the entire input
    /// in general because you're never sure where an ambiguous sequence would
    /// live in the various parse trees. For example, in one interpretation,
    /// an ambiguous input sequence would be matched completely in expression
    /// but in another it could match all the way back to the root.
    ///
    /// s : e '!'? ;
    /// e : ID
    /// | ID '!'
    /// ;
    ///
    /// Here, x! can be matched as (s (e ID) !) or (s (e ID !)). In the first
    /// case, the ambiguous sequence is fully contained only by the root.
    /// In the second case, the ambiguous sequences fully contained within just
    /// e, as in: (e ID !).
    ///
    /// Rather than trying to optimize this and make
    /// some intelligent decisions for optimization purposes, I settled on
    /// just re-parsing the whole input and then using
    /// {link Trees#getRootOfSubtreeEnclosingRegion} to find the minimal
    /// subtree that contains the ambiguous sequence. I originally tried to
    /// record the call stack at the point the parser detected and ambiguity but
    /// left recursive rules create a parse tree stack that does not reflect
    /// the actual call stack. That impedance mismatch was enough to make
    /// it it challenging to restart the parser at a deeply nested rule
    /// invocation.
    ///
    /// Only parser interpreters can override decisions so as to avoid inserting
    /// override checking code in the critical ALL(*) prediction execution path.
    ///
    /// - Since: 4.5.1
    ///
    public func addDecisionOverride(_ decision: Int, _ tokenIndex: Int, _ forcedAlt: Int) {
        overrideDecision = decision
        overrideDecisionInputIndex = tokenIndex
        overrideDecisionAlt = forcedAlt
    }
}


LexerInterpreter

///
///
public class LexerInterpreter: Lexer {
    internal let grammarFileName: String
    internal let atn: ATN
    internal let ruleNames: [String]
    internal let channelNames: [String]
    internal let modeNames: [String]
    private let vocabulary: Vocabulary?
    internal final var _decisionToDFA: [DFA]
    internal let _sharedContextCache = PredictionContextCache()
    public init(_ grammarFileName: String, _ vocabulary: Vocabulary, _ ruleNames: Array<String>, _ channelNames: Array<String>, _ modeNames: Array<String>, _ atn: ATN, _ input: CharStream) throws {
        self.grammarFileName = grammarFileName
        self.atn = atn
        self.ruleNames = ruleNames
        self.channelNames = channelNames
        self.modeNames = modeNames
        self.vocabulary = vocabulary
        self._decisionToDFA = [DFA]()
        for i in 0 ..< atn.getNumberOfDecisions() {
            _decisionToDFA.append(DFA(atn.getDecisionState(i)!, i))
        }
        super.init(input)
        self._interp = LexerATNSimulator(self, atn, _decisionToDFA, _sharedContextCache)
        if atn.grammarType != ATNType.lexer {
            throw ANTLRError.illegalArgument(msg: "The ATN must be a lexer ATN.")
        }
    }
    public required init(_ input: CharStream) {
        fatalError("Use the other initializer")
    }
    override
    public func getATN() -> ATN {
        return atn
    }
    override
    public func getGrammarFileName() -> String {
        return grammarFileName
    }
    override
    public func getRuleNames() -> [String] {
        return ruleNames
    }
    override
    public func getChannelNames() -> [String] {
        return channelNames
    }
    override
    public func getModeNames() -> [String] {
        return modeNames
    }
    override
    public func getVocabulary() -> Vocabulary {
        return vocabulary ?? super.getVocabulary()
    }
}


BailErrorStrategy

///
///
///
///
/// This implementation of _org.antlr.v4.runtime.ANTLRErrorStrategy_ responds to syntax errors
/// by immediately canceling the parse operation with a
/// _org.antlr.v4.runtime.misc.ParseCancellationException_. The implementation ensures that the
/// _org.antlr.v4.runtime.ParserRuleContext#exception_ field is set for all parse tree nodes
/// that were not completed prior to encountering the error.
///
/// This error strategy is useful in the following scenarios.
///
/// * __Two-stage parsing:__ This error strategy allows the first
/// stage of two-stage parsing to immediately terminate if an error is
/// encountered, and immediately fall back to the second stage. In addition to
/// avoiding wasted work by attempting to recover from errors here, the empty
/// implementation of _org.antlr.v4.runtime.BailErrorStrategy#sync_ improves the performance of
/// the first stage.
///
/// * __Silent validation:__ When syntax errors are not being
/// reported or logged, and the parse result is simply ignored if errors occur,
/// the _org.antlr.v4.runtime.BailErrorStrategy_ avoids wasting work on recovering from errors
/// when the result will be ignored either way.
///
/// `myparser.setErrorHandler(new BailErrorStrategy());`
///
/// - seealso: org.antlr.v4.runtime.Parser#setErrorHandler(org.antlr.v4.runtime.ANTLRErrorStrategy)
///
///
open class BailErrorStrategy: DefaultErrorStrategy {
    public override init() {
    }
    ///
    /// Instead of recovering from exception `e`, re-throw it wrapped
    /// in a _org.antlr.v4.runtime.misc.ParseCancellationException_ so it is not caught by the
    /// rule function catches.  Use _Exception#getCause()_ to get the
    /// original _org.antlr.v4.runtime.RecognitionException_.
    ///
    override open func recover(_ recognizer: Parser, _ e: RecognitionException) throws {
        var context = recognizer.getContext()
        while let contextWrap = context {
            contextWrap.exception = e
            context = (contextWrap.getParent() as? ParserRuleContext)
        }
        throw ANTLRException.parseCancellation(e: e)
    }
    ///
    /// Make sure we don't attempt to recover inline; if the parser
    /// successfully recovers, it won't throw an exception.
    ///
    override
    open func recoverInline(_ recognizer: Parser) throws -> Token {
        let e = InputMismatchException(recognizer)
        var context = recognizer.getContext()
        while let contextWrap = context {
             contextWrap.exception = e
             context = (contextWrap.getParent() as? ParserRuleContext)
        }
        throw ANTLRException.parseCancellation(e: e)
    }
    ///
    /// Make sure we don't attempt to recover from problems in subrules.
    ///
    override
    open func sync(_ recognizer: Parser) {
    }
}


BufferedTokenStream

///
///
///
/// This implementation of _org.antlr.v4.runtime.TokenStream_ loads tokens from a
/// _org.antlr.v4.runtime.TokenSource_ on-demand, and places the tokens in a buffer to provide
/// access to any previous token by index.
///
///
/// This token stream ignores the value of _org.antlr.v4.runtime.Token#getChannel_. If your
/// parser requires the token stream filter tokens to only those on a particular
/// channel, such as _org.antlr.v4.runtime.Token#DEFAULT_CHANNEL_ or
/// _org.antlr.v4.runtime.Token#HIDDEN_CHANNEL_, use a filtering token stream such a
/// _org.antlr.v4.runtime.CommonTokenStream_.
///
public class BufferedTokenStream: TokenStream {
    ///
    /// The _org.antlr.v4.runtime.TokenSource_ from which tokens for this stream are fetched.
    ///
    internal var tokenSource: TokenSource
    ///
    /// A collection of all tokens fetched from the token source. The list is
    /// considered a complete view of the input once _#fetchedEOF_ is set
    /// to `true`.
    ///
    internal var tokens = [Token]()
    ///
    /// The index into _#tokens_ of the current token (next token to
    /// _#consume_). _#tokens_`[`_#p_`]` should be
    /// _#LT LT(1)_.
    ///
    /// This field is set to -1 when the stream is first constructed or when
    /// _#setTokenSource_ is called, indicating that the first token has
    /// not yet been fetched from the token source. For additional information,
    /// see the documentation of _org.antlr.v4.runtime.IntStream_ for a description of
    /// Initializing Methods.
    ///
    internal var p = -1
    ///
    /// Indicates whether the _org.antlr.v4.runtime.Token#EOF_ token has been fetched from
    /// _#tokenSource_ and added to _#tokens_. This field improves
    /// performance for the following cases:
    ///
    /// * _#consume_: The lookahead check in _#consume_ to prevent
    /// consuming the EOF symbol is optimized by checking the values of
    /// _#fetchedEOF_ and _#p_ instead of calling _#LA_.
    ///
    /// * _#fetch_: The check to prevent adding multiple EOF symbols into
    /// _#tokens_ is trivial with this field.
    ///
    internal var fetchedEOF = false
    public init(_ tokenSource: TokenSource) {
        self.tokenSource = tokenSource
    }
    public func getTokenSource() -> TokenSource {
        return tokenSource
    }
    public func index() -> Int {
        return p
    }
    public func mark() -> Int {
        return 0
    }
    public func release(_ marker: Int) {
        // no resources to release
    }
    public func reset() throws {
        try seek(0)
    }
    public func seek(_ index: Int) throws {
        try lazyInit()
        p = try adjustSeekIndex(index)
    }
    public func size() -> Int {
        return tokens.count
    }
    public func consume() throws {
        var skipEofCheck: Bool
        if p >= 0 {
            if fetchedEOF {
                // the last token in tokens is EOF. skip check if p indexes any
                // fetched token except the last.
                skipEofCheck = p < tokens.count - 1
            } else {
                // no EOF token in tokens. skip check if p indexes a fetched token.
                skipEofCheck = p < tokens.count
            }
        } else {
            // not yet initialized
            skipEofCheck = false
        }
        if try !skipEofCheck && LA(1) == BufferedTokenStream.EOF {
            throw ANTLRError.illegalState(msg: "cannot consume EOF")
        }
        if try sync(p + 1) {
            p = try adjustSeekIndex(p + 1)
        }
    }
    ///
    /// Make sure index `i` in tokens has a token.
    ///
    /// - returns: `true` if a token is located at index `i`, otherwise
    /// `false`.
    /// - seealso: #get(int i)
    ///
    internal func sync(_ i: Int) throws -> Bool {
        assert(i >= 0, "Expected: i>=0")
        let n = i - tokens.count + 1 // how many more elements we need?
        //print("sync("+i+") needs "+n);
        if n > 0 {
            let fetched = try fetch(n)
            return fetched >= n
        }
        return true
    }
    ///
    /// Add `n` elements to buffer.
    ///
    /// - returns: The actual number of elements added to the buffer.
    ///
    internal func fetch(_ n: Int) throws -> Int {
        if fetchedEOF {
            return 0
        }
        for i in 0..<n {
            let t = try tokenSource.nextToken()
            if let wt = t as? WritableToken {
                wt.setTokenIndex(tokens.count)
            }
            tokens.append(t)
            if t.getType() == BufferedTokenStream.EOF {
                fetchedEOF = true
                return i + 1
            }
        }
        return n
    }
    public func get(_ i: Int) throws -> Token {
        guard tokens.indices.contains(i) else {
            throw ANTLRError.indexOutOfBounds(msg: "token index \(i) out of range 0 ..< \(tokens.count)")
        }
        return tokens[i]
    }
    ///
    /// Get all tokens from start...stop inclusively
    ///
    public func get(_ start: Int,_ stop: Int) throws -> Array<Token>? {
        var stop = stop
        if start < 0 || stop < 0 {
            return nil
        }
        try lazyInit()
        var subset = [Token]()
        if stop >= tokens.count {
            stop = tokens.count - 1
        }
        for i in start...stop {
            let t = tokens[i]
            if t.getType() == BufferedTokenStream.EOF {
                break
            }
            subset.append(t)
        }
        return subset
    }
    public func LA(_ i: Int) throws -> Int {
        return try LT(i)!.getType()
    }
    internal func LB(_ k: Int) throws -> Token? {
        if (p - k) < 0 {
            return nil
        }
        return tokens[p - k]
    }
    public func LT(_ k: Int) throws -> Token? {
        try lazyInit()
        if k == 0 {
            return nil
        }
        if k < 0 {
            return try LB(-k)
        }
        let i = p + k - 1
        try sync(i)
        if i >= tokens.count {
            // return EOF token
            // EOF must be last token
            return tokens.last!
        }
        return tokens[i]
    }
    ///
    /// Allowed derived classes to modify the behavior of operations which change
    /// the current stream position by adjusting the target token index of a seek
    /// operation. The default implementation simply returns `i`. If an
    /// exception is thrown in this method, the current stream index should not be
    /// changed.
    ///
    /// For example, _org.antlr.v4.runtime.CommonTokenStream_ overrides this method to ensure that
    /// the seek target is always an on-channel token.
    ///
    /// - parameter i: The target token index.
    /// - returns: The adjusted target token index.
    ///
    internal func adjustSeekIndex(_ i: Int) throws -> Int {
        return i
    }
    internal final func lazyInit() throws {
        if p == -1 {
            try setup()
        }
    }
    internal func setup() throws {
        try sync(0)
        p = try adjustSeekIndex(0)
    }
    ///
    /// Reset this token stream by setting its token source.
    ///
    public func setTokenSource(_ tokenSource: TokenSource) {
        self.tokenSource = tokenSource
        tokens.removeAll()
        p = -1
        fetchedEOF = false
    }
    public func getTokens() -> [Token] {
        return tokens
    }
    public func getTokens(_ start: Int, _ stop: Int) throws -> [Token]? {
        return try getTokens(start, stop, nil)
    }
    ///
    /// Given a start and stop index, return a List of all tokens in
    /// the token type BitSet.  Return null if no tokens were found.  This
    /// method looks at both on and off channel tokens.
    ///
    public func getTokens(_ start: Int, _ stop: Int, _ types: Set<Int>?) throws -> [Token]? {
        try lazyInit()
        guard tokens.indices.contains(start),
              tokens.indices.contains(stop) else {
            throw ANTLRError.indexOutOfBounds(msg: "start \(start) or stop \(stop) not in 0 ..< \(tokens.count)")
        }
        if start > stop {
            return nil
        }
        var filteredTokens = [Token]()
        for i in start...stop {
            let t = tokens[i]
            if types?.contains(t.getType()) ?? true {
                filteredTokens.append(t)
            }
        }
        if filteredTokens.isEmpty {
            return nil
        }
        return filteredTokens
    }
    public func getTokens(_ start: Int, _ stop: Int, _ ttype: Int) throws -> [Token]? {
        return try getTokens(start, stop, [ttype])
    }
    ///
    /// Given a starting index, return the index of the next token on channel.
    /// Return `i` if `tokens[i]` is on channel. Return the index of
    /// the EOF token if there are no tokens on channel between `i` and
    /// EOF.
    ///
    internal func nextTokenOnChannel(_ i: Int, _ channel: Int) throws -> Int {
        var i = i
        try sync(i)
        if i >= size() {
            return size() - 1
        }
        var token = tokens[i]
        while token.getChannel() != channel {
            if token.getType() == BufferedTokenStream.EOF {
                return i
            }
            i += 1
            try sync(i)
            token = tokens[i]
        }
        return i
    }
    ///
    /// Given a starting index, return the index of the previous token on
    /// channel. Return `i` if `tokens[i]` is on channel. Return -1
    /// if there are no tokens on channel between `i` and 0.
    ///
    ///
    /// If `i` specifies an index at or after the EOF token, the EOF token
    /// index is returned. This is due to the fact that the EOF token is treated
    /// as though it were on every channel.
    ///
    internal func previousTokenOnChannel(_ i: Int, _ channel: Int) throws -> Int {
        var i = i
        try sync(i)
        if i >= size() {
            // the EOF token is on every channel
            return size() - 1
        }
        while i >= 0 {
            let token = tokens[i]
            if token.getType() == BufferedTokenStream.EOF || token.getChannel() == channel {
                return i
            }
            i -= 1
        }
        return i
    }
    ///
    /// Collect all tokens on specified channel to the right of
    /// the current token up until we see a token on DEFAULT_TOKEN_CHANNEL or
    /// EOF. If channel is -1, find any non default channel token.
    ///
    public func getHiddenTokensToRight(_ tokenIndex: Int, _ channel: Int = -1) throws -> [Token]? {
        try lazyInit()
        guard tokens.indices.contains(tokenIndex) else {
            throw ANTLRError.indexOutOfBounds(msg: "\(tokenIndex) not in 0 ..< \(tokens.count)")
        }
        let nextOnChannel = try nextTokenOnChannel(tokenIndex + 1, Lexer.DEFAULT_TOKEN_CHANNEL)
        let from = tokenIndex + 1
        let to: Int
        // if none onchannel to right, nextOnChannel=-1 so set to = last token
        if nextOnChannel == -1 {
            to = size() - 1
        }
        else {
            to = nextOnChannel
        }
        return filterForChannel(from, to, channel)
    }
    ///
    /// Collect all tokens on specified channel to the left of
    /// the current token up until we see a token on DEFAULT_TOKEN_CHANNEL.
    /// If channel is -1, find any non default channel token.
    ///
    public func getHiddenTokensToLeft(_ tokenIndex: Int, _ channel: Int = -1) throws -> [Token]? {
        try lazyInit()
        guard tokens.indices.contains(tokenIndex) else {
            throw ANTLRError.indexOutOfBounds(msg: "\(tokenIndex) not in 0 ..< \(tokens.count)")
        }
        if tokenIndex == 0 {
            // obviously no tokens can appear before the first token
            return nil
        }
        let prevOnChannel = try previousTokenOnChannel(tokenIndex - 1, Lexer.DEFAULT_TOKEN_CHANNEL)
        if prevOnChannel == tokenIndex - 1 {
            return nil
        }
        // if none onchannel to left, prevOnChannel=-1 then from=0
        let from = prevOnChannel + 1
        let to = tokenIndex - 1
        return filterForChannel(from, to, channel)
    }
    internal func filterForChannel(_ from: Int, _ to: Int, _ channel: Int) -> [Token]? {
        var hidden = [Token]()
        for t in tokens[from...to] {
            if channel == -1 {
                if t.getChannel() != Lexer.DEFAULT_TOKEN_CHANNEL {
                    hidden.append(t)
                }
            } else {
                if t.getChannel() == channel {
                    hidden.append(t)
                }
            }
        }
        if hidden.isEmpty {
            return nil
        }
        return hidden
    }
    public func getSourceName() -> String {
        return tokenSource.getSourceName()
    }
    ///
    /// Get the text of all tokens in this buffer.
    ///
    public func getText() throws -> String {
        return try getText(Interval.of(0, size() - 1))
    }
    public func getText(_ interval: Interval) throws -> String {
        let start = interval.a
        if start < 0 {
            return ""
        }
        try fill()
        let stop = min(tokens.count, interval.b + 1)
        var buf = ""
        for t in tokens[start ..< stop] {
            if t.getType() == BufferedTokenStream.EOF {
                break
            }
            buf += t.getText()!
        }
        return buf
    }
    public func getText(_ ctx: RuleContext) throws -> String {
        return try getText(ctx.getSourceInterval())
    }
    public func getText(_ start: Token?, _ stop: Token?) throws -> String {
        if let start = start, let stop = stop {
            return try getText(Interval.of(start.getTokenIndex(), stop.getTokenIndex()))
        }
        return ""
    }
    ///
    /// Get all tokens from lexer until EOF
    ///
    public func fill() throws {
        try lazyInit()
        let blockSize = 1000
        while true {
            let fetched = try fetch(blockSize)
            if fetched < blockSize {
                return
            }
        }
    }
}


TokenSource

 */
///
/// A source of tokens must provide a sequence of tokens via _#nextToken()_
/// and also must reveal it's source of characters; _org.antlr.v4.runtime.CommonToken_'s text is
/// computed from a _org.antlr.v4.runtime.CharStream_; it only store indices into the char
/// stream.
///
/// Errors from the lexer are never passed to the parser. Either you want to keep
/// going or you do not upon token recognition error. If you do not want to
/// continue lexing then you do not want to continue parsing. Just throw an
/// exception not under _org.antlr.v4.runtime.RecognitionException_ and Java will naturally toss
/// you all the way out of the recognizers. If you want to continue lexing then
/// you should not throw an exception to the parser--it has already requested a
/// token. Keep lexing until you get a valid one. Just report errors and keep
/// going, looking for a valid token.
///
public protocol TokenSource: AnyObject {
    ///
    /// Return a _org.antlr.v4.runtime.Token_ object from your input stream (usually a
    /// _org.antlr.v4.runtime.CharStream_). Do not fail/return upon lexing error; keep chewing
    /// on the characters until you get a good one; errors are not passed through
    /// to the parser.
    ///
    func nextToken() throws -> Token
    ///
    /// Get the line number for the current position in the input stream. The
    /// first line in the input is line 1.
    ///
    /// - Returns: The line number for the current position in the input stream, or
    /// 0 if the current token source does not track line numbers.
    ///
    func getLine() -> Int
    ///
    /// Get the index into the current line for the current position in the input
    /// stream. The first character on a line has position 0.
    ///
    /// - Returns: The line number for the current position in the input stream, or
    /// -1 if the current token source does not track character positions.
    ///
    func getCharPositionInLine() -> Int
    ///
    /// Get the _org.antlr.v4.runtime.CharStream_ from which this token source is currently
    /// providing tokens.
    ///
    /// - Returns: The _org.antlr.v4.runtime.CharStream_ associated with the current position in
    /// the input, or `null` if no input stream is available for the token
    /// source.
    ///
    func getInputStream() -> CharStream?
    ///
    /// Gets the name of the underlying input source. This method returns a
    /// non-null, non-empty string. If such a name is not known, this method
    /// returns _org.antlr.v4.runtime.IntStream#UNKNOWN_SOURCE_NAME_.
    ///
    func getSourceName() -> String
    ///
    /// Set the _org.antlr.v4.runtime.TokenFactory_ this token source should use for creating
    /// _org.antlr.v4.runtime.Token_ objects from the input.
    ///
    /// - Parameter factory: The _org.antlr.v4.runtime.TokenFactory_ to use for creating tokens.
    ///
    func setTokenFactory(_ factory: TokenFactory)
    ///
    /// Gets the _org.antlr.v4.runtime.TokenFactory_ this token source is currently using for
    /// creating _org.antlr.v4.runtime.Token_ objects from the input.
    ///
    /// - Returns: The _org.antlr.v4.runtime.TokenFactory_ currently used by this token source.
    ///
    func getTokenFactory() -> TokenFactory
}


RuntimeMetaData

 */
///
/// This class provides access to the current version of the ANTLR 4 runtime
/// library as compile-time and runtime constants, along with methods for
/// checking for matching version numbers and notifying listeners in the case
/// where a version mismatch is detected.
///
///
/// The runtime version information is provided by _#VERSION_ and
/// _#getRuntimeVersion()_. Detailed information about these values is
/// provided in the documentation for each member.
///
///
/// The runtime version check is implemented by _#checkVersion_. Detailed
/// information about incorporating this call into user code, as well as its use
/// in generated code, is provided in the documentation for the method.
///
///
/// Version strings x.y and x.y.z are considered "compatible" and no error
/// would be generated. Likewise, version strings x.y-SNAPSHOT and x.y.z are
/// considered "compatible" because the major and minor components x.y
/// are the same in each.
///
///
/// To trap any error messages issued by this code, use System.setErr()
/// in your main() startup code.
///
///
/// - Since: 4.3
///
public class RuntimeMetaData {
    ///
    /// A compile-time constant containing the current version of the ANTLR 4
    /// runtime library.
    ///
    /// This compile-time constant value allows generated parsers and other
    /// libraries to include a literal reference to the version of the ANTLR 4
    /// runtime library the code was compiled against. At each release, we
    /// change this value.
    ///
    /// Version numbers are assumed to have the form
    ///
    /// __major__.__minor__.__patch__.__revision__-__suffix__,
    ///
    /// with the individual components defined as follows.
    ///
    /// * __major__ is a required non-negative integer, and is equal to
    /// `4` for ANTLR 4.
    /// * __minor__ is a required non-negative integer.
    /// * __patch__ is an optional non-negative integer. When
    /// patch is omitted, the `.` (dot) appearing before it is
    /// also omitted.
    /// * __revision__ is an optional non-negative integer, and may only
    /// be included when __patch__ is also included. When __revision__
    /// is omitted, the `.` (dot) appearing before it is also omitted.
    /// * __suffix__ is an optional string. When __suffix__ is
    /// omitted, the `-` (hyphen-minus) appearing before it is also
    /// omitted.
    ///
    public static let VERSION: String = "4.13.0"
    ///
    /// Gets the currently executing version of the ANTLR 4 runtime library.
    ///
    ///
    /// This method provides runtime access to the _#VERSION_ field, as
    /// opposed to directly referencing the field as a compile-time constant.
    ///
    /// - Returns: The currently executing version of the ANTLR 4 library
    ///
    public static func getRuntimeVersion() -> String {
        return RuntimeMetaData.VERSION
    }
    ///
    /// This method provides the ability to detect mismatches between the version
    /// of ANTLR 4 used to generate a parser, the version of the ANTLR runtime a
    /// parser was compiled against, and the version of the ANTLR runtime which
    /// is currently executing.
    ///
    /// The version check is designed to detect the following two specific
    /// scenarios.
    ///
    /// * The ANTLR Tool version used for code generation does not match the
    /// currently executing runtime version.
    /// * The ANTLR Runtime version referenced at the time a parser was
    /// compiled does not match the currently executing runtime version.
    ///
    /// Starting with ANTLR 4.3, the code generator emits a call to this method
    /// using two constants in each generated lexer and parser: a hard-coded
    /// constant indicating the version of the tool used to generate the parser
    /// and a reference to the compile-time constant _#VERSION_. At
    /// runtime, this method is called during the initialization of the generated
    /// parser to detect mismatched versions, and notify the registered listeners
    /// prior to creating instances of the parser.
    ///
    /// This method does not perform any detection or filtering of semantic
    /// changes between tool and runtime versions. It simply checks for a
    /// version match and emits an error to stderr if a difference
    /// is detected.
    ///
    /// Note that some breaking changes between releases could result in other
    /// types of runtime exceptions, such as a _LinkageError_, prior to
    /// calling this method. In these cases, the underlying version mismatch will
    /// not be reported here. This method is primarily intended to
    /// notify users of potential semantic changes between releases that do not
    /// result in binary compatibility problems which would be detected by the
    /// class loader. As with semantic changes, changes that break binary
    /// compatibility between releases are mentioned in the release notes
    /// accompanying the affected release.
    ///
    /// __ Additional note for target developers:__ The version check
    /// implemented by this class is designed to address specific compatibility
    /// concerns that may arise during the execution of Java applications. Other
    /// targets should consider the implementation of this method in the context
    /// of that target's known execution environment, which may or may not
    /// resemble the design provided for the Java target.
    ///
    /// - Parameter generatingToolVersion: The version of the tool used to generate a parser.
    /// This value may be null when called from user code that was not generated
    /// by, and does not reference, the ANTLR 4 Tool itself.
    /// - Parameter compileTimeVersion: The version of the runtime the parser was
    /// compiled against. This should always be passed using a direct reference
    /// to _#VERSION_.
    ///
    public static func checkVersion(_ generatingToolVersion: String, _ compileTimeVersion: String) {
        let runtimeVersion: String = RuntimeMetaData.VERSION
        var runtimeConflictsWithGeneratingTool: Bool = false
        var runtimeConflictsWithCompileTimeTool: Bool = false
        //if ( generatingToolVersion != nil ) {
        runtimeConflictsWithGeneratingTool =
                !(runtimeVersion == (generatingToolVersion)) &&
                !(getMajorMinorVersion(runtimeVersion) == (getMajorMinorVersion(generatingToolVersion)))
        //}
        runtimeConflictsWithCompileTimeTool =
                !(runtimeVersion == (compileTimeVersion)) &&
                !(getMajorMinorVersion(runtimeVersion) == (getMajorMinorVersion(compileTimeVersion)))
        if runtimeConflictsWithGeneratingTool {
            print("ANTLR Tool version \(generatingToolVersion) used for code generation does not match the current runtime version \(runtimeVersion)")
        }
        if runtimeConflictsWithCompileTimeTool {
            print("ANTLR Runtime version \(compileTimeVersion)used for parser compilation does not match the current runtime version \(runtimeVersion)")
        }
    }
    ///
    /// Gets the major and minor version numbers from a version string. For
    /// details about the syntax of the input `version`.
    /// E.g., from x.y.z return x.y.
    ///
    /// - Parameter version: The complete version string.
    /// - Returns: A string of the form __major__.__minor__ containing
    /// only the major and minor components of the version string.
    ///
    public static func getMajorMinorVersion(_ version: String) -> String {
        var result = version
        let dotBits = version.split(separator: ".", maxSplits: 2, omittingEmptySubsequences: false)
        if dotBits.count >= 2 {
            result = dotBits[0..<2].joined(separator: ".")
        }
        let dashBits = result.split(separator: "-", maxSplits: 1, omittingEmptySubsequences: false)
        return String(dashBits[0])
    }
}


CommonTokenFactory

///
///
///
/// This default implementation of _org.antlr.v4.runtime.TokenFactory_ creates
/// _org.antlr.v4.runtime.CommonToken_ objects.
///
public class CommonTokenFactory: TokenFactory {
    ///
    /// The default _org.antlr.v4.runtime.CommonTokenFactory_ instance.
    ///
    ///
    /// This token factory does not explicitly copy token text when constructing
    /// tokens.
    ///
    public static let DEFAULT: TokenFactory = CommonTokenFactory()
    ///
    /// Indicates whether _org.antlr.v4.runtime.CommonToken#setText_ should be called after
    /// constructing tokens to explicitly set the text. This is useful for cases
    /// where the input stream might not be able to provide arbitrary substrings
    /// of text from the input after the lexer creates a token (e.g. the
    /// implementation of _org.antlr.v4.runtime.CharStream#getText_ in
    /// _org.antlr.v4.runtime.UnbufferedCharStream_ throws an
    /// _UnsupportedOperationException_). Explicitly setting the token text
    /// allows _org.antlr.v4.runtime.Token#getText_ to be called at any time regardless of the
    /// input stream implementation.
    ///
    ///
    /// The default value is `false` to avoid the performance and memory
    ///
    internal let copyText: Bool
    ///
    /// Constructs a _org.antlr.v4.runtime.CommonTokenFactory_ with the specified value for
    /// _#copyText_.
    ///
    ///
    /// When `copyText` is `false`, the _#DEFAULT_ instance
    /// should be used instead of constructing a new instance.
    ///
    /// - parameter copyText: The value for _#copyText_.
    ///
    public init(_ copyText: Bool) {
        self.copyText = copyText
    }
    ///
    /// Constructs a _org.antlr.v4.runtime.CommonTokenFactory_ with _#copyText_ set to
    /// `false`.
    ///
    ///
    /// The _#DEFAULT_ instance should be used instead of calling this
    /// directly.
    ///
    public convenience init() {
        self.init(false)
    }
    public func create(_ source: TokenSourceAndStream, _ type: Int, _ text: String?,
                       _ channel: Int, _ start: Int, _ stop: Int,
                       _ line: Int, _ charPositionInLine: Int) -> Token {
        let t = CommonToken(source, type, channel, start, stop)
        t.setLine(line)
        t.setCharPositionInLine(charPositionInLine)
        if let text = text {
            t.setText(text)
        }
        else if let cStream = source.stream, copyText {
            t.setText(try! cStream.getText(Interval.of(start, stop)))
        }
        return t
    }
    public func create(_ type: Int, _ text: String) -> Token {
        return CommonToken(type, text)
    }
}


TokenStream

 */
///
/// An _org.antlr.v4.runtime.IntStream_ whose symbols are _org.antlr.v4.runtime.Token_ instances.
///
public protocol TokenStream: IntStream {
    ///
    /// Get the _org.antlr.v4.runtime.Token_ instance associated with the value returned by
    /// _#LA LA(k)_. This method has the same pre- and post-conditions as
    /// _org.antlr.v4.runtime.IntStream#LA_. In addition, when the preconditions of this method
    /// are met, the return value is non-null and the value of
    /// `LT(k).getType()==LA(k)`.
    ///
    /// - SeeAlso: org.antlr.v4.runtime.IntStream#LA
    ///
    func LT(_ k: Int) throws -> Token?
    ///
    /// Gets the _org.antlr.v4.runtime.Token_ at the specified `index` in the stream. When
    /// the preconditions of this method are met, the return value is non-null.
    ///
    /// The preconditions for this method are the same as the preconditions of
    /// _org.antlr.v4.runtime.IntStream#seek_. If the behavior of `seek(index)` is
    /// unspecified for the current state and given `index`, then the
    /// behavior of this method is also unspecified.
    ///
    /// The symbol referred to by `index` differs from `seek()` only
    /// in the case of filtering streams where `index` lies before the end
    /// of the stream. Unlike `seek()`, this method does not adjust
    /// `index` to point to a non-ignored symbol.
    ///
    /// - Throws: ANTLRError.illegalArgument if {code index} is less than 0
    /// - Throws: ANTLRError.unsupportedOperation if the stream does not support
    /// retrieving the token at the specified index
    ///
    func get(_ index: Int) throws -> Token
    ///
    /// Gets the underlying _org.antlr.v4.runtime.TokenSource_ which provides tokens for this
    /// stream.
    ///
    func getTokenSource() -> TokenSource
    ///
    /// Return the text of all tokens within the specified `interval`. This
    /// method behaves like the following code (including potential exceptions
    /// for violating preconditions of _#get_, but may be optimized by the
    /// specific implementation.
    ///
    ///
    /// TokenStream stream = ...;
    /// String text = "";
    /// for (int i = interval.a; i <= interval.b; i++) {
    /// text += stream.get(i).getText();
    /// }
    ///
    ///
    /// - Parameter interval: The interval of tokens within this stream to get text
    /// for.
    /// - Returns: The text of all tokens within the specified interval in this
    /// stream.
    ///
    ///
    func getText(_ interval: Interval) throws -> String
    ///
    /// Return the text of all tokens in the stream. This method behaves like the
    /// following code, including potential exceptions from the calls to
    /// _org.antlr.v4.runtime.IntStream#size_ and _#getText(org.antlr.v4.runtime.misc.Interval)_, but may be
    /// optimized by the specific implementation.
    ///
    ///
    /// TokenStream stream = ...;
    /// String text = stream.getText(new Interval(0, stream.size()));
    ///
    ///
    /// - Returns: The text of all tokens in the stream.
    ///
    func getText() throws -> String
    ///
    /// Return the text of all tokens in the source interval of the specified
    /// context. This method behaves like the following code, including potential
    /// exceptions from the call to _#getText(org.antlr.v4.runtime.misc.Interval)_, but may be
    /// optimized by the specific implementation.
    ///
    /// If `ctx.getSourceInterval()` does not return a valid interval of
    /// tokens provided by this stream, the behavior is unspecified.
    ///
    ///
    /// TokenStream stream = ...;
    /// String text = stream.getText(ctx.getSourceInterval());
    ///
    ///
    /// - Parameter ctx: The context providing the source interval of tokens to get
    /// text for.
    /// - Returns: The text of all tokens within the source interval of `ctx`.
    ///
    func getText(_ ctx: RuleContext) throws -> String
    ///
    /// Return the text of all tokens in this stream between `start` and
    /// `stop` (inclusive).
    ///
    /// If the specified `start` or `stop` token was not provided by
    /// this stream, or if the `stop` occurred before the `start`
    /// token, the behavior is unspecified.
    ///
    /// For streams which ensure that the _org.antlr.v4.runtime.Token#getTokenIndex_ method is
    /// accurate for all of its provided tokens, this method behaves like the
    /// following code. Other streams may implement this method in other ways
    /// provided the behavior is consistent with this at a high level.
    ///
    ///
    /// TokenStream stream = ...;
    /// String text = "";
    /// for (int i = start.getTokenIndex(); i <= stop.getTokenIndex(); i++) {
    /// text += stream.get(i).getText();
    /// }
    ///
    ///
    /// - Parameter start: The first token in the interval to get text for.
    /// - Parameter stop: The last token in the interval to get text for (inclusive).
    /// - Throws: ANTLRError.unsupportedOperation if this stream does not support
    /// this method for the specified tokens
    /// - Returns: The text of all tokens lying between the specified `start`
    /// and `stop` tokens.
    ///
    ///
    func getText(_ start: Token?, _ stop: Token?) throws -> String
}