convert documentation to Swift style

This commit is contained in:
Hanzhou Shi 2017-01-15 21:54:50 -08:00
parent ee82046201
commit 139225f76c
134 changed files with 4732 additions and 6315 deletions

View File

@ -1,23 +0,0 @@
import Antlr4
var input = "hello world"
let lexer = HelloLexer(ANTLRInputStream(input))
let tokens = CommonTokenStream(lexer)
do {
let parser = try HelloParser(tokens)
let tree = try parser.r()
let walker = ParseTreeWalker()
try walker.walk(HelloWalker(), tree)
}
catch ANTLRException.cannotInvokeStartRule {
print("Error: cannot invoke start rule.")
}
catch ANTLRException.recognition(let e) {
print("Unrecoverable recognition error: \(e)")
}
catch {
print("Unknown error: \(error)")
}

View File

@ -1,5 +0,0 @@
// Define a grammar called Hello
grammar Hello;
r : 'hello' ID ; // match keyword hello followed by an identifier
ID : [a-z]+ ; // match lower-case identifiers
WS : [ \t\r\n]+ -> skip ; // skip spaces, tabs, newlines

View File

@ -1,4 +0,0 @@
T__0=1
ID=2
WS=3
'hello'=1

View File

@ -1,50 +0,0 @@
// Generated from Hello.g4 by ANTLR 4.6
import Antlr4
/**
* This class provides an empty implementation of {@link HelloListener},
* which can be extended to create a listener which only needs to handle a subset
* of the available methods.
*/
open class HelloBaseListener: HelloListener {
public init() { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
open func enterR(_ ctx: HelloParser.RContext) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
open func exitR(_ ctx: HelloParser.RContext) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
open func enterEveryRule(_ ctx: ParserRuleContext) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
open func exitEveryRule(_ ctx: ParserRuleContext) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
open func visitTerminal(_ node: TerminalNode) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
open func visitErrorNode(_ node: ErrorNode) { }
}

View File

@ -1,20 +0,0 @@
// Generated from Hello.g4 by ANTLR 4.6
import Antlr4
/**
* This class provides an empty implementation of {@link HelloVisitor},
* which can be extended to create a visitor which only needs to handle a subset
* of the available methods.
*
* @param <T> The return type of the visit operation. Use {@link Void} for
* operations with no return type.
*/
open class HelloBaseVisitor<T>: AbstractParseTreeVisitor<T> {
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
open func visitR(_ ctx: HelloParser.RContext) -> T? { return visitChildren(ctx) }
}

View File

@ -1,84 +0,0 @@
// Generated from Hello.g4 by ANTLR 4.6
import Antlr4
open class HelloLexer: Lexer {
internal static var _decisionToDFA: [DFA] = {
var decisionToDFA = [DFA]()
let length = HelloLexer._ATN.getNumberOfDecisions()
for i in 0..<length {
decisionToDFA.append(DFA(HelloLexer._ATN.getDecisionState(i)!, i))
}
return decisionToDFA
}()
internal static let _sharedContextCache:PredictionContextCache = PredictionContextCache()
public static let T__0=1, ID=2, WS=3
public static let modeNames: [String] = [
"DEFAULT_MODE"
]
public static let ruleNames: [String] = [
"T__0", "ID", "WS"
]
private static let _LITERAL_NAMES: [String?] = [
nil, "'hello'"
]
private static let _SYMBOLIC_NAMES: [String?] = [
nil, nil, "ID", "WS"
]
public static let VOCABULARY: Vocabulary = Vocabulary(_LITERAL_NAMES, _SYMBOLIC_NAMES)
/**
* @deprecated Use {@link #VOCABULARY} instead.
*/
//@Deprecated
public let tokenNames: [String?]? = {
let length = _SYMBOLIC_NAMES.count
var tokenNames = [String?](repeating: nil, count: length)
for i in 0..<length {
var name = VOCABULARY.getLiteralName(i)
if name == nil {
name = VOCABULARY.getSymbolicName(i)
}
if name == nil {
name = "<INVALID>"
}
tokenNames[i] = name
}
return tokenNames
}()
override
open func getTokenNames() -> [String?]? {
return tokenNames
}
open override func getVocabulary() -> Vocabulary {
return HelloLexer.VOCABULARY
}
public override init(_ input: CharStream) {
RuntimeMetaData.checkVersion("4.6", RuntimeMetaData.VERSION)
super.init(input)
_interp = LexerATNSimulator(self, HelloLexer._ATN, HelloLexer._decisionToDFA, HelloLexer._sharedContextCache)
}
override
open func getGrammarFileName() -> String { return "Hello.g4" }
override
open func getRuleNames() -> [String] { return HelloLexer.ruleNames }
override
open func getSerializedATN() -> String { return HelloLexer._serializedATN }
override
open func getModeNames() -> [String] { return HelloLexer.modeNames }
override
open func getATN() -> ATN { return HelloLexer._ATN }
public static let _serializedATN: String = HelloLexerATN().jsonString
public static let _ATN: ATN = ATNDeserializer().deserializeFromJson(_serializedATN)
}

View File

@ -1,4 +0,0 @@
T__0=1
ID=2
WS=3
'hello'=1

View File

@ -1,3 +0,0 @@
class HelloLexerATN {
let jsonString: String = "{\"version\":3,\"uuid\":\"aadb8d7e-aeef-4415-ad2b-8204d6cf042e\",\"grammarType\":0,\"maxTokenType\":3,\"states\":[{\"stateType\":6,\"ruleIndex\":-1},{\"stateType\":2,\"ruleIndex\":0},{\"stateType\":7,\"ruleIndex\":0},{\"stateType\":2,\"ruleIndex\":1},{\"stateType\":7,\"ruleIndex\":1},{\"stateType\":2,\"ruleIndex\":2},{\"stateType\":7,\"ruleIndex\":2},{\"stateType\":1,\"ruleIndex\":0},{\"stateType\":1,\"ruleIndex\":0},{\"stateType\":1,\"ruleIndex\":0},{\"stateType\":1,\"ruleIndex\":0},{\"stateType\":1,\"ruleIndex\":0},{\"stateType\":1,\"ruleIndex\":0},{\"stateType\":1,\"ruleIndex\":1},{\"stateType\":4,\"ruleIndex\":1,\"detailStateNumber\":15},{\"stateType\":8,\"ruleIndex\":1},{\"stateType\":11,\"ruleIndex\":1},{\"stateType\":12,\"ruleIndex\":1,\"detailStateNumber\":16},{\"stateType\":1,\"ruleIndex\":2},{\"stateType\":4,\"ruleIndex\":2,\"detailStateNumber\":20},{\"stateType\":8,\"ruleIndex\":2},{\"stateType\":11,\"ruleIndex\":2},{\"stateType\":12,\"ruleIndex\":2,\"detailStateNumber\":21},{\"stateType\":1,\"ruleIndex\":2},{\"stateType\":1,\"ruleIndex\":2}],\"nonGreedyStates\":[],\"precedenceStates\":[],\"ruleToStartState\":[{\"stateNumber\":1,\"ruleToTokenType\":1},{\"stateNumber\":3,\"ruleToTokenType\":2},{\"stateNumber\":5,\"ruleToTokenType\":3}],\"modeToStartState\":[0],\"nsets\":2,\"IntervalSet\":[{\"size\":1,\"containsEof\":0,\"Intervals\":[{\"a\":97,\"b\":122}]},{\"size\":3,\"containsEof\":0,\"Intervals\":[{\"a\":9,\"b\":10},{\"a\":13,\"b\":13},{\"a\":32,\"b\":32}]}],\"allTransitionsBuilder\":[[{\"src\":0,\"trg\":1,\"edgeType\":1,\"arg1\":0,\"arg2\":0,\"arg3\":0},{\"src\":0,\"trg\":3,\"edgeType\":1,\"arg1\":0,\"arg2\":0,\"arg3\":0},{\"src\":0,\"trg\":5,\"edgeType\":1,\"arg1\":0,\"arg2\":0,\"arg3\":0}],[{\"src\":1,\"trg\":7,\"edgeType\":1,\"arg1\":0,\"arg2\":0,\"arg3\":0}],[{\"src\":3,\"trg\":14,\"edgeType\":1,\"arg1\":0,\"arg2\":0,\"arg3\":0}],[{\"src\":5,\"trg\":19,\"edgeType\":1,\"arg1\":0,\"arg2\":0,\"arg3\":0}],[{\"src\":7,\"trg\":8,\"edgeType\":5,\"arg1\":104,\"arg2\":0,\"arg3\":0}],[{\"src\":8,\"trg\":9,\"edgeType\":5,\"arg1\":101,\"arg2\":0,\"arg3\":0}],[{\"src\":9,\"trg\":10,\"edgeType\":5,\"arg1\":108,\"arg2\":0,\"arg3\":0}],[{\"src\":10,\"trg\":11,\"edgeType\":5,\"arg1\":108,\"arg2\":0,\"arg3\":0}],[{\"src\":11,\"trg\":12,\"edgeType\":5,\"arg1\":111,\"arg2\":0,\"arg3\":0}],[{\"src\":12,\"trg\":2,\"edgeType\":1,\"arg1\":0,\"arg2\":0,\"arg3\":0}],[{\"src\":13,\"trg\":15,\"edgeType\":7,\"arg1\":0,\"arg2\":0,\"arg3\":0}],[{\"src\":14,\"trg\":13,\"edgeType\":1,\"arg1\":0,\"arg2\":0,\"arg3\":0}],[{\"src\":15,\"trg\":16,\"edgeType\":1,\"arg1\":0,\"arg2\":0,\"arg3\":0}],[{\"src\":16,\"trg\":14,\"edgeType\":1,\"arg1\":0,\"arg2\":0,\"arg3\":0},{\"src\":16,\"trg\":17,\"edgeType\":1,\"arg1\":0,\"arg2\":0,\"arg3\":0}],[{\"src\":17,\"trg\":4,\"edgeType\":1,\"arg1\":0,\"arg2\":0,\"arg3\":0}],[{\"src\":18,\"trg\":20,\"edgeType\":7,\"arg1\":1,\"arg2\":0,\"arg3\":0}],[{\"src\":19,\"trg\":18,\"edgeType\":1,\"arg1\":0,\"arg2\":0,\"arg3\":0}],[{\"src\":20,\"trg\":21,\"edgeType\":1,\"arg1\":0,\"arg2\":0,\"arg3\":0}],[{\"src\":21,\"trg\":19,\"edgeType\":1,\"arg1\":0,\"arg2\":0,\"arg3\":0},{\"src\":21,\"trg\":22,\"edgeType\":1,\"arg1\":0,\"arg2\":0,\"arg3\":0}],[{\"src\":22,\"trg\":23,\"edgeType\":1,\"arg1\":0,\"arg2\":0,\"arg3\":0}],[{\"src\":23,\"trg\":24,\"edgeType\":6,\"arg1\":2,\"arg2\":0,\"arg3\":0}],[{\"src\":24,\"trg\":6,\"edgeType\":1,\"arg1\":0,\"arg2\":0,\"arg3\":0}]],\"decisionToState\":[0,16,21],\"lexerActions\":[{\"actionType\":6,\"a\":0,\"b\":0}]}"
}

View File

@ -1,21 +0,0 @@
// Generated from Hello.g4 by ANTLR 4.6
import Antlr4
/**
* This interface defines a complete listener for a parse tree produced by
* {@link HelloParser}.
*/
public protocol HelloListener: ParseTreeListener {
/**
* Enter a parse tree produced by {@link HelloParser#r}.
- Parameters:
- ctx: the parse tree
*/
func enterR(_ ctx: HelloParser.RContext)
/**
* Exit a parse tree produced by {@link HelloParser#r}.
- Parameters:
- ctx: the parse tree
*/
func exitR(_ ctx: HelloParser.RContext)
}

View File

@ -1,130 +0,0 @@
// Generated from Hello.g4 by ANTLR 4.6
import Antlr4
open class HelloParser: Parser {
internal static var _decisionToDFA: [DFA] = {
var decisionToDFA = [DFA]()
let length = HelloParser._ATN.getNumberOfDecisions()
for i in 0..<length {
decisionToDFA.append(DFA(HelloParser._ATN.getDecisionState(i)!, i))
}
return decisionToDFA
}()
internal static let _sharedContextCache: PredictionContextCache = PredictionContextCache()
public enum Tokens: Int {
case EOF = -1, T__0 = 1, ID = 2, WS = 3
}
public static let RULE_r = 0
public static let ruleNames: [String] = [
"r"
]
private static let _LITERAL_NAMES: [String?] = [
nil, "'hello'"
]
private static let _SYMBOLIC_NAMES: [String?] = [
nil, nil, "ID", "WS"
]
public static let VOCABULARY: Vocabulary = Vocabulary(_LITERAL_NAMES, _SYMBOLIC_NAMES)
/**
* @deprecated Use {@link #VOCABULARY} instead.
*/
//@Deprecated
public let tokenNames: [String?]? = {
let length = _SYMBOLIC_NAMES.count
var tokenNames = [String?](repeating: nil, count: length)
for i in 0..<length {
var name = VOCABULARY.getLiteralName(i)
if name == nil {
name = VOCABULARY.getSymbolicName(i)
}
if name == nil {
name = "<INVALID>"
}
tokenNames[i] = name
}
return tokenNames
}()
override
open func getTokenNames() -> [String?]? {
return tokenNames
}
override
open func getGrammarFileName() -> String { return "Hello.g4" }
override
open func getRuleNames() -> [String] { return HelloParser.ruleNames }
override
open func getSerializedATN() -> String { return HelloParser._serializedATN }
override
open func getATN() -> ATN { return HelloParser._ATN }
open override func getVocabulary() -> Vocabulary {
return HelloParser.VOCABULARY
}
public override init(_ input:TokenStream)throws {
RuntimeMetaData.checkVersion("4.6", RuntimeMetaData.VERSION)
try super.init(input)
_interp = ParserATNSimulator(self,HelloParser._ATN,HelloParser._decisionToDFA, HelloParser._sharedContextCache)
}
open class RContext:ParserRuleContext {
open func ID() -> TerminalNode? { return getToken(HelloParser.Tokens.ID.rawValue, 0) }
open override func getRuleIndex() -> Int { return HelloParser.RULE_r }
override
open func enterRule(_ listener: ParseTreeListener) {
if listener is HelloListener {
(listener as! HelloListener).enterR(self)
}
}
override
open func exitRule(_ listener: ParseTreeListener) {
if listener is HelloListener {
(listener as! HelloListener).exitR(self)
}
}
override
open func accept<T>(_ visitor: ParseTreeVisitor<T>) -> T? {
if visitor is HelloVisitor {
return (visitor as! HelloVisitor<T>).visitR(self)
}else if visitor is HelloBaseVisitor {
return (visitor as! HelloBaseVisitor<T>).visitR(self)
}
else {
return visitor.visitChildren(self)
}
}
}
@discardableResult
open func r() throws -> RContext {
var _localctx: RContext = RContext(_ctx, getState())
try enterRule(_localctx, 0, HelloParser.RULE_r)
defer {
try! exitRule()
}
do {
try enterOuterAlt(_localctx, 1)
setState(2)
try match(HelloParser.Tokens.T__0.rawValue)
setState(3)
try match(HelloParser.Tokens.ID.rawValue)
}
catch ANTLRException.recognition(let re) {
_localctx.exception = re
_errHandler.reportError(self, re)
try _errHandler.recover(self, re)
}
return _localctx
}
public static let _serializedATN : String = HelloParserATN().jsonString
public static let _ATN: ATN = ATNDeserializer().deserializeFromJson(_serializedATN)
}

View File

@ -1,3 +0,0 @@
class HelloParserATN {
let jsonString: String = "{\"version\":3,\"uuid\":\"aadb8d7e-aeef-4415-ad2b-8204d6cf042e\",\"grammarType\":1,\"maxTokenType\":3,\"states\":[{\"stateType\":2,\"ruleIndex\":0},{\"stateType\":7,\"ruleIndex\":0},{\"stateType\":1,\"ruleIndex\":0},{\"stateType\":1,\"ruleIndex\":0},{\"stateType\":1,\"ruleIndex\":0},{\"stateType\":1,\"ruleIndex\":0}],\"nonGreedyStates\":[],\"precedenceStates\":[],\"ruleToStartState\":[{\"stateNumber\":0}],\"modeToStartState\":[],\"nsets\":0,\"IntervalSet\":[],\"allTransitionsBuilder\":[[{\"src\":0,\"trg\":2,\"edgeType\":1,\"arg1\":0,\"arg2\":0,\"arg3\":0}],[{\"src\":2,\"trg\":3,\"edgeType\":5,\"arg1\":1,\"arg2\":0,\"arg3\":0}],[{\"src\":3,\"trg\":4,\"edgeType\":5,\"arg1\":2,\"arg2\":0,\"arg3\":0}],[{\"src\":4,\"trg\":1,\"edgeType\":1,\"arg1\":0,\"arg2\":0,\"arg3\":0}],[]],\"decisionToState\":[],\"lexerActions\":[]}"
}

View File

@ -1,22 +0,0 @@
// Generated from Hello.g4 by ANTLR 4.6
import Antlr4
/**
* This interface defines a complete generic visitor for a parse tree produced
* by {@link HelloParser}.
*
* @param <T> The return type of the visit operation. Use {@link Void} for
* operations with no return type.
*/
open class HelloVisitor<T>: ParseTreeVisitor<T> {
/**
* Visit a parse tree produced by {@link HelloParser#r}.
- Parameters:
- ctx: the parse tree
- returns: the visitor result
*/
open func visitR(_ ctx: HelloParser.RContext) -> T{
fatalError(#function + " must be overridden")
}
}

View File

@ -1,18 +0,0 @@
import Antlr4
public class HelloWalker: HelloBaseListener {
public override func enterR(_ ctx: HelloParser.RContext) {
print("enterR: \(ctx.IDText())")
}
public override func exitR(_ ctx: HelloParser.RContext) {
print("exitR: \(ctx.IDText())")
}
}
fileprivate extension HelloParser.RContext {
fileprivate func IDText() -> String {
return ID()?.getText() ?? ""
}
}

View File

@ -1,4 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='5.0' target-platform='macos'>
<timeline fileName='timeline.xctimeline'/>
</playground>

View File

@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:">
</FileRef>
</Workspace>

View File

@ -4,7 +4,4 @@
<FileRef <FileRef
location = "container:Antlr4.xcodeproj"> location = "container:Antlr4.xcodeproj">
</FileRef> </FileRef>
<FileRef
location = "container:Antlr4 playground.playground">
</FileRef>
</Workspace> </Workspace>

View File

@ -1,43 +1,40 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/ /// How to emit recognition errors.
/** How to emit recognition errors. */
public protocol ANTLRErrorListener: class { public protocol ANTLRErrorListener: class {
/** /// Upon syntax error, notify any interested parties. This is not how to
* Upon syntax error, notify any interested parties. This is not how to /// recover from errors or compute error messages. {@link org.antlr.v4.runtime.ANTLRErrorStrategy}
* recover from errors or compute error messages. {@link org.antlr.v4.runtime.ANTLRErrorStrategy} /// specifies how to recover from syntax errors and how to compute error
* specifies how to recover from syntax errors and how to compute error /// messages. This listener's job is simply to emit a computed message,
* messages. This listener's job is simply to emit a computed message, /// though it has enough information to create its own message in many cases.
* though it has enough information to create its own message in many cases. ///
* /// <p>The {@link org.antlr.v4.runtime.RecognitionException} is non-null for all syntax errors except
* <p>The {@link org.antlr.v4.runtime.RecognitionException} is non-null for all syntax errors except /// when we discover mismatched token errors that we can recover from
* when we discover mismatched token errors that we can recover from /// in-line, without returning from the surrounding rule (via the single
* in-line, without returning from the surrounding rule (via the single /// token insertion and deletion mechanism).</p>
* token insertion and deletion mechanism).</p> ///
* /// - parameter recognizer:
* @param recognizer /// What parser got the error. From this
* What parser got the error. From this /// object, you can access the context as well
* object, you can access the context as well /// as the input stream.
* as the input stream. /// - parameter offendingSymbol:
* @param offendingSymbol /// The offending token in the input token
* The offending token in the input token /// stream, unless recognizer is a lexer (then it's null). If
* stream, unless recognizer is a lexer (then it's null). If /// no viable alternative error, {@code e} has token at which we
* no viable alternative error, {@code e} has token at which we /// started production for the decision.
* started production for the decision. /// - parameter line:
* @param line /// The line number in the input where the error occurred.
* The line number in the input where the error occurred. /// - parameter charPositionInLine:
* @param charPositionInLine /// The character position within that line where the error occurred.
* The character position within that line where the error occurred. /// - parameter msg:
* @param msg /// The message to emit.
* The message to emit. /// - parameter e:
* @param e /// The exception generated by the parser that led to
* The exception generated by the parser that led to /// the reporting of an error. It is null in the case where
* the reporting of an error. It is null in the case where /// the parser was able to recover in line without exiting the
* the parser was able to recover in line without exiting the /// surrounding rule.
* surrounding rule.
*/
func syntaxError<T:ATNSimulator>(_ recognizer: Recognizer<T>, func syntaxError<T:ATNSimulator>(_ recognizer: Recognizer<T>,
_ offendingSymbol: AnyObject?, _ offendingSymbol: AnyObject?,
_ line: Int, _ line: Int,
@ -46,46 +43,44 @@ public protocol ANTLRErrorListener: class {
_ e: AnyObject?// RecognitionException? _ e: AnyObject?// RecognitionException?
) )
/** /// This method is called by the parser when a full-context prediction
* This method is called by the parser when a full-context prediction /// results in an ambiguity.
* results in an ambiguity. ///
* /// <p>Each full-context prediction which does not result in a syntax error
* <p>Each full-context prediction which does not result in a syntax error /// will call either {@link #reportContextSensitivity} or
* will call either {@link #reportContextSensitivity} or /// {@link #reportAmbiguity}.</p>
* {@link #reportAmbiguity}.</p> ///
* /// <p>When {@code ambigAlts} is not null, it contains the set of potentially
* <p>When {@code ambigAlts} is not null, it contains the set of potentially /// viable alternatives identified by the prediction algorithm. When
* viable alternatives identified by the prediction algorithm. When /// {@code ambigAlts} is null, use {@link org.antlr.v4.runtime.atn.ATNConfigSet#getAlts} to obtain the
* {@code ambigAlts} is null, use {@link org.antlr.v4.runtime.atn.ATNConfigSet#getAlts} to obtain the /// represented alternatives from the {@code configs} argument.</p>
* represented alternatives from the {@code configs} argument.</p> ///
* /// <p>When {@code exact} is {@code true}, <em>all</em> of the potentially
* <p>When {@code exact} is {@code true}, <em>all</em> of the potentially /// viable alternatives are truly viable, i.e. this is reporting an exact
* viable alternatives are truly viable, i.e. this is reporting an exact /// ambiguity. When {@code exact} is {@code false}, <em>at least two</em> of
* ambiguity. When {@code exact} is {@code false}, <em>at least two</em> of /// the potentially viable alternatives are viable for the current input, but
* the potentially viable alternatives are viable for the current input, but /// the prediction algorithm terminated as soon as it determined that at
* the prediction algorithm terminated as soon as it determined that at /// least the <em>minimum</em> potentially viable alternative is truly
* least the <em>minimum</em> potentially viable alternative is truly /// viable.</p>
* viable.</p> ///
* /// <p>When the {@link org.antlr.v4.runtime.atn.PredictionMode#LL_EXACT_AMBIG_DETECTION} prediction
* <p>When the {@link org.antlr.v4.runtime.atn.PredictionMode#LL_EXACT_AMBIG_DETECTION} prediction /// mode is used, the parser is required to identify exact ambiguities so
* mode is used, the parser is required to identify exact ambiguities so /// {@code exact} will always be {@code true}.</p>
* {@code exact} will always be {@code true}.</p> ///
* /// <p>This method is not used by lexers.</p>
* <p>This method is not used by lexers.</p> ///
* /// - parameter recognizer: the parser instance
* @param recognizer the parser instance /// - parameter dfa: the DFA for the current decision
* @param dfa the DFA for the current decision /// - parameter startIndex: the input index where the decision started
* @param startIndex the input index where the decision started /// - parameter stopIndex: the input input where the ambiguity was identified
* @param stopIndex the input input where the ambiguity was identified /// - parameter exact: {@code true} if the ambiguity is exactly known, otherwise
* @param exact {@code true} if the ambiguity is exactly known, otherwise /// {@code false}. This is always {@code true} when
* {@code false}. This is always {@code true} when /// {@link org.antlr.v4.runtime.atn.PredictionMode#LL_EXACT_AMBIG_DETECTION} is used.
* {@link org.antlr.v4.runtime.atn.PredictionMode#LL_EXACT_AMBIG_DETECTION} is used. /// - parameter ambigAlts: the potentially ambiguous alternatives, or {@code null}
* @param ambigAlts the potentially ambiguous alternatives, or {@code null} /// to indicate that the potentially ambiguous alternatives are the complete
* to indicate that the potentially ambiguous alternatives are the complete /// set of represented alternatives in {@code configs}
* set of represented alternatives in {@code configs} /// - parameter configs: the ATN configuration set where the ambiguity was
* @param configs the ATN configuration set where the ambiguity was /// identified
* identified
*/
func reportAmbiguity(_ recognizer: Parser, func reportAmbiguity(_ recognizer: Parser,
_ dfa: DFA, _ dfa: DFA,
_ startIndex: Int, _ startIndex: Int,
@ -94,29 +89,27 @@ public protocol ANTLRErrorListener: class {
_ ambigAlts: BitSet, _ ambigAlts: BitSet,
_ configs: ATNConfigSet) throws _ configs: ATNConfigSet) throws
/** /// This method is called when an SLL conflict occurs and the parser is about
* This method is called when an SLL conflict occurs and the parser is about /// to use the full context information to make an LL decision.
* to use the full context information to make an LL decision. ///
* /// <p>If one or more configurations in {@code configs} contains a semantic
* <p>If one or more configurations in {@code configs} contains a semantic /// predicate, the predicates are evaluated before this method is called. The
* predicate, the predicates are evaluated before this method is called. The /// subset of alternatives which are still viable after predicates are
* subset of alternatives which are still viable after predicates are /// evaluated is reported in {@code conflictingAlts}.</p>
* evaluated is reported in {@code conflictingAlts}.</p> ///
* /// <p>This method is not used by lexers.</p>
* <p>This method is not used by lexers.</p> ///
* /// - parameter recognizer: the parser instance
* @param recognizer the parser instance /// - parameter dfa: the DFA for the current decision
* @param dfa the DFA for the current decision /// - parameter startIndex: the input index where the decision started
* @param startIndex the input index where the decision started /// - parameter stopIndex: the input index where the SLL conflict occurred
* @param stopIndex the input index where the SLL conflict occurred /// - parameter conflictingAlts: The specific conflicting alternatives. If this is
* @param conflictingAlts The specific conflicting alternatives. If this is /// {@code null}, the conflicting alternatives are all alternatives
* {@code null}, the conflicting alternatives are all alternatives /// represented in {@code configs}. At the moment, conflictingAlts is non-null
* represented in {@code configs}. At the moment, conflictingAlts is non-null /// (for the reference implementation, but Sam's optimized version can see this
* (for the reference implementation, but Sam's optimized version can see this /// as null).
* as null). /// - parameter configs: the ATN configuration set where the SLL conflict was
* @param configs the ATN configuration set where the SLL conflict was /// detected
* detected
*/
func reportAttemptingFullContext(_ recognizer: Parser, func reportAttemptingFullContext(_ recognizer: Parser,
_ dfa: DFA, _ dfa: DFA,
_ startIndex: Int, _ startIndex: Int,
@ -124,44 +117,42 @@ public protocol ANTLRErrorListener: class {
_ conflictingAlts: BitSet?, _ conflictingAlts: BitSet?,
_ configs: ATNConfigSet) throws _ configs: ATNConfigSet) throws
/** /// This method is called by the parser when a full-context prediction has a
* This method is called by the parser when a full-context prediction has a /// unique result.
* unique result. ///
* /// <p>Each full-context prediction which does not result in a syntax error
* <p>Each full-context prediction which does not result in a syntax error /// will call either {@link #reportContextSensitivity} or
* will call either {@link #reportContextSensitivity} or /// {@link #reportAmbiguity}.</p>
* {@link #reportAmbiguity}.</p> ///
* /// <p>For prediction implementations that only evaluate full-context
* <p>For prediction implementations that only evaluate full-context /// predictions when an SLL conflict is found (including the default
* predictions when an SLL conflict is found (including the default /// {@link org.antlr.v4.runtime.atn.ParserATNSimulator} implementation), this method reports cases
* {@link org.antlr.v4.runtime.atn.ParserATNSimulator} implementation), this method reports cases /// where SLL conflicts were resolved to unique full-context predictions,
* where SLL conflicts were resolved to unique full-context predictions, /// i.e. the decision was context-sensitive. This report does not necessarily
* i.e. the decision was context-sensitive. This report does not necessarily /// indicate a problem, and it may appear even in completely unambiguous
* indicate a problem, and it may appear even in completely unambiguous /// grammars.</p>
* grammars.</p> ///
* /// <p>{@code configs} may have more than one represented alternative if the
* <p>{@code configs} may have more than one represented alternative if the /// full-context prediction algorithm does not evaluate predicates before
* full-context prediction algorithm does not evaluate predicates before /// beginning the full-context prediction. In all cases, the final prediction
* beginning the full-context prediction. In all cases, the final prediction /// is passed as the {@code prediction} argument.</p>
* is passed as the {@code prediction} argument.</p> ///
* /// <p>Note that the definition of "context sensitivity" in this method
* <p>Note that the definition of "context sensitivity" in this method /// differs from the concept in {@link org.antlr.v4.runtime.atn.DecisionInfo#contextSensitivities}.
* differs from the concept in {@link org.antlr.v4.runtime.atn.DecisionInfo#contextSensitivities}. /// This method reports all instances where an SLL conflict occurred but LL
* This method reports all instances where an SLL conflict occurred but LL /// parsing produced a unique result, whether or not that unique result
* parsing produced a unique result, whether or not that unique result /// matches the minimum alternative in the SLL conflicting set.</p>
* matches the minimum alternative in the SLL conflicting set.</p> ///
* /// <p>This method is not used by lexers.</p>
* <p>This method is not used by lexers.</p> ///
* /// - parameter recognizer: the parser instance
* @param recognizer the parser instance /// - parameter dfa: the DFA for the current decision
* @param dfa the DFA for the current decision /// - parameter startIndex: the input index where the decision started
* @param startIndex the input index where the decision started /// - parameter stopIndex: the input index where the context sensitivity was
* @param stopIndex the input index where the context sensitivity was /// finally determined
* finally determined /// - parameter prediction: the unambiguous result of the full-context prediction
* @param prediction the unambiguous result of the full-context prediction /// - parameter configs: the ATN configuration set where the unambiguous prediction
* @param configs the ATN configuration set where the unambiguous prediction /// was determined
* was determined
*/
func reportContextSensitivity(_ recognizer: Parser, func reportContextSensitivity(_ recognizer: Parser,
_ dfa: DFA, _ dfa: DFA,
_ startIndex: Int, _ startIndex: Int,

View File

@ -1,115 +1,98 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/ /// The interface for defining strategies to deal with syntax errors encountered
/** /// during a parse by ANTLR-generated parsers. We distinguish between three
* The interface for defining strategies to deal with syntax errors encountered /// different kinds of errors:
* during a parse by ANTLR-generated parsers. We distinguish between three ///
* different kinds of errors: /// <ul>
* /// <li>The parser could not figure out which path to take in the ATN (none of
* <ul> /// the available alternatives could possibly match)</li>
* <li>The parser could not figure out which path to take in the ATN (none of /// <li>The current input does not match what we were looking for</li>
* the available alternatives could possibly match)</li> /// <li>A predicate evaluated to false</li>
* <li>The current input does not match what we were looking for</li> /// </ul>
* <li>A predicate evaluated to false</li> ///
* </ul> /// Implementations of this interface report syntax errors by calling
* /// {@link org.antlr.v4.runtime.Parser#notifyErrorListeners}.
* Implementations of this interface report syntax errors by calling ///
* {@link org.antlr.v4.runtime.Parser#notifyErrorListeners}. /// <p>TODO: what to do about lexers</p>
*
* <p>TODO: what to do about lexers</p>
*/
public protocol ANTLRErrorStrategy { public protocol ANTLRErrorStrategy {
/** /// Reset the error handler state for the specified {@code recognizer}.
* Reset the error handler state for the specified {@code recognizer}. /// - parameter recognizer: the parser instance
* @param recognizer the parser instance
*/
func reset(_ recognizer: Parser) func reset(_ recognizer: Parser)
/** /// This method is called when an unexpected symbol is encountered during an
* This method is called when an unexpected symbol is encountered during an /// inline match operation, such as {@link org.antlr.v4.runtime.Parser#match}. If the error
* inline match operation, such as {@link org.antlr.v4.runtime.Parser#match}. If the error /// strategy successfully recovers from the match failure, this method
* strategy successfully recovers from the match failure, this method /// returns the {@link org.antlr.v4.runtime.Token} instance which should be treated as the
* returns the {@link org.antlr.v4.runtime.Token} instance which should be treated as the /// successful result of the match.
* successful result of the match. ///
* /// <p>This method handles the consumption of any tokens - the caller should
* <p>This method handles the consumption of any tokens - the caller should /// <b>not</b> call {@link org.antlr.v4.runtime.Parser#consume} after a successful recovery.</p>
* <b>not</b> call {@link org.antlr.v4.runtime.Parser#consume} after a successful recovery.</p> ///
* /// <p>Note that the calling code will not report an error if this method
* <p>Note that the calling code will not report an error if this method /// returns successfully. The error strategy implementation is responsible
* returns successfully. The error strategy implementation is responsible /// for calling {@link org.antlr.v4.runtime.Parser#notifyErrorListeners} as appropriate.</p>
* for calling {@link org.antlr.v4.runtime.Parser#notifyErrorListeners} as appropriate.</p> ///
* /// - parameter recognizer: the parser instance
* @param recognizer the parser instance /// - org.antlr.v4.runtime.RecognitionException if the error strategy was not able to
* @throws org.antlr.v4.runtime.RecognitionException if the error strategy was not able to /// recover from the unexpected input symbol
* recover from the unexpected input symbol
*/
@discardableResult @discardableResult
func recoverInline(_ recognizer: Parser) throws -> Token // RecognitionException; func recoverInline(_ recognizer: Parser) throws -> Token // RecognitionException;
/** /// This method is called to recover from exception {@code e}. This method is
* This method is called to recover from exception {@code e}. This method is /// called after {@link #reportError} by the default exception handler
* called after {@link #reportError} by the default exception handler /// generated for a rule method.
* generated for a rule method. ///
* /// - seealso: #reportError
* @see #reportError ///
* /// - parameter recognizer: the parser instance
* @param recognizer the parser instance /// - parameter e: the recognition exception to recover from
* @param e the recognition exception to recover from /// - org.antlr.v4.runtime.RecognitionException if the error strategy could not recover from
* @throws org.antlr.v4.runtime.RecognitionException if the error strategy could not recover from /// the recognition exception
* the recognition exception
*/
func recover(_ recognizer: Parser, _ e: AnyObject) throws // RecognitionException; func recover(_ recognizer: Parser, _ e: AnyObject) throws // RecognitionException;
/** /// This method provides the error handler with an opportunity to handle
* This method provides the error handler with an opportunity to handle /// syntactic or semantic errors in the input stream before they result in a
* syntactic or semantic errors in the input stream before they result in a /// {@link org.antlr.v4.runtime.RecognitionException}.
* {@link org.antlr.v4.runtime.RecognitionException}. ///
* /// <p>The generated code currently contains calls to {@link #sync} after
* <p>The generated code currently contains calls to {@link #sync} after /// entering the decision state of a closure block ({@code (...)*} or
* entering the decision state of a closure block ({@code (...)*} or /// {@code (...)+}).</p>
* {@code (...)+}).</p> ///
* /// <p>For an implementation based on Jim Idle's "magic sync" mechanism, see
* <p>For an implementation based on Jim Idle's "magic sync" mechanism, see /// {@link org.antlr.v4.runtime.DefaultErrorStrategy#sync}.</p>
* {@link org.antlr.v4.runtime.DefaultErrorStrategy#sync}.</p> ///
* /// - seealso: org.antlr.v4.runtime.DefaultErrorStrategy#sync
* @see org.antlr.v4.runtime.DefaultErrorStrategy#sync ///
* /// - parameter recognizer: the parser instance
* @param recognizer the parser instance /// - org.antlr.v4.runtime.RecognitionException if an error is detected by the error
* @throws org.antlr.v4.runtime.RecognitionException if an error is detected by the error /// strategy but cannot be automatically recovered at the current state in
* strategy but cannot be automatically recovered at the current state in /// the parsing process
* the parsing process
*/
func sync(_ recognizer: Parser) throws // RecognitionException; func sync(_ recognizer: Parser) throws // RecognitionException;
/** /// Tests whether or not {@code recognizer} is in the process of recovering
* Tests whether or not {@code recognizer} is in the process of recovering /// from an error. In error recovery mode, {@link org.antlr.v4.runtime.Parser#consume} adds
* from an error. In error recovery mode, {@link org.antlr.v4.runtime.Parser#consume} adds /// symbols to the parse tree by calling
* symbols to the parse tree by calling /// {@link org.antlr.v4.runtime.ParserRuleContext#addErrorNode(org.antlr.v4.runtime.Token)} instead of
* {@link org.antlr.v4.runtime.ParserRuleContext#addErrorNode(org.antlr.v4.runtime.Token)} instead of /// {@link org.antlr.v4.runtime.ParserRuleContext#addChild(org.antlr.v4.runtime.Token)}.
* {@link org.antlr.v4.runtime.ParserRuleContext#addChild(org.antlr.v4.runtime.Token)}. ///
* /// - parameter recognizer: the parser instance
* @param recognizer the parser instance /// - returns: {@code true} if the parser is currently recovering from a parse
* @return {@code true} if the parser is currently recovering from a parse /// error, otherwise {@code false}
* error, otherwise {@code false}
*/
func inErrorRecoveryMode(_ recognizer: Parser) -> Bool func inErrorRecoveryMode(_ recognizer: Parser) -> Bool
/** /// This method is called by when the parser successfully matches an input
* This method is called by when the parser successfully matches an input /// symbol.
* symbol. ///
* /// - parameter recognizer: the parser instance
* @param recognizer the parser instance
*/
func reportMatch(_ recognizer: Parser) func reportMatch(_ recognizer: Parser)
/** /// Report any kind of {@link org.antlr.v4.runtime.RecognitionException}. This method is called by
* Report any kind of {@link org.antlr.v4.runtime.RecognitionException}. This method is called by /// the default exception handler generated for a rule method.
* the default exception handler generated for a rule method. ///
* /// - parameter recognizer: the parser instance
* @param recognizer the parser instance /// - parameter e: the recognition exception to report
* @param e the recognition exception to report
*/
func reportError(_ recognizer: Parser, _ e: AnyObject) func reportError(_ recognizer: Parser, _ e: AnyObject)
} }

View File

@ -1,11 +1,8 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/ /// This is an {@link org.antlr.v4.runtime.ANTLRInputStream} that is loaded from a file all at once
/** /// when you construct the object.
* This is an {@link org.antlr.v4.runtime.ANTLRInputStream} that is loaded from a file all at once
* when you construct the object.
*/
import Foundation import Foundation

View File

@ -1,29 +1,26 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/ /// Vacuum all input from a {@link java.io.Reader}/{@link java.io.InputStream} and then treat it
/** /// like a {@code char[]} buffer. Can also pass in a {@link String} or
* Vacuum all input from a {@link java.io.Reader}/{@link java.io.InputStream} and then treat it /// {@code char[]} to use.
* like a {@code char[]} buffer. Can also pass in a {@link String} or ///
* {@code char[]} to use. /// <p>If you need encoding, pass in stream/reader with correct encoding.</p>
*
* <p>If you need encoding, pass in stream/reader with correct encoding.</p>
*/
public class ANTLRInputStream: CharStream { public class ANTLRInputStream: CharStream {
public static let READ_BUFFER_SIZE: Int = 1024 public static let READ_BUFFER_SIZE: Int = 1024
public static let INITIAL_BUFFER_SIZE: Int = 1024 public static let INITIAL_BUFFER_SIZE: Int = 1024
/** The data being scanned */ /// The data being scanned
internal var data: [Character] internal var data: [Character]
/** How many characters are actually in the buffer */ /// How many characters are actually in the buffer
internal var n: Int internal var n: Int
/** 0..n-1 index into string of next char */ /// 0..n-1 index into string of next char
internal var p: Int = 0 internal var p: Int = 0
/** What is name or source of this char stream? */ /// What is name or source of this char stream?
public var name: String? public var name: String?
public init() { public init() {
@ -31,84 +28,81 @@ public class ANTLRInputStream: CharStream {
data = [Character]() data = [Character]()
} }
/** Copy data in string to a local char array */ /// Copy data in string to a local char array
public init(_ input: String) { public init(_ input: String) {
self.data = Array(input.characters) // input.toCharArray(); self.data = Array(input.characters) // input.toCharArray();
self.n = input.length self.n = input.length
} }
/** This is the preferred constructor for strings as no data is copied */ /// This is the preferred constructor for strings as no data is copied
public init(_ data: [Character], _ numberOfActualCharsInArray: Int) { public init(_ data: [Character], _ numberOfActualCharsInArray: Int) {
self.data = data self.data = data
self.n = numberOfActualCharsInArray self.n = numberOfActualCharsInArray
} }
/* /// public convenience init(_ r : Reader) throws; IOException {
public convenience init(_ r : Reader) throws; IOException { /// self.init(r, INITIAL_BUFFER_SIZE, READ_BUFFER_SIZE);
self.init(r, INITIAL_BUFFER_SIZE, READ_BUFFER_SIZE); /// }
} ///
/// public convenience init(_ r : Reader, _ initialSize : Int) throws; IOException {
public convenience init(_ r : Reader, _ initialSize : Int) throws; IOException { /// self.init(r, initialSize, READ_BUFFER_SIZE);
self.init(r, initialSize, READ_BUFFER_SIZE); /// }
} ///
/// public init(_ r : Reader, _ initialSize : Int, _ readChunkSize : Int) throws; IOException {
public init(_ r : Reader, _ initialSize : Int, _ readChunkSize : Int) throws; IOException { /// load(r, initialSize, readChunkSize);
load(r, initialSize, readChunkSize); /// }
} ///
/// public convenience init(_ input : InputStream) throws; IOException {
public convenience init(_ input : InputStream) throws; IOException { /// self.init(InputStreamReader(input), INITIAL_BUFFER_SIZE);
self.init(InputStreamReader(input), INITIAL_BUFFER_SIZE); /// }
} ///
/// public convenience init(_ input : InputStream, _ initialSize : Int) throws; IOException {
public convenience init(_ input : InputStream, _ initialSize : Int) throws; IOException { /// self.init(InputStreamReader(input), initialSize);
self.init(InputStreamReader(input), initialSize); /// }
} ///
/// public convenience init(_ input : InputStream, _ initialSize : Int, _ readChunkSize : Int) throws; IOException {
public convenience init(_ input : InputStream, _ initialSize : Int, _ readChunkSize : Int) throws; IOException { /// self.init(InputStreamReader(input), initialSize, readChunkSize);
self.init(InputStreamReader(input), initialSize, readChunkSize); /// }
} ///
/// public func load(r : Reader, _ size : Int, _ readChunkSize : Int)
public func load(r : Reader, _ size : Int, _ readChunkSize : Int) /// throws; IOException
throws; IOException /// {
{ /// if ( r==nil ) {
if ( r==nil ) { /// return;
return; /// }
} /// if ( size<=0 ) {
if ( size<=0 ) { /// size = INITIAL_BUFFER_SIZE;
size = INITIAL_BUFFER_SIZE; /// }
} /// if ( readChunkSize<=0 ) {
if ( readChunkSize<=0 ) { /// readChunkSize = READ_BUFFER_SIZE;
readChunkSize = READ_BUFFER_SIZE; /// }
} /// // print("load "+size+" in chunks of "+readChunkSize);
// print("load "+size+" in chunks of "+readChunkSize); /// try {
try { /// // alloc initial buffer size.
// alloc initial buffer size. /// data = new char[size];
data = new char[size]; /// // read all the data in chunks of readChunkSize
// read all the data in chunks of readChunkSize /// var numRead : Int=0;
var numRead : Int=0; /// var p : Int = 0;
var p : Int = 0; /// do {
do { /// if ( p+readChunkSize > data.length ) { // overflow?
if ( p+readChunkSize > data.length ) { // overflow? /// // print("### overflow p="+p+", data.length="+data.length);
// print("### overflow p="+p+", data.length="+data.length); /// data = Arrays.copyOf(data, data.length * 2);
data = Arrays.copyOf(data, data.length * 2); /// }
} /// numRead = r.read(data, p, readChunkSize);
numRead = r.read(data, p, readChunkSize); /// // print("read "+numRead+" chars; p was "+p+" is now "+(p+numRead));
// print("read "+numRead+" chars; p was "+p+" is now "+(p+numRead)); /// p += numRead;
p += numRead; /// } while (numRead!=-1); // while not EOF
} while (numRead!=-1); // while not EOF /// // set the actual size of the data available;
// set the actual size of the data available; /// // EOF subtracted one above in p+=numRead; add one back
// EOF subtracted one above in p+=numRead; add one back /// n = p+1;
n = p+1; /// //print("n="+n);
//print("n="+n); /// }
} /// finally {
finally { /// r.close();
r.close(); /// }
} /// }
} /// Reset the stream so that it's in the same state it was
*/ /// when the object was created *except* the data array is not
/** Reset the stream so that it's in the same state it was /// touched.
* when the object was created *except* the data array is not
* touched.
*/
public func reset() { public func reset() {
p = 0 p = 0
@ -156,10 +150,9 @@ public class ANTLRInputStream: CharStream {
return LA(i) return LA(i)
} }
/** Return the current input symbol index 0..n where n indicates the /// 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 /// last symbol has been read. The index is the index of char to
* be returned from LA(1). /// be returned from LA(1).
*/
public func index() -> Int { public func index() -> Int {
return p return p
} }
@ -168,7 +161,7 @@ public class ANTLRInputStream: CharStream {
return n return n
} }
/** mark/release do nothing; we have entire buffer */ /// mark/release do nothing; we have entire buffer
public func mark() -> Int { public func mark() -> Int {
return -1 return -1
@ -177,9 +170,8 @@ public class ANTLRInputStream: CharStream {
public func release(_ marker: Int) { public func release(_ marker: Int) {
} }
/** consume() ahead until p==index; can't just set p=index as we must /// 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 /// update line and charPositionInLine. If we seek backwards, just set p
*/
public func seek(_ index: Int) throws { public func seek(_ index: Int) throws {
var index = index var index = index

View File

@ -1,46 +1,42 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** /// This implementation of {@link org.antlr.v4.runtime.ANTLRErrorStrategy} responds to syntax errors
* This implementation of {@link org.antlr.v4.runtime.ANTLRErrorStrategy} responds to syntax errors /// by immediately canceling the parse operation with a
* by immediately canceling the parse operation with a /// {@link org.antlr.v4.runtime.misc.ParseCancellationException}. The implementation ensures that the
* {@link org.antlr.v4.runtime.misc.ParseCancellationException}. The implementation ensures that the /// {@link org.antlr.v4.runtime.ParserRuleContext#exception} field is set for all parse tree nodes
* {@link org.antlr.v4.runtime.ParserRuleContext#exception} field is set for all parse tree nodes /// that were not completed prior to encountering the error.
* that were not completed prior to encountering the error. ///
* /// <p>
* <p> /// This error strategy is useful in the following scenarios.</p>
* This error strategy is useful in the following scenarios.</p> ///
* /// <ul>
* <ul> /// <li><strong>Two-stage parsing:</strong> This error strategy allows the first
* <li><strong>Two-stage parsing:</strong> This error strategy allows the first /// stage of two-stage parsing to immediately terminate if an error is
* stage of two-stage parsing to immediately terminate if an error is /// encountered, and immediately fall back to the second stage. In addition to
* encountered, and immediately fall back to the second stage. In addition to /// avoiding wasted work by attempting to recover from errors here, the empty
* avoiding wasted work by attempting to recover from errors here, the empty /// implementation of {@link org.antlr.v4.runtime.BailErrorStrategy#sync} improves the performance of
* implementation of {@link org.antlr.v4.runtime.BailErrorStrategy#sync} improves the performance of /// the first stage.</li>
* the first stage.</li> /// <li><strong>Silent validation:</strong> When syntax errors are not being
* <li><strong>Silent validation:</strong> When syntax errors are not being /// reported or logged, and the parse result is simply ignored if errors occur,
* reported or logged, and the parse result is simply ignored if errors occur, /// the {@link org.antlr.v4.runtime.BailErrorStrategy} avoids wasting work on recovering from errors
* the {@link org.antlr.v4.runtime.BailErrorStrategy} avoids wasting work on recovering from errors /// when the result will be ignored either way.</li>
* when the result will be ignored either way.</li> /// </ul>
* </ul> ///
* /// <p>
* <p> /// {@code myparser.setErrorHandler(new BailErrorStrategy());}</p>
* {@code myparser.setErrorHandler(new BailErrorStrategy());}</p> ///
* /// - seealso: org.antlr.v4.runtime.Parser#setErrorHandler(org.antlr.v4.runtime.ANTLRErrorStrategy)
* @see org.antlr.v4.runtime.Parser#setErrorHandler(org.antlr.v4.runtime.ANTLRErrorStrategy)
*/
public class BailErrorStrategy: DefaultErrorStrategy { public class BailErrorStrategy: DefaultErrorStrategy {
public override init(){} public override init(){}
/** Instead of recovering from exception {@code e}, re-throw it wrapped /// Instead of recovering from exception {@code e}, re-throw it wrapped
* in a {@link org.antlr.v4.runtime.misc.ParseCancellationException} so it is not caught by the /// in a {@link org.antlr.v4.runtime.misc.ParseCancellationException} so it is not caught by the
* rule function catches. Use {@link Exception#getCause()} to get the /// rule function catches. Use {@link Exception#getCause()} to get the
* original {@link org.antlr.v4.runtime.RecognitionException}. /// original {@link org.antlr.v4.runtime.RecognitionException}.
*/
override override
public func recover(_ recognizer: Parser, _ e: AnyObject) throws { public func recover(_ recognizer: Parser, _ e: AnyObject) throws {
var context: ParserRuleContext? = recognizer.getContext() var context: ParserRuleContext? = recognizer.getContext()
@ -52,9 +48,8 @@ public class BailErrorStrategy: DefaultErrorStrategy {
throw ANTLRException.recognition(e: e) throw ANTLRException.recognition(e: e)
} }
/** Make sure we don't attempt to recover inline; if the parser /// Make sure we don't attempt to recover inline; if the parser
* successfully recovers, it won't throw an exception. /// successfully recovers, it won't throw an exception.
*/
override override
public func recoverInline(_ recognizer: Parser) throws -> Token { public func recoverInline(_ recognizer: Parser) throws -> Token {
let e: InputMismatchException = try InputMismatchException(recognizer) let e: InputMismatchException = try InputMismatchException(recognizer)
@ -68,7 +63,7 @@ public class BailErrorStrategy: DefaultErrorStrategy {
} }
/** Make sure we don't attempt to recover from problems in subrules. */ /// Make sure we don't attempt to recover from problems in subrules.
override override
public func sync(_ recognizer: Parser) { public func sync(_ recognizer: Parser) {
} }

View File

@ -1,16 +1,13 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** /// Provides an empty default implementation of {@link org.antlr.v4.runtime.ANTLRErrorListener}. The
* Provides an empty default implementation of {@link org.antlr.v4.runtime.ANTLRErrorListener}. The /// default implementation of each method does nothing, but can be overridden as
* default implementation of each method does nothing, but can be overridden as /// necessary.
* necessary. ///
* /// - Sam Harwell
* @author Sam Harwell
*/
public class BaseErrorListener: ANTLRErrorListener { public class BaseErrorListener: ANTLRErrorListener {

View File

@ -1,63 +1,52 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** /// This implementation of {@link org.antlr.v4.runtime.TokenStream} loads tokens from a
* This implementation of {@link org.antlr.v4.runtime.TokenStream} loads tokens from a /// {@link org.antlr.v4.runtime.TokenSource} on-demand, and places the tokens in a buffer to provide
* {@link org.antlr.v4.runtime.TokenSource} on-demand, and places the tokens in a buffer to provide /// access to any previous token by index.
* access to any previous token by index. ///
* /// <p>
* <p> /// This token stream ignores the value of {@link org.antlr.v4.runtime.Token#getChannel}. If your
* This token stream ignores the value of {@link org.antlr.v4.runtime.Token#getChannel}. If your /// parser requires the token stream filter tokens to only those on a particular
* parser requires the token stream filter tokens to only those on a particular /// channel, such as {@link org.antlr.v4.runtime.Token#DEFAULT_CHANNEL} or
* channel, such as {@link org.antlr.v4.runtime.Token#DEFAULT_CHANNEL} or /// {@link org.antlr.v4.runtime.Token#HIDDEN_CHANNEL}, use a filtering token stream such a
* {@link org.antlr.v4.runtime.Token#HIDDEN_CHANNEL}, use a filtering token stream such a /// {@link org.antlr.v4.runtime.CommonTokenStream}.</p>
* {@link org.antlr.v4.runtime.CommonTokenStream}.</p>
*/
public class BufferedTokenStream: TokenStream { public class BufferedTokenStream: TokenStream {
/** /// The {@link org.antlr.v4.runtime.TokenSource} from which tokens for this stream are fetched.
* The {@link org.antlr.v4.runtime.TokenSource} from which tokens for this stream are fetched.
*/
internal var tokenSource: TokenSource internal var tokenSource: TokenSource
/** /// A collection of all tokens fetched from the token source. The list is
* A collection of all tokens fetched from the token source. The list is /// considered a complete view of the input once {@link #fetchedEOF} is set
* considered a complete view of the input once {@link #fetchedEOF} is set /// to {@code true}.
* to {@code true}.
*/
internal var tokens: Array<Token> = Array<Token>() internal var tokens: Array<Token> = Array<Token>()
// Array<Token>(100 // Array<Token>(100
/** /// The index into {@link #tokens} of the current token (next token to
* The index into {@link #tokens} of the current token (next token to /// {@link #consume}). {@link #tokens}{@code [}{@link #p}{@code ]} should be
* {@link #consume}). {@link #tokens}{@code [}{@link #p}{@code ]} should be /// {@link #LT LT(1)}.
* {@link #LT LT(1)}. ///
* /// <p>This field is set to -1 when the stream is first constructed or when
* <p>This field is set to -1 when the stream is first constructed or when /// {@link #setTokenSource} is called, indicating that the first token has
* {@link #setTokenSource} is called, indicating that the first token has /// not yet been fetched from the token source. For additional information,
* not yet been fetched from the token source. For additional information, /// see the documentation of {@link org.antlr.v4.runtime.IntStream} for a description of
* see the documentation of {@link org.antlr.v4.runtime.IntStream} for a description of /// Initializing Methods.</p>
* Initializing Methods.</p>
*/
internal var p: Int = -1 internal var p: Int = -1
/** /// Indicates whether the {@link org.antlr.v4.runtime.Token#EOF} token has been fetched from
* Indicates whether the {@link org.antlr.v4.runtime.Token#EOF} token has been fetched from /// {@link #tokenSource} and added to {@link #tokens}. This field improves
* {@link #tokenSource} and added to {@link #tokens}. This field improves /// performance for the following cases:
* performance for the following cases: ///
* /// <ul>
* <ul> /// <li>{@link #consume}: The lookahead check in {@link #consume} to prevent
* <li>{@link #consume}: The lookahead check in {@link #consume} to prevent /// consuming the EOF symbol is optimized by checking the values of
* consuming the EOF symbol is optimized by checking the values of /// {@link #fetchedEOF} and {@link #p} instead of calling {@link #LA}.</li>
* {@link #fetchedEOF} and {@link #p} instead of calling {@link #LA}.</li> /// <li>{@link #fetch}: The check to prevent adding multiple EOF symbols into
* <li>{@link #fetch}: The check to prevent adding multiple EOF symbols into /// {@link #tokens} is trivial with this field.</li>
* {@link #tokens} is trivial with this field.</li> /// <ul>
* <ul>
*/
internal var fetchedEOF: Bool = false internal var fetchedEOF: Bool = false
public init(_ tokenSource: TokenSource) { public init(_ tokenSource: TokenSource) {
@ -128,12 +117,11 @@ public class BufferedTokenStream: TokenStream {
} }
} }
/** Make sure index {@code i} in tokens has a token. /// Make sure index {@code i} in tokens has a token.
* ///
* @return {@code true} if a token is located at index {@code i}, otherwise /// - returns: {@code true} if a token is located at index {@code i}, otherwise
* {@code false}. /// {@code false}.
* @see #get(int i) /// - seealso: #get(int i)
*/
@discardableResult @discardableResult
internal func sync(_ i: Int) throws -> Bool { internal func sync(_ i: Int) throws -> Bool {
assert(i >= 0, "Expected: i>=0") assert(i >= 0, "Expected: i>=0")
@ -147,10 +135,9 @@ public class BufferedTokenStream: TokenStream {
return true return true
} }
/** Add {@code n} elements to buffer. /// Add {@code n} elements to buffer.
* ///
* @return The actual number of elements added to the buffer. /// - returns: The actual number of elements added to the buffer.
*/
internal func fetch(_ n: Int) throws -> Int { internal func fetch(_ n: Int) throws -> Int {
if fetchedEOF { if fetchedEOF {
return 0 return 0
@ -181,7 +168,7 @@ public class BufferedTokenStream: TokenStream {
return tokens[i] //tokens[i] return tokens[i] //tokens[i]
} }
/** Get all tokens from start..stop inclusively */ /// Get all tokens from start..stop inclusively
public func get(_ start: Int,_ stop: Int) throws -> Array<Token>? { public func get(_ start: Int,_ stop: Int) throws -> Array<Token>? {
var stop = stop var stop = stop
if start < 0 || stop < 0 { if start < 0 || stop < 0 {
@ -235,19 +222,17 @@ public class BufferedTokenStream: TokenStream {
return tokens[i] return tokens[i]
} }
/** /// Allowed derived classes to modify the behavior of operations which change
* Allowed derived classes to modify the behavior of operations which change /// the current stream position by adjusting the target token index of a seek
* the current stream position by adjusting the target token index of a seek /// operation. The default implementation simply returns {@code i}. If an
* operation. The default implementation simply returns {@code i}. If an /// exception is thrown in this method, the current stream index should not be
* exception is thrown in this method, the current stream index should not be /// changed.
* changed. ///
* /// <p>For example, {@link org.antlr.v4.runtime.CommonTokenStream} overrides this method to ensure that
* <p>For example, {@link org.antlr.v4.runtime.CommonTokenStream} overrides this method to ensure that /// the seek target is always an on-channel token.</p>
* the seek target is always an on-channel token.</p> ///
* /// - parameter i: The target token index.
* @param i The target token index. /// - returns: The adjusted target token index.
* @return The adjusted target token index.
*/
internal func adjustSeekIndex(_ i: Int) throws -> Int { internal func adjustSeekIndex(_ i: Int) throws -> Int {
return i return i
} }
@ -263,7 +248,7 @@ public class BufferedTokenStream: TokenStream {
p = try adjustSeekIndex(0) p = try adjustSeekIndex(0)
} }
/** Reset this token stream by setting its token source. */ /// Reset this token stream by setting its token source.
public func setTokenSource(_ tokenSource: TokenSource) { public func setTokenSource(_ tokenSource: TokenSource) {
self.tokenSource = tokenSource self.tokenSource = tokenSource
tokens.removeAll() tokens.removeAll()
@ -278,10 +263,9 @@ public class BufferedTokenStream: TokenStream {
return try getTokens(start, stop, nil) return try getTokens(start, stop, nil)
} }
/** Given a start and stop index, return a List of all tokens in /// 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 /// the token type BitSet. Return null if no tokens were found. This
* method looks at both on and off channel tokens. /// method looks at both on and off channel tokens.
*/
public func getTokens(_ start: Int, _ stop: Int, _ types: Set<Int>?) throws -> Array<Token>? { public func getTokens(_ start: Int, _ stop: Int, _ types: Set<Int>?) throws -> Array<Token>? {
try lazyInit() try lazyInit()
if start < 0 || stop >= tokens.count || if start < 0 || stop >= tokens.count ||
@ -318,12 +302,10 @@ public class BufferedTokenStream: TokenStream {
return try getTokens(start, stop, s) return try getTokens(start, stop, s)
} }
/** /// Given a starting index, return the index of the next token on channel.
* Given a starting index, return the index of the next token on channel. /// Return {@code i} if {@code tokens[i]} is on channel. Return the index of
* Return {@code i} if {@code tokens[i]} is on channel. Return the index of /// the EOF token if there are no tokens on channel between {@code i} and
* the EOF token if there are no tokens on channel between {@code i} and /// EOF.
* EOF.
*/
internal func nextTokenOnChannel(_ i: Int, _ channel: Int) throws -> Int { internal func nextTokenOnChannel(_ i: Int, _ channel: Int) throws -> Int {
var i = i var i = i
try sync(i) try sync(i)
@ -345,16 +327,14 @@ public class BufferedTokenStream: TokenStream {
return i return i
} }
/** /// Given a starting index, return the index of the previous token on
* Given a starting index, return the index of the previous token on /// channel. Return {@code i} if {@code tokens[i]} is on channel. Return -1
* channel. Return {@code i} if {@code tokens[i]} is on channel. Return -1 /// if there are no tokens on channel between {@code i} and 0.
* if there are no tokens on channel between {@code i} and 0. ///
* /// <p>
* <p> /// If {@code i} specifies an index at or after the EOF token, the EOF token
* If {@code 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
* index is returned. This is due to the fact that the EOF token is treated /// as though it were on every channel.</p>
* as though it were on every channel.</p>
*/
internal func previousTokenOnChannel(_ i: Int, _ channel: Int) throws -> Int { internal func previousTokenOnChannel(_ i: Int, _ channel: Int) throws -> Int {
var i = i var i = i
try sync(i) try sync(i)
@ -375,10 +355,9 @@ public class BufferedTokenStream: TokenStream {
return i return i
} }
/** Collect all tokens on specified channel to the right of /// Collect all tokens on specified channel to the right of
* the current token up until we see a token on DEFAULT_TOKEN_CHANNEL or /// 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. /// EOF. If channel is -1, find any non default channel token.
*/
public func getHiddenTokensToRight(_ tokenIndex: Int, _ channel: Int) throws -> Array<Token>? { public func getHiddenTokensToRight(_ tokenIndex: Int, _ channel: Int) throws -> Array<Token>? {
try lazyInit() try lazyInit()
if tokenIndex < 0 || tokenIndex >= tokens.count { if tokenIndex < 0 || tokenIndex >= tokens.count {
@ -400,18 +379,16 @@ public class BufferedTokenStream: TokenStream {
return filterForChannel(from, to, channel) return filterForChannel(from, to, channel)
} }
/** Collect all hidden tokens (any off-default channel) to the right of /// Collect all hidden tokens (any off-default channel) to the right of
* the current token up until we see a token on DEFAULT_TOKEN_CHANNEL /// the current token up until we see a token on DEFAULT_TOKEN_CHANNEL
* or EOF. /// or EOF.
*/
public func getHiddenTokensToRight(_ tokenIndex: Int) throws -> Array<Token>? { public func getHiddenTokensToRight(_ tokenIndex: Int) throws -> Array<Token>? {
return try getHiddenTokensToRight(tokenIndex, -1) return try getHiddenTokensToRight(tokenIndex, -1)
} }
/** Collect all tokens on specified channel to the left of /// Collect all tokens on specified channel to the left of
* the current token up until we see a token on DEFAULT_TOKEN_CHANNEL. /// the current token up until we see a token on DEFAULT_TOKEN_CHANNEL.
* If channel is -1, find any non default channel token. /// If channel is -1, find any non default channel token.
*/
public func getHiddenTokensToLeft(_ tokenIndex: Int, _ channel: Int) throws -> Array<Token>? { public func getHiddenTokensToLeft(_ tokenIndex: Int, _ channel: Int) throws -> Array<Token>? {
try lazyInit() try lazyInit()
if tokenIndex < 0 || tokenIndex >= tokens.count { if tokenIndex < 0 || tokenIndex >= tokens.count {
@ -437,9 +414,8 @@ public class BufferedTokenStream: TokenStream {
return filterForChannel(from, to, channel) return filterForChannel(from, to, channel)
} }
/** Collect all hidden tokens (any off-default channel) to the left of /// Collect all hidden tokens (any off-default channel) to the left of
* the current token up until we see a token on DEFAULT_TOKEN_CHANNEL. /// the current token up until we see a token on DEFAULT_TOKEN_CHANNEL.
*/
public func getHiddenTokensToLeft(_ tokenIndex: Int) throws -> Array<Token>? { public func getHiddenTokensToLeft(_ tokenIndex: Int) throws -> Array<Token>? {
return try getHiddenTokensToLeft(tokenIndex, -1) return try getHiddenTokensToLeft(tokenIndex, -1)
} }
@ -469,7 +445,7 @@ public class BufferedTokenStream: TokenStream {
return tokenSource.getSourceName() return tokenSource.getSourceName()
} }
/** Get the text of all tokens in this buffer. */ /// Get the text of all tokens in this buffer.
public func getText() throws -> String { public func getText() throws -> String {
@ -513,7 +489,7 @@ public class BufferedTokenStream: TokenStream {
return "" return ""
} }
/** Get all tokens from lexer until EOF */ /// Get all tokens from lexer until EOF
public func fill() throws { public func fill() throws {
try lazyInit() try lazyInit()
let blockSize: Int = 1000 let blockSize: Int = 1000

View File

@ -1,27 +1,24 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** A source of characters for an ANTLR lexer. */ /// A source of characters for an ANTLR lexer.
public protocol CharStream: IntStream { public protocol CharStream: IntStream {
/** /// This method returns the text for a range of characters within this input
* 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
* stream. This method is guaranteed to not throw an exception if the /// specified {@code interval} lies entirely within a marked range. For more
* specified {@code interval} lies entirely within a marked range. For more /// information about marked ranges, see {@link org.antlr.v4.runtime.IntStream#mark}.
* information about marked ranges, see {@link org.antlr.v4.runtime.IntStream#mark}. ///
* /// - parameter interval: an interval within the stream
* @param interval an interval within the stream /// - returns: the text of the specified interval
* @return the text of the specified interval ///
* /// - NullPointerException if {@code interval} is {@code null}
* @throws NullPointerException if {@code interval} is {@code null} /// - IllegalArgumentException if {@code interval.a < 0}, or if
* @throws IllegalArgumentException if {@code interval.a < 0}, or if /// {@code interval.b < interval.a - 1}, or if {@code interval.b} lies at or
* {@code interval.b < interval.a - 1}, or if {@code interval.b} lies at or /// past the end of the stream
* past the end of the stream /// - UnsupportedOperationException if the stream does not support
* @throws UnsupportedOperationException if the stream does not support /// getting the text of the specified interval
* getting the text of the specified interval
*/
func getText(_ interval: Interval) -> String func getText(_ interval: Interval) -> String
} }

View File

@ -1,84 +1,61 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
public class CommonToken: WritableToken { public class CommonToken: WritableToken {
/** /// An empty {@link org.antlr.v4.runtime.misc.Pair} which is used as the default value of
* An empty {@link org.antlr.v4.runtime.misc.Pair} which is used as the default value of /// {@link #source} for tokens that do not have a source.
* {@link #source} for tokens that do not have a source.
*/
internal static let EMPTY_SOURCE: (TokenSource?, CharStream?) = (nil, nil) internal static let EMPTY_SOURCE: (TokenSource?, CharStream?) = (nil, nil)
/** /// This is the backing field for {@link #getType} and {@link #setType}.
* This is the backing field for {@link #getType} and {@link #setType}.
*/
internal var type: Int internal var type: Int
/** /// This is the backing field for {@link #getLine} and {@link #setLine}.
* This is the backing field for {@link #getLine} and {@link #setLine}.
*/
internal var line: Int = 0 internal var line: Int = 0
/** /// This is the backing field for {@link #getCharPositionInLine} and
* This is the backing field for {@link #getCharPositionInLine} and /// {@link #setCharPositionInLine}.
* {@link #setCharPositionInLine}.
*/
internal var charPositionInLine: Int = -1 internal var charPositionInLine: Int = -1
// set to invalid position // set to invalid position
/** /// This is the backing field for {@link #getChannel} and
* This is the backing field for {@link #getChannel} and /// {@link #setChannel}.
* {@link #setChannel}.
*/
internal var channel: Int = DEFAULT_CHANNEL internal var channel: Int = DEFAULT_CHANNEL
/** /// This is the backing field for {@link #getTokenSource} and
* This is the backing field for {@link #getTokenSource} and /// {@link #getInputStream}.
* {@link #getInputStream}. ///
* /// <p>
* <p> /// These properties share a field to reduce the memory footprint of
* These properties share a field to reduce the memory footprint of /// {@link org.antlr.v4.runtime.CommonToken}. Tokens created by a {@link org.antlr.v4.runtime.CommonTokenFactory} from
* {@link org.antlr.v4.runtime.CommonToken}. Tokens created by a {@link org.antlr.v4.runtime.CommonTokenFactory} from /// the same source and input stream share a reference to the same
* the same source and input stream share a reference to the same /// {@link org.antlr.v4.runtime.misc.Pair} containing these values.</p>
* {@link org.antlr.v4.runtime.misc.Pair} containing these values.</p>
*/
internal var source: (TokenSource?, CharStream?) internal var source: (TokenSource?, CharStream?)
/** /// This is the backing field for {@link #getText} when the token text is
* This is the backing field for {@link #getText} when the token text is /// explicitly set in the constructor or via {@link #setText}.
* explicitly set in the constructor or via {@link #setText}. ///
* /// - seealso: #getText()
* @see #getText()
*/
internal var text: String? internal var text: String?
/** /// This is the backing field for {@link #getTokenIndex} and
* This is the backing field for {@link #getTokenIndex} and /// {@link #setTokenIndex}.
* {@link #setTokenIndex}.
*/
internal var index: Int = -1 internal var index: Int = -1
/** /// This is the backing field for {@link #getStartIndex} and
* This is the backing field for {@link #getStartIndex} and /// {@link #setStartIndex}.
* {@link #setStartIndex}.
*/
internal var start: Int = 0 internal var start: Int = 0
/** /// This is the backing field for {@link #getStopIndex} and
* This is the backing field for {@link #getStopIndex} and /// {@link #setStopIndex}.
* {@link #setStopIndex}.
*/
internal var stop: Int = 0 internal var stop: Int = 0
/** /// Constructs a new {@link org.antlr.v4.runtime.CommonToken} with the specified token type.
* Constructs a new {@link org.antlr.v4.runtime.CommonToken} with the specified token type. ///
* /// - parameter type: The token type.
* @param type The token type.
*/
private var _visited: Bool = false private var _visited: Bool = false
@ -99,13 +76,11 @@ public class CommonToken: WritableToken {
} }
} }
/** /// Constructs a new {@link org.antlr.v4.runtime.CommonToken} with the specified token type and
* Constructs a new {@link org.antlr.v4.runtime.CommonToken} with the specified token type and /// text.
* text. ///
* /// - parameter type: The token type.
* @param type The token type. /// - parameter text: The text of the token.
* @param text The text of the token.
*/
public init(_ type: Int, _ text: String?) { public init(_ type: Int, _ text: String?) {
self.type = type self.type = type
self.channel = CommonToken.DEFAULT_CHANNEL self.channel = CommonToken.DEFAULT_CHANNEL
@ -113,19 +88,17 @@ public class CommonToken: WritableToken {
self.source = CommonToken.EMPTY_SOURCE self.source = CommonToken.EMPTY_SOURCE
} }
/** /// Constructs a new {@link org.antlr.v4.runtime.CommonToken} as a copy of another {@link org.antlr.v4.runtime.Token}.
* Constructs a new {@link org.antlr.v4.runtime.CommonToken} as a copy of another {@link org.antlr.v4.runtime.Token}. ///
* /// <p>
* <p> /// If {@code oldToken} is also a {@link org.antlr.v4.runtime.CommonToken} instance, the newly
* If {@code oldToken} is also a {@link org.antlr.v4.runtime.CommonToken} instance, the newly /// constructed token will share a reference to the {@link #text} field and
* constructed token will share a reference to the {@link #text} field and /// the {@link org.antlr.v4.runtime.misc.Pair} stored in {@link #source}. Otherwise, {@link #text} will
* the {@link org.antlr.v4.runtime.misc.Pair} stored in {@link #source}. Otherwise, {@link #text} will /// be assigned the result of calling {@link #getText}, and {@link #source}
* be assigned the result of calling {@link #getText}, and {@link #source} /// will be constructed from the result of {@link org.antlr.v4.runtime.Token#getTokenSource} and
* will be constructed from the result of {@link org.antlr.v4.runtime.Token#getTokenSource} and /// {@link org.antlr.v4.runtime.Token#getInputStream}.</p>
* {@link org.antlr.v4.runtime.Token#getInputStream}.</p> ///
* /// - parameter oldToken: The token to copy.
* @param oldToken The token to copy.
*/
public init(_ oldToken: Token) { public init(_ oldToken: Token) {
type = oldToken.getType() type = oldToken.getType()
line = oldToken.getLine() line = oldToken.getLine()
@ -173,15 +146,13 @@ public class CommonToken: WritableToken {
} }
/** /// Explicitly set the text for this token. If {code text} is not
* Explicitly set the text for this token. If {code text} is not /// {@code null}, then {@link #getText} will return this value rather than
* {@code null}, then {@link #getText} will return this value rather than /// extracting the text from the input.
* extracting the text from the input. ///
* /// - parameter text: The explicit text of the token, or {@code null} if the text
* @param text The explicit text of the token, or {@code null} if the text /// should be obtained from the input along with the start and stop indexes
* should be obtained from the input along with the start and stop indexes /// of the token.
* of the token.
*/
public func setText(_ text: String) { public func setText(_ text: String) {
self.text = text self.text = text

View File

@ -1,64 +1,53 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** /// This default implementation of {@link org.antlr.v4.runtime.TokenFactory} creates
* This default implementation of {@link org.antlr.v4.runtime.TokenFactory} creates /// {@link org.antlr.v4.runtime.CommonToken} objects.
* {@link org.antlr.v4.runtime.CommonToken} objects.
*/
public class CommonTokenFactory: TokenFactory { public class CommonTokenFactory: TokenFactory {
/** /// The default {@link org.antlr.v4.runtime.CommonTokenFactory} instance.
* The default {@link org.antlr.v4.runtime.CommonTokenFactory} instance. ///
* /// <p>
* <p> /// This token factory does not explicitly copy token text when constructing
* This token factory does not explicitly copy token text when constructing /// tokens.</p>
* tokens.</p>
*/
public static let DEFAULT: TokenFactory = CommonTokenFactory() public static let DEFAULT: TokenFactory = CommonTokenFactory()
/** /// Indicates whether {@link org.antlr.v4.runtime.CommonToken#setText} should be called after
* Indicates whether {@link org.antlr.v4.runtime.CommonToken#setText} should be called after /// constructing tokens to explicitly set the text. This is useful for cases
* constructing tokens to explicitly set the text. This is useful for cases /// where the input stream might not be able to provide arbitrary substrings
* 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
* of text from the input after the lexer creates a token (e.g. the /// implementation of {@link org.antlr.v4.runtime.CharStream#getText} in
* implementation of {@link org.antlr.v4.runtime.CharStream#getText} in /// {@link org.antlr.v4.runtime.UnbufferedCharStream} throws an
* {@link org.antlr.v4.runtime.UnbufferedCharStream} throws an /// {@link UnsupportedOperationException}). Explicitly setting the token text
* {@link UnsupportedOperationException}). Explicitly setting the token text /// allows {@link org.antlr.v4.runtime.Token#getText} to be called at any time regardless of the
* allows {@link org.antlr.v4.runtime.Token#getText} to be called at any time regardless of the /// input stream implementation.
* input stream implementation. ///
* /// <p>
* <p> /// The default value is {@code false} to avoid the performance and memory
* The default value is {@code false} to avoid the performance and memory /// overhead of copying text for every token unless explicitly requested.</p>
* overhead of copying text for every token unless explicitly requested.</p>
*/
internal final var copyText: Bool internal final var copyText: Bool
/** /// Constructs a {@link org.antlr.v4.runtime.CommonTokenFactory} with the specified value for
* Constructs a {@link org.antlr.v4.runtime.CommonTokenFactory} with the specified value for /// {@link #copyText}.
* {@link #copyText}. ///
* /// <p>
* <p> /// When {@code copyText} is {@code false}, the {@link #DEFAULT} instance
* When {@code copyText} is {@code false}, the {@link #DEFAULT} instance /// should be used instead of constructing a new instance.</p>
* should be used instead of constructing a new instance.</p> ///
* /// - parameter copyText: The value for {@link #copyText}.
* @param copyText The value for {@link #copyText}.
*/
public init(_ copyText: Bool) { public init(_ copyText: Bool) {
self.copyText = copyText self.copyText = copyText
} }
/** /// Constructs a {@link org.antlr.v4.runtime.CommonTokenFactory} with {@link #copyText} set to
* Constructs a {@link org.antlr.v4.runtime.CommonTokenFactory} with {@link #copyText} set to /// {@code false}.
* {@code false}. ///
* /// <p>
* <p> /// The {@link #DEFAULT} instance should be used instead of calling this
* The {@link #DEFAULT} instance should be used instead of calling this /// directly.</p>
* directly.</p>
*/
public convenience init() { public convenience init() {
self.init(false) self.init(false)
} }

View File

@ -1,65 +1,56 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** /// This class extends {@link org.antlr.v4.runtime.BufferedTokenStream} with functionality to filter
* This class extends {@link org.antlr.v4.runtime.BufferedTokenStream} with functionality to filter /// token streams to tokens on a particular channel (tokens where
* token streams to tokens on a particular channel (tokens where /// {@link org.antlr.v4.runtime.Token#getChannel} returns a particular value).
* {@link org.antlr.v4.runtime.Token#getChannel} returns a particular value). ///
* /// <p>
* <p> /// This token stream provides access to all tokens by index or when calling
* This token stream provides access to all tokens by index or when calling /// methods like {@link #getText}. The channel filtering is only used for code
* methods like {@link #getText}. The channel filtering is only used for code /// accessing tokens via the lookahead methods {@link #LA}, {@link #LT}, and
* accessing tokens via the lookahead methods {@link #LA}, {@link #LT}, and /// {@link #LB}.</p>
* {@link #LB}.</p> ///
* /// <p>
* <p> /// By default, tokens are placed on the default channel
* By default, tokens are placed on the default channel /// ({@link org.antlr.v4.runtime.Token#DEFAULT_CHANNEL}), but may be reassigned by using the
* ({@link org.antlr.v4.runtime.Token#DEFAULT_CHANNEL}), but may be reassigned by using the /// {@code ->channel(HIDDEN)} lexer command, or by using an embedded action to
* {@code ->channel(HIDDEN)} lexer command, or by using an embedded action to /// call {@link org.antlr.v4.runtime.Lexer#setChannel}.
* call {@link org.antlr.v4.runtime.Lexer#setChannel}. /// </p>
* </p> ///
* /// <p>
* <p> /// Note: lexer rules which use the {@code ->skip} lexer command or call
* Note: lexer rules which use the {@code ->skip} lexer command or call /// {@link org.antlr.v4.runtime.Lexer#skip} do not produce tokens at all, so input text matched by
* {@link org.antlr.v4.runtime.Lexer#skip} do not produce tokens at all, so input text matched by /// such a rule will not be available as part of the token stream, regardless of
* such a rule will not be available as part of the token stream, regardless of /// channel.</p>
* channel.</p>
*/
public class CommonTokenStream: BufferedTokenStream { public class CommonTokenStream: BufferedTokenStream {
/** /// Specifies the channel to use for filtering tokens.
* Specifies the channel to use for filtering tokens. ///
* /// <p>
* <p> /// The default value is {@link org.antlr.v4.runtime.Token#DEFAULT_CHANNEL}, which matches the
* The default value is {@link org.antlr.v4.runtime.Token#DEFAULT_CHANNEL}, which matches the /// default channel assigned to tokens created by the lexer.</p>
* default channel assigned to tokens created by the lexer.</p>
*/
internal var channel: Int = CommonToken.DEFAULT_CHANNEL internal var channel: Int = CommonToken.DEFAULT_CHANNEL
/** /// Constructs a new {@link org.antlr.v4.runtime.CommonTokenStream} using the specified token
* Constructs a new {@link org.antlr.v4.runtime.CommonTokenStream} using the specified token /// source and the default token channel ({@link org.antlr.v4.runtime.Token#DEFAULT_CHANNEL}).
* source and the default token channel ({@link org.antlr.v4.runtime.Token#DEFAULT_CHANNEL}). ///
* /// - parameter tokenSource: The token source.
* @param tokenSource The token source.
*/
public override init(_ tokenSource: TokenSource) { public override init(_ tokenSource: TokenSource) {
super.init(tokenSource) super.init(tokenSource)
} }
/** /// Constructs a new {@link org.antlr.v4.runtime.CommonTokenStream} using the specified token
* Constructs a new {@link org.antlr.v4.runtime.CommonTokenStream} using the specified token /// source and filtering tokens to the specified channel. Only tokens whose
* source and filtering tokens to the specified channel. Only tokens whose /// {@link org.antlr.v4.runtime.Token#getChannel} matches {@code channel} or have the
* {@link org.antlr.v4.runtime.Token#getChannel} matches {@code channel} or have the /// {@link org.antlr.v4.runtime.Token#getType} equal to {@link org.antlr.v4.runtime.Token#EOF} will be returned by the
* {@link org.antlr.v4.runtime.Token#getType} equal to {@link org.antlr.v4.runtime.Token#EOF} will be returned by the /// token stream lookahead methods.
* token stream lookahead methods. ///
* /// - parameter tokenSource: The token source.
* @param tokenSource The token source. /// - parameter channel: The channel to use for filtering tokens.
* @param channel The channel to use for filtering tokens.
*/
public convenience init(_ tokenSource: TokenSource, _ channel: Int) { public convenience init(_ tokenSource: TokenSource, _ channel: Int) {
self.init(tokenSource) self.init(tokenSource)
self.channel = channel self.channel = channel
@ -114,7 +105,7 @@ public class CommonTokenStream: BufferedTokenStream {
return tokens[i] return tokens[i]
} }
/** Count EOF just once. */ /// Count EOF just once.
public func getNumberOfOnChannelTokens() throws -> Int { public func getNumberOfOnChannelTokens() throws -> Int {
var n: Int = 0 var n: Int = 0
try fill() try fill()

View File

@ -1,32 +1,25 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** ///
* /// - Sam Harwell
* @author Sam Harwell
*/
public class ConsoleErrorListener: BaseErrorListener { public class ConsoleErrorListener: BaseErrorListener {
/** /// Provides a default instance of {@link org.antlr.v4.runtime.ConsoleErrorListener}.
* Provides a default instance of {@link org.antlr.v4.runtime.ConsoleErrorListener}.
*/
public static let INSTANCE: ConsoleErrorListener = ConsoleErrorListener() public static let INSTANCE: ConsoleErrorListener = ConsoleErrorListener()
/** /// {@inheritDoc}
* {@inheritDoc} ///
* /// <p>
* <p> /// This implementation prints messages to {@link System#err} containing the
* This implementation prints messages to {@link System#err} containing the /// values of {@code line}, {@code charPositionInLine}, and {@code msg} using
* values of {@code line}, {@code charPositionInLine}, and {@code msg} using /// the following format.</p>
* the following format.</p> ///
* /// <pre>
* <pre> /// line <em>line</em>:<em>charPositionInLine</em> <em>msg</em>
* line <em>line</em>:<em>charPositionInLine</em> <em>msg</em> /// </pre>
* </pre>
*/
override override
public func syntaxError<T:ATNSimulator>(_ recognizer: Recognizer<T>, public func syntaxError<T:ATNSimulator>(_ recognizer: Recognizer<T>,
_ offendingSymbol: AnyObject?, _ offendingSymbol: AnyObject?,

View File

@ -1,107 +1,89 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** /// This is the default implementation of {@link org.antlr.v4.runtime.ANTLRErrorStrategy} used for
* This is the default implementation of {@link org.antlr.v4.runtime.ANTLRErrorStrategy} used for /// error reporting and recovery in ANTLR parsers.
* error reporting and recovery in ANTLR parsers.
*/
import Foundation import Foundation
public class DefaultErrorStrategy: ANTLRErrorStrategy { public class DefaultErrorStrategy: ANTLRErrorStrategy {
/** /// Indicates whether the error strategy is currently "recovering from an
* Indicates whether the error strategy is currently "recovering from an /// error". This is used to suppress reporting multiple error messages while
* error". This is used to suppress reporting multiple error messages while /// attempting to recover from a detected syntax error.
* attempting to recover from a detected syntax error. ///
* /// - seealso: #inErrorRecoveryMode
* @see #inErrorRecoveryMode
*/
internal var errorRecoveryMode: Bool = false internal var errorRecoveryMode: Bool = false
/** The index into the input stream where the last error occurred. /// The index into the input stream where the last error occurred.
* This is used to prevent infinite loops where an error is found /// This is used to prevent infinite loops where an error is found
* but no token is consumed during recovery...another 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 /// ad nauseum. This is a failsafe mechanism to guarantee that at least
* one token/tree node is consumed for two errors. /// one token/tree node is consumed for two errors.
*/
internal var lastErrorIndex: Int = -1 internal var lastErrorIndex: Int = -1
internal var lastErrorStates: IntervalSet? internal var lastErrorStates: IntervalSet?
/** /// {@inheritDoc}
* {@inheritDoc} ///
* /// <p>The default implementation simply calls {@link #endErrorCondition} to
* <p>The default implementation simply calls {@link #endErrorCondition} to /// ensure that the handler is not in error recovery mode.</p>
* ensure that the handler is not in error recovery mode.</p>
*/
public func reset(_ recognizer: Parser) { public func reset(_ recognizer: Parser) {
endErrorCondition(recognizer) endErrorCondition(recognizer)
} }
/** /// This method is called to enter error recovery mode when a recognition
* This method is called to enter error recovery mode when a recognition /// exception is reported.
* exception is reported. ///
* /// - parameter recognizer: the parser instance
* @param recognizer the parser instance
*/
internal func beginErrorCondition(_ recognizer: Parser) { internal func beginErrorCondition(_ recognizer: Parser) {
errorRecoveryMode = true errorRecoveryMode = true
} }
/** /// {@inheritDoc}
* {@inheritDoc}
*/
public func inErrorRecoveryMode(_ recognizer: Parser) -> Bool { public func inErrorRecoveryMode(_ recognizer: Parser) -> Bool {
return errorRecoveryMode return errorRecoveryMode
} }
/** /// This method is called to leave error recovery mode after recovering from
* This method is called to leave error recovery mode after recovering from /// a recognition exception.
* a recognition exception. ///
* /// - parameter recognizer:
* @param recognizer
*/
internal func endErrorCondition(_ recognizer: Parser) { internal func endErrorCondition(_ recognizer: Parser) {
errorRecoveryMode = false errorRecoveryMode = false
lastErrorStates = nil lastErrorStates = nil
lastErrorIndex = -1 lastErrorIndex = -1
} }
/** /// {@inheritDoc}
* {@inheritDoc} ///
* /// <p>The default implementation simply calls {@link #endErrorCondition}.</p>
* <p>The default implementation simply calls {@link #endErrorCondition}.</p>
*/
public func reportMatch(_ recognizer: Parser) { public func reportMatch(_ recognizer: Parser) {
endErrorCondition(recognizer) endErrorCondition(recognizer)
} }
/** /// {@inheritDoc}
* {@inheritDoc} ///
* /// <p>The default implementation returns immediately if the handler is already
* <p>The default implementation returns immediately if the handler is already /// in error recovery mode. Otherwise, it calls {@link #beginErrorCondition}
* in error recovery mode. Otherwise, it calls {@link #beginErrorCondition} /// and dispatches the reporting task based on the runtime type of {@code e}
* and dispatches the reporting task based on the runtime type of {@code e} /// according to the following table.</p>
* according to the following table.</p> ///
* /// <ul>
* <ul> /// <li>{@link org.antlr.v4.runtime.NoViableAltException}: Dispatches the call to
* <li>{@link org.antlr.v4.runtime.NoViableAltException}: Dispatches the call to /// {@link #reportNoViableAlternative}</li>
* {@link #reportNoViableAlternative}</li> /// <li>{@link org.antlr.v4.runtime.InputMismatchException}: Dispatches the call to
* <li>{@link org.antlr.v4.runtime.InputMismatchException}: Dispatches the call to /// {@link #reportInputMismatch}</li>
* {@link #reportInputMismatch}</li> /// <li>{@link org.antlr.v4.runtime.FailedPredicateException}: Dispatches the call to
* <li>{@link org.antlr.v4.runtime.FailedPredicateException}: Dispatches the call to /// {@link #reportFailedPredicate}</li>
* {@link #reportFailedPredicate}</li> /// <li>All other types: calls {@link org.antlr.v4.runtime.Parser#notifyErrorListeners} to report
* <li>All other types: calls {@link org.antlr.v4.runtime.Parser#notifyErrorListeners} to report /// the exception</li>
* the exception</li> /// </ul>
* </ul>
*/
public func reportError(_ recognizer: Parser, public func reportError(_ recognizer: Parser,
_ e: AnyObject) { _ e: AnyObject) {
@ -130,13 +112,11 @@ public class DefaultErrorStrategy: ANTLRErrorStrategy {
} }
} }
/** /// {@inheritDoc}
* {@inheritDoc} ///
* /// <p>The default implementation resynchronizes the parser by consuming tokens
* <p>The default implementation resynchronizes the parser by consuming tokens /// until we find one in the resynchronization set--loosely the set of tokens
* until we find one in the resynchronization set--loosely the set of tokens /// that can follow the current rule.</p>
* that can follow the current rule.</p>
*/
public func recover(_ recognizer: Parser, _ e: AnyObject) throws { public func recover(_ recognizer: Parser, _ e: AnyObject) throws {
// print("recover in "+recognizer.getRuleInvocationStack()+ // print("recover in "+recognizer.getRuleInvocationStack()+
@ -165,52 +145,50 @@ public class DefaultErrorStrategy: ANTLRErrorStrategy {
try consumeUntil(recognizer, followSet) try consumeUntil(recognizer, followSet)
} }
/** /// The default implementation of {@link org.antlr.v4.runtime.ANTLRErrorStrategy#sync} makes sure
* The default implementation of {@link org.antlr.v4.runtime.ANTLRErrorStrategy#sync} makes sure /// that the current lookahead symbol is consistent with what were expecting
* 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
* at this point in the ATN. You can call this anytime but ANTLR only /// generates code to check before subrules/loops and each iteration.
* generates code to check before subrules/loops and each iteration. ///
* /// <p>Implements Jim Idle's magic sync mechanism in closures and optional
* <p>Implements Jim Idle's magic sync mechanism in closures and optional /// subrules. E.g.,</p>
* subrules. E.g.,</p> ///
* /// <pre>
* <pre> /// a : sync ( stuff sync )* ;
* a : sync ( stuff sync )* ; /// sync : {consume to what can follow sync} ;
* sync : {consume to what can follow sync} ; /// </pre>
* </pre> ///
* /// At the start of a sub rule upon error, {@link #sync} performs single
* At the start of a sub rule upon error, {@link #sync} performs single /// token deletion, if possible. If it can't do that, it bails on the current
* 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
* rule and uses the default error recovery, which consumes until the /// resynchronization set of the current rule.
* resynchronization set of the current rule. ///
* /// <p>If the sub rule is optional ({@code (...)?}, {@code (...)*}, or block
* <p>If the sub rule is optional ({@code (...)?}, {@code (...)*}, or block /// with an empty alternative), then the expected set includes what follows
* with an empty alternative), then the expected set includes what follows /// the subrule.</p>
* the subrule.</p> ///
* /// <p>During loop iteration, it consumes until it sees a token that can start a
* <p>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
* sub rule or what follows loop. Yes, that is pretty aggressive. We opt to /// stay in the loop as long as possible.</p>
* stay in the loop as long as possible.</p> ///
* /// <p><strong>ORIGINS</strong></p>
* <p><strong>ORIGINS</strong></p> ///
* /// <p>Previous versions of ANTLR did a poor job of their recovery within loops.
* <p>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
* A single mismatch token or missing token would force the parser to bail /// out of the entire rules surrounding the loop. So, for rule</p>
* out of the entire rules surrounding the loop. So, for rule</p> ///
* /// <pre>
* <pre> /// classDef : 'class' ID '{' member* '}'
* classDef : 'class' ID '{' member* '}' /// </pre>
* </pre> ///
* /// input with an extra token between members would force the parser to
* input with an extra token between members would force the parser to /// consume until it found the next class definition rather than the next
* consume until it found the next class definition rather than the next /// member definition of the current class.
* member definition of the current class. ///
* /// <p>This functionality cost a little bit of effort because the parser has to
* <p>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
* 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
* some reason speed is suffering for you, you can turn off this /// functionality by simply overriding this method as a blank { }.</p>
* functionality by simply overriding this method as a blank { }.</p>
*/
public func sync(_ recognizer: Parser) throws { public func sync(_ recognizer: Parser) throws {
let s: ATNState = recognizer.getInterpreter().atn.states[recognizer.getState()]! let s: ATNState = recognizer.getInterpreter().atn.states[recognizer.getState()]!
@ -261,15 +239,13 @@ public class DefaultErrorStrategy: ANTLRErrorStrategy {
} }
} }
/** /// This is called by {@link #reportError} when the exception is a
* This is called by {@link #reportError} when the exception is a /// {@link org.antlr.v4.runtime.NoViableAltException}.
* {@link org.antlr.v4.runtime.NoViableAltException}. ///
* /// - seealso: #reportError
* @see #reportError ///
* /// - parameter recognizer: the parser instance
* @param recognizer the parser instance /// - parameter e: the recognition exception
* @param e the recognition exception
*/
internal func reportNoViableAlternative(_ recognizer: Parser, internal func reportNoViableAlternative(_ recognizer: Parser,
_ e: NoViableAltException) throws { _ e: NoViableAltException) throws {
let tokens: TokenStream? = getTokenStream(recognizer) let tokens: TokenStream? = getTokenStream(recognizer)
@ -287,15 +263,13 @@ public class DefaultErrorStrategy: ANTLRErrorStrategy {
recognizer.notifyErrorListeners(e.getOffendingToken(), msg, e) recognizer.notifyErrorListeners(e.getOffendingToken(), msg, e)
} }
/** /// This is called by {@link #reportError} when the exception is an
* This is called by {@link #reportError} when the exception is an /// {@link org.antlr.v4.runtime.InputMismatchException}.
* {@link org.antlr.v4.runtime.InputMismatchException}. ///
* /// - seealso: #reportError
* @see #reportError ///
* /// - parameter recognizer: the parser instance
* @param recognizer the parser instance /// - parameter e: the recognition exception
* @param e the recognition exception
*/
internal func reportInputMismatch(_ recognizer: Parser, internal func reportInputMismatch(_ recognizer: Parser,
_ e: InputMismatchException) { _ e: InputMismatchException) {
let msg: String = "mismatched input " + getTokenErrorDisplay(e.getOffendingToken()) + let msg: String = "mismatched input " + getTokenErrorDisplay(e.getOffendingToken()) +
@ -303,15 +277,13 @@ public class DefaultErrorStrategy: ANTLRErrorStrategy {
recognizer.notifyErrorListeners(e.getOffendingToken(), msg, e) recognizer.notifyErrorListeners(e.getOffendingToken(), msg, e)
} }
/** /// This is called by {@link #reportError} when the exception is a
* This is called by {@link #reportError} when the exception is a /// {@link org.antlr.v4.runtime.FailedPredicateException}.
* {@link org.antlr.v4.runtime.FailedPredicateException}. ///
* /// - seealso: #reportError
* @see #reportError ///
* /// - parameter recognizer: the parser instance
* @param recognizer the parser instance /// - parameter e: the recognition exception
* @param e the recognition exception
*/
internal func reportFailedPredicate(_ recognizer: Parser, internal func reportFailedPredicate(_ recognizer: Parser,
_ e: FailedPredicateException) { _ e: FailedPredicateException) {
let ruleName: String = recognizer.getRuleNames()[recognizer._ctx!.getRuleIndex()] let ruleName: String = recognizer.getRuleNames()[recognizer._ctx!.getRuleIndex()]
@ -319,24 +291,22 @@ public class DefaultErrorStrategy: ANTLRErrorStrategy {
recognizer.notifyErrorListeners(e.getOffendingToken(), msg, e) recognizer.notifyErrorListeners(e.getOffendingToken(), msg, e)
} }
/** /// This method is called to report a syntax error which requires the removal
* 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
* of a token from the input stream. At the time this method is called, the /// erroneous symbol is current {@code LT(1)} symbol and has not yet been
* erroneous symbol is current {@code LT(1)} symbol and has not yet been /// removed from the input stream. When this method returns,
* removed from the input stream. When this method returns, /// {@code recognizer} is in error recovery mode.
* {@code recognizer} is in error recovery mode. ///
* /// <p>This method is called when {@link #singleTokenDeletion} identifies
* <p>This method is called when {@link #singleTokenDeletion} identifies /// single-token deletion as a viable recovery strategy for a mismatched
* single-token deletion as a viable recovery strategy for a mismatched /// input error.</p>
* input error.</p> ///
* /// <p>The default implementation simply returns if the handler is already in
* <p>The default implementation simply returns if the handler is already in /// error recovery mode. Otherwise, it calls {@link #beginErrorCondition} to
* error recovery mode. Otherwise, it calls {@link #beginErrorCondition} to /// enter error recovery mode, followed by calling
* enter error recovery mode, followed by calling /// {@link org.antlr.v4.runtime.Parser#notifyErrorListeners}.</p>
* {@link org.antlr.v4.runtime.Parser#notifyErrorListeners}.</p> ///
* /// - parameter recognizer: the parser instance
* @param recognizer the parser instance
*/
internal func reportUnwantedToken(_ recognizer: Parser) throws { internal func reportUnwantedToken(_ recognizer: Parser) throws {
if inErrorRecoveryMode(recognizer) { if inErrorRecoveryMode(recognizer) {
return return
@ -352,23 +322,21 @@ public class DefaultErrorStrategy: ANTLRErrorStrategy {
recognizer.notifyErrorListeners(t, msg, nil) recognizer.notifyErrorListeners(t, msg, nil)
} }
/** /// This method is called to report a syntax error which requires the
* 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
* 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 is called, the missing token has not yet been inserted. When this /// method returns, {@code recognizer} is in error recovery mode.
* method returns, {@code recognizer} is in error recovery mode. ///
* /// <p>This method is called when {@link #singleTokenInsertion} identifies
* <p>This method is called when {@link #singleTokenInsertion} identifies /// single-token insertion as a viable recovery strategy for a mismatched
* single-token insertion as a viable recovery strategy for a mismatched /// input error.</p>
* input error.</p> ///
* /// <p>The default implementation simply returns if the handler is already in
* <p>The default implementation simply returns if the handler is already in /// error recovery mode. Otherwise, it calls {@link #beginErrorCondition} to
* error recovery mode. Otherwise, it calls {@link #beginErrorCondition} to /// enter error recovery mode, followed by calling
* enter error recovery mode, followed by calling /// {@link org.antlr.v4.runtime.Parser#notifyErrorListeners}.</p>
* {@link org.antlr.v4.runtime.Parser#notifyErrorListeners}.</p> ///
* /// - parameter recognizer: the parser instance
* @param recognizer the parser instance
*/
internal func reportMissingToken(_ recognizer: Parser) throws { internal func reportMissingToken(_ recognizer: Parser) throws {
if inErrorRecoveryMode(recognizer) { if inErrorRecoveryMode(recognizer) {
return return
@ -384,56 +352,54 @@ public class DefaultErrorStrategy: ANTLRErrorStrategy {
recognizer.notifyErrorListeners(t, msg, nil) recognizer.notifyErrorListeners(t, msg, nil)
} }
/** /// {@inheritDoc}
* {@inheritDoc} ///
* /// <p>The default implementation attempts to recover from the mismatched input
* <p>The default implementation attempts to recover from the mismatched input /// by using single token insertion and deletion as described below. If the
* by using single token insertion and deletion as described below. If the /// recovery attempt fails, this method throws an
* recovery attempt fails, this method throws an /// {@link org.antlr.v4.runtime.InputMismatchException}.</p>
* {@link org.antlr.v4.runtime.InputMismatchException}.</p> ///
* /// <p><strong>EXTRA TOKEN</strong> (single token deletion)</p>
* <p><strong>EXTRA TOKEN</strong> (single token deletion)</p> ///
* /// <p>{@code LA(1)} is not what we are looking for. If {@code LA(2)} has the
* <p>{@code LA(1)} is not what we are looking for. If {@code LA(2)} has the /// right token, however, then assume {@code LA(1)} is some extra spurious
* right token, however, then assume {@code LA(1)} is some extra spurious /// token and delete it. Then consume and return the next token (which was
* token and delete it. Then consume and return the next token (which was /// the {@code LA(2)} token) as the successful result of the match operation.</p>
* the {@code LA(2)} token) as the successful result of the match operation.</p> ///
* /// <p>This recovery strategy is implemented by {@link #singleTokenDeletion}.</p>
* <p>This recovery strategy is implemented by {@link #singleTokenDeletion}.</p> ///
* /// <p><strong>MISSING TOKEN</strong> (single token insertion)</p>
* <p><strong>MISSING TOKEN</strong> (single token insertion)</p> ///
* /// <p>If current token (at {@code LA(1)}) is consistent with what could come
* <p>If current token (at {@code LA(1)}) is consistent with what could come /// after the expected {@code LA(1)} token, then assume the token is missing
* after the expected {@code LA(1)} token, then assume the token is missing /// and use the parser's {@link org.antlr.v4.runtime.TokenFactory} to create it on the fly. The
* and use the parser's {@link org.antlr.v4.runtime.TokenFactory} to create it on the fly. The /// "insertion" is performed by returning the created token as the successful
* "insertion" is performed by returning the created token as the successful /// result of the match operation.</p>
* result of the match operation.</p> ///
* /// <p>This recovery strategy is implemented by {@link #singleTokenInsertion}.</p>
* <p>This recovery strategy is implemented by {@link #singleTokenInsertion}.</p> ///
* /// <p><strong>EXAMPLE</strong></p>
* <p><strong>EXAMPLE</strong></p> ///
* /// <p>For example, Input {@code i=(3;} is clearly missing the {@code ')'}. When
* <p>For example, Input {@code i=(3;} is clearly missing the {@code ')'}. When /// the parser returns from the nested call to {@code expr}, it will have
* the parser returns from the nested call to {@code expr}, it will have /// call chain:</p>
* call chain:</p> ///
* /// <pre>
* <pre> /// stat &rarr; expr &rarr; atom
* stat &rarr; expr &rarr; atom /// </pre>
* </pre> ///
* /// and it will be trying to match the {@code ')'} at this point in the
* and it will be trying to match the {@code ')'} at this point in the /// derivation:
* derivation: ///
* /// <pre>
* <pre> /// =&gt; ID '=' '(' INT ')' ('+' atom)* ';'
* =&gt; ID '=' '(' INT ')' ('+' atom)* ';' /// ^
* ^ /// </pre>
* </pre> ///
* /// The attempt to match {@code ')'} will fail when it sees {@code ';'} and
* The attempt to match {@code ')'} will fail when it sees {@code ';'} and /// call {@link #recoverInline}. To recover, it sees that {@code LA(1)==';'}
* call {@link #recoverInline}. To recover, it sees that {@code LA(1)==';'} /// is in the set of tokens that can follow the {@code ')'} token reference
* is in the set of tokens that can follow the {@code ')'} token reference /// in rule {@code atom}. It can assume that you forgot the {@code ')'}.
* in rule {@code atom}. It can assume that you forgot the {@code ')'}.
*/
public func recoverInline(_ recognizer: Parser) throws -> Token { public func recoverInline(_ recognizer: Parser) throws -> Token {
// SINGLE TOKEN DELETION // SINGLE TOKEN DELETION
@ -456,23 +422,21 @@ public class DefaultErrorStrategy: ANTLRErrorStrategy {
//throwException() /* throw InputMismatchException(recognizer); */ //throwException() /* throw InputMismatchException(recognizer); */
} }
/** /// This method implements the single-token insertion inline error recovery
* This method implements the single-token insertion inline error recovery /// strategy. It is called by {@link #recoverInline} if the single-token
* strategy. It is called by {@link #recoverInline} if the single-token /// deletion strategy fails to recover from the mismatched input. If this
* deletion strategy fails to recover from the mismatched input. If this /// method returns {@code true}, {@code recognizer} will be in error recovery
* method returns {@code true}, {@code recognizer} will be in error recovery /// mode.
* mode. ///
* /// <p>This method determines whether or not single-token insertion is viable by
* <p>This method determines whether or not single-token insertion is viable by /// checking if the {@code LA(1)} input symbol could be successfully matched
* checking if the {@code LA(1)} input symbol could be successfully matched /// if it were instead the {@code LA(2)} symbol. If this method returns
* if it were instead the {@code LA(2)} symbol. If this method returns /// {@code true}, the caller is responsible for creating and inserting a
* {@code true}, the caller is responsible for creating and inserting a /// token with the correct type to produce this behavior.</p>
* token with the correct type to produce this behavior.</p> ///
* /// - parameter recognizer: the parser instance
* @param recognizer the parser instance /// - returns: {@code true} if single-token insertion is a viable recovery
* @return {@code true} if single-token insertion is a viable recovery /// strategy for the current mismatched input, otherwise {@code false}
* strategy for the current mismatched input, otherwise {@code false}
*/
internal func singleTokenInsertion(_ recognizer: Parser) throws -> Bool { internal func singleTokenInsertion(_ recognizer: Parser) throws -> Bool {
let currentSymbolType: Int = try getTokenStream(recognizer).LA(1) let currentSymbolType: Int = try getTokenStream(recognizer).LA(1)
// if current token is consistent with what could come after current // if current token is consistent with what could come after current
@ -490,36 +454,32 @@ public class DefaultErrorStrategy: ANTLRErrorStrategy {
return false return false
} }
/** /// This method implements the single-token deletion inline error recovery
* This method implements the single-token deletion inline error recovery /// strategy. It is called by {@link #recoverInline} to attempt to recover
* strategy. It is called by {@link #recoverInline} to attempt to recover /// from mismatched input. If this method returns null, the parser and error
* from mismatched input. If this method returns null, the parser and error /// handler state will not have changed. If this method returns non-null,
* handler state will not have changed. If this method returns non-null, /// {@code recognizer} will <em>not</em> be in error recovery mode since the
* {@code recognizer} will <em>not</em> be in error recovery mode since the /// returned token was a successful match.
* returned token was a successful match. ///
* /// <p>If the single-token deletion is successful, this method calls
* <p>If the single-token deletion is successful, this method calls /// {@link #reportUnwantedToken} to report the error, followed by
* {@link #reportUnwantedToken} to report the error, followed by /// {@link org.antlr.v4.runtime.Parser#consume} to actually "delete" the extraneous token. Then,
* {@link org.antlr.v4.runtime.Parser#consume} to actually "delete" the extraneous token. Then, /// before returning {@link #reportMatch} is called to signal a successful
* before returning {@link #reportMatch} is called to signal a successful /// match.</p>
* match.</p> ///
* /// - parameter recognizer: the parser instance
* @param recognizer the parser instance /// - returns: the successfully matched {@link org.antlr.v4.runtime.Token} instance if single-token
* @return the successfully matched {@link org.antlr.v4.runtime.Token} instance if single-token /// deletion successfully recovers from the mismatched input, otherwise
* deletion successfully recovers from the mismatched input, otherwise /// {@code null}
* {@code null}
*/
internal func singleTokenDeletion(_ recognizer: Parser) throws -> Token? { internal func singleTokenDeletion(_ recognizer: Parser) throws -> Token? {
let nextTokenType: Int = try getTokenStream(recognizer).LA(2) let nextTokenType: Int = try getTokenStream(recognizer).LA(2)
let expecting: IntervalSet = try getExpectedTokens(recognizer) let expecting: IntervalSet = try getExpectedTokens(recognizer)
if expecting.contains(nextTokenType) { if expecting.contains(nextTokenType) {
try reportUnwantedToken(recognizer) try reportUnwantedToken(recognizer)
/* /// errPrint("recoverFromMismatchedToken deleting "+
errPrint("recoverFromMismatchedToken deleting "+ /// ((TokenStream)getTokenStream(recognizer)).LT(1)+
((TokenStream)getTokenStream(recognizer)).LT(1)+ /// " since "+((TokenStream)getTokenStream(recognizer)).LT(2)+
" since "+((TokenStream)getTokenStream(recognizer)).LT(2)+ /// " is what we want");
" is what we want");
*/
try recognizer.consume() // simply delete extra token try recognizer.consume() // simply delete extra token
// we want to return the token we're actually matching // we want to return the token we're actually matching
let matchedSymbol: Token = try recognizer.getCurrentToken() let matchedSymbol: Token = try recognizer.getCurrentToken()
@ -529,25 +489,24 @@ public class DefaultErrorStrategy: ANTLRErrorStrategy {
return nil return nil
} }
/** Conjure up a missing token during error recovery. /// Conjure up a missing token during error recovery.
* ///
* The recognizer attempts to recover from single missing /// The recognizer attempts to recover from single missing
* symbols. But, actions might refer to that missing symbol. /// symbols. But, actions might refer to that missing symbol.
* For example, x=ID {f($x);}. The action clearly assumes /// For example, x=ID {f($x);}. The action clearly assumes
* that there has been an identifier matched previously and that /// that there has been an identifier matched previously and that
* $x points at that token. If that token is missing, but /// $x points at that token. If that token is missing, but
* the next token in the stream is what we want we assume that /// the next token in the stream is what we want we assume that
* this token is missing and we keep going. Because we /// this token is missing and we keep going. Because we
* have to return some token to replace the missing token, /// have to return some token to replace the missing token,
* we have to conjure one up. This method gives the user control /// we have to conjure one up. This method gives the user control
* over the tokens returned for missing tokens. Mostly, /// over the tokens returned for missing tokens. Mostly,
* you will want to create something special for identifier /// you will want to create something special for identifier
* tokens. For literals such as '{' and ',', the default /// tokens. For literals such as '{' and ',', the default
* action in the parser or tree parser works. It simply creates /// action in the parser or tree parser works. It simply creates
* a CommonToken of the appropriate type. The text will be the token. /// a CommonToken of the appropriate type. The text will be the token.
* If you change what tokens must be created by the lexer, /// If you change what tokens must be created by the lexer,
* override this method to create the appropriate tokens. /// override this method to create the appropriate tokens.
*/
internal func getTokenStream(_ recognizer: Parser) -> TokenStream { internal func getTokenStream(_ recognizer: Parser) -> TokenStream {
return recognizer.getInputStream() as! TokenStream return recognizer.getInputStream() as! TokenStream
@ -582,14 +541,13 @@ public class DefaultErrorStrategy: ANTLRErrorStrategy {
return try recognizer.getExpectedTokens() return try recognizer.getExpectedTokens()
} }
/** How should a token be displayed in an error message? The default /// How should a token be displayed in an error message? The default
* is to display just the text, but during development you might /// is to display just the text, but during development you might
* want to have a lot of information spit out. Override in that case /// want to have a lot of information spit out. Override in that case
* to use t.toString() (which, for CommonToken, dumps everything about /// to use t.toString() (which, for CommonToken, dumps everything about
* the token). This is better than forcing you to override a method in /// 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 /// your token objects because you don't have to go modify your lexer
* so that it creates a new Java type. /// so that it creates a new Java type.
*/
internal func getTokenErrorDisplay(_ t: Token?) -> String { internal func getTokenErrorDisplay(_ t: Token?) -> String {
if t == nil { if t == nil {
return "<no token>" return "<no token>"
@ -622,98 +580,97 @@ public class DefaultErrorStrategy: ANTLRErrorStrategy {
return "'" + s + "'" return "'" + s + "'"
} }
/* Compute the error recovery set for the current rule. During /// Compute the error recovery set for the current rule. During
* rule invocation, the parser pushes the set of tokens that can /// rule invocation, the parser pushes the set of tokens that can
* follow that rule reference on the stack; this amounts to /// follow that rule reference on the stack; this amounts to
* computing FIRST of what follows the rule reference in the /// computing FIRST of what follows the rule reference in the
* enclosing rule. See LinearApproximator.FIRST(). /// enclosing rule. See LinearApproximator.FIRST().
* This local follow set only includes tokens /// This local follow set only includes tokens
* from within the rule; i.e., the FIRST computation done by /// from within the rule; i.e., the FIRST computation done by
* ANTLR stops at the end of a rule. /// ANTLR stops at the end of a rule.
* ///
* EXAMPLE /// EXAMPLE
* ///
* When you find a "no viable alt exception", the input is not /// When you find a "no viable alt exception", the input is not
* consistent with any of the alternatives for rule r. The best /// consistent with any of the alternatives for rule r. The best
* thing to do is to consume tokens until you see something that /// 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. /// 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 /// You don't want the exact set of viable next tokens because the
* input might just be missing a token--you might consume the /// input might just be missing a token--you might consume the
* rest of the input looking for one of the missing tokens. /// rest of the input looking for one of the missing tokens.
* ///
* Consider grammar: /// Consider grammar:
* ///
* a : '[' b ']' /// a : '[' b ']'
* | '(' b ')' /// | '(' b ')'
* ; /// ;
* b : c '^' INT ; /// b : c '^' INT ;
* c : ID /// c : ID
* | INT /// | INT
* ; /// ;
* ///
* At each rule invocation, the set of tokens that could follow /// At each rule invocation, the set of tokens that could follow
* that rule is pushed on a stack. Here are the various /// that rule is pushed on a stack. Here are the various
* context-sensitive follow sets: /// context-sensitive follow sets:
* ///
* FOLLOW(b1_in_a) = FIRST(']') = ']' /// FOLLOW(b1_in_a) = FIRST(']') = ']'
* FOLLOW(b2_in_a) = FIRST(')') = ')' /// FOLLOW(b2_in_a) = FIRST(')') = ')'
* FOLLOW(c_in_b) = FIRST('^') = '^' /// FOLLOW(c_in_b) = FIRST('^') = '^'
* ///
* Upon erroneous input "[]", the call chain is /// Upon erroneous input "[]", the call chain is
* ///
* a -> b -> c /// a -> b -> c
* ///
* and, hence, the follow context stack is: /// and, hence, the follow context stack is:
* ///
* depth follow set start of rule execution /// depth follow set start of rule execution
* 0 <EOF> a (from main()) /// 0 <EOF> a (from main())
* 1 ']' b /// 1 ']' b
* 2 '^' c /// 2 '^' c
* ///
* Notice that ')' is not included, because b would have to have /// Notice that ')' is not included, because b would have to have
* been called from a different context in rule a for ')' to be /// been called from a different context in rule a for ')' to be
* included. /// included.
* ///
* For error recovery, we cannot consider FOLLOW(c) /// For error recovery, we cannot consider FOLLOW(c)
* (context-sensitive or otherwise). We need the combined set of /// (context-sensitive or otherwise). We need the combined set of
* all context-sensitive FOLLOW sets--the set of all tokens that /// all context-sensitive FOLLOW sets--the set of all tokens that
* could follow any reference in the call chain. We need to /// could follow any reference in the call chain. We need to
* resync to one of those tokens. Note that FOLLOW(c)='^' and if /// resync to one of those tokens. Note that FOLLOW(c)='^' and if
* we resync'd to that token, we'd consume until EOF. We need to /// we resync'd to that token, we'd consume until EOF. We need to
* sync to context-sensitive FOLLOWs for a, b, and c: {']','^'}. /// 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 /// 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 /// not consume anything. After printing an error, rule c would
* return normally. Rule b would not find the required '^' though. /// return normally. Rule b would not find the required '^' though.
* At this point, it gets a mismatched token error and throws an /// At this point, it gets a mismatched token error and throws an
* exception (since LA(1) is not in the viable following token /// exception (since LA(1) is not in the viable following token
* set). The rule exception handler tries to recover, but finds /// set). The rule exception handler tries to recover, but finds
* the same recovery set and doesn't consume anything. Rule b /// the same recovery set and doesn't consume anything. Rule b
* exits normally returning to rule a. Now it finds the ']' (and /// exits normally returning to rule a. Now it finds the ']' (and
* with the successful match exits errorRecovery mode). /// with the successful match exits errorRecovery mode).
* ///
* So, you can see that the parser walks up the call chain looking /// So, you can see that the parser walks up the call chain looking
* for the token that was a member of the recovery set. /// for the token that was a member of the recovery set.
* ///
* Errors are not generated in errorRecovery mode. /// Errors are not generated in errorRecovery mode.
* ///
* ANTLR's error recovery mechanism is based upon original ideas: /// ANTLR's error recovery mechanism is based upon original ideas:
* ///
* "Algorithms + Data Structures = Programs" by Niklaus Wirth /// "Algorithms + Data Structures = Programs" by Niklaus Wirth
* ///
* and /// and
* ///
* "A note on error recovery in recursive descent parsers": /// "A note on error recovery in recursive descent parsers":
* http://portal.acm.org/citation.cfm?id=947902.947905 /// http://portal.acm.org/citation.cfm?id=947902.947905
* ///
* Later, Josef Grosch had some good ideas: /// Later, Josef Grosch had some good ideas:
* ///
* "Efficient and Comfortable Error Recovery in Recursive Descent /// "Efficient and Comfortable Error Recovery in Recursive Descent
* Parsers": /// Parsers":
* ftp://www.cocolab.com/products/cocktail/doca4.ps/ell.ps.zip /// ftp://www.cocolab.com/products/cocktail/doca4.ps/ell.ps.zip
* ///
* Like Grosch I implement context-sensitive FOLLOW sets that are combined /// Like Grosch I implement context-sensitive FOLLOW sets that are combined
* at run-time upon error to avoid overhead during parsing. /// at run-time upon error to avoid overhead during parsing.
*/
internal func getErrorRecoverySet(_ recognizer: Parser) throws -> IntervalSet { internal func getErrorRecoverySet(_ recognizer: Parser) throws -> IntervalSet {
let atn: ATN = recognizer.getInterpreter().atn let atn: ATN = recognizer.getInterpreter().atn
var ctx: RuleContext? = recognizer._ctx var ctx: RuleContext? = recognizer._ctx
@ -731,7 +688,7 @@ public class DefaultErrorStrategy: ANTLRErrorStrategy {
return recoverSet return recoverSet
} }
/** Consume tokens until one matches the given token set. */ /// Consume tokens until one matches the given token set.
internal func consumeUntil(_ recognizer: Parser, _ set: IntervalSet) throws { internal func consumeUntil(_ recognizer: Parser, _ set: IntervalSet) throws {
// errPrint("consumeUntil("+set.toString(recognizer.getTokenNames())+")"); // errPrint("consumeUntil("+set.toString(recognizer.getTokenNames())+")");
var ttype: Int = try getTokenStream(recognizer).LA(1) var ttype: Int = try getTokenStream(recognizer).LA(1)

View File

@ -1,54 +1,45 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** /// This implementation of {@link org.antlr.v4.runtime.ANTLRErrorListener} can be used to identify
* This implementation of {@link org.antlr.v4.runtime.ANTLRErrorListener} can be used to identify /// certain potential correctness and performance problems in grammars. "Reports"
* certain potential correctness and performance problems in grammars. "Reports" /// are made by calling {@link org.antlr.v4.runtime.Parser#notifyErrorListeners} with the appropriate
* are made by calling {@link org.antlr.v4.runtime.Parser#notifyErrorListeners} with the appropriate /// message.
* message. ///
* /// <ul>
* <ul> /// <li><b>Ambiguities</b>: These are cases where more than one path through the
* <li><b>Ambiguities</b>: These are cases where more than one path through the /// grammar can match the input.</li>
* grammar can match the input.</li> /// <li><b>Weak context sensitivity</b>: These are cases where full-context
* <li><b>Weak context sensitivity</b>: These are cases where full-context /// prediction resolved an SLL conflict to a unique alternative which equaled the
* prediction resolved an SLL conflict to a unique alternative which equaled the /// minimum alternative of the SLL conflict.</li>
* minimum alternative of the SLL conflict.</li> /// <li><b>Strong (forced) context sensitivity</b>: These are cases where the
* <li><b>Strong (forced) context sensitivity</b>: These are cases where the /// full-context prediction resolved an SLL conflict to a unique alternative,
* full-context prediction resolved an SLL conflict to a unique alternative, /// <em>and</em> the minimum alternative of the SLL conflict was found to not be
* <em>and</em> 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
* a truly viable alternative. Two-stage parsing cannot be used for inputs where /// this situation occurs.</li>
* this situation occurs.</li> /// </ul>
* </ul> ///
* /// - Sam Harwell
* @author Sam Harwell
*/
import Foundation import Foundation
public class DiagnosticErrorListener: BaseErrorListener { public class DiagnosticErrorListener: BaseErrorListener {
/** /// When {@code true}, only exactly known ambiguities are reported.
* When {@code true}, only exactly known ambiguities are reported.
*/
internal final var exactOnly: Bool internal final var exactOnly: Bool
/** /// Initializes a new instance of {@link org.antlr.v4.runtime.DiagnosticErrorListener} which only
* Initializes a new instance of {@link org.antlr.v4.runtime.DiagnosticErrorListener} which only /// reports exact ambiguities.
* reports exact ambiguities.
*/
public convenience override init() { public convenience override init() {
self.init(true) self.init(true)
} }
/** /// Initializes a new instance of {@link org.antlr.v4.runtime.DiagnosticErrorListener}, specifying
* Initializes a new instance of {@link org.antlr.v4.runtime.DiagnosticErrorListener}, specifying /// whether all ambiguities or only exact ambiguities are reported.
* whether all ambiguities or only exact ambiguities are reported. ///
* /// - parameter exactOnly: {@code true} to report only exact ambiguities, otherwise
* @param exactOnly {@code true} to report only exact ambiguities, otherwise /// {@code false} to report all ambiguities.
* {@code false} to report all ambiguities.
*/
public init(_ exactOnly: Bool) { public init(_ exactOnly: Bool) {
self.exactOnly = exactOnly self.exactOnly = exactOnly
} }
@ -120,17 +111,15 @@ public class DiagnosticErrorListener: BaseErrorListener {
return NSString(format: "%d (%@)", decision, ruleName) as String return NSString(format: "%d (%@)", decision, ruleName) as String
} }
/** /// Computes the set of conflicting or ambiguous alternatives from a
* Computes the set of conflicting or ambiguous alternatives from a /// configuration set, if that information was not already provided by the
* configuration set, if that information was not already provided by the /// parser.
* parser. ///
* /// - parameter reportedAlts: The set of conflicting or ambiguous alternatives, as
* @param reportedAlts The set of conflicting or ambiguous alternatives, as /// reported by the parser.
* reported by the parser. /// - parameter configs: The conflicting or ambiguous configuration set.
* @param configs The conflicting or ambiguous configuration set. /// - returns: Returns {@code reportedAlts} if it is not {@code null}, otherwise
* @return Returns {@code reportedAlts} if it is not {@code null}, otherwise /// returns the set of alternatives represented in {@code configs}.
* returns the set of alternatives represented in {@code configs}.
*/
internal func getConflictingAlts(_ reportedAlts: BitSet?, _ configs: ATNConfigSet) throws -> BitSet { internal func getConflictingAlts(_ reportedAlts: BitSet?, _ configs: ATNConfigSet) throws -> BitSet {
if reportedAlts != nil { if reportedAlts != nil {
return reportedAlts! return reportedAlts!

View File

@ -1,14 +1,12 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** A semantic predicate failed during validation. Validation of predicates /// A semantic predicate failed during validation. Validation of predicates
* occurs when normally parsing the alternative just like matching a token. /// occurs when normally parsing the alternative just like matching a token.
* Disambiguating predicate evaluation occurs when we test a predicate during /// Disambiguating predicate evaluation occurs when we test a predicate during
* prediction. /// prediction.
*/
public class FailedPredicateException: RecognitionException<ParserATNSimulator> { public class FailedPredicateException: RecognitionException<ParserATNSimulator> {
private final var ruleIndex: Int private final var ruleIndex: Int
private final var predicateIndex: Int private final var predicateIndex: Int

View File

@ -1,12 +1,10 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** This signifies any kind of mismatched input exceptions such as /// This signifies any kind of mismatched input exceptions such as
* when the current input does not match the expected token. /// when the current input does not match the expected token.
*/
public class InputMismatchException: RecognitionException<ParserATNSimulator> { public class InputMismatchException: RecognitionException<ParserATNSimulator> {
public init(_ recognizer: Parser) throws { public init(_ recognizer: Parser) throws {

View File

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

View File

@ -1,38 +1,33 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** /// This class extends {@link org.antlr.v4.runtime.ParserRuleContext} by allowing the value of
* This class extends {@link org.antlr.v4.runtime.ParserRuleContext} by allowing the value of /// {@link #getRuleIndex} to be explicitly set for the context.
* {@link #getRuleIndex} to be explicitly set for the context. ///
* /// <p>
* <p> /// {@link org.antlr.v4.runtime.ParserRuleContext} does not include field storage for the rule index
* {@link org.antlr.v4.runtime.ParserRuleContext} does not include field storage for the rule index /// since the context classes created by the code generator override the
* since the context classes created by the code generator override the /// {@link #getRuleIndex} method to return the correct value for that context.
* {@link #getRuleIndex} method to return the correct value for that context. /// Since the parser interpreter does not use the context classes generated for a
* Since the parser interpreter does not use the context classes generated for a /// parser, this class (with slightly more memory overhead per node) is used to
* parser, this class (with slightly more memory overhead per node) is used to /// provide equivalent functionality.</p>
* provide equivalent functionality.</p>
*/
public class InterpreterRuleContext: ParserRuleContext { public class InterpreterRuleContext: ParserRuleContext {
/** This is the backing field for {@link #getRuleIndex}. */ /// This is the backing field for {@link #getRuleIndex}.
private var ruleIndex: Int = -1 private var ruleIndex: Int = -1
public override init() { public override init() {
super.init() super.init()
} }
/** /// Constructs a new {@link org.antlr.v4.runtime.InterpreterRuleContext} with the specified
* Constructs a new {@link org.antlr.v4.runtime.InterpreterRuleContext} with the specified /// parent, invoking state, and rule index.
* parent, invoking state, and rule index. ///
* /// - parameter parent: The parent context.
* @param parent The parent context. /// - parameter invokingStateNumber: The invoking state number.
* @param invokingStateNumber The invoking state number. /// - parameter ruleIndex: The rule index for the current context.
* @param ruleIndex The rule index for the current context.
*/
public init(_ parent: ParserRuleContext?, public init(_ parent: ParserRuleContext?,
_ invokingStateNumber: Int, _ invokingStateNumber: Int,
_ ruleIndex: Int) { _ ruleIndex: Int) {
@ -46,10 +41,9 @@ public class InterpreterRuleContext: ParserRuleContext {
return ruleIndex return ruleIndex
} }
/** Copy a {@link org.antlr.v4.runtime.ParserRuleContext} or {@link org.antlr.v4.runtime.InterpreterRuleContext} /// Copy a {@link org.antlr.v4.runtime.ParserRuleContext} or {@link org.antlr.v4.runtime.InterpreterRuleContext}
* stack to a {@link org.antlr.v4.runtime.InterpreterRuleContext} tree. /// stack to a {@link org.antlr.v4.runtime.InterpreterRuleContext} tree.
* Return {@link null} if {@code ctx} is null. /// Return {@link null} if {@code ctx} is null.
*/
public static func fromParserRuleContext(_ ctx: ParserRuleContext?) -> InterpreterRuleContext? { public static func fromParserRuleContext(_ ctx: ParserRuleContext?) -> InterpreterRuleContext? {
guard let ctx = ctx else { guard let ctx = ctx else {
return nil return nil

View File

@ -1,14 +1,12 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** A lexer is recognizer that draws input symbols from a character stream. /// A lexer is recognizer that draws input symbols from a character stream.
* lexer grammars result in a subclass of this object. A Lexer object /// lexer grammars result in a subclass of this object. A Lexer object
* uses simplified match() and error recovery mechanisms in the interest /// uses simplified match() and error recovery mechanisms in the interest
* of speed. /// of speed.
*/
import Foundation import Foundation
@ -29,48 +27,44 @@ open class Lexer: Recognizer<LexerATNSimulator>
public var _input: CharStream? public var _input: CharStream?
internal var _tokenFactorySourcePair: (TokenSource?, CharStream?) internal var _tokenFactorySourcePair: (TokenSource?, CharStream?)
/** How to create token objects */ /// How to create token objects
internal var _factory: TokenFactory = CommonTokenFactory.DEFAULT internal var _factory: TokenFactory = CommonTokenFactory.DEFAULT
/** The goal of all lexer rules/methods is to create a token object. /// The goal of all lexer rules/methods is to create a token object.
* This is an instance variable as multiple rules may collaborate to /// This is an instance variable as multiple rules may collaborate to
* create a single token. nextToken will return this object after /// create a single token. nextToken will return this object after
* matching lexer rule(s). If you subclass to allow multiple token /// matching lexer rule(s). If you subclass to allow multiple token
* emissions, then set this to the last token to be matched or /// emissions, then set this to the last token to be matched or
* something nonnull so that the auto token emit mechanism will not /// something nonnull so that the auto token emit mechanism will not
* emit another token. /// emit another token.
*/
public var _token: Token? public var _token: Token?
/** What character index in the stream did the current token start at? /// What character index in the stream did the current token start at?
* Needed, for example, to get the text for current token. Set at /// Needed, for example, to get the text for current token. Set at
* the start of nextToken. /// the start of nextToken.
*/
public var _tokenStartCharIndex: Int = -1 public var _tokenStartCharIndex: Int = -1
/** The line on which the first character of the token resides */ /// The line on which the first character of the token resides
public var _tokenStartLine: Int = 0 public var _tokenStartLine: Int = 0
/** The character position of first character within the line */ /// The character position of first character within the line
public var _tokenStartCharPositionInLine: Int = 0 public var _tokenStartCharPositionInLine: Int = 0
/** Once we see EOF on char stream, next token will be EOF. /// Once we see EOF on char stream, next token will be EOF.
* If you have DONE : EOF ; then you see DONE EOF. /// If you have DONE : EOF ; then you see DONE EOF.
*/
public var _hitEOF: Bool = false public var _hitEOF: Bool = false
/** The channel number for the current token */ /// The channel number for the current token
public var _channel: Int = 0 public var _channel: Int = 0
/** The token type for the current token */ /// The token type for the current token
public var _type: Int = 0 public var _type: Int = 0
public final var _modeStack: Stack<Int> = Stack<Int>() public final var _modeStack: Stack<Int> = Stack<Int>()
public var _mode: Int = Lexer.DEFAULT_MODE public var _mode: Int = Lexer.DEFAULT_MODE
/** You can set the text for the current token to override what is in /// 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. /// the input char buffer. Use setText() or can set this instance var.
*/
public var _text: String? public var _text: String?
public override init() { public override init() {
@ -103,9 +97,8 @@ open class Lexer: Recognizer<LexerATNSimulator>
getInterpreter().reset() getInterpreter().reset()
} }
/** Return a token from this source; i.e., match a token on the char /// Return a token from this source; i.e., match a token on the char
* stream. /// stream.
*/
open func nextToken() throws -> Token { open func nextToken() throws -> Token {
guard let _input = _input else { guard let _input = _input else {
@ -168,12 +161,11 @@ open class Lexer: Recognizer<LexerATNSimulator>
} }
/** Instruct the lexer to skip creating a token for current lexer rule /// Instruct the lexer to skip creating a token for current lexer rule
* and look for another token. nextToken() knows to keep looking when /// and look for another token. nextToken() knows to keep looking when
* a lexer rule finishes with token set to SKIP_TOKEN. Recall that /// 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 /// if token==null at end of any token rule, it creates one for you
* and emits it. /// and emits it.
*/
open func skip() { open func skip() {
_type = Lexer.SKIP _type = Lexer.SKIP
} }
@ -218,7 +210,7 @@ open class Lexer: Recognizer<LexerATNSimulator>
return _factory return _factory
} }
/** Set the char stream and reset the lexer */ /// Set the char stream and reset the lexer
open override func setInputStream(_ input: IntStream) throws { open override func setInputStream(_ input: IntStream) throws {
self._input = nil self._input = nil
@ -238,22 +230,20 @@ open class Lexer: Recognizer<LexerATNSimulator>
return _input return _input
} }
/** By default does not support multiple emits per nextToken invocation /// By default does not support multiple emits per nextToken invocation
* for efficiency reasons. Subclass and override this method, nextToken, /// for efficiency reasons. Subclass and override this method, nextToken,
* and getToken (to push tokens into a list and pull from that list /// and getToken (to push tokens into a list and pull from that list
* rather than a single variable as this implementation does). /// rather than a single variable as this implementation does).
*/
open func emit(_ token: Token) { open func emit(_ token: Token) {
//System.err.println("emit "+token); //System.err.println("emit "+token);
self._token = token self._token = token
} }
/** The standard method called to automatically emit a token at the /// The standard method called to automatically emit a token at the
* outermost lexical rule. The token object should point into the /// outermost lexical rule. The token object should point into the
* char buffer start..stop. If there is a text override in 'text', /// 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 /// use that to set the token's text. Override this method to emit
* custom Token objects or provide a new factory. /// custom Token objects or provide a new factory.
*/
@discardableResult @discardableResult
open func emit() -> Token { open func emit() -> Token {
let t: Token = _factory.create(_tokenFactorySourcePair, _type, _text, _channel, _tokenStartCharIndex, getCharIndex() - 1, let t: Token = _factory.create(_tokenFactorySourcePair, _type, _text, _channel, _tokenStartCharIndex, getCharIndex() - 1,
@ -296,14 +286,13 @@ open class Lexer: Recognizer<LexerATNSimulator>
getInterpreter().setCharPositionInLine(charPositionInLine) getInterpreter().setCharPositionInLine(charPositionInLine)
} }
/** What is the index of the current character of lookahead? */ /// What is the index of the current character of lookahead?
open func getCharIndex() -> Int { open func getCharIndex() -> Int {
return _input!.index() return _input!.index()
} }
/** Return the text matched so far for the current token or any /// Return the text matched so far for the current token or any
* text override. /// text override.
*/
open func getText() -> String { open func getText() -> String {
if _text != nil { if _text != nil {
return _text! return _text!
@ -311,14 +300,13 @@ open class Lexer: Recognizer<LexerATNSimulator>
return getInterpreter().getText(_input!) return getInterpreter().getText(_input!)
} }
/** Set the complete text of this token; it wipes any previous /// Set the complete text of this token; it wipes any previous
* changes to the text. /// changes to the text.
*/
open func setText(_ text: String) { open func setText(_ text: String) {
self._text = text self._text = text
} }
/** Override if emitting multiple tokens. */ /// Override if emitting multiple tokens.
open func getToken() -> Token { open func getToken() -> Token {
return _token! return _token!
} }
@ -347,18 +335,16 @@ open class Lexer: Recognizer<LexerATNSimulator>
return nil return nil
} }
/** Used to print out token names like ID during debugging and /// Used to print out token names like ID during debugging and
* error reporting. The generated parsers implement a method /// error reporting. The generated parsers implement a method
* that overrides this to point to their String[] tokenNames. /// that overrides this to point to their String[] tokenNames.
*/
override override
open func getTokenNames() -> [String?]? { open func getTokenNames() -> [String?]? {
return nil return nil
} }
/** Return a list of all Token objects in input char stream. /// Return a list of all Token objects in input char stream.
* Forces load of all tokens. Does not include EOF token. /// Forces load of all tokens. Does not include EOF token.
*/
open func getAllTokens() throws -> Array<Token> { open func getAllTokens() throws -> Array<Token> {
var tokens: Array<Token> = Array<Token>() var tokens: Array<Token> = Array<Token>()
var t: Token = try nextToken() var t: Token = try nextToken()
@ -419,11 +405,10 @@ open class Lexer: Recognizer<LexerATNSimulator>
return "'\(s)'" return "'\(s)'"
} }
/** Lexers can normally match any char in it's vocabulary after matching /// 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 /// 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 /// it all works out. You can instead use the rule invocation stack
* to do sophisticated error recovery if you are in a fragment rule. /// to do sophisticated error recovery if you are in a fragment rule.
*/
//public func recover(re : RecognitionException) { //public func recover(re : RecognitionException) {
open func recover(_ re: AnyObject) throws { open func recover(_ re: AnyObject) throws {

View File

@ -1,7 +1,6 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
public class LexerInterpreter: Lexer { public class LexerInterpreter: Lexer {

View File

@ -1,14 +1,13 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
public class LexerNoViableAltException: RecognitionException<LexerATNSimulator>, CustomStringConvertible { public class LexerNoViableAltException: RecognitionException<LexerATNSimulator>, CustomStringConvertible {
/** Matching attempted at what input index? */ /// Matching attempted at what input index?
private final var startIndex: Int private final var startIndex: Int
/** Which configurations did we try at input.index() that couldn't match input.LA(1)? */ /// Which configurations did we try at input.index() that couldn't match input.LA(1)?
private final var deadEndConfigs: ATNConfigSet private final var deadEndConfigs: ATNConfigSet
public init(_ lexer: Lexer?, public init(_ lexer: Lexer?,

View File

@ -1,83 +1,64 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** /// Provides an implementation of {@link org.antlr.v4.runtime.TokenSource} as a wrapper around a list
* Provides an implementation of {@link org.antlr.v4.runtime.TokenSource} as a wrapper around a list /// of {@link org.antlr.v4.runtime.Token} objects.
* of {@link org.antlr.v4.runtime.Token} objects. ///
* /// <p>If the final token in the list is an {@link org.antlr.v4.runtime.Token#EOF} token, it will be used
* <p>If the final token in the list is an {@link org.antlr.v4.runtime.Token#EOF} token, it will be used /// as the EOF token for every call to {@link #nextToken} after the end of the
* as the EOF token for every call to {@link #nextToken} after the end of the /// list is reached. Otherwise, an EOF token will be created.</p>
* list is reached. Otherwise, an EOF token will be created.</p>
*/
public class ListTokenSource: TokenSource { public class ListTokenSource: TokenSource {
/** /// The wrapped collection of {@link org.antlr.v4.runtime.Token} objects to return.
* The wrapped collection of {@link org.antlr.v4.runtime.Token} objects to return.
*/
internal final var tokens: Array<Token> internal final var tokens: Array<Token>
/** /// The name of the input source. If this value is {@code null}, a call to
* The name of the input source. If this value is {@code null}, a call to /// {@link #getSourceName} should return the source name used to create the
* {@link #getSourceName} should return the source name used to create the /// the next token in {@link #tokens} (or the previous token if the end of
* the next token in {@link #tokens} (or the previous token if the end of /// the input has been reached).
* the input has been reached).
*/
private final var sourceName: String? private final var sourceName: String?
/** /// The index into {@link #tokens} of token to return by the next call to
* The index into {@link #tokens} of token to return by the next call to /// {@link #nextToken}. The end of the input is indicated by this value
* {@link #nextToken}. The end of the input is indicated by this value /// being greater than or equal to the number of items in {@link #tokens}.
* being greater than or equal to the number of items in {@link #tokens}.
*/
internal var i: Int = 0 internal var i: Int = 0
/** /// This field caches the EOF token for the token source.
* This field caches the EOF token for the token source.
*/
internal var eofToken: Token? internal var eofToken: Token?
/** /// This is the backing field for {@link #getTokenFactory} and
* This is the backing field for {@link #getTokenFactory} and /// {@link setTokenFactory}.
* {@link setTokenFactory}.
*/
private var _factory: TokenFactory = CommonTokenFactory.DEFAULT private var _factory: TokenFactory = CommonTokenFactory.DEFAULT
/** /// Constructs a new {@link org.antlr.v4.runtime.ListTokenSource} instance from the specified
* Constructs a new {@link org.antlr.v4.runtime.ListTokenSource} instance from the specified /// collection of {@link org.antlr.v4.runtime.Token} objects.
* collection of {@link org.antlr.v4.runtime.Token} objects. ///
* /// - parameter tokens: The collection of {@link org.antlr.v4.runtime.Token} objects to provide as a
* @param tokens The collection of {@link org.antlr.v4.runtime.Token} objects to provide as a /// {@link org.antlr.v4.runtime.TokenSource}.
* {@link org.antlr.v4.runtime.TokenSource}. /// - NullPointerException if {@code tokens} is {@code null}
* @exception NullPointerException if {@code tokens} is {@code null}
*/
public convenience init(_ tokens: Array<Token>) { public convenience init(_ tokens: Array<Token>) {
self.init(tokens, nil) self.init(tokens, nil)
} }
/** /// Constructs a new {@link org.antlr.v4.runtime.ListTokenSource} instance from the specified
* Constructs a new {@link org.antlr.v4.runtime.ListTokenSource} instance from the specified /// collection of {@link org.antlr.v4.runtime.Token} objects and source name.
* collection of {@link org.antlr.v4.runtime.Token} objects and source name. ///
* /// - parameter tokens: The collection of {@link org.antlr.v4.runtime.Token} objects to provide as a
* @param tokens The collection of {@link org.antlr.v4.runtime.Token} objects to provide as a /// {@link org.antlr.v4.runtime.TokenSource}.
* {@link org.antlr.v4.runtime.TokenSource}. /// - parameter sourceName: The name of the {@link org.antlr.v4.runtime.TokenSource}. If this value is
* @param sourceName The name of the {@link org.antlr.v4.runtime.TokenSource}. If this value is /// {@code null}, {@link #getSourceName} will attempt to infer the name from
* {@code null}, {@link #getSourceName} will attempt to infer the name from /// the next {@link org.antlr.v4.runtime.Token} (or the previous token if the end of the input has
* the next {@link org.antlr.v4.runtime.Token} (or the previous token if the end of the input has /// been reached).
* been reached). ///
* /// - NullPointerException if {@code tokens} is {@code null}
* @exception NullPointerException if {@code tokens} is {@code null}
*/
public init(_ tokens: Array<Token>, _ sourceName: String?) { public init(_ tokens: Array<Token>, _ sourceName: String?) {
self.tokens = tokens self.tokens = tokens
self.sourceName = sourceName self.sourceName = sourceName
} }
/** /// {@inheritDoc}
* {@inheritDoc}
*/
public func getCharPositionInLine() -> Int { public func getCharPositionInLine() -> Int {
if i < tokens.count { if i < tokens.count {
@ -111,9 +92,7 @@ public class ListTokenSource: TokenSource {
return 0 return 0
} }
/** /// {@inheritDoc}
* {@inheritDoc}
*/
public func nextToken() -> Token { public func nextToken() -> Token {
if i >= tokens.count { if i >= tokens.count {
@ -142,9 +121,7 @@ public class ListTokenSource: TokenSource {
return t return t
} }
/** /// {@inheritDoc}
* {@inheritDoc}
*/
public func getLine() -> Int { public func getLine() -> Int {
if i < tokens.count { if i < tokens.count {
@ -179,9 +156,7 @@ public class ListTokenSource: TokenSource {
return 1 return 1
} }
/** /// {@inheritDoc}
* {@inheritDoc}
*/
public func getInputStream() -> CharStream? { public func getInputStream() -> CharStream? {
if i < tokens.count { if i < tokens.count {
@ -200,9 +175,7 @@ public class ListTokenSource: TokenSource {
return nil return nil
} }
/** /// {@inheritDoc}
* {@inheritDoc}
*/
public func getSourceName() -> String { public func getSourceName() -> String {
if sourceName != nil { if sourceName != nil {
@ -216,17 +189,13 @@ public class ListTokenSource: TokenSource {
return "List" return "List"
} }
/** /// {@inheritDoc}
* {@inheritDoc}
*/
public func setTokenFactory(_ factory: TokenFactory) { public func setTokenFactory(_ factory: TokenFactory) {
self._factory = factory self._factory = factory
} }
/** /// {@inheritDoc}
* {@inheritDoc}
*/
public func getTokenFactory() -> TokenFactory { public func getTokenFactory() -> TokenFactory {
return _factory return _factory

View File

@ -1,7 +1,6 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
public class ATN { public class ATN {
@ -10,75 +9,59 @@ public class ATN {
public final var states: Array<ATNState?> = Array<ATNState?>() public final var states: Array<ATNState?> = Array<ATNState?>()
/** Each subrule/rule is a decision point and we must track them so we /// Each subrule/rule is a decision point and we must track them so we
* can go back later and build DFA predictors for them. This includes /// can go back later and build DFA predictors for them. This includes
* all the rules, subrules, optional blocks, ()+, ()* etc... /// all the rules, subrules, optional blocks, ()+, ()* etc...
*/
public final var decisionToState: Array<DecisionState> = Array<DecisionState>() public final var decisionToState: Array<DecisionState> = Array<DecisionState>()
/** /// Maps from rule index to starting state number.
* Maps from rule index to starting state number.
*/
public final var ruleToStartState: [RuleStartState]! public final var ruleToStartState: [RuleStartState]!
/** /// Maps from rule index to stop state number.
* Maps from rule index to stop state number.
*/
public final var ruleToStopState: [RuleStopState]! public final var ruleToStopState: [RuleStopState]!
public final let modeNameToStartState: Dictionary<String, TokensStartState> = Dictionary<String, TokensStartState>() public final let modeNameToStartState: Dictionary<String, TokensStartState> = Dictionary<String, TokensStartState>()
//LinkedHashMap<String, TokensStartState>(); //LinkedHashMap<String, TokensStartState>();
/** /// The type of the ATN.
* The type of the ATN.
*/
public let grammarType: ATNType! public let grammarType: ATNType!
/** /// The maximum value for any symbol recognized by a transition in the ATN.
* The maximum value for any symbol recognized by a transition in the ATN.
*/
public let maxTokenType: Int public let maxTokenType: Int
/** /// For lexer ATNs, this maps the rule index to the resulting token type.
* For lexer ATNs, this maps the rule index to the resulting token type. /// For parser ATNs, this maps the rule index to the generated bypass token
* For parser ATNs, this maps the rule index to the generated bypass token /// type if the
* type if the /// {@link org.antlr.v4.runtime.atn.ATNDeserializationOptions#isGenerateRuleBypassTransitions}
* {@link org.antlr.v4.runtime.atn.ATNDeserializationOptions#isGenerateRuleBypassTransitions} /// deserialization option was specified; otherwise, this is {@code null}.
* deserialization option was specified; otherwise, this is {@code null}.
*/
public final var ruleToTokenType: [Int]! public final var ruleToTokenType: [Int]!
/** /// For lexer ATNs, this is an array of {@link org.antlr.v4.runtime.atn.LexerAction} objects which may
* For lexer ATNs, this is an array of {@link org.antlr.v4.runtime.atn.LexerAction} objects which may /// be referenced by action transitions in the ATN.
* be referenced by action transitions in the ATN.
*/
public final var lexerActions: [LexerAction]! public final var lexerActions: [LexerAction]!
public final var modeToStartState: Array<TokensStartState> = Array<TokensStartState>() public final var modeToStartState: Array<TokensStartState> = Array<TokensStartState>()
/** Used for runtime deserialization of ATNs from strings */ /// Used for runtime deserialization of ATNs from strings
public init(_ grammarType: ATNType, _ maxTokenType: Int) { public init(_ grammarType: ATNType, _ maxTokenType: Int) {
self.grammarType = grammarType self.grammarType = grammarType
self.maxTokenType = maxTokenType self.maxTokenType = maxTokenType
} }
/** Compute the set of valid tokens that can occur starting in state {@code s}. /// Compute the set of valid tokens that can occur starting in state {@code s}.
* If {@code ctx} is null, the set of tokens will not include what can follow /// If {@code ctx} is null, the set of tokens will not include what can follow
* the rule surrounding {@code s}. In other words, the set will be /// the rule surrounding {@code s}. In other words, the set will be
* restricted to tokens reachable staying within {@code s}'s rule. /// restricted to tokens reachable staying within {@code s}'s rule.
*/
public func nextTokens(_ s: ATNState, _ ctx: RuleContext?)throws -> IntervalSet { public func nextTokens(_ s: ATNState, _ ctx: RuleContext?)throws -> IntervalSet {
let anal: LL1Analyzer = LL1Analyzer(self) let anal: LL1Analyzer = LL1Analyzer(self)
let next: IntervalSet = try anal.LOOK(s, ctx) let next: IntervalSet = try anal.LOOK(s, ctx)
return next return next
} }
/** /// Compute the set of valid tokens that can occur starting in {@code s} and
* Compute the set of valid tokens that can occur starting in {@code s} and /// staying in same rule. {@link org.antlr.v4.runtime.Token#EPSILON} is in set if we reach end of
* staying in same rule. {@link org.antlr.v4.runtime.Token#EPSILON} is in set if we reach end of /// rule.
* rule.
*/
public func nextTokens(_ s: ATNState) throws -> IntervalSet { public func nextTokens(_ s: ATNState) throws -> IntervalSet {
if let nextTokenWithinRule = s.nextTokenWithinRule if let nextTokenWithinRule = s.nextTokenWithinRule
{ {
@ -121,29 +104,27 @@ public class ATN {
return decisionToState.count return decisionToState.count
} }
/** /// Computes the set of input symbols which could follow ATN state number
* Computes the set of input symbols which could follow ATN state number /// {@code stateNumber} in the specified full {@code context}. This method
* {@code stateNumber} in the specified full {@code context}. This method /// considers the complete parser context, but does not evaluate semantic
* considers the complete parser context, but does not evaluate semantic /// predicates (i.e. all predicates encountered during the calculation are
* predicates (i.e. all predicates encountered during the calculation are /// assumed true). If a path in the ATN exists from the starting state to the
* assumed true). If a path in the ATN exists from the starting state to the /// {@link org.antlr.v4.runtime.atn.RuleStopState} of the outermost context without matching any
* {@link org.antlr.v4.runtime.atn.RuleStopState} of the outermost context without matching any /// symbols, {@link org.antlr.v4.runtime.Token#EOF} is added to the returned set.
* symbols, {@link org.antlr.v4.runtime.Token#EOF} is added to the returned set. ///
* /// <p>If {@code context} is {@code null}, it is treated as
* <p>If {@code context} is {@code null}, it is treated as /// {@link org.antlr.v4.runtime.ParserRuleContext#EMPTY}.</p>
* {@link org.antlr.v4.runtime.ParserRuleContext#EMPTY}.</p> ///
* /// - parameter stateNumber: the ATN state number
* @param stateNumber the ATN state number /// - parameter context: the full parse context
* @param context the full parse context /// - returns: The set of potentially valid input symbols which could follow the
* @return The set of potentially valid input symbols which could follow the /// specified state in the specified context.
* specified state in the specified context. /// - IllegalArgumentException if the ATN does not contain a state with
* @throws IllegalArgumentException if the ATN does not contain a state with /// number {@code stateNumber}
* number {@code stateNumber}
*/
public func getExpectedTokens(_ stateNumber: Int, _ context: RuleContext) throws -> IntervalSet { public func getExpectedTokens(_ stateNumber: Int, _ context: RuleContext) throws -> IntervalSet {
if stateNumber < 0 || stateNumber >= states.count { if stateNumber < 0 || stateNumber >= states.count {
throw ANTLRError.illegalArgument(msg: "Invalid state number.") throw ANTLRError.illegalArgument(msg: "Invalid state number.")
/* throw IllegalArgumentException("Invalid state number."); */ /// throw IllegalArgumentException("Invalid state number.");
} }
var ctx: RuleContext? = context var ctx: RuleContext? = context

View File

@ -1,60 +1,53 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** A tuple: (ATN state, predicted alt, syntactic, semantic context). /// A tuple: (ATN state, predicted alt, syntactic, semantic context).
* The syntactic context is a graph-structured stack node whose /// The syntactic context is a graph-structured stack node whose
* path(s) to the root is the rule invocation(s) /// path(s) to the root is the rule invocation(s)
* chain used to arrive at the state. The semantic context is /// chain used to arrive at the state. The semantic context is
* the tree of semantic predicates encountered before reaching /// the tree of semantic predicates encountered before reaching
* an ATN state. /// an ATN state.
*/
public class ATNConfig: Hashable, CustomStringConvertible { public class ATNConfig: Hashable, CustomStringConvertible {
/** /// This field stores the bit mask for implementing the
* This field stores the bit mask for implementing the /// {@link #isPrecedenceFilterSuppressed} property as a bit within the
* {@link #isPrecedenceFilterSuppressed} property as a bit within the /// existing {@link #reachesIntoOuterContext} field.
* existing {@link #reachesIntoOuterContext} field.
*/
private final let SUPPRESS_PRECEDENCE_FILTER: Int = 0x40000000 private final let SUPPRESS_PRECEDENCE_FILTER: Int = 0x40000000
/** The ATN state associated with this configuration */ /// The ATN state associated with this configuration
public final let state: ATNState public final let state: ATNState
/** What alt (or lexer rule) is predicted by this configuration */ /// What alt (or lexer rule) is predicted by this configuration
public final let alt: Int public final let alt: Int
/** The stack of invoking states leading to the rule/states associated /// The stack of invoking states leading to the rule/states associated
* with this config. We track only those contexts pushed during /// with this config. We track only those contexts pushed during
* execution of the ATN simulator. /// execution of the ATN simulator.
*/
public final var context: PredictionContext? public final var context: PredictionContext?
/** /// We cannot execute predicates dependent upon local context unless
* We cannot execute predicates dependent upon local context unless /// we know for sure we are in the correct context. Because there is
* we know for sure we are in the correct context. Because there is /// no way to do this efficiently, we simply cannot evaluate
* no way to do this efficiently, we simply cannot evaluate /// dependent predicates unless we are in the rule that initially
* dependent predicates unless we are in the rule that initially /// invokes the ATN simulator.
* invokes the ATN simulator. ///
* /// <p>
* <p> /// closure() tracks the depth of how far we dip into the outer context:
* closure() tracks the depth of how far we dip into the outer context: /// depth &gt; 0. Note that it may not be totally accurate depth since I
* depth &gt; 0. Note that it may not be totally accurate depth since I /// don't ever decrement. TODO: make it a boolean then</p>
* don't ever decrement. TODO: make it a boolean then</p> ///
* /// <p>
* <p> /// For memory efficiency, the {@link #isPrecedenceFilterSuppressed} method
* For memory efficiency, the {@link #isPrecedenceFilterSuppressed} method /// is also backed by this field. Since the field is publicly accessible, the
* is also backed by this field. Since the field is publicly accessible, the /// highest bit which would not cause the value to become negative is used to
* highest bit which would not cause the value to become negative is used to /// store this field. This choice minimizes the risk that code which only
* store this field. This choice minimizes the risk that code which only /// compares this value to 0 would be affected by the new purpose of the
* compares this value to 0 would be affected by the new purpose of the /// flag. It also ensures the performance of the existing {@link org.antlr.v4.runtime.atn.ATNConfig}
* flag. It also ensures the performance of the existing {@link org.antlr.v4.runtime.atn.ATNConfig} /// constructors as well as certain operations like
* constructors as well as certain operations like /// {@link org.antlr.v4.runtime.atn.ATNConfigSet#add(org.antlr.v4.runtime.atn.ATNConfig, DoubleKeyMap)} method are
* {@link org.antlr.v4.runtime.atn.ATNConfigSet#add(org.antlr.v4.runtime.atn.ATNConfig, DoubleKeyMap)} method are /// <em>completely</em> unaffected by the change.</p>
* <em>completely</em> unaffected by the change.</p>
*/
public final var reachesIntoOuterContext: Int = 0 public final var reachesIntoOuterContext: Int = 0
//=0 intital by janyou //=0 intital by janyou
@ -115,11 +108,9 @@ public class ATNConfig: Hashable, CustomStringConvertible {
self.reachesIntoOuterContext = c.reachesIntoOuterContext self.reachesIntoOuterContext = c.reachesIntoOuterContext
} }
/** /// This method gets the value of the {@link #reachesIntoOuterContext} field
* This method gets the value of the {@link #reachesIntoOuterContext} field /// as it existed prior to the introduction of the
* as it existed prior to the introduction of the /// {@link #isPrecedenceFilterSuppressed} method.
* {@link #isPrecedenceFilterSuppressed} method.
*/
public final func getOuterContextDepth() -> Int { public final func getOuterContextDepth() -> Int {
return reachesIntoOuterContext & ~SUPPRESS_PRECEDENCE_FILTER return reachesIntoOuterContext & ~SUPPRESS_PRECEDENCE_FILTER
} }
@ -136,10 +127,9 @@ public class ATNConfig: Hashable, CustomStringConvertible {
} }
} }
/** An ATN configuration is equal to another if both have /// An ATN configuration is equal to another if both have
* the same state, they predict the same alternative, and /// the same state, they predict the same alternative, and
* syntactic/semantic contexts are the same. /// syntactic/semantic contexts are the same.
*/
public var hashValue: Int { public var hashValue: Int {
var hashCode: Int = MurmurHash.initialize(7) var hashCode: Int = MurmurHash.initialize(7)
@ -197,9 +187,9 @@ public func ==(lhs: ATNConfig, rhs: ATNConfig) -> Bool {
return true return true
} }
//TODO : rhs nil? //TODO : rhs nil?
/*else { if (other == nil) { /// else { if (other == nil) {
return false; /// return false;
} }*/ /// }
if (lhs is LexerATNConfig) && (rhs is LexerATNConfig) { if (lhs is LexerATNConfig) && (rhs is LexerATNConfig) {
return (lhs as! LexerATNConfig) == (rhs as! LexerATNConfig) return (lhs as! LexerATNConfig) == (rhs as! LexerATNConfig)

View File

@ -1,52 +1,43 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** /// Specialized {@link java.util.Set}{@code <}{@link org.antlr.v4.runtime.atn.ATNConfig}{@code >} that can track
* Specialized {@link java.util.Set}{@code <}{@link org.antlr.v4.runtime.atn.ATNConfig}{@code >} that can track /// info about the set, with support for combining similar configurations using a
* info about the set, with support for combining similar configurations using a /// graph-structured stack.
* graph-structured stack.
*/
//: Set<ATNConfig> //: Set<ATNConfig>
public class ATNConfigSet: Hashable, CustomStringConvertible { public class ATNConfigSet: Hashable, CustomStringConvertible {
/** /// The reason that we need this is because we don't want the hash map to use
* The reason that we need this is because we don't want the hash map to use /// the standard hash code and equals. We need all configurations with the same
* the standard hash code and equals. We need all configurations with the same /// {@code (s,i,_,semctx)} to be equal. Unfortunately, this key effectively doubles
* {@code (s,i,_,semctx)} to be equal. Unfortunately, this key effectively doubles /// the number of objects associated with ATNConfigs. The other solution is to
* the number of objects associated with ATNConfigs. The other solution is to /// use a hash table that lets us specify the equals/hashcode operation.
* use a hash table that lets us specify the equals/hashcode operation.
*/
/** Indicates that the set of configurations is read-only. Do not /// Indicates that the set of configurations is read-only. Do not
* allow any code to manipulate the set; DFA states will point at /// allow any code to manipulate the set; DFA states will point at
* the sets and they must not change. This does not protect the other /// the sets and they must not change. This does not protect the other
* fields; in particular, conflictingAlts is set after /// fields; in particular, conflictingAlts is set after
* we've made this readonly. /// we've made this readonly.
*/
internal final var readonly: Bool = false internal final var readonly: Bool = false
/** /// All configs but hashed by (s, i, _, pi) not including context. Wiped out
* All configs but hashed by (s, i, _, pi) not including context. Wiped out /// when we go readonly as this set becomes a DFA state.
* when we go readonly as this set becomes a DFA state.
*/
public final var configLookup: LookupDictionary public final var configLookup: LookupDictionary
/** Track the elements as they are added to the set; supports get(i) */ /// Track the elements as they are added to the set; supports get(i)
public final var configs: Array<ATNConfig> = Array<ATNConfig>() public final var configs: Array<ATNConfig> = Array<ATNConfig>()
// TODO: these fields make me pretty uncomfortable but nice to pack up info together, saves recomputation // TODO: these fields make me pretty uncomfortable but nice to pack up info together, saves recomputation
// TODO: can we track conflicts as they are added to save scanning configs later? // TODO: can we track conflicts as they are added to save scanning configs later?
public final var uniqueAlt: Int = 0 public final var uniqueAlt: Int = 0
//TODO no default //TODO no default
/** Currently this is only used when we detect SLL conflict; this does /// Currently this is only used when we detect SLL conflict; this does
* not necessarily represent the ambiguous alternatives. In fact, /// not necessarily represent the ambiguous alternatives. In fact,
* I should also point out that this seems to include predicated alternatives /// I should also point out that this seems to include predicated alternatives
* that have predicates that evaluate to false. Computed in computeTargetState(). /// that have predicates that evaluate to false. Computed in computeTargetState().
*/
internal final var conflictingAlts: BitSet? internal final var conflictingAlts: BitSet?
// Used in parser and lexer. In lexer, it indicates we hit a pred // Used in parser and lexer. In lexer, it indicates we hit a pred
@ -56,10 +47,9 @@ public class ATNConfigSet: Hashable, CustomStringConvertible {
public final var dipsIntoOuterContext: Bool = false public final var dipsIntoOuterContext: Bool = false
//TODO no default //TODO no default
/** Indicates that this configuration set is part of a full context /// Indicates that this configuration set is part of a full context
* LL prediction. It will be used to determine how to merge $. With SLL /// LL prediction. It will be used to determine how to merge $. With SLL
* it's a wildcard whereas it is not for LL context merge. /// it's a wildcard whereas it is not for LL context merge.
*/
public final var fullCtx: Bool public final var fullCtx: Bool
private var cachedHashCode: Int = -1 private var cachedHashCode: Int = -1
@ -88,16 +78,14 @@ public class ATNConfigSet: Hashable, CustomStringConvertible {
return try add(config, &mergeCache) return try add(config, &mergeCache)
} }
/** /// Adding a new config means merging contexts with existing configs for
* Adding a new config means merging contexts with existing configs for /// {@code (s, i, pi, _)}, where {@code s} is the
* {@code (s, i, pi, _)}, where {@code s} is the /// {@link org.antlr.v4.runtime.atn.ATNConfig#state}, {@code i} is the {@link org.antlr.v4.runtime.atn.ATNConfig#alt}, and
* {@link org.antlr.v4.runtime.atn.ATNConfig#state}, {@code i} is the {@link org.antlr.v4.runtime.atn.ATNConfig#alt}, and /// {@code pi} is the {@link org.antlr.v4.runtime.atn.ATNConfig#semanticContext}. We use
* {@code pi} is the {@link org.antlr.v4.runtime.atn.ATNConfig#semanticContext}. We use /// {@code (s,i,pi)} as key.
* {@code (s,i,pi)} as key. ///
* /// <p>This method updates {@link #dipsIntoOuterContext} and
* <p>This method updates {@link #dipsIntoOuterContext} and /// {@link #hasSemanticContext} when necessary.</p>
* {@link #hasSemanticContext} when necessary.</p>
*/
@discardableResult @discardableResult
public final func add( public final func add(
_ config: ATNConfig, _ config: ATNConfig,
@ -147,7 +135,7 @@ public class ATNConfigSet: Hashable, CustomStringConvertible {
} }
/** Return a List holding list of configs */ /// Return a List holding list of configs
public final func elements() -> Array<ATNConfig> { public final func elements() -> Array<ATNConfig> {
return configs return configs
} }
@ -162,14 +150,12 @@ public class ATNConfigSet: Hashable, CustomStringConvertible {
return states return states
} }
/** /// Gets the complete set of represented alternatives for the configuration
* Gets the complete set of represented alternatives for the configuration /// set.
* set. ///
* /// - returns: the set of represented alternatives in this configuration set
* @return the set of represented alternatives in this configuration set ///
* /// - 4.3
* @since 4.3
*/
public final func getAlts() throws -> BitSet { public final func getAlts() throws -> BitSet {
let alts: BitSet = BitSet() let alts: BitSet = BitSet()
@ -310,10 +296,9 @@ public class ATNConfigSet: Hashable, CustomStringConvertible {
// return Array( configLookup.map{$0.config}) ; // return Array( configLookup.map{$0.config}) ;
// } // }
/*override /// override
public <T> func toArray(a : [T]) -> [T] { /// public <T> func toArray(a : [T]) -> [T] {
return configLookup.toArray(a); /// return configLookup.toArray(a);
}*/
private final func configHash(_ stateNumber: Int,_ context: PredictionContext?) -> Int{ private final func configHash(_ stateNumber: Int,_ context: PredictionContext?) -> Int{
var hashCode: Int = MurmurHash.initialize(7) var hashCode: Int = MurmurHash.initialize(7)
@ -471,10 +456,9 @@ public class ATNConfigSet: Hashable, CustomStringConvertible {
} }
if !configs[i].isPrecedenceFilterSuppressed() { if !configs[i].isPrecedenceFilterSuppressed() {
/* In the future, this elimination step could be updated to also /// In the future, this elimination step could be updated to also
* filter the prediction context for alternatives predicting alt>1 /// filter the prediction context for alternatives predicting alt>1
* (basically a graph subtraction algorithm). /// (basically a graph subtraction algorithm).
*/
let context: PredictionContext? = statesFromAlt1[configs[i].state.stateNumber] let context: PredictionContext? = statesFromAlt1[configs[i].state.stateNumber]
if context != nil && context == configs[i].context { if context != nil && context == configs[i].context {
// eliminated // eliminated
@ -537,15 +521,14 @@ public class ATNConfigSet: Hashable, CustomStringConvertible {
return alts.getMinElement() return alts.getMinElement()
} }
/** Walk the list of configurations and split them according to /// Walk the list of configurations and split them according to
* those that have preds evaluating to true/false. If no pred, assume /// those that have preds evaluating to true/false. If no pred, assume
* true pred and include in succeeded set. Returns Pair of sets. /// true pred and include in succeeded set. Returns Pair of sets.
* ///
* Create a new set so as not to alter the incoming parameter. /// Create a new set so as not to alter the incoming parameter.
* ///
* Assumption: the input stream has been restored to the starting point /// Assumption: the input stream has been restored to the starting point
* prediction, which is where predicates need to evaluate. /// prediction, which is where predicates need to evaluate.
*/
public final func splitAccordingToSemanticValidity( public final func splitAccordingToSemanticValidity(
_ outerContext: ParserRuleContext, _ outerContext: ParserRuleContext,
_ evalSemanticContext:( SemanticContext,ParserRuleContext,Int,Bool) throws -> Bool) throws -> (ATNConfigSet, ATNConfigSet) { _ evalSemanticContext:( SemanticContext,ParserRuleContext,Int,Bool) throws -> Bool) throws -> (ATNConfigSet, ATNConfigSet) {

View File

@ -1,14 +1,11 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** ///
* /// - Sam Harwell
* @author Sam Harwell
*/
public class ATNDeserializationOptions { public class ATNDeserializationOptions {

View File

@ -1,14 +1,11 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** ///
* /// - Sam Harwell
* @author Sam Harwell
*/
import Foundation import Foundation
@ -19,26 +16,18 @@ public class ATNDeserializer {
}() }()
/** /// This is the earliest supported serialized UUID.
* This is the earliest supported serialized UUID.
*/
private static let BASE_SERIALIZED_UUID: UUID = UUID(uuidString: "33761B2D-78BB-4A43-8B0B-4F5BEE8AACF3")! private static let BASE_SERIALIZED_UUID: UUID = UUID(uuidString: "33761B2D-78BB-4A43-8B0B-4F5BEE8AACF3")!
/** /// This UUID indicates an extension of {@link BASE_SERIALIZED_UUID} for the
* This UUID indicates an extension of {@link BASE_SERIALIZED_UUID} for the /// addition of precedence predicates.
* addition of precedence predicates.
*/
private static let ADDED_PRECEDENCE_TRANSITIONS: UUID = UUID(uuidString: "1DA0C57D-6C06-438A-9B27-10BCB3CE0F61")! private static let ADDED_PRECEDENCE_TRANSITIONS: UUID = UUID(uuidString: "1DA0C57D-6C06-438A-9B27-10BCB3CE0F61")!
/** /// This UUID indicates an extension of {@link #ADDED_PRECEDENCE_TRANSITIONS}
* This UUID indicates an extension of {@link #ADDED_PRECEDENCE_TRANSITIONS} /// for the addition of lexer actions encoded as a sequence of
* for the addition of lexer actions encoded as a sequence of /// {@link org.antlr.v4.runtime.atn.LexerAction} instances.
* {@link org.antlr.v4.runtime.atn.LexerAction} instances.
*/
private static let ADDED_LEXER_ACTIONS: UUID = UUID(uuidString: "AADB8D7E-AEEF-4415-AD2B-8204D6CF042E")! private static let ADDED_LEXER_ACTIONS: UUID = UUID(uuidString: "AADB8D7E-AEEF-4415-AD2B-8204D6CF042E")!
/** /// This list contains all of the currently supported UUIDs, ordered by when
* This list contains all of the currently supported UUIDs, ordered by when /// the feature first appeared in this branch.
* the feature first appeared in this branch.
*/
private static let SUPPORTED_UUIDS: Array<UUID> = { private static let SUPPORTED_UUIDS: Array<UUID> = {
var suuid = Array<UUID>() var suuid = Array<UUID>()
suuid.append(ATNDeserializer.BASE_SERIALIZED_UUID) suuid.append(ATNDeserializer.BASE_SERIALIZED_UUID)
@ -48,9 +37,7 @@ public class ATNDeserializer {
}() }()
/** /// This is the current serialized UUID.
* This is the current serialized UUID.
*/
public static let SERIALIZED_UUID: UUID = { public static let SERIALIZED_UUID: UUID = {
// SERIALIZED_UUID = ADDED_LEXER_ACTIONS; // SERIALIZED_UUID = ADDED_LEXER_ACTIONS;
return UUID(uuidString: "AADB8D7E-AEEF-4415-AD2B-8204D6CF042E")! return UUID(uuidString: "AADB8D7E-AEEF-4415-AD2B-8204D6CF042E")!
@ -74,19 +61,17 @@ public class ATNDeserializer {
} }
/** /// Determines if a particular serialized representation of an ATN supports
* Determines if a particular serialized representation of an ATN supports /// a particular feature, identified by the {@link java.util.UUID} used for serializing
* a particular feature, identified by the {@link java.util.UUID} used for serializing /// the ATN at the time the feature was first introduced.
* the ATN at the time the feature was first introduced. ///
* /// - parameter feature: The {@link java.util.UUID} marking the first time the feature was
* @param feature The {@link java.util.UUID} marking the first time the feature was /// supported in the serialized ATN.
* supported in the serialized ATN. /// - parameter actualUuid: The {@link java.util.UUID} of the actual serialized ATN which is
* @param actualUuid The {@link java.util.UUID} of the actual serialized ATN which is /// currently being deserialized.
* currently being deserialized. /// - returns: {@code true} if the {@code actualUuid} value represents a
* @return {@code true} if the {@code actualUuid} value represents a /// serialized ATN at or after the feature identified by {@code feature} was
* serialized ATN at or after the feature identified by {@code feature} was /// introduced; otherwise, {@code false}.
* introduced; otherwise, {@code false}.
*/
internal func isFeatureSupported(_ feature: UUID, _ actualUuid: UUID) -> Bool { internal func isFeatureSupported(_ feature: UUID, _ actualUuid: UUID) -> Bool {
let featureIndex: Int = ATNDeserializer.SUPPORTED_UUIDS.index(of: feature)! let featureIndex: Int = ATNDeserializer.SUPPORTED_UUIDS.index(of: feature)!
if featureIndex < 0 { if featureIndex < 0 {
@ -976,21 +961,18 @@ public class ATNDeserializer {
} }
/** /// Analyze the {@link org.antlr.v4.runtime.atn.StarLoopEntryState} states in the specified ATN to set
* Analyze the {@link org.antlr.v4.runtime.atn.StarLoopEntryState} states in the specified ATN to set /// the {@link org.antlr.v4.runtime.atn.StarLoopEntryState#precedenceRuleDecision} field to the
* the {@link org.antlr.v4.runtime.atn.StarLoopEntryState#precedenceRuleDecision} field to the /// correct value.
* correct value. ///
* /// - parameter atn: The ATN.
* @param atn The ATN.
*/
internal func markPrecedenceDecisions(_ atn: ATN) { internal func markPrecedenceDecisions(_ atn: ATN) {
for state: ATNState? in atn.states { for state: ATNState? in atn.states {
if let state = state as? StarLoopEntryState { if let state = state as? StarLoopEntryState {
/* We analyze the ATN to determine if this ATN decision state is the /// We analyze the ATN to determine if this ATN decision state is the
* decision for the closure block that determines whether a /// decision for the closure block that determines whether a
* precedence rule should continue or complete. /// precedence rule should continue or complete.
*/
if let stateRuleIndex = state.ruleIndex { if let stateRuleIndex = state.ruleIndex {
if atn.ruleToStartState[stateRuleIndex].isPrecedenceRule { if atn.ruleToStartState[stateRuleIndex].isPrecedenceRule {
let maybeLoopEndState: ATNState = state.transition(state.getNumberOfTransitions() - 1).target let maybeLoopEndState: ATNState = state.transition(state.getNumberOfTransitions() - 1).target

View File

@ -1,30 +1,25 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
import Foundation import Foundation
open class ATNSimulator { open class ATNSimulator {
/** /// - Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#SERIALIZED_VERSION} instead.
* @deprecated Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#SERIALIZED_VERSION} instead.
*/
public static let SERIALIZED_VERSION: Int = { public static let SERIALIZED_VERSION: Int = {
return ATNDeserializer.SERIALIZED_VERSION return ATNDeserializer.SERIALIZED_VERSION
}() }()
/** /// This is the current serialized UUID.
* This is the current serialized UUID. /// - Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#checkCondition(boolean)} instead.
* @deprecated Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#checkCondition(boolean)} instead.
*/
public static let SERIALIZED_UUID: UUID = { public static let SERIALIZED_UUID: UUID = {
return (ATNDeserializer.SERIALIZED_UUID as UUID) return (ATNDeserializer.SERIALIZED_UUID as UUID)
}() }()
/** Must distinguish between missing edge and edge we know leads nowhere */ /// Must distinguish between missing edge and edge we know leads nowhere
public static let ERROR: DFAState = { public static let ERROR: DFAState = {
let error = DFAState(ATNConfigSet()) let error = DFAState(ATNConfigSet())
@ -34,26 +29,25 @@ open class ATNSimulator {
public var atn: ATN public var atn: ATN
/** The context cache maps all PredictionContext objects that are equals() /// The context cache maps all PredictionContext objects that are equals()
* to a single cached copy. This cache is shared across all contexts /// to a single cached copy. This cache is shared across all contexts
* in all ATNConfigs in all DFA states. We rebuild each ATNConfigSet /// in all ATNConfigs in all DFA states. We rebuild each ATNConfigSet
* to use only cached nodes/graphs in addDFAState(). We don't want to /// to use only cached nodes/graphs in addDFAState(). We don't want to
* fill this during closure() since there are lots of contexts that /// fill this during closure() since there are lots of contexts that
* pop up but are not used ever again. It also greatly slows down closure(). /// pop up but are not used ever again. It also greatly slows down closure().
* ///
* <p>This cache makes a huge difference in memory and a little bit in speed. /// <p>This cache makes a huge difference in memory and a little bit in speed.
* For the Java grammar on java.*, it dropped the memory requirements /// For the Java grammar on java.*, it dropped the memory requirements
* at the end from 25M to 16M. We don't store any of the full context /// at the end from 25M to 16M. We don't store any of the full context
* graphs in the DFA because they are limited to local context only, /// graphs in the DFA because they are limited to local context only,
* but apparently there's a lot of repetition there as well. We optimize /// but apparently there's a lot of repetition there as well. We optimize
* the config contexts before storing the config set in the DFA states /// the config contexts before storing the config set in the DFA states
* by literally rebuilding them with cached subgraphs only.</p> /// by literally rebuilding them with cached subgraphs only.</p>
* ///
* <p>I tried a cache for use during closure operations, that was /// <p>I tried a cache for use during closure operations, that was
* whacked after each adaptivePredict(). It cost a little bit /// whacked after each adaptivePredict(). It cost a little bit
* more time I think and doesn't save on the overall footprint /// more time I think and doesn't save on the overall footprint
* so it's not worth the complexity.</p> /// so it's not worth the complexity.</p>
*/
internal final var sharedContextCache: PredictionContextCache? internal final var sharedContextCache: PredictionContextCache?
//static; { //static; {
@ -72,17 +66,15 @@ open class ATNSimulator {
RuntimeException(" must overriden ") RuntimeException(" must overriden ")
} }
/** /// Clear the DFA cache used by the current instance. Since the DFA cache may
* Clear the DFA cache used by the current instance. Since the DFA cache may /// be shared by multiple ATN simulators, this method may affect the
* be shared by multiple ATN simulators, this method may affect the /// performance (but not accuracy) of other parsers which are being used
* performance (but not accuracy) of other parsers which are being used /// concurrently.
* concurrently. ///
* /// - UnsupportedOperationException if the current instance does not
* @throws UnsupportedOperationException if the current instance does not /// support clearing the DFA.
* support clearing the DFA. ///
* /// - 4.3
* @since 4.3
*/
open func clearDFA() throws { open func clearDFA() throws {
throw ANTLRError.unsupportedOperation(msg: "This ATN simulator does not support clearing the DFA. ") throw ANTLRError.unsupportedOperation(msg: "This ATN simulator does not support clearing the DFA. ")
} }
@ -107,65 +99,49 @@ open class ATNSimulator {
//} //}
} }
/** /// - Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#deserialize} instead.
* @deprecated Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#deserialize} instead.
*/
////@Deprecated ////@Deprecated
public static func deserialize(_ data: [Character]) throws -> ATN { public static func deserialize(_ data: [Character]) throws -> ATN {
return try ATNDeserializer().deserialize(data) return try ATNDeserializer().deserialize(data)
} }
/** /// - Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#checkCondition(boolean)} instead.
* @deprecated Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#checkCondition(boolean)} instead.
*/
////@Deprecated ////@Deprecated
public static func checkCondition(_ condition: Bool) throws { public static func checkCondition(_ condition: Bool) throws {
try ATNDeserializer().checkCondition(condition) try ATNDeserializer().checkCondition(condition)
} }
/** /// - Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#checkCondition(boolean, String)} instead.
* @deprecated Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#checkCondition(boolean, String)} instead.
*/
////@Deprecated ////@Deprecated
public static func checkCondition(_ condition: Bool, _ message: String) throws { public static func checkCondition(_ condition: Bool, _ message: String) throws {
try ATNDeserializer().checkCondition(condition, message) try ATNDeserializer().checkCondition(condition, message)
} }
/** /// - Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#toInt} instead.
* @deprecated Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#toInt} instead.
*/
////@Deprecated ////@Deprecated
public func toInt(_ c: Character) -> Int { public func toInt(_ c: Character) -> Int {
return toInt(c) return toInt(c)
} }
/** /// - Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#toInt32} instead.
* @deprecated Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#toInt32} instead.
*/
////@Deprecated ////@Deprecated
public func toInt32(_ data: [Character], _ offset: Int) -> Int { public func toInt32(_ data: [Character], _ offset: Int) -> Int {
return toInt32(data, offset) return toInt32(data, offset)
} }
/** /// - Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#toLong} instead.
* @deprecated Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#toLong} instead.
*/
////@Deprecated ////@Deprecated
public func toLong(_ data: [Character], _ offset: Int) -> Int64 { public func toLong(_ data: [Character], _ offset: Int) -> Int64 {
return toLong(data, offset) return toLong(data, offset)
} }
/** /// - Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#toUUID} instead.
* @deprecated Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#toUUID} instead.
*/
////@Deprecated ////@Deprecated
//public class func toUUID(data : [Character], _ offset : Int) -> NSUUID { //public class func toUUID(data : [Character], _ offset : Int) -> NSUUID {
//return ATNDeserializer.toUUID(data, offset); //return ATNDeserializer.toUUID(data, offset);
//} //}
/** /// - Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#edgeFactory} instead.
* @deprecated Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#edgeFactory} instead.
*/
////@Deprecated ////@Deprecated
public static func edgeFactory(_ atn: ATN, public static func edgeFactory(_ atn: ATN,
@ -175,9 +151,7 @@ open class ATNSimulator {
return try ATNDeserializer().edgeFactory(atn, type, src, trg, arg1, arg2, arg3, sets) return try ATNDeserializer().edgeFactory(atn, type, src, trg, arg1, arg2, arg3, sets)
} }
/** /// - Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#stateFactory} instead.
* @deprecated Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#stateFactory} instead.
*/
////@Deprecated ////@Deprecated
public static func stateFactory(_ type: Int, _ ruleIndex: Int) throws -> ATNState { public static func stateFactory(_ type: Int, _ ruleIndex: Int) throws -> ATNState {
return try ATNDeserializer().stateFactory(type, ruleIndex)! return try ATNDeserializer().stateFactory(type, ruleIndex)!

View File

@ -1,70 +1,67 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** /// The following images show the relation of states and
* The following images show the relation of states and /// {@link org.antlr.v4.runtime.atn.ATNState#transitions} for various grammar constructs.
* {@link org.antlr.v4.runtime.atn.ATNState#transitions} for various grammar constructs. ///
* /// <ul>
* <ul> ///
* /// <li>Solid edges marked with an &#0949; indicate a required
* <li>Solid edges marked with an &#0949; indicate a required /// {@link org.antlr.v4.runtime.atn.EpsilonTransition}.</li>
* {@link org.antlr.v4.runtime.atn.EpsilonTransition}.</li> ///
* /// <li>Dashed edges indicate locations where any transition derived from
* <li>Dashed edges indicate locations where any transition derived from /// {@link org.antlr.v4.runtime.atn.Transition} might appear.</li>
* {@link org.antlr.v4.runtime.atn.Transition} might appear.</li> ///
* /// <li>Dashed nodes are place holders for either a sequence of linked
* <li>Dashed nodes are place holders for either a sequence of linked /// {@link org.antlr.v4.runtime.atn.BasicState} states or the inclusion of a block representing a nested
* {@link org.antlr.v4.runtime.atn.BasicState} states or the inclusion of a block representing a nested /// construct in one of the forms below.</li>
* construct in one of the forms below.</li> ///
* /// <li>Nodes showing multiple outgoing alternatives with a {@code ...} support
* <li>Nodes showing multiple outgoing alternatives with a {@code ...} support /// any number of alternatives (one or more). Nodes without the {@code ...} only
* any number of alternatives (one or more). Nodes without the {@code ...} only /// support the exact number of alternatives shown in the diagram.</li>
* support the exact number of alternatives shown in the diagram.</li> ///
* /// </ul>
* </ul> ///
* /// <h2>Basic Blocks</h2>
* <h2>Basic Blocks</h2> ///
* /// <h3>Rule</h3>
* <h3>Rule</h3> ///
* /// <embed src="images/Rule.svg" type="image/svg+xml"/>
* <embed src="images/Rule.svg" type="image/svg+xml"/> ///
* /// <h3>Block of 1 or more alternatives</h3>
* <h3>Block of 1 or more alternatives</h3> ///
* /// <embed src="images/Block.svg" type="image/svg+xml"/>
* <embed src="images/Block.svg" type="image/svg+xml"/> ///
* /// <h2>Greedy Loops</h2>
* <h2>Greedy Loops</h2> ///
* /// <h3>Greedy Closure: {@code (...)*}</h3>
* <h3>Greedy Closure: {@code (...)*}</h3> ///
* /// <embed src="images/ClosureGreedy.svg" type="image/svg+xml"/>
* <embed src="images/ClosureGreedy.svg" type="image/svg+xml"/> ///
* /// <h3>Greedy Positive Closure: {@code (...)+}</h3>
* <h3>Greedy Positive Closure: {@code (...)+}</h3> ///
* /// <embed src="images/PositiveClosureGreedy.svg" type="image/svg+xml"/>
* <embed src="images/PositiveClosureGreedy.svg" type="image/svg+xml"/> ///
* /// <h3>Greedy Optional: {@code (...)?}</h3>
* <h3>Greedy Optional: {@code (...)?}</h3> ///
* /// <embed src="images/OptionalGreedy.svg" type="image/svg+xml"/>
* <embed src="images/OptionalGreedy.svg" type="image/svg+xml"/> ///
* /// <h2>Non-Greedy Loops</h2>
* <h2>Non-Greedy Loops</h2> ///
* /// <h3>Non-Greedy Closure: {@code (...)*?}</h3>
* <h3>Non-Greedy Closure: {@code (...)*?}</h3> ///
* /// <embed src="images/ClosureNonGreedy.svg" type="image/svg+xml"/>
* <embed src="images/ClosureNonGreedy.svg" type="image/svg+xml"/> ///
* /// <h3>Non-Greedy Positive Closure: {@code (...)+?}</h3>
* <h3>Non-Greedy Positive Closure: {@code (...)+?}</h3> ///
* /// <embed src="images/PositiveClosureNonGreedy.svg" type="image/svg+xml"/>
* <embed src="images/PositiveClosureNonGreedy.svg" type="image/svg+xml"/> ///
* /// <h3>Non-Greedy Optional: {@code (...)??}</h3>
* <h3>Non-Greedy Optional: {@code (...)??}</h3> ///
* /// <embed src="images/OptionalNonGreedy.svg" type="image/svg+xml"/>
* <embed src="images/OptionalNonGreedy.svg" type="image/svg+xml"/>
*/
public class ATNState: Hashable, CustomStringConvertible { public class ATNState: Hashable, CustomStringConvertible {
public static let INITIAL_NUM_TRANSITIONS: Int = 4 public static let INITIAL_NUM_TRANSITIONS: Int = 4
@ -103,7 +100,7 @@ public class ATNState: Hashable, CustomStringConvertible {
public static let INVALID_STATE_NUMBER: Int = -1 public static let INVALID_STATE_NUMBER: Int = -1
/** Which ATN are we in? */ /// Which ATN are we in?
public final var atn: ATN? = nil public final var atn: ATN? = nil
public final var stateNumber: Int = INVALID_STATE_NUMBER public final var stateNumber: Int = INVALID_STATE_NUMBER
@ -113,11 +110,11 @@ public class ATNState: Hashable, CustomStringConvertible {
public final var epsilonOnlyTransitions: Bool = false public final var epsilonOnlyTransitions: Bool = false
/** Track the transitions emanating from this ATN state. */ /// Track the transitions emanating from this ATN state.
internal final var transitions: Array<Transition> = Array<Transition>() internal final var transitions: Array<Transition> = Array<Transition>()
//Array<Transition>(INITIAL_NUM_TRANSITIONS); //Array<Transition>(INITIAL_NUM_TRANSITIONS);
/** Used to cache lookahead during parsing, not used during construction */ /// Used to cache lookahead during parsing, not used during construction
public final var nextTokenWithinRule: IntervalSet? public final var nextTokenWithinRule: IntervalSet?

View File

@ -1,15 +1,12 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** /// Represents the type of recognizer an ATN applies to.
* Represents the type of recognizer an ATN applies to. ///
* /// - Sam Harwell
* @author Sam Harwell
*/
public enum ATNType: Int { public enum ATNType: Int {

View File

@ -1,14 +1,11 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** ///
* /// - Sam Harwell
* @author Sam Harwell
*/
public class AbstractPredicateTransition: Transition { public class AbstractPredicateTransition: Transition {

View File

@ -1,7 +1,6 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
public final class ActionTransition: Transition, CustomStringConvertible { public final class ActionTransition: Transition, CustomStringConvertible {

View File

@ -1,60 +1,55 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** /// This class represents profiling event information for an ambiguity.
* This class represents profiling event information for an ambiguity. /// Ambiguities are decisions where a particular input resulted in an SLL
* Ambiguities are decisions where a particular input resulted in an SLL /// conflict, followed by LL prediction also reaching a conflict state
* conflict, followed by LL prediction also reaching a conflict state /// (indicating a true ambiguity in the grammar).
* (indicating a true ambiguity in the grammar). ///
* /// <p>
* <p> /// This event may be reported during SLL prediction in cases where the
* This event may be reported during SLL prediction in cases where the /// conflicting SLL configuration set provides sufficient information to
* conflicting SLL configuration set provides sufficient information to /// determine that the SLL conflict is truly an ambiguity. For example, if none
* determine that the SLL conflict is truly an ambiguity. For example, if none /// of the ATN configurations in the conflicting SLL configuration set have
* of the ATN configurations in the conflicting SLL configuration set have /// traversed a global follow transition (i.e.
* traversed a global follow transition (i.e. /// {@link org.antlr.v4.runtime.atn.ATNConfig#reachesIntoOuterContext} is 0 for all configurations), then
* {@link org.antlr.v4.runtime.atn.ATNConfig#reachesIntoOuterContext} is 0 for all configurations), then /// the result of SLL prediction for that input is known to be equivalent to the
* the result of SLL prediction for that input is known to be equivalent to the /// result of LL prediction for that input.</p>
* result of LL prediction for that input.</p> ///
* /// <p>
* <p> /// In some cases, the minimum represented alternative in the conflicting LL
* In some cases, the minimum represented alternative in the conflicting LL /// configuration set is not equal to the minimum represented alternative in the
* configuration set is not equal to the minimum represented alternative in the /// conflicting SLL configuration set. Grammars and inputs which result in this
* conflicting SLL configuration set. Grammars and inputs which result in this /// scenario are unable to use {@link org.antlr.v4.runtime.atn.PredictionMode#SLL}, which in turn means
* scenario are unable to use {@link org.antlr.v4.runtime.atn.PredictionMode#SLL}, which in turn means /// they cannot use the two-stage parsing strategy to improve parsing performance
* they cannot use the two-stage parsing strategy to improve parsing performance /// for that input.</p>
* for that input.</p> ///
* /// - seealso: org.antlr.v4.runtime.atn.ParserATNSimulator#reportAmbiguity
* @see org.antlr.v4.runtime.atn.ParserATNSimulator#reportAmbiguity /// - seealso: org.antlr.v4.runtime.ANTLRErrorListener#reportAmbiguity
* @see org.antlr.v4.runtime.ANTLRErrorListener#reportAmbiguity ///
* /// - 4.3
* @since 4.3
*/
public class AmbiguityInfo: DecisionEventInfo { public class AmbiguityInfo: DecisionEventInfo {
/** The set of alternative numbers for this decision event that lead to a valid parse. */ /// The set of alternative numbers for this decision event that lead to a valid parse.
public var ambigAlts: BitSet public var ambigAlts: BitSet
/** /// Constructs a new instance of the {@link org.antlr.v4.runtime.atn.AmbiguityInfo} class with the
* Constructs a new instance of the {@link org.antlr.v4.runtime.atn.AmbiguityInfo} class with the /// specified detailed ambiguity information.
* specified detailed ambiguity information. ///
* /// - parameter decision: The decision number
* @param decision The decision number /// - parameter configs: The final configuration set identifying the ambiguous
* @param configs The final configuration set identifying the ambiguous /// alternatives for the current input
* alternatives for the current input /// - parameter ambigAlts: The set of alternatives in the decision that lead to a valid parse.
* @param ambigAlts The set of alternatives in the decision that lead to a valid parse. /// - parameter input: The input token stream
* @param input The input token stream /// - parameter startIndex: The start index for the current prediction
* @param startIndex The start index for the current prediction /// - parameter stopIndex: The index at which the ambiguity was identified during
* @param stopIndex The index at which the ambiguity was identified during /// prediction
* prediction /// - parameter fullCtx: {@code true} if the ambiguity was identified during LL
* @param fullCtx {@code true} if the ambiguity was identified during LL /// prediction; otherwise, {@code false} if the ambiguity was identified
* prediction; otherwise, {@code false} if the ambiguity was identified /// during SLL prediction
* during SLL prediction
*/
public init(_ decision: Int, public init(_ decision: Int,
_ configs: ATNConfigSet, _ configs: ATNConfigSet,
_ ambigAlts: BitSet, _ ambigAlts: BitSet,

View File

@ -1,19 +1,16 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
public class ArrayPredictionContext: PredictionContext { public class ArrayPredictionContext: PredictionContext {
/** Parent can be null only if full ctx mode and we make an array /// Parent can be null only if full ctx mode and we make an array
* from {@link #EMPTY} and non-empty. We merge {@link #EMPTY} by using null parent and /// from {@link #EMPTY} and non-empty. We merge {@link #EMPTY} by using null parent and
* returnState == {@link #EMPTY_RETURN_STATE}. /// returnState == {@link #EMPTY_RETURN_STATE}.
*/
public final var parents: [PredictionContext?] public final var parents: [PredictionContext?]
/** Sorted for merge, no duplicates; if present, /// Sorted for merge, no duplicates; if present,
* {@link #EMPTY_RETURN_STATE} is always last. /// {@link #EMPTY_RETURN_STATE} is always last.
*/
public final let returnStates: [Int] public final let returnStates: [Int]
public convenience init(_ a: SingletonPredictionContext) { public convenience init(_ a: SingletonPredictionContext) {

View File

@ -1,13 +1,12 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** TODO: make all transitions sets? no, should remove set edges */ /// TODO: make all transitions sets? no, should remove set edges
public final class AtomTransition: Transition, CustomStringConvertible { public final class AtomTransition: Transition, CustomStringConvertible {
/** The token type or character value; or, signifies special label. */ /// The token type or character value; or, signifies special label.
public let label: Int public let label: Int
public init(_ target: ATNState, _ label: Int) { public init(_ target: ATNState, _ label: Int) {

View File

@ -1,14 +1,11 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** ///
* /// - Sam Harwell
* @author Sam Harwell
*/
public final class BasicBlockStartState: BlockStartState { public final class BasicBlockStartState: BlockStartState {
override override

View File

@ -1,14 +1,11 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** ///
* /// - Sam Harwell
* @author Sam Harwell
*/
public final class BasicState: ATNState { public final class BasicState: ATNState {

View File

@ -1,11 +1,10 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** Terminal node of a simple {@code (a|b|c)} block. */ /// Terminal node of a simple {@code (a|b|c)} block.
public final class BlockEndState: ATNState { public final class BlockEndState: ATNState {
public var startState: BlockStartState? public var startState: BlockStartState?

View File

@ -1,10 +1,9 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** The start of a regular {@code (...)} block. */ /// The start of a regular {@code (...)} block.
public class BlockStartState: DecisionState { public class BlockStartState: DecisionState {
public var endState: BlockEndState? public var endState: BlockEndState?

View File

@ -1,41 +1,36 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** /// This class represents profiling event information for a context sensitivity.
* This class represents profiling event information for a context sensitivity. /// Context sensitivities are decisions where a particular input resulted in an
* Context sensitivities are decisions where a particular input resulted in an /// SLL conflict, but LL prediction produced a single unique alternative.
* SLL conflict, but LL prediction produced a single unique alternative. ///
* /// <p>
* <p> /// In some cases, the unique alternative identified by LL prediction is not
* In some cases, the unique alternative identified by LL prediction is not /// equal to the minimum represented alternative in the conflicting SLL
* equal to the minimum represented alternative in the conflicting SLL /// configuration set. Grammars and inputs which result in this scenario are
* configuration set. Grammars and inputs which result in this scenario are /// unable to use {@link org.antlr.v4.runtime.atn.PredictionMode#SLL}, which in turn means they cannot use
* unable to use {@link org.antlr.v4.runtime.atn.PredictionMode#SLL}, which in turn means they cannot use /// the two-stage parsing strategy to improve parsing performance for that
* the two-stage parsing strategy to improve parsing performance for that /// input.</p>
* input.</p> ///
* /// - seealso: org.antlr.v4.runtime.atn.ParserATNSimulator#reportContextSensitivity
* @see org.antlr.v4.runtime.atn.ParserATNSimulator#reportContextSensitivity /// - seealso: org.antlr.v4.runtime.ANTLRErrorListener#reportContextSensitivity
* @see org.antlr.v4.runtime.ANTLRErrorListener#reportContextSensitivity ///
* /// - 4.3
* @since 4.3
*/
public class ContextSensitivityInfo: DecisionEventInfo { public class ContextSensitivityInfo: DecisionEventInfo {
/** /// Constructs a new instance of the {@link org.antlr.v4.runtime.atn.ContextSensitivityInfo} class
* Constructs a new instance of the {@link org.antlr.v4.runtime.atn.ContextSensitivityInfo} class /// with the specified detailed context sensitivity information.
* with the specified detailed context sensitivity information. ///
* /// - parameter decision: The decision number
* @param decision The decision number /// - parameter configs: The final configuration set containing the unique
* @param configs The final configuration set containing the unique /// alternative identified by full-context prediction
* alternative identified by full-context prediction /// - parameter input: The input token stream
* @param input The input token stream /// - parameter startIndex: The start index for the current prediction
* @param startIndex The start index for the current prediction /// - parameter stopIndex: The index at which the context sensitivity was
* @param stopIndex The index at which the context sensitivity was /// identified during full-context prediction
* identified during full-context prediction
*/
public init(_ decision: Int, public init(_ decision: Int,
_ configs: ATNConfigSet, _ configs: ATNConfigSet,
_ input: TokenStream, _ startIndex: Int, _ stopIndex: Int) { _ input: TokenStream, _ startIndex: Int, _ stopIndex: Int) {

View File

@ -1,61 +1,46 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** /// This is the base class for gathering detailed information about prediction
* This is the base class for gathering detailed information about prediction /// events which occur during parsing.
* events which occur during parsing. ///
* /// Note that we could record the parser call stack at the time this event
* Note that we could record the parser call stack at the time this event /// occurred but in the presence of left recursive rules, the stack is kind of
* occurred but in the presence of left recursive rules, the stack is kind of /// meaningless. It's better to look at the individual configurations for their
* meaningless. It's better to look at the individual configurations for their /// individual stacks. Of course that is a {@link org.antlr.v4.runtime.atn.PredictionContext} object
* individual stacks. Of course that is a {@link org.antlr.v4.runtime.atn.PredictionContext} object /// not a parse tree node and so it does not have information about the extent
* not a parse tree node and so it does not have information about the extent /// (start...stop) of the various subtrees. Examining the stack tops of all
* (start...stop) of the various subtrees. Examining the stack tops of all /// configurations provide the return states for the rule invocations.
* configurations provide the return states for the rule invocations. /// From there you can get the enclosing rule.
* From there you can get the enclosing rule. ///
* /// - 4.3
* @since 4.3
*/
public class DecisionEventInfo { public class DecisionEventInfo {
/** /// The invoked decision number which this event is related to.
* The invoked decision number which this event is related to. ///
* /// - seealso: org.antlr.v4.runtime.atn.ATN#decisionToState
* @see org.antlr.v4.runtime.atn.ATN#decisionToState
*/
public let decision: Int public let decision: Int
/** /// The configuration set containing additional information relevant to the
* The configuration set containing additional information relevant to the /// prediction state when the current event occurred, or {@code null} if no
* prediction state when the current event occurred, or {@code null} if no /// additional information is relevant or available.
* additional information is relevant or available.
*/
public let configs: ATNConfigSet? public let configs: ATNConfigSet?
/** /// The input token stream which is being parsed.
* The input token stream which is being parsed.
*/
public let input: TokenStream public let input: TokenStream
/** /// The token index in the input stream at which the current prediction was
* The token index in the input stream at which the current prediction was /// originally invoked.
* originally invoked.
*/
public let startIndex: Int public let startIndex: Int
/** /// The token index in the input stream at which the current event occurred.
* The token index in the input stream at which the current event occurred.
*/
public let stopIndex: Int public let stopIndex: Int
/** /// {@code true} if the current event occurred during LL prediction;
* {@code true} if the current event occurred during LL prediction; /// otherwise, {@code false} if the input occurred during SLL prediction.
* otherwise, {@code false} if the input occurred during SLL prediction.
*/
public let fullCtx: Bool public let fullCtx: Bool
public init(_ decision: Int, public init(_ decision: Int,

View File

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

View File

@ -1,7 +1,6 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
public class DecisionState: ATNState { public class DecisionState: ATNState {

View File

@ -1,7 +1,6 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
// //
// DefaultATNConfig.swift // DefaultATNConfig.swift

View File

@ -1,7 +1,6 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
public class EmptyPredictionContext: SingletonPredictionContext { public class EmptyPredictionContext: SingletonPredictionContext {

View File

@ -1,7 +1,6 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
public final class EpsilonTransition: Transition, CustomStringConvertible { public final class EpsilonTransition: Transition, CustomStringConvertible {
@ -18,14 +17,12 @@ public final class EpsilonTransition: Transition, CustomStringConvertible {
super.init(target) super.init(target)
} }
/** /// - returns: the rule index of a precedence rule for which this transition is
* @return the rule index of a precedence rule for which this transition is /// returning from, where the precedence value is 0; otherwise, -1.
* returning from, where the precedence value is 0; otherwise, -1. ///
* /// - seealso: org.antlr.v4.runtime.atn.ATNConfig#isPrecedenceFilterSuppressed()
* @see org.antlr.v4.runtime.atn.ATNConfig#isPrecedenceFilterSuppressed() /// - seealso: org.antlr.v4.runtime.atn.ParserATNSimulator#applyPrecedenceFilter(org.antlr.v4.runtime.atn.ATNConfigSet)
* @see org.antlr.v4.runtime.atn.ParserATNSimulator#applyPrecedenceFilter(org.antlr.v4.runtime.atn.ATNConfigSet) /// - 4.4.1
* @since 4.4.1
*/
public func outermostPrecedenceReturn() -> Int { public func outermostPrecedenceReturn() -> Int {
return outermostPrecedenceReturnInside return outermostPrecedenceReturnInside
} }

View File

@ -1,37 +1,32 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** /// This class represents profiling event information for a syntax error
* This class represents profiling event information for a syntax error /// identified during prediction. Syntax errors occur when the prediction
* identified during prediction. Syntax errors occur when the prediction /// algorithm is unable to identify an alternative which would lead to a
* algorithm is unable to identify an alternative which would lead to a /// successful parse.
* successful parse. ///
* /// - seealso: org.antlr.v4.runtime.Parser#notifyErrorListeners(org.antlr.v4.runtime.Token, String, org.antlr.v4.runtime.RecognitionException)
* @see org.antlr.v4.runtime.Parser#notifyErrorListeners(org.antlr.v4.runtime.Token, String, org.antlr.v4.runtime.RecognitionException) /// - seealso: org.antlr.v4.runtime.ANTLRErrorListener#syntaxError
* @see org.antlr.v4.runtime.ANTLRErrorListener#syntaxError ///
* /// - 4.3
* @since 4.3
*/
public class ErrorInfo: DecisionEventInfo { public class ErrorInfo: DecisionEventInfo {
/** /// Constructs a new instance of the {@link org.antlr.v4.runtime.atn.ErrorInfo} class with the
* Constructs a new instance of the {@link org.antlr.v4.runtime.atn.ErrorInfo} class with the /// specified detailed syntax error information.
* specified detailed syntax error information. ///
* /// - parameter decision: The decision number
* @param decision The decision number /// - parameter configs: The final configuration set reached during prediction
* @param configs The final configuration set reached during prediction /// prior to reaching the {@link org.antlr.v4.runtime.atn.ATNSimulator#ERROR} state
* prior to reaching the {@link org.antlr.v4.runtime.atn.ATNSimulator#ERROR} state /// - parameter input: The input token stream
* @param input The input token stream /// - parameter startIndex: The start index for the current prediction
* @param startIndex The start index for the current prediction /// - parameter stopIndex: The index at which the syntax error was identified
* @param stopIndex The index at which the syntax error was identified /// - parameter fullCtx: {@code true} if the syntax error was identified during LL
* @param fullCtx {@code true} if the syntax error was identified during LL /// prediction; otherwise, {@code false} if the syntax error was identified
* prediction; otherwise, {@code false} if the syntax error was identified /// during SLL prediction
* during SLL prediction
*/
public init(_ decision: Int, public init(_ decision: Int,
_ configs: ATNConfigSet, _ configs: ATNConfigSet,
_ input: TokenStream, _ startIndex: Int, _ stopIndex: Int, _ input: TokenStream, _ startIndex: Int, _ stopIndex: Int,

View File

@ -1,13 +1,11 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
public class LL1Analyzer { public class LL1Analyzer {
/** Special value added to the lookahead sets to indicate that we hit /// Special value added to the lookahead sets to indicate that we hit
* a predicate during analysis if {@code seeThruPreds==false}. /// a predicate during analysis if {@code seeThruPreds==false}.
*/
public let HIT_PRED: Int = CommonToken.INVALID_TYPE public let HIT_PRED: Int = CommonToken.INVALID_TYPE
public let atn: ATN public let atn: ATN
@ -16,16 +14,14 @@ public class LL1Analyzer {
self.atn = atn self.atn = atn
} }
/** /// Calculates the SLL(1) expected lookahead set for each outgoing transition
* Calculates the SLL(1) expected lookahead set for each outgoing transition /// of an {@link org.antlr.v4.runtime.atn.ATNState}. The returned array has one element for each
* of an {@link org.antlr.v4.runtime.atn.ATNState}. The returned array has one element for each /// outgoing transition in {@code s}. If the closure from transition
* outgoing transition in {@code s}. If the closure from transition /// <em>i</em> leads to a semantic predicate before matching a symbol, the
* <em>i</em> leads to a semantic predicate before matching a symbol, the /// element at index <em>i</em> of the result will be {@code null}.
* element at index <em>i</em> of the result will be {@code null}. ///
* /// - parameter s: the ATN state
* @param s the ATN state /// - returns: the expected symbols for each outgoing transition of {@code s}.
* @return the expected symbols for each outgoing transition of {@code s}.
*/
public func getDecisionLookahead(_ s: ATNState?) throws -> [IntervalSet?]? { public func getDecisionLookahead(_ s: ATNState?) throws -> [IntervalSet?]? {
// print("LOOK("+s.stateNumber+")"); // print("LOOK("+s.stateNumber+")");
@ -50,44 +46,40 @@ public class LL1Analyzer {
return look return look
} }
/** /// Compute set of tokens that can follow {@code s} in the ATN in the
* Compute set of tokens that can follow {@code s} in the ATN in the /// specified {@code ctx}.
* specified {@code ctx}. ///
* /// <p>If {@code ctx} is {@code null} and the end of the rule containing
* <p>If {@code ctx} is {@code null} and the end of the rule containing /// {@code s} is reached, {@link org.antlr.v4.runtime.Token#EPSILON} is added to the result set.
* {@code s} is reached, {@link org.antlr.v4.runtime.Token#EPSILON} is added to the result set. /// If {@code ctx} is not {@code null} and the end of the outermost rule is
* If {@code ctx} is not {@code null} and the end of the outermost rule is /// reached, {@link org.antlr.v4.runtime.Token#EOF} is added to the result set.</p>
* reached, {@link org.antlr.v4.runtime.Token#EOF} is added to the result set.</p> ///
* /// - parameter s: the ATN state
* @param s the ATN state /// - parameter ctx: the complete parser context, or {@code null} if the context
* @param ctx the complete parser context, or {@code null} if the context /// should be ignored
* should be ignored ///
* /// - returns: The set of tokens that can follow {@code s} in the ATN in the
* @return The set of tokens that can follow {@code s} in the ATN in the /// specified {@code ctx}.
* specified {@code ctx}.
*/
public func LOOK(_ s: ATNState, _ ctx: RuleContext?) throws -> IntervalSet { public func LOOK(_ s: ATNState, _ ctx: RuleContext?) throws -> IntervalSet {
return try LOOK(s, nil, ctx) return try LOOK(s, nil, ctx)
} }
/** /// Compute set of tokens that can follow {@code s} in the ATN in the
* Compute set of tokens that can follow {@code s} in the ATN in the /// specified {@code ctx}.
* specified {@code ctx}. ///
* /// <p>If {@code ctx} is {@code null} and the end of the rule containing
* <p>If {@code ctx} is {@code null} and the end of the rule containing /// {@code s} is reached, {@link org.antlr.v4.runtime.Token#EPSILON} is added to the result set.
* {@code s} is reached, {@link org.antlr.v4.runtime.Token#EPSILON} is added to the result set. /// If {@code ctx} is not {@code null} and the end of the outermost rule is
* If {@code ctx} is not {@code null} and the end of the outermost rule is /// reached, {@link org.antlr.v4.runtime.Token#EOF} is added to the result set.</p>
* reached, {@link org.antlr.v4.runtime.Token#EOF} is added to the result set.</p> ///
* /// - parameter s: the ATN state
* @param s the ATN state /// - parameter stopState: the ATN state to stop at. This can be a
* @param stopState the ATN state to stop at. This can be a /// {@link org.antlr.v4.runtime.atn.BlockEndState} to detect epsilon paths through a closure.
* {@link org.antlr.v4.runtime.atn.BlockEndState} to detect epsilon paths through a closure. /// - parameter ctx: the complete parser context, or {@code null} if the context
* @param ctx the complete parser context, or {@code null} if the context /// should be ignored
* should be ignored ///
* /// - returns: The set of tokens that can follow {@code s} in the ATN in the
* @return The set of tokens that can follow {@code s} in the ATN in the /// specified {@code ctx}.
* specified {@code ctx}.
*/
public func LOOK(_ s: ATNState, _ stopState: ATNState?, _ ctx: RuleContext?) throws -> IntervalSet { public func LOOK(_ s: ATNState, _ stopState: ATNState?, _ ctx: RuleContext?) throws -> IntervalSet {
let r: IntervalSet = try IntervalSet() let r: IntervalSet = try IntervalSet()
@ -99,36 +91,34 @@ public class LL1Analyzer {
return r return r
} }
/** /// Compute set of tokens that can follow {@code s} in the ATN in the
* Compute set of tokens that can follow {@code s} in the ATN in the /// specified {@code ctx}.
* specified {@code ctx}. ///
* /// <p>If {@code ctx} is {@code null} and {@code stopState} or the end of the
* <p>If {@code ctx} is {@code null} and {@code stopState} or the end of the /// rule containing {@code s} is reached, {@link org.antlr.v4.runtime.Token#EPSILON} is added to
* rule containing {@code s} is reached, {@link org.antlr.v4.runtime.Token#EPSILON} is added to /// the result set. If {@code ctx} is not {@code null} and {@code addEOF} is
* the result set. If {@code ctx} is not {@code null} and {@code addEOF} is /// {@code true} and {@code stopState} or the end of the outermost rule is
* {@code true} and {@code stopState} or the end of the outermost rule is /// reached, {@link org.antlr.v4.runtime.Token#EOF} is added to the result set.</p>
* reached, {@link org.antlr.v4.runtime.Token#EOF} is added to the result set.</p> ///
* /// - parameter s: the ATN state.
* @param s the ATN state. /// - parameter stopState: the ATN state to stop at. This can be a
* @param stopState the ATN state to stop at. This can be a /// {@link org.antlr.v4.runtime.atn.BlockEndState} to detect epsilon paths through a closure.
* {@link org.antlr.v4.runtime.atn.BlockEndState} to detect epsilon paths through a closure. /// - parameter ctx: The outer context, or {@code null} if the outer context should
* @param ctx The outer context, or {@code null} if the outer context should /// not be used.
* not be used. /// - parameter look: The result lookahead set.
* @param look The result lookahead set. /// - parameter lookBusy: A set used for preventing epsilon closures in the ATN
* @param lookBusy A set used for preventing epsilon closures in the ATN /// from causing a stack overflow. Outside code should pass
* from causing a stack overflow. Outside code should pass /// {@code new HashSet<ATNConfig>} for this argument.
* {@code new HashSet<ATNConfig>} for this argument. /// - parameter calledRuleStack: A set used for preventing left recursion in the
* @param calledRuleStack A set used for preventing left recursion in the /// ATN from causing a stack overflow. Outside code should pass
* ATN from causing a stack overflow. Outside code should pass /// {@code new BitSet()} for this argument.
* {@code new BitSet()} for this argument. /// - parameter seeThruPreds: {@code true} to true semantic predicates as
* @param seeThruPreds {@code true} to true semantic predicates as /// implicitly {@code true} and "see through them", otherwise {@code false}
* implicitly {@code true} and "see through them", otherwise {@code false} /// to treat semantic predicates as opaque and add {@link #HIT_PRED} to the
* to treat semantic predicates as opaque and add {@link #HIT_PRED} to the /// result if one is encountered.
* result if one is encountered. /// - parameter addEOF: Add {@link org.antlr.v4.runtime.Token#EOF} to the result if the end of the
* @param addEOF Add {@link org.antlr.v4.runtime.Token#EOF} to the result if the end of the /// outermost context is reached. This parameter has no effect if {@code ctx}
* outermost context is reached. This parameter has no effect if {@code ctx} /// is {@code null}.
* is {@code null}.
*/
internal func _LOOK(_ s: ATNState, internal func _LOOK(_ s: ATNState,
_ stopState: ATNState?, _ stopState: ATNState?,
_ ctx: PredictionContext?, _ ctx: PredictionContext?,

View File

@ -1,13 +1,10 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
public class LexerATNConfig: ATNConfig { public class LexerATNConfig: ATNConfig {
/** /// This is the backing field for {@link #getLexerActionExecutor}.
* This is the backing field for {@link #getLexerActionExecutor}.
*/
private let lexerActionExecutor: LexerActionExecutor? private let lexerActionExecutor: LexerActionExecutor?
fileprivate let passedThroughNonGreedyDecision: Bool fileprivate let passedThroughNonGreedyDecision: Bool
@ -59,10 +56,8 @@ public class LexerATNConfig: ATNConfig {
return source.passedThroughNonGreedyDecision return source.passedThroughNonGreedyDecision
|| target is DecisionState && (target as! DecisionState).nonGreedy || target is DecisionState && (target as! DecisionState).nonGreedy
} }
/** /// Gets the {@link org.antlr.v4.runtime.atn.LexerActionExecutor} capable of executing the embedded
* Gets the {@link org.antlr.v4.runtime.atn.LexerActionExecutor} capable of executing the embedded /// action(s) for the current configuration.
* action(s) for the current configuration.
*/
public final func getLexerActionExecutor() -> LexerActionExecutor? { public final func getLexerActionExecutor() -> LexerActionExecutor? {
return lexerActionExecutor return lexerActionExecutor
} }

View File

@ -1,11 +1,10 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** "dup" of ParserInterpreter */ /// "dup" of ParserInterpreter
open class LexerATNSimulator: ATNSimulator { open class LexerATNSimulator: ATNSimulator {
public static let debug: Bool = false public static let debug: Bool = false
@ -15,21 +14,20 @@ open class LexerATNSimulator: ATNSimulator {
public static let MAX_DFA_EDGE: Int = 127 public static let MAX_DFA_EDGE: Int = 127
// forces unicode to stay in ATN // forces unicode to stay in ATN
/** When we hit an accept state in either the DFA or the ATN, we /// When we hit an accept state in either the DFA or the ATN, we
* have to notify the character stream to start buffering characters /// have to notify the character stream to start buffering characters
* via {@link org.antlr.v4.runtime.IntStream#mark} and record the current state. The current sim state /// via {@link org.antlr.v4.runtime.IntStream#mark} and record the current state. The current sim state
* includes the current index into the input, the current line, /// includes the current index into the input, the current line,
* and current character position in that line. Note that the Lexer is /// and current character position in that line. Note that the Lexer is
* tracking the starting line and characterization of the token. These /// tracking the starting line and characterization of the token. These
* variables track the "state" of the simulator when it hits an accept state. /// variables track the "state" of the simulator when it hits an accept state.
* ///
* <p>We track these variables separately for the DFA and ATN simulation /// <p>We track these variables separately for the DFA and ATN simulation
* because the DFA simulation often has to fail over to the ATN /// because the DFA simulation often has to fail over to the ATN
* simulation. If the ATN simulation fails, we need the DFA to fall /// simulation. If the ATN simulation fails, we need the DFA to fall
* back to its previously accepted state, if any. If the ATN succeeds, /// back to its previously accepted state, if any. If the ATN succeeds,
* then the ATN does the accept and the DFA simulator that invoked it /// then the ATN does the accept and the DFA simulator that invoked it
* can simply return the predicted token type.</p> /// can simply return the predicted token type.</p>
*/
internal class SimState { internal class SimState {
internal var index: Int = -1 internal var index: Int = -1
@ -48,23 +46,22 @@ open class LexerATNSimulator: ATNSimulator {
internal let recog: Lexer? internal let recog: Lexer?
/** The current token's starting index into the character stream. /// The current token's starting index into the character stream.
* Shared across DFA to ATN simulation in case the ATN fails and the /// Shared across DFA to ATN simulation in case the ATN fails and the
* DFA did not have a previous accept state. In this case, we use the /// DFA did not have a previous accept state. In this case, we use the
* ATN-generated exception object. /// ATN-generated exception object.
*/
internal var startIndex: Int = -1 internal var startIndex: Int = -1
/** line number 1..n within the input */ /// line number 1..n within the input
public var line: Int = 1 public var line: Int = 1
/** The index of the character relative to the beginning of the line 0..n-1 */ /// The index of the character relative to the beginning of the line 0..n-1
public var charPositionInLine: Int = 0 public var charPositionInLine: Int = 0
public final var decisionToDFA: [DFA] public final var decisionToDFA: [DFA]
internal var mode: Int = Lexer.DEFAULT_MODE internal var mode: Int = Lexer.DEFAULT_MODE
/** Used during DFA/ATN exec to record the most recent accept configuration info */ /// Used during DFA/ATN exec to record the most recent accept configuration info
internal final var prevAccept: SimState = SimState() internal final var prevAccept: SimState = SimState()
@ -229,17 +226,15 @@ open class LexerATNSimulator: ATNSimulator {
return try failOrAccept(prevAccept, input, s.configs, t) return try failOrAccept(prevAccept, input, s.configs, t)
} }
/** /// Get an existing target state for an edge in the DFA. If the target state
* Get an existing target state for an edge in the DFA. If the target state /// for the edge has not yet been computed or is otherwise not available,
* for the edge has not yet been computed or is otherwise not available, /// this method returns {@code null}.
* this method returns {@code null}. ///
* /// - parameter s: The current DFA state
* @param s The current DFA state /// - parameter t: The next input symbol
* @param t The next input symbol /// - returns: The existing target DFA state for the given input symbol
* @return The existing target DFA state for the given input symbol /// {@code t}, or {@code null} if the target state for this edge is not
* {@code t}, or {@code null} if the target state for this edge is not /// already cached
* already cached
*/
internal func getExistingTargetState(_ s: DFAState, _ t: Int) -> DFAState? { internal func getExistingTargetState(_ s: DFAState, _ t: Int) -> DFAState? {
if s.edges == nil || t < LexerATNSimulator.MIN_DFA_EDGE || t > LexerATNSimulator.MAX_DFA_EDGE { if s.edges == nil || t < LexerATNSimulator.MIN_DFA_EDGE || t > LexerATNSimulator.MAX_DFA_EDGE {
@ -254,18 +249,16 @@ open class LexerATNSimulator: ATNSimulator {
return target return target
} }
/** /// Compute a target state for an edge in the DFA, and attempt to add the
* Compute a target state for an edge in the DFA, and attempt to add the /// computed state and corresponding edge to the DFA.
* computed state and corresponding edge to the DFA. ///
* /// - parameter input: The input stream
* @param input The input stream /// - parameter s: The current DFA state
* @param s The current DFA state /// - parameter t: The next input symbol
* @param t The next input symbol ///
* /// - returns: The computed target DFA state for the given input symbol
* @return The computed target DFA state for the given input symbol /// {@code t}. If {@code t} does not lead to a valid DFA state, this method
* {@code t}. If {@code t} does not lead to a valid DFA state, this method /// returns {@link #ERROR}.
* returns {@link #ERROR}.
*/
internal func computeTargetState(_ input: CharStream, _ s: DFAState, _ t: Int) throws -> DFAState { internal func computeTargetState(_ input: CharStream, _ s: DFAState, _ t: Int) throws -> DFAState {
let reach: ATNConfigSet = OrderedATNConfigSet() let reach: ATNConfigSet = OrderedATNConfigSet()
@ -308,10 +301,9 @@ open class LexerATNSimulator: ATNSimulator {
} }
} }
/** Given a starting configuration set, figure out all ATN configurations /// Given a starting configuration set, figure out all ATN configurations
* we can reach upon input {@code t}. Parameter {@code reach} is a return /// we can reach upon input {@code t}. Parameter {@code reach} is a return
* parameter. /// parameter.
*/
internal func getReachableConfigSet(_ input: CharStream, _ closureConfig: ATNConfigSet, _ reach: ATNConfigSet, _ t: Int) throws { internal func getReachableConfigSet(_ input: CharStream, _ closureConfig: ATNConfigSet, _ reach: ATNConfigSet, _ t: Int) throws {
// this is used to skip processing for configs which have a lower priority // this is used to skip processing for configs which have a lower priority
// than a config that already reached an accept state for the same rule // than a config that already reached an accept state for the same rule
@ -397,16 +389,14 @@ open class LexerATNSimulator: ATNSimulator {
return configs return configs
} }
/** /// Since the alternatives within any lexer decision are ordered by
* Since the alternatives within any lexer decision are ordered by /// preference, this method stops pursuing the closure as soon as an accept
* preference, this method stops pursuing the closure as soon as an accept /// state is reached. After the first accept state is reached by depth-first
* state is reached. After the first accept state is reached by depth-first /// search from {@code config}, all other (potentially reachable) states for
* search from {@code config}, all other (potentially reachable) states for /// this rule would have a lower priority.
* this rule would have a lower priority. ///
* /// - returns: {@code true} if an accept state is reached, otherwise
* @return {@code true} if an accept state is reached, otherwise /// {@code false}.
* {@code false}.
*/
@discardableResult @discardableResult
final func closure(_ input: CharStream, _ config: LexerATNConfig, _ configs: ATNConfigSet, _ currentAltReachedAcceptState: Bool, _ speculative: Bool, _ treatEofAsEpsilon: Bool) throws -> Bool { final func closure(_ input: CharStream, _ config: LexerATNConfig, _ configs: ATNConfigSet, _ currentAltReachedAcceptState: Bool, _ speculative: Bool, _ treatEofAsEpsilon: Bool) throws -> Bool {
var currentAltReachedAcceptState = currentAltReachedAcceptState var currentAltReachedAcceptState = currentAltReachedAcceptState
@ -492,24 +482,23 @@ open class LexerATNSimulator: ATNSimulator {
case Transition.PREDICATE: case Transition.PREDICATE:
/* Track traversing semantic predicates. If we traverse, /// Track traversing semantic predicates. If we traverse,
we cannot add a DFA state for this "reach" computation /// we cannot add a DFA state for this "reach" computation
because the DFA would not test the predicate again in the /// because the DFA would not test the predicate again in the
future. Rather than creating collections of semantic predicates /// future. Rather than creating collections of semantic predicates
like v3 and testing them on prediction, v4 will test them on the /// like v3 and testing them on prediction, v4 will test them on the
fly all the time using the ATN not the DFA. This is slower but /// fly all the time using the ATN not the DFA. This is slower but
semantically it's not used that often. One of the key elements to /// semantically it's not used that often. One of the key elements to
this predicate mechanism is not adding DFA states that see /// this predicate mechanism is not adding DFA states that see
predicates immediately afterwards in the ATN. For example, /// predicates immediately afterwards in the ATN. For example,
///
a : ID {p1}? | ID {p2}? ; /// a : ID {p1}? | ID {p2}? ;
///
should create the start state for rule 'a' (to save start state /// should create the start state for rule 'a' (to save start state
competition), but should not create target of ID state. The /// competition), but should not create target of ID state. The
collection of ATN states the following ID references includes /// collection of ATN states the following ID references includes
states reached by traversing predicates. Since this is when we /// states reached by traversing predicates. Since this is when we
test them, we cannot cash the DFA state target of ID. /// test them, we cannot cash the DFA state target of ID.
*/
let pt: PredicateTransition = t as! PredicateTransition let pt: PredicateTransition = t as! PredicateTransition
if LexerATNSimulator.debug { if LexerATNSimulator.debug {
print("EVAL rule \(pt.ruleIndex):\(pt.predIndex)") print("EVAL rule \(pt.ruleIndex):\(pt.predIndex)")
@ -565,27 +554,25 @@ open class LexerATNSimulator: ATNSimulator {
return c return c
} }
/** /// Evaluate a predicate specified in the lexer.
* Evaluate a predicate specified in the lexer. ///
* /// <p>If {@code speculative} is {@code true}, this method was called before
* <p>If {@code speculative} is {@code true}, this method was called before /// {@link #consume} for the matched character. This method should call
* {@link #consume} for the matched character. This method should call /// {@link #consume} before evaluating the predicate to ensure position
* {@link #consume} before evaluating the predicate to ensure position /// sensitive values, including {@link org.antlr.v4.runtime.Lexer#getText}, {@link org.antlr.v4.runtime.Lexer#getLine},
* sensitive values, including {@link org.antlr.v4.runtime.Lexer#getText}, {@link org.antlr.v4.runtime.Lexer#getLine}, /// and {@link org.antlr.v4.runtime.Lexer#getCharPositionInLine}, properly reflect the current
* and {@link org.antlr.v4.runtime.Lexer#getCharPositionInLine}, properly reflect the current /// lexer state. This method should restore {@code input} and the simulator
* lexer state. This method should restore {@code input} and the simulator /// to the original state before returning (i.e. undo the actions made by the
* to the original state before returning (i.e. undo the actions made by the /// call to {@link #consume}.</p>
* call to {@link #consume}.</p> ///
* /// - parameter input: The input stream.
* @param input The input stream. /// - parameter ruleIndex: The rule containing the predicate.
* @param ruleIndex The rule containing the predicate. /// - parameter predIndex: The index of the predicate within the rule.
* @param predIndex The index of the predicate within the rule. /// - parameter speculative: {@code true} if the current index in {@code input} is
* @param speculative {@code true} if the current index in {@code input} is /// one character before the predicate's location.
* one character before the predicate's location. ///
* /// - returns: {@code true} if the specified predicate evaluates to
* @return {@code true} if the specified predicate evaluates to /// {@code true}.
* {@code true}.
*/
final func evaluatePredicate(_ input: CharStream, _ ruleIndex: Int, _ predIndex: Int, _ speculative: Bool) throws -> Bool { final func evaluatePredicate(_ input: CharStream, _ ruleIndex: Int, _ predIndex: Int, _ speculative: Bool) throws -> Bool {
// assume true if no recognizer was provided // assume true if no recognizer was provided
guard let recog = recog else { guard let recog = recog else {
@ -627,17 +614,16 @@ open class LexerATNSimulator: ATNSimulator {
final func addDFAEdge(_ from: DFAState, final func addDFAEdge(_ from: DFAState,
_ t: Int, _ t: Int,
_ q: ATNConfigSet) -> DFAState { _ q: ATNConfigSet) -> DFAState {
/* leading to this call, ATNConfigSet.hasSemanticContext is used as a /// leading to this call, ATNConfigSet.hasSemanticContext is used as a
* marker indicating dynamic predicate evaluation makes this edge /// marker indicating dynamic predicate evaluation makes this edge
* dependent on the specific input sequence, so the static edge in the /// dependent on the specific input sequence, so the static edge in the
* DFA should be omitted. The target DFAState is still created since /// DFA should be omitted. The target DFAState is still created since
* execATN has the ability to resynchronize with the DFA state cache /// execATN has the ability to resynchronize with the DFA state cache
* following the predicate evaluation step. /// following the predicate evaluation step.
* ///
* TJP notes: next time through the DFA, we see a pred again and eval. /// TJP notes: next time through the DFA, we see a pred again and eval.
* If that gets us to a previously created (but dangling) DFA /// If that gets us to a previously created (but dangling) DFA
* state, we can continue in pure DFA mode from there. /// state, we can continue in pure DFA mode from there.
*/
let suppressEdge: Bool = q.hasSemanticContext let suppressEdge: Bool = q.hasSemanticContext
q.hasSemanticContext = false q.hasSemanticContext = false
@ -672,16 +658,14 @@ open class LexerATNSimulator: ATNSimulator {
} }
} }
/** Add a new DFA state if there isn't one with this set of /// Add a new DFA state if there isn't one with this set of
configurations already. This method also detects the first /// configurations already. This method also detects the first
configuration containing an ATN rule stop state. Later, when /// configuration containing an ATN rule stop state. Later, when
traversing the DFA, we will know which rule to accept. /// traversing the DFA, we will know which rule to accept.
*/
final func addDFAState(_ configs: ATNConfigSet) -> DFAState { final func addDFAState(_ configs: ATNConfigSet) -> DFAState {
/* the lexer evaluates predicates on-the-fly; by this point configs /// the lexer evaluates predicates on-the-fly; by this point configs
* should not contain any configurations with unevaluated predicates. /// should not contain any configurations with unevaluated predicates.
*/
assert(!configs.hasSemanticContext, "Expected: !configs.hasSemanticContext") assert(!configs.hasSemanticContext, "Expected: !configs.hasSemanticContext")
let proposed: DFAState = DFAState(configs) let proposed: DFAState = DFAState(configs)
@ -715,8 +699,7 @@ open class LexerATNSimulator: ATNSimulator {
return decisionToDFA[mode] return decisionToDFA[mode]
} }
/** Get the text matched so far for the current token. /// Get the text matched so far for the current token.
*/
public func getText(_ input: CharStream) -> String { public func getText(_ input: CharStream) -> String {
// index is first lookahead char, don't include. // index is first lookahead char, don't include.

View File

@ -1,58 +1,49 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** /// Represents a single action which can be executed following the successful
* Represents a single action which can be executed following the successful /// match of a lexer rule. Lexer actions are used for both embedded action syntax
* match of a lexer rule. Lexer actions are used for both embedded action syntax /// and ANTLR 4's new lexer command syntax.
* and ANTLR 4's new lexer command syntax. ///
* /// - Sam Harwell
* @author Sam Harwell /// - 4.2
* @since 4.2
*/
public class LexerAction: Hashable { public class LexerAction: Hashable {
/** /// Gets the serialization type of the lexer action.
* Gets the serialization type of the lexer action. ///
* /// - returns: The serialization type of the lexer action.
* @return The serialization type of the lexer action.
*/
public func getActionType() -> LexerActionType { public func getActionType() -> LexerActionType {
RuntimeException(" must overriden ") RuntimeException(" must overriden ")
fatalError() fatalError()
} }
/** /// Gets whether the lexer action is position-dependent. Position-dependent
* Gets whether the lexer action is position-dependent. Position-dependent /// actions may have different semantics depending on the {@link org.antlr.v4.runtime.CharStream}
* actions may have different semantics depending on the {@link org.antlr.v4.runtime.CharStream} /// index at the time the action is executed.
* index at the time the action is executed. ///
* /// <p>Many lexer commands, including {@code type}, {@code skip}, and
* <p>Many lexer commands, including {@code type}, {@code skip}, and /// {@code more}, do not check the input index during their execution.
* {@code more}, do not check the input index during their execution. /// Actions like this are position-independent, and may be stored more
* Actions like this are position-independent, and may be stored more /// efficiently as part of the {@link org.antlr.v4.runtime.atn.LexerATNConfig#lexerActionExecutor}.</p>
* efficiently as part of the {@link org.antlr.v4.runtime.atn.LexerATNConfig#lexerActionExecutor}.</p> ///
* /// - returns: {@code true} if the lexer action semantics can be affected by the
* @return {@code true} if the lexer action semantics can be affected by the /// position of the input {@link org.antlr.v4.runtime.CharStream} at the time it is executed;
* position of the input {@link org.antlr.v4.runtime.CharStream} at the time it is executed; /// otherwise, {@code false}.
* otherwise, {@code false}.
*/
public func isPositionDependent() -> Bool { public func isPositionDependent() -> Bool {
RuntimeException(" must overriden ") RuntimeException(" must overriden ")
fatalError() fatalError()
} }
/** /// Execute the lexer action in the context of the specified {@link org.antlr.v4.runtime.Lexer}.
* Execute the lexer action in the context of the specified {@link org.antlr.v4.runtime.Lexer}. ///
* /// <p>For position-dependent actions, the input stream must already be
* <p>For position-dependent actions, the input stream must already be /// positioned correctly prior to calling this method.</p>
* positioned correctly prior to calling this method.</p> ///
* /// - parameter lexer: The lexer instance.
* @param lexer The lexer instance.
*/
public func execute(_ lexer: Lexer) throws { public func execute(_ lexer: Lexer) throws {
RuntimeException(" must overriden ") RuntimeException(" must overriden ")
} }

View File

@ -1,37 +1,30 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** /// Represents an executor for a sequence of lexer actions which traversed during
* Represents an executor for a sequence of lexer actions which traversed during /// the matching operation of a lexer rule (token).
* the matching operation of a lexer rule (token). ///
* /// <p>The executor tracks position information for position-dependent lexer actions
* <p>The executor tracks position information for position-dependent lexer actions /// efficiently, ensuring that actions appearing only at the end of the rule do
* efficiently, ensuring that actions appearing only at the end of the rule do /// not cause bloating of the {@link org.antlr.v4.runtime.dfa.DFA} created for the lexer.</p>
* not cause bloating of the {@link org.antlr.v4.runtime.dfa.DFA} created for the lexer.</p> ///
* /// - Sam Harwell
* @author Sam Harwell /// - 4.2
* @since 4.2
*/
public class LexerActionExecutor: Hashable { public class LexerActionExecutor: Hashable {
fileprivate final var lexerActions: [LexerAction] fileprivate final var lexerActions: [LexerAction]
/** /// Caches the result of {@link #hashCode} since the hash code is an element
* Caches the result of {@link #hashCode} since the hash code is an element /// of the performance-critical {@link org.antlr.v4.runtime.atn.LexerATNConfig#hashCode} operation.
* of the performance-critical {@link org.antlr.v4.runtime.atn.LexerATNConfig#hashCode} operation.
*/
fileprivate final var hashCode: Int fileprivate final var hashCode: Int
/** /// Constructs an executor for a sequence of {@link org.antlr.v4.runtime.atn.LexerAction} actions.
* Constructs an executor for a sequence of {@link org.antlr.v4.runtime.atn.LexerAction} actions. /// - parameter lexerActions: The lexer actions to execute.
* @param lexerActions The lexer actions to execute.
*/
public init(_ lexerActions: [LexerAction]) { public init(_ lexerActions: [LexerAction]) {
self.lexerActions = lexerActions self.lexerActions = lexerActions
@ -43,21 +36,19 @@ public class LexerActionExecutor: Hashable {
self.hashCode = MurmurHash.finish(hash, lexerActions.count) self.hashCode = MurmurHash.finish(hash, lexerActions.count)
} }
/** /// Creates a {@link org.antlr.v4.runtime.atn.LexerActionExecutor} which executes the actions for
* Creates a {@link org.antlr.v4.runtime.atn.LexerActionExecutor} which executes the actions for /// the input {@code lexerActionExecutor} followed by a specified
* the input {@code lexerActionExecutor} followed by a specified /// {@code lexerAction}.
* {@code lexerAction}. ///
* /// - parameter lexerActionExecutor: The executor for actions already traversed by
* @param lexerActionExecutor The executor for actions already traversed by /// the lexer while matching a token within a particular
* the lexer while matching a token within a particular /// {@link org.antlr.v4.runtime.atn.LexerATNConfig}. If this is {@code null}, the method behaves as
* {@link org.antlr.v4.runtime.atn.LexerATNConfig}. If this is {@code null}, the method behaves as /// though it were an empty executor.
* though it were an empty executor. /// - parameter lexerAction: The lexer action to execute after the actions
* @param lexerAction The lexer action to execute after the actions /// specified in {@code lexerActionExecutor}.
* specified in {@code lexerActionExecutor}. ///
* /// - returns: A {@link org.antlr.v4.runtime.atn.LexerActionExecutor} for executing the combine actions
* @return A {@link org.antlr.v4.runtime.atn.LexerActionExecutor} for executing the combine actions /// of {@code lexerActionExecutor} and {@code lexerAction}.
* of {@code lexerActionExecutor} and {@code lexerAction}.
*/
public static func append(_ lexerActionExecutor: LexerActionExecutor?, _ lexerAction: LexerAction) -> LexerActionExecutor { public static func append(_ lexerActionExecutor: LexerActionExecutor?, _ lexerAction: LexerAction) -> LexerActionExecutor {
if lexerActionExecutor == nil { if lexerActionExecutor == nil {
return LexerActionExecutor([lexerAction]) return LexerActionExecutor([lexerAction])
@ -70,35 +61,33 @@ public class LexerActionExecutor: Hashable {
return LexerActionExecutor(lexerActions) return LexerActionExecutor(lexerActions)
} }
/** /// Creates a {@link org.antlr.v4.runtime.atn.LexerActionExecutor} which encodes the current offset
* Creates a {@link org.antlr.v4.runtime.atn.LexerActionExecutor} which encodes the current offset /// for position-dependent lexer actions.
* for position-dependent lexer actions. ///
* /// <p>Normally, when the executor encounters lexer actions where
* <p>Normally, when the executor encounters lexer actions where /// {@link org.antlr.v4.runtime.atn.LexerAction#isPositionDependent} returns {@code true}, it calls
* {@link org.antlr.v4.runtime.atn.LexerAction#isPositionDependent} returns {@code true}, it calls /// {@link org.antlr.v4.runtime.IntStream#seek} on the input {@link org.antlr.v4.runtime.CharStream} to set the input
* {@link org.antlr.v4.runtime.IntStream#seek} on the input {@link org.antlr.v4.runtime.CharStream} to set the input /// position to the <em>end</em> of the current token. This behavior provides
* position to the <em>end</em> of the current token. This behavior provides /// for efficient DFA representation of lexer actions which appear at the end
* for efficient DFA representation of lexer actions which appear at the end /// of a lexer rule, even when the lexer rule matches a variable number of
* of a lexer rule, even when the lexer rule matches a variable number of /// characters.</p>
* characters.</p> ///
* /// <p>Prior to traversing a match transition in the ATN, the current offset
* <p>Prior to traversing a match transition in the ATN, the current offset /// from the token start index is assigned to all position-dependent lexer
* from the token start index is assigned to all position-dependent lexer /// actions which have not already been assigned a fixed offset. By storing
* actions which have not already been assigned a fixed offset. By storing /// the offsets relative to the token start index, the DFA representation of
* the offsets relative to the token start index, the DFA representation of /// lexer actions which appear in the middle of tokens remains efficient due
* lexer actions which appear in the middle of tokens remains efficient due /// to sharing among tokens of the same length, regardless of their absolute
* to sharing among tokens of the same length, regardless of their absolute /// position in the input stream.</p>
* position in the input stream.</p> ///
* /// <p>If the current executor already has offsets assigned to all
* <p>If the current executor already has offsets assigned to all /// position-dependent lexer actions, the method returns {@code this}.</p>
* position-dependent lexer actions, the method returns {@code this}.</p> ///
* /// - parameter offset: The current offset to assign to all position-dependent
* @param offset The current offset to assign to all position-dependent /// lexer actions which do not already have offsets assigned.
* lexer actions which do not already have offsets assigned. ///
* /// - returns: A {@link org.antlr.v4.runtime.atn.LexerActionExecutor} which stores input stream offsets
* @return A {@link org.antlr.v4.runtime.atn.LexerActionExecutor} which stores input stream offsets /// for all position-dependent lexer actions.
* for all position-dependent lexer actions.
*/
public func fixOffsetBeforeMatch(_ offset: Int) -> LexerActionExecutor { public func fixOffsetBeforeMatch(_ offset: Int) -> LexerActionExecutor {
var updatedLexerActions: [LexerAction]? = nil var updatedLexerActions: [LexerAction]? = nil
let length = lexerActions.count let length = lexerActions.count
@ -119,33 +108,29 @@ public class LexerActionExecutor: Hashable {
return LexerActionExecutor(updatedLexerActions!) return LexerActionExecutor(updatedLexerActions!)
} }
/** /// Gets the lexer actions to be executed by this executor.
* Gets the lexer actions to be executed by this executor. /// - returns: The lexer actions to be executed by this executor.
* @return The lexer actions to be executed by this executor.
*/
public func getLexerActions() -> [LexerAction] { public func getLexerActions() -> [LexerAction] {
return lexerActions return lexerActions
} }
/** /// Execute the actions encapsulated by this executor within the context of a
* Execute the actions encapsulated by this executor within the context of a /// particular {@link org.antlr.v4.runtime.Lexer}.
* particular {@link org.antlr.v4.runtime.Lexer}. ///
* /// <p>This method calls {@link org.antlr.v4.runtime.IntStream#seek} to set the position of the
* <p>This method calls {@link org.antlr.v4.runtime.IntStream#seek} to set the position of the /// {@code input} {@link org.antlr.v4.runtime.CharStream} prior to calling
* {@code input} {@link org.antlr.v4.runtime.CharStream} prior to calling /// {@link org.antlr.v4.runtime.atn.LexerAction#execute} on a position-dependent action. Before the
* {@link org.antlr.v4.runtime.atn.LexerAction#execute} on a position-dependent action. Before the /// method returns, the input position will be restored to the same position
* method returns, the input position will be restored to the same position /// it was in when the method was invoked.</p>
* it was in when the method was invoked.</p> ///
* /// - parameter lexer: The lexer instance.
* @param lexer The lexer instance. /// - parameter input: The input stream which is the source for the current token.
* @param input The input stream which is the source for the current token. /// When this method is called, the current {@link org.antlr.v4.runtime.IntStream#index} for
* When this method is called, the current {@link org.antlr.v4.runtime.IntStream#index} for /// {@code input} should be the start of the following token, i.e. 1
* {@code input} should be the start of the following token, i.e. 1 /// character past the end of the current token.
* character past the end of the current token. /// - parameter startIndex: The token start index. This value may be passed to
* @param startIndex The token start index. This value may be passed to /// {@link org.antlr.v4.runtime.IntStream#seek} to set the {@code input} position to the beginning
* {@link org.antlr.v4.runtime.IntStream#seek} to set the {@code input} position to the beginning /// of the token.
* of the token.
*/
public func execute(_ lexer: Lexer, _ input: CharStream, _ startIndex: Int) throws { public func execute(_ lexer: Lexer, _ input: CharStream, _ startIndex: Int) throws {
var requiresSeek: Bool = false var requiresSeek: Bool = false
var stopIndex: Int = input.index() var stopIndex: Int = input.index()

View File

@ -1,16 +1,13 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** /// Represents the serialization type of a {@link org.antlr.v4.runtime.atn.LexerAction}.
* Represents the serialization type of a {@link org.antlr.v4.runtime.atn.LexerAction}. ///
* /// - Sam Harwell
* @author Sam Harwell /// - 4.2
* @since 4.2
*/
public enum LexerActionType: Int { public enum LexerActionType: Int {
/** /**

View File

@ -1,61 +1,48 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** /// Implements the {@code channel} lexer action by calling
* Implements the {@code channel} lexer action by calling /// {@link org.antlr.v4.runtime.Lexer#setChannel} with the assigned channel.
* {@link org.antlr.v4.runtime.Lexer#setChannel} with the assigned channel. ///
* /// - Sam Harwell
* @author Sam Harwell /// - 4.2
* @since 4.2
*/
public final class LexerChannelAction: LexerAction, CustomStringConvertible { public final class LexerChannelAction: LexerAction, CustomStringConvertible {
fileprivate let channel: Int fileprivate let channel: Int
/** /// Constructs a new {@code channel} action with the specified channel value.
* Constructs a new {@code channel} action with the specified channel value. /// - parameter channel: The channel value to pass to {@link org.antlr.v4.runtime.Lexer#setChannel}.
* @param channel The channel value to pass to {@link org.antlr.v4.runtime.Lexer#setChannel}.
*/
public init(_ channel: Int) { public init(_ channel: Int) {
self.channel = channel self.channel = channel
} }
/** /// Gets the channel to use for the {@link org.antlr.v4.runtime.Token} created by the lexer.
* Gets the channel to use for the {@link org.antlr.v4.runtime.Token} created by the lexer. ///
* /// - returns: The channel to use for the {@link org.antlr.v4.runtime.Token} created by the lexer.
* @return The channel to use for the {@link org.antlr.v4.runtime.Token} created by the lexer.
*/
public func getChannel() -> Int { public func getChannel() -> Int {
return channel return channel
} }
/** /// {@inheritDoc}
* {@inheritDoc} /// - returns: This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#CHANNEL}.
* @return This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#CHANNEL}.
*/
public override func getActionType() -> LexerActionType { public override func getActionType() -> LexerActionType {
return LexerActionType.channel return LexerActionType.channel
} }
/** /// {@inheritDoc}
* {@inheritDoc} /// - returns: This method returns {@code false}.
* @return This method returns {@code false}.
*/
public override func isPositionDependent() -> Bool { public override func isPositionDependent() -> Bool {
return false return false
} }
/** /// {@inheritDoc}
* {@inheritDoc} ///
* /// <p>This action is implemented by calling {@link org.antlr.v4.runtime.Lexer#setChannel} with the
* <p>This action is implemented by calling {@link org.antlr.v4.runtime.Lexer#setChannel} with the /// value provided by {@link #getChannel}.</p>
* value provided by {@link #getChannel}.</p>
*/
public override func execute(_ lexer: Lexer) { public override func execute(_ lexer: Lexer) {
lexer.setChannel(channel) lexer.setChannel(channel)

View File

@ -1,91 +1,76 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** /// Executes a custom lexer action by calling {@link org.antlr.v4.runtime.Recognizer#action} with the
* Executes a custom lexer action by calling {@link org.antlr.v4.runtime.Recognizer#action} with the /// rule and action indexes assigned to the custom action. The implementation of
* rule and action indexes assigned to the custom action. The implementation of /// a custom action is added to the generated code for the lexer in an override
* a custom action is added to the generated code for the lexer in an override /// of {@link org.antlr.v4.runtime.Recognizer#action} when the grammar is compiled.
* of {@link org.antlr.v4.runtime.Recognizer#action} when the grammar is compiled. ///
* /// <p>This class may represent embedded actions created with the <code>{...}</code>
* <p>This class may represent embedded actions created with the <code>{...}</code> /// syntax in ANTLR 4, as well as actions created for lexer commands where the
* syntax in ANTLR 4, as well as actions created for lexer commands where the /// command argument could not be evaluated when the grammar was compiled.</p>
* command argument could not be evaluated when the grammar was compiled.</p> ///
* /// - Sam Harwell
* @author Sam Harwell /// - 4.2
* @since 4.2
*/
public final class LexerCustomAction: LexerAction { public final class LexerCustomAction: LexerAction {
fileprivate let ruleIndex: Int fileprivate let ruleIndex: Int
fileprivate let actionIndex: Int fileprivate let actionIndex: Int
/** /// Constructs a custom lexer action with the specified rule and action
* Constructs a custom lexer action with the specified rule and action /// indexes.
* indexes. ///
* /// - parameter ruleIndex: The rule index to use for calls to
* @param ruleIndex The rule index to use for calls to /// {@link org.antlr.v4.runtime.Recognizer#action}.
* {@link org.antlr.v4.runtime.Recognizer#action}. /// - parameter actionIndex: The action index to use for calls to
* @param actionIndex The action index to use for calls to /// {@link org.antlr.v4.runtime.Recognizer#action}.
* {@link org.antlr.v4.runtime.Recognizer#action}.
*/
public init(_ ruleIndex: Int, _ actionIndex: Int) { public init(_ ruleIndex: Int, _ actionIndex: Int) {
self.ruleIndex = ruleIndex self.ruleIndex = ruleIndex
self.actionIndex = actionIndex self.actionIndex = actionIndex
} }
/** /// Gets the rule index to use for calls to {@link org.antlr.v4.runtime.Recognizer#action}.
* Gets the rule index to use for calls to {@link org.antlr.v4.runtime.Recognizer#action}. ///
* /// - returns: The rule index for the custom action.
* @return The rule index for the custom action.
*/
public func getRuleIndex() -> Int { public func getRuleIndex() -> Int {
return ruleIndex return ruleIndex
} }
/** /// Gets the action index to use for calls to {@link org.antlr.v4.runtime.Recognizer#action}.
* Gets the action index to use for calls to {@link org.antlr.v4.runtime.Recognizer#action}. ///
* /// - returns: The action index for the custom action.
* @return The action index for the custom action.
*/
public func getActionIndex() -> Int { public func getActionIndex() -> Int {
return actionIndex return actionIndex
} }
/** /// {@inheritDoc}
* {@inheritDoc} ///
* /// - returns: This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#CUSTOM}.
* @return This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#CUSTOM}.
*/
public override func getActionType() -> LexerActionType { public override func getActionType() -> LexerActionType {
return LexerActionType.custom return LexerActionType.custom
} }
/** /// Gets whether the lexer action is position-dependent. Position-dependent
* Gets whether the lexer action is position-dependent. Position-dependent /// actions may have different semantics depending on the {@link org.antlr.v4.runtime.CharStream}
* actions may have different semantics depending on the {@link org.antlr.v4.runtime.CharStream} /// index at the time the action is executed.
* index at the time the action is executed. ///
* /// <p>Custom actions are position-dependent since they may represent a
* <p>Custom actions are position-dependent since they may represent a /// user-defined embedded action which makes calls to methods like
* user-defined embedded action which makes calls to methods like /// {@link org.antlr.v4.runtime.Lexer#getText}.</p>
* {@link org.antlr.v4.runtime.Lexer#getText}.</p> ///
* /// - returns: This method returns {@code true}.
* @return This method returns {@code true}.
*/
override override
public func isPositionDependent() -> Bool { public func isPositionDependent() -> Bool {
return true return true
} }
/** /// {@inheritDoc}
* {@inheritDoc} ///
* /// <p>Custom actions are implemented by calling {@link org.antlr.v4.runtime.Lexer#action} with the
* <p>Custom actions are implemented by calling {@link org.antlr.v4.runtime.Lexer#action} with the /// appropriate rule and action indexes.</p>
* appropriate rule and action indexes.</p>
*/
override override
public func execute(_ lexer: Lexer) throws { public func execute(_ lexer: Lexer) throws {
try lexer.action(nil, ruleIndex, actionIndex) try lexer.action(nil, ruleIndex, actionIndex)

View File

@ -1,93 +1,78 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** /// This implementation of {@link org.antlr.v4.runtime.atn.LexerAction} is used for tracking input offsets
* This implementation of {@link org.antlr.v4.runtime.atn.LexerAction} is used for tracking input offsets /// for position-dependent actions within a {@link org.antlr.v4.runtime.atn.LexerActionExecutor}.
* for position-dependent actions within a {@link org.antlr.v4.runtime.atn.LexerActionExecutor}. ///
* /// <p>This action is not serialized as part of the ATN, and is only required for
* <p>This action is not serialized as part of the ATN, and is only required for /// position-dependent lexer actions which appear at a location other than the
* position-dependent lexer actions which appear at a location other than the /// end of a rule. For more information about DFA optimizations employed for
* end of a rule. For more information about DFA optimizations employed for /// lexer actions, see {@link org.antlr.v4.runtime.atn.LexerActionExecutor#append} and
* lexer actions, see {@link org.antlr.v4.runtime.atn.LexerActionExecutor#append} and /// {@link org.antlr.v4.runtime.atn.LexerActionExecutor#fixOffsetBeforeMatch}.</p>
* {@link org.antlr.v4.runtime.atn.LexerActionExecutor#fixOffsetBeforeMatch}.</p> ///
* /// - Sam Harwell
* @author Sam Harwell /// - 4.2
* @since 4.2
*/
public final class LexerIndexedCustomAction: LexerAction { public final class LexerIndexedCustomAction: LexerAction {
fileprivate let offset: Int fileprivate let offset: Int
fileprivate let action: LexerAction fileprivate let action: LexerAction
/** /// Constructs a new indexed custom action by associating a character offset
* Constructs a new indexed custom action by associating a character offset /// with a {@link org.antlr.v4.runtime.atn.LexerAction}.
* with a {@link org.antlr.v4.runtime.atn.LexerAction}. ///
* /// <p>Note: This class is only required for lexer actions for which
* <p>Note: This class is only required for lexer actions for which /// {@link org.antlr.v4.runtime.atn.LexerAction#isPositionDependent} returns {@code true}.</p>
* {@link org.antlr.v4.runtime.atn.LexerAction#isPositionDependent} returns {@code true}.</p> ///
* /// - parameter offset: The offset into the input {@link org.antlr.v4.runtime.CharStream}, relative to
* @param offset The offset into the input {@link org.antlr.v4.runtime.CharStream}, relative to /// the token start index, at which the specified lexer action should be
* the token start index, at which the specified lexer action should be /// executed.
* executed. /// - parameter action: The lexer action to execute at a particular offset in the
* @param action The lexer action to execute at a particular offset in the /// input {@link org.antlr.v4.runtime.CharStream}.
* input {@link org.antlr.v4.runtime.CharStream}.
*/
public init(_ offset: Int, _ action: LexerAction) { public init(_ offset: Int, _ action: LexerAction) {
self.offset = offset self.offset = offset
self.action = action self.action = action
} }
/** /// Gets the location in the input {@link org.antlr.v4.runtime.CharStream} at which the lexer
* Gets the location in the input {@link org.antlr.v4.runtime.CharStream} at which the lexer /// action should be executed. The value is interpreted as an offset relative
* action should be executed. The value is interpreted as an offset relative /// to the token start index.
* to the token start index. ///
* /// - returns: The location in the input {@link org.antlr.v4.runtime.CharStream} at which the lexer
* @return The location in the input {@link org.antlr.v4.runtime.CharStream} at which the lexer /// action should be executed.
* action should be executed.
*/
public func getOffset() -> Int { public func getOffset() -> Int {
return offset return offset
} }
/** /// Gets the lexer action to execute.
* Gets the lexer action to execute. ///
* /// - returns: A {@link org.antlr.v4.runtime.atn.LexerAction} object which executes the lexer action.
* @return A {@link org.antlr.v4.runtime.atn.LexerAction} object which executes the lexer action.
*/
public func getAction() -> LexerAction { public func getAction() -> LexerAction {
return action return action
} }
/** /// {@inheritDoc}
* {@inheritDoc} ///
* /// - returns: This method returns the result of calling {@link #getActionType}
* @return This method returns the result of calling {@link #getActionType} /// on the {@link org.antlr.v4.runtime.atn.LexerAction} returned by {@link #getAction}.
* on the {@link org.antlr.v4.runtime.atn.LexerAction} returned by {@link #getAction}.
*/
public override func getActionType() -> LexerActionType { public override func getActionType() -> LexerActionType {
return action.getActionType() return action.getActionType()
} }
/** /// {@inheritDoc}
* {@inheritDoc} /// - returns: This method returns {@code true}.
* @return This method returns {@code true}.
*/
public override func isPositionDependent() -> Bool { public override func isPositionDependent() -> Bool {
return true return true
} }
/** /// {@inheritDoc}
* {@inheritDoc} ///
* /// <p>This method calls {@link #execute} on the result of {@link #getAction}
* <p>This method calls {@link #execute} on the result of {@link #getAction} /// using the provided {@code lexer}.</p>
* using the provided {@code lexer}.</p>
*/
public override func execute(_ lexer: Lexer) throws { public override func execute(_ lexer: Lexer) throws {
// assume the input stream position was properly set by the calling code // assume the input stream position was properly set by the calling code

View File

@ -1,62 +1,49 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** /// Implements the {@code mode} lexer action by calling {@link org.antlr.v4.runtime.Lexer#mode} with
* Implements the {@code mode} lexer action by calling {@link org.antlr.v4.runtime.Lexer#mode} with /// the assigned mode.
* the assigned mode. ///
* /// - Sam Harwell
* @author Sam Harwell /// - 4.2
* @since 4.2
*/
public final class LexerModeAction: LexerAction, CustomStringConvertible { public final class LexerModeAction: LexerAction, CustomStringConvertible {
fileprivate final var mode: Int fileprivate final var mode: Int
/** /// Constructs a new {@code mode} action with the specified mode value.
* Constructs a new {@code mode} action with the specified mode value. /// - parameter mode: The mode value to pass to {@link org.antlr.v4.runtime.Lexer#mode}.
* @param mode The mode value to pass to {@link org.antlr.v4.runtime.Lexer#mode}.
*/
public init(_ mode: Int) { public init(_ mode: Int) {
self.mode = mode self.mode = mode
} }
/** /// Get the lexer mode this action should transition the lexer to.
* Get the lexer mode this action should transition the lexer to. ///
* /// - returns: The lexer mode for this {@code mode} command.
* @return The lexer mode for this {@code mode} command.
*/
public func getMode() -> Int { public func getMode() -> Int {
return mode return mode
} }
/** /// {@inheritDoc}
* {@inheritDoc} /// - returns: This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#MODE}.
* @return This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#MODE}.
*/
public override func getActionType() -> LexerActionType { public override func getActionType() -> LexerActionType {
return LexerActionType.mode return LexerActionType.mode
} }
/** /// {@inheritDoc}
* {@inheritDoc} /// - returns: This method returns {@code false}.
* @return This method returns {@code false}.
*/
public override func isPositionDependent() -> Bool { public override func isPositionDependent() -> Bool {
return false return false
} }
/** /// {@inheritDoc}
* {@inheritDoc} ///
* /// <p>This action is implemented by calling {@link org.antlr.v4.runtime.Lexer#mode} with the
* <p>This action is implemented by calling {@link org.antlr.v4.runtime.Lexer#mode} with the /// value provided by {@link #getMode}.</p>
* value provided by {@link #getMode}.</p>
*/
override override
public func execute(_ lexer: Lexer) { public func execute(_ lexer: Lexer) {
lexer.mode(mode) lexer.mode(mode)

View File

@ -1,54 +1,41 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** /// Implements the {@code more} lexer action by calling {@link org.antlr.v4.runtime.Lexer#more}.
* Implements the {@code more} lexer action by calling {@link org.antlr.v4.runtime.Lexer#more}. ///
* /// <p>The {@code more} command does not have any parameters, so this action is
* <p>The {@code more} command does not have any parameters, so this action is /// implemented as a singleton instance exposed by {@link #INSTANCE}.</p>
* implemented as a singleton instance exposed by {@link #INSTANCE}.</p> ///
* /// - Sam Harwell
* @author Sam Harwell /// - 4.2
* @since 4.2
*/
public final class LexerMoreAction: LexerAction, CustomStringConvertible { public final class LexerMoreAction: LexerAction, CustomStringConvertible {
/** /// Provides a singleton instance of this parameterless lexer action.
* Provides a singleton instance of this parameterless lexer action.
*/
public static let INSTANCE: LexerMoreAction = LexerMoreAction() public static let INSTANCE: LexerMoreAction = LexerMoreAction()
/** /// Constructs the singleton instance of the lexer {@code more} command.
* Constructs the singleton instance of the lexer {@code more} command.
*/
private override init() { private override init() {
} }
/** /// {@inheritDoc}
* {@inheritDoc} /// - returns: This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#MORE}.
* @return This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#MORE}.
*/
override override
public func getActionType() -> LexerActionType { public func getActionType() -> LexerActionType {
return LexerActionType.more return LexerActionType.more
} }
/** /// {@inheritDoc}
* {@inheritDoc} /// - returns: This method returns {@code false}.
* @return This method returns {@code false}.
*/
override override
public func isPositionDependent() -> Bool { public func isPositionDependent() -> Bool {
return false return false
} }
/** /// {@inheritDoc}
* {@inheritDoc} ///
* /// <p>This action is implemented by calling {@link org.antlr.v4.runtime.Lexer#more}.</p>
* <p>This action is implemented by calling {@link org.antlr.v4.runtime.Lexer#more}.</p>
*/
override override
public func execute(_ lexer: Lexer) { public func execute(_ lexer: Lexer) {
lexer.more() lexer.more()

View File

@ -1,55 +1,42 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** /// Implements the {@code popMode} lexer action by calling {@link org.antlr.v4.runtime.Lexer#popMode}.
* Implements the {@code popMode} lexer action by calling {@link org.antlr.v4.runtime.Lexer#popMode}. ///
* /// <p>The {@code popMode} command does not have any parameters, so this action is
* <p>The {@code popMode} command does not have any parameters, so this action is /// implemented as a singleton instance exposed by {@link #INSTANCE}.</p>
* implemented as a singleton instance exposed by {@link #INSTANCE}.</p> ///
* /// - Sam Harwell
* @author Sam Harwell /// - 4.2
* @since 4.2
*/
public final class LexerPopModeAction: LexerAction, CustomStringConvertible { public final class LexerPopModeAction: LexerAction, CustomStringConvertible {
/** /// Provides a singleton instance of this parameterless lexer action.
* Provides a singleton instance of this parameterless lexer action.
*/
public static let INSTANCE: LexerPopModeAction = LexerPopModeAction() public static let INSTANCE: LexerPopModeAction = LexerPopModeAction()
/** /// Constructs the singleton instance of the lexer {@code popMode} command.
* Constructs the singleton instance of the lexer {@code popMode} command.
*/
private override init() { private override init() {
} }
/** /// {@inheritDoc}
* {@inheritDoc} /// - returns: This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#popMode}.
* @return This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#popMode}.
*/
override override
public func getActionType() -> LexerActionType { public func getActionType() -> LexerActionType {
return LexerActionType.popMode return LexerActionType.popMode
} }
/** /// {@inheritDoc}
* {@inheritDoc} /// - returns: This method returns {@code false}.
* @return This method returns {@code false}.
*/
public override func isPositionDependent() -> Bool { public override func isPositionDependent() -> Bool {
return false return false
} }
/** /// {@inheritDoc}
* {@inheritDoc} ///
* /// <p>This action is implemented by calling {@link org.antlr.v4.runtime.Lexer#popMode}.</p>
* <p>This action is implemented by calling {@link org.antlr.v4.runtime.Lexer#popMode}.</p>
*/
public override func execute(_ lexer: Lexer) throws { public override func execute(_ lexer: Lexer) throws {
try lexer.popMode() try lexer.popMode()

View File

@ -1,62 +1,49 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** /// Implements the {@code pushMode} lexer action by calling
* Implements the {@code pushMode} lexer action by calling /// {@link org.antlr.v4.runtime.Lexer#pushMode} with the assigned mode.
* {@link org.antlr.v4.runtime.Lexer#pushMode} with the assigned mode. ///
* /// - Sam Harwell
* @author Sam Harwell /// - 4.2
* @since 4.2
*/
public final class LexerPushModeAction: LexerAction, CustomStringConvertible { public final class LexerPushModeAction: LexerAction, CustomStringConvertible {
fileprivate final var mode: Int fileprivate final var mode: Int
/** /// Constructs a new {@code pushMode} action with the specified mode value.
* Constructs a new {@code pushMode} action with the specified mode value. /// - parameter mode: The mode value to pass to {@link org.antlr.v4.runtime.Lexer#pushMode}.
* @param mode The mode value to pass to {@link org.antlr.v4.runtime.Lexer#pushMode}.
*/
public init(_ mode: Int) { public init(_ mode: Int) {
self.mode = mode self.mode = mode
} }
/** /// Get the lexer mode this action should transition the lexer to.
* Get the lexer mode this action should transition the lexer to. ///
* /// - returns: The lexer mode for this {@code pushMode} command.
* @return The lexer mode for this {@code pushMode} command.
*/
public func getMode() -> Int { public func getMode() -> Int {
return mode return mode
} }
/** /// {@inheritDoc}
* {@inheritDoc} /// - returns: This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#pushMode}.
* @return This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#pushMode}.
*/
public override func getActionType() -> LexerActionType { public override func getActionType() -> LexerActionType {
return LexerActionType.pushMode return LexerActionType.pushMode
} }
/** /// {@inheritDoc}
* {@inheritDoc} /// - returns: This method returns {@code false}.
* @return This method returns {@code false}.
*/
public override func isPositionDependent() -> Bool { public override func isPositionDependent() -> Bool {
return false return false
} }
/** /// {@inheritDoc}
* {@inheritDoc} ///
* /// <p>This action is implemented by calling {@link org.antlr.v4.runtime.Lexer#pushMode} with the
* <p>This action is implemented by calling {@link org.antlr.v4.runtime.Lexer#pushMode} with the /// value provided by {@link #getMode}.</p>
* value provided by {@link #getMode}.</p>
*/
override override
public func execute(_ lexer: Lexer) { public func execute(_ lexer: Lexer) {
lexer.pushMode(mode) lexer.pushMode(mode)

View File

@ -1,54 +1,41 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** /// Implements the {@code skip} lexer action by calling {@link org.antlr.v4.runtime.Lexer#skip}.
* Implements the {@code skip} lexer action by calling {@link org.antlr.v4.runtime.Lexer#skip}. ///
* /// <p>The {@code skip} command does not have any parameters, so this action is
* <p>The {@code skip} command does not have any parameters, so this action is /// implemented as a singleton instance exposed by {@link #INSTANCE}.</p>
* implemented as a singleton instance exposed by {@link #INSTANCE}.</p> ///
* /// - Sam Harwell
* @author Sam Harwell /// - 4.2
* @since 4.2
*/
public final class LexerSkipAction: LexerAction, CustomStringConvertible { public final class LexerSkipAction: LexerAction, CustomStringConvertible {
/** /// Provides a singleton instance of this parameterless lexer action.
* Provides a singleton instance of this parameterless lexer action.
*/
public static let INSTANCE: LexerSkipAction = LexerSkipAction() public static let INSTANCE: LexerSkipAction = LexerSkipAction()
/** /// Constructs the singleton instance of the lexer {@code skip} command.
* Constructs the singleton instance of the lexer {@code skip} command.
*/
private override init() { private override init() {
} }
/** /// {@inheritDoc}
* {@inheritDoc} /// - returns: This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#SKIP}.
* @return This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#SKIP}.
*/
override override
public func getActionType() -> LexerActionType { public func getActionType() -> LexerActionType {
return LexerActionType.skip return LexerActionType.skip
} }
/** /// {@inheritDoc}
* {@inheritDoc} /// - returns: This method returns {@code false}.
* @return This method returns {@code false}.
*/
override override
public func isPositionDependent() -> Bool { public func isPositionDependent() -> Bool {
return false return false
} }
/** /// {@inheritDoc}
* {@inheritDoc} ///
* /// <p>This action is implemented by calling {@link org.antlr.v4.runtime.Lexer#skip}.</p>
* <p>This action is implemented by calling {@link org.antlr.v4.runtime.Lexer#skip}.</p>
*/
override override
public func execute(_ lexer: Lexer) { public func execute(_ lexer: Lexer) {
lexer.skip() lexer.skip()

View File

@ -1,60 +1,47 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** /// Implements the {@code type} lexer action by calling {@link org.antlr.v4.runtime.Lexer#setType}
* Implements the {@code type} lexer action by calling {@link org.antlr.v4.runtime.Lexer#setType} /// with the assigned type.
* with the assigned type. ///
* /// - Sam Harwell
* @author Sam Harwell /// - 4.2
* @since 4.2
*/
public class LexerTypeAction: LexerAction, CustomStringConvertible { public class LexerTypeAction: LexerAction, CustomStringConvertible {
fileprivate final var type: Int fileprivate final var type: Int
/** /// Constructs a new {@code type} action with the specified token type value.
* Constructs a new {@code type} action with the specified token type value. /// - parameter type: The type to assign to the token using {@link org.antlr.v4.runtime.Lexer#setType}.
* @param type The type to assign to the token using {@link org.antlr.v4.runtime.Lexer#setType}.
*/
public init(_ type: Int) { public init(_ type: Int) {
self.type = type self.type = type
} }
/** /// Gets the type to assign to a token created by the lexer.
* Gets the type to assign to a token created by the lexer. /// - returns: The type to assign to a token created by the lexer.
* @return The type to assign to a token created by the lexer.
*/
public func getType() -> Int { public func getType() -> Int {
return type return type
} }
/** /// {@inheritDoc}
* {@inheritDoc} /// - returns: This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#TYPE}.
* @return This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#TYPE}.
*/
public override func getActionType() -> LexerActionType { public override func getActionType() -> LexerActionType {
return LexerActionType.type return LexerActionType.type
} }
/** /// {@inheritDoc}
* {@inheritDoc} /// - returns: This method returns {@code false}.
* @return This method returns {@code false}.
*/
override override
public func isPositionDependent() -> Bool { public func isPositionDependent() -> Bool {
return false return false
} }
/** /// {@inheritDoc}
* {@inheritDoc} ///
* /// <p>This action is implemented by calling {@link org.antlr.v4.runtime.Lexer#setType} with the
* <p>This action is implemented by calling {@link org.antlr.v4.runtime.Lexer#setType} with the /// value provided by {@link #getType}.</p>
* value provided by {@link #getType}.</p>
*/
public override func execute(_ lexer: Lexer) { public override func execute(_ lexer: Lexer) {
lexer.setType(type) lexer.setType(type)

View File

@ -1,32 +1,27 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** /// This class represents profiling event information for tracking the lookahead
* This class represents profiling event information for tracking the lookahead /// depth required in order to make a prediction.
* depth required in order to make a prediction. ///
* /// - 4.3
* @since 4.3
*/
public class LookaheadEventInfo: DecisionEventInfo { public class LookaheadEventInfo: DecisionEventInfo {
/** /// Constructs a new instance of the {@link org.antlr.v4.runtime.atn.LookaheadEventInfo} class with
* Constructs a new instance of the {@link org.antlr.v4.runtime.atn.LookaheadEventInfo} class with /// the specified detailed lookahead information.
* the specified detailed lookahead information. ///
* /// - parameter decision: The decision number
* @param decision The decision number /// - parameter configs: The final configuration set containing the necessary
* @param configs The final configuration set containing the necessary /// information to determine the result of a prediction, or {@code null} if
* information to determine the result of a prediction, or {@code null} if /// the final configuration set is not available
* the final configuration set is not available /// - parameter input: The input token stream
* @param input The input token stream /// - parameter startIndex: The start index for the current prediction
* @param startIndex The start index for the current prediction /// - parameter stopIndex: The index at which the prediction was finally made
* @param stopIndex The index at which the prediction was finally made /// - parameter fullCtx: {@code true} if the current lookahead is part of an LL
* @param fullCtx {@code true} if the current lookahead is part of an LL /// prediction; otherwise, {@code false} if the current lookahead is part of
* prediction; otherwise, {@code false} if the current lookahead is part of /// an SLL prediction
* an SLL prediction
*/
public override init(_ decision: Int, public override init(_ decision: Int,
_ configs: ATNConfigSet?, _ configs: ATNConfigSet?,
_ input: TokenStream, _ startIndex: Int, _ stopIndex: Int, _ input: TokenStream, _ startIndex: Int, _ stopIndex: Int,

View File

@ -1,7 +1,6 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
// //
// LookupATNConfig.swift // LookupATNConfig.swift

View File

@ -1,7 +1,6 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
// //
// LookupDictionary.swift // LookupDictionary.swift

View File

@ -1,11 +1,10 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** Mark the end of a * or + loop. */ /// Mark the end of a * or + loop.
public final class LoopEndState: ATNState { public final class LoopEndState: ATNState {
public var loopBackState: ATNState? public var loopBackState: ATNState?

View File

@ -1,7 +1,6 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
public final class NotSetTransition: SetTransition { public final class NotSetTransition: SetTransition {

View File

@ -1,7 +1,6 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
// //
// OrderedATNConfig.swift // OrderedATNConfig.swift

View File

@ -1,13 +1,10 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** ///
* /// - Sam Harwell
* @author Sam Harwell
*/
public class OrderedATNConfigSet: ATNConfigSet { public class OrderedATNConfigSet: ATNConfigSet {

View File

@ -1,16 +1,13 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** /// This class provides access to specific and aggregate statistics gathered
* This class provides access to specific and aggregate statistics gathered /// during profiling of a parser.
* during profiling of a parser. ///
* /// - 4.3
* @since 4.3
*/
public class ParseInfo { public class ParseInfo {
internal let atnSimulator: ProfilingATNSimulator internal let atnSimulator: ProfilingATNSimulator
@ -19,25 +16,21 @@ public class ParseInfo {
self.atnSimulator = atnSimulator self.atnSimulator = atnSimulator
} }
/** /// Gets an array of {@link org.antlr.v4.runtime.atn.DecisionInfo} instances containing the profiling
* Gets an array of {@link org.antlr.v4.runtime.atn.DecisionInfo} instances containing the profiling /// information gathered for each decision in the ATN.
* information gathered for each decision in the ATN. ///
* /// - returns: An array of {@link org.antlr.v4.runtime.atn.DecisionInfo} instances, indexed by decision
* @return An array of {@link org.antlr.v4.runtime.atn.DecisionInfo} instances, indexed by decision /// number.
* number.
*/
public func getDecisionInfo() -> [DecisionInfo] { public func getDecisionInfo() -> [DecisionInfo] {
return atnSimulator.getDecisionInfo() return atnSimulator.getDecisionInfo()
} }
/** /// Gets the decision numbers for decisions that required one or more
* Gets the decision numbers for decisions that required one or more /// full-context predictions during parsing. These are decisions for which
* full-context predictions during parsing. These are decisions for which /// {@link org.antlr.v4.runtime.atn.DecisionInfo#LL_Fallback} is non-zero.
* {@link org.antlr.v4.runtime.atn.DecisionInfo#LL_Fallback} is non-zero. ///
* /// - returns: A list of decision numbers which required one or more
* @return A list of decision numbers which required one or more /// full-context predictions during parsing.
* full-context predictions during parsing.
*/
public func getLLDecisions() -> Array<Int> { public func getLLDecisions() -> Array<Int> {
var decisions: [DecisionInfo] = atnSimulator.getDecisionInfo() var decisions: [DecisionInfo] = atnSimulator.getDecisionInfo()
var LL: Array<Int> = Array<Int>() var LL: Array<Int> = Array<Int>()
@ -52,11 +45,9 @@ public class ParseInfo {
return LL return LL
} }
/** /// Gets the total time spent during prediction across all decisions made
* Gets the total time spent during prediction across all decisions made /// during parsing. This value is the sum of
* during parsing. This value is the sum of /// {@link org.antlr.v4.runtime.atn.DecisionInfo#timeInPrediction} for all decisions.
* {@link org.antlr.v4.runtime.atn.DecisionInfo#timeInPrediction} for all decisions.
*/
public func getTotalTimeInPrediction() -> Int64 { public func getTotalTimeInPrediction() -> Int64 {
var decisions: [DecisionInfo] = atnSimulator.getDecisionInfo() var decisions: [DecisionInfo] = atnSimulator.getDecisionInfo()
var t: Int64 = 0 var t: Int64 = 0
@ -67,11 +58,9 @@ public class ParseInfo {
return t return t
} }
/** /// Gets the total number of SLL lookahead operations across all decisions
* Gets the total number of SLL lookahead operations across all decisions /// made during parsing. This value is the sum of
* made during parsing. This value is the sum of /// {@link org.antlr.v4.runtime.atn.DecisionInfo#SLL_TotalLook} for all decisions.
* {@link org.antlr.v4.runtime.atn.DecisionInfo#SLL_TotalLook} for all decisions.
*/
public func getTotalSLLLookaheadOps() -> Int64 { public func getTotalSLLLookaheadOps() -> Int64 {
var decisions: [DecisionInfo] = atnSimulator.getDecisionInfo() var decisions: [DecisionInfo] = atnSimulator.getDecisionInfo()
var k: Int64 = 0 var k: Int64 = 0
@ -82,11 +71,9 @@ public class ParseInfo {
return k return k
} }
/** /// Gets the total number of LL lookahead operations across all decisions
* Gets the total number of LL lookahead operations across all decisions /// made during parsing. This value is the sum of
* made during parsing. This value is the sum of /// {@link org.antlr.v4.runtime.atn.DecisionInfo#LL_TotalLook} for all decisions.
* {@link org.antlr.v4.runtime.atn.DecisionInfo#LL_TotalLook} for all decisions.
*/
public func getTotalLLLookaheadOps() -> Int64 { public func getTotalLLLookaheadOps() -> Int64 {
var decisions: [DecisionInfo] = atnSimulator.getDecisionInfo() var decisions: [DecisionInfo] = atnSimulator.getDecisionInfo()
var k: Int64 = 0 var k: Int64 = 0
@ -97,10 +84,8 @@ public class ParseInfo {
return k return k
} }
/** /// Gets the total number of ATN lookahead operations for SLL prediction
* Gets the total number of ATN lookahead operations for SLL prediction /// across all decisions made during parsing.
* across all decisions made during parsing.
*/
public func getTotalSLLATNLookaheadOps() -> Int64 { public func getTotalSLLATNLookaheadOps() -> Int64 {
var decisions: [DecisionInfo] = atnSimulator.getDecisionInfo() var decisions: [DecisionInfo] = atnSimulator.getDecisionInfo()
var k: Int64 = 0 var k: Int64 = 0
@ -111,10 +96,8 @@ public class ParseInfo {
return k return k
} }
/** /// Gets the total number of ATN lookahead operations for LL prediction
* Gets the total number of ATN lookahead operations for LL prediction /// across all decisions made during parsing.
* across all decisions made during parsing.
*/
public func getTotalLLATNLookaheadOps() -> Int64 { public func getTotalLLATNLookaheadOps() -> Int64 {
var decisions: [DecisionInfo] = atnSimulator.getDecisionInfo() var decisions: [DecisionInfo] = atnSimulator.getDecisionInfo()
var k: Int64 = 0 var k: Int64 = 0
@ -125,14 +108,12 @@ public class ParseInfo {
return k return k
} }
/** /// Gets the total number of ATN lookahead operations for SLL and LL
* Gets the total number of ATN lookahead operations for SLL and LL /// prediction across all decisions made during parsing.
* prediction across all decisions made during parsing. ///
* /// <p>
* <p> /// This value is the sum of {@link #getTotalSLLATNLookaheadOps} and
* This value is the sum of {@link #getTotalSLLATNLookaheadOps} and /// {@link #getTotalLLATNLookaheadOps}.</p>
* {@link #getTotalLLATNLookaheadOps}.</p>
*/
public func getTotalATNLookaheadOps() -> Int64 { public func getTotalATNLookaheadOps() -> Int64 {
var decisions: [DecisionInfo] = atnSimulator.getDecisionInfo() var decisions: [DecisionInfo] = atnSimulator.getDecisionInfo()
var k: Int64 = 0 var k: Int64 = 0
@ -144,10 +125,8 @@ public class ParseInfo {
return k return k
} }
/** /// Gets the total number of DFA states stored in the DFA cache for all
* Gets the total number of DFA states stored in the DFA cache for all /// decisions in the ATN.
* decisions in the ATN.
*/
public func getDFASize() -> Int { public func getDFASize() -> Int {
var n: Int = 0 var n: Int = 0
let decisionToDFA: [DFA] = atnSimulator.decisionToDFA let decisionToDFA: [DFA] = atnSimulator.decisionToDFA
@ -158,10 +137,8 @@ public class ParseInfo {
return n return n
} }
/** /// Gets the total number of DFA states stored in the DFA cache for a
* Gets the total number of DFA states stored in the DFA cache for a /// particular decision.
* particular decision.
*/
public func getDFASize(_ decision: Int) -> Int { public func getDFASize(_ decision: Int) -> Int {
let decisionToDFA: DFA = atnSimulator.decisionToDFA[decision] let decisionToDFA: DFA = atnSimulator.decisionToDFA[decision]
return decisionToDFA.states.count return decisionToDFA.states.count

File diff suppressed because it is too large Load Diff

View File

@ -1,15 +1,13 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** Start of {@code (A|B|...)+} loop. Technically a decision state, but /// Start of {@code (A|B|...)+} loop. Technically a decision state, but
* we don't use for code generation; somebody might need it, so I'm defining /// we don't use for code generation; somebody might need it, so I'm defining
* it for completeness. In reality, the {@link org.antlr.v4.runtime.atn.PlusLoopbackState} node is the /// it for completeness. In reality, the {@link org.antlr.v4.runtime.atn.PlusLoopbackState} node is the
* real decision-making note for {@code A+}. /// real decision-making note for {@code A+}.
*/
public final class PlusBlockStartState: BlockStartState { public final class PlusBlockStartState: BlockStartState {
public var loopBackState: PlusLoopbackState? public var loopBackState: PlusLoopbackState?

View File

@ -1,13 +1,11 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** Decision state for {@code A+} and {@code (A|B)+}. It has two transitions: /// Decision state for {@code A+} and {@code (A|B)+}. It has two transitions:
* one to the loop back to start of the block and one to exit. /// one to the loop back to start of the block and one to exit.
*/
public final class PlusLoopbackState: DecisionState { public final class PlusLoopbackState: DecisionState {

View File

@ -1,14 +1,11 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** ///
* /// - Sam Harwell
* @author Sam Harwell
*/
public final class PrecedencePredicateTransition: AbstractPredicateTransition, CustomStringConvertible { public final class PrecedencePredicateTransition: AbstractPredicateTransition, CustomStringConvertible {
public final var precedence: Int public final var precedence: Int

View File

@ -1,58 +1,47 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** /// This class represents profiling event information for semantic predicate
* This class represents profiling event information for semantic predicate /// evaluations which occur during prediction.
* evaluations which occur during prediction. ///
* /// - seealso: org.antlr.v4.runtime.atn.ParserATNSimulator#evalSemanticContext
* @see org.antlr.v4.runtime.atn.ParserATNSimulator#evalSemanticContext ///
* /// - 4.3
* @since 4.3
*/
public class PredicateEvalInfo: DecisionEventInfo { public class PredicateEvalInfo: DecisionEventInfo {
/** /// The semantic context which was evaluated.
* The semantic context which was evaluated.
*/
public private(set) var semctx: SemanticContext public private(set) var semctx: SemanticContext
/** /// The alternative number for the decision which is guarded by the semantic
* The alternative number for the decision which is guarded by the semantic /// context {@link #semctx}. Note that other ATN
* context {@link #semctx}. Note that other ATN /// configurations may predict the same alternative which are guarded by
* configurations may predict the same alternative which are guarded by /// other semantic contexts and/or {@link org.antlr.v4.runtime.atn.SemanticContext#NONE}.
* other semantic contexts and/or {@link org.antlr.v4.runtime.atn.SemanticContext#NONE}.
*/
public private(set) var predictedAlt: Int public private(set) var predictedAlt: Int
/** /// The result of evaluating the semantic context {@link #semctx}.
* The result of evaluating the semantic context {@link #semctx}.
*/
public private(set) var evalResult: Bool public private(set) var evalResult: Bool
/** /// Constructs a new instance of the {@link org.antlr.v4.runtime.atn.PredicateEvalInfo} class with the
* Constructs a new instance of the {@link org.antlr.v4.runtime.atn.PredicateEvalInfo} class with the /// specified detailed predicate evaluation information.
* specified detailed predicate evaluation information. ///
* /// - parameter decision: The decision number
* @param decision The decision number /// - parameter input: The input token stream
* @param input The input token stream /// - parameter startIndex: The start index for the current prediction
* @param startIndex The start index for the current prediction /// - parameter stopIndex: The index at which the predicate evaluation was
* @param stopIndex The index at which the predicate evaluation was /// triggered. Note that the input stream may be reset to other positions for
* triggered. Note that the input stream may be reset to other positions for /// the actual evaluation of individual predicates.
* the actual evaluation of individual predicates. /// - parameter semctx: The semantic context which was evaluated
* @param semctx The semantic context which was evaluated /// - parameter evalResult: The results of evaluating the semantic context
* @param evalResult The results of evaluating the semantic context /// - parameter predictedAlt: The alternative number for the decision which is
* @param predictedAlt The alternative number for the decision which is /// guarded by the semantic context {@code semctx}. See {@link #predictedAlt}
* guarded by the semantic context {@code semctx}. See {@link #predictedAlt} /// for more information.
* for more information. /// - parameter fullCtx: {@code true} if the semantic context was
* @param fullCtx {@code true} if the semantic context was /// evaluated during LL prediction; otherwise, {@code false} if the semantic
* evaluated during LL prediction; otherwise, {@code false} if the semantic /// context was evaluated during SLL prediction
* context was evaluated during SLL prediction ///
* /// - seealso: org.antlr.v4.runtime.atn.ParserATNSimulator#evalSemanticContext(org.antlr.v4.runtime.atn.SemanticContext, org.antlr.v4.runtime.ParserRuleContext, int, boolean)
* @see org.antlr.v4.runtime.atn.ParserATNSimulator#evalSemanticContext(org.antlr.v4.runtime.atn.SemanticContext, org.antlr.v4.runtime.ParserRuleContext, int, boolean) /// - seealso: org.antlr.v4.runtime.atn.SemanticContext#eval(org.antlr.v4.runtime.Recognizer, org.antlr.v4.runtime.RuleContext)
* @see org.antlr.v4.runtime.atn.SemanticContext#eval(org.antlr.v4.runtime.Recognizer, org.antlr.v4.runtime.RuleContext)
*/
public init(_ decision: Int, public init(_ decision: Int,
_ input: TokenStream, _ input: TokenStream,
_ startIndex: Int, _ startIndex: Int,

View File

@ -1,16 +1,14 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** TODO: this is old comment: /// TODO: this is old comment:
* A tree of semantic predicates from the grammar AST if label==SEMPRED. /// A tree of semantic predicates from the grammar AST if label==SEMPRED.
* In the ATN, labels will always be exactly one predicate, but the DFA /// In the ATN, labels will always be exactly one predicate, but the DFA
* may have to combine a bunch of them as it collects predicates from /// may have to combine a bunch of them as it collects predicates from
* multiple ATN configurations into a single DFA state. /// multiple ATN configurations into a single DFA state.
*/
public final class PredicateTransition: AbstractPredicateTransition { public final class PredicateTransition: AbstractPredicateTransition {
public let ruleIndex: Int public let ruleIndex: Int

View File

@ -1,23 +1,18 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
import Foundation import Foundation
public class PredictionContext: Hashable, CustomStringConvertible { public class PredictionContext: Hashable, CustomStringConvertible {
/** /// Represents {@code $} in local context prediction, which means wildcard.
* Represents {@code $} in local context prediction, which means wildcard. /// {@code *+x = *}.
* {@code *+x = *}.
*/
public static let EMPTY: EmptyPredictionContext = EmptyPredictionContext() public static let EMPTY: EmptyPredictionContext = EmptyPredictionContext()
/** /// Represents {@code $} in an array in full context mode, when {@code $}
* Represents {@code $} in an array in full context mode, when {@code $} /// doesn't mean wildcard: {@code $ + x = [$,x]}. Here,
* doesn't mean wildcard: {@code $ + x = [$,x]}. Here, /// {@code $} = {@link #EMPTY_RETURN_STATE}.
* {@code $} = {@link #EMPTY_RETURN_STATE}.
*/
public static let EMPTY_RETURN_STATE: Int = Int(Int32.max) public static let EMPTY_RETURN_STATE: Int = Int(Int32.max)
private static let INITIAL_HASH: Int = 1 private static let INITIAL_HASH: Int = 1
@ -29,36 +24,33 @@ public class PredictionContext: Hashable, CustomStringConvertible {
return oldGlobalNodeCount return oldGlobalNodeCount
}() }()
/** /// Stores the computed hash code of this {@link org.antlr.v4.runtime.atn.PredictionContext}. The hash
* Stores the computed hash code of this {@link org.antlr.v4.runtime.atn.PredictionContext}. The hash /// code is computed in parts to match the following reference algorithm.
* code is computed in parts to match the following reference algorithm. ///
* /// <pre>
* <pre> /// private int referenceHashCode() {
* private int referenceHashCode() { /// int hash = {@link org.antlr.v4.runtime.misc.MurmurHash#initialize MurmurHash.initialize}({@link #INITIAL_HASH});
* int hash = {@link org.antlr.v4.runtime.misc.MurmurHash#initialize MurmurHash.initialize}({@link #INITIAL_HASH}); ///
* /// for (int i = 0; i &lt; {@link #size()}; i++) {
* for (int i = 0; i &lt; {@link #size()}; i++) { /// hash = {@link org.antlr.v4.runtime.misc.MurmurHash#update MurmurHash.update}(hash, {@link #getParent getParent}(i));
* hash = {@link org.antlr.v4.runtime.misc.MurmurHash#update MurmurHash.update}(hash, {@link #getParent getParent}(i)); /// }
* } ///
* /// for (int i = 0; i &lt; {@link #size()}; i++) {
* for (int i = 0; i &lt; {@link #size()}; i++) { /// hash = {@link org.antlr.v4.runtime.misc.MurmurHash#update MurmurHash.update}(hash, {@link #getReturnState getReturnState}(i));
* hash = {@link org.antlr.v4.runtime.misc.MurmurHash#update MurmurHash.update}(hash, {@link #getReturnState getReturnState}(i)); /// }
* } ///
* /// hash = {@link org.antlr.v4.runtime.misc.MurmurHash#finish MurmurHash.finish}(hash, 2 * {@link #size()});
* hash = {@link org.antlr.v4.runtime.misc.MurmurHash#finish MurmurHash.finish}(hash, 2 * {@link #size()}); /// return hash;
* return hash; /// }
* } /// </pre>
* </pre>
*/
public let cachedHashCode: Int public let cachedHashCode: Int
init(_ cachedHashCode: Int) { init(_ cachedHashCode: Int) {
self.cachedHashCode = cachedHashCode self.cachedHashCode = cachedHashCode
} }
/** Convert a {@link org.antlr.v4.runtime.RuleContext} tree to a {@link org.antlr.v4.runtime.atn.PredictionContext} graph. /// Convert a {@link org.antlr.v4.runtime.RuleContext} tree to a {@link org.antlr.v4.runtime.atn.PredictionContext} graph.
* Return {@link #EMPTY} if {@code outerContext} is empty or null. /// Return {@link #EMPTY} if {@code outerContext} is empty or null.
*/
public static func fromRuleContext(_ atn: ATN, _ outerContext: RuleContext?) -> PredictionContext { public static func fromRuleContext(_ atn: ATN, _ outerContext: RuleContext?) -> PredictionContext {
var _outerContext: RuleContext var _outerContext: RuleContext
if let outerContext = outerContext { if let outerContext = outerContext {
@ -100,7 +92,7 @@ public class PredictionContext: Hashable, CustomStringConvertible {
} }
/** This means only the {@link #EMPTY} context is in set. */ /// This means only the {@link #EMPTY} context is in set.
public func isEmpty() -> Bool { public func isEmpty() -> Bool {
return self === PredictionContext.EMPTY return self === PredictionContext.EMPTY
} }
@ -187,33 +179,31 @@ public class PredictionContext: Hashable, CustomStringConvertible {
rootIsWildcard, &mergeCache) rootIsWildcard, &mergeCache)
} }
/** /// Merge two {@link org.antlr.v4.runtime.atn.SingletonPredictionContext} instances.
* Merge two {@link org.antlr.v4.runtime.atn.SingletonPredictionContext} instances. ///
* /// <p>Stack tops equal, parents merge is same; return left graph.<br>
* <p>Stack tops equal, parents merge is same; return left graph.<br> /// <embed src="images/SingletonMerge_SameRootSamePar.svg" type="image/svg+xml"/></p>
* <embed src="images/SingletonMerge_SameRootSamePar.svg" type="image/svg+xml"/></p> ///
* /// <p>Same stack top, parents differ; merge parents giving array node, then
* <p>Same stack top, parents differ; merge parents giving array node, then /// remainders of those graphs. A new root node is created to point to the
* remainders of those graphs. A new root node is created to point to the /// merged parents.<br>
* merged parents.<br> /// <embed src="images/SingletonMerge_SameRootDiffPar.svg" type="image/svg+xml"/></p>
* <embed src="images/SingletonMerge_SameRootDiffPar.svg" type="image/svg+xml"/></p> ///
* /// <p>Different stack tops pointing to same parent. Make array node for the
* <p>Different stack tops pointing to same parent. Make array node for the /// root where both element in the root point to the same (original)
* root where both element in the root point to the same (original) /// parent.<br>
* parent.<br> /// <embed src="images/SingletonMerge_DiffRootSamePar.svg" type="image/svg+xml"/></p>
* <embed src="images/SingletonMerge_DiffRootSamePar.svg" type="image/svg+xml"/></p> ///
* /// <p>Different stack tops pointing to different parents. Make array node for
* <p>Different stack tops pointing to different parents. Make array node for /// the root where each element points to the corresponding original
* the root where each element points to the corresponding original /// parent.<br>
* parent.<br> /// <embed src="images/SingletonMerge_DiffRootDiffPar.svg" type="image/svg+xml"/></p>
* <embed src="images/SingletonMerge_DiffRootDiffPar.svg" type="image/svg+xml"/></p> ///
* /// - parameter a: the first {@link org.antlr.v4.runtime.atn.SingletonPredictionContext}
* @param a the first {@link org.antlr.v4.runtime.atn.SingletonPredictionContext} /// - parameter b: the second {@link org.antlr.v4.runtime.atn.SingletonPredictionContext}
* @param b the second {@link org.antlr.v4.runtime.atn.SingletonPredictionContext} /// - parameter rootIsWildcard: {@code true} if this is a local-context merge,
* @param rootIsWildcard {@code true} if this is a local-context merge, /// otherwise false to indicate a full-context merge
* otherwise false to indicate a full-context merge /// - parameter mergeCache:
* @param mergeCache
*/
public static func mergeSingletons( public static func mergeSingletons(
_ a: SingletonPredictionContext, _ a: SingletonPredictionContext,
_ b: SingletonPredictionContext, _ b: SingletonPredictionContext,
@ -304,44 +294,42 @@ public class PredictionContext: Hashable, CustomStringConvertible {
} }
} }
/** /// Handle case where at least one of {@code a} or {@code b} is
* Handle case where at least one of {@code a} or {@code b} is /// {@link #EMPTY}. In the following diagrams, the symbol {@code $} is used
* {@link #EMPTY}. In the following diagrams, the symbol {@code $} is used /// to represent {@link #EMPTY}.
* to represent {@link #EMPTY}. ///
* /// <h2>Local-Context Merges</h2>
* <h2>Local-Context Merges</h2> ///
* /// <p>These local-context merge operations are used when {@code rootIsWildcard}
* <p>These local-context merge operations are used when {@code rootIsWildcard} /// is true.</p>
* is true.</p> ///
* /// <p>{@link #EMPTY} is superset of any graph; return {@link #EMPTY}.<br>
* <p>{@link #EMPTY} is superset of any graph; return {@link #EMPTY}.<br> /// <embed src="images/LocalMerge_EmptyRoot.svg" type="image/svg+xml"/></p>
* <embed src="images/LocalMerge_EmptyRoot.svg" type="image/svg+xml"/></p> ///
* /// <p>{@link #EMPTY} and anything is {@code #EMPTY}, so merged parent is
* <p>{@link #EMPTY} and anything is {@code #EMPTY}, so merged parent is /// {@code #EMPTY}; return left graph.<br>
* {@code #EMPTY}; return left graph.<br> /// <embed src="images/LocalMerge_EmptyParent.svg" type="image/svg+xml"/></p>
* <embed src="images/LocalMerge_EmptyParent.svg" type="image/svg+xml"/></p> ///
* /// <p>Special case of last merge if local context.<br>
* <p>Special case of last merge if local context.<br> /// <embed src="images/LocalMerge_DiffRoots.svg" type="image/svg+xml"/></p>
* <embed src="images/LocalMerge_DiffRoots.svg" type="image/svg+xml"/></p> ///
* /// <h2>Full-Context Merges</h2>
* <h2>Full-Context Merges</h2> ///
* /// <p>These full-context merge operations are used when {@code rootIsWildcard}
* <p>These full-context merge operations are used when {@code rootIsWildcard} /// is false.</p>
* is false.</p> ///
* /// <p><embed src="images/FullMerge_EmptyRoots.svg" type="image/svg+xml"/></p>
* <p><embed src="images/FullMerge_EmptyRoots.svg" type="image/svg+xml"/></p> ///
* /// <p>Must keep all contexts; {@link #EMPTY} in array is a special value (and
* <p>Must keep all contexts; {@link #EMPTY} in array is a special value (and /// null parent).<br>
* null parent).<br> /// <embed src="images/FullMerge_EmptyRoot.svg" type="image/svg+xml"/></p>
* <embed src="images/FullMerge_EmptyRoot.svg" type="image/svg+xml"/></p> ///
* /// <p><embed src="images/FullMerge_SameRoot.svg" type="image/svg+xml"/></p>
* <p><embed src="images/FullMerge_SameRoot.svg" type="image/svg+xml"/></p> ///
* /// - parameter a: the first {@link org.antlr.v4.runtime.atn.SingletonPredictionContext}
* @param a the first {@link org.antlr.v4.runtime.atn.SingletonPredictionContext} /// - parameter b: the second {@link org.antlr.v4.runtime.atn.SingletonPredictionContext}
* @param b the second {@link org.antlr.v4.runtime.atn.SingletonPredictionContext} /// - parameter rootIsWildcard: {@code true} if this is a local-context merge,
* @param rootIsWildcard {@code true} if this is a local-context merge, /// otherwise false to indicate a full-context merge
* otherwise false to indicate a full-context merge
*/
public static func mergeRoot(_ a: SingletonPredictionContext, public static func mergeRoot(_ a: SingletonPredictionContext,
_ b: SingletonPredictionContext, _ b: SingletonPredictionContext,
_ rootIsWildcard: Bool) -> PredictionContext? { _ rootIsWildcard: Bool) -> PredictionContext? {
@ -376,25 +364,23 @@ public class PredictionContext: Hashable, CustomStringConvertible {
return nil return nil
} }
/** /// Merge two {@link org.antlr.v4.runtime.atn.ArrayPredictionContext} instances.
* Merge two {@link org.antlr.v4.runtime.atn.ArrayPredictionContext} instances. ///
* /// <p>Different tops, different parents.<br>
* <p>Different tops, different parents.<br> /// <embed src="images/ArrayMerge_DiffTopDiffPar.svg" type="image/svg+xml"/></p>
* <embed src="images/ArrayMerge_DiffTopDiffPar.svg" type="image/svg+xml"/></p> ///
* /// <p>Shared top, same parents.<br>
* <p>Shared top, same parents.<br> /// <embed src="images/ArrayMerge_ShareTopSamePar.svg" type="image/svg+xml"/></p>
* <embed src="images/ArrayMerge_ShareTopSamePar.svg" type="image/svg+xml"/></p> ///
* /// <p>Shared top, different parents.<br>
* <p>Shared top, different parents.<br> /// <embed src="images/ArrayMerge_ShareTopDiffPar.svg" type="image/svg+xml"/></p>
* <embed src="images/ArrayMerge_ShareTopDiffPar.svg" type="image/svg+xml"/></p> ///
* /// <p>Shared top, all shared parents.<br>
* <p>Shared top, all shared parents.<br> /// <embed src="images/ArrayMerge_ShareTopSharePar.svg" type="image/svg+xml"/></p>
* <embed src="images/ArrayMerge_ShareTopSharePar.svg" type="image/svg+xml"/></p> ///
* /// <p>Equal tops, merge parents and reduce top to
* <p>Equal tops, merge parents and reduce top to /// {@link org.antlr.v4.runtime.atn.SingletonPredictionContext}.<br>
* {@link org.antlr.v4.runtime.atn.SingletonPredictionContext}.<br> /// <embed src="images/ArrayMerge_EqualTop.svg" type="image/svg+xml"/></p>
* <embed src="images/ArrayMerge_EqualTop.svg" type="image/svg+xml"/></p>
*/
public static func mergeArrays( public static func mergeArrays(
_ a: ArrayPredictionContext, _ a: ArrayPredictionContext,
_ b: ArrayPredictionContext, _ b: ArrayPredictionContext,
@ -537,10 +523,8 @@ public class PredictionContext: Hashable, CustomStringConvertible {
return M return M
} }
/** /// Make pass over all <em>M</em> {@code parents}; merge any {@code equals()}
* Make pass over all <em>M</em> {@code parents}; merge any {@code equals()} /// ones.
* ones.
*/
// internal static func combineCommonParents(inout parents: [PredictionContext?]) { // internal static func combineCommonParents(inout parents: [PredictionContext?]) {
// var uniqueParents: Dictionary<PredictionContext, PredictionContext> = // var uniqueParents: Dictionary<PredictionContext, PredictionContext> =
// Dictionary<PredictionContext, PredictionContext>() // Dictionary<PredictionContext, PredictionContext>()

View File

@ -1,13 +1,11 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** Used to cache {@link org.antlr.v4.runtime.atn.PredictionContext} objects. Its used for the shared /// Used to cache {@link org.antlr.v4.runtime.atn.PredictionContext} objects. Its used for the shared
* context cash associated with contexts in DFA states. This cache /// context cash associated with contexts in DFA states. This cache
* can be used for both lexers and parsers. /// can be used for both lexers and parsers.
*/
public final class PredictionContextCache { public final class PredictionContextCache {
//internal final var //internal final var
@ -15,10 +13,9 @@ public final class PredictionContextCache {
HashMap<PredictionContext, PredictionContext>() HashMap<PredictionContext, PredictionContext>()
public init() { public init() {
} }
/** Add a context to the cache and return it. If the context already exists, /// Add a context to the cache and return it. If the context already exists,
* return that one instead and do not add a new context to the cache. /// return that one instead and do not add a new context to the cache.
* Protect shared cache from unsafe thread access. /// Protect shared cache from unsafe thread access.
*/
@discardableResult @discardableResult
public func add(_ ctx: PredictionContext) -> PredictionContext { public func add(_ ctx: PredictionContext) -> PredictionContext {
if ctx === PredictionContext.EMPTY { if ctx === PredictionContext.EMPTY {

View File

@ -1,15 +1,12 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** /// This enumeration defines the prediction modes available in ANTLR 4 along with
* This enumeration defines the prediction modes available in ANTLR 4 along with /// utility methods for analyzing configuration sets for conflicts and/or
* utility methods for analyzing configuration sets for conflicts and/or /// ambiguities.
* ambiguities.
*/
public enum PredictionMode { public enum PredictionMode {
/** /**
@ -73,105 +70,102 @@ public enum PredictionMode {
case LL_EXACT_AMBIG_DETECTION case LL_EXACT_AMBIG_DETECTION
/** /// Computes the SLL prediction termination condition.
* Computes the SLL prediction termination condition. ///
* /// <p>
* <p> /// This method computes the SLL prediction termination condition for both of
* This method computes the SLL prediction termination condition for both of /// the following cases.</p>
* the following cases.</p> ///
* /// <ul>
* <ul> /// <li>The usual SLL+LL fallback upon SLL conflict</li>
* <li>The usual SLL+LL fallback upon SLL conflict</li> /// <li>Pure SLL without LL fallback</li>
* <li>Pure SLL without LL fallback</li> /// </ul>
* </ul> ///
* /// <p><strong>COMBINED SLL+LL PARSING</strong></p>
* <p><strong>COMBINED SLL+LL PARSING</strong></p> ///
* /// <p>When LL-fallback is enabled upon SLL conflict, correct predictions are
* <p>When LL-fallback is enabled upon SLL conflict, correct predictions are /// ensured regardless of how the termination condition is computed by this
* ensured regardless of how the termination condition is computed by this /// method. Due to the substantially higher cost of LL prediction, the
* method. Due to the substantially higher cost of LL prediction, the /// prediction should only fall back to LL when the additional lookahead
* prediction should only fall back to LL when the additional lookahead /// cannot lead to a unique SLL prediction.</p>
* cannot lead to a unique SLL prediction.</p> ///
* /// <p>Assuming combined SLL+LL parsing, an SLL configuration set with only
* <p>Assuming combined SLL+LL parsing, an SLL configuration set with only /// conflicting subsets should fall back to full LL, even if the
* conflicting subsets should fall back to full LL, even if the /// configuration sets don't resolve to the same alternative (e.g.
* configuration sets don't resolve to the same alternative (e.g. /// {@code {1,2}} and {@code {3,4}}. If there is at least one non-conflicting
* {@code {1,2}} and {@code {3,4}}. If there is at least one non-conflicting /// configuration, SLL could continue with the hopes that more lookahead will
* configuration, SLL could continue with the hopes that more lookahead will /// resolve via one of those non-conflicting configurations.</p>
* resolve via one of those non-conflicting configurations.</p> ///
* /// <p>Here's the prediction termination rule them: SLL (for SLL+LL parsing)
* <p>Here's the prediction termination rule them: SLL (for SLL+LL parsing) /// stops when it sees only conflicting configuration subsets. In contrast,
* stops when it sees only conflicting configuration subsets. In contrast, /// full LL keeps going when there is uncertainty.</p>
* full LL keeps going when there is uncertainty.</p> ///
* /// <p><strong>HEURISTIC</strong></p>
* <p><strong>HEURISTIC</strong></p> ///
* /// <p>As a heuristic, we stop prediction when we see any conflicting subset
* <p>As a heuristic, we stop prediction when we see any conflicting subset /// unless we see a state that only has one alternative associated with it.
* unless we see a state that only has one alternative associated with it. /// The single-alt-state thing lets prediction continue upon rules like
* The single-alt-state thing lets prediction continue upon rules like /// (otherwise, it would admit defeat too soon):</p>
* (otherwise, it would admit defeat too soon):</p> ///
* /// <p>{@code [12|1|[], 6|2|[], 12|2|[]]. s : (ID | ID ID?) ';' ;}</p>
* <p>{@code [12|1|[], 6|2|[], 12|2|[]]. s : (ID | ID ID?) ';' ;}</p> ///
* /// <p>When the ATN simulation reaches the state before {@code ';'}, it has a
* <p>When the ATN simulation reaches the state before {@code ';'}, it has a /// DFA state that looks like: {@code [12|1|[], 6|2|[], 12|2|[]]}. Naturally
* DFA state that looks like: {@code [12|1|[], 6|2|[], 12|2|[]]}. Naturally /// {@code 12|1|[]} and {@code 12|2|[]} conflict, but we cannot stop
* {@code 12|1|[]} and {@code 12|2|[]} conflict, but we cannot stop /// processing this node because alternative to has another way to continue,
* processing this node because alternative to has another way to continue, /// via {@code [6|2|[]]}.</p>
* via {@code [6|2|[]]}.</p> ///
* /// <p>It also let's us continue for this rule:</p>
* <p>It also let's us continue for this rule:</p> ///
* /// <p>{@code [1|1|[], 1|2|[], 8|3|[]] a : A | A | A B ;}</p>
* <p>{@code [1|1|[], 1|2|[], 8|3|[]] a : A | A | A B ;}</p> ///
* /// <p>After matching input A, we reach the stop state for rule A, state 1.
* <p>After matching input A, we reach the stop state for rule A, state 1. /// State 8 is the state right before B. Clearly alternatives 1 and 2
* State 8 is the state right before B. Clearly alternatives 1 and 2 /// conflict and no amount of further lookahead will separate the two.
* conflict and no amount of further lookahead will separate the two. /// However, alternative 3 will be able to continue and so we do not stop
* However, alternative 3 will be able to continue and so we do not stop /// working on this state. In the previous example, we're concerned with
* working on this state. In the previous example, we're concerned with /// states associated with the conflicting alternatives. Here alt 3 is not
* states associated with the conflicting alternatives. Here alt 3 is not /// associated with the conflicting configs, but since we can continue
* associated with the conflicting configs, but since we can continue /// looking for input reasonably, don't declare the state done.</p>
* looking for input reasonably, don't declare the state done.</p> ///
* /// <p><strong>PURE SLL PARSING</strong></p>
* <p><strong>PURE SLL PARSING</strong></p> ///
* /// <p>To handle pure SLL parsing, all we have to do is make sure that we
* <p>To handle pure SLL parsing, all we have to do is make sure that we /// combine stack contexts for configurations that differ only by semantic
* combine stack contexts for configurations that differ only by semantic /// predicate. From there, we can do the usual SLL termination heuristic.</p>
* predicate. From there, we can do the usual SLL termination heuristic.</p> ///
* /// <p><strong>PREDICATES IN SLL+LL PARSING</strong></p>
* <p><strong>PREDICATES IN SLL+LL PARSING</strong></p> ///
* /// <p>SLL decisions don't evaluate predicates until after they reach DFA stop
* <p>SLL decisions don't evaluate predicates until after they reach DFA stop /// states because they need to create the DFA cache that works in all
* states because they need to create the DFA cache that works in all /// semantic situations. In contrast, full LL evaluates predicates collected
* semantic situations. In contrast, full LL evaluates predicates collected /// during start state computation so it can ignore predicates thereafter.
* during start state computation so it can ignore predicates thereafter. /// This means that SLL termination detection can totally ignore semantic
* This means that SLL termination detection can totally ignore semantic /// predicates.</p>
* predicates.</p> ///
* /// <p>Implementation-wise, {@link org.antlr.v4.runtime.atn.ATNConfigSet} combines stack contexts but not
* <p>Implementation-wise, {@link org.antlr.v4.runtime.atn.ATNConfigSet} combines stack contexts but not /// semantic predicate contexts so we might see two configurations like the
* semantic predicate contexts so we might see two configurations like the /// following.</p>
* following.</p> ///
* /// <p>{@code (s, 1, x, {}), (s, 1, x', {p})}</p>
* <p>{@code (s, 1, x, {}), (s, 1, x', {p})}</p> ///
* /// <p>Before testing these configurations against others, we have to merge
* <p>Before testing these configurations against others, we have to merge /// {@code x} and {@code x'} (without modifying the existing configurations).
* {@code x} and {@code x'} (without modifying the existing configurations). /// For example, we test {@code (x+x')==x''} when looking for conflicts in
* For example, we test {@code (x+x')==x''} when looking for conflicts in /// the following configurations.</p>
* the following configurations.</p> ///
* /// <p>{@code (s, 1, x, {}), (s, 1, x', {p}), (s, 2, x'', {})}</p>
* <p>{@code (s, 1, x, {}), (s, 1, x', {p}), (s, 2, x'', {})}</p> ///
* /// <p>If the configuration set has predicates (as indicated by
* <p>If the configuration set has predicates (as indicated by /// {@link org.antlr.v4.runtime.atn.ATNConfigSet#hasSemanticContext}), this algorithm makes a copy of
* {@link org.antlr.v4.runtime.atn.ATNConfigSet#hasSemanticContext}), this algorithm makes a copy of /// the configurations to strip out all of the predicates so that a standard
* the configurations to strip out all of the predicates so that a standard /// {@link org.antlr.v4.runtime.atn.ATNConfigSet} will merge everything ignoring predicates.</p>
* {@link org.antlr.v4.runtime.atn.ATNConfigSet} will merge everything ignoring predicates.</p>
*/
public static func hasSLLConflictTerminatingPrediction(_ mode: PredictionMode,_ configs: ATNConfigSet) throws -> Bool { public static func hasSLLConflictTerminatingPrediction(_ mode: PredictionMode,_ configs: ATNConfigSet) throws -> Bool {
var configs = configs var configs = configs
/* Configs in rule stop states indicate reaching the end of the decision /// Configs in rule stop states indicate reaching the end of the decision
* rule (local context) or end of start rule (full context). If all /// rule (local context) or end of start rule (full context). If all
* configs meet this condition, then none of the configurations is able /// configs meet this condition, then none of the configurations is able
* to match additional input so we terminate prediction. /// to match additional input so we terminate prediction.
*/
if allConfigsInRuleStopStates(configs) { if allConfigsInRuleStopStates(configs) {
return true return true
} }
@ -197,201 +191,191 @@ public enum PredictionMode {
return heuristic return heuristic
} }
/** /// Checks if any configuration in {@code configs} is in a
* Checks if any configuration in {@code configs} is in a /// {@link org.antlr.v4.runtime.atn.RuleStopState}. Configurations meeting this condition have reached
* {@link org.antlr.v4.runtime.atn.RuleStopState}. Configurations meeting this condition have reached /// the end of the decision rule (local context) or end of start rule (full
* the end of the decision rule (local context) or end of start rule (full /// context).
* context). ///
* /// - parameter configs: the configuration set to test
* @param configs the configuration set to test /// - returns: {@code true} if any configuration in {@code configs} is in a
* @return {@code true} if any configuration in {@code configs} is in a /// {@link org.antlr.v4.runtime.atn.RuleStopState}, otherwise {@code false}
* {@link org.antlr.v4.runtime.atn.RuleStopState}, otherwise {@code false}
*/
public static func hasConfigInRuleStopState(_ configs: ATNConfigSet) -> Bool { public static func hasConfigInRuleStopState(_ configs: ATNConfigSet) -> Bool {
return configs.hasConfigInRuleStopState return configs.hasConfigInRuleStopState
} }
/** /// Checks if all configurations in {@code configs} are in a
* Checks if all configurations in {@code configs} are in a /// {@link org.antlr.v4.runtime.atn.RuleStopState}. Configurations meeting this condition have reached
* {@link org.antlr.v4.runtime.atn.RuleStopState}. Configurations meeting this condition have reached /// the end of the decision rule (local context) or end of start rule (full
* the end of the decision rule (local context) or end of start rule (full /// context).
* context). ///
* /// - parameter configs: the configuration set to test
* @param configs the configuration set to test /// - returns: {@code true} if all configurations in {@code configs} are in a
* @return {@code true} if all configurations in {@code configs} are in a /// {@link org.antlr.v4.runtime.atn.RuleStopState}, otherwise {@code false}
* {@link org.antlr.v4.runtime.atn.RuleStopState}, otherwise {@code false}
*/
public static func allConfigsInRuleStopStates(_ configs: ATNConfigSet) -> Bool { public static func allConfigsInRuleStopStates(_ configs: ATNConfigSet) -> Bool {
return configs.allConfigsInRuleStopStates return configs.allConfigsInRuleStopStates
} }
/** /// Full LL prediction termination.
* Full LL prediction termination. ///
* /// <p>Can we stop looking ahead during ATN simulation or is there some
* <p>Can we stop looking ahead during ATN simulation or is there some /// uncertainty as to which alternative we will ultimately pick, after
* uncertainty as to which alternative we will ultimately pick, after /// consuming more input? Even if there are partial conflicts, we might know
* consuming more input? Even if there are partial conflicts, we might know /// that everything is going to resolve to the same minimum alternative. That
* that everything is going to resolve to the same minimum alternative. That /// means we can stop since no more lookahead will change that fact. On the
* means we can stop since no more lookahead will change that fact. On the /// other hand, there might be multiple conflicts that resolve to different
* other hand, there might be multiple conflicts that resolve to different /// minimums. That means we need more look ahead to decide which of those
* minimums. That means we need more look ahead to decide which of those /// alternatives we should predict.</p>
* alternatives we should predict.</p> ///
* /// <p>The basic idea is to split the set of configurations {@code C}, into
* <p>The basic idea is to split the set of configurations {@code C}, into /// conflicting subsets {@code (s, _, ctx, _)} and singleton subsets with
* conflicting subsets {@code (s, _, ctx, _)} and singleton subsets with /// non-conflicting configurations. Two configurations conflict if they have
* non-conflicting configurations. Two configurations conflict if they have /// identical {@link org.antlr.v4.runtime.atn.ATNConfig#state} and {@link org.antlr.v4.runtime.atn.ATNConfig#context} values
* identical {@link org.antlr.v4.runtime.atn.ATNConfig#state} and {@link org.antlr.v4.runtime.atn.ATNConfig#context} values /// but different {@link org.antlr.v4.runtime.atn.ATNConfig#alt} value, e.g. {@code (s, i, ctx, _)}
* but different {@link org.antlr.v4.runtime.atn.ATNConfig#alt} value, e.g. {@code (s, i, ctx, _)} /// and {@code (s, j, ctx, _)} for {@code i!=j}.</p>
* and {@code (s, j, ctx, _)} for {@code i!=j}.</p> ///
* /// <p>Reduce these configuration subsets to the set of possible alternatives.
* <p>Reduce these configuration subsets to the set of possible alternatives. /// You can compute the alternative subsets in one pass as follows:</p>
* You can compute the alternative subsets in one pass as follows:</p> ///
* /// <p>{@code A_s,ctx = {i | (s, i, ctx, _)}} for each configuration in
* <p>{@code A_s,ctx = {i | (s, i, ctx, _)}} for each configuration in /// {@code C} holding {@code s} and {@code ctx} fixed.</p>
* {@code C} holding {@code s} and {@code ctx} fixed.</p> ///
* /// <p>Or in pseudo-code, for each configuration {@code c} in {@code C}:</p>
* <p>Or in pseudo-code, for each configuration {@code c} in {@code C}:</p> ///
* /// <pre>
* <pre> /// map[c] U= c.{@link org.antlr.v4.runtime.atn.ATNConfig#alt alt} # map hash/equals uses s and x, not
* map[c] U= c.{@link org.antlr.v4.runtime.atn.ATNConfig#alt alt} # map hash/equals uses s and x, not /// alt and not pred
* alt and not pred /// </pre>
* </pre> ///
* /// <p>The values in {@code map} are the set of {@code A_s,ctx} sets.</p>
* <p>The values in {@code map} are the set of {@code A_s,ctx} sets.</p> ///
* /// <p>If {@code |A_s,ctx|=1} then there is no conflict associated with
* <p>If {@code |A_s,ctx|=1} then there is no conflict associated with /// {@code s} and {@code ctx}.</p>
* {@code s} and {@code ctx}.</p> ///
* /// <p>Reduce the subsets to singletons by choosing a minimum of each subset. If
* <p>Reduce the subsets to singletons by choosing a minimum of each subset. If /// the union of these alternative subsets is a singleton, then no amount of
* the union of these alternative subsets is a singleton, then no amount of /// more lookahead will help us. We will always pick that alternative. If,
* more lookahead will help us. We will always pick that alternative. If, /// however, there is more than one alternative, then we are uncertain which
* however, there is more than one alternative, then we are uncertain which /// alternative to predict and must continue looking for resolution. We may
* alternative to predict and must continue looking for resolution. We may /// or may not discover an ambiguity in the future, even if there are no
* or may not discover an ambiguity in the future, even if there are no /// conflicting subsets this round.</p>
* conflicting subsets this round.</p> ///
* /// <p>The biggest sin is to terminate early because it means we've made a
* <p>The biggest sin is to terminate early because it means we've made a /// decision but were uncertain as to the eventual outcome. We haven't used
* decision but were uncertain as to the eventual outcome. We haven't used /// enough lookahead. On the other hand, announcing a conflict too late is no
* enough lookahead. On the other hand, announcing a conflict too late is no /// big deal; you will still have the conflict. It's just inefficient. It
* big deal; you will still have the conflict. It's just inefficient. It /// might even look until the end of file.</p>
* might even look until the end of file.</p> ///
* /// <p>No special consideration for semantic predicates is required because
* <p>No special consideration for semantic predicates is required because /// predicates are evaluated on-the-fly for full LL prediction, ensuring that
* predicates are evaluated on-the-fly for full LL prediction, ensuring that /// no configuration contains a semantic context during the termination
* no configuration contains a semantic context during the termination /// check.</p>
* check.</p> ///
* /// <p><strong>CONFLICTING CONFIGS</strong></p>
* <p><strong>CONFLICTING CONFIGS</strong></p> ///
* /// <p>Two configurations {@code (s, i, x)} and {@code (s, j, x')}, conflict
* <p>Two configurations {@code (s, i, x)} and {@code (s, j, x')}, conflict /// when {@code i!=j} but {@code x=x'}. Because we merge all
* when {@code i!=j} but {@code x=x'}. Because we merge all /// {@code (s, i, _)} configurations together, that means that there are at
* {@code (s, i, _)} configurations together, that means that there are at /// most {@code n} configurations associated with state {@code s} for
* most {@code n} configurations associated with state {@code s} for /// {@code n} possible alternatives in the decision. The merged stacks
* {@code n} possible alternatives in the decision. The merged stacks /// complicate the comparison of configuration contexts {@code x} and
* complicate the comparison of configuration contexts {@code x} and /// {@code x'}. Sam checks to see if one is a subset of the other by calling
* {@code x'}. Sam checks to see if one is a subset of the other by calling /// merge and checking to see if the merged result is either {@code x} or
* merge and checking to see if the merged result is either {@code x} or /// {@code x'}. If the {@code x} associated with lowest alternative {@code i}
* {@code x'}. If the {@code x} associated with lowest alternative {@code i} /// is the superset, then {@code i} is the only possible prediction since the
* is the superset, then {@code i} is the only possible prediction since the /// others resolve to {@code min(i)} as well. However, if {@code x} is
* others resolve to {@code min(i)} as well. However, if {@code x} is /// associated with {@code j>i} then at least one stack configuration for
* associated with {@code j>i} then at least one stack configuration for /// {@code j} is not in conflict with alternative {@code i}. The algorithm
* {@code j} is not in conflict with alternative {@code i}. The algorithm /// should keep going, looking for more lookahead due to the uncertainty.</p>
* should keep going, looking for more lookahead due to the uncertainty.</p> ///
* /// <p>For simplicity, I'm doing a equality check between {@code x} and
* <p>For simplicity, I'm doing a equality check between {@code x} and /// {@code x'} that lets the algorithm continue to consume lookahead longer
* {@code x'} that lets the algorithm continue to consume lookahead longer /// than necessary. The reason I like the equality is of course the
* than necessary. The reason I like the equality is of course the /// simplicity but also because that is the test you need to detect the
* simplicity but also because that is the test you need to detect the /// alternatives that are actually in conflict.</p>
* alternatives that are actually in conflict.</p> ///
* /// <p><strong>CONTINUE/STOP RULE</strong></p>
* <p><strong>CONTINUE/STOP RULE</strong></p> ///
* /// <p>Continue if union of resolved alternative sets from non-conflicting and
* <p>Continue if union of resolved alternative sets from non-conflicting and /// conflicting alternative subsets has more than one alternative. We are
* conflicting alternative subsets has more than one alternative. We are /// uncertain about which alternative to predict.</p>
* uncertain about which alternative to predict.</p> ///
* /// <p>The complete set of alternatives, {@code [i for (_,i,_)]}, tells us which
* <p>The complete set of alternatives, {@code [i for (_,i,_)]}, tells us which /// alternatives are still in the running for the amount of input we've
* alternatives are still in the running for the amount of input we've /// consumed at this point. The conflicting sets let us to strip away
* consumed at this point. The conflicting sets let us to strip away /// configurations that won't lead to more states because we resolve
* configurations that won't lead to more states because we resolve /// conflicts to the configuration with a minimum alternate for the
* conflicts to the configuration with a minimum alternate for the /// conflicting set.</p>
* conflicting set.</p> ///
* /// <p><strong>CASES</strong></p>
* <p><strong>CASES</strong></p> ///
* /// <ul>
* <ul> ///
* /// <li>no conflicts and more than 1 alternative in set =&gt; continue</li>
* <li>no conflicts and more than 1 alternative in set =&gt; continue</li> ///
* /// <li> {@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s, 3, z)},
* <li> {@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s, 3, z)}, /// {@code (s', 1, y)}, {@code (s', 2, y)} yields non-conflicting set
* {@code (s', 1, y)}, {@code (s', 2, y)} yields non-conflicting set /// {@code {3}} U conflicting sets {@code min({1,2})} U {@code min({1,2})} =
* {@code {3}} U conflicting sets {@code min({1,2})} U {@code min({1,2})} = /// {@code {1,3}} =&gt; continue
* {@code {1,3}} =&gt; continue /// </li>
* </li> ///
* /// <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 1, y)},
* <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 1, y)}, /// {@code (s', 2, y)}, {@code (s'', 1, z)} yields non-conflicting set
* {@code (s', 2, y)}, {@code (s'', 1, z)} yields non-conflicting set /// {@code {1}} U conflicting sets {@code min({1,2})} U {@code min({1,2})} =
* {@code {1}} U conflicting sets {@code min({1,2})} U {@code min({1,2})} = /// {@code {1}} =&gt; stop and predict 1</li>
* {@code {1}} =&gt; stop and predict 1</li> ///
* /// <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 1, y)},
* <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 1, y)}, /// {@code (s', 2, y)} yields conflicting, reduced sets {@code {1}} U
* {@code (s', 2, y)} yields conflicting, reduced sets {@code {1}} U /// {@code {1}} = {@code {1}} =&gt; stop and predict 1, can announce
* {@code {1}} = {@code {1}} =&gt; stop and predict 1, can announce /// ambiguity {@code {1,2}}</li>
* ambiguity {@code {1,2}}</li> ///
* /// <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 2, y)},
* <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 2, y)}, /// {@code (s', 3, y)} yields conflicting, reduced sets {@code {1}} U
* {@code (s', 3, y)} yields conflicting, reduced sets {@code {1}} U /// {@code {2}} = {@code {1,2}} =&gt; continue</li>
* {@code {2}} = {@code {1,2}} =&gt; continue</li> ///
* /// <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 3, y)},
* <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 3, y)}, /// {@code (s', 4, y)} yields conflicting, reduced sets {@code {1}} U
* {@code (s', 4, y)} yields conflicting, reduced sets {@code {1}} U /// {@code {3}} = {@code {1,3}} =&gt; continue</li>
* {@code {3}} = {@code {1,3}} =&gt; continue</li> ///
* /// </ul>
* </ul> ///
* /// <p><strong>EXACT AMBIGUITY DETECTION</strong></p>
* <p><strong>EXACT AMBIGUITY DETECTION</strong></p> ///
* /// <p>If all states report the same conflicting set of alternatives, then we
* <p>If all states report the same conflicting set of alternatives, then we /// know we have the exact ambiguity set.</p>
* know we have the exact ambiguity set.</p> ///
* /// <p><code>|A_<em>i</em>|&gt;1</code> and
* <p><code>|A_<em>i</em>|&gt;1</code> and /// <code>A_<em>i</em> = A_<em>j</em></code> for all <em>i</em>, <em>j</em>.</p>
* <code>A_<em>i</em> = A_<em>j</em></code> for all <em>i</em>, <em>j</em>.</p> ///
* /// <p>In other words, we continue examining lookahead until all {@code A_i}
* <p>In other words, we continue examining lookahead until all {@code A_i} /// have more than one alternative and all {@code A_i} are the same. If
* have more than one alternative and all {@code A_i} are the same. If /// {@code A={{1,2}, {1,3}}}, then regular LL prediction would terminate
* {@code A={{1,2}, {1,3}}}, then regular LL prediction would terminate /// because the resolved set is {@code {1}}. To determine what the real
* because the resolved set is {@code {1}}. To determine what the real /// ambiguity is, we have to know whether the ambiguity is between one and
* ambiguity is, we have to know whether the ambiguity is between one and /// two or one and three so we keep going. We can only stop prediction when
* two or one and three so we keep going. We can only stop prediction when /// we need exact ambiguity detection when the sets look like
* we need exact ambiguity detection when the sets look like /// {@code A={{1,2}}} or {@code {{1,2},{1,2}}}, etc...</p>
* {@code A={{1,2}}} or {@code {{1,2},{1,2}}}, etc...</p>
*/
public static func resolvesToJustOneViableAlt(_ altsets: Array<BitSet>) throws -> Int { public static func resolvesToJustOneViableAlt(_ altsets: Array<BitSet>) throws -> Int {
return try getSingleViableAlt(altsets) return try getSingleViableAlt(altsets)
} }
/** /// Determines if every alternative subset in {@code altsets} contains more
* Determines if every alternative subset in {@code altsets} contains more /// than one alternative.
* than one alternative. ///
* /// - parameter altsets: a collection of alternative subsets
* @param altsets a collection of alternative subsets /// - returns: {@code true} if every {@link java.util.BitSet} in {@code altsets} has
* @return {@code true} if every {@link java.util.BitSet} in {@code altsets} has /// {@link java.util.BitSet#cardinality cardinality} &gt; 1, otherwise {@code false}
* {@link java.util.BitSet#cardinality cardinality} &gt; 1, otherwise {@code false}
*/
public static func allSubsetsConflict(_ altsets: Array<BitSet>) -> Bool { public static func allSubsetsConflict(_ altsets: Array<BitSet>) -> Bool {
return !hasNonConflictingAltSet(altsets) return !hasNonConflictingAltSet(altsets)
} }
/** /// Determines if any single alternative subset in {@code altsets} contains
* Determines if any single alternative subset in {@code altsets} contains /// exactly one alternative.
* exactly one alternative. ///
* /// - parameter altsets: a collection of alternative subsets
* @param altsets a collection of alternative subsets /// - returns: {@code true} if {@code altsets} contains a {@link java.util.BitSet} with
* @return {@code true} if {@code altsets} contains a {@link java.util.BitSet} with /// {@link java.util.BitSet#cardinality cardinality} 1, otherwise {@code false}
* {@link java.util.BitSet#cardinality cardinality} 1, otherwise {@code false}
*/
public static func hasNonConflictingAltSet(_ altsets: Array<BitSet>) -> Bool { public static func hasNonConflictingAltSet(_ altsets: Array<BitSet>) -> Bool {
for alts: BitSet in altsets { for alts: BitSet in altsets {
if alts.cardinality() == 1 { if alts.cardinality() == 1 {
@ -401,14 +385,12 @@ public enum PredictionMode {
return false return false
} }
/** /// Determines if any single alternative subset in {@code altsets} contains
* Determines if any single alternative subset in {@code altsets} contains /// more than one alternative.
* more than one alternative. ///
* /// - parameter altsets: a collection of alternative subsets
* @param altsets a collection of alternative subsets /// - returns: {@code true} if {@code altsets} contains a {@link java.util.BitSet} with
* @return {@code true} if {@code altsets} contains a {@link java.util.BitSet} with /// {@link java.util.BitSet#cardinality cardinality} &gt; 1, otherwise {@code false}
* {@link java.util.BitSet#cardinality cardinality} &gt; 1, otherwise {@code false}
*/
public static func hasConflictingAltSet(_ altsets: Array<BitSet>) -> Bool { public static func hasConflictingAltSet(_ altsets: Array<BitSet>) -> Bool {
for alts: BitSet in altsets { for alts: BitSet in altsets {
if alts.cardinality() > 1 { if alts.cardinality() > 1 {
@ -418,13 +400,11 @@ public enum PredictionMode {
return false return false
} }
/** /// Determines if every alternative subset in {@code altsets} is equivalent.
* Determines if every alternative subset in {@code altsets} is equivalent. ///
* /// - parameter altsets: a collection of alternative subsets
* @param altsets a collection of alternative subsets /// - returns: {@code true} if every member of {@code altsets} is equal to the
* @return {@code true} if every member of {@code altsets} is equal to the /// others, otherwise {@code false}
* others, otherwise {@code false}
*/
public static func allSubsetsEqual(_ altsets: Array<BitSet>) -> Bool { public static func allSubsetsEqual(_ altsets: Array<BitSet>) -> Bool {
let first: BitSet = altsets[0] let first: BitSet = altsets[0]
@ -437,13 +417,11 @@ public enum PredictionMode {
return true return true
} }
/** /// Returns the unique alternative predicted by all alternative subsets in
* Returns the unique alternative predicted by all alternative subsets in /// {@code altsets}. If no such alternative exists, this method returns
* {@code altsets}. If no such alternative exists, this method returns /// {@link org.antlr.v4.runtime.atn.ATN#INVALID_ALT_NUMBER}.
* {@link org.antlr.v4.runtime.atn.ATN#INVALID_ALT_NUMBER}. ///
* /// - parameter altsets: a collection of alternative subsets
* @param altsets a collection of alternative subsets
*/
public static func getUniqueAlt(_ altsets: Array<BitSet>) throws -> Int { public static func getUniqueAlt(_ altsets: Array<BitSet>) throws -> Int {
let all: BitSet = getAlts(altsets) let all: BitSet = getAlts(altsets)
if all.cardinality() == 1 { if all.cardinality() == 1 {
@ -452,14 +430,12 @@ public enum PredictionMode {
return ATN.INVALID_ALT_NUMBER return ATN.INVALID_ALT_NUMBER
} }
/** /// Gets the complete set of represented alternatives for a collection of
* Gets the complete set of represented alternatives for a collection of /// alternative subsets. This method returns the union of each {@link java.util.BitSet}
* alternative subsets. This method returns the union of each {@link java.util.BitSet} /// in {@code altsets}.
* in {@code altsets}. ///
* /// - parameter altsets: a collection of alternative subsets
* @param altsets a collection of alternative subsets /// - returns: the set of represented alternatives in {@code altsets}
* @return the set of represented alternatives in {@code altsets}
*/
public static func getAlts(_ altsets: Array<BitSet>) -> BitSet { public static func getAlts(_ altsets: Array<BitSet>) -> BitSet {
let all: BitSet = BitSet() let all: BitSet = BitSet()
for alts: BitSet in altsets { for alts: BitSet in altsets {
@ -468,36 +444,32 @@ public enum PredictionMode {
return all return all
} }
/** Get union of all alts from configs. @since 4.5.1 */ /// Get union of all alts from configs. @since 4.5.1
public static func getAlts(_ configs: ATNConfigSet) throws -> BitSet { public static func getAlts(_ configs: ATNConfigSet) throws -> BitSet {
return try configs.getAltBitSet() return try configs.getAltBitSet()
} }
/** /// This function gets the conflicting alt subsets from a configuration set.
* This function gets the conflicting alt subsets from a configuration set. /// For each configuration {@code c} in {@code configs}:
* For each configuration {@code c} in {@code configs}: ///
* /// <pre>
* <pre> /// map[c] U= c.{@link org.antlr.v4.runtime.atn.ATNConfig#alt alt} # map hash/equals uses s and x, not
* map[c] U= c.{@link org.antlr.v4.runtime.atn.ATNConfig#alt alt} # map hash/equals uses s and x, not /// alt and not pred
* alt and not pred /// </pre>
* </pre>
*/
public static func getConflictingAltSubsets(_ configs: ATNConfigSet) throws -> Array<BitSet> { public static func getConflictingAltSubsets(_ configs: ATNConfigSet) throws -> Array<BitSet> {
return try configs.getConflictingAltSubsets() return try configs.getConflictingAltSubsets()
} }
/** /// Get a map from state to alt subset from a configuration set. For each
* Get a map from state to alt subset from a configuration set. For each /// configuration {@code c} in {@code configs}:
* configuration {@code c} in {@code configs}: ///
* /// <pre>
* <pre> /// map[c.{@link org.antlr.v4.runtime.atn.ATNConfig#state state}] U= c.{@link org.antlr.v4.runtime.atn.ATNConfig#alt alt}
* map[c.{@link org.antlr.v4.runtime.atn.ATNConfig#state state}] U= c.{@link org.antlr.v4.runtime.atn.ATNConfig#alt alt} /// </pre>
* </pre>
*/
public static func getStateToAltMap(_ configs: ATNConfigSet) throws -> HashMap<ATNState, BitSet> { public static func getStateToAltMap(_ configs: ATNConfigSet) throws -> HashMap<ATNState, BitSet> {
return try configs.getStateToAltMap() return try configs.getStateToAltMap()

View File

@ -1,12 +1,9 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** /// - 4.3
* @since 4.3
*/
import Foundation import Foundation
@ -20,17 +17,16 @@ public class ProfilingATNSimulator: ParserATNSimulator {
internal var currentDecision: Int = 0 internal var currentDecision: Int = 0
internal var currentState: DFAState? internal var currentState: DFAState?
/** At the point of LL failover, we record how SLL would resolve the conflict so that /// At the point of LL failover, we record how SLL would resolve the conflict so that
* we can determine whether or not a decision / input pair is context-sensitive. /// we can determine whether or not a decision / input pair is context-sensitive.
* If LL gives a different result than SLL's predicted alternative, we have a /// If LL gives a different result than SLL's predicted alternative, we have a
* context sensitivity for sure. The converse is not necessarily true, however. /// context sensitivity for sure. The converse is not necessarily true, however.
* It's possible that after conflict resolution chooses minimum alternatives, /// It's possible that after conflict resolution chooses minimum alternatives,
* SLL could get the same answer as LL. Regardless of whether or not the result indicates /// SLL could get the same answer as LL. Regardless of whether or not the result indicates
* an ambiguity, it is not treated as a context sensitivity because LL prediction /// an ambiguity, it is not treated as a context sensitivity because LL prediction
* was not required in order to produce a correct prediction for this decision and input sequence. /// was not required in order to produce a correct prediction for this decision and input sequence.
* It may in fact still be a context sensitivity but we don't know by looking at the /// It may in fact still be a context sensitivity but we don't know by looking at the
* minimum alternatives for the current input. /// minimum alternatives for the current input.
*/
internal var conflictingAltResolvedBySLL: Int = 0 internal var conflictingAltResolvedBySLL: Int = 0
public init(_ parser: Parser) { public init(_ parser: Parser) {

View File

@ -1,7 +1,6 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
public final class RangeTransition: Transition, CustomStringConvertible { public final class RangeTransition: Transition, CustomStringConvertible {

View File

@ -1,7 +1,6 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
public final class RuleStartState: ATNState { public final class RuleStartState: ATNState {

View File

@ -1,15 +1,13 @@
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that /// Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root. /// can be found in the LICENSE.txt file in the project root.
*/
/** The last node in the ATN for a rule, unless that rule is the start symbol. /// The last node in the ATN for a rule, unless that rule is the start symbol.
* In that case, there is one transition to EOF. Later, we might encode /// In that case, there is one transition to EOF. Later, we might encode
* references to all calls to this rule to compute FOLLOW sets for /// references to all calls to this rule to compute FOLLOW sets for
* error handling. /// error handling.
*/
public final class RuleStopState: ATNState { public final class RuleStopState: ATNState {

Some files were not shown because too many files have changed in this diff Show More