From 139225f76c29776bbac1c9f458ca1f57bedb1973 Mon Sep 17 00:00:00 2001 From: Hanzhou Shi Date: Sun, 15 Jan 2017 21:54:50 -0800 Subject: [PATCH] convert documentation to Swift style --- .../Contents.swift | 23 - .../Resources/Hello.g4 | 5 - .../Resources/TestHello.txt | 1 - .../Sources/Autogen/Hello.tokens | 4 - .../Sources/Autogen/HelloBaseListener.swift | 50 - .../Sources/Autogen/HelloBaseVisitor.swift | 20 - .../Sources/Autogen/HelloLexer.swift | 84 - .../Sources/Autogen/HelloLexer.tokens | 4 - .../Sources/Autogen/HelloLexerATN.swift | 3 - .../Sources/Autogen/HelloListener.swift | 21 - .../Sources/Autogen/HelloParser.swift | 130 -- .../Sources/Autogen/HelloParserATN.swift | 3 - .../Sources/Autogen/HelloVisitor.swift | 22 - .../Sources/HelloWalker.swift | 18 - .../contents.xcplayground | 4 - .../contents.xcworkspacedata | 7 - .../contents.xcworkspacedata | 3 - .../Sources/Antlr4/ANTLRErrorListener.swift | 269 ++- .../Sources/Antlr4/ANTLRErrorStrategy.swift | 179 +- .../Sources/Antlr4/ANTLRFileStream.swift | 13 +- .../Sources/Antlr4/ANTLRInputStream.swift | 176 +- .../Sources/Antlr4/BailErrorStrategy.swift | 77 +- .../Sources/Antlr4/BaseErrorListener.swift | 19 +- .../Sources/Antlr4/BufferedTokenStream.swift | 196 +- runtime/Swift/Sources/Antlr4/CharStream.swift | 39 +- .../Swift/Sources/Antlr4/CommonToken.swift | 139 +- .../Sources/Antlr4/CommonTokenFactory.swift | 85 +- .../Sources/Antlr4/CommonTokenStream.swift | 95 +- .../Sources/Antlr4/ConsoleErrorListener.swift | 39 +- .../Sources/Antlr4/DefaultErrorStrategy.swift | 743 ++++---- .../Antlr4/DiagnosticErrorListener.swift | 89 +- .../Antlr4/FailedPredicateException.swift | 16 +- .../Antlr4/InputMismatchException.swift | 12 +- runtime/Swift/Sources/Antlr4/IntStream.swift | 357 ++-- .../Antlr4/InterpreterRuleContext.swift | 52 +- runtime/Swift/Sources/Antlr4/Lexer.swift | 131 +- .../Sources/Antlr4/LexerInterpreter.swift | 7 +- .../Antlr4/LexerNoViableAltException.swift | 11 +- .../Sources/Antlr4/ListTokenSource.swift | 119 +- runtime/Swift/Sources/Antlr4/atn/ATN.swift | 105 +- .../Swift/Sources/Antlr4/atn/ATNConfig.swift | 104 +- .../Sources/Antlr4/atn/ATNConfigSet.swift | 127 +- .../atn/ATNDeserializationOptions.swift | 13 +- .../Sources/Antlr4/atn/ATNDeserializer.swift | 84 +- .../Sources/Antlr4/atn/ATNSimulator.swift | 114 +- .../Swift/Sources/Antlr4/atn/ATNState.swift | 131 +- .../Swift/Sources/Antlr4/atn/ATNType.swift | 15 +- .../atn/AbstractPredicateTransition.swift | 13 +- .../Sources/Antlr4/atn/ActionTransition.swift | 7 +- .../Sources/Antlr4/atn/AmbiguityInfo.swift | 95 +- .../Antlr4/atn/ArrayPredictionContext.swift | 19 +- .../Sources/Antlr4/atn/AtomTransition.swift | 11 +- .../Antlr4/atn/BasicBlockStartState.swift | 13 +- .../Swift/Sources/Antlr4/atn/BasicState.swift | 13 +- .../Sources/Antlr4/atn/BlockEndState.swift | 9 +- .../Sources/Antlr4/atn/BlockStartState.swift | 9 +- .../Antlr4/atn/ContextSensitivityInfo.swift | 63 +- .../Antlr4/atn/DecisionEventInfo.swift | 71 +- .../Sources/Antlr4/atn/DecisionInfo.swift | 307 ++- .../Sources/Antlr4/atn/DecisionState.swift | 7 +- .../Sources/Antlr4/atn/DefaultATNConfig.swift | 7 +- .../Antlr4/atn/EmptyPredictionContext.swift | 7 +- .../Antlr4/atn/EpsilonTransition.swift | 21 +- .../Swift/Sources/Antlr4/atn/ErrorInfo.swift | 53 +- .../Sources/Antlr4/atn/LL1Analyzer.swift | 152 +- .../Sources/Antlr4/atn/LexerATNConfig.swift | 17 +- .../Antlr4/atn/LexerATNSimulator.swift | 233 ++- .../Sources/Antlr4/atn/LexerAction.swift | 69 +- .../Antlr4/atn/LexerActionExecutor.swift | 165 +- .../Sources/Antlr4/atn/LexerActionType.swift | 17 +- .../Antlr4/atn/LexerChannelAction.swift | 55 +- .../Antlr4/atn/LexerCustomAction.swift | 101 +- .../Antlr4/atn/LexerIndexedCustomAction.swift | 103 +- .../Sources/Antlr4/atn/LexerModeAction.swift | 55 +- .../Sources/Antlr4/atn/LexerMoreAction.swift | 51 +- .../Antlr4/atn/LexerPopModeAction.swift | 51 +- .../Antlr4/atn/LexerPushModeAction.swift | 55 +- .../Sources/Antlr4/atn/LexerSkipAction.swift | 51 +- .../Sources/Antlr4/atn/LexerTypeAction.swift | 53 +- .../Antlr4/atn/LookaheadEventInfo.swift | 45 +- .../Sources/Antlr4/atn/LookupATNConfig.swift | 7 +- .../Sources/Antlr4/atn/LookupDictionary.swift | 7 +- .../Sources/Antlr4/atn/LoopEndState.swift | 9 +- .../Sources/Antlr4/atn/NotSetTransition.swift | 7 +- .../Sources/Antlr4/atn/OrderedATNConfig.swift | 7 +- .../Antlr4/atn/OrderedATNConfigSet.swift | 13 +- .../Swift/Sources/Antlr4/atn/ParseInfo.swift | 105 +- .../Antlr4/atn/ParserATNSimulator.swift | 1644 ++++++++--------- .../Antlr4/atn/PlusBlockStartState.swift | 16 +- .../Antlr4/atn/PlusLoopbackState.swift | 12 +- .../atn/PrecedencePredicateTransition.swift | 13 +- .../Antlr4/atn/PredicateEvalInfo.swift | 81 +- .../Antlr4/atn/PredicateTransition.swift | 18 +- .../Antlr4/atn/PredictionContext.swift | 236 ++- .../Antlr4/atn/PredictionContextCache.swift | 21 +- .../Sources/Antlr4/atn/PredictionMode.swift | 634 +++---- .../Antlr4/atn/ProfilingATNSimulator.swift | 32 +- .../Sources/Antlr4/atn/RangeTransition.swift | 7 +- .../Sources/Antlr4/atn/RuleStartState.swift | 7 +- .../Sources/Antlr4/atn/RuleStopState.swift | 16 +- .../Sources/Antlr4/atn/RuleTransition.swift | 19 +- .../Sources/Antlr4/atn/SemanticContext.swift | 150 +- .../Sources/Antlr4/atn/SetTransition.swift | 9 +- .../atn/SingletonPredictionContext.swift | 7 +- .../Antlr4/atn/StarBlockStartState.swift | 9 +- .../Antlr4/atn/StarLoopEntryState.swift | 25 +- .../Antlr4/atn/StarLoopbackState.swift | 7 +- .../Sources/Antlr4/atn/TokensStartState.swift | 9 +- .../Swift/Sources/Antlr4/atn/Transition.swift | 48 +- .../Antlr4/atn/WildcardTransition.swift | 7 +- runtime/Swift/Sources/Antlr4/dfa/DFA.swift | 104 +- .../Sources/Antlr4/dfa/DFASerializer.swift | 13 +- .../Swift/Sources/Antlr4/dfa/DFAState.swift | 130 +- .../Antlr4/dfa/LexerDFASerializer.swift | 7 +- .../Swift/Sources/Antlr4/misc/ArrayList.swift | 7 +- .../Sources/Antlr4/misc/ArrayWrapper.swift | 7 +- .../Swift/Sources/Antlr4/misc/BitSet.swift | 713 ++++--- .../Sources/Antlr4/misc/DoubleKeyMap.swift | 14 +- .../Swift/Sources/Antlr4/misc/HashMap.swift | 197 +- .../Swift/Sources/Antlr4/misc/IntSet.swift | 229 +-- .../Swift/Sources/Antlr4/misc/Interval.swift | 52 +- .../Sources/Antlr4/misc/IntervalSet.swift | 162 +- .../Swift/Sources/Antlr4/misc/MultiMap.swift | 7 +- .../Antlr4/misc/exception/ANTLRError.swift | 7 +- .../misc/exception/ANTLRException.swift | 7 +- .../misc/extension/ArrayExtension.swift | 54 +- .../misc/extension/CharacterExtension.swift | 7 +- .../misc/extension/IntStreamExtension.swift | 19 +- .../misc/extension/NSUUIDExtension.swift | 7 +- .../misc/extension/StirngExtension.swift | 7 +- .../misc/extension/TokenExtension.swift | 44 +- .../Swift/Tests/Antlr4Tests/Antlr4Tests.swift | 7 +- .../Swift/Tests/Antlr4Tests/BaseTest.swift | 40 - .../Swift/Tests/Antlr4Tests/HashMapTest.swift | 68 - 134 files changed, 4732 insertions(+), 6315 deletions(-) delete mode 100644 runtime/Swift/Antlr4 playground.playground/Contents.swift delete mode 100644 runtime/Swift/Antlr4 playground.playground/Resources/Hello.g4 delete mode 100644 runtime/Swift/Antlr4 playground.playground/Resources/TestHello.txt delete mode 100644 runtime/Swift/Antlr4 playground.playground/Sources/Autogen/Hello.tokens delete mode 100644 runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloBaseListener.swift delete mode 100644 runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloBaseVisitor.swift delete mode 100644 runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloLexer.swift delete mode 100644 runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloLexer.tokens delete mode 100644 runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloLexerATN.swift delete mode 100644 runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloListener.swift delete mode 100644 runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloParser.swift delete mode 100644 runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloParserATN.swift delete mode 100644 runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloVisitor.swift delete mode 100644 runtime/Swift/Antlr4 playground.playground/Sources/HelloWalker.swift delete mode 100644 runtime/Swift/Antlr4 playground.playground/contents.xcplayground delete mode 100644 runtime/Swift/Antlr4 playground.playground/playground.xcworkspace/contents.xcworkspacedata delete mode 100644 runtime/Swift/Tests/Antlr4Tests/BaseTest.swift delete mode 100644 runtime/Swift/Tests/Antlr4Tests/HashMapTest.swift diff --git a/runtime/Swift/Antlr4 playground.playground/Contents.swift b/runtime/Swift/Antlr4 playground.playground/Contents.swift deleted file mode 100644 index 524c83fac..000000000 --- a/runtime/Swift/Antlr4 playground.playground/Contents.swift +++ /dev/null @@ -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)") -} diff --git a/runtime/Swift/Antlr4 playground.playground/Resources/Hello.g4 b/runtime/Swift/Antlr4 playground.playground/Resources/Hello.g4 deleted file mode 100644 index bd86f31ab..000000000 --- a/runtime/Swift/Antlr4 playground.playground/Resources/Hello.g4 +++ /dev/null @@ -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 \ No newline at end of file diff --git a/runtime/Swift/Antlr4 playground.playground/Resources/TestHello.txt b/runtime/Swift/Antlr4 playground.playground/Resources/TestHello.txt deleted file mode 100644 index 95d09f2b1..000000000 --- a/runtime/Swift/Antlr4 playground.playground/Resources/TestHello.txt +++ /dev/null @@ -1 +0,0 @@ -hello world \ No newline at end of file diff --git a/runtime/Swift/Antlr4 playground.playground/Sources/Autogen/Hello.tokens b/runtime/Swift/Antlr4 playground.playground/Sources/Autogen/Hello.tokens deleted file mode 100644 index 090a996ac..000000000 --- a/runtime/Swift/Antlr4 playground.playground/Sources/Autogen/Hello.tokens +++ /dev/null @@ -1,4 +0,0 @@ -T__0=1 -ID=2 -WS=3 -'hello'=1 diff --git a/runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloBaseListener.swift b/runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloBaseListener.swift deleted file mode 100644 index 639608796..000000000 --- a/runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloBaseListener.swift +++ /dev/null @@ -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} - * - *

The default implementation does nothing.

- */ - open func enterR(_ ctx: HelloParser.RContext) { } - /** - * {@inheritDoc} - * - *

The default implementation does nothing.

- */ - open func exitR(_ ctx: HelloParser.RContext) { } - - /** - * {@inheritDoc} - * - *

The default implementation does nothing.

- */ - open func enterEveryRule(_ ctx: ParserRuleContext) { } - /** - * {@inheritDoc} - * - *

The default implementation does nothing.

- */ - open func exitEveryRule(_ ctx: ParserRuleContext) { } - /** - * {@inheritDoc} - * - *

The default implementation does nothing.

- */ - open func visitTerminal(_ node: TerminalNode) { } - /** - * {@inheritDoc} - * - *

The default implementation does nothing.

- */ - open func visitErrorNode(_ node: ErrorNode) { } -} \ No newline at end of file diff --git a/runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloBaseVisitor.swift b/runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloBaseVisitor.swift deleted file mode 100644 index 2047aef18..000000000 --- a/runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloBaseVisitor.swift +++ /dev/null @@ -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 The return type of the visit operation. Use {@link Void} for - * operations with no return type. - */ -open class HelloBaseVisitor: AbstractParseTreeVisitor { - /** - * {@inheritDoc} - * - *

The default implementation returns the result of calling - * {@link #visitChildren} on {@code ctx}.

- */ - open func visitR(_ ctx: HelloParser.RContext) -> T? { return visitChildren(ctx) } -} \ No newline at end of file diff --git a/runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloLexer.swift b/runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloLexer.swift deleted file mode 100644 index f622fa3b2..000000000 --- a/runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloLexer.swift +++ /dev/null @@ -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.. [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) -} \ No newline at end of file diff --git a/runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloLexer.tokens b/runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloLexer.tokens deleted file mode 100644 index 090a996ac..000000000 --- a/runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloLexer.tokens +++ /dev/null @@ -1,4 +0,0 @@ -T__0=1 -ID=2 -WS=3 -'hello'=1 diff --git a/runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloLexerATN.swift b/runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloLexerATN.swift deleted file mode 100644 index b9afb3575..000000000 --- a/runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloLexerATN.swift +++ /dev/null @@ -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}]}" -} \ No newline at end of file diff --git a/runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloListener.swift b/runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloListener.swift deleted file mode 100644 index eaac711a4..000000000 --- a/runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloListener.swift +++ /dev/null @@ -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) -} \ No newline at end of file diff --git a/runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloParser.swift b/runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloParser.swift deleted file mode 100644 index 666c46372..000000000 --- a/runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloParser.swift +++ /dev/null @@ -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.. [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(_ visitor: ParseTreeVisitor) -> T? { - if visitor is HelloVisitor { - return (visitor as! HelloVisitor).visitR(self) - }else if visitor is HelloBaseVisitor { - return (visitor as! HelloBaseVisitor).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) -} \ No newline at end of file diff --git a/runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloParserATN.swift b/runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloParserATN.swift deleted file mode 100644 index 963aa6ded..000000000 --- a/runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloParserATN.swift +++ /dev/null @@ -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\":[]}" -} \ No newline at end of file diff --git a/runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloVisitor.swift b/runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloVisitor.swift deleted file mode 100644 index ed3f13a9f..000000000 --- a/runtime/Swift/Antlr4 playground.playground/Sources/Autogen/HelloVisitor.swift +++ /dev/null @@ -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 The return type of the visit operation. Use {@link Void} for - * operations with no return type. - */ -open class HelloVisitor: ParseTreeVisitor { - /** - * 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") - } - -} \ No newline at end of file diff --git a/runtime/Swift/Antlr4 playground.playground/Sources/HelloWalker.swift b/runtime/Swift/Antlr4 playground.playground/Sources/HelloWalker.swift deleted file mode 100644 index 128127494..000000000 --- a/runtime/Swift/Antlr4 playground.playground/Sources/HelloWalker.swift +++ /dev/null @@ -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() ?? "" - } -} diff --git a/runtime/Swift/Antlr4 playground.playground/contents.xcplayground b/runtime/Swift/Antlr4 playground.playground/contents.xcplayground deleted file mode 100644 index 63b6dd8df..000000000 --- a/runtime/Swift/Antlr4 playground.playground/contents.xcplayground +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/runtime/Swift/Antlr4 playground.playground/playground.xcworkspace/contents.xcworkspacedata b/runtime/Swift/Antlr4 playground.playground/playground.xcworkspace/contents.xcworkspacedata deleted file mode 100644 index 919434a62..000000000 --- a/runtime/Swift/Antlr4 playground.playground/playground.xcworkspace/contents.xcworkspacedata +++ /dev/null @@ -1,7 +0,0 @@ - - - - - diff --git a/runtime/Swift/Antlr4.xcworkspace/contents.xcworkspacedata b/runtime/Swift/Antlr4.xcworkspace/contents.xcworkspacedata index 8be4a847c..6584c73ac 100644 --- a/runtime/Swift/Antlr4.xcworkspace/contents.xcworkspacedata +++ b/runtime/Swift/Antlr4.xcworkspace/contents.xcworkspacedata @@ -4,7 +4,4 @@ - - diff --git a/runtime/Swift/Sources/Antlr4/ANTLRErrorListener.swift b/runtime/Swift/Sources/Antlr4/ANTLRErrorListener.swift index a2675be05..193f91bb2 100644 --- a/runtime/Swift/Sources/Antlr4/ANTLRErrorListener.swift +++ b/runtime/Swift/Sources/Antlr4/ANTLRErrorListener.swift @@ -1,43 +1,40 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ -/** How to emit recognition errors. */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. +/// How to emit recognition errors. public protocol ANTLRErrorListener: class { - /** - * 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} - * specifies how to recover from syntax errors and how to compute error - * 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. - * - *

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 - * in-line, without returning from the surrounding rule (via the single - * token insertion and deletion mechanism).

- * - * @param recognizer - * What parser got the error. From this - * object, you can access the context as well - * as the input stream. - * @param offendingSymbol - * The offending token in the input token - * stream, unless recognizer is a lexer (then it's null). If - * no viable alternative error, {@code e} has token at which we - * started production for the decision. - * @param line - * The line number in the input where the error occurred. - * @param charPositionInLine - * The character position within that line where the error occurred. - * @param msg - * The message to emit. - * @param e - * The exception generated by the parser that led to - * the reporting of an error. It is null in the case where - * the parser was able to recover in line without exiting the - * surrounding rule. - */ + /// 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} + /// specifies how to recover from syntax errors and how to compute error + /// 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. + /// + ///

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 + /// in-line, without returning from the surrounding rule (via the single + /// token insertion and deletion mechanism).

+ /// + /// - parameter recognizer: + /// What parser got the error. From this + /// object, you can access the context as well + /// as the input stream. + /// - parameter offendingSymbol: + /// The offending token in the input token + /// stream, unless recognizer is a lexer (then it's null). If + /// no viable alternative error, {@code e} has token at which we + /// started production for the decision. + /// - parameter line: + /// The line number in the input where the error occurred. + /// - parameter charPositionInLine: + /// The character position within that line where the error occurred. + /// - parameter msg: + /// The message to emit. + /// - parameter e: + /// The exception generated by the parser that led to + /// the reporting of an error. It is null in the case where + /// the parser was able to recover in line without exiting the + /// surrounding rule. func syntaxError(_ recognizer: Recognizer, _ offendingSymbol: AnyObject?, _ line: Int, @@ -46,46 +43,44 @@ public protocol ANTLRErrorListener: class { _ e: AnyObject?// RecognitionException? ) - /** - * This method is called by the parser when a full-context prediction - * results in an ambiguity. - * - *

Each full-context prediction which does not result in a syntax error - * will call either {@link #reportContextSensitivity} or - * {@link #reportAmbiguity}.

- * - *

When {@code ambigAlts} is not null, it contains the set of potentially - * viable alternatives identified by the prediction algorithm. When - * {@code ambigAlts} is null, use {@link org.antlr.v4.runtime.atn.ATNConfigSet#getAlts} to obtain the - * represented alternatives from the {@code configs} argument.

- * - *

When {@code exact} is {@code true}, all of the potentially - * viable alternatives are truly viable, i.e. this is reporting an exact - * ambiguity. When {@code exact} is {@code false}, at least two of - * the potentially viable alternatives are viable for the current input, but - * the prediction algorithm terminated as soon as it determined that at - * least the minimum potentially viable alternative is truly - * viable.

- * - *

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 - * {@code exact} will always be {@code true}.

- * - *

This method is not used by lexers.

- * - * @param recognizer the parser instance - * @param dfa the DFA for the current decision - * @param startIndex the input index where the decision started - * @param stopIndex the input input where the ambiguity was identified - * @param exact {@code true} if the ambiguity is exactly known, otherwise - * {@code false}. This is always {@code true} when - * {@link org.antlr.v4.runtime.atn.PredictionMode#LL_EXACT_AMBIG_DETECTION} is used. - * @param ambigAlts the potentially ambiguous alternatives, or {@code null} - * to indicate that the potentially ambiguous alternatives are the complete - * set of represented alternatives in {@code configs} - * @param configs the ATN configuration set where the ambiguity was - * identified - */ + /// This method is called by the parser when a full-context prediction + /// results in an ambiguity. + /// + ///

Each full-context prediction which does not result in a syntax error + /// will call either {@link #reportContextSensitivity} or + /// {@link #reportAmbiguity}.

+ /// + ///

When {@code ambigAlts} is not null, it contains the set of potentially + /// viable alternatives identified by the prediction algorithm. When + /// {@code ambigAlts} is null, use {@link org.antlr.v4.runtime.atn.ATNConfigSet#getAlts} to obtain the + /// represented alternatives from the {@code configs} argument.

+ /// + ///

When {@code exact} is {@code true}, all of the potentially + /// viable alternatives are truly viable, i.e. this is reporting an exact + /// ambiguity. When {@code exact} is {@code false}, at least two of + /// the potentially viable alternatives are viable for the current input, but + /// the prediction algorithm terminated as soon as it determined that at + /// least the minimum potentially viable alternative is truly + /// viable.

+ /// + ///

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 + /// {@code exact} will always be {@code true}.

+ /// + ///

This method is not used by lexers.

+ /// + /// - parameter recognizer: the parser instance + /// - parameter dfa: the DFA for the current decision + /// - parameter startIndex: the input index where the decision started + /// - parameter stopIndex: the input input where the ambiguity was identified + /// - parameter exact: {@code true} if the ambiguity is exactly known, otherwise + /// {@code false}. This is always {@code true} when + /// {@link org.antlr.v4.runtime.atn.PredictionMode#LL_EXACT_AMBIG_DETECTION} is used. + /// - parameter ambigAlts: the potentially ambiguous alternatives, or {@code null} + /// to indicate that the potentially ambiguous alternatives are the complete + /// set of represented alternatives in {@code configs} + /// - parameter configs: the ATN configuration set where the ambiguity was + /// identified func reportAmbiguity(_ recognizer: Parser, _ dfa: DFA, _ startIndex: Int, @@ -94,29 +89,27 @@ public protocol ANTLRErrorListener: class { _ ambigAlts: BitSet, _ configs: ATNConfigSet) throws - /** - * 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. - * - *

If one or more configurations in {@code configs} contains a semantic - * predicate, the predicates are evaluated before this method is called. The - * subset of alternatives which are still viable after predicates are - * evaluated is reported in {@code conflictingAlts}.

- * - *

This method is not used by lexers.

- * - * @param recognizer the parser instance - * @param dfa the DFA for the current decision - * @param startIndex the input index where the decision started - * @param stopIndex the input index where the SLL conflict occurred - * @param conflictingAlts The specific conflicting alternatives. If this is - * {@code null}, the conflicting alternatives are all alternatives - * represented in {@code configs}. At the moment, conflictingAlts is non-null - * (for the reference implementation, but Sam's optimized version can see this - * as null). - * @param configs the ATN configuration set where the SLL conflict was - * detected - */ + /// 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. + /// + ///

If one or more configurations in {@code configs} contains a semantic + /// predicate, the predicates are evaluated before this method is called. The + /// subset of alternatives which are still viable after predicates are + /// evaluated is reported in {@code conflictingAlts}.

+ /// + ///

This method is not used by lexers.

+ /// + /// - parameter recognizer: the parser instance + /// - parameter dfa: the DFA for the current decision + /// - parameter startIndex: the input index where the decision started + /// - parameter stopIndex: the input index where the SLL conflict occurred + /// - parameter conflictingAlts: The specific conflicting alternatives. If this is + /// {@code null}, the conflicting alternatives are all alternatives + /// represented in {@code configs}. At the moment, conflictingAlts is non-null + /// (for the reference implementation, but Sam's optimized version can see this + /// as null). + /// - parameter configs: the ATN configuration set where the SLL conflict was + /// detected func reportAttemptingFullContext(_ recognizer: Parser, _ dfa: DFA, _ startIndex: Int, @@ -124,44 +117,42 @@ public protocol ANTLRErrorListener: class { _ conflictingAlts: BitSet?, _ configs: ATNConfigSet) throws - /** - * This method is called by the parser when a full-context prediction has a - * unique result. - * - *

Each full-context prediction which does not result in a syntax error - * will call either {@link #reportContextSensitivity} or - * {@link #reportAmbiguity}.

- * - *

For prediction implementations that only evaluate full-context - * predictions when an SLL conflict is found (including the default - * {@link org.antlr.v4.runtime.atn.ParserATNSimulator} implementation), this method reports cases - * where SLL conflicts were resolved to unique full-context predictions, - * i.e. the decision was context-sensitive. This report does not necessarily - * indicate a problem, and it may appear even in completely unambiguous - * grammars.

- * - *

{@code configs} may have more than one represented alternative if the - * full-context prediction algorithm does not evaluate predicates before - * beginning the full-context prediction. In all cases, the final prediction - * is passed as the {@code prediction} argument.

- * - *

Note that the definition of "context sensitivity" in this method - * 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 - * parsing produced a unique result, whether or not that unique result - * matches the minimum alternative in the SLL conflicting set.

- * - *

This method is not used by lexers.

- * - * @param recognizer the parser instance - * @param dfa the DFA for the current decision - * @param startIndex the input index where the decision started - * @param stopIndex the input index where the context sensitivity was - * finally determined - * @param prediction the unambiguous result of the full-context prediction - * @param configs the ATN configuration set where the unambiguous prediction - * was determined - */ + /// This method is called by the parser when a full-context prediction has a + /// unique result. + /// + ///

Each full-context prediction which does not result in a syntax error + /// will call either {@link #reportContextSensitivity} or + /// {@link #reportAmbiguity}.

+ /// + ///

For prediction implementations that only evaluate full-context + /// predictions when an SLL conflict is found (including the default + /// {@link org.antlr.v4.runtime.atn.ParserATNSimulator} implementation), this method reports cases + /// where SLL conflicts were resolved to unique full-context predictions, + /// i.e. the decision was context-sensitive. This report does not necessarily + /// indicate a problem, and it may appear even in completely unambiguous + /// grammars.

+ /// + ///

{@code configs} may have more than one represented alternative if the + /// full-context prediction algorithm does not evaluate predicates before + /// beginning the full-context prediction. In all cases, the final prediction + /// is passed as the {@code prediction} argument.

+ /// + ///

Note that the definition of "context sensitivity" in this method + /// 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 + /// parsing produced a unique result, whether or not that unique result + /// matches the minimum alternative in the SLL conflicting set.

+ /// + ///

This method is not used by lexers.

+ /// + /// - parameter recognizer: the parser instance + /// - parameter dfa: the DFA for the current decision + /// - parameter startIndex: the input index where the decision started + /// - parameter stopIndex: the input index where the context sensitivity was + /// finally determined + /// - parameter prediction: the unambiguous result of the full-context prediction + /// - parameter configs: the ATN configuration set where the unambiguous prediction + /// was determined func reportContextSensitivity(_ recognizer: Parser, _ dfa: DFA, _ startIndex: Int, diff --git a/runtime/Swift/Sources/Antlr4/ANTLRErrorStrategy.swift b/runtime/Swift/Sources/Antlr4/ANTLRErrorStrategy.swift index dec361c79..ffa726461 100644 --- a/runtime/Swift/Sources/Antlr4/ANTLRErrorStrategy.swift +++ b/runtime/Swift/Sources/Antlr4/ANTLRErrorStrategy.swift @@ -1,115 +1,98 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ -/** - * The interface for defining strategies to deal with syntax errors encountered - * during a parse by ANTLR-generated parsers. We distinguish between three - * different kinds of errors: - * - *
    - *
  • The parser could not figure out which path to take in the ATN (none of - * the available alternatives could possibly match)
  • - *
  • The current input does not match what we were looking for
  • - *
  • A predicate evaluated to false
  • - *
- * - * Implementations of this interface report syntax errors by calling - * {@link org.antlr.v4.runtime.Parser#notifyErrorListeners}. - * - *

TODO: what to do about lexers

- */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. +/// The interface for defining strategies to deal with syntax errors encountered +/// during a parse by ANTLR-generated parsers. We distinguish between three +/// different kinds of errors: +/// +///
    +///
  • The parser could not figure out which path to take in the ATN (none of +/// the available alternatives could possibly match)
  • +///
  • The current input does not match what we were looking for
  • +///
  • A predicate evaluated to false
  • +///
+/// +/// Implementations of this interface report syntax errors by calling +/// {@link org.antlr.v4.runtime.Parser#notifyErrorListeners}. +/// +///

TODO: what to do about lexers

public protocol ANTLRErrorStrategy { - /** - * Reset the error handler state for the specified {@code recognizer}. - * @param recognizer the parser instance - */ + /// Reset the error handler state for the specified {@code recognizer}. + /// - parameter recognizer: the parser instance func reset(_ recognizer: Parser) - /** - * 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 - * strategy successfully recovers from the match failure, this method - * returns the {@link org.antlr.v4.runtime.Token} instance which should be treated as the - * successful result of the match. - * - *

This method handles the consumption of any tokens - the caller should - * not call {@link org.antlr.v4.runtime.Parser#consume} after a successful recovery.

- * - *

Note that the calling code will not report an error if this method - * returns successfully. The error strategy implementation is responsible - * for calling {@link org.antlr.v4.runtime.Parser#notifyErrorListeners} as appropriate.

- * - * @param recognizer the parser instance - * @throws org.antlr.v4.runtime.RecognitionException if the error strategy was not able to - * recover from the unexpected input symbol - */ + /// 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 + /// strategy successfully recovers from the match failure, this method + /// returns the {@link org.antlr.v4.runtime.Token} instance which should be treated as the + /// successful result of the match. + /// + ///

This method handles the consumption of any tokens - the caller should + /// not call {@link org.antlr.v4.runtime.Parser#consume} after a successful recovery.

+ /// + ///

Note that the calling code will not report an error if this method + /// returns successfully. The error strategy implementation is responsible + /// for calling {@link org.antlr.v4.runtime.Parser#notifyErrorListeners} as appropriate.

+ /// + /// - parameter recognizer: the parser instance + /// - org.antlr.v4.runtime.RecognitionException if the error strategy was not able to + /// recover from the unexpected input symbol @discardableResult func recoverInline(_ recognizer: Parser) throws -> Token // RecognitionException; - /** - * This method is called to recover from exception {@code e}. This method is - * called after {@link #reportError} by the default exception handler - * generated for a rule method. - * - * @see #reportError - * - * @param recognizer the parser instance - * @param e the recognition exception to recover from - * @throws org.antlr.v4.runtime.RecognitionException if the error strategy could not recover from - * the recognition exception - */ + /// This method is called to recover from exception {@code e}. This method is + /// called after {@link #reportError} by the default exception handler + /// generated for a rule method. + /// + /// - seealso: #reportError + /// + /// - parameter recognizer: the parser instance + /// - parameter e: the recognition exception to recover from + /// - org.antlr.v4.runtime.RecognitionException if the error strategy could not recover from + /// the recognition exception func recover(_ recognizer: Parser, _ e: AnyObject) throws // RecognitionException; - /** - * This method provides the error handler with an opportunity to handle - * syntactic or semantic errors in the input stream before they result in a - * {@link org.antlr.v4.runtime.RecognitionException}. - * - *

The generated code currently contains calls to {@link #sync} after - * entering the decision state of a closure block ({@code (...)*} or - * {@code (...)+}).

- * - *

For an implementation based on Jim Idle's "magic sync" mechanism, see - * {@link org.antlr.v4.runtime.DefaultErrorStrategy#sync}.

- * - * @see org.antlr.v4.runtime.DefaultErrorStrategy#sync - * - * @param recognizer the parser instance - * @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 - * the parsing process - */ + /// This method provides the error handler with an opportunity to handle + /// syntactic or semantic errors in the input stream before they result in a + /// {@link org.antlr.v4.runtime.RecognitionException}. + /// + ///

The generated code currently contains calls to {@link #sync} after + /// entering the decision state of a closure block ({@code (...)*} or + /// {@code (...)+}).

+ /// + ///

For an implementation based on Jim Idle's "magic sync" mechanism, see + /// {@link org.antlr.v4.runtime.DefaultErrorStrategy#sync}.

+ /// + /// - seealso: org.antlr.v4.runtime.DefaultErrorStrategy#sync + /// + /// - parameter recognizer: the parser instance + /// - org.antlr.v4.runtime.RecognitionException if an error is detected by the error + /// strategy but cannot be automatically recovered at the current state in + /// the parsing process func sync(_ recognizer: Parser) throws // RecognitionException; - /** - * 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 - * 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#addChild(org.antlr.v4.runtime.Token)}. - * - * @param recognizer the parser instance - * @return {@code true} if the parser is currently recovering from a parse - * error, otherwise {@code false} - */ + /// 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 + /// 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#addChild(org.antlr.v4.runtime.Token)}. + /// + /// - parameter recognizer: the parser instance + /// - returns: {@code true} if the parser is currently recovering from a parse + /// error, otherwise {@code false} func inErrorRecoveryMode(_ recognizer: Parser) -> Bool - /** - * This method is called by when the parser successfully matches an input - * symbol. - * - * @param recognizer the parser instance - */ + /// This method is called by when the parser successfully matches an input + /// symbol. + /// + /// - parameter recognizer: the parser instance func reportMatch(_ recognizer: Parser) - /** - * Report any kind of {@link org.antlr.v4.runtime.RecognitionException}. This method is called by - * the default exception handler generated for a rule method. - * - * @param recognizer the parser instance - * @param e the recognition exception to report - */ + /// Report any kind of {@link org.antlr.v4.runtime.RecognitionException}. This method is called by + /// the default exception handler generated for a rule method. + /// + /// - parameter recognizer: the parser instance + /// - parameter e: the recognition exception to report func reportError(_ recognizer: Parser, _ e: AnyObject) } diff --git a/runtime/Swift/Sources/Antlr4/ANTLRFileStream.swift b/runtime/Swift/Sources/Antlr4/ANTLRFileStream.swift index b88b38e74..68463d0d1 100644 --- a/runtime/Swift/Sources/Antlr4/ANTLRFileStream.swift +++ b/runtime/Swift/Sources/Antlr4/ANTLRFileStream.swift @@ -1,11 +1,8 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ -/** - * This is an {@link org.antlr.v4.runtime.ANTLRInputStream} that is loaded from a file all at once - * when you construct the object. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. +/// 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 diff --git a/runtime/Swift/Sources/Antlr4/ANTLRInputStream.swift b/runtime/Swift/Sources/Antlr4/ANTLRInputStream.swift index cf3effe5e..bd9e4ad6f 100644 --- a/runtime/Swift/Sources/Antlr4/ANTLRInputStream.swift +++ b/runtime/Swift/Sources/Antlr4/ANTLRInputStream.swift @@ -1,29 +1,26 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ -/** - * 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 - * {@code char[]} to use. - * - *

If you need encoding, pass in stream/reader with correct encoding.

- */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. +/// 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 +/// {@code char[]} to use. +/// +///

If you need encoding, pass in stream/reader with correct encoding.

public class ANTLRInputStream: CharStream { public static let READ_BUFFER_SIZE: Int = 1024 public static let INITIAL_BUFFER_SIZE: Int = 1024 - /** The data being scanned */ + /// The data being scanned internal var data: [Character] - /** How many characters are actually in the buffer */ + /// How many characters are actually in the buffer 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 - /** What is name or source of this char stream? */ + /// What is name or source of this char stream? public var name: String? public init() { @@ -31,84 +28,81 @@ public class ANTLRInputStream: CharStream { data = [Character]() } - /** Copy data in string to a local char array */ + /// Copy data in string to a local char array public init(_ input: String) { self.data = Array(input.characters) // input.toCharArray(); 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) { self.data = data self.n = numberOfActualCharsInArray } - /* - public convenience init(_ r : Reader) throws; IOException { - self.init(r, INITIAL_BUFFER_SIZE, READ_BUFFER_SIZE); - } - - public convenience init(_ r : Reader, _ initialSize : Int) throws; IOException { - self.init(r, initialSize, READ_BUFFER_SIZE); - } - - public init(_ r : Reader, _ initialSize : Int, _ readChunkSize : Int) throws; IOException { - load(r, initialSize, readChunkSize); - } - - public convenience init(_ input : InputStream) throws; IOException { - self.init(InputStreamReader(input), INITIAL_BUFFER_SIZE); - } - - public convenience init(_ input : InputStream, _ initialSize : Int) throws; IOException { - self.init(InputStreamReader(input), initialSize); - } - - public convenience init(_ input : InputStream, _ initialSize : Int, _ readChunkSize : Int) throws; IOException { - self.init(InputStreamReader(input), initialSize, readChunkSize); - } - - public func load(r : Reader, _ size : Int, _ readChunkSize : Int) - throws; IOException - { - if ( r==nil ) { - return; - } - if ( size<=0 ) { - size = INITIAL_BUFFER_SIZE; - } - if ( readChunkSize<=0 ) { - readChunkSize = READ_BUFFER_SIZE; - } - // print("load "+size+" in chunks of "+readChunkSize); - try { - // alloc initial buffer size. - data = new char[size]; - // read all the data in chunks of readChunkSize - var numRead : Int=0; - var p : Int = 0; - do { - if ( p+readChunkSize > data.length ) { // overflow? - // print("### overflow p="+p+", data.length="+data.length); - data = Arrays.copyOf(data, data.length * 2); - } - numRead = r.read(data, p, readChunkSize); - // print("read "+numRead+" chars; p was "+p+" is now "+(p+numRead)); - p += numRead; - } while (numRead!=-1); // while not EOF - // set the actual size of the data available; - // EOF subtracted one above in p+=numRead; add one back - n = p+1; - //print("n="+n); - } - finally { - 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 - * touched. - */ + /// public convenience init(_ r : Reader) throws; IOException { + /// self.init(r, INITIAL_BUFFER_SIZE, READ_BUFFER_SIZE); + /// } + /// + /// public convenience init(_ r : Reader, _ initialSize : Int) throws; IOException { + /// self.init(r, initialSize, READ_BUFFER_SIZE); + /// } + /// + /// public init(_ r : Reader, _ initialSize : Int, _ readChunkSize : Int) throws; IOException { + /// load(r, initialSize, readChunkSize); + /// } + /// + /// public convenience init(_ input : InputStream) throws; IOException { + /// self.init(InputStreamReader(input), INITIAL_BUFFER_SIZE); + /// } + /// + /// public convenience init(_ input : InputStream, _ initialSize : Int) throws; IOException { + /// self.init(InputStreamReader(input), initialSize); + /// } + /// + /// public convenience init(_ input : InputStream, _ initialSize : Int, _ readChunkSize : Int) throws; IOException { + /// self.init(InputStreamReader(input), initialSize, readChunkSize); + /// } + /// + /// public func load(r : Reader, _ size : Int, _ readChunkSize : Int) + /// throws; IOException + /// { + /// if ( r==nil ) { + /// return; + /// } + /// if ( size<=0 ) { + /// size = INITIAL_BUFFER_SIZE; + /// } + /// if ( readChunkSize<=0 ) { + /// readChunkSize = READ_BUFFER_SIZE; + /// } + /// // print("load "+size+" in chunks of "+readChunkSize); + /// try { + /// // alloc initial buffer size. + /// data = new char[size]; + /// // read all the data in chunks of readChunkSize + /// var numRead : Int=0; + /// var p : Int = 0; + /// do { + /// if ( p+readChunkSize > data.length ) { // overflow? + /// // print("### overflow p="+p+", data.length="+data.length); + /// data = Arrays.copyOf(data, data.length * 2); + /// } + /// numRead = r.read(data, p, readChunkSize); + /// // print("read "+numRead+" chars; p was "+p+" is now "+(p+numRead)); + /// p += numRead; + /// } while (numRead!=-1); // while not EOF + /// // set the actual size of the data available; + /// // EOF subtracted one above in p+=numRead; add one back + /// n = p+1; + /// //print("n="+n); + /// } + /// finally { + /// 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 + /// touched. public func reset() { p = 0 @@ -156,10 +150,9 @@ public class ANTLRInputStream: CharStream { return LA(i) } - /** Return the current input symbol index 0..n where n indicates the - * last symbol has been read. The index is the index of char to - * be returned from LA(1). - */ + /// Return the current input symbol index 0..n where n indicates the + /// last symbol has been read. The index is the index of char to + /// be returned from LA(1). public func index() -> Int { return p } @@ -168,7 +161,7 @@ public class ANTLRInputStream: CharStream { return n } - /** mark/release do nothing; we have entire buffer */ + /// mark/release do nothing; we have entire buffer public func mark() -> Int { return -1 @@ -177,9 +170,8 @@ public class ANTLRInputStream: CharStream { public func release(_ marker: Int) { } - /** consume() ahead until p==index; can't just set p=index as we must - * update line and charPositionInLine. If we seek backwards, just set p - */ + /// consume() ahead until p==index; can't just set p=index as we must + /// update line and charPositionInLine. If we seek backwards, just set p public func seek(_ index: Int) throws { var index = index diff --git a/runtime/Swift/Sources/Antlr4/BailErrorStrategy.swift b/runtime/Swift/Sources/Antlr4/BailErrorStrategy.swift index 8e9bf83f6..6a2de1dae 100644 --- a/runtime/Swift/Sources/Antlr4/BailErrorStrategy.swift +++ b/runtime/Swift/Sources/Antlr4/BailErrorStrategy.swift @@ -1,46 +1,42 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * This implementation of {@link org.antlr.v4.runtime.ANTLRErrorStrategy} responds to syntax errors - * 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.ParserRuleContext#exception} field is set for all parse tree nodes - * that were not completed prior to encountering the error. - * - *

- * This error strategy is useful in the following scenarios.

- * - *
    - *
  • Two-stage parsing: This error strategy allows the first - * stage of two-stage parsing to immediately terminate if an error is - * encountered, and immediately fall back to the second stage. In addition to - * avoiding wasted work by attempting to recover from errors here, the empty - * implementation of {@link org.antlr.v4.runtime.BailErrorStrategy#sync} improves the performance of - * the first stage.
  • - *
  • Silent validation: When syntax errors are not being - * reported or logged, and the parse result is simply ignored if errors occur, - * the {@link org.antlr.v4.runtime.BailErrorStrategy} avoids wasting work on recovering from errors - * when the result will be ignored either way.
  • - *
- * - *

- * {@code myparser.setErrorHandler(new BailErrorStrategy());}

- * - * @see org.antlr.v4.runtime.Parser#setErrorHandler(org.antlr.v4.runtime.ANTLRErrorStrategy) - */ +/// This implementation of {@link org.antlr.v4.runtime.ANTLRErrorStrategy} responds to syntax errors +/// 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.ParserRuleContext#exception} field is set for all parse tree nodes +/// that were not completed prior to encountering the error. +/// +///

+/// This error strategy is useful in the following scenarios.

+/// +///
    +///
  • Two-stage parsing: This error strategy allows the first +/// stage of two-stage parsing to immediately terminate if an error is +/// encountered, and immediately fall back to the second stage. In addition to +/// avoiding wasted work by attempting to recover from errors here, the empty +/// implementation of {@link org.antlr.v4.runtime.BailErrorStrategy#sync} improves the performance of +/// the first stage.
  • +///
  • Silent validation: When syntax errors are not being +/// reported or logged, and the parse result is simply ignored if errors occur, +/// the {@link org.antlr.v4.runtime.BailErrorStrategy} avoids wasting work on recovering from errors +/// when the result will be ignored either way.
  • +///
+/// +///

+/// {@code myparser.setErrorHandler(new BailErrorStrategy());}

+/// +/// - seealso: org.antlr.v4.runtime.Parser#setErrorHandler(org.antlr.v4.runtime.ANTLRErrorStrategy) public class BailErrorStrategy: DefaultErrorStrategy { public override init(){} - /** 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 - * rule function catches. Use {@link Exception#getCause()} to get the - * original {@link org.antlr.v4.runtime.RecognitionException}. - */ + /// 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 + /// rule function catches. Use {@link Exception#getCause()} to get the + /// original {@link org.antlr.v4.runtime.RecognitionException}. override public func recover(_ recognizer: Parser, _ e: AnyObject) throws { var context: ParserRuleContext? = recognizer.getContext() @@ -52,9 +48,8 @@ public class BailErrorStrategy: DefaultErrorStrategy { throw ANTLRException.recognition(e: e) } - /** Make sure we don't attempt to recover inline; if the parser - * successfully recovers, it won't throw an exception. - */ + /// Make sure we don't attempt to recover inline; if the parser + /// successfully recovers, it won't throw an exception. override public func recoverInline(_ recognizer: Parser) throws -> Token { 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 public func sync(_ recognizer: Parser) { } diff --git a/runtime/Swift/Sources/Antlr4/BaseErrorListener.swift b/runtime/Swift/Sources/Antlr4/BaseErrorListener.swift index aa6fe49bb..f282d53f3 100644 --- a/runtime/Swift/Sources/Antlr4/BaseErrorListener.swift +++ b/runtime/Swift/Sources/Antlr4/BaseErrorListener.swift @@ -1,16 +1,13 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * 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 - * necessary. - * - * @author Sam Harwell - */ +/// 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 +/// necessary. +/// +/// - Sam Harwell public class BaseErrorListener: ANTLRErrorListener { diff --git a/runtime/Swift/Sources/Antlr4/BufferedTokenStream.swift b/runtime/Swift/Sources/Antlr4/BufferedTokenStream.swift index ff7ff6ddf..ed2ef43dc 100644 --- a/runtime/Swift/Sources/Antlr4/BufferedTokenStream.swift +++ b/runtime/Swift/Sources/Antlr4/BufferedTokenStream.swift @@ -1,63 +1,52 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * 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 - * access to any previous token by index. - * - *

- * 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 - * 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.CommonTokenStream}.

- */ +/// 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 +/// access to any previous token by index. +/// +///

+/// 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 +/// 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.CommonTokenStream}.

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 - /** - * 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 - * to {@code true}. - */ + /// 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 + /// to {@code true}. internal var tokens: Array = Array() // Array(100 - /** - * The index into {@link #tokens} of the current token (next token to - * {@link #consume}). {@link #tokens}{@code [}{@link #p}{@code ]} should be - * {@link #LT LT(1)}. - * - *

This field is set to -1 when the stream is first constructed or when - * {@link #setTokenSource} is called, indicating that the first token has - * 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 - * Initializing Methods.

- */ + /// The index into {@link #tokens} of the current token (next token to + /// {@link #consume}). {@link #tokens}{@code [}{@link #p}{@code ]} should be + /// {@link #LT LT(1)}. + /// + ///

This field is set to -1 when the stream is first constructed or when + /// {@link #setTokenSource} is called, indicating that the first token has + /// 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 + /// Initializing Methods.

internal var p: Int = -1 - /** - * 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 - * performance for the following cases: - * - *
    - *
  • {@link #consume}: The lookahead check in {@link #consume} to prevent - * consuming the EOF symbol is optimized by checking the values of - * {@link #fetchedEOF} and {@link #p} instead of calling {@link #LA}.
  • - *
  • {@link #fetch}: The check to prevent adding multiple EOF symbols into - * {@link #tokens} is trivial with this field.
  • - *
      - */ + /// 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 + /// performance for the following cases: + /// + ///
        + ///
      • {@link #consume}: The lookahead check in {@link #consume} to prevent + /// consuming the EOF symbol is optimized by checking the values of + /// {@link #fetchedEOF} and {@link #p} instead of calling {@link #LA}.
      • + ///
      • {@link #fetch}: The check to prevent adding multiple EOF symbols into + /// {@link #tokens} is trivial with this field.
      • + ///
          internal var fetchedEOF: Bool = false public init(_ tokenSource: TokenSource) { @@ -128,12 +117,11 @@ public class BufferedTokenStream: TokenStream { } } - /** Make sure index {@code i} in tokens has a token. - * - * @return {@code true} if a token is located at index {@code i}, otherwise - * {@code false}. - * @see #get(int i) - */ + /// Make sure index {@code i} in tokens has a token. + /// + /// - returns: {@code true} if a token is located at index {@code i}, otherwise + /// {@code false}. + /// - seealso: #get(int i) @discardableResult internal func sync(_ i: Int) throws -> Bool { assert(i >= 0, "Expected: i>=0") @@ -147,10 +135,9 @@ public class BufferedTokenStream: TokenStream { return true } - /** Add {@code n} elements to buffer. - * - * @return The actual number of elements added to the buffer. - */ + /// Add {@code n} elements to buffer. + /// + /// - returns: The actual number of elements added to the buffer. internal func fetch(_ n: Int) throws -> Int { if fetchedEOF { return 0 @@ -181,7 +168,7 @@ public class BufferedTokenStream: TokenStream { 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? { var stop = stop if start < 0 || stop < 0 { @@ -235,19 +222,17 @@ public class BufferedTokenStream: TokenStream { return tokens[i] } - /** - * Allowed derived classes to modify the behavior of operations which change - * the current stream position by adjusting the target token index of a seek - * operation. The default implementation simply returns {@code i}. If an - * exception is thrown in this method, the current stream index should not be - * changed. - * - *

          For example, {@link org.antlr.v4.runtime.CommonTokenStream} overrides this method to ensure that - * the seek target is always an on-channel token.

          - * - * @param i The target token index. - * @return The adjusted target token index. - */ + /// Allowed derived classes to modify the behavior of operations which change + /// the current stream position by adjusting the target token index of a seek + /// operation. The default implementation simply returns {@code i}. If an + /// exception is thrown in this method, the current stream index should not be + /// changed. + /// + ///

          For example, {@link org.antlr.v4.runtime.CommonTokenStream} overrides this method to ensure that + /// the seek target is always an on-channel token.

          + /// + /// - parameter i: The target token index. + /// - returns: The adjusted target token index. internal func adjustSeekIndex(_ i: Int) throws -> Int { return i } @@ -263,7 +248,7 @@ public class BufferedTokenStream: TokenStream { 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) { self.tokenSource = tokenSource tokens.removeAll() @@ -278,10 +263,9 @@ public class BufferedTokenStream: TokenStream { return try getTokens(start, stop, nil) } - /** Given a start and stop index, return a List of all tokens in - * the token type BitSet. Return null if no tokens were found. This - * method looks at both on and off channel tokens. - */ + /// Given a start and stop index, return a List of all tokens in + /// the token type BitSet. Return null if no tokens were found. This + /// method looks at both on and off channel tokens. public func getTokens(_ start: Int, _ stop: Int, _ types: Set?) throws -> Array? { try lazyInit() if start < 0 || stop >= tokens.count || @@ -318,12 +302,10 @@ public class BufferedTokenStream: TokenStream { return try getTokens(start, stop, s) } - /** - * 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 - * the EOF token if there are no tokens on channel between {@code i} and - * EOF. - */ + /// 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 + /// the EOF token if there are no tokens on channel between {@code i} and + /// EOF. internal func nextTokenOnChannel(_ i: Int, _ channel: Int) throws -> Int { var i = i try sync(i) @@ -345,16 +327,14 @@ public class BufferedTokenStream: TokenStream { return i } - /** - * 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 - * if there are no tokens on channel between {@code i} and 0. - * - *

          - * 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 - * as though it were on every channel.

          - */ + /// 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 + /// if there are no tokens on channel between {@code i} and 0. + /// + ///

          + /// 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 + /// as though it were on every channel.

          internal func previousTokenOnChannel(_ i: Int, _ channel: Int) throws -> Int { var i = i try sync(i) @@ -375,10 +355,9 @@ public class BufferedTokenStream: TokenStream { return i } - /** Collect all tokens on specified channel to the right of - * the current token up until we see a token on DEFAULT_TOKEN_CHANNEL or - * EOF. If channel is -1, find any non default channel token. - */ + /// Collect all tokens on specified channel to the right of + /// the current token up until we see a token on DEFAULT_TOKEN_CHANNEL or + /// EOF. If channel is -1, find any non default channel token. public func getHiddenTokensToRight(_ tokenIndex: Int, _ channel: Int) throws -> Array? { try lazyInit() if tokenIndex < 0 || tokenIndex >= tokens.count { @@ -400,18 +379,16 @@ public class BufferedTokenStream: TokenStream { return filterForChannel(from, to, channel) } - /** 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 - * or EOF. - */ + /// 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 + /// or EOF. public func getHiddenTokensToRight(_ tokenIndex: Int) throws -> Array? { return try getHiddenTokensToRight(tokenIndex, -1) } - /** Collect all tokens on specified channel to the left of - * the current token up until we see a token on DEFAULT_TOKEN_CHANNEL. - * If channel is -1, find any non default channel token. - */ + /// Collect all tokens on specified channel to the left of + /// the current token up until we see a token on DEFAULT_TOKEN_CHANNEL. + /// If channel is -1, find any non default channel token. public func getHiddenTokensToLeft(_ tokenIndex: Int, _ channel: Int) throws -> Array? { try lazyInit() if tokenIndex < 0 || tokenIndex >= tokens.count { @@ -437,9 +414,8 @@ public class BufferedTokenStream: TokenStream { return filterForChannel(from, to, channel) } - /** 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. - */ + /// 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. public func getHiddenTokensToLeft(_ tokenIndex: Int) throws -> Array? { return try getHiddenTokensToLeft(tokenIndex, -1) } @@ -469,7 +445,7 @@ public class BufferedTokenStream: TokenStream { 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 { @@ -513,7 +489,7 @@ public class BufferedTokenStream: TokenStream { return "" } - /** Get all tokens from lexer until EOF */ + /// Get all tokens from lexer until EOF public func fill() throws { try lazyInit() let blockSize: Int = 1000 diff --git a/runtime/Swift/Sources/Antlr4/CharStream.swift b/runtime/Swift/Sources/Antlr4/CharStream.swift index e37c18786..6a22999e6 100644 --- a/runtime/Swift/Sources/Antlr4/CharStream.swift +++ b/runtime/Swift/Sources/Antlr4/CharStream.swift @@ -1,27 +1,24 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** A source of characters for an ANTLR lexer. */ +/// A source of characters for an ANTLR lexer. public protocol CharStream: IntStream { - /** - * This method returns the text for a range of characters within this input - * stream. This method is guaranteed to not throw an exception if the - * specified {@code interval} lies entirely within a marked range. For more - * information about marked ranges, see {@link org.antlr.v4.runtime.IntStream#mark}. - * - * @param interval an interval within the stream - * @return the text of the specified interval - * - * @throws NullPointerException if {@code interval} is {@code null} - * @throws IllegalArgumentException if {@code interval.a < 0}, or if - * {@code interval.b < interval.a - 1}, or if {@code interval.b} lies at or - * past the end of the stream - * @throws UnsupportedOperationException if the stream does not support - * getting the text of the specified interval - */ + /// This method returns the text for a range of characters within this input + /// stream. This method is guaranteed to not throw an exception if the + /// specified {@code interval} lies entirely within a marked range. For more + /// information about marked ranges, see {@link org.antlr.v4.runtime.IntStream#mark}. + /// + /// - parameter interval: an interval within the stream + /// - returns: the text of the specified interval + /// + /// - NullPointerException if {@code interval} is {@code null} + /// - IllegalArgumentException if {@code interval.a < 0}, or if + /// {@code interval.b < interval.a - 1}, or if {@code interval.b} lies at or + /// past the end of the stream + /// - UnsupportedOperationException if the stream does not support + /// getting the text of the specified interval func getText(_ interval: Interval) -> String } diff --git a/runtime/Swift/Sources/Antlr4/CommonToken.swift b/runtime/Swift/Sources/Antlr4/CommonToken.swift index 4ca4094da..cfe7fb67b 100644 --- a/runtime/Swift/Sources/Antlr4/CommonToken.swift +++ b/runtime/Swift/Sources/Antlr4/CommonToken.swift @@ -1,84 +1,61 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. public class CommonToken: WritableToken { - /** - * 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. - */ + /// 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. 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 - /** - * 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 - /** - * This is the backing field for {@link #getCharPositionInLine} and - * {@link #setCharPositionInLine}. - */ + /// This is the backing field for {@link #getCharPositionInLine} and + /// {@link #setCharPositionInLine}. internal var charPositionInLine: Int = -1 // set to invalid position - /** - * This is the backing field for {@link #getChannel} and - * {@link #setChannel}. - */ + /// This is the backing field for {@link #getChannel} and + /// {@link #setChannel}. internal var channel: Int = DEFAULT_CHANNEL - /** - * This is the backing field for {@link #getTokenSource} and - * {@link #getInputStream}. - * - *

          - * 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 - * the same source and input stream share a reference to the same - * {@link org.antlr.v4.runtime.misc.Pair} containing these values.

          - */ + /// This is the backing field for {@link #getTokenSource} and + /// {@link #getInputStream}. + /// + ///

          + /// 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 + /// the same source and input stream share a reference to the same + /// {@link org.antlr.v4.runtime.misc.Pair} containing these values.

          internal var source: (TokenSource?, CharStream?) - /** - * This is the backing field for {@link #getText} when the token text is - * explicitly set in the constructor or via {@link #setText}. - * - * @see #getText() - */ + /// This is the backing field for {@link #getText} when the token text is + /// explicitly set in the constructor or via {@link #setText}. + /// + /// - seealso: #getText() internal var text: String? - /** - * This is the backing field for {@link #getTokenIndex} and - * {@link #setTokenIndex}. - */ + /// This is the backing field for {@link #getTokenIndex} and + /// {@link #setTokenIndex}. internal var index: Int = -1 - /** - * This is the backing field for {@link #getStartIndex} and - * {@link #setStartIndex}. - */ + /// This is the backing field for {@link #getStartIndex} and + /// {@link #setStartIndex}. internal var start: Int = 0 - /** - * This is the backing field for {@link #getStopIndex} and - * {@link #setStopIndex}. - */ + /// This is the backing field for {@link #getStopIndex} and + /// {@link #setStopIndex}. internal var stop: Int = 0 - /** - * Constructs a new {@link org.antlr.v4.runtime.CommonToken} with the specified token type. - * - * @param type The token type. - */ + /// Constructs a new {@link org.antlr.v4.runtime.CommonToken} with the specified token type. + /// + /// - parameter type: The token type. 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 - * text. - * - * @param type The token type. - * @param text The text of the token. - */ + /// Constructs a new {@link org.antlr.v4.runtime.CommonToken} with the specified token type and + /// text. + /// + /// - parameter type: The token type. + /// - parameter text: The text of the token. public init(_ type: Int, _ text: String?) { self.type = type self.channel = CommonToken.DEFAULT_CHANNEL @@ -113,19 +88,17 @@ public class CommonToken: WritableToken { 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}. - * - *

          - * 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 - * 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} - * will be constructed from the result of {@link org.antlr.v4.runtime.Token#getTokenSource} and - * {@link org.antlr.v4.runtime.Token#getInputStream}.

          - * - * @param oldToken The token to copy. - */ + /// Constructs a new {@link org.antlr.v4.runtime.CommonToken} as a copy of another {@link org.antlr.v4.runtime.Token}. + /// + ///

          + /// 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 + /// 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} + /// will be constructed from the result of {@link org.antlr.v4.runtime.Token#getTokenSource} and + /// {@link org.antlr.v4.runtime.Token#getInputStream}.

          + /// + /// - parameter oldToken: The token to copy. public init(_ oldToken: Token) { type = oldToken.getType() line = oldToken.getLine() @@ -173,15 +146,13 @@ public class CommonToken: WritableToken { } - /** - * Explicitly set the text for this token. If {code text} is not - * {@code null}, then {@link #getText} will return this value rather than - * extracting the text from the input. - * - * @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 - * of the token. - */ + /// Explicitly set the text for this token. If {code text} is not + /// {@code null}, then {@link #getText} will return this value rather than + /// extracting the text from the input. + /// + /// - parameter 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 + /// of the token. public func setText(_ text: String) { self.text = text diff --git a/runtime/Swift/Sources/Antlr4/CommonTokenFactory.swift b/runtime/Swift/Sources/Antlr4/CommonTokenFactory.swift index b17738f91..597abc349 100644 --- a/runtime/Swift/Sources/Antlr4/CommonTokenFactory.swift +++ b/runtime/Swift/Sources/Antlr4/CommonTokenFactory.swift @@ -1,64 +1,53 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * This default implementation of {@link org.antlr.v4.runtime.TokenFactory} creates - * {@link org.antlr.v4.runtime.CommonToken} objects. - */ +/// This default implementation of {@link org.antlr.v4.runtime.TokenFactory} creates +/// {@link org.antlr.v4.runtime.CommonToken} objects. public class CommonTokenFactory: TokenFactory { - /** - * The default {@link org.antlr.v4.runtime.CommonTokenFactory} instance. - * - *

          - * This token factory does not explicitly copy token text when constructing - * tokens.

          - */ + /// The default {@link org.antlr.v4.runtime.CommonTokenFactory} instance. + /// + ///

          + /// This token factory does not explicitly copy token text when constructing + /// tokens.

          public static let DEFAULT: TokenFactory = CommonTokenFactory() - /** - * Indicates whether {@link org.antlr.v4.runtime.CommonToken#setText} should be called after - * constructing tokens to explicitly set the text. This is useful for cases - * where the input stream might not be able to provide arbitrary substrings - * of text from the input after the lexer creates a token (e.g. the - * implementation of {@link org.antlr.v4.runtime.CharStream#getText} in - * {@link org.antlr.v4.runtime.UnbufferedCharStream} throws an - * {@link UnsupportedOperationException}). Explicitly setting the token text - * allows {@link org.antlr.v4.runtime.Token#getText} to be called at any time regardless of the - * input stream implementation. - * - *

          - * The default value is {@code false} to avoid the performance and memory - * overhead of copying text for every token unless explicitly requested.

          - */ + /// 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 + /// where the input stream might not be able to provide arbitrary substrings + /// of text from the input after the lexer creates a token (e.g. the + /// implementation of {@link org.antlr.v4.runtime.CharStream#getText} in + /// {@link org.antlr.v4.runtime.UnbufferedCharStream} throws an + /// {@link UnsupportedOperationException}). Explicitly setting the token text + /// allows {@link org.antlr.v4.runtime.Token#getText} to be called at any time regardless of the + /// input stream implementation. + /// + ///

          + /// The default value is {@code false} to avoid the performance and memory + /// overhead of copying text for every token unless explicitly requested.

          internal final var copyText: Bool - /** - * Constructs a {@link org.antlr.v4.runtime.CommonTokenFactory} with the specified value for - * {@link #copyText}. - * - *

          - * When {@code copyText} is {@code false}, the {@link #DEFAULT} instance - * should be used instead of constructing a new instance.

          - * - * @param copyText The value for {@link #copyText}. - */ + /// Constructs a {@link org.antlr.v4.runtime.CommonTokenFactory} with the specified value for + /// {@link #copyText}. + /// + ///

          + /// When {@code copyText} is {@code false}, the {@link #DEFAULT} instance + /// should be used instead of constructing a new instance.

          + /// + /// - parameter copyText: The value for {@link #copyText}. public init(_ copyText: Bool) { self.copyText = copyText } - /** - * Constructs a {@link org.antlr.v4.runtime.CommonTokenFactory} with {@link #copyText} set to - * {@code false}. - * - *

          - * The {@link #DEFAULT} instance should be used instead of calling this - * directly.

          - */ + /// Constructs a {@link org.antlr.v4.runtime.CommonTokenFactory} with {@link #copyText} set to + /// {@code false}. + /// + ///

          + /// The {@link #DEFAULT} instance should be used instead of calling this + /// directly.

          public convenience init() { self.init(false) } diff --git a/runtime/Swift/Sources/Antlr4/CommonTokenStream.swift b/runtime/Swift/Sources/Antlr4/CommonTokenStream.swift index 0f34d1fc3..795c34ec0 100644 --- a/runtime/Swift/Sources/Antlr4/CommonTokenStream.swift +++ b/runtime/Swift/Sources/Antlr4/CommonTokenStream.swift @@ -1,65 +1,56 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * This class extends {@link org.antlr.v4.runtime.BufferedTokenStream} with functionality to filter - * token streams to tokens on a particular channel (tokens where - * {@link org.antlr.v4.runtime.Token#getChannel} returns a particular value). - * - *

          - * 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 - * accessing tokens via the lookahead methods {@link #LA}, {@link #LT}, and - * {@link #LB}.

          - * - *

          - * By default, tokens are placed on the default channel - * ({@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 - * call {@link org.antlr.v4.runtime.Lexer#setChannel}. - *

          - * - *

          - * 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 - * such a rule will not be available as part of the token stream, regardless of - * channel.

          - */ +/// This class extends {@link org.antlr.v4.runtime.BufferedTokenStream} with functionality to filter +/// token streams to tokens on a particular channel (tokens where +/// {@link org.antlr.v4.runtime.Token#getChannel} returns a particular value). +/// +///

          +/// 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 +/// accessing tokens via the lookahead methods {@link #LA}, {@link #LT}, and +/// {@link #LB}.

          +/// +///

          +/// By default, tokens are placed on the default channel +/// ({@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 +/// call {@link org.antlr.v4.runtime.Lexer#setChannel}. +///

          +/// +///

          +/// 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 +/// such a rule will not be available as part of the token stream, regardless of +/// channel.

          public class CommonTokenStream: BufferedTokenStream { - /** - * Specifies the channel to use for filtering tokens. - * - *

          - * The default value is {@link org.antlr.v4.runtime.Token#DEFAULT_CHANNEL}, which matches the - * default channel assigned to tokens created by the lexer.

          - */ + /// Specifies the channel to use for filtering tokens. + /// + ///

          + /// The default value is {@link org.antlr.v4.runtime.Token#DEFAULT_CHANNEL}, which matches the + /// default channel assigned to tokens created by the lexer.

          internal var channel: Int = CommonToken.DEFAULT_CHANNEL - /** - * 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}). - * - * @param tokenSource The token source. - */ + /// 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}). + /// + /// - parameter tokenSource: The token source. public override init(_ tokenSource: TokenSource) { super.init(tokenSource) } - /** - * Constructs a new {@link org.antlr.v4.runtime.CommonTokenStream} using the specified token - * 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#getType} equal to {@link org.antlr.v4.runtime.Token#EOF} will be returned by the - * token stream lookahead methods. - * - * @param tokenSource The token source. - * @param channel The channel to use for filtering tokens. - */ + /// Constructs a new {@link org.antlr.v4.runtime.CommonTokenStream} using the specified token + /// 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#getType} equal to {@link org.antlr.v4.runtime.Token#EOF} will be returned by the + /// token stream lookahead methods. + /// + /// - parameter tokenSource: The token source. + /// - parameter channel: The channel to use for filtering tokens. public convenience init(_ tokenSource: TokenSource, _ channel: Int) { self.init(tokenSource) self.channel = channel @@ -114,7 +105,7 @@ public class CommonTokenStream: BufferedTokenStream { return tokens[i] } - /** Count EOF just once. */ + /// Count EOF just once. public func getNumberOfOnChannelTokens() throws -> Int { var n: Int = 0 try fill() diff --git a/runtime/Swift/Sources/Antlr4/ConsoleErrorListener.swift b/runtime/Swift/Sources/Antlr4/ConsoleErrorListener.swift index 95fe4d334..178260ac6 100644 --- a/runtime/Swift/Sources/Antlr4/ConsoleErrorListener.swift +++ b/runtime/Swift/Sources/Antlr4/ConsoleErrorListener.swift @@ -1,32 +1,25 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * - * @author Sam Harwell - */ +/// +/// - Sam Harwell 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() - /** - * {@inheritDoc} - * - *

          - * This implementation prints messages to {@link System#err} containing the - * values of {@code line}, {@code charPositionInLine}, and {@code msg} using - * the following format.

          - * - *
          -     * line line:charPositionInLine msg
          -     * 
          - */ + /// {@inheritDoc} + /// + ///

          + /// This implementation prints messages to {@link System#err} containing the + /// values of {@code line}, {@code charPositionInLine}, and {@code msg} using + /// the following format.

          + /// + ///
          +    /// line line:charPositionInLine msg
          +    /// 
          override public func syntaxError(_ recognizer: Recognizer, _ offendingSymbol: AnyObject?, diff --git a/runtime/Swift/Sources/Antlr4/DefaultErrorStrategy.swift b/runtime/Swift/Sources/Antlr4/DefaultErrorStrategy.swift index 6a1ca226d..3c2784eba 100644 --- a/runtime/Swift/Sources/Antlr4/DefaultErrorStrategy.swift +++ b/runtime/Swift/Sources/Antlr4/DefaultErrorStrategy.swift @@ -1,107 +1,89 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * This is the default implementation of {@link org.antlr.v4.runtime.ANTLRErrorStrategy} used for - * error reporting and recovery in ANTLR parsers. - */ +/// This is the default implementation of {@link org.antlr.v4.runtime.ANTLRErrorStrategy} used for +/// error reporting and recovery in ANTLR parsers. import Foundation public class DefaultErrorStrategy: ANTLRErrorStrategy { - /** - * Indicates whether the error strategy is currently "recovering from an - * error". This is used to suppress reporting multiple error messages while - * attempting to recover from a detected syntax error. - * - * @see #inErrorRecoveryMode - */ + /// Indicates whether the error strategy is currently "recovering from an + /// error". This is used to suppress reporting multiple error messages while + /// attempting to recover from a detected syntax error. + /// + /// - seealso: #inErrorRecoveryMode internal var errorRecoveryMode: Bool = false - /** The index into the input stream where the last error occurred. - * This is used to prevent infinite loops where an error is found - * but no token is consumed during recovery...another error is found, - * ad nauseum. This is a failsafe mechanism to guarantee that at least - * one token/tree node is consumed for two errors. - */ + /// The index into the input stream where the last error occurred. + /// This is used to prevent infinite loops where an error is found + /// but no token is consumed during recovery...another error is found, + /// ad nauseum. This is a failsafe mechanism to guarantee that at least + /// one token/tree node is consumed for two errors. internal var lastErrorIndex: Int = -1 internal var lastErrorStates: IntervalSet? - /** - * {@inheritDoc} - * - *

          The default implementation simply calls {@link #endErrorCondition} to - * ensure that the handler is not in error recovery mode.

          - */ + /// {@inheritDoc} + /// + ///

          The default implementation simply calls {@link #endErrorCondition} to + /// ensure that the handler is not in error recovery mode.

          public func reset(_ recognizer: Parser) { endErrorCondition(recognizer) } - /** - * This method is called to enter error recovery mode when a recognition - * exception is reported. - * - * @param recognizer the parser instance - */ + /// This method is called to enter error recovery mode when a recognition + /// exception is reported. + /// + /// - parameter recognizer: the parser instance internal func beginErrorCondition(_ recognizer: Parser) { errorRecoveryMode = true } - /** - * {@inheritDoc} - */ + /// {@inheritDoc} public func inErrorRecoveryMode(_ recognizer: Parser) -> Bool { return errorRecoveryMode } - /** - * This method is called to leave error recovery mode after recovering from - * a recognition exception. - * - * @param recognizer - */ + /// This method is called to leave error recovery mode after recovering from + /// a recognition exception. + /// + /// - parameter recognizer: internal func endErrorCondition(_ recognizer: Parser) { errorRecoveryMode = false lastErrorStates = nil lastErrorIndex = -1 } - /** - * {@inheritDoc} - * - *

          The default implementation simply calls {@link #endErrorCondition}.

          - */ + /// {@inheritDoc} + /// + ///

          The default implementation simply calls {@link #endErrorCondition}.

          public func reportMatch(_ recognizer: Parser) { endErrorCondition(recognizer) } - /** - * {@inheritDoc} - * - *

          The default implementation returns immediately if the handler is already - * in error recovery mode. Otherwise, it calls {@link #beginErrorCondition} - * and dispatches the reporting task based on the runtime type of {@code e} - * according to the following table.

          - * - *
            - *
          • {@link org.antlr.v4.runtime.NoViableAltException}: Dispatches the call to - * {@link #reportNoViableAlternative}
          • - *
          • {@link org.antlr.v4.runtime.InputMismatchException}: Dispatches the call to - * {@link #reportInputMismatch}
          • - *
          • {@link org.antlr.v4.runtime.FailedPredicateException}: Dispatches the call to - * {@link #reportFailedPredicate}
          • - *
          • All other types: calls {@link org.antlr.v4.runtime.Parser#notifyErrorListeners} to report - * the exception
          • - *
          - */ + /// {@inheritDoc} + /// + ///

          The default implementation returns immediately if the handler is already + /// in error recovery mode. Otherwise, it calls {@link #beginErrorCondition} + /// and dispatches the reporting task based on the runtime type of {@code e} + /// according to the following table.

          + /// + ///
            + ///
          • {@link org.antlr.v4.runtime.NoViableAltException}: Dispatches the call to + /// {@link #reportNoViableAlternative}
          • + ///
          • {@link org.antlr.v4.runtime.InputMismatchException}: Dispatches the call to + /// {@link #reportInputMismatch}
          • + ///
          • {@link org.antlr.v4.runtime.FailedPredicateException}: Dispatches the call to + /// {@link #reportFailedPredicate}
          • + ///
          • All other types: calls {@link org.antlr.v4.runtime.Parser#notifyErrorListeners} to report + /// the exception
          • + ///
          public func reportError(_ recognizer: Parser, _ e: AnyObject) { @@ -130,13 +112,11 @@ public class DefaultErrorStrategy: ANTLRErrorStrategy { } } - /** - * {@inheritDoc} - * - *

          The default implementation resynchronizes the parser by consuming tokens - * until we find one in the resynchronization set--loosely the set of tokens - * that can follow the current rule.

          - */ + /// {@inheritDoc} + /// + ///

          The default implementation resynchronizes the parser by consuming tokens + /// until we find one in the resynchronization set--loosely the set of tokens + /// that can follow the current rule.

          public func recover(_ recognizer: Parser, _ e: AnyObject) throws { // print("recover in "+recognizer.getRuleInvocationStack()+ @@ -165,52 +145,50 @@ public class DefaultErrorStrategy: ANTLRErrorStrategy { try consumeUntil(recognizer, followSet) } - /** - * The default implementation of {@link org.antlr.v4.runtime.ANTLRErrorStrategy#sync} makes sure - * that the current lookahead symbol is consistent with what were expecting - * at this point in the ATN. You can call this anytime but ANTLR only - * generates code to check before subrules/loops and each iteration. - * - *

          Implements Jim Idle's magic sync mechanism in closures and optional - * subrules. E.g.,

          - * - *
          -     * a : sync ( stuff sync )* ;
          -     * sync : {consume to what can follow sync} ;
          -     * 
          - * - * At the start of a sub rule upon error, {@link #sync} performs single - * token deletion, if possible. If it can't do that, it bails on the current - * rule and uses the default error recovery, which consumes until the - * resynchronization set of the current rule. - * - *

          If the sub rule is optional ({@code (...)?}, {@code (...)*}, or block - * with an empty alternative), then the expected set includes what follows - * the subrule.

          - * - *

          During loop iteration, it consumes until it sees a token that can start a - * sub rule or what follows loop. Yes, that is pretty aggressive. We opt to - * stay in the loop as long as possible.

          - * - *

          ORIGINS

          - * - *

          Previous versions of ANTLR did a poor job of their recovery within loops. - * A single mismatch token or missing token would force the parser to bail - * out of the entire rules surrounding the loop. So, for rule

          - * - *
          -     * classDef : 'class' ID '{' member* '}'
          -     * 
          - * - * input with an extra token between members would force the parser to - * consume until it found the next class definition rather than the next - * member definition of the current class. - * - *

          This functionality cost a little bit of effort because the parser has to - * compare token set at the start of the loop and at each iteration. If for - * some reason speed is suffering for you, you can turn off this - * functionality by simply overriding this method as a blank { }.

          - */ + /// The default implementation of {@link org.antlr.v4.runtime.ANTLRErrorStrategy#sync} makes sure + /// that the current lookahead symbol is consistent with what were expecting + /// at this point in the ATN. You can call this anytime but ANTLR only + /// generates code to check before subrules/loops and each iteration. + /// + ///

          Implements Jim Idle's magic sync mechanism in closures and optional + /// subrules. E.g.,

          + /// + ///
          +    /// a : sync ( stuff sync )* ;
          +    /// sync : {consume to what can follow sync} ;
          +    /// 
          + /// + /// At the start of a sub rule upon error, {@link #sync} performs single + /// token deletion, if possible. If it can't do that, it bails on the current + /// rule and uses the default error recovery, which consumes until the + /// resynchronization set of the current rule. + /// + ///

          If the sub rule is optional ({@code (...)?}, {@code (...)*}, or block + /// with an empty alternative), then the expected set includes what follows + /// the subrule.

          + /// + ///

          During loop iteration, it consumes until it sees a token that can start a + /// sub rule or what follows loop. Yes, that is pretty aggressive. We opt to + /// stay in the loop as long as possible.

          + /// + ///

          ORIGINS

          + /// + ///

          Previous versions of ANTLR did a poor job of their recovery within loops. + /// A single mismatch token or missing token would force the parser to bail + /// out of the entire rules surrounding the loop. So, for rule

          + /// + ///
          +    /// classDef : 'class' ID '{' member* '}'
          +    /// 
          + /// + /// input with an extra token between members would force the parser to + /// consume until it found the next class definition rather than the next + /// member definition of the current class. + /// + ///

          This functionality cost a little bit of effort because the parser has to + /// compare token set at the start of the loop and at each iteration. If for + /// some reason speed is suffering for you, you can turn off this + /// functionality by simply overriding this method as a blank { }.

          public func sync(_ recognizer: Parser) throws { 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 - * {@link org.antlr.v4.runtime.NoViableAltException}. - * - * @see #reportError - * - * @param recognizer the parser instance - * @param e the recognition exception - */ + /// This is called by {@link #reportError} when the exception is a + /// {@link org.antlr.v4.runtime.NoViableAltException}. + /// + /// - seealso: #reportError + /// + /// - parameter recognizer: the parser instance + /// - parameter e: the recognition exception internal func reportNoViableAlternative(_ recognizer: Parser, _ e: NoViableAltException) throws { let tokens: TokenStream? = getTokenStream(recognizer) @@ -287,15 +263,13 @@ public class DefaultErrorStrategy: ANTLRErrorStrategy { recognizer.notifyErrorListeners(e.getOffendingToken(), msg, e) } - /** - * This is called by {@link #reportError} when the exception is an - * {@link org.antlr.v4.runtime.InputMismatchException}. - * - * @see #reportError - * - * @param recognizer the parser instance - * @param e the recognition exception - */ + /// This is called by {@link #reportError} when the exception is an + /// {@link org.antlr.v4.runtime.InputMismatchException}. + /// + /// - seealso: #reportError + /// + /// - parameter recognizer: the parser instance + /// - parameter e: the recognition exception internal func reportInputMismatch(_ recognizer: Parser, _ e: InputMismatchException) { let msg: String = "mismatched input " + getTokenErrorDisplay(e.getOffendingToken()) + @@ -303,15 +277,13 @@ public class DefaultErrorStrategy: ANTLRErrorStrategy { recognizer.notifyErrorListeners(e.getOffendingToken(), msg, e) } - /** - * This is called by {@link #reportError} when the exception is a - * {@link org.antlr.v4.runtime.FailedPredicateException}. - * - * @see #reportError - * - * @param recognizer the parser instance - * @param e the recognition exception - */ + /// This is called by {@link #reportError} when the exception is a + /// {@link org.antlr.v4.runtime.FailedPredicateException}. + /// + /// - seealso: #reportError + /// + /// - parameter recognizer: the parser instance + /// - parameter e: the recognition exception internal func reportFailedPredicate(_ recognizer: Parser, _ e: FailedPredicateException) { let ruleName: String = recognizer.getRuleNames()[recognizer._ctx!.getRuleIndex()] @@ -319,24 +291,22 @@ public class DefaultErrorStrategy: ANTLRErrorStrategy { recognizer.notifyErrorListeners(e.getOffendingToken(), msg, e) } - /** - * This method is called to report a syntax error which requires the removal - * of a token from the input stream. At the time this method is called, the - * erroneous symbol is current {@code LT(1)} symbol and has not yet been - * removed from the input stream. When this method returns, - * {@code recognizer} is in error recovery mode. - * - *

          This method is called when {@link #singleTokenDeletion} identifies - * single-token deletion as a viable recovery strategy for a mismatched - * input error.

          - * - *

          The default implementation simply returns if the handler is already in - * error recovery mode. Otherwise, it calls {@link #beginErrorCondition} to - * enter error recovery mode, followed by calling - * {@link org.antlr.v4.runtime.Parser#notifyErrorListeners}.

          - * - * @param recognizer the parser instance - */ + /// This method is called to report a syntax error which requires the removal + /// of a token from the input stream. At the time this method is called, the + /// erroneous symbol is current {@code LT(1)} symbol and has not yet been + /// removed from the input stream. When this method returns, + /// {@code recognizer} is in error recovery mode. + /// + ///

          This method is called when {@link #singleTokenDeletion} identifies + /// single-token deletion as a viable recovery strategy for a mismatched + /// input error.

          + /// + ///

          The default implementation simply returns if the handler is already in + /// error recovery mode. Otherwise, it calls {@link #beginErrorCondition} to + /// enter error recovery mode, followed by calling + /// {@link org.antlr.v4.runtime.Parser#notifyErrorListeners}.

          + /// + /// - parameter recognizer: the parser instance internal func reportUnwantedToken(_ recognizer: Parser) throws { if inErrorRecoveryMode(recognizer) { return @@ -352,23 +322,21 @@ public class DefaultErrorStrategy: ANTLRErrorStrategy { recognizer.notifyErrorListeners(t, msg, nil) } - /** - * This method is called to report a syntax error which requires the - * insertion of a missing token into the input stream. At the time this - * method is called, the missing token has not yet been inserted. When this - * method returns, {@code recognizer} is in error recovery mode. - * - *

          This method is called when {@link #singleTokenInsertion} identifies - * single-token insertion as a viable recovery strategy for a mismatched - * input error.

          - * - *

          The default implementation simply returns if the handler is already in - * error recovery mode. Otherwise, it calls {@link #beginErrorCondition} to - * enter error recovery mode, followed by calling - * {@link org.antlr.v4.runtime.Parser#notifyErrorListeners}.

          - * - * @param recognizer the parser instance - */ + /// This method is called to report a syntax error which requires the + /// insertion of a missing token into the input stream. At the time this + /// method is called, the missing token has not yet been inserted. When this + /// method returns, {@code recognizer} is in error recovery mode. + /// + ///

          This method is called when {@link #singleTokenInsertion} identifies + /// single-token insertion as a viable recovery strategy for a mismatched + /// input error.

          + /// + ///

          The default implementation simply returns if the handler is already in + /// error recovery mode. Otherwise, it calls {@link #beginErrorCondition} to + /// enter error recovery mode, followed by calling + /// {@link org.antlr.v4.runtime.Parser#notifyErrorListeners}.

          + /// + /// - parameter recognizer: the parser instance internal func reportMissingToken(_ recognizer: Parser) throws { if inErrorRecoveryMode(recognizer) { return @@ -384,56 +352,54 @@ public class DefaultErrorStrategy: ANTLRErrorStrategy { recognizer.notifyErrorListeners(t, msg, nil) } - /** - * {@inheritDoc} - * - *

          The default implementation attempts to recover from the mismatched input - * by using single token insertion and deletion as described below. If the - * recovery attempt fails, this method throws an - * {@link org.antlr.v4.runtime.InputMismatchException}.

          - * - *

          EXTRA TOKEN (single token deletion)

          - * - *

          {@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 - * 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.

          - * - *

          This recovery strategy is implemented by {@link #singleTokenDeletion}.

          - * - *

          MISSING TOKEN (single token insertion)

          - * - *

          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 - * 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 - * result of the match operation.

          - * - *

          This recovery strategy is implemented by {@link #singleTokenInsertion}.

          - * - *

          EXAMPLE

          - * - *

          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 - * call chain:

          - * - *
          -     * stat → expr → atom
          -     * 
          - * - * and it will be trying to match the {@code ')'} at this point in the - * derivation: - * - *
          -     * => ID '=' '(' INT ')' ('+' atom)* ';'
          -     *                    ^
          -     * 
          - * - * The attempt to match {@code ')'} will fail when it sees {@code ';'} and - * call {@link #recoverInline}. To recover, it sees that {@code LA(1)==';'} - * 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 ')'}. - */ + /// {@inheritDoc} + /// + ///

          The default implementation attempts to recover from the mismatched input + /// by using single token insertion and deletion as described below. If the + /// recovery attempt fails, this method throws an + /// {@link org.antlr.v4.runtime.InputMismatchException}.

          + /// + ///

          EXTRA TOKEN (single token deletion)

          + /// + ///

          {@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 + /// 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.

          + /// + ///

          This recovery strategy is implemented by {@link #singleTokenDeletion}.

          + /// + ///

          MISSING TOKEN (single token insertion)

          + /// + ///

          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 + /// 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 + /// result of the match operation.

          + /// + ///

          This recovery strategy is implemented by {@link #singleTokenInsertion}.

          + /// + ///

          EXAMPLE

          + /// + ///

          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 + /// call chain:

          + /// + ///
          +    /// stat → expr → atom
          +    /// 
          + /// + /// and it will be trying to match the {@code ')'} at this point in the + /// derivation: + /// + ///
          +    /// => ID '=' '(' INT ')' ('+' atom)* ';'
          +    /// ^
          +    /// 
          + /// + /// The attempt to match {@code ')'} will fail when it sees {@code ';'} and + /// call {@link #recoverInline}. To recover, it sees that {@code LA(1)==';'} + /// 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 ')'}. public func recoverInline(_ recognizer: Parser) throws -> Token { // SINGLE TOKEN DELETION @@ -456,23 +422,21 @@ public class DefaultErrorStrategy: ANTLRErrorStrategy { //throwException() /* throw InputMismatchException(recognizer); */ } - /** - * This method implements the single-token insertion inline error recovery - * strategy. It is called by {@link #recoverInline} if the single-token - * deletion strategy fails to recover from the mismatched input. If this - * method returns {@code true}, {@code recognizer} will be in error recovery - * mode. - * - *

          This method determines whether or not single-token insertion is viable by - * 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 - * {@code true}, the caller is responsible for creating and inserting a - * token with the correct type to produce this behavior.

          - * - * @param recognizer the parser instance - * @return {@code true} if single-token insertion is a viable recovery - * strategy for the current mismatched input, otherwise {@code false} - */ + /// This method implements the single-token insertion inline error recovery + /// strategy. It is called by {@link #recoverInline} if the single-token + /// deletion strategy fails to recover from the mismatched input. If this + /// method returns {@code true}, {@code recognizer} will be in error recovery + /// mode. + /// + ///

          This method determines whether or not single-token insertion is viable by + /// 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 + /// {@code true}, the caller is responsible for creating and inserting a + /// token with the correct type to produce this behavior.

          + /// + /// - parameter recognizer: the parser instance + /// - returns: {@code true} if single-token insertion is a viable recovery + /// strategy for the current mismatched input, otherwise {@code false} internal func singleTokenInsertion(_ recognizer: Parser) throws -> Bool { let currentSymbolType: Int = try getTokenStream(recognizer).LA(1) // if current token is consistent with what could come after current @@ -490,36 +454,32 @@ public class DefaultErrorStrategy: ANTLRErrorStrategy { return false } - /** - * This method implements the single-token deletion inline error recovery - * strategy. It is called by {@link #recoverInline} to attempt to recover - * from mismatched input. If this method returns null, the parser and error - * handler state will not have changed. If this method returns non-null, - * {@code recognizer} will not be in error recovery mode since the - * returned token was a successful match. - * - *

          If the single-token deletion is successful, this method calls - * {@link #reportUnwantedToken} to report the error, followed by - * {@link org.antlr.v4.runtime.Parser#consume} to actually "delete" the extraneous token. Then, - * before returning {@link #reportMatch} is called to signal a successful - * match.

          - * - * @param recognizer the parser instance - * @return the successfully matched {@link org.antlr.v4.runtime.Token} instance if single-token - * deletion successfully recovers from the mismatched input, otherwise - * {@code null} - */ + /// This method implements the single-token deletion inline error recovery + /// strategy. It is called by {@link #recoverInline} to attempt to recover + /// from mismatched input. If this method returns null, the parser and error + /// handler state will not have changed. If this method returns non-null, + /// {@code recognizer} will not be in error recovery mode since the + /// returned token was a successful match. + /// + ///

          If the single-token deletion is successful, this method calls + /// {@link #reportUnwantedToken} to report the error, followed by + /// {@link org.antlr.v4.runtime.Parser#consume} to actually "delete" the extraneous token. Then, + /// before returning {@link #reportMatch} is called to signal a successful + /// match.

          + /// + /// - parameter recognizer: the parser instance + /// - returns: the successfully matched {@link org.antlr.v4.runtime.Token} instance if single-token + /// deletion successfully recovers from the mismatched input, otherwise + /// {@code null} internal func singleTokenDeletion(_ recognizer: Parser) throws -> Token? { let nextTokenType: Int = try getTokenStream(recognizer).LA(2) let expecting: IntervalSet = try getExpectedTokens(recognizer) if expecting.contains(nextTokenType) { try reportUnwantedToken(recognizer) - /* - errPrint("recoverFromMismatchedToken deleting "+ - ((TokenStream)getTokenStream(recognizer)).LT(1)+ - " since "+((TokenStream)getTokenStream(recognizer)).LT(2)+ - " is what we want"); - */ + /// errPrint("recoverFromMismatchedToken deleting "+ + /// ((TokenStream)getTokenStream(recognizer)).LT(1)+ + /// " since "+((TokenStream)getTokenStream(recognizer)).LT(2)+ + /// " is what we want"); try recognizer.consume() // simply delete extra token // we want to return the token we're actually matching let matchedSymbol: Token = try recognizer.getCurrentToken() @@ -529,25 +489,24 @@ public class DefaultErrorStrategy: ANTLRErrorStrategy { return nil } - /** Conjure up a missing token during error recovery. - * - * The recognizer attempts to recover from single missing - * symbols. But, actions might refer to that missing symbol. - * For example, x=ID {f($x);}. The action clearly assumes - * that there has been an identifier matched previously and that - * $x points at that token. If that token is missing, but - * the next token in the stream is what we want we assume that - * this token is missing and we keep going. Because we - * have to return some token to replace the missing token, - * we have to conjure one up. This method gives the user control - * over the tokens returned for missing tokens. Mostly, - * you will want to create something special for identifier - * tokens. For literals such as '{' and ',', the default - * action in the parser or tree parser works. It simply creates - * a CommonToken of the appropriate type. The text will be the token. - * If you change what tokens must be created by the lexer, - * override this method to create the appropriate tokens. - */ + /// Conjure up a missing token during error recovery. + /// + /// The recognizer attempts to recover from single missing + /// symbols. But, actions might refer to that missing symbol. + /// For example, x=ID {f($x);}. The action clearly assumes + /// that there has been an identifier matched previously and that + /// $x points at that token. If that token is missing, but + /// the next token in the stream is what we want we assume that + /// this token is missing and we keep going. Because we + /// have to return some token to replace the missing token, + /// we have to conjure one up. This method gives the user control + /// over the tokens returned for missing tokens. Mostly, + /// you will want to create something special for identifier + /// tokens. For literals such as '{' and ',', the default + /// action in the parser or tree parser works. It simply creates + /// a CommonToken of the appropriate type. The text will be the token. + /// If you change what tokens must be created by the lexer, + /// override this method to create the appropriate tokens. internal func getTokenStream(_ recognizer: Parser) -> TokenStream { return recognizer.getInputStream() as! TokenStream @@ -582,14 +541,13 @@ public class DefaultErrorStrategy: ANTLRErrorStrategy { return try recognizer.getExpectedTokens() } - /** How should a token be displayed in an error message? The default - * is to display just the text, but during development you might - * want to have a lot of information spit out. Override in that case - * to use t.toString() (which, for CommonToken, dumps everything about - * the token). This is better than forcing you to override a method in - * your token objects because you don't have to go modify your lexer - * so that it creates a new Java type. - */ + /// How should a token be displayed in an error message? The default + /// is to display just the text, but during development you might + /// want to have a lot of information spit out. Override in that case + /// to use t.toString() (which, for CommonToken, dumps everything about + /// the token). This is better than forcing you to override a method in + /// your token objects because you don't have to go modify your lexer + /// so that it creates a new Java type. internal func getTokenErrorDisplay(_ t: Token?) -> String { if t == nil { return "" @@ -622,98 +580,97 @@ public class DefaultErrorStrategy: ANTLRErrorStrategy { return "'" + s + "'" } - /* Compute the error recovery set for the current rule. During - * rule invocation, the parser pushes the set of tokens that can - * follow that rule reference on the stack; this amounts to - * computing FIRST of what follows the rule reference in the - * enclosing rule. See LinearApproximator.FIRST(). - * This local follow set only includes tokens - * from within the rule; i.e., the FIRST computation done by - * ANTLR stops at the end of a rule. - * - * EXAMPLE - * - * When you find a "no viable alt exception", the input is not - * consistent with any of the alternatives for rule r. The best - * thing to do is to consume tokens until you see something that - * can legally follow a call to r *or* any rule that called r. - * You don't want the exact set of viable next tokens because the - * input might just be missing a token--you might consume the - * rest of the input looking for one of the missing tokens. - * - * Consider grammar: - * - * a : '[' b ']' - * | '(' b ')' - * ; - * b : c '^' INT ; - * c : ID - * | INT - * ; - * - * At each rule invocation, the set of tokens that could follow - * that rule is pushed on a stack. Here are the various - * context-sensitive follow sets: - * - * FOLLOW(b1_in_a) = FIRST(']') = ']' - * FOLLOW(b2_in_a) = FIRST(')') = ')' - * FOLLOW(c_in_b) = FIRST('^') = '^' - * - * Upon erroneous input "[]", the call chain is - * - * a -> b -> c - * - * and, hence, the follow context stack is: - * - * depth follow set start of rule execution - * 0 a (from main()) - * 1 ']' b - * 2 '^' c - * - * Notice that ')' is not included, because b would have to have - * been called from a different context in rule a for ')' to be - * included. - * - * For error recovery, we cannot consider FOLLOW(c) - * (context-sensitive or otherwise). We need the combined set of - * all context-sensitive FOLLOW sets--the set of all tokens that - * could follow any reference in the call chain. We need to - * 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 - * sync to context-sensitive FOLLOWs for a, b, and c: {']','^'}. - * In this case, for input "[]", LA(1) is ']' and in the set, so we would - * not consume anything. After printing an error, rule c would - * return normally. Rule b would not find the required '^' though. - * At this point, it gets a mismatched token error and throws an - * exception (since LA(1) is not in the viable following token - * set). The rule exception handler tries to recover, but finds - * the same recovery set and doesn't consume anything. Rule b - * exits normally returning to rule a. Now it finds the ']' (and - * with the successful match exits errorRecovery mode). - * - * So, you can see that the parser walks up the call chain looking - * for the token that was a member of the recovery set. - * - * Errors are not generated in errorRecovery mode. - * - * ANTLR's error recovery mechanism is based upon original ideas: - * - * "Algorithms + Data Structures = Programs" by Niklaus Wirth - * - * and - * - * "A note on error recovery in recursive descent parsers": - * http://portal.acm.org/citation.cfm?id=947902.947905 - * - * Later, Josef Grosch had some good ideas: - * - * "Efficient and Comfortable Error Recovery in Recursive Descent - * Parsers": - * ftp://www.cocolab.com/products/cocktail/doca4.ps/ell.ps.zip - * - * Like Grosch I implement context-sensitive FOLLOW sets that are combined - * at run-time upon error to avoid overhead during parsing. - */ + /// Compute the error recovery set for the current rule. During + /// rule invocation, the parser pushes the set of tokens that can + /// follow that rule reference on the stack; this amounts to + /// computing FIRST of what follows the rule reference in the + /// enclosing rule. See LinearApproximator.FIRST(). + /// This local follow set only includes tokens + /// from within the rule; i.e., the FIRST computation done by + /// ANTLR stops at the end of a rule. + /// + /// EXAMPLE + /// + /// When you find a "no viable alt exception", the input is not + /// consistent with any of the alternatives for rule r. The best + /// thing to do is to consume tokens until you see something that + /// can legally follow a call to r *or* any rule that called r. + /// You don't want the exact set of viable next tokens because the + /// input might just be missing a token--you might consume the + /// rest of the input looking for one of the missing tokens. + /// + /// Consider grammar: + /// + /// a : '[' b ']' + /// | '(' b ')' + /// ; + /// b : c '^' INT ; + /// c : ID + /// | INT + /// ; + /// + /// At each rule invocation, the set of tokens that could follow + /// that rule is pushed on a stack. Here are the various + /// context-sensitive follow sets: + /// + /// FOLLOW(b1_in_a) = FIRST(']') = ']' + /// FOLLOW(b2_in_a) = FIRST(')') = ')' + /// FOLLOW(c_in_b) = FIRST('^') = '^' + /// + /// Upon erroneous input "[]", the call chain is + /// + /// a -> b -> c + /// + /// and, hence, the follow context stack is: + /// + /// depth follow set start of rule execution + /// 0 a (from main()) + /// 1 ']' b + /// 2 '^' c + /// + /// Notice that ')' is not included, because b would have to have + /// been called from a different context in rule a for ')' to be + /// included. + /// + /// For error recovery, we cannot consider FOLLOW(c) + /// (context-sensitive or otherwise). We need the combined set of + /// all context-sensitive FOLLOW sets--the set of all tokens that + /// could follow any reference in the call chain. We need to + /// 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 + /// sync to context-sensitive FOLLOWs for a, b, and c: {']','^'}. + /// In this case, for input "[]", LA(1) is ']' and in the set, so we would + /// not consume anything. After printing an error, rule c would + /// return normally. Rule b would not find the required '^' though. + /// At this point, it gets a mismatched token error and throws an + /// exception (since LA(1) is not in the viable following token + /// set). The rule exception handler tries to recover, but finds + /// the same recovery set and doesn't consume anything. Rule b + /// exits normally returning to rule a. Now it finds the ']' (and + /// with the successful match exits errorRecovery mode). + /// + /// So, you can see that the parser walks up the call chain looking + /// for the token that was a member of the recovery set. + /// + /// Errors are not generated in errorRecovery mode. + /// + /// ANTLR's error recovery mechanism is based upon original ideas: + /// + /// "Algorithms + Data Structures = Programs" by Niklaus Wirth + /// + /// and + /// + /// "A note on error recovery in recursive descent parsers": + /// http://portal.acm.org/citation.cfm?id=947902.947905 + /// + /// Later, Josef Grosch had some good ideas: + /// + /// "Efficient and Comfortable Error Recovery in Recursive Descent + /// Parsers": + /// ftp://www.cocolab.com/products/cocktail/doca4.ps/ell.ps.zip + /// + /// Like Grosch I implement context-sensitive FOLLOW sets that are combined + /// at run-time upon error to avoid overhead during parsing. internal func getErrorRecoverySet(_ recognizer: Parser) throws -> IntervalSet { let atn: ATN = recognizer.getInterpreter().atn var ctx: RuleContext? = recognizer._ctx @@ -731,7 +688,7 @@ public class DefaultErrorStrategy: ANTLRErrorStrategy { 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 { // errPrint("consumeUntil("+set.toString(recognizer.getTokenNames())+")"); var ttype: Int = try getTokenStream(recognizer).LA(1) diff --git a/runtime/Swift/Sources/Antlr4/DiagnosticErrorListener.swift b/runtime/Swift/Sources/Antlr4/DiagnosticErrorListener.swift index 4d0daab67..e00702891 100644 --- a/runtime/Swift/Sources/Antlr4/DiagnosticErrorListener.swift +++ b/runtime/Swift/Sources/Antlr4/DiagnosticErrorListener.swift @@ -1,54 +1,45 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** -* This implementation of {@link org.antlr.v4.runtime.ANTLRErrorListener} can be used to identify -* certain potential correctness and performance problems in grammars. "Reports" -* are made by calling {@link org.antlr.v4.runtime.Parser#notifyErrorListeners} with the appropriate -* message. -* -*
            -*
          • Ambiguities: These are cases where more than one path through the -* grammar can match the input.
          • -*
          • Weak context sensitivity: These are cases where full-context -* prediction resolved an SLL conflict to a unique alternative which equaled the -* minimum alternative of the SLL conflict.
          • -*
          • Strong (forced) context sensitivity: These are cases where the -* full-context prediction resolved an SLL conflict to a unique alternative, -* and the minimum alternative of the SLL conflict was found to not be -* a truly viable alternative. Two-stage parsing cannot be used for inputs where -* this situation occurs.
          • -*
          -* -* @author Sam Harwell -*/ +/// This implementation of {@link org.antlr.v4.runtime.ANTLRErrorListener} can be used to identify +/// certain potential correctness and performance problems in grammars. "Reports" +/// are made by calling {@link org.antlr.v4.runtime.Parser#notifyErrorListeners} with the appropriate +/// message. +/// +///
            +///
          • Ambiguities: These are cases where more than one path through the +/// grammar can match the input.
          • +///
          • Weak context sensitivity: These are cases where full-context +/// prediction resolved an SLL conflict to a unique alternative which equaled the +/// minimum alternative of the SLL conflict.
          • +///
          • Strong (forced) context sensitivity: These are cases where the +/// full-context prediction resolved an SLL conflict to a unique alternative, +/// and the minimum alternative of the SLL conflict was found to not be +/// a truly viable alternative. Two-stage parsing cannot be used for inputs where +/// this situation occurs.
          • +///
          +/// +/// - Sam Harwell import Foundation public class DiagnosticErrorListener: BaseErrorListener { - /** - * When {@code true}, only exactly known ambiguities are reported. - */ + /// When {@code true}, only exactly known ambiguities are reported. internal final var exactOnly: Bool - /** - * Initializes a new instance of {@link org.antlr.v4.runtime.DiagnosticErrorListener} which only - * reports exact ambiguities. - */ + /// Initializes a new instance of {@link org.antlr.v4.runtime.DiagnosticErrorListener} which only + /// reports exact ambiguities. public convenience override init() { self.init(true) } - /** - * Initializes a new instance of {@link org.antlr.v4.runtime.DiagnosticErrorListener}, specifying - * whether all ambiguities or only exact ambiguities are reported. - * - * @param exactOnly {@code true} to report only exact ambiguities, otherwise - * {@code false} to report all ambiguities. - */ + /// Initializes a new instance of {@link org.antlr.v4.runtime.DiagnosticErrorListener}, specifying + /// whether all ambiguities or only exact ambiguities are reported. + /// + /// - parameter exactOnly: {@code true} to report only exact ambiguities, otherwise + /// {@code false} to report all ambiguities. public init(_ exactOnly: Bool) { self.exactOnly = exactOnly } @@ -120,17 +111,15 @@ public class DiagnosticErrorListener: BaseErrorListener { return NSString(format: "%d (%@)", decision, ruleName) as String } - /** - * Computes the set of conflicting or ambiguous alternatives from a - * configuration set, if that information was not already provided by the - * parser. - * - * @param reportedAlts The set of conflicting or ambiguous alternatives, as - * reported by the parser. - * @param configs The conflicting or ambiguous configuration set. - * @return Returns {@code reportedAlts} if it is not {@code null}, otherwise - * returns the set of alternatives represented in {@code configs}. - */ + /// Computes the set of conflicting or ambiguous alternatives from a + /// configuration set, if that information was not already provided by the + /// parser. + /// + /// - parameter reportedAlts: The set of conflicting or ambiguous alternatives, as + /// reported by the parser. + /// - parameter configs: The conflicting or ambiguous configuration set. + /// - returns: Returns {@code reportedAlts} if it is not {@code null}, otherwise + /// returns the set of alternatives represented in {@code configs}. internal func getConflictingAlts(_ reportedAlts: BitSet?, _ configs: ATNConfigSet) throws -> BitSet { if reportedAlts != nil { return reportedAlts! diff --git a/runtime/Swift/Sources/Antlr4/FailedPredicateException.swift b/runtime/Swift/Sources/Antlr4/FailedPredicateException.swift index 5dc761848..f86273d81 100644 --- a/runtime/Swift/Sources/Antlr4/FailedPredicateException.swift +++ b/runtime/Swift/Sources/Antlr4/FailedPredicateException.swift @@ -1,14 +1,12 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** A semantic predicate failed during validation. Validation of predicates - * occurs when normally parsing the alternative just like matching a token. - * Disambiguating predicate evaluation occurs when we test a predicate during - * prediction. - */ +/// A semantic predicate failed during validation. Validation of predicates +/// occurs when normally parsing the alternative just like matching a token. +/// Disambiguating predicate evaluation occurs when we test a predicate during +/// prediction. public class FailedPredicateException: RecognitionException { private final var ruleIndex: Int private final var predicateIndex: Int diff --git a/runtime/Swift/Sources/Antlr4/InputMismatchException.swift b/runtime/Swift/Sources/Antlr4/InputMismatchException.swift index 69ec3d93f..e23ed66fd 100644 --- a/runtime/Swift/Sources/Antlr4/InputMismatchException.swift +++ b/runtime/Swift/Sources/Antlr4/InputMismatchException.swift @@ -1,12 +1,10 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** This signifies any kind of mismatched input exceptions such as - * when the current input does not match the expected token. - */ +/// This signifies any kind of mismatched input exceptions such as +/// when the current input does not match the expected token. public class InputMismatchException: RecognitionException { public init(_ recognizer: Parser) throws { diff --git a/runtime/Swift/Sources/Antlr4/IntStream.swift b/runtime/Swift/Sources/Antlr4/IntStream.swift index 8a684131a..20421a8a7 100644 --- a/runtime/Swift/Sources/Antlr4/IntStream.swift +++ b/runtime/Swift/Sources/Antlr4/IntStream.swift @@ -1,216 +1,193 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * A simple stream of symbols whose values are represented as integers. This - * interface provides marked ranges with support for a minimum level - * of buffering necessary to implement arbitrary lookahead during prediction. - * For more information on marked ranges, see {@link #mark}. - * - *

          Initializing Methods: Some methods in this interface have - * unspecified behavior if no call to an initializing method has occurred after - * the stream was constructed. The following is a list of initializing methods:

          - * - *
            - *
          • {@link #LA}
          • - *
          • {@link #consume}
          • - *
          • {@link #size}
          • - *
          - */ +/// A simple stream of symbols whose values are represented as integers. This +/// interface provides marked ranges with support for a minimum level +/// of buffering necessary to implement arbitrary lookahead during prediction. +/// For more information on marked ranges, see {@link #mark}. +/// +///

          Initializing Methods: Some methods in this interface have +/// unspecified behavior if no call to an initializing method has occurred after +/// the stream was constructed. The following is a list of initializing methods:

          +/// +///
            +///
          • {@link #LA}
          • +///
          • {@link #consume}
          • +///
          • {@link #size}
          • +///
          public protocol IntStream: class { - /** - * The value returned by {@link #LA LA()} when the end of the stream is - * reached. - */ + /// The value returned by {@link #LA LA()} when the end of the stream is + /// reached. //let EOF : Int = -1; - /** - * The value returned by {@link #getSourceName} when the actual name of the - * underlying source is not known. - */ + /// The value returned by {@link #getSourceName} when the actual name of the + /// underlying source is not known. //let UNKNOWN_SOURCE_NAME : String = ""; - /** - * Consumes the current symbol in the stream. This method has the following - * effects: - * - *
            - *
          • Forward movement: The value of {@link #index index()} - * before calling this method is less than the value of {@code index()} - * after calling this method.
          • - *
          • Ordered lookahead: The value of {@code LA(1)} before - * calling this method becomes the value of {@code LA(-1)} after calling - * this method.
          • - *
          - * - * Note that calling this method does not guarantee that {@code index()} is - * incremented by exactly 1, as that would preclude the ability to implement - * filtering streams (e.g. {@link org.antlr.v4.runtime.CommonTokenStream} which distinguishes - * between "on-channel" and "off-channel" tokens). - * - * @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 - * {@code consume}). - */ + /// Consumes the current symbol in the stream. This method has the following + /// effects: + /// + ///
            + ///
          • Forward movement: The value of {@link #index index()} + /// before calling this method is less than the value of {@code index()} + /// after calling this method.
          • + ///
          • Ordered lookahead: The value of {@code LA(1)} before + /// calling this method becomes the value of {@code LA(-1)} after calling + /// this method.
          • + ///
          + /// + /// Note that calling this method does not guarantee that {@code index()} is + /// incremented by exactly 1, as that would preclude the ability to implement + /// filtering streams (e.g. {@link org.antlr.v4.runtime.CommonTokenStream} which distinguishes + /// between "on-channel" and "off-channel" tokens). + /// + /// - 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 + /// {@code consume}). func consume() throws - /** - * 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 - * 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 - * symbol in the stream. It is not valid to call this method with - * {@code i==0}, but the specific behavior is unspecified because this - * method is frequently called from performance-critical code. - * - *

          This method is guaranteed to succeed if any of the following are true:

          - * - *
            - *
          • {@code i>0}
          • - *
          • {@code i==-1} and {@link #index index()} returns a value greater - * than the value of {@code index()} after the stream was constructed - * and {@code LA(1)} was called in that order. Specifying the current - * {@code index()} relative to the index after the stream was created - * allows for filtering implementations that do not return every symbol - * from the underlying source. Specifying the call to {@code LA(1)} - * allows for lazily initialized streams.
          • - *
          • {@code LA(i)} refers to a symbol consumed within a marked region - * that has not yet been released.
          • - *
          - * - *

          If {@code i} represents a position at or beyond the end of the stream, - * this method returns {@link #EOF}.

          - * - *

          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 - * the stream before calling this method.

          - * - * @throws UnsupportedOperationException if the stream does not support - * retrieving the value of the specified symbol - */ + /// 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 + /// 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 + /// symbol in the stream. It is not valid to call this method with + /// {@code i==0}, but the specific behavior is unspecified because this + /// method is frequently called from performance-critical code. + /// + ///

          This method is guaranteed to succeed if any of the following are true:

          + /// + ///
            + ///
          • {@code i>0}
          • + ///
          • {@code i==-1} and {@link #index index()} returns a value greater + /// than the value of {@code index()} after the stream was constructed + /// and {@code LA(1)} was called in that order. Specifying the current + /// {@code index()} relative to the index after the stream was created + /// allows for filtering implementations that do not return every symbol + /// from the underlying source. Specifying the call to {@code LA(1)} + /// allows for lazily initialized streams.
          • + ///
          • {@code LA(i)} refers to a symbol consumed within a marked region + /// that has not yet been released.
          • + ///
          + /// + ///

          If {@code i} represents a position at or beyond the end of the stream, + /// this method returns {@link #EOF}.

          + /// + ///

          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 + /// the stream before calling this method.

          + /// + /// - UnsupportedOperationException if the stream does not support + /// retrieving the value of the specified symbol func LA(_ i: Int) throws -> Int - /** - * A mark provides a guarantee that {@link #seek seek()} operations will be - * 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 - * streaming input sources by specifying the minimum buffering requirements - * to support arbitrary lookahead during prediction. - * - *

          The returned mark is an opaque handle (type {@code int}) which is passed - * to {@link #release release()} when the guarantees provided by the marked - * range are no longer necessary. When calls to - * {@code mark()}/{@code release()} are nested, the marks must be released - * in reverse order of which they were obtained. Since marked regions are - * used during performance-critical sections of prediction, the specific - * behavior of invalid usage is unspecified (i.e. a mark is not released, or - * a mark is released twice, or marks are not released in reverse order from - * which they were created).

          - * - *

          The behavior of this method is unspecified if no call to an - * {@link org.antlr.v4.runtime.IntStream initializing method} has occurred after this stream was - * constructed.

          - * - *

          This method does not change the current position in the input stream.

          - * - *

          The following example shows the use of {@link #mark mark()}, - * {@link #release release(mark)}, {@link #index index()}, and - * {@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 - * release the mark.

          - *
          -     * IntStream stream = ...;
          -     * int index = -1;
          -     * int mark = stream.mark();
          -     * try {
          -     *   index = stream.index();
          -     *   // perform work here...
          -     * } finally {
          -     *   if (index != -1) {
          -     *     stream.seek(index);
          -     *   }
          -     *   stream.release(mark);
          -     * }
          -     * 
          - * - * @return An opaque marker which should be passed to - * {@link #release release()} when the marked range is no longer required. - */ + /// A mark provides a guarantee that {@link #seek seek()} operations will be + /// 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 + /// streaming input sources by specifying the minimum buffering requirements + /// to support arbitrary lookahead during prediction. + /// + ///

          The returned mark is an opaque handle (type {@code int}) which is passed + /// to {@link #release release()} when the guarantees provided by the marked + /// range are no longer necessary. When calls to + /// {@code mark()}/{@code release()} are nested, the marks must be released + /// in reverse order of which they were obtained. Since marked regions are + /// used during performance-critical sections of prediction, the specific + /// behavior of invalid usage is unspecified (i.e. a mark is not released, or + /// a mark is released twice, or marks are not released in reverse order from + /// which they were created).

          + /// + ///

          The behavior of this method is unspecified if no call to an + /// {@link org.antlr.v4.runtime.IntStream initializing method} has occurred after this stream was + /// constructed.

          + /// + ///

          This method does not change the current position in the input stream.

          + /// + ///

          The following example shows the use of {@link #mark mark()}, + /// {@link #release release(mark)}, {@link #index index()}, and + /// {@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 + /// release the mark.

          + ///
          +    /// IntStream stream = ...;
          +    /// int index = -1;
          +    /// int mark = stream.mark();
          +    /// try {
          +    /// index = stream.index();
          +    /// // perform work here...
          +    /// } finally {
          +    /// if (index != -1) {
          +    /// stream.seek(index);
          +    /// }
          +    /// stream.release(mark);
          +    /// }
          +    /// 
          + /// + /// - returns: An opaque marker which should be passed to + /// {@link #release release()} when the marked range is no longer required. func mark() -> Int - /** - * This method releases a marked range created by a call to - * {@link #mark mark()}. Calls to {@code release()} must appear in the - * 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 - * corresponding calls to {@code mark()}, the behavior is unspecified. - * - *

          For more information and an example, see {@link #mark}.

          - * - * @param marker A marker returned by a call to {@code mark()}. - * @see #mark - */ + /// This method releases a marked range created by a call to + /// {@link #mark mark()}. Calls to {@code release()} must appear in the + /// 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 + /// corresponding calls to {@code mark()}, the behavior is unspecified. + /// + ///

          For more information and an example, see {@link #mark}.

          + /// + /// - parameter marker: A marker returned by a call to {@code mark()}. + /// - seealso: #mark func release(_ marker: Int) throws - /** - * Return the index into the stream of the input symbol referred to by - * {@code LA(1)}. - * - *

          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 - * constructed.

          - */ + /// Return the index into the stream of the input symbol referred to by + /// {@code LA(1)}. + /// + ///

          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 + /// constructed.

          func index() -> Int - /** - * 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 - * 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 - * will be true. - * - *
            - *
          • {@link #index index()} will return the index of the first symbol - * appearing at or after the specified {@code index}. Specifically, - * implementations which filter their sources should automatically - * adjust {@code index} forward the minimum amount required for the - * operation to target a non-ignored symbol.
          • - *
          • {@code LA(1)} returns {@link #EOF}
          • - *
          - * - * This operation is guaranteed to not throw an exception if {@code index} - * 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 - * an {@link org.antlr.v4.runtime.IntStream initializing method} has occurred after this stream - * was constructed. - * - * @param index The absolute index to seek to. - * - * @throws IllegalArgumentException if {@code index} is less than 0 - * @throws UnsupportedOperationException if the stream does not support - * seeking to the specified index - */ + /// 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 + /// 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 + /// will be true. + /// + ///
            + ///
          • {@link #index index()} will return the index of the first symbol + /// appearing at or after the specified {@code index}. Specifically, + /// implementations which filter their sources should automatically + /// adjust {@code index} forward the minimum amount required for the + /// operation to target a non-ignored symbol.
          • + ///
          • {@code LA(1)} returns {@link #EOF}
          • + ///
          + /// + /// This operation is guaranteed to not throw an exception if {@code index} + /// 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 + /// an {@link org.antlr.v4.runtime.IntStream initializing method} has occurred after this stream + /// was constructed. + /// + /// - parameter index: The absolute index to seek to. + /// + /// - IllegalArgumentException if {@code index} is less than 0 + /// - UnsupportedOperationException if the stream does not support + /// seeking to the specified index func seek(_ index: Int) throws - /** - * Returns the total number of symbols in the stream, including a single EOF - * symbol. - * - * @throws UnsupportedOperationException if the size of the stream is - * unknown. - */ + /// Returns the total number of symbols in the stream, including a single EOF + /// symbol. + /// + /// - UnsupportedOperationException if the size of the stream is + /// unknown. func size() -> Int - /** - * Gets the name of the underlying symbol source. This method returns a - * non-null, non-empty string. If such a name is not known, this method - * returns {@link #UNKNOWN_SOURCE_NAME}. - */ + /// Gets the name of the underlying symbol source. This method returns a + /// non-null, non-empty string. If such a name is not known, this method + /// returns {@link #UNKNOWN_SOURCE_NAME}. func getSourceName() -> String } diff --git a/runtime/Swift/Sources/Antlr4/InterpreterRuleContext.swift b/runtime/Swift/Sources/Antlr4/InterpreterRuleContext.swift index 7346a31ae..bd910a532 100644 --- a/runtime/Swift/Sources/Antlr4/InterpreterRuleContext.swift +++ b/runtime/Swift/Sources/Antlr4/InterpreterRuleContext.swift @@ -1,38 +1,33 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * This class extends {@link org.antlr.v4.runtime.ParserRuleContext} by allowing the value of - * {@link #getRuleIndex} to be explicitly set for the context. - * - *

          - * {@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 - * {@link #getRuleIndex} method to return the correct value for that context. - * 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 - * provide equivalent functionality.

          - */ +/// This class extends {@link org.antlr.v4.runtime.ParserRuleContext} by allowing the value of +/// {@link #getRuleIndex} to be explicitly set for the context. +/// +///

          +/// {@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 +/// {@link #getRuleIndex} method to return the correct value for that context. +/// 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 +/// provide equivalent functionality.

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

          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 - * list is reached. Otherwise, an EOF token will be created.

          - */ +/// Provides an implementation of {@link org.antlr.v4.runtime.TokenSource} as a wrapper around a list +/// of {@link org.antlr.v4.runtime.Token} objects. +/// +///

          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 +/// list is reached. Otherwise, an EOF token will be created.

          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 - /** - * 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 - * the next token in {@link #tokens} (or the previous token if the end of - * the input has been reached). - */ + /// 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 + /// the next token in {@link #tokens} (or the previous token if the end of + /// the input has been reached). private final var sourceName: String? - /** - * 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 - * being greater than or equal to the number of items in {@link #tokens}. - */ + /// 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 + /// being greater than or equal to the number of items in {@link #tokens}. 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? - /** - * This is the backing field for {@link #getTokenFactory} and - * {@link setTokenFactory}. - */ + /// This is the backing field for {@link #getTokenFactory} and + /// {@link setTokenFactory}. private var _factory: TokenFactory = CommonTokenFactory.DEFAULT - /** - * Constructs a new {@link org.antlr.v4.runtime.ListTokenSource} instance from the specified - * collection of {@link org.antlr.v4.runtime.Token} objects. - * - * @param tokens The collection of {@link org.antlr.v4.runtime.Token} objects to provide as a - * {@link org.antlr.v4.runtime.TokenSource}. - * @exception NullPointerException if {@code tokens} is {@code null} - */ + /// Constructs a new {@link org.antlr.v4.runtime.ListTokenSource} instance from the specified + /// 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 + /// {@link org.antlr.v4.runtime.TokenSource}. + /// - NullPointerException if {@code tokens} is {@code null} public convenience init(_ tokens: Array) { self.init(tokens, nil) } - /** - * 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. - * - * @param tokens The collection of {@link org.antlr.v4.runtime.Token} objects to provide as a - * {@link org.antlr.v4.runtime.TokenSource}. - * @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 - * the next {@link org.antlr.v4.runtime.Token} (or the previous token if the end of the input has - * been reached). - * - * @exception NullPointerException if {@code tokens} is {@code null} - */ + /// 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. + /// + /// - parameter tokens: The collection of {@link org.antlr.v4.runtime.Token} objects to provide as a + /// {@link org.antlr.v4.runtime.TokenSource}. + /// - parameter 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 + /// the next {@link org.antlr.v4.runtime.Token} (or the previous token if the end of the input has + /// been reached). + /// + /// - NullPointerException if {@code tokens} is {@code null} public init(_ tokens: Array, _ sourceName: String?) { self.tokens = tokens self.sourceName = sourceName } - /** - * {@inheritDoc} - */ + /// {@inheritDoc} public func getCharPositionInLine() -> Int { if i < tokens.count { @@ -111,9 +92,7 @@ public class ListTokenSource: TokenSource { return 0 } - /** - * {@inheritDoc} - */ + /// {@inheritDoc} public func nextToken() -> Token { if i >= tokens.count { @@ -142,9 +121,7 @@ public class ListTokenSource: TokenSource { return t } - /** - * {@inheritDoc} - */ + /// {@inheritDoc} public func getLine() -> Int { if i < tokens.count { @@ -179,9 +156,7 @@ public class ListTokenSource: TokenSource { return 1 } - /** - * {@inheritDoc} - */ + /// {@inheritDoc} public func getInputStream() -> CharStream? { if i < tokens.count { @@ -200,9 +175,7 @@ public class ListTokenSource: TokenSource { return nil } - /** - * {@inheritDoc} - */ + /// {@inheritDoc} public func getSourceName() -> String { if sourceName != nil { @@ -216,17 +189,13 @@ public class ListTokenSource: TokenSource { return "List" } - /** - * {@inheritDoc} - */ + /// {@inheritDoc} public func setTokenFactory(_ factory: TokenFactory) { self._factory = factory } - /** - * {@inheritDoc} - */ + /// {@inheritDoc} public func getTokenFactory() -> TokenFactory { return _factory diff --git a/runtime/Swift/Sources/Antlr4/atn/ATN.swift b/runtime/Swift/Sources/Antlr4/atn/ATN.swift index ac45ad165..8270bfe0e 100644 --- a/runtime/Swift/Sources/Antlr4/atn/ATN.swift +++ b/runtime/Swift/Sources/Antlr4/atn/ATN.swift @@ -1,7 +1,6 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. public class ATN { @@ -10,75 +9,59 @@ public class ATN { public final var states: Array = Array() - /** Each subrule/rule is a decision point and we must track them so we - * can go back later and build DFA predictors for them. This includes - * all the rules, subrules, optional blocks, ()+, ()* etc... - */ + /// Each subrule/rule is a decision point and we must track them so we + /// can go back later and build DFA predictors for them. This includes + /// all the rules, subrules, optional blocks, ()+, ()* etc... public final var decisionToState: Array = Array() - /** - * Maps from rule index to starting state number. - */ + /// Maps from rule index to starting state number. 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 let modeNameToStartState: Dictionary = Dictionary() //LinkedHashMap(); - /** - * The type of the ATN. - */ + /// The type of the ATN. 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 - /** - * For lexer ATNs, this maps the rule index to the resulting token type. - * For parser ATNs, this maps the rule index to the generated bypass token - * type if the - * {@link org.antlr.v4.runtime.atn.ATNDeserializationOptions#isGenerateRuleBypassTransitions} - * deserialization option was specified; otherwise, this is {@code null}. - */ + /// For lexer ATNs, this maps the rule index to the resulting token type. + /// For parser ATNs, this maps the rule index to the generated bypass token + /// type if the + /// {@link org.antlr.v4.runtime.atn.ATNDeserializationOptions#isGenerateRuleBypassTransitions} + /// deserialization option was specified; otherwise, this is {@code null}. public final var ruleToTokenType: [Int]! - /** - * 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. - */ + /// 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. public final var lexerActions: [LexerAction]! public final var modeToStartState: Array = Array() - /** Used for runtime deserialization of ATNs from strings */ + /// Used for runtime deserialization of ATNs from strings public init(_ grammarType: ATNType, _ maxTokenType: Int) { self.grammarType = grammarType self.maxTokenType = maxTokenType } - /** Compute the set of valid tokens that can occur starting in state {@code s}. - * 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 - * restricted to tokens reachable staying within {@code s}'s rule. - */ + /// 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 + /// the rule surrounding {@code s}. In other words, the set will be + /// restricted to tokens reachable staying within {@code s}'s rule. public func nextTokens(_ s: ATNState, _ ctx: RuleContext?)throws -> IntervalSet { let anal: LL1Analyzer = LL1Analyzer(self) let next: IntervalSet = try anal.LOOK(s, ctx) return next } - /** - * 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 - * rule. - */ + /// 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 + /// rule. public func nextTokens(_ s: ATNState) throws -> IntervalSet { if let nextTokenWithinRule = s.nextTokenWithinRule { @@ -121,29 +104,27 @@ public class ATN { return decisionToState.count } - /** - * Computes the set of input symbols which could follow ATN state number - * {@code stateNumber} in the specified full {@code context}. This method - * considers the complete parser context, but does not evaluate semantic - * predicates (i.e. all predicates encountered during the calculation are - * assumed true). If a path in the ATN exists from the starting state to the - * {@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. - * - *

          If {@code context} is {@code null}, it is treated as - * {@link org.antlr.v4.runtime.ParserRuleContext#EMPTY}.

          - * - * @param stateNumber the ATN state number - * @param context the full parse context - * @return The set of potentially valid input symbols which could follow the - * specified state in the specified context. - * @throws IllegalArgumentException if the ATN does not contain a state with - * number {@code stateNumber} - */ + /// Computes the set of input symbols which could follow ATN state number + /// {@code stateNumber} in the specified full {@code context}. This method + /// considers the complete parser context, but does not evaluate semantic + /// predicates (i.e. all predicates encountered during the calculation are + /// assumed true). If a path in the ATN exists from the starting state to the + /// {@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. + /// + ///

          If {@code context} is {@code null}, it is treated as + /// {@link org.antlr.v4.runtime.ParserRuleContext#EMPTY}.

          + /// + /// - parameter stateNumber: the ATN state number + /// - parameter context: the full parse context + /// - returns: The set of potentially valid input symbols which could follow the + /// specified state in the specified context. + /// - IllegalArgumentException if the ATN does not contain a state with + /// number {@code stateNumber} public func getExpectedTokens(_ stateNumber: Int, _ context: RuleContext) throws -> IntervalSet { if stateNumber < 0 || stateNumber >= states.count { throw ANTLRError.illegalArgument(msg: "Invalid state number.") - /* throw IllegalArgumentException("Invalid state number."); */ + /// throw IllegalArgumentException("Invalid state number."); } var ctx: RuleContext? = context diff --git a/runtime/Swift/Sources/Antlr4/atn/ATNConfig.swift b/runtime/Swift/Sources/Antlr4/atn/ATNConfig.swift index 08e88620a..e2ffa432f 100644 --- a/runtime/Swift/Sources/Antlr4/atn/ATNConfig.swift +++ b/runtime/Swift/Sources/Antlr4/atn/ATNConfig.swift @@ -1,60 +1,53 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** A tuple: (ATN state, predicted alt, syntactic, semantic context). - * The syntactic context is a graph-structured stack node whose - * path(s) to the root is the rule invocation(s) - * chain used to arrive at the state. The semantic context is - * the tree of semantic predicates encountered before reaching - * an ATN state. - */ +/// A tuple: (ATN state, predicted alt, syntactic, semantic context). +/// The syntactic context is a graph-structured stack node whose +/// path(s) to the root is the rule invocation(s) +/// chain used to arrive at the state. The semantic context is +/// the tree of semantic predicates encountered before reaching +/// an ATN state. public class ATNConfig: Hashable, CustomStringConvertible { - /** - * This field stores the bit mask for implementing the - * {@link #isPrecedenceFilterSuppressed} property as a bit within the - * existing {@link #reachesIntoOuterContext} field. - */ + /// This field stores the bit mask for implementing the + /// {@link #isPrecedenceFilterSuppressed} property as a bit within the + /// existing {@link #reachesIntoOuterContext} field. 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 - /** 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 - /** The stack of invoking states leading to the rule/states associated - * with this config. We track only those contexts pushed during - * execution of the ATN simulator. - */ + /// The stack of invoking states leading to the rule/states associated + /// with this config. We track only those contexts pushed during + /// execution of the ATN simulator. public final var context: PredictionContext? - /** - * We cannot execute predicates dependent upon local context unless - * we know for sure we are in the correct context. Because there is - * no way to do this efficiently, we simply cannot evaluate - * dependent predicates unless we are in the rule that initially - * invokes the ATN simulator. - * - *

          - * closure() tracks the depth of how far we dip into the outer context: - * depth > 0. Note that it may not be totally accurate depth since I - * don't ever decrement. TODO: make it a boolean then

          - * - *

          - * For memory efficiency, the {@link #isPrecedenceFilterSuppressed} method - * 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 - * 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 - * flag. It also ensures the performance of the existing {@link org.antlr.v4.runtime.atn.ATNConfig} - * constructors as well as certain operations like - * {@link org.antlr.v4.runtime.atn.ATNConfigSet#add(org.antlr.v4.runtime.atn.ATNConfig, DoubleKeyMap)} method are - * completely unaffected by the change.

          - */ + /// We cannot execute predicates dependent upon local context unless + /// we know for sure we are in the correct context. Because there is + /// no way to do this efficiently, we simply cannot evaluate + /// dependent predicates unless we are in the rule that initially + /// invokes the ATN simulator. + /// + ///

          + /// closure() tracks the depth of how far we dip into the outer context: + /// depth > 0. Note that it may not be totally accurate depth since I + /// don't ever decrement. TODO: make it a boolean then

          + /// + ///

          + /// For memory efficiency, the {@link #isPrecedenceFilterSuppressed} method + /// 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 + /// 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 + /// flag. It also ensures the performance of the existing {@link org.antlr.v4.runtime.atn.ATNConfig} + /// constructors as well as certain operations like + /// {@link org.antlr.v4.runtime.atn.ATNConfigSet#add(org.antlr.v4.runtime.atn.ATNConfig, DoubleKeyMap)} method are + /// completely unaffected by the change.

          public final var reachesIntoOuterContext: Int = 0 //=0 intital by janyou @@ -115,11 +108,9 @@ public class ATNConfig: Hashable, CustomStringConvertible { self.reachesIntoOuterContext = c.reachesIntoOuterContext } - /** - * This method gets the value of the {@link #reachesIntoOuterContext} field - * as it existed prior to the introduction of the - * {@link #isPrecedenceFilterSuppressed} method. - */ + /// This method gets the value of the {@link #reachesIntoOuterContext} field + /// as it existed prior to the introduction of the + /// {@link #isPrecedenceFilterSuppressed} method. public final func getOuterContextDepth() -> Int { return reachesIntoOuterContext & ~SUPPRESS_PRECEDENCE_FILTER } @@ -136,10 +127,9 @@ public class ATNConfig: Hashable, CustomStringConvertible { } } - /** An ATN configuration is equal to another if both have - * the same state, they predict the same alternative, and - * syntactic/semantic contexts are the same. - */ + /// An ATN configuration is equal to another if both have + /// the same state, they predict the same alternative, and + /// syntactic/semantic contexts are the same. public var hashValue: Int { var hashCode: Int = MurmurHash.initialize(7) @@ -197,9 +187,9 @@ public func ==(lhs: ATNConfig, rhs: ATNConfig) -> Bool { return true } //TODO : rhs nil? - /*else { if (other == nil) { - return false; - } }*/ + /// else { if (other == nil) { + /// return false; + /// } if (lhs is LexerATNConfig) && (rhs is LexerATNConfig) { return (lhs as! LexerATNConfig) == (rhs as! LexerATNConfig) diff --git a/runtime/Swift/Sources/Antlr4/atn/ATNConfigSet.swift b/runtime/Swift/Sources/Antlr4/atn/ATNConfigSet.swift index fe02ba151..0c8e58c85 100644 --- a/runtime/Swift/Sources/Antlr4/atn/ATNConfigSet.swift +++ b/runtime/Swift/Sources/Antlr4/atn/ATNConfigSet.swift @@ -1,52 +1,43 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** -* 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 -* graph-structured stack. -*/ +/// 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 +/// graph-structured stack. //: Set public class ATNConfigSet: Hashable, CustomStringConvertible { - /** - * 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 - * {@code (s,i,_,semctx)} to be equal. Unfortunately, this key effectively doubles - * the number of objects associated with ATNConfigs. The other solution is to - * use a hash table that lets us specify the equals/hashcode operation. - */ + /// 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 + /// {@code (s,i,_,semctx)} to be equal. Unfortunately, this key effectively doubles + /// the number of objects associated with ATNConfigs. The other solution is to + /// use a hash table that lets us specify the equals/hashcode operation. - /** Indicates that the set of configurations is read-only. Do not - * 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 - * fields; in particular, conflictingAlts is set after - * we've made this readonly. - */ + /// Indicates that the set of configurations is read-only. Do not + /// 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 + /// fields; in particular, conflictingAlts is set after + /// we've made this readonly. internal final var readonly: Bool = false - /** - * All configs but hashed by (s, i, _, pi) not including context. Wiped out - * when we go readonly as this set becomes a DFA state. - */ + /// All configs but hashed by (s, i, _, pi) not including context. Wiped out + /// when we go readonly as this set becomes a DFA state. 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 = Array() // 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? public final var uniqueAlt: Int = 0 //TODO no default - /** Currently this is only used when we detect SLL conflict; this does - * not necessarily represent the ambiguous alternatives. In fact, - * I should also point out that this seems to include predicated alternatives - * that have predicates that evaluate to false. Computed in computeTargetState(). - */ + /// Currently this is only used when we detect SLL conflict; this does + /// not necessarily represent the ambiguous alternatives. In fact, + /// I should also point out that this seems to include predicated alternatives + /// that have predicates that evaluate to false. Computed in computeTargetState(). internal final var conflictingAlts: BitSet? // 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 //TODO no default - /** Indicates that this configuration set is part of a full context - * 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. - */ + /// Indicates that this configuration set is part of a full context + /// 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. public final var fullCtx: Bool private var cachedHashCode: Int = -1 @@ -88,16 +78,14 @@ public class ATNConfigSet: Hashable, CustomStringConvertible { return try add(config, &mergeCache) } - /** - * Adding a new config means merging contexts with existing configs for - * {@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 - * {@code pi} is the {@link org.antlr.v4.runtime.atn.ATNConfig#semanticContext}. We use - * {@code (s,i,pi)} as key. - * - *

          This method updates {@link #dipsIntoOuterContext} and - * {@link #hasSemanticContext} when necessary.

          - */ + /// Adding a new config means merging contexts with existing configs for + /// {@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 + /// {@code pi} is the {@link org.antlr.v4.runtime.atn.ATNConfig#semanticContext}. We use + /// {@code (s,i,pi)} as key. + /// + ///

          This method updates {@link #dipsIntoOuterContext} and + /// {@link #hasSemanticContext} when necessary.

          @discardableResult public final func add( _ 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 { return configs } @@ -162,14 +150,12 @@ public class ATNConfigSet: Hashable, CustomStringConvertible { return states } - /** - * Gets the complete set of represented alternatives for the configuration - * set. - * - * @return the set of represented alternatives in this configuration set - * - * @since 4.3 - */ + /// Gets the complete set of represented alternatives for the configuration + /// set. + /// + /// - returns: the set of represented alternatives in this configuration set + /// + /// - 4.3 public final func getAlts() throws -> BitSet { let alts: BitSet = BitSet() @@ -310,10 +296,9 @@ public class ATNConfigSet: Hashable, CustomStringConvertible { // return Array( configLookup.map{$0.config}) ; // } - /*override - public func toArray(a : [T]) -> [T] { - return configLookup.toArray(a); - }*/ + /// override + /// public func toArray(a : [T]) -> [T] { + /// return configLookup.toArray(a); private final func configHash(_ stateNumber: Int,_ context: PredictionContext?) -> Int{ var hashCode: Int = MurmurHash.initialize(7) @@ -471,10 +456,9 @@ public class ATNConfigSet: Hashable, CustomStringConvertible { } if !configs[i].isPrecedenceFilterSuppressed() { - /* In the future, this elimination step could be updated to also - * filter the prediction context for alternatives predicting alt>1 - * (basically a graph subtraction algorithm). - */ + /// In the future, this elimination step could be updated to also + /// filter the prediction context for alternatives predicting alt>1 + /// (basically a graph subtraction algorithm). let context: PredictionContext? = statesFromAlt1[configs[i].state.stateNumber] if context != nil && context == configs[i].context { // eliminated @@ -537,15 +521,14 @@ public class ATNConfigSet: Hashable, CustomStringConvertible { return alts.getMinElement() } - /** Walk the list of configurations and split them according to - * those that have preds evaluating to true/false. If no pred, assume - * true pred and include in succeeded set. Returns Pair of sets. - * - * Create a new set so as not to alter the incoming parameter. - * - * Assumption: the input stream has been restored to the starting point - * prediction, which is where predicates need to evaluate. - */ + /// Walk the list of configurations and split them according to + /// those that have preds evaluating to true/false. If no pred, assume + /// true pred and include in succeeded set. Returns Pair of sets. + /// + /// Create a new set so as not to alter the incoming parameter. + /// + /// Assumption: the input stream has been restored to the starting point + /// prediction, which is where predicates need to evaluate. public final func splitAccordingToSemanticValidity( _ outerContext: ParserRuleContext, _ evalSemanticContext:( SemanticContext,ParserRuleContext,Int,Bool) throws -> Bool) throws -> (ATNConfigSet, ATNConfigSet) { diff --git a/runtime/Swift/Sources/Antlr4/atn/ATNDeserializationOptions.swift b/runtime/Swift/Sources/Antlr4/atn/ATNDeserializationOptions.swift index f42d9e45d..f0c0d9054 100644 --- a/runtime/Swift/Sources/Antlr4/atn/ATNDeserializationOptions.swift +++ b/runtime/Swift/Sources/Antlr4/atn/ATNDeserializationOptions.swift @@ -1,14 +1,11 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * - * @author Sam Harwell - */ +/// +/// - Sam Harwell public class ATNDeserializationOptions { diff --git a/runtime/Swift/Sources/Antlr4/atn/ATNDeserializer.swift b/runtime/Swift/Sources/Antlr4/atn/ATNDeserializer.swift index 6ab6f535f..dce134e3b 100644 --- a/runtime/Swift/Sources/Antlr4/atn/ATNDeserializer.swift +++ b/runtime/Swift/Sources/Antlr4/atn/ATNDeserializer.swift @@ -1,14 +1,11 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** -* -* @author Sam Harwell -*/ +/// +/// - Sam Harwell 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")! - /** - * This UUID indicates an extension of {@link BASE_SERIALIZED_UUID} for the - * addition of precedence predicates. - */ + /// This UUID indicates an extension of {@link BASE_SERIALIZED_UUID} for the + /// addition of precedence predicates. private static let ADDED_PRECEDENCE_TRANSITIONS: UUID = UUID(uuidString: "1DA0C57D-6C06-438A-9B27-10BCB3CE0F61")! - /** - * This UUID indicates an extension of {@link #ADDED_PRECEDENCE_TRANSITIONS} - * for the addition of lexer actions encoded as a sequence of - * {@link org.antlr.v4.runtime.atn.LexerAction} instances. - */ + /// This UUID indicates an extension of {@link #ADDED_PRECEDENCE_TRANSITIONS} + /// for the addition of lexer actions encoded as a sequence of + /// {@link org.antlr.v4.runtime.atn.LexerAction} instances. 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 - * the feature first appeared in this branch. - */ + /// This list contains all of the currently supported UUIDs, ordered by when + /// the feature first appeared in this branch. private static let SUPPORTED_UUIDS: Array = { var suuid = Array() 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 = { // SERIALIZED_UUID = ADDED_LEXER_ACTIONS; 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 - * a particular feature, identified by the {@link java.util.UUID} used for serializing - * the ATN at the time the feature was first introduced. - * - * @param feature The {@link java.util.UUID} marking the first time the feature was - * supported in the serialized ATN. - * @param actualUuid The {@link java.util.UUID} of the actual serialized ATN which is - * currently being deserialized. - * @return {@code true} if the {@code actualUuid} value represents a - * serialized ATN at or after the feature identified by {@code feature} was - * introduced; otherwise, {@code false}. - */ + /// Determines if a particular serialized representation of an ATN supports + /// a particular feature, identified by the {@link java.util.UUID} used for serializing + /// the ATN at the time the feature was first introduced. + /// + /// - parameter feature: The {@link java.util.UUID} marking the first time the feature was + /// supported in the serialized ATN. + /// - parameter actualUuid: The {@link java.util.UUID} of the actual serialized ATN which is + /// currently being deserialized. + /// - returns: {@code true} if the {@code actualUuid} value represents a + /// serialized ATN at or after the feature identified by {@code feature} was + /// introduced; otherwise, {@code false}. internal func isFeatureSupported(_ feature: UUID, _ actualUuid: UUID) -> Bool { let featureIndex: Int = ATNDeserializer.SUPPORTED_UUIDS.index(of: feature)! 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 - * the {@link org.antlr.v4.runtime.atn.StarLoopEntryState#precedenceRuleDecision} field to the - * correct value. - * - * @param atn The ATN. - */ + /// 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 + /// correct value. + /// + /// - parameter atn: The ATN. internal func markPrecedenceDecisions(_ atn: ATN) { for state: ATNState? in atn.states { if let state = state as? StarLoopEntryState { - /* We analyze the ATN to determine if this ATN decision state is the - * decision for the closure block that determines whether a - * precedence rule should continue or complete. - */ + /// We analyze the ATN to determine if this ATN decision state is the + /// decision for the closure block that determines whether a + /// precedence rule should continue or complete. if let stateRuleIndex = state.ruleIndex { if atn.ruleToStartState[stateRuleIndex].isPrecedenceRule { let maybeLoopEndState: ATNState = state.transition(state.getNumberOfTransitions() - 1).target diff --git a/runtime/Swift/Sources/Antlr4/atn/ATNSimulator.swift b/runtime/Swift/Sources/Antlr4/atn/ATNSimulator.swift index c079516fe..4474e1c0a 100644 --- a/runtime/Swift/Sources/Antlr4/atn/ATNSimulator.swift +++ b/runtime/Swift/Sources/Antlr4/atn/ATNSimulator.swift @@ -1,30 +1,25 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. import Foundation open class ATNSimulator { - /** - * @deprecated Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#SERIALIZED_VERSION} instead. - */ + /// - Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#SERIALIZED_VERSION} instead. public static let SERIALIZED_VERSION: Int = { return ATNDeserializer.SERIALIZED_VERSION }() - /** - * This is the current serialized UUID. - * @deprecated Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#checkCondition(boolean)} instead. - */ + /// This is the current serialized UUID. + /// - Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#checkCondition(boolean)} instead. public static let SERIALIZED_UUID: 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 = { let error = DFAState(ATNConfigSet()) @@ -34,26 +29,25 @@ open class ATNSimulator { public var atn: ATN - /** The context cache maps all PredictionContext objects that are equals() - * to a single cached copy. This cache is shared across all contexts - * in all ATNConfigs in all DFA states. We rebuild each ATNConfigSet - * to use only cached nodes/graphs in addDFAState(). We don't want to - * 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(). - * - *

          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 - * 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, - * 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 - * by literally rebuilding them with cached subgraphs only.

          - * - *

          I tried a cache for use during closure operations, that was - * whacked after each adaptivePredict(). It cost a little bit - * more time I think and doesn't save on the overall footprint - * so it's not worth the complexity.

          - */ + /// The context cache maps all PredictionContext objects that are equals() + /// to a single cached copy. This cache is shared across all contexts + /// in all ATNConfigs in all DFA states. We rebuild each ATNConfigSet + /// to use only cached nodes/graphs in addDFAState(). We don't want to + /// 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(). + /// + ///

          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 + /// 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, + /// 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 + /// by literally rebuilding them with cached subgraphs only.

          + /// + ///

          I tried a cache for use during closure operations, that was + /// whacked after each adaptivePredict(). It cost a little bit + /// more time I think and doesn't save on the overall footprint + /// so it's not worth the complexity.

          internal final var sharedContextCache: PredictionContextCache? //static; { @@ -72,17 +66,15 @@ open class ATNSimulator { RuntimeException(" must overriden ") } - /** - * 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 - * performance (but not accuracy) of other parsers which are being used - * concurrently. - * - * @throws UnsupportedOperationException if the current instance does not - * support clearing the DFA. - * - * @since 4.3 - */ + /// 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 + /// performance (but not accuracy) of other parsers which are being used + /// concurrently. + /// + /// - UnsupportedOperationException if the current instance does not + /// support clearing the DFA. + /// + /// - 4.3 open func clearDFA() throws { throw ANTLRError.unsupportedOperation(msg: "This ATN simulator does not support clearing the DFA. ") } @@ -107,65 +99,49 @@ open class ATNSimulator { //} } - /** - * @deprecated Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#deserialize} instead. - */ + /// - Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#deserialize} instead. ////@Deprecated public static func deserialize(_ data: [Character]) throws -> ATN { return try ATNDeserializer().deserialize(data) } - /** - * @deprecated Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#checkCondition(boolean)} instead. - */ + /// - Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#checkCondition(boolean)} instead. ////@Deprecated public static func checkCondition(_ condition: Bool) throws { try ATNDeserializer().checkCondition(condition) } - /** - * @deprecated Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#checkCondition(boolean, String)} instead. - */ + /// - Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#checkCondition(boolean, String)} instead. ////@Deprecated public static func checkCondition(_ condition: Bool, _ message: String) throws { try ATNDeserializer().checkCondition(condition, message) } - /** - * @deprecated Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#toInt} instead. - */ + /// - Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#toInt} instead. ////@Deprecated public func toInt(_ c: Character) -> Int { return toInt(c) } - /** - * @deprecated Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#toInt32} instead. - */ + /// - Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#toInt32} instead. ////@Deprecated public func toInt32(_ data: [Character], _ offset: Int) -> Int { return toInt32(data, offset) } - /** - * @deprecated Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#toLong} instead. - */ + /// - Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#toLong} instead. ////@Deprecated public func toLong(_ data: [Character], _ offset: Int) -> Int64 { return toLong(data, offset) } - /** - * @deprecated Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#toUUID} instead. - */ + /// - Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#toUUID} instead. ////@Deprecated //public class func toUUID(data : [Character], _ offset : Int) -> NSUUID { //return ATNDeserializer.toUUID(data, offset); //} - /** - * @deprecated Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#edgeFactory} instead. - */ + /// - Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#edgeFactory} instead. ////@Deprecated 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) } - /** - * @deprecated Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#stateFactory} instead. - */ + /// - Use {@link org.antlr.v4.runtime.atn.ATNDeserializer#stateFactory} instead. ////@Deprecated public static func stateFactory(_ type: Int, _ ruleIndex: Int) throws -> ATNState { return try ATNDeserializer().stateFactory(type, ruleIndex)! diff --git a/runtime/Swift/Sources/Antlr4/atn/ATNState.swift b/runtime/Swift/Sources/Antlr4/atn/ATNState.swift index b3ed0a77d..368ec8042 100644 --- a/runtime/Swift/Sources/Antlr4/atn/ATNState.swift +++ b/runtime/Swift/Sources/Antlr4/atn/ATNState.swift @@ -1,70 +1,67 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** -* The following images show the relation of states and -* {@link org.antlr.v4.runtime.atn.ATNState#transitions} for various grammar constructs. -* -*
            -* -*
          • Solid edges marked with an ε indicate a required -* {@link org.antlr.v4.runtime.atn.EpsilonTransition}.
          • -* -*
          • Dashed edges indicate locations where any transition derived from -* {@link org.antlr.v4.runtime.atn.Transition} might appear.
          • -* -*
          • 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 -* construct in one of the forms below.
          • -* -*
          • Nodes showing multiple outgoing alternatives with a {@code ...} support -* any number of alternatives (one or more). Nodes without the {@code ...} only -* support the exact number of alternatives shown in the diagram.
          • -* -*
          -* -*

          Basic Blocks

          -* -*

          Rule

          -* -* -* -*

          Block of 1 or more alternatives

          -* -* -* -*

          Greedy Loops

          -* -*

          Greedy Closure: {@code (...)*}

          -* -* -* -*

          Greedy Positive Closure: {@code (...)+}

          -* -* -* -*

          Greedy Optional: {@code (...)?}

          -* -* -* -*

          Non-Greedy Loops

          -* -*

          Non-Greedy Closure: {@code (...)*?}

          -* -* -* -*

          Non-Greedy Positive Closure: {@code (...)+?}

          -* -* -* -*

          Non-Greedy Optional: {@code (...)??}

          -* -* -*/ +/// The following images show the relation of states and +/// {@link org.antlr.v4.runtime.atn.ATNState#transitions} for various grammar constructs. +/// +///
            +/// +///
          • Solid edges marked with an ε indicate a required +/// {@link org.antlr.v4.runtime.atn.EpsilonTransition}.
          • +/// +///
          • Dashed edges indicate locations where any transition derived from +/// {@link org.antlr.v4.runtime.atn.Transition} might appear.
          • +/// +///
          • 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 +/// construct in one of the forms below.
          • +/// +///
          • Nodes showing multiple outgoing alternatives with a {@code ...} support +/// any number of alternatives (one or more). Nodes without the {@code ...} only +/// support the exact number of alternatives shown in the diagram.
          • +/// +///
          +/// +///

          Basic Blocks

          +/// +///

          Rule

          +/// +/// +/// +///

          Block of 1 or more alternatives

          +/// +/// +/// +///

          Greedy Loops

          +/// +///

          Greedy Closure: {@code (...)*}

          +/// +/// +/// +///

          Greedy Positive Closure: {@code (...)+}

          +/// +/// +/// +///

          Greedy Optional: {@code (...)?}

          +/// +/// +/// +///

          Non-Greedy Loops

          +/// +///

          Non-Greedy Closure: {@code (...)*?}

          +/// +/// +/// +///

          Non-Greedy Positive Closure: {@code (...)+?}

          +/// +/// +/// +///

          Non-Greedy Optional: {@code (...)??}

          +/// +/// public class ATNState: Hashable, CustomStringConvertible { 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 - /** Which ATN are we in? */ + /// Which ATN are we in? public final var atn: ATN? = nil public final var stateNumber: Int = INVALID_STATE_NUMBER @@ -113,11 +110,11 @@ public class ATNState: Hashable, CustomStringConvertible { 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 = Array() //Array(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? diff --git a/runtime/Swift/Sources/Antlr4/atn/ATNType.swift b/runtime/Swift/Sources/Antlr4/atn/ATNType.swift index 4d628776d..0e3a776bf 100644 --- a/runtime/Swift/Sources/Antlr4/atn/ATNType.swift +++ b/runtime/Swift/Sources/Antlr4/atn/ATNType.swift @@ -1,15 +1,12 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * Represents the type of recognizer an ATN applies to. - * - * @author Sam Harwell - */ +/// Represents the type of recognizer an ATN applies to. +/// +/// - Sam Harwell public enum ATNType: Int { diff --git a/runtime/Swift/Sources/Antlr4/atn/AbstractPredicateTransition.swift b/runtime/Swift/Sources/Antlr4/atn/AbstractPredicateTransition.swift index 5f8d98ace..21af9f555 100644 --- a/runtime/Swift/Sources/Antlr4/atn/AbstractPredicateTransition.swift +++ b/runtime/Swift/Sources/Antlr4/atn/AbstractPredicateTransition.swift @@ -1,14 +1,11 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * - * @author Sam Harwell - */ +/// +/// - Sam Harwell public class AbstractPredicateTransition: Transition { diff --git a/runtime/Swift/Sources/Antlr4/atn/ActionTransition.swift b/runtime/Swift/Sources/Antlr4/atn/ActionTransition.swift index bebe83364..64ff98fc1 100644 --- a/runtime/Swift/Sources/Antlr4/atn/ActionTransition.swift +++ b/runtime/Swift/Sources/Antlr4/atn/ActionTransition.swift @@ -1,7 +1,6 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. public final class ActionTransition: Transition, CustomStringConvertible { diff --git a/runtime/Swift/Sources/Antlr4/atn/AmbiguityInfo.swift b/runtime/Swift/Sources/Antlr4/atn/AmbiguityInfo.swift index 3e6adaa71..ae9f9b829 100644 --- a/runtime/Swift/Sources/Antlr4/atn/AmbiguityInfo.swift +++ b/runtime/Swift/Sources/Antlr4/atn/AmbiguityInfo.swift @@ -1,60 +1,55 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** -* This class represents profiling event information for an ambiguity. -* Ambiguities are decisions where a particular input resulted in an SLL -* conflict, followed by LL prediction also reaching a conflict state -* (indicating a true ambiguity in the grammar). -* -*

          -* This event may be reported during SLL prediction in cases where the -* conflicting SLL configuration set provides sufficient information to -* determine that the SLL conflict is truly an ambiguity. For example, if none -* of the ATN configurations in the conflicting SLL configuration set have -* traversed a global follow transition (i.e. -* {@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 -* result of LL prediction for that input.

          -* -*

          -* In some cases, the minimum represented alternative in the conflicting LL -* configuration set is not equal to the minimum represented alternative in the -* conflicting SLL configuration set. Grammars and inputs which result in this -* scenario are unable to use {@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 input.

          -* -* @see org.antlr.v4.runtime.atn.ParserATNSimulator#reportAmbiguity -* @see org.antlr.v4.runtime.ANTLRErrorListener#reportAmbiguity -* -* @since 4.3 -*/ +/// This class represents profiling event information for an ambiguity. +/// Ambiguities are decisions where a particular input resulted in an SLL +/// conflict, followed by LL prediction also reaching a conflict state +/// (indicating a true ambiguity in the grammar). +/// +///

          +/// This event may be reported during SLL prediction in cases where the +/// conflicting SLL configuration set provides sufficient information to +/// determine that the SLL conflict is truly an ambiguity. For example, if none +/// of the ATN configurations in the conflicting SLL configuration set have +/// traversed a global follow transition (i.e. +/// {@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 +/// result of LL prediction for that input.

          +/// +///

          +/// In some cases, the minimum represented alternative in the conflicting LL +/// configuration set is not equal to the minimum represented alternative in the +/// conflicting SLL configuration set. Grammars and inputs which result in this +/// scenario are unable to use {@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 input.

          +/// +/// - seealso: org.antlr.v4.runtime.atn.ParserATNSimulator#reportAmbiguity +/// - seealso: org.antlr.v4.runtime.ANTLRErrorListener#reportAmbiguity +/// +/// - 4.3 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 - /** - * Constructs a new instance of the {@link org.antlr.v4.runtime.atn.AmbiguityInfo} class with the - * specified detailed ambiguity information. - * - * @param decision The decision number - * @param configs The final configuration set identifying the ambiguous - * alternatives for the current input - * @param ambigAlts The set of alternatives in the decision that lead to a valid parse. - * @param input The input token stream - * @param startIndex The start index for the current prediction - * @param stopIndex The index at which the ambiguity was identified during - * prediction - * @param fullCtx {@code true} if the ambiguity was identified during LL - * prediction; otherwise, {@code false} if the ambiguity was identified - * during SLL prediction - */ + /// Constructs a new instance of the {@link org.antlr.v4.runtime.atn.AmbiguityInfo} class with the + /// specified detailed ambiguity information. + /// + /// - parameter decision: The decision number + /// - parameter configs: The final configuration set identifying the ambiguous + /// alternatives for the current input + /// - parameter ambigAlts: The set of alternatives in the decision that lead to a valid parse. + /// - parameter input: The input token stream + /// - parameter startIndex: The start index for the current prediction + /// - parameter stopIndex: The index at which the ambiguity was identified during + /// prediction + /// - parameter fullCtx: {@code true} if the ambiguity was identified during LL + /// prediction; otherwise, {@code false} if the ambiguity was identified + /// during SLL prediction public init(_ decision: Int, _ configs: ATNConfigSet, _ ambigAlts: BitSet, diff --git a/runtime/Swift/Sources/Antlr4/atn/ArrayPredictionContext.swift b/runtime/Swift/Sources/Antlr4/atn/ArrayPredictionContext.swift index 38dbc116c..b20ec63ff 100644 --- a/runtime/Swift/Sources/Antlr4/atn/ArrayPredictionContext.swift +++ b/runtime/Swift/Sources/Antlr4/atn/ArrayPredictionContext.swift @@ -1,19 +1,16 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. public class ArrayPredictionContext: PredictionContext { - /** 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 - * returnState == {@link #EMPTY_RETURN_STATE}. - */ + /// 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 + /// returnState == {@link #EMPTY_RETURN_STATE}. public final var parents: [PredictionContext?] - /** Sorted for merge, no duplicates; if present, - * {@link #EMPTY_RETURN_STATE} is always last. - */ + /// Sorted for merge, no duplicates; if present, + /// {@link #EMPTY_RETURN_STATE} is always last. public final let returnStates: [Int] public convenience init(_ a: SingletonPredictionContext) { diff --git a/runtime/Swift/Sources/Antlr4/atn/AtomTransition.swift b/runtime/Swift/Sources/Antlr4/atn/AtomTransition.swift index 6b96077ff..e9db9e8f7 100644 --- a/runtime/Swift/Sources/Antlr4/atn/AtomTransition.swift +++ b/runtime/Swift/Sources/Antlr4/atn/AtomTransition.swift @@ -1,13 +1,12 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** 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 { - /** 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 init(_ target: ATNState, _ label: Int) { diff --git a/runtime/Swift/Sources/Antlr4/atn/BasicBlockStartState.swift b/runtime/Swift/Sources/Antlr4/atn/BasicBlockStartState.swift index a86363759..508e39217 100644 --- a/runtime/Swift/Sources/Antlr4/atn/BasicBlockStartState.swift +++ b/runtime/Swift/Sources/Antlr4/atn/BasicBlockStartState.swift @@ -1,14 +1,11 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * - * @author Sam Harwell - */ +/// +/// - Sam Harwell public final class BasicBlockStartState: BlockStartState { override diff --git a/runtime/Swift/Sources/Antlr4/atn/BasicState.swift b/runtime/Swift/Sources/Antlr4/atn/BasicState.swift index 91c51d5d5..6a31cc1ef 100644 --- a/runtime/Swift/Sources/Antlr4/atn/BasicState.swift +++ b/runtime/Swift/Sources/Antlr4/atn/BasicState.swift @@ -1,14 +1,11 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * - * @author Sam Harwell - */ +/// +/// - Sam Harwell public final class BasicState: ATNState { diff --git a/runtime/Swift/Sources/Antlr4/atn/BlockEndState.swift b/runtime/Swift/Sources/Antlr4/atn/BlockEndState.swift index 6518ac968..f09b7022f 100644 --- a/runtime/Swift/Sources/Antlr4/atn/BlockEndState.swift +++ b/runtime/Swift/Sources/Antlr4/atn/BlockEndState.swift @@ -1,11 +1,10 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** 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 var startState: BlockStartState? diff --git a/runtime/Swift/Sources/Antlr4/atn/BlockStartState.swift b/runtime/Swift/Sources/Antlr4/atn/BlockStartState.swift index 2e4ac7822..add3c69dd 100644 --- a/runtime/Swift/Sources/Antlr4/atn/BlockStartState.swift +++ b/runtime/Swift/Sources/Antlr4/atn/BlockStartState.swift @@ -1,10 +1,9 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** The start of a regular {@code (...)} block. */ +/// The start of a regular {@code (...)} block. public class BlockStartState: DecisionState { public var endState: BlockEndState? diff --git a/runtime/Swift/Sources/Antlr4/atn/ContextSensitivityInfo.swift b/runtime/Swift/Sources/Antlr4/atn/ContextSensitivityInfo.swift index ee01ff617..f4d9f66d4 100644 --- a/runtime/Swift/Sources/Antlr4/atn/ContextSensitivityInfo.swift +++ b/runtime/Swift/Sources/Antlr4/atn/ContextSensitivityInfo.swift @@ -1,41 +1,36 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * This class represents profiling event information for a context sensitivity. - * Context sensitivities are decisions where a particular input resulted in an - * SLL conflict, but LL prediction produced a single unique alternative. - * - *

          - * In some cases, the unique alternative identified by LL prediction is not - * equal to the minimum represented alternative in the conflicting SLL - * configuration set. Grammars and inputs which result in this scenario are - * unable to use {@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 - * input.

          - * - * @see org.antlr.v4.runtime.atn.ParserATNSimulator#reportContextSensitivity - * @see org.antlr.v4.runtime.ANTLRErrorListener#reportContextSensitivity - * - * @since 4.3 - */ +/// This class represents profiling event information for a context sensitivity. +/// Context sensitivities are decisions where a particular input resulted in an +/// SLL conflict, but LL prediction produced a single unique alternative. +/// +///

          +/// In some cases, the unique alternative identified by LL prediction is not +/// equal to the minimum represented alternative in the conflicting SLL +/// configuration set. Grammars and inputs which result in this scenario are +/// unable to use {@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 +/// input.

          +/// +/// - seealso: org.antlr.v4.runtime.atn.ParserATNSimulator#reportContextSensitivity +/// - seealso: org.antlr.v4.runtime.ANTLRErrorListener#reportContextSensitivity +/// +/// - 4.3 public class ContextSensitivityInfo: DecisionEventInfo { - /** - * Constructs a new instance of the {@link org.antlr.v4.runtime.atn.ContextSensitivityInfo} class - * with the specified detailed context sensitivity information. - * - * @param decision The decision number - * @param configs The final configuration set containing the unique - * alternative identified by full-context prediction - * @param input The input token stream - * @param startIndex The start index for the current prediction - * @param stopIndex The index at which the context sensitivity was - * identified during full-context prediction - */ + /// Constructs a new instance of the {@link org.antlr.v4.runtime.atn.ContextSensitivityInfo} class + /// with the specified detailed context sensitivity information. + /// + /// - parameter decision: The decision number + /// - parameter configs: The final configuration set containing the unique + /// alternative identified by full-context prediction + /// - parameter input: The input token stream + /// - parameter startIndex: The start index for the current prediction + /// - parameter stopIndex: The index at which the context sensitivity was + /// identified during full-context prediction public init(_ decision: Int, _ configs: ATNConfigSet, _ input: TokenStream, _ startIndex: Int, _ stopIndex: Int) { diff --git a/runtime/Swift/Sources/Antlr4/atn/DecisionEventInfo.swift b/runtime/Swift/Sources/Antlr4/atn/DecisionEventInfo.swift index dd9805c01..ab245e3d4 100644 --- a/runtime/Swift/Sources/Antlr4/atn/DecisionEventInfo.swift +++ b/runtime/Swift/Sources/Antlr4/atn/DecisionEventInfo.swift @@ -1,61 +1,46 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * This is the base class for gathering detailed information about prediction - * events which occur during parsing. - * - * Note that we could record the parser call stack at the time this event - * occurred but in the presence of left recursive rules, the stack is kind of - * meaningless. It's better to look at the individual configurations for their - * individual stacks. Of course that is a {@link org.antlr.v4.runtime.atn.PredictionContext} object - * not a parse tree node and so it does not have information about the extent - * (start...stop) of the various subtrees. Examining the stack tops of all - * configurations provide the return states for the rule invocations. - * From there you can get the enclosing rule. - * - * @since 4.3 - */ +/// This is the base class for gathering detailed information about prediction +/// events which occur during parsing. +/// +/// Note that we could record the parser call stack at the time this event +/// occurred but in the presence of left recursive rules, the stack is kind of +/// meaningless. It's better to look at the individual configurations for their +/// individual stacks. Of course that is a {@link org.antlr.v4.runtime.atn.PredictionContext} object +/// not a parse tree node and so it does not have information about the extent +/// (start...stop) of the various subtrees. Examining the stack tops of all +/// configurations provide the return states for the rule invocations. +/// From there you can get the enclosing rule. +/// +/// - 4.3 public class DecisionEventInfo { - /** - * The invoked decision number which this event is related to. - * - * @see org.antlr.v4.runtime.atn.ATN#decisionToState - */ + /// The invoked decision number which this event is related to. + /// + /// - seealso: org.antlr.v4.runtime.atn.ATN#decisionToState public let decision: Int - /** - * The configuration set containing additional information relevant to the - * prediction state when the current event occurred, or {@code null} if no - * additional information is relevant or available. - */ + /// The configuration set containing additional information relevant to the + /// prediction state when the current event occurred, or {@code null} if no + /// additional information is relevant or available. public let configs: ATNConfigSet? - /** - * The input token stream which is being parsed. - */ + /// The input token stream which is being parsed. public let input: TokenStream - /** - * The token index in the input stream at which the current prediction was - * originally invoked. - */ + /// The token index in the input stream at which the current prediction was + /// originally invoked. public let startIndex: Int - /** - * The token index in the input stream at which the current event occurred. - */ + /// The token index in the input stream at which the current event occurred. public let stopIndex: Int - /** - * {@code true} if the current event occurred during LL prediction; - * otherwise, {@code false} if the input occurred during SLL prediction. - */ + /// {@code true} if the current event occurred during LL prediction; + /// otherwise, {@code false} if the input occurred during SLL prediction. public let fullCtx: Bool public init(_ decision: Int, diff --git a/runtime/Swift/Sources/Antlr4/atn/DecisionInfo.swift b/runtime/Swift/Sources/Antlr4/atn/DecisionInfo.swift index 2300e363d..b5314d381 100644 --- a/runtime/Swift/Sources/Antlr4/atn/DecisionInfo.swift +++ b/runtime/Swift/Sources/Antlr4/atn/DecisionInfo.swift @@ -1,223 +1,178 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * This class contains profiling gathered for a particular decision. - * - *

          - * Parsing performance in ANTLR 4 is heavily influenced by both static factors - * (e.g. the form of the rules in the grammar) and dynamic factors (e.g. the - * choice of input and the state of the DFA cache at the time profiling - * operations are started). For best results, gather and use aggregate - * statistics from a large sample of inputs representing the inputs expected in - * production before using the results to make changes in the grammar.

          - * - * @since 4.3 - */ +/// This class contains profiling gathered for a particular decision. +/// +///

          +/// Parsing performance in ANTLR 4 is heavily influenced by both static factors +/// (e.g. the form of the rules in the grammar) and dynamic factors (e.g. the +/// choice of input and the state of the DFA cache at the time profiling +/// operations are started). For best results, gather and use aggregate +/// statistics from a large sample of inputs representing the inputs expected in +/// production before using the results to make changes in the grammar.

          +/// +/// - 4.3 public class DecisionInfo: CustomStringConvertible { - /** - * The decision number, which is an index into {@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 - /** - * The total number of times {@link org.antlr.v4.runtime.atn.ParserATNSimulator#adaptivePredict} was - * invoked for this decision. - */ + /// The total number of times {@link org.antlr.v4.runtime.atn.ParserATNSimulator#adaptivePredict} was + /// invoked for this decision. public var invocations: Int64 = 0 - /** - * The total time spent in {@link org.antlr.v4.runtime.atn.ParserATNSimulator#adaptivePredict} for - * this decision, in nanoseconds. - * - *

          - * The value of this field contains the sum of differential results obtained - * by {@link System#nanoTime()}, and is not adjusted to compensate for JIT - * and/or garbage collection overhead. For best accuracy, use a modern JVM - * implementation that provides precise results from - * {@link System#nanoTime()}, and perform profiling in a separate process - * 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 - * state before starting the profiling measurement pass.

          - */ + /// The total time spent in {@link org.antlr.v4.runtime.atn.ParserATNSimulator#adaptivePredict} for + /// this decision, in nanoseconds. + /// + ///

          + /// The value of this field contains the sum of differential results obtained + /// by {@link System#nanoTime()}, and is not adjusted to compensate for JIT + /// and/or garbage collection overhead. For best accuracy, use a modern JVM + /// implementation that provides precise results from + /// {@link System#nanoTime()}, and perform profiling in a separate process + /// 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 + /// state before starting the profiling measurement pass.

          public var timeInPrediction: Int64 = 0 - /** - * The sum of the lookahead required for SLL prediction for this decision. - * Note that SLL prediction is used before LL prediction for performance - * reasons even when {@link org.antlr.v4.runtime.atn.PredictionMode#LL} or - * {@link org.antlr.v4.runtime.atn.PredictionMode#LL_EXACT_AMBIG_DETECTION} is used. - */ + /// The sum of the lookahead required for SLL prediction for this decision. + /// Note that SLL prediction is used before LL prediction for performance + /// reasons even when {@link org.antlr.v4.runtime.atn.PredictionMode#LL} or + /// {@link org.antlr.v4.runtime.atn.PredictionMode#LL_EXACT_AMBIG_DETECTION} is used. public var SLL_TotalLook: Int64 = 0 - /** - * Gets the minimum lookahead required for any single SLL prediction to - * complete for this decision, by reaching a unique prediction, reaching an - * SLL conflict state, or encountering a syntax error. - */ + /// Gets the minimum lookahead required for any single SLL prediction to + /// complete for this decision, by reaching a unique prediction, reaching an + /// SLL conflict state, or encountering a syntax error. public var SLL_MinLook: Int64 = 0 - /** - * Gets the maximum lookahead required for any single SLL prediction to - * complete for this decision, by reaching a unique prediction, reaching an - * SLL conflict state, or encountering a syntax error. - */ + /// Gets the maximum lookahead required for any single SLL prediction to + /// complete for this decision, by reaching a unique prediction, reaching an + /// SLL conflict state, or encountering a syntax error. public var SLL_MaxLook: Int64 = 0 - /** - * Gets the {@link org.antlr.v4.runtime.atn.LookaheadEventInfo} associated with the event where the - * {@link #SLL_MaxLook} value was set. - */ + /// Gets the {@link org.antlr.v4.runtime.atn.LookaheadEventInfo} associated with the event where the + /// {@link #SLL_MaxLook} value was set. public var SLL_MaxLookEvent: LookaheadEventInfo! - /** - * The sum of the lookahead required for LL prediction for this decision. - * Note that LL prediction is only used when SLL prediction reaches a - * conflict state. - */ + /// The sum of the lookahead required for LL prediction for this decision. + /// Note that LL prediction is only used when SLL prediction reaches a + /// conflict state. public var LL_TotalLook: Int64 = 0 - /** - * Gets the minimum lookahead required for any single LL prediction to - * complete for this decision. An LL prediction completes when the algorithm - * reaches a unique prediction, a conflict state (for - * {@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. - */ + /// Gets the minimum lookahead required for any single LL prediction to + /// complete for this decision. An LL prediction completes when the algorithm + /// reaches a unique prediction, a conflict state (for + /// {@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. public var LL_MinLook: Int64 = 0 - /** - * Gets the maximum lookahead required for any single LL prediction to - * complete for this decision. An LL prediction completes when the algorithm - * reaches a unique prediction, a conflict state (for - * {@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. - */ + /// Gets the maximum lookahead required for any single LL prediction to + /// complete for this decision. An LL prediction completes when the algorithm + /// reaches a unique prediction, a conflict state (for + /// {@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. public var LL_MaxLook: Int64 = 0 - /** - * Gets the {@link org.antlr.v4.runtime.atn.LookaheadEventInfo} associated with the event where the - * {@link #LL_MaxLook} value was set. - */ + /// Gets the {@link org.antlr.v4.runtime.atn.LookaheadEventInfo} associated with the event where the + /// {@link #LL_MaxLook} value was set. public var LL_MaxLookEvent: LookaheadEventInfo! - /** - * A collection of {@link org.antlr.v4.runtime.atn.ContextSensitivityInfo} instances describing the - * context sensitivities encountered during LL prediction for this decision. - * - * @see org.antlr.v4.runtime.atn.ContextSensitivityInfo - */ + /// A collection of {@link org.antlr.v4.runtime.atn.ContextSensitivityInfo} instances describing the + /// context sensitivities encountered during LL prediction for this decision. + /// + /// - seealso: org.antlr.v4.runtime.atn.ContextSensitivityInfo public final var contextSensitivities: Array = Array() - /** - * 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 - * this decision. - * - * @see org.antlr.v4.runtime.atn.ErrorInfo - */ + /// 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 + /// this decision. + /// + /// - seealso: org.antlr.v4.runtime.atn.ErrorInfo public final var errors: Array = Array() - /** - * A collection of {@link org.antlr.v4.runtime.atn.AmbiguityInfo} instances describing the - * ambiguities encountered during LL prediction for this decision. - * - * @see org.antlr.v4.runtime.atn.AmbiguityInfo - */ + /// A collection of {@link org.antlr.v4.runtime.atn.AmbiguityInfo} instances describing the + /// ambiguities encountered during LL prediction for this decision. + /// + /// - seealso: org.antlr.v4.runtime.atn.AmbiguityInfo public final var ambiguities: Array = Array() - /** - * A collection of {@link org.antlr.v4.runtime.atn.PredicateEvalInfo} instances describing the - * results of evaluating individual predicates during prediction for this - * decision. - * - * @see org.antlr.v4.runtime.atn.PredicateEvalInfo - */ + /// A collection of {@link org.antlr.v4.runtime.atn.PredicateEvalInfo} instances describing the + /// results of evaluating individual predicates during prediction for this + /// decision. + /// + /// - seealso: org.antlr.v4.runtime.atn.PredicateEvalInfo public final var predicateEvals: Array = Array() - /** - * The total number of ATN transitions required during SLL prediction for - * this decision. An ATN transition is determined by the number of times the - * DFA does not contain an edge that is required for prediction, resulting - * in on-the-fly computation of that edge. - * - *

          - * If DFA caching of SLL transitions is employed by the implementation, ATN - * computation may cache the computed edge for efficient lookup during - * future parsing of this decision. Otherwise, the SLL parsing algorithm - * will use ATN transitions exclusively.

          - * - * @see #SLL_ATNTransitions - * @see org.antlr.v4.runtime.atn.ParserATNSimulator#computeTargetState - * @see org.antlr.v4.runtime.atn.LexerATNSimulator#computeTargetState - */ + /// The total number of ATN transitions required during SLL prediction for + /// this decision. An ATN transition is determined by the number of times the + /// DFA does not contain an edge that is required for prediction, resulting + /// in on-the-fly computation of that edge. + /// + ///

          + /// If DFA caching of SLL transitions is employed by the implementation, ATN + /// computation may cache the computed edge for efficient lookup during + /// future parsing of this decision. Otherwise, the SLL parsing algorithm + /// will use ATN transitions exclusively.

          + /// + /// - seealso: #SLL_ATNTransitions + /// - seealso: org.antlr.v4.runtime.atn.ParserATNSimulator#computeTargetState + /// - seealso: org.antlr.v4.runtime.atn.LexerATNSimulator#computeTargetState public var SLL_ATNTransitions: Int64 = 0 - /** - * The total number of DFA transitions required during SLL prediction for - * this decision. - * - *

          If the ATN simulator implementation does not use DFA caching for SLL - * transitions, this value will be 0.

          - * - * @see org.antlr.v4.runtime.atn.ParserATNSimulator#getExistingTargetState - * @see org.antlr.v4.runtime.atn.LexerATNSimulator#getExistingTargetState - */ + /// The total number of DFA transitions required during SLL prediction for + /// this decision. + /// + ///

          If the ATN simulator implementation does not use DFA caching for SLL + /// transitions, this value will be 0.

          + /// + /// - seealso: org.antlr.v4.runtime.atn.ParserATNSimulator#getExistingTargetState + /// - seealso: org.antlr.v4.runtime.atn.LexerATNSimulator#getExistingTargetState public var SLL_DFATransitions: Int64 = 0 - /** - * Gets the total number of times SLL prediction completed in a conflict - * state, resulting in fallback to LL prediction. - * - *

          Note that this value is not related to whether or not - * {@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 - * 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 - * parsing result as {@link org.antlr.v4.runtime.atn.PredictionMode#LL}.

          - */ + /// Gets the total number of times SLL prediction completed in a conflict + /// state, resulting in fallback to LL prediction. + /// + ///

          Note that this value is not related to whether or not + /// {@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 + /// 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 + /// parsing result as {@link org.antlr.v4.runtime.atn.PredictionMode#LL}.

          public var LL_Fallback: Int64 = 0 - /** - * The total number of ATN transitions required during LL prediction for - * this decision. An ATN transition is determined by the number of times the - * DFA does not contain an edge that is required for prediction, resulting - * in on-the-fly computation of that edge. - * - *

          - * If DFA caching of LL transitions is employed by the implementation, ATN - * computation may cache the computed edge for efficient lookup during - * future parsing of this decision. Otherwise, the LL parsing algorithm will - * use ATN transitions exclusively.

          - * - * @see #LL_DFATransitions - * @see org.antlr.v4.runtime.atn.ParserATNSimulator#computeTargetState - * @see org.antlr.v4.runtime.atn.LexerATNSimulator#computeTargetState - */ + /// The total number of ATN transitions required during LL prediction for + /// this decision. An ATN transition is determined by the number of times the + /// DFA does not contain an edge that is required for prediction, resulting + /// in on-the-fly computation of that edge. + /// + ///

          + /// If DFA caching of LL transitions is employed by the implementation, ATN + /// computation may cache the computed edge for efficient lookup during + /// future parsing of this decision. Otherwise, the LL parsing algorithm will + /// use ATN transitions exclusively.

          + /// + /// - seealso: #LL_DFATransitions + /// - seealso: org.antlr.v4.runtime.atn.ParserATNSimulator#computeTargetState + /// - seealso: org.antlr.v4.runtime.atn.LexerATNSimulator#computeTargetState public var LL_ATNTransitions: Int64 = 0 - /** - * The total number of DFA transitions required during LL prediction for - * this decision. - * - *

          If the ATN simulator implementation does not use DFA caching for LL - * transitions, this value will be 0.

          - * - * @see org.antlr.v4.runtime.atn.ParserATNSimulator#getExistingTargetState - * @see org.antlr.v4.runtime.atn.LexerATNSimulator#getExistingTargetState - */ + /// The total number of DFA transitions required during LL prediction for + /// this decision. + /// + ///

          If the ATN simulator implementation does not use DFA caching for LL + /// transitions, this value will be 0.

          + /// + /// - seealso: org.antlr.v4.runtime.atn.ParserATNSimulator#getExistingTargetState + /// - seealso: org.antlr.v4.runtime.atn.LexerATNSimulator#getExistingTargetState public var LL_DFATransitions: Int64 = 0 - /** - * Constructs a new instance of the {@link org.antlr.v4.runtime.atn.DecisionInfo} class to contain - * statistics for a particular decision. - * - * @param decision The decision number - */ + /// Constructs a new instance of the {@link org.antlr.v4.runtime.atn.DecisionInfo} class to contain + /// statistics for a particular decision. + /// + /// - parameter decision: The decision number public init(_ decision: Int) { self.decision = decision } diff --git a/runtime/Swift/Sources/Antlr4/atn/DecisionState.swift b/runtime/Swift/Sources/Antlr4/atn/DecisionState.swift index fd909d895..713dc267e 100644 --- a/runtime/Swift/Sources/Antlr4/atn/DecisionState.swift +++ b/runtime/Swift/Sources/Antlr4/atn/DecisionState.swift @@ -1,7 +1,6 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. public class DecisionState: ATNState { diff --git a/runtime/Swift/Sources/Antlr4/atn/DefaultATNConfig.swift b/runtime/Swift/Sources/Antlr4/atn/DefaultATNConfig.swift index 99cec5e1b..a1cc145f4 100644 --- a/runtime/Swift/Sources/Antlr4/atn/DefaultATNConfig.swift +++ b/runtime/Swift/Sources/Antlr4/atn/DefaultATNConfig.swift @@ -1,7 +1,6 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. // // DefaultATNConfig.swift diff --git a/runtime/Swift/Sources/Antlr4/atn/EmptyPredictionContext.swift b/runtime/Swift/Sources/Antlr4/atn/EmptyPredictionContext.swift index f09f14cde..d2e42eede 100644 --- a/runtime/Swift/Sources/Antlr4/atn/EmptyPredictionContext.swift +++ b/runtime/Swift/Sources/Antlr4/atn/EmptyPredictionContext.swift @@ -1,7 +1,6 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. public class EmptyPredictionContext: SingletonPredictionContext { diff --git a/runtime/Swift/Sources/Antlr4/atn/EpsilonTransition.swift b/runtime/Swift/Sources/Antlr4/atn/EpsilonTransition.swift index a955d0eb9..0b01b2bb6 100644 --- a/runtime/Swift/Sources/Antlr4/atn/EpsilonTransition.swift +++ b/runtime/Swift/Sources/Antlr4/atn/EpsilonTransition.swift @@ -1,7 +1,6 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. public final class EpsilonTransition: Transition, CustomStringConvertible { @@ -18,14 +17,12 @@ public final class EpsilonTransition: Transition, CustomStringConvertible { super.init(target) } - /** - * @return the rule index of a precedence rule for which this transition is - * returning from, where the precedence value is 0; otherwise, -1. - * - * @see org.antlr.v4.runtime.atn.ATNConfig#isPrecedenceFilterSuppressed() - * @see org.antlr.v4.runtime.atn.ParserATNSimulator#applyPrecedenceFilter(org.antlr.v4.runtime.atn.ATNConfigSet) - * @since 4.4.1 - */ + /// - returns: the rule index of a precedence rule for which this transition is + /// returning from, where the precedence value is 0; otherwise, -1. + /// + /// - seealso: org.antlr.v4.runtime.atn.ATNConfig#isPrecedenceFilterSuppressed() + /// - seealso: org.antlr.v4.runtime.atn.ParserATNSimulator#applyPrecedenceFilter(org.antlr.v4.runtime.atn.ATNConfigSet) + /// - 4.4.1 public func outermostPrecedenceReturn() -> Int { return outermostPrecedenceReturnInside } diff --git a/runtime/Swift/Sources/Antlr4/atn/ErrorInfo.swift b/runtime/Swift/Sources/Antlr4/atn/ErrorInfo.swift index 51c67f6a1..bb8df5a3c 100644 --- a/runtime/Swift/Sources/Antlr4/atn/ErrorInfo.swift +++ b/runtime/Swift/Sources/Antlr4/atn/ErrorInfo.swift @@ -1,37 +1,32 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * This class represents profiling event information for a syntax error - * identified during prediction. Syntax errors occur when the prediction - * algorithm is unable to identify an alternative which would lead to a - * successful parse. - * - * @see org.antlr.v4.runtime.Parser#notifyErrorListeners(org.antlr.v4.runtime.Token, String, org.antlr.v4.runtime.RecognitionException) - * @see org.antlr.v4.runtime.ANTLRErrorListener#syntaxError - * - * @since 4.3 - */ +/// This class represents profiling event information for a syntax error +/// identified during prediction. Syntax errors occur when the prediction +/// algorithm is unable to identify an alternative which would lead to a +/// successful parse. +/// +/// - seealso: org.antlr.v4.runtime.Parser#notifyErrorListeners(org.antlr.v4.runtime.Token, String, org.antlr.v4.runtime.RecognitionException) +/// - seealso: org.antlr.v4.runtime.ANTLRErrorListener#syntaxError +/// +/// - 4.3 public class ErrorInfo: DecisionEventInfo { - /** - * Constructs a new instance of the {@link org.antlr.v4.runtime.atn.ErrorInfo} class with the - * specified detailed syntax error information. - * - * @param decision The decision number - * @param configs The final configuration set reached during prediction - * prior to reaching the {@link org.antlr.v4.runtime.atn.ATNSimulator#ERROR} state - * @param input The input token stream - * @param startIndex The start index for the current prediction - * @param stopIndex The index at which the syntax error was identified - * @param fullCtx {@code true} if the syntax error was identified during LL - * prediction; otherwise, {@code false} if the syntax error was identified - * during SLL prediction - */ + /// Constructs a new instance of the {@link org.antlr.v4.runtime.atn.ErrorInfo} class with the + /// specified detailed syntax error information. + /// + /// - parameter decision: The decision number + /// - parameter configs: The final configuration set reached during prediction + /// prior to reaching the {@link org.antlr.v4.runtime.atn.ATNSimulator#ERROR} state + /// - parameter input: The input token stream + /// - parameter startIndex: The start index for the current prediction + /// - parameter stopIndex: The index at which the syntax error was identified + /// - parameter fullCtx: {@code true} if the syntax error was identified during LL + /// prediction; otherwise, {@code false} if the syntax error was identified + /// during SLL prediction public init(_ decision: Int, _ configs: ATNConfigSet, _ input: TokenStream, _ startIndex: Int, _ stopIndex: Int, diff --git a/runtime/Swift/Sources/Antlr4/atn/LL1Analyzer.swift b/runtime/Swift/Sources/Antlr4/atn/LL1Analyzer.swift index e4791a016..b5b7f7b39 100644 --- a/runtime/Swift/Sources/Antlr4/atn/LL1Analyzer.swift +++ b/runtime/Swift/Sources/Antlr4/atn/LL1Analyzer.swift @@ -1,13 +1,11 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. public class LL1Analyzer { - /** Special value added to the lookahead sets to indicate that we hit - * a predicate during analysis if {@code seeThruPreds==false}. - */ + /// Special value added to the lookahead sets to indicate that we hit + /// a predicate during analysis if {@code seeThruPreds==false}. public let HIT_PRED: Int = CommonToken.INVALID_TYPE public let atn: ATN @@ -16,16 +14,14 @@ public class LL1Analyzer { self.atn = atn } - /** - * 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 - * outgoing transition in {@code s}. If the closure from transition - * i leads to a semantic predicate before matching a symbol, the - * element at index i of the result will be {@code null}. - * - * @param s the ATN state - * @return the expected symbols for each outgoing transition of {@code s}. - */ + /// 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 + /// outgoing transition in {@code s}. If the closure from transition + /// i leads to a semantic predicate before matching a symbol, the + /// element at index i of the result will be {@code null}. + /// + /// - parameter s: the ATN state + /// - returns: the expected symbols for each outgoing transition of {@code s}. public func getDecisionLookahead(_ s: ATNState?) throws -> [IntervalSet?]? { // print("LOOK("+s.stateNumber+")"); @@ -50,44 +46,40 @@ public class LL1Analyzer { return look } - /** - * Compute set of tokens that can follow {@code s} in the ATN in the - * specified {@code ctx}. - * - *

          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. - * 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.

          - * - * @param s the ATN state - * @param ctx the complete parser context, or {@code null} if the context - * should be ignored - * - * @return The set of tokens that can follow {@code s} in the ATN in the - * specified {@code ctx}. - */ + /// Compute set of tokens that can follow {@code s} in the ATN in the + /// specified {@code ctx}. + /// + ///

          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. + /// 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.

          + /// + /// - parameter s: the ATN state + /// - parameter ctx: the complete parser context, or {@code null} if the context + /// should be ignored + /// + /// - returns: The set of tokens that can follow {@code s} in the ATN in the + /// specified {@code ctx}. public func LOOK(_ s: ATNState, _ ctx: RuleContext?) throws -> IntervalSet { return try LOOK(s, nil, ctx) } - /** - * Compute set of tokens that can follow {@code s} in the ATN in the - * specified {@code ctx}. - * - *

          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. - * 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.

          - * - * @param s the ATN state - * @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. - * @param ctx the complete parser context, or {@code null} if the context - * should be ignored - * - * @return The set of tokens that can follow {@code s} in the ATN in the - * specified {@code ctx}. - */ + /// Compute set of tokens that can follow {@code s} in the ATN in the + /// specified {@code ctx}. + /// + ///

          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. + /// 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.

          + /// + /// - parameter s: the ATN state + /// - parameter 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. + /// - parameter ctx: the complete parser context, or {@code null} if the context + /// should be ignored + /// + /// - returns: The set of tokens that can follow {@code s} in the ATN in the + /// specified {@code ctx}. public func LOOK(_ s: ATNState, _ stopState: ATNState?, _ ctx: RuleContext?) throws -> IntervalSet { let r: IntervalSet = try IntervalSet() @@ -99,36 +91,34 @@ public class LL1Analyzer { return r } - /** - * Compute set of tokens that can follow {@code s} in the ATN in the - * specified {@code ctx}. - * - *

          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 - * 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 - * reached, {@link org.antlr.v4.runtime.Token#EOF} is added to the result set.

          - * - * @param s the ATN state. - * @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. - * @param ctx The outer context, or {@code null} if the outer context should - * not be used. - * @param look The result lookahead set. - * @param lookBusy A set used for preventing epsilon closures in the ATN - * from causing a stack overflow. Outside code should pass - * {@code new HashSet} for this argument. - * @param calledRuleStack A set used for preventing left recursion in the - * ATN from causing a stack overflow. Outside code should pass - * {@code new BitSet()} for this argument. - * @param seeThruPreds {@code true} to true semantic predicates as - * implicitly {@code true} and "see through them", otherwise {@code false} - * to treat semantic predicates as opaque and add {@link #HIT_PRED} to the - * result if one is encountered. - * @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} - * is {@code null}. - */ + /// Compute set of tokens that can follow {@code s} in the ATN in the + /// specified {@code ctx}. + /// + ///

          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 + /// 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 + /// reached, {@link org.antlr.v4.runtime.Token#EOF} is added to the result set.

          + /// + /// - parameter s: the ATN state. + /// - parameter 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. + /// - parameter ctx: The outer context, or {@code null} if the outer context should + /// not be used. + /// - parameter look: The result lookahead set. + /// - parameter lookBusy: A set used for preventing epsilon closures in the ATN + /// from causing a stack overflow. Outside code should pass + /// {@code new HashSet} for this argument. + /// - parameter calledRuleStack: A set used for preventing left recursion in the + /// ATN from causing a stack overflow. Outside code should pass + /// {@code new BitSet()} for this argument. + /// - parameter seeThruPreds: {@code true} to true semantic predicates as + /// implicitly {@code true} and "see through them", otherwise {@code false} + /// to treat semantic predicates as opaque and add {@link #HIT_PRED} to the + /// result if one is encountered. + /// - parameter 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} + /// is {@code null}. internal func _LOOK(_ s: ATNState, _ stopState: ATNState?, _ ctx: PredictionContext?, diff --git a/runtime/Swift/Sources/Antlr4/atn/LexerATNConfig.swift b/runtime/Swift/Sources/Antlr4/atn/LexerATNConfig.swift index 10fb784c2..c245b8ed4 100644 --- a/runtime/Swift/Sources/Antlr4/atn/LexerATNConfig.swift +++ b/runtime/Swift/Sources/Antlr4/atn/LexerATNConfig.swift @@ -1,13 +1,10 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. public class LexerATNConfig: ATNConfig { - /** - * This is the backing field for {@link #getLexerActionExecutor}. - */ + /// This is the backing field for {@link #getLexerActionExecutor}. private let lexerActionExecutor: LexerActionExecutor? fileprivate let passedThroughNonGreedyDecision: Bool @@ -59,10 +56,8 @@ public class LexerATNConfig: ATNConfig { return source.passedThroughNonGreedyDecision || target is DecisionState && (target as! DecisionState).nonGreedy } - /** - * Gets the {@link org.antlr.v4.runtime.atn.LexerActionExecutor} capable of executing the embedded - * action(s) for the current configuration. - */ + /// Gets the {@link org.antlr.v4.runtime.atn.LexerActionExecutor} capable of executing the embedded + /// action(s) for the current configuration. public final func getLexerActionExecutor() -> LexerActionExecutor? { return lexerActionExecutor } diff --git a/runtime/Swift/Sources/Antlr4/atn/LexerATNSimulator.swift b/runtime/Swift/Sources/Antlr4/atn/LexerATNSimulator.swift index 87b09967e..c60d6f24c 100644 --- a/runtime/Swift/Sources/Antlr4/atn/LexerATNSimulator.swift +++ b/runtime/Swift/Sources/Antlr4/atn/LexerATNSimulator.swift @@ -1,11 +1,10 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** "dup" of ParserInterpreter */ +/// "dup" of ParserInterpreter open class LexerATNSimulator: ATNSimulator { public static let debug: Bool = false @@ -15,21 +14,20 @@ open class LexerATNSimulator: ATNSimulator { public static let MAX_DFA_EDGE: Int = 127 // forces unicode to stay in ATN - /** When we hit an accept state in either the DFA or the ATN, we - * 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 - * includes the current index into the input, the current line, - * and current character position in that line. Note that the Lexer is - * tracking the starting line and characterization of the token. These - * variables track the "state" of the simulator when it hits an accept state. - * - *

          We track these variables separately for the DFA and ATN simulation - * because the DFA simulation often has to fail over to the ATN - * simulation. If the ATN simulation fails, we need the DFA to fall - * 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 - * can simply return the predicted token type.

          - */ + /// When we hit an accept state in either the DFA or the ATN, we + /// 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 + /// includes the current index into the input, the current line, + /// and current character position in that line. Note that the Lexer is + /// tracking the starting line and characterization of the token. These + /// variables track the "state" of the simulator when it hits an accept state. + /// + ///

          We track these variables separately for the DFA and ATN simulation + /// because the DFA simulation often has to fail over to the ATN + /// simulation. If the ATN simulation fails, we need the DFA to fall + /// 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 + /// can simply return the predicted token type.

          internal class SimState { internal var index: Int = -1 @@ -48,23 +46,22 @@ open class LexerATNSimulator: ATNSimulator { internal let recog: Lexer? - /** The current token's starting index into the character stream. - * 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 - * ATN-generated exception object. - */ + /// The current token's starting index into the character stream. + /// 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 + /// ATN-generated exception object. internal var startIndex: Int = -1 - /** line number 1..n within the input */ + /// line number 1..n within the input 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 final var decisionToDFA: [DFA] 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() @@ -229,17 +226,15 @@ open class LexerATNSimulator: ATNSimulator { return try failOrAccept(prevAccept, input, s.configs, t) } - /** - * 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, - * this method returns {@code null}. - * - * @param s The current DFA state - * @param t The next 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 - * already cached - */ + /// 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, + /// this method returns {@code null}. + /// + /// - parameter s: The current DFA state + /// - parameter t: The next input symbol + /// - returns: The existing target DFA state for the given input symbol + /// {@code t}, or {@code null} if the target state for this edge is not + /// already cached internal func getExistingTargetState(_ s: DFAState, _ t: Int) -> DFAState? { if s.edges == nil || t < LexerATNSimulator.MIN_DFA_EDGE || t > LexerATNSimulator.MAX_DFA_EDGE { @@ -254,18 +249,16 @@ open class LexerATNSimulator: ATNSimulator { return target } - /** - * Compute a target state for an edge in the DFA, and attempt to add the - * computed state and corresponding edge to the DFA. - * - * @param input The input stream - * @param s The current DFA state - * @param t The next 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 - * returns {@link #ERROR}. - */ + /// Compute a target state for an edge in the DFA, and attempt to add the + /// computed state and corresponding edge to the DFA. + /// + /// - parameter input: The input stream + /// - parameter s: The current DFA state + /// - parameter t: The next input symbol + /// + /// - returns: 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 + /// returns {@link #ERROR}. internal func computeTargetState(_ input: CharStream, _ s: DFAState, _ t: Int) throws -> DFAState { let reach: ATNConfigSet = OrderedATNConfigSet() @@ -308,10 +301,9 @@ open class LexerATNSimulator: ATNSimulator { } } - /** Given a starting configuration set, figure out all ATN configurations - * we can reach upon input {@code t}. Parameter {@code reach} is a return - * parameter. - */ + /// Given a starting configuration set, figure out all ATN configurations + /// we can reach upon input {@code t}. Parameter {@code reach} is a return + /// parameter. 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 // than a config that already reached an accept state for the same rule @@ -397,16 +389,14 @@ open class LexerATNSimulator: ATNSimulator { return configs } - /** - * Since the alternatives within any lexer decision are ordered by - * 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 - * search from {@code config}, all other (potentially reachable) states for - * this rule would have a lower priority. - * - * @return {@code true} if an accept state is reached, otherwise - * {@code false}. - */ + /// Since the alternatives within any lexer decision are ordered by + /// 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 + /// search from {@code config}, all other (potentially reachable) states for + /// this rule would have a lower priority. + /// + /// - returns: {@code true} if an accept state is reached, otherwise + /// {@code false}. @discardableResult final func closure(_ input: CharStream, _ config: LexerATNConfig, _ configs: ATNConfigSet, _ currentAltReachedAcceptState: Bool, _ speculative: Bool, _ treatEofAsEpsilon: Bool) throws -> Bool { var currentAltReachedAcceptState = currentAltReachedAcceptState @@ -492,24 +482,23 @@ open class LexerATNSimulator: ATNSimulator { case Transition.PREDICATE: - /* Track traversing semantic predicates. If we traverse, - we cannot add a DFA state for this "reach" computation - because the DFA would not test the predicate again in the - future. Rather than creating collections of semantic predicates - 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 - semantically it's not used that often. One of the key elements to - this predicate mechanism is not adding DFA states that see - predicates immediately afterwards in the ATN. For example, - - a : ID {p1}? | ID {p2}? ; - - should create the start state for rule 'a' (to save start state - competition), but should not create target of ID state. The - collection of ATN states the following ID references includes - states reached by traversing predicates. Since this is when we - test them, we cannot cash the DFA state target of ID. - */ + /// Track traversing semantic predicates. If we traverse, + /// we cannot add a DFA state for this "reach" computation + /// because the DFA would not test the predicate again in the + /// future. Rather than creating collections of semantic predicates + /// 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 + /// semantically it's not used that often. One of the key elements to + /// this predicate mechanism is not adding DFA states that see + /// predicates immediately afterwards in the ATN. For example, + /// + /// a : ID {p1}? | ID {p2}? ; + /// + /// should create the start state for rule 'a' (to save start state + /// competition), but should not create target of ID state. The + /// collection of ATN states the following ID references includes + /// states reached by traversing predicates. Since this is when we + /// test them, we cannot cash the DFA state target of ID. let pt: PredicateTransition = t as! PredicateTransition if LexerATNSimulator.debug { print("EVAL rule \(pt.ruleIndex):\(pt.predIndex)") @@ -565,27 +554,25 @@ open class LexerATNSimulator: ATNSimulator { return c } - /** - * Evaluate a predicate specified in the lexer. - * - *

          If {@code speculative} is {@code true}, this method was called before - * {@link #consume} for the matched character. This method should call - * {@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}, - * and {@link org.antlr.v4.runtime.Lexer#getCharPositionInLine}, properly reflect the current - * 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 - * call to {@link #consume}.

          - * - * @param input The input stream. - * @param ruleIndex The rule containing the predicate. - * @param predIndex The index of the predicate within the rule. - * @param speculative {@code true} if the current index in {@code input} is - * one character before the predicate's location. - * - * @return {@code true} if the specified predicate evaluates to - * {@code true}. - */ + /// Evaluate a predicate specified in the lexer. + /// + ///

          If {@code speculative} is {@code true}, this method was called before + /// {@link #consume} for the matched character. This method should call + /// {@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}, + /// and {@link org.antlr.v4.runtime.Lexer#getCharPositionInLine}, properly reflect the current + /// 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 + /// call to {@link #consume}.

          + /// + /// - parameter input: The input stream. + /// - parameter ruleIndex: The rule containing the predicate. + /// - parameter predIndex: The index of the predicate within the rule. + /// - parameter speculative: {@code true} if the current index in {@code input} is + /// one character before the predicate's location. + /// + /// - returns: {@code true} if the specified predicate evaluates to + /// {@code true}. final func evaluatePredicate(_ input: CharStream, _ ruleIndex: Int, _ predIndex: Int, _ speculative: Bool) throws -> Bool { // assume true if no recognizer was provided guard let recog = recog else { @@ -627,17 +614,16 @@ open class LexerATNSimulator: ATNSimulator { final func addDFAEdge(_ from: DFAState, _ t: Int, _ q: ATNConfigSet) -> DFAState { - /* leading to this call, ATNConfigSet.hasSemanticContext is used as a - * marker indicating dynamic predicate evaluation makes this edge - * dependent on the specific input sequence, so the static edge in the - * DFA should be omitted. The target DFAState is still created since - * execATN has the ability to resynchronize with the DFA state cache - * following the predicate evaluation step. - * - * 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 - * state, we can continue in pure DFA mode from there. - */ + /// leading to this call, ATNConfigSet.hasSemanticContext is used as a + /// marker indicating dynamic predicate evaluation makes this edge + /// dependent on the specific input sequence, so the static edge in the + /// DFA should be omitted. The target DFAState is still created since + /// execATN has the ability to resynchronize with the DFA state cache + /// following the predicate evaluation step. + /// + /// 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 + /// state, we can continue in pure DFA mode from there. let suppressEdge: Bool = q.hasSemanticContext 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 - configurations already. This method also detects the first - configuration containing an ATN rule stop state. Later, when - traversing the DFA, we will know which rule to accept. - */ + /// Add a new DFA state if there isn't one with this set of + /// configurations already. This method also detects the first + /// configuration containing an ATN rule stop state. Later, when + /// traversing the DFA, we will know which rule to accept. final func addDFAState(_ configs: ATNConfigSet) -> DFAState { - /* the lexer evaluates predicates on-the-fly; by this point configs - * should not contain any configurations with unevaluated predicates. - */ + /// the lexer evaluates predicates on-the-fly; by this point configs + /// should not contain any configurations with unevaluated predicates. assert(!configs.hasSemanticContext, "Expected: !configs.hasSemanticContext") let proposed: DFAState = DFAState(configs) @@ -715,8 +699,7 @@ open class LexerATNSimulator: ATNSimulator { 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 { // index is first lookahead char, don't include. diff --git a/runtime/Swift/Sources/Antlr4/atn/LexerAction.swift b/runtime/Swift/Sources/Antlr4/atn/LexerAction.swift index 450a1f692..21b6d95b7 100644 --- a/runtime/Swift/Sources/Antlr4/atn/LexerAction.swift +++ b/runtime/Swift/Sources/Antlr4/atn/LexerAction.swift @@ -1,58 +1,49 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * 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 - * and ANTLR 4's new lexer command syntax. - * - * @author Sam Harwell - * @since 4.2 - */ +/// 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 +/// and ANTLR 4's new lexer command syntax. +/// +/// - Sam Harwell +/// - 4.2 public class LexerAction: Hashable { - /** - * Gets the serialization type of the lexer action. - * - * @return The serialization type of the lexer action. - */ + /// Gets the serialization type of the lexer action. + /// + /// - returns: The serialization type of the lexer action. public func getActionType() -> LexerActionType { RuntimeException(" must overriden ") fatalError() } - /** - * Gets whether the lexer action is position-dependent. Position-dependent - * actions may have different semantics depending on the {@link org.antlr.v4.runtime.CharStream} - * index at the time the action is executed. - * - *

          Many lexer commands, including {@code type}, {@code skip}, and - * {@code more}, do not check the input index during their execution. - * Actions like this are position-independent, and may be stored more - * efficiently as part of the {@link org.antlr.v4.runtime.atn.LexerATNConfig#lexerActionExecutor}.

          - * - * @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; - * otherwise, {@code false}. - */ + /// Gets whether the lexer action is position-dependent. Position-dependent + /// actions may have different semantics depending on the {@link org.antlr.v4.runtime.CharStream} + /// index at the time the action is executed. + /// + ///

          Many lexer commands, including {@code type}, {@code skip}, and + /// {@code more}, do not check the input index during their execution. + /// Actions like this are position-independent, and may be stored more + /// efficiently as part of the {@link org.antlr.v4.runtime.atn.LexerATNConfig#lexerActionExecutor}.

          + /// + /// - returns: {@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; + /// otherwise, {@code false}. public func isPositionDependent() -> Bool { RuntimeException(" must overriden ") fatalError() } - /** - * Execute the lexer action in the context of the specified {@link org.antlr.v4.runtime.Lexer}. - * - *

          For position-dependent actions, the input stream must already be - * positioned correctly prior to calling this method.

          - * - * @param lexer The lexer instance. - */ + /// Execute the lexer action in the context of the specified {@link org.antlr.v4.runtime.Lexer}. + /// + ///

          For position-dependent actions, the input stream must already be + /// positioned correctly prior to calling this method.

          + /// + /// - parameter lexer: The lexer instance. public func execute(_ lexer: Lexer) throws { RuntimeException(" must overriden ") } diff --git a/runtime/Swift/Sources/Antlr4/atn/LexerActionExecutor.swift b/runtime/Swift/Sources/Antlr4/atn/LexerActionExecutor.swift index 006cfd6d1..a8087f380 100644 --- a/runtime/Swift/Sources/Antlr4/atn/LexerActionExecutor.swift +++ b/runtime/Swift/Sources/Antlr4/atn/LexerActionExecutor.swift @@ -1,37 +1,30 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * Represents an executor for a sequence of lexer actions which traversed during - * the matching operation of a lexer rule (token). - * - *

          The executor tracks position information for position-dependent lexer actions - * 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.

          - * - * @author Sam Harwell - * @since 4.2 - */ +/// Represents an executor for a sequence of lexer actions which traversed during +/// the matching operation of a lexer rule (token). +/// +///

          The executor tracks position information for position-dependent lexer actions +/// 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.

          +/// +/// - Sam Harwell +/// - 4.2 public class LexerActionExecutor: Hashable { fileprivate final var lexerActions: [LexerAction] - /** - * 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. - */ + /// 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. fileprivate final var hashCode: Int - /** - * Constructs an executor for a sequence of {@link org.antlr.v4.runtime.atn.LexerAction} actions. - * @param lexerActions The lexer actions to execute. - */ + /// Constructs an executor for a sequence of {@link org.antlr.v4.runtime.atn.LexerAction} actions. + /// - parameter lexerActions: The lexer actions to execute. public init(_ lexerActions: [LexerAction]) { self.lexerActions = lexerActions @@ -43,21 +36,19 @@ public class LexerActionExecutor: Hashable { self.hashCode = MurmurHash.finish(hash, lexerActions.count) } - /** - * Creates a {@link org.antlr.v4.runtime.atn.LexerActionExecutor} which executes the actions for - * the input {@code lexerActionExecutor} followed by a specified - * {@code lexerAction}. - * - * @param lexerActionExecutor The executor for actions already traversed by - * 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 - * though it were an empty executor. - * @param lexerAction The lexer action to execute after the actions - * specified in {@code lexerActionExecutor}. - * - * @return A {@link org.antlr.v4.runtime.atn.LexerActionExecutor} for executing the combine actions - * of {@code lexerActionExecutor} and {@code lexerAction}. - */ + /// Creates a {@link org.antlr.v4.runtime.atn.LexerActionExecutor} which executes the actions for + /// the input {@code lexerActionExecutor} followed by a specified + /// {@code lexerAction}. + /// + /// - parameter lexerActionExecutor: The executor for actions already traversed by + /// 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 + /// though it were an empty executor. + /// - parameter lexerAction: The lexer action to execute after the actions + /// specified in {@code lexerActionExecutor}. + /// + /// - returns: A {@link org.antlr.v4.runtime.atn.LexerActionExecutor} for executing the combine actions + /// of {@code lexerActionExecutor} and {@code lexerAction}. public static func append(_ lexerActionExecutor: LexerActionExecutor?, _ lexerAction: LexerAction) -> LexerActionExecutor { if lexerActionExecutor == nil { return LexerActionExecutor([lexerAction]) @@ -70,35 +61,33 @@ public class LexerActionExecutor: Hashable { return LexerActionExecutor(lexerActions) } - /** - * Creates a {@link org.antlr.v4.runtime.atn.LexerActionExecutor} which encodes the current offset - * for position-dependent lexer actions. - * - *

          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.IntStream#seek} on the input {@link org.antlr.v4.runtime.CharStream} to set the input - * position to the end of the current token. This behavior provides - * 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 - * characters.

          - * - *

          Prior to traversing a match transition in the ATN, the current offset - * from the token start index is assigned to all position-dependent lexer - * actions which have not already been assigned a fixed offset. By storing - * the offsets relative to the token start index, the DFA representation of - * lexer actions which appear in the middle of tokens remains efficient due - * to sharing among tokens of the same length, regardless of their absolute - * position in the input stream.

          - * - *

          If the current executor already has offsets assigned to all - * position-dependent lexer actions, the method returns {@code this}.

          - * - * @param offset The current offset to assign to all position-dependent - * lexer actions which do not already have offsets assigned. - * - * @return A {@link org.antlr.v4.runtime.atn.LexerActionExecutor} which stores input stream offsets - * for all position-dependent lexer actions. - */ + /// Creates a {@link org.antlr.v4.runtime.atn.LexerActionExecutor} which encodes the current offset + /// for position-dependent lexer actions. + /// + ///

          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.IntStream#seek} on the input {@link org.antlr.v4.runtime.CharStream} to set the input + /// position to the end of the current token. This behavior provides + /// 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 + /// characters.

          + /// + ///

          Prior to traversing a match transition in the ATN, the current offset + /// from the token start index is assigned to all position-dependent lexer + /// actions which have not already been assigned a fixed offset. By storing + /// the offsets relative to the token start index, the DFA representation of + /// lexer actions which appear in the middle of tokens remains efficient due + /// to sharing among tokens of the same length, regardless of their absolute + /// position in the input stream.

          + /// + ///

          If the current executor already has offsets assigned to all + /// position-dependent lexer actions, the method returns {@code this}.

          + /// + /// - parameter offset: The current offset to assign to all position-dependent + /// lexer actions which do not already have offsets assigned. + /// + /// - returns: A {@link org.antlr.v4.runtime.atn.LexerActionExecutor} which stores input stream offsets + /// for all position-dependent lexer actions. public func fixOffsetBeforeMatch(_ offset: Int) -> LexerActionExecutor { var updatedLexerActions: [LexerAction]? = nil let length = lexerActions.count @@ -119,33 +108,29 @@ public class LexerActionExecutor: Hashable { return LexerActionExecutor(updatedLexerActions!) } - /** - * Gets the lexer actions to be executed by this executor. - * @return 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. public func getLexerActions() -> [LexerAction] { return lexerActions } - /** - * Execute the actions encapsulated by this executor within the context of a - * particular {@link org.antlr.v4.runtime.Lexer}. - * - *

          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 - * {@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 - * it was in when the method was invoked.

          - * - * @param lexer The lexer instance. - * @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 - * {@code input} should be the start of the following token, i.e. 1 - * character past the end of the current token. - * @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 - * of the token. - */ + /// Execute the actions encapsulated by this executor within the context of a + /// particular {@link org.antlr.v4.runtime.Lexer}. + /// + ///

          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 + /// {@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 + /// it was in when the method was invoked.

          + /// + /// - parameter lexer: The lexer instance. + /// - parameter 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 + /// {@code input} should be the start of the following token, i.e. 1 + /// character past the end of the current token. + /// - parameter 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 + /// of the token. public func execute(_ lexer: Lexer, _ input: CharStream, _ startIndex: Int) throws { var requiresSeek: Bool = false var stopIndex: Int = input.index() diff --git a/runtime/Swift/Sources/Antlr4/atn/LexerActionType.swift b/runtime/Swift/Sources/Antlr4/atn/LexerActionType.swift index 0b9eb8084..437ec003b 100644 --- a/runtime/Swift/Sources/Antlr4/atn/LexerActionType.swift +++ b/runtime/Swift/Sources/Antlr4/atn/LexerActionType.swift @@ -1,16 +1,13 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * Represents the serialization type of a {@link org.antlr.v4.runtime.atn.LexerAction}. - * - * @author Sam Harwell - * @since 4.2 - */ +/// Represents the serialization type of a {@link org.antlr.v4.runtime.atn.LexerAction}. +/// +/// - Sam Harwell +/// - 4.2 public enum LexerActionType: Int { /** diff --git a/runtime/Swift/Sources/Antlr4/atn/LexerChannelAction.swift b/runtime/Swift/Sources/Antlr4/atn/LexerChannelAction.swift index 58580635b..1ce466985 100644 --- a/runtime/Swift/Sources/Antlr4/atn/LexerChannelAction.swift +++ b/runtime/Swift/Sources/Antlr4/atn/LexerChannelAction.swift @@ -1,61 +1,48 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * Implements the {@code channel} lexer action by calling - * {@link org.antlr.v4.runtime.Lexer#setChannel} with the assigned channel. - * - * @author Sam Harwell - * @since 4.2 - */ +/// Implements the {@code channel} lexer action by calling +/// {@link org.antlr.v4.runtime.Lexer#setChannel} with the assigned channel. +/// +/// - Sam Harwell +/// - 4.2 public final class LexerChannelAction: LexerAction, CustomStringConvertible { fileprivate let channel: Int - /** - * Constructs a new {@code channel} action with the specified channel value. - * @param channel The channel value to pass to {@link org.antlr.v4.runtime.Lexer#setChannel}. - */ + /// 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}. public init(_ channel: Int) { self.channel = channel } - /** - * Gets 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. - */ + /// 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. public func getChannel() -> Int { return channel } - /** - * {@inheritDoc} - * @return This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#CHANNEL}. - */ + /// {@inheritDoc} + /// - returns: This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#CHANNEL}. public override func getActionType() -> LexerActionType { return LexerActionType.channel } - /** - * {@inheritDoc} - * @return This method returns {@code false}. - */ + /// {@inheritDoc} + /// - returns: This method returns {@code false}. public override func isPositionDependent() -> Bool { return false } - /** - * {@inheritDoc} - * - *

          This action is implemented by calling {@link org.antlr.v4.runtime.Lexer#setChannel} with the - * value provided by {@link #getChannel}.

          - */ + /// {@inheritDoc} + /// + ///

          This action is implemented by calling {@link org.antlr.v4.runtime.Lexer#setChannel} with the + /// value provided by {@link #getChannel}.

          public override func execute(_ lexer: Lexer) { lexer.setChannel(channel) diff --git a/runtime/Swift/Sources/Antlr4/atn/LexerCustomAction.swift b/runtime/Swift/Sources/Antlr4/atn/LexerCustomAction.swift index 3cc6d9700..954ef337d 100644 --- a/runtime/Swift/Sources/Antlr4/atn/LexerCustomAction.swift +++ b/runtime/Swift/Sources/Antlr4/atn/LexerCustomAction.swift @@ -1,91 +1,76 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * 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 - * 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. - * - *

          This class may represent embedded actions created with 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.

          - * - * @author Sam Harwell - * @since 4.2 - */ +/// 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 +/// 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. +/// +///

          This class may represent embedded actions created with 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.

          +/// +/// - Sam Harwell +/// - 4.2 public final class LexerCustomAction: LexerAction { fileprivate let ruleIndex: Int fileprivate let actionIndex: Int - /** - * Constructs a custom lexer action with the specified rule and action - * indexes. - * - * @param ruleIndex The rule index to use for calls to - * {@link org.antlr.v4.runtime.Recognizer#action}. - * @param actionIndex The action index to use for calls to - * {@link org.antlr.v4.runtime.Recognizer#action}. - */ + /// Constructs a custom lexer action with the specified rule and action + /// indexes. + /// + /// - parameter ruleIndex: The rule index to use for calls to + /// {@link org.antlr.v4.runtime.Recognizer#action}. + /// - parameter actionIndex: The action index to use for calls to + /// {@link org.antlr.v4.runtime.Recognizer#action}. public init(_ ruleIndex: Int, _ actionIndex: Int) { self.ruleIndex = ruleIndex self.actionIndex = actionIndex } - /** - * Gets the rule index to use for calls to {@link org.antlr.v4.runtime.Recognizer#action}. - * - * @return The rule index for the custom 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. public func getRuleIndex() -> Int { return ruleIndex } - /** - * Gets the action index to use for calls to {@link org.antlr.v4.runtime.Recognizer#action}. - * - * @return The action index for the custom 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. public func getActionIndex() -> Int { return actionIndex } - /** - * {@inheritDoc} - * - * @return This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#CUSTOM}. - */ + /// {@inheritDoc} + /// + /// - returns: This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#CUSTOM}. public override func getActionType() -> LexerActionType { return LexerActionType.custom } - /** - * Gets whether the lexer action is position-dependent. Position-dependent - * actions may have different semantics depending on the {@link org.antlr.v4.runtime.CharStream} - * index at the time the action is executed. - * - *

          Custom actions are position-dependent since they may represent a - * user-defined embedded action which makes calls to methods like - * {@link org.antlr.v4.runtime.Lexer#getText}.

          - * - * @return This method returns {@code true}. - */ + /// Gets whether the lexer action is position-dependent. Position-dependent + /// actions may have different semantics depending on the {@link org.antlr.v4.runtime.CharStream} + /// index at the time the action is executed. + /// + ///

          Custom actions are position-dependent since they may represent a + /// user-defined embedded action which makes calls to methods like + /// {@link org.antlr.v4.runtime.Lexer#getText}.

          + /// + /// - returns: This method returns {@code true}. override public func isPositionDependent() -> Bool { return true } - /** - * {@inheritDoc} - * - *

          Custom actions are implemented by calling {@link org.antlr.v4.runtime.Lexer#action} with the - * appropriate rule and action indexes.

          - */ + /// {@inheritDoc} + /// + ///

          Custom actions are implemented by calling {@link org.antlr.v4.runtime.Lexer#action} with the + /// appropriate rule and action indexes.

          override public func execute(_ lexer: Lexer) throws { try lexer.action(nil, ruleIndex, actionIndex) diff --git a/runtime/Swift/Sources/Antlr4/atn/LexerIndexedCustomAction.swift b/runtime/Swift/Sources/Antlr4/atn/LexerIndexedCustomAction.swift index 315f01fb1..44e8b8b06 100644 --- a/runtime/Swift/Sources/Antlr4/atn/LexerIndexedCustomAction.swift +++ b/runtime/Swift/Sources/Antlr4/atn/LexerIndexedCustomAction.swift @@ -1,93 +1,78 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * 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}. - * - *

          This action is not serialized as part of the ATN, and is only required for - * position-dependent lexer actions which appear at a location other than the - * end of a rule. For more information about DFA optimizations employed for - * lexer actions, see {@link org.antlr.v4.runtime.atn.LexerActionExecutor#append} and - * {@link org.antlr.v4.runtime.atn.LexerActionExecutor#fixOffsetBeforeMatch}.

          - * - * @author Sam Harwell - * @since 4.2 - */ +/// 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}. +/// +///

          This action is not serialized as part of the ATN, and is only required for +/// position-dependent lexer actions which appear at a location other than the +/// end of a rule. For more information about DFA optimizations employed for +/// lexer actions, see {@link org.antlr.v4.runtime.atn.LexerActionExecutor#append} and +/// {@link org.antlr.v4.runtime.atn.LexerActionExecutor#fixOffsetBeforeMatch}.

          +/// +/// - Sam Harwell +/// - 4.2 public final class LexerIndexedCustomAction: LexerAction { fileprivate let offset: Int fileprivate let action: LexerAction - /** - * Constructs a new indexed custom action by associating a character offset - * with a {@link org.antlr.v4.runtime.atn.LexerAction}. - * - *

          Note: This class is only required for lexer actions for which - * {@link org.antlr.v4.runtime.atn.LexerAction#isPositionDependent} returns {@code true}.

          - * - * @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 - * executed. - * @param action The lexer action to execute at a particular offset in the - * input {@link org.antlr.v4.runtime.CharStream}. - */ + /// Constructs a new indexed custom action by associating a character offset + /// with a {@link org.antlr.v4.runtime.atn.LexerAction}. + /// + ///

          Note: This class is only required for lexer actions for which + /// {@link org.antlr.v4.runtime.atn.LexerAction#isPositionDependent} returns {@code true}.

          + /// + /// - parameter 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 + /// executed. + /// - parameter action: The lexer action to execute at a particular offset in the + /// input {@link org.antlr.v4.runtime.CharStream}. public init(_ offset: Int, _ action: LexerAction) { self.offset = offset self.action = action } - /** - * 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 - * to the token start index. - * - * @return The location in the input {@link org.antlr.v4.runtime.CharStream} at which the lexer - * action should be executed. - */ + /// 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 + /// to the token start index. + /// + /// - returns: The location in the input {@link org.antlr.v4.runtime.CharStream} at which the lexer + /// action should be executed. public func getOffset() -> Int { return offset } - /** - * Gets the lexer action to execute. - * - * @return A {@link org.antlr.v4.runtime.atn.LexerAction} object which executes the lexer action. - */ + /// Gets the lexer action to execute. + /// + /// - returns: A {@link org.antlr.v4.runtime.atn.LexerAction} object which executes the lexer action. public func getAction() -> LexerAction { return action } - /** - * {@inheritDoc} - * - * @return This method returns the result of calling {@link #getActionType} - * on the {@link org.antlr.v4.runtime.atn.LexerAction} returned by {@link #getAction}. - */ + /// {@inheritDoc} + /// + /// - returns: This method returns the result of calling {@link #getActionType} + /// on the {@link org.antlr.v4.runtime.atn.LexerAction} returned by {@link #getAction}. public override func getActionType() -> LexerActionType { return action.getActionType() } - /** - * {@inheritDoc} - * @return This method returns {@code true}. - */ + /// {@inheritDoc} + /// - returns: This method returns {@code true}. public override func isPositionDependent() -> Bool { return true } - /** - * {@inheritDoc} - * - *

          This method calls {@link #execute} on the result of {@link #getAction} - * using the provided {@code lexer}.

          - */ + /// {@inheritDoc} + /// + ///

          This method calls {@link #execute} on the result of {@link #getAction} + /// using the provided {@code lexer}.

          public override func execute(_ lexer: Lexer) throws { // assume the input stream position was properly set by the calling code diff --git a/runtime/Swift/Sources/Antlr4/atn/LexerModeAction.swift b/runtime/Swift/Sources/Antlr4/atn/LexerModeAction.swift index fdf065336..6f364a65d 100644 --- a/runtime/Swift/Sources/Antlr4/atn/LexerModeAction.swift +++ b/runtime/Swift/Sources/Antlr4/atn/LexerModeAction.swift @@ -1,62 +1,49 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * Implements the {@code mode} lexer action by calling {@link org.antlr.v4.runtime.Lexer#mode} with - * the assigned mode. - * - * @author Sam Harwell - * @since 4.2 - */ +/// Implements the {@code mode} lexer action by calling {@link org.antlr.v4.runtime.Lexer#mode} with +/// the assigned mode. +/// +/// - Sam Harwell +/// - 4.2 public final class LexerModeAction: LexerAction, CustomStringConvertible { fileprivate final var mode: Int - /** - * Constructs a new {@code mode} action with the specified mode value. - * @param mode The mode value to pass to {@link org.antlr.v4.runtime.Lexer#mode}. - */ + /// 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}. public init(_ mode: Int) { self.mode = mode } - /** - * Get the lexer mode this action should transition the lexer to. - * - * @return The lexer mode for this {@code mode} command. - */ + /// Get the lexer mode this action should transition the lexer to. + /// + /// - returns: The lexer mode for this {@code mode} command. public func getMode() -> Int { return mode } - /** - * {@inheritDoc} - * @return This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#MODE}. - */ + /// {@inheritDoc} + /// - returns: This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#MODE}. public override func getActionType() -> LexerActionType { return LexerActionType.mode } - /** - * {@inheritDoc} - * @return This method returns {@code false}. - */ + /// {@inheritDoc} + /// - returns: This method returns {@code false}. public override func isPositionDependent() -> Bool { return false } - /** - * {@inheritDoc} - * - *

          This action is implemented by calling {@link org.antlr.v4.runtime.Lexer#mode} with the - * value provided by {@link #getMode}.

          - */ + /// {@inheritDoc} + /// + ///

          This action is implemented by calling {@link org.antlr.v4.runtime.Lexer#mode} with the + /// value provided by {@link #getMode}.

          override public func execute(_ lexer: Lexer) { lexer.mode(mode) diff --git a/runtime/Swift/Sources/Antlr4/atn/LexerMoreAction.swift b/runtime/Swift/Sources/Antlr4/atn/LexerMoreAction.swift index 6bea6e82d..0f939037b 100644 --- a/runtime/Swift/Sources/Antlr4/atn/LexerMoreAction.swift +++ b/runtime/Swift/Sources/Antlr4/atn/LexerMoreAction.swift @@ -1,54 +1,41 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * Implements the {@code more} lexer action by calling {@link org.antlr.v4.runtime.Lexer#more}. - * - *

          The {@code more} command does not have any parameters, so this action is - * implemented as a singleton instance exposed by {@link #INSTANCE}.

          - * - * @author Sam Harwell - * @since 4.2 - */ +/// Implements the {@code more} lexer action by calling {@link org.antlr.v4.runtime.Lexer#more}. +/// +///

          The {@code more} command does not have any parameters, so this action is +/// implemented as a singleton instance exposed by {@link #INSTANCE}.

          +/// +/// - Sam Harwell +/// - 4.2 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() - /** - * Constructs the singleton instance of the lexer {@code more} command. - */ + /// Constructs the singleton instance of the lexer {@code more} command. private override init() { } - /** - * {@inheritDoc} - * @return This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#MORE}. - */ + /// {@inheritDoc} + /// - returns: This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#MORE}. override public func getActionType() -> LexerActionType { return LexerActionType.more } - /** - * {@inheritDoc} - * @return This method returns {@code false}. - */ + /// {@inheritDoc} + /// - returns: This method returns {@code false}. override public func isPositionDependent() -> Bool { return false } - /** - * {@inheritDoc} - * - *

          This action is implemented by calling {@link org.antlr.v4.runtime.Lexer#more}.

          - */ + /// {@inheritDoc} + /// + ///

          This action is implemented by calling {@link org.antlr.v4.runtime.Lexer#more}.

          override public func execute(_ lexer: Lexer) { lexer.more() diff --git a/runtime/Swift/Sources/Antlr4/atn/LexerPopModeAction.swift b/runtime/Swift/Sources/Antlr4/atn/LexerPopModeAction.swift index 0acc6589e..8ac62628a 100644 --- a/runtime/Swift/Sources/Antlr4/atn/LexerPopModeAction.swift +++ b/runtime/Swift/Sources/Antlr4/atn/LexerPopModeAction.swift @@ -1,55 +1,42 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * Implements the {@code popMode} lexer action by calling {@link org.antlr.v4.runtime.Lexer#popMode}. - * - *

          The {@code popMode} command does not have any parameters, so this action is - * implemented as a singleton instance exposed by {@link #INSTANCE}.

          - * - * @author Sam Harwell - * @since 4.2 - */ +/// Implements the {@code popMode} lexer action by calling {@link org.antlr.v4.runtime.Lexer#popMode}. +/// +///

          The {@code popMode} command does not have any parameters, so this action is +/// implemented as a singleton instance exposed by {@link #INSTANCE}.

          +/// +/// - Sam Harwell +/// - 4.2 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() - /** - * Constructs the singleton instance of the lexer {@code popMode} command. - */ + /// Constructs the singleton instance of the lexer {@code popMode} command. private override init() { } - /** - * {@inheritDoc} - * @return This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#popMode}. - */ + /// {@inheritDoc} + /// - returns: This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#popMode}. override public func getActionType() -> LexerActionType { return LexerActionType.popMode } - /** - * {@inheritDoc} - * @return This method returns {@code false}. - */ + /// {@inheritDoc} + /// - returns: This method returns {@code false}. public override func isPositionDependent() -> Bool { return false } - /** - * {@inheritDoc} - * - *

          This action is implemented by calling {@link org.antlr.v4.runtime.Lexer#popMode}.

          - */ + /// {@inheritDoc} + /// + ///

          This action is implemented by calling {@link org.antlr.v4.runtime.Lexer#popMode}.

          public override func execute(_ lexer: Lexer) throws { try lexer.popMode() diff --git a/runtime/Swift/Sources/Antlr4/atn/LexerPushModeAction.swift b/runtime/Swift/Sources/Antlr4/atn/LexerPushModeAction.swift index a998f732d..f9761f1c4 100644 --- a/runtime/Swift/Sources/Antlr4/atn/LexerPushModeAction.swift +++ b/runtime/Swift/Sources/Antlr4/atn/LexerPushModeAction.swift @@ -1,62 +1,49 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * Implements the {@code pushMode} lexer action by calling - * {@link org.antlr.v4.runtime.Lexer#pushMode} with the assigned mode. - * - * @author Sam Harwell - * @since 4.2 - */ +/// Implements the {@code pushMode} lexer action by calling +/// {@link org.antlr.v4.runtime.Lexer#pushMode} with the assigned mode. +/// +/// - Sam Harwell +/// - 4.2 public final class LexerPushModeAction: LexerAction, CustomStringConvertible { fileprivate final var mode: Int - /** - * Constructs a new {@code pushMode} action with the specified mode value. - * @param mode The mode value to pass to {@link org.antlr.v4.runtime.Lexer#pushMode}. - */ + /// 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}. public init(_ mode: Int) { self.mode = mode } - /** - * Get the lexer mode this action should transition the lexer to. - * - * @return The lexer mode for this {@code pushMode} command. - */ + /// Get the lexer mode this action should transition the lexer to. + /// + /// - returns: The lexer mode for this {@code pushMode} command. public func getMode() -> Int { return mode } - /** - * {@inheritDoc} - * @return This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#pushMode}. - */ + /// {@inheritDoc} + /// - returns: This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#pushMode}. public override func getActionType() -> LexerActionType { return LexerActionType.pushMode } - /** - * {@inheritDoc} - * @return This method returns {@code false}. - */ + /// {@inheritDoc} + /// - returns: This method returns {@code false}. public override func isPositionDependent() -> Bool { return false } - /** - * {@inheritDoc} - * - *

          This action is implemented by calling {@link org.antlr.v4.runtime.Lexer#pushMode} with the - * value provided by {@link #getMode}.

          - */ + /// {@inheritDoc} + /// + ///

          This action is implemented by calling {@link org.antlr.v4.runtime.Lexer#pushMode} with the + /// value provided by {@link #getMode}.

          override public func execute(_ lexer: Lexer) { lexer.pushMode(mode) diff --git a/runtime/Swift/Sources/Antlr4/atn/LexerSkipAction.swift b/runtime/Swift/Sources/Antlr4/atn/LexerSkipAction.swift index 35893f30a..19a0328b6 100644 --- a/runtime/Swift/Sources/Antlr4/atn/LexerSkipAction.swift +++ b/runtime/Swift/Sources/Antlr4/atn/LexerSkipAction.swift @@ -1,54 +1,41 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * Implements the {@code skip} lexer action by calling {@link org.antlr.v4.runtime.Lexer#skip}. - * - *

          The {@code skip} command does not have any parameters, so this action is - * implemented as a singleton instance exposed by {@link #INSTANCE}.

          - * - * @author Sam Harwell - * @since 4.2 - */ +/// Implements the {@code skip} lexer action by calling {@link org.antlr.v4.runtime.Lexer#skip}. +/// +///

          The {@code skip} command does not have any parameters, so this action is +/// implemented as a singleton instance exposed by {@link #INSTANCE}.

          +/// +/// - Sam Harwell +/// - 4.2 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() - /** - * Constructs the singleton instance of the lexer {@code skip} command. - */ + /// Constructs the singleton instance of the lexer {@code skip} command. private override init() { } - /** - * {@inheritDoc} - * @return This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#SKIP}. - */ + /// {@inheritDoc} + /// - returns: This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#SKIP}. override public func getActionType() -> LexerActionType { return LexerActionType.skip } - /** - * {@inheritDoc} - * @return This method returns {@code false}. - */ + /// {@inheritDoc} + /// - returns: This method returns {@code false}. override public func isPositionDependent() -> Bool { return false } - /** - * {@inheritDoc} - * - *

          This action is implemented by calling {@link org.antlr.v4.runtime.Lexer#skip}.

          - */ + /// {@inheritDoc} + /// + ///

          This action is implemented by calling {@link org.antlr.v4.runtime.Lexer#skip}.

          override public func execute(_ lexer: Lexer) { lexer.skip() diff --git a/runtime/Swift/Sources/Antlr4/atn/LexerTypeAction.swift b/runtime/Swift/Sources/Antlr4/atn/LexerTypeAction.swift index 3934c80aa..ecaef04a8 100644 --- a/runtime/Swift/Sources/Antlr4/atn/LexerTypeAction.swift +++ b/runtime/Swift/Sources/Antlr4/atn/LexerTypeAction.swift @@ -1,60 +1,47 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * Implements the {@code type} lexer action by calling {@link org.antlr.v4.runtime.Lexer#setType} - * with the assigned type. - * - * @author Sam Harwell - * @since 4.2 - */ +/// Implements the {@code type} lexer action by calling {@link org.antlr.v4.runtime.Lexer#setType} +/// with the assigned type. +/// +/// - Sam Harwell +/// - 4.2 public class LexerTypeAction: LexerAction, CustomStringConvertible { fileprivate final var type: Int - /** - * Constructs a new {@code type} action with the specified token type value. - * @param type The type to assign to the token using {@link org.antlr.v4.runtime.Lexer#setType}. - */ + /// 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}. public init(_ type: Int) { self.type = type } - /** - * Gets the type to assign to a token created by the lexer. - * @return 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. public func getType() -> Int { return type } - /** - * {@inheritDoc} - * @return This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#TYPE}. - */ + /// {@inheritDoc} + /// - returns: This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#TYPE}. public override func getActionType() -> LexerActionType { return LexerActionType.type } - /** - * {@inheritDoc} - * @return This method returns {@code false}. - */ + /// {@inheritDoc} + /// - returns: This method returns {@code false}. override public func isPositionDependent() -> Bool { return false } - /** - * {@inheritDoc} - * - *

          This action is implemented by calling {@link org.antlr.v4.runtime.Lexer#setType} with the - * value provided by {@link #getType}.

          - */ + /// {@inheritDoc} + /// + ///

          This action is implemented by calling {@link org.antlr.v4.runtime.Lexer#setType} with the + /// value provided by {@link #getType}.

          public override func execute(_ lexer: Lexer) { lexer.setType(type) diff --git a/runtime/Swift/Sources/Antlr4/atn/LookaheadEventInfo.swift b/runtime/Swift/Sources/Antlr4/atn/LookaheadEventInfo.swift index afe7b519e..b4c1a3468 100644 --- a/runtime/Swift/Sources/Antlr4/atn/LookaheadEventInfo.swift +++ b/runtime/Swift/Sources/Antlr4/atn/LookaheadEventInfo.swift @@ -1,32 +1,27 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * This class represents profiling event information for tracking the lookahead - * depth required in order to make a prediction. - * - * @since 4.3 - */ +/// This class represents profiling event information for tracking the lookahead +/// depth required in order to make a prediction. +/// +/// - 4.3 public class LookaheadEventInfo: DecisionEventInfo { - /** - * Constructs a new instance of the {@link org.antlr.v4.runtime.atn.LookaheadEventInfo} class with - * the specified detailed lookahead information. - * - * @param decision The decision number - * @param configs The final configuration set containing the necessary - * information to determine the result of a prediction, or {@code null} if - * the final configuration set is not available - * @param input The input token stream - * @param startIndex The start index for the current prediction - * @param stopIndex The index at which the prediction was finally made - * @param fullCtx {@code true} if the current lookahead is part of an LL - * prediction; otherwise, {@code false} if the current lookahead is part of - * an SLL prediction - */ + /// Constructs a new instance of the {@link org.antlr.v4.runtime.atn.LookaheadEventInfo} class with + /// the specified detailed lookahead information. + /// + /// - parameter decision: The decision number + /// - parameter configs: The final configuration set containing the necessary + /// information to determine the result of a prediction, or {@code null} if + /// the final configuration set is not available + /// - parameter input: The input token stream + /// - parameter startIndex: The start index for the current prediction + /// - parameter stopIndex: The index at which the prediction was finally made + /// - parameter fullCtx: {@code true} if the current lookahead is part of an LL + /// prediction; otherwise, {@code false} if the current lookahead is part of + /// an SLL prediction public override init(_ decision: Int, _ configs: ATNConfigSet?, _ input: TokenStream, _ startIndex: Int, _ stopIndex: Int, diff --git a/runtime/Swift/Sources/Antlr4/atn/LookupATNConfig.swift b/runtime/Swift/Sources/Antlr4/atn/LookupATNConfig.swift index 3cadf29f0..6d796eb5f 100644 --- a/runtime/Swift/Sources/Antlr4/atn/LookupATNConfig.swift +++ b/runtime/Swift/Sources/Antlr4/atn/LookupATNConfig.swift @@ -1,7 +1,6 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. // // LookupATNConfig.swift diff --git a/runtime/Swift/Sources/Antlr4/atn/LookupDictionary.swift b/runtime/Swift/Sources/Antlr4/atn/LookupDictionary.swift index eabad6523..e7de2cba6 100644 --- a/runtime/Swift/Sources/Antlr4/atn/LookupDictionary.swift +++ b/runtime/Swift/Sources/Antlr4/atn/LookupDictionary.swift @@ -1,7 +1,6 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. // // LookupDictionary.swift diff --git a/runtime/Swift/Sources/Antlr4/atn/LoopEndState.swift b/runtime/Swift/Sources/Antlr4/atn/LoopEndState.swift index 0a5dca192..0043a9187 100644 --- a/runtime/Swift/Sources/Antlr4/atn/LoopEndState.swift +++ b/runtime/Swift/Sources/Antlr4/atn/LoopEndState.swift @@ -1,11 +1,10 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** Mark the end of a * or + loop. */ +/// Mark the end of a * or + loop. public final class LoopEndState: ATNState { public var loopBackState: ATNState? diff --git a/runtime/Swift/Sources/Antlr4/atn/NotSetTransition.swift b/runtime/Swift/Sources/Antlr4/atn/NotSetTransition.swift index 040460ebf..ac2fb5f87 100644 --- a/runtime/Swift/Sources/Antlr4/atn/NotSetTransition.swift +++ b/runtime/Swift/Sources/Antlr4/atn/NotSetTransition.swift @@ -1,7 +1,6 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. public final class NotSetTransition: SetTransition { diff --git a/runtime/Swift/Sources/Antlr4/atn/OrderedATNConfig.swift b/runtime/Swift/Sources/Antlr4/atn/OrderedATNConfig.swift index 01357aca9..2c201d244 100644 --- a/runtime/Swift/Sources/Antlr4/atn/OrderedATNConfig.swift +++ b/runtime/Swift/Sources/Antlr4/atn/OrderedATNConfig.swift @@ -1,7 +1,6 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. // // OrderedATNConfig.swift diff --git a/runtime/Swift/Sources/Antlr4/atn/OrderedATNConfigSet.swift b/runtime/Swift/Sources/Antlr4/atn/OrderedATNConfigSet.swift index 943157f4a..1620d3f25 100644 --- a/runtime/Swift/Sources/Antlr4/atn/OrderedATNConfigSet.swift +++ b/runtime/Swift/Sources/Antlr4/atn/OrderedATNConfigSet.swift @@ -1,13 +1,10 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * - * @author Sam Harwell - */ +/// +/// - Sam Harwell public class OrderedATNConfigSet: ATNConfigSet { diff --git a/runtime/Swift/Sources/Antlr4/atn/ParseInfo.swift b/runtime/Swift/Sources/Antlr4/atn/ParseInfo.swift index b43ff076f..afd9aa08e 100644 --- a/runtime/Swift/Sources/Antlr4/atn/ParseInfo.swift +++ b/runtime/Swift/Sources/Antlr4/atn/ParseInfo.swift @@ -1,16 +1,13 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * This class provides access to specific and aggregate statistics gathered - * during profiling of a parser. - * - * @since 4.3 - */ +/// This class provides access to specific and aggregate statistics gathered +/// during profiling of a parser. +/// +/// - 4.3 public class ParseInfo { internal let atnSimulator: ProfilingATNSimulator @@ -19,25 +16,21 @@ public class ParseInfo { self.atnSimulator = atnSimulator } - /** - * Gets an array of {@link org.antlr.v4.runtime.atn.DecisionInfo} instances containing the profiling - * information gathered for each decision in the ATN. - * - * @return An array of {@link org.antlr.v4.runtime.atn.DecisionInfo} instances, indexed by decision - * number. - */ + /// Gets an array of {@link org.antlr.v4.runtime.atn.DecisionInfo} instances containing the profiling + /// information gathered for each decision in the ATN. + /// + /// - returns: An array of {@link org.antlr.v4.runtime.atn.DecisionInfo} instances, indexed by decision + /// number. public func getDecisionInfo() -> [DecisionInfo] { return atnSimulator.getDecisionInfo() } - /** - * Gets the decision numbers for decisions that required one or more - * full-context predictions during parsing. These are decisions for which - * {@link org.antlr.v4.runtime.atn.DecisionInfo#LL_Fallback} is non-zero. - * - * @return A list of decision numbers which required one or more - * full-context predictions during parsing. - */ + /// Gets the decision numbers for decisions that required one or more + /// full-context predictions during parsing. These are decisions for which + /// {@link org.antlr.v4.runtime.atn.DecisionInfo#LL_Fallback} is non-zero. + /// + /// - returns: A list of decision numbers which required one or more + /// full-context predictions during parsing. public func getLLDecisions() -> Array { var decisions: [DecisionInfo] = atnSimulator.getDecisionInfo() var LL: Array = Array() @@ -52,11 +45,9 @@ public class ParseInfo { return LL } - /** - * Gets the total time spent during prediction across all decisions made - * during parsing. This value is the sum of - * {@link org.antlr.v4.runtime.atn.DecisionInfo#timeInPrediction} for all decisions. - */ + /// Gets the total time spent during prediction across all decisions made + /// during parsing. This value is the sum of + /// {@link org.antlr.v4.runtime.atn.DecisionInfo#timeInPrediction} for all decisions. public func getTotalTimeInPrediction() -> Int64 { var decisions: [DecisionInfo] = atnSimulator.getDecisionInfo() var t: Int64 = 0 @@ -67,11 +58,9 @@ public class ParseInfo { return t } - /** - * Gets the total number of SLL lookahead operations across all decisions - * made during parsing. This value is the sum of - * {@link org.antlr.v4.runtime.atn.DecisionInfo#SLL_TotalLook} for all decisions. - */ + /// Gets the total number of SLL lookahead operations across all decisions + /// made during parsing. This value is the sum of + /// {@link org.antlr.v4.runtime.atn.DecisionInfo#SLL_TotalLook} for all decisions. public func getTotalSLLLookaheadOps() -> Int64 { var decisions: [DecisionInfo] = atnSimulator.getDecisionInfo() var k: Int64 = 0 @@ -82,11 +71,9 @@ public class ParseInfo { return k } - /** - * Gets the total number of LL lookahead operations across all decisions - * made during parsing. This value is the sum of - * {@link org.antlr.v4.runtime.atn.DecisionInfo#LL_TotalLook} for all decisions. - */ + /// Gets the total number of LL lookahead operations across all decisions + /// made during parsing. This value is the sum of + /// {@link org.antlr.v4.runtime.atn.DecisionInfo#LL_TotalLook} for all decisions. public func getTotalLLLookaheadOps() -> Int64 { var decisions: [DecisionInfo] = atnSimulator.getDecisionInfo() var k: Int64 = 0 @@ -97,10 +84,8 @@ public class ParseInfo { return k } - /** - * Gets the total number of ATN lookahead operations for SLL prediction - * across all decisions made during parsing. - */ + /// Gets the total number of ATN lookahead operations for SLL prediction + /// across all decisions made during parsing. public func getTotalSLLATNLookaheadOps() -> Int64 { var decisions: [DecisionInfo] = atnSimulator.getDecisionInfo() var k: Int64 = 0 @@ -111,10 +96,8 @@ public class ParseInfo { return k } - /** - * Gets the total number of ATN lookahead operations for LL prediction - * across all decisions made during parsing. - */ + /// Gets the total number of ATN lookahead operations for LL prediction + /// across all decisions made during parsing. public func getTotalLLATNLookaheadOps() -> Int64 { var decisions: [DecisionInfo] = atnSimulator.getDecisionInfo() var k: Int64 = 0 @@ -125,14 +108,12 @@ public class ParseInfo { return k } - /** - * Gets the total number of ATN lookahead operations for SLL and LL - * prediction across all decisions made during parsing. - * - *

          - * This value is the sum of {@link #getTotalSLLATNLookaheadOps} and - * {@link #getTotalLLATNLookaheadOps}.

          - */ + /// Gets the total number of ATN lookahead operations for SLL and LL + /// prediction across all decisions made during parsing. + /// + ///

          + /// This value is the sum of {@link #getTotalSLLATNLookaheadOps} and + /// {@link #getTotalLLATNLookaheadOps}.

          public func getTotalATNLookaheadOps() -> Int64 { var decisions: [DecisionInfo] = atnSimulator.getDecisionInfo() var k: Int64 = 0 @@ -144,10 +125,8 @@ public class ParseInfo { return k } - /** - * Gets the total number of DFA states stored in the DFA cache for all - * decisions in the ATN. - */ + /// Gets the total number of DFA states stored in the DFA cache for all + /// decisions in the ATN. public func getDFASize() -> Int { var n: Int = 0 let decisionToDFA: [DFA] = atnSimulator.decisionToDFA @@ -158,10 +137,8 @@ public class ParseInfo { return n } - /** - * Gets the total number of DFA states stored in the DFA cache for a - * particular decision. - */ + /// Gets the total number of DFA states stored in the DFA cache for a + /// particular decision. public func getDFASize(_ decision: Int) -> Int { let decisionToDFA: DFA = atnSimulator.decisionToDFA[decision] return decisionToDFA.states.count diff --git a/runtime/Swift/Sources/Antlr4/atn/ParserATNSimulator.swift b/runtime/Swift/Sources/Antlr4/atn/ParserATNSimulator.swift index 3488bff0a..9c4d34fba 100644 --- a/runtime/Swift/Sources/Antlr4/atn/ParserATNSimulator.swift +++ b/runtime/Swift/Sources/Antlr4/atn/ParserATNSimulator.swift @@ -1,237 +1,234 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** -* The embodiment of the adaptive LL(*), ALL(*), parsing strategy. -* -*

          -* The basic complexity of the adaptive strategy makes it harder to understand. -* We begin with ATN simulation to build paths in a DFA. Subsequent prediction -* requests go through the DFA first. If they reach a state without an edge for -* the current symbol, the algorithm fails over to the ATN simulation to -* complete the DFA path for the current input (until it finds a conflict state -* or uniquely predicting state).

          -* -*

          -* All of that is done without using the outer context because we want to create -* a DFA that is not dependent upon the rule invocation stack when we do a -* prediction. One DFA works in all contexts. We avoid using context not -* necessarily because it's slower, although it can be, but because of the DFA -* caching problem. The closure routine only considers the rule invocation stack -* created during prediction beginning in the decision rule. For example, if -* prediction occurs without invoking another rule's ATN, there are no context -* stacks in the configurations. When lack of context leads to a conflict, we -* don't know if it's an ambiguity or a weakness in the strong LL(*) parsing -* strategy (versus full LL(*)).

          -* -*

          -* When SLL yields a configuration set with conflict, we rewind the input and -* retry the ATN simulation, this time using full outer context without adding -* to the DFA. Configuration context stacks will be the full invocation stacks -* from the start rule. If we get a conflict using full context, then we can -* definitively say we have a true ambiguity for that input sequence. If we -* don't get a conflict, it implies that the decision is sensitive to the outer -* context. (It is not context-sensitive in the sense of context-sensitive -* grammars.)

          -* -*

          -* The next time we reach this DFA state with an SLL conflict, through DFA -* simulation, we will again retry the ATN simulation using full context mode. -* This is slow because we can't save the results and have to "interpret" the -* ATN each time we get that input.

          -* -*

          -* CACHING FULL CONTEXT PREDICTIONS

          -* -*

          -* We could cache results from full context to predicted alternative easily and -* that saves a lot of time but doesn't work in presence of predicates. The set -* of visible predicates from the ATN start state changes depending on the -* context, because closure can fall off the end of a rule. I tried to cache -* tuples (stack context, semantic context, predicted alt) but it was slower -* than interpreting and much more complicated. Also required a huge amount of -* memory. The goal is not to create the world's fastest parser anyway. I'd like -* to keep this algorithm simple. By launching multiple threads, we can improve -* the speed of parsing across a large number of files.

          -* -*

          -* There is no strict ordering between the amount of input used by SLL vs LL, -* which makes it really hard to build a cache for full context. Let's say that -* we have input A B C that leads to an SLL conflict with full context X. That -* implies that using X we might only use A B but we could also use A B C D to -* resolve conflict. Input A B C D could predict alternative 1 in one position -* in the input and A B C E could predict alternative 2 in another position in -* input. The conflicting SLL configurations could still be non-unique in the -* full context prediction, which would lead us to requiring more input than the -* original A B C. To make a prediction cache work, we have to track the exact -* input used during the previous prediction. That amounts to a cache that maps -* X to a specific DFA for that context.

          -* -*

          -* Something should be done for left-recursive expression predictions. They are -* likely LL(1) + pred eval. Easier to do the whole SLL unless error and retry -* with full LL thing Sam does.

          -* -*

          -* AVOIDING FULL CONTEXT PREDICTION

          -* -*

          -* We avoid doing full context retry when the outer context is empty, we did not -* dip into the outer context by falling off the end of the decision state rule, -* or when we force SLL mode.

          -* -*

          -* As an example of the not dip into outer context case, consider as super -* constructor calls versus function calls. One grammar might look like -* this:

          -* -*
          -* ctorBody
          -*   : '{' superCall? stat* '}'
          -*   ;
          -* 
          -* -*

          -* Or, you might see something like

          -* -*
          -* stat
          -*   : superCall ';'
          -*   | expression ';'
          -*   | ...
          -*   ;
          -* 
          -* -*

          -* In both cases I believe that no closure operations will dip into the outer -* context. In the first case ctorBody in the worst case will stop at the '}'. -* In the 2nd case it should stop at the ';'. Both cases should stay within the -* entry rule and not dip into the outer context.

          -* -*

          -* PREDICATES

          -* -*

          -* Predicates are always evaluated if present in either SLL or LL both. SLL and -* LL simulation deals with predicates differently. SLL collects predicates as -* it performs closure operations like ANTLR v3 did. It delays predicate -* evaluation until it reaches and accept state. This allows us to cache the SLL -* ATN simulation whereas, if we had evaluated predicates on-the-fly during -* closure, the DFA state configuration sets would be different and we couldn't -* build up a suitable DFA.

          -* -*

          -* When building a DFA accept state during ATN simulation, we evaluate any -* predicates and return the sole semantically valid alternative. If there is -* more than 1 alternative, we report an ambiguity. If there are 0 alternatives, -* we throw an exception. Alternatives without predicates act like they have -* true predicates. The simple way to think about it is to strip away all -* alternatives with false predicates and choose the minimum alternative that -* remains.

          -* -*

          -* When we start in the DFA and reach an accept state that's predicated, we test -* those and return the minimum semantically viable alternative. If no -* alternatives are viable, we throw an exception.

          -* -*

          -* During full LL ATN simulation, closure always evaluates predicates and -* on-the-fly. This is crucial to reducing the configuration set size during -* closure. It hits a landmine when parsing with the Java grammar, for example, -* without this on-the-fly evaluation.

          -* -*

          -* SHARING DFA

          -* -*

          -* All instances of the same parser share the same decision DFAs through a -* static field. Each instance gets its own ATN simulator but they share the -* same {@link #decisionToDFA} field. They also share a -* {@link org.antlr.v4.runtime.atn.PredictionContextCache} object that makes sure that all -* {@link org.antlr.v4.runtime.atn.PredictionContext} objects are shared among the DFA states. This makes -* a big size difference.

          -* -*

          -* THREAD SAFETY

          -* -*

          -* The {@link org.antlr.v4.runtime.atn.ParserATNSimulator} locks on the {@link #decisionToDFA} field when -* it adds a new DFA object to that array. {@link #addDFAEdge} -* locks on the DFA for the current decision when setting the -* {@link org.antlr.v4.runtime.dfa.DFAState#edges} field. {@link #addDFAState} locks on -* the DFA for the current decision when looking up a DFA state to see if it -* already exists. We must make sure that all requests to add DFA states that -* are equivalent result in the same shared DFA object. This is because lots of -* threads will be trying to update the DFA at once. The -* {@link #addDFAState} method also locks inside the DFA lock -* but this time on the shared context cache when it rebuilds the -* configurations' {@link org.antlr.v4.runtime.atn.PredictionContext} objects using cached -* subgraphs/nodes. No other locking occurs, even during DFA simulation. This is -* safe as long as we can guarantee that all threads referencing -* {@code s.edge[t]} get the same physical target {@link org.antlr.v4.runtime.dfa.DFAState}, or -* {@code null}. Once into the DFA, the DFA simulation does not reference the -* {@link org.antlr.v4.runtime.dfa.DFA#states} map. It follows the {@link org.antlr.v4.runtime.dfa.DFAState#edges} field to new -* targets. The DFA simulator will either find {@link org.antlr.v4.runtime.dfa.DFAState#edges} to be -* {@code null}, to be non-{@code null} and {@code dfa.edges[t]} null, or -* {@code dfa.edges[t]} to be non-null. The -* {@link #addDFAEdge} method could be racing to set the field -* but in either case the DFA simulator works; if {@code null}, and requests ATN -* simulation. It could also race trying to get {@code dfa.edges[t]}, but either -* way it will work because it's not doing a test and set operation.

          -* -*

          -* Starting with SLL then failing to combined SLL/LL (Two-Stage -* Parsing)

          -* -*

          -* Sam pointed out that if SLL does not give a syntax error, then there is no -* point in doing full LL, which is slower. We only have to try LL if we get a -* syntax error. For maximum speed, Sam starts the parser set to pure SLL -* mode with the {@link org.antlr.v4.runtime.BailErrorStrategy}:

          -* -*
          -* parser.{@link org.antlr.v4.runtime.Parser#getInterpreter() getInterpreter()}.{@link #setPredictionMode setPredictionMode}{@code (}{@link PredictionMode#SLL}{@code )};
          -* parser.{@link org.antlr.v4.runtime.Parser#setErrorHandler setErrorHandler}(new {@link org.antlr.v4.runtime.BailErrorStrategy}());
          -* 
          -* -*

          -* If it does not get a syntax error, then we're done. If it does get a syntax -* error, we need to retry with the combined SLL/LL strategy.

          -* -*

          -* The reason this works is as follows. If there are no SLL conflicts, then the -* grammar is SLL (at least for that input set). If there is an SLL conflict, -* the full LL analysis must yield a set of viable alternatives which is a -* subset of the alternatives reported by SLL. If the LL set is a singleton, -* then the grammar is LL but not SLL. If the LL set is the same size as the SLL -* set, the decision is SLL. If the LL set has size > 1, then that decision -* is truly ambiguous on the current input. If the LL set is smaller, then the -* SLL conflict resolution might choose an alternative that the full LL would -* rule out as a possibility based upon better context information. If that's -* the case, then the SLL parse will definitely get an error because the full LL -* analysis says it's not viable. If SLL conflict resolution chooses an -* alternative within the LL set, them both SLL and LL would choose the same -* alternative because they both choose the minimum of multiple conflicting -* alternatives.

          -* -*

          -* Let's say we have a set of SLL conflicting alternatives {@code {1, 2, 3}} and -* a smaller LL set called s. If s is {@code {2, 3}}, then SLL -* parsing will get an error because SLL will pursue alternative 1. If -* s is {@code {1, 2}} or {@code {1, 3}} then both SLL and LL will -* choose the same alternative because alternative one is the minimum of either -* set. If s is {@code {2}} or {@code {3}} then SLL will get a syntax -* error. If s is {@code {1}} then SLL will succeed.

          -* -*

          -* Of course, if the input is invalid, then we will get an error for sure in -* both SLL and LL parsing. Erroneous input will therefore require 2 passes over -* the input.

          -*/ +/// The embodiment of the adaptive LL(*), ALL(*), parsing strategy. +/// +///

          +/// The basic complexity of the adaptive strategy makes it harder to understand. +/// We begin with ATN simulation to build paths in a DFA. Subsequent prediction +/// requests go through the DFA first. If they reach a state without an edge for +/// the current symbol, the algorithm fails over to the ATN simulation to +/// complete the DFA path for the current input (until it finds a conflict state +/// or uniquely predicting state).

          +/// +///

          +/// All of that is done without using the outer context because we want to create +/// a DFA that is not dependent upon the rule invocation stack when we do a +/// prediction. One DFA works in all contexts. We avoid using context not +/// necessarily because it's slower, although it can be, but because of the DFA +/// caching problem. The closure routine only considers the rule invocation stack +/// created during prediction beginning in the decision rule. For example, if +/// prediction occurs without invoking another rule's ATN, there are no context +/// stacks in the configurations. When lack of context leads to a conflict, we +/// don't know if it's an ambiguity or a weakness in the strong LL(*) parsing +/// strategy (versus full LL(*)).

          +/// +///

          +/// When SLL yields a configuration set with conflict, we rewind the input and +/// retry the ATN simulation, this time using full outer context without adding +/// to the DFA. Configuration context stacks will be the full invocation stacks +/// from the start rule. If we get a conflict using full context, then we can +/// definitively say we have a true ambiguity for that input sequence. If we +/// don't get a conflict, it implies that the decision is sensitive to the outer +/// context. (It is not context-sensitive in the sense of context-sensitive +/// grammars.)

          +/// +///

          +/// The next time we reach this DFA state with an SLL conflict, through DFA +/// simulation, we will again retry the ATN simulation using full context mode. +/// This is slow because we can't save the results and have to "interpret" the +/// ATN each time we get that input.

          +/// +///

          +/// CACHING FULL CONTEXT PREDICTIONS

          +/// +///

          +/// We could cache results from full context to predicted alternative easily and +/// that saves a lot of time but doesn't work in presence of predicates. The set +/// of visible predicates from the ATN start state changes depending on the +/// context, because closure can fall off the end of a rule. I tried to cache +/// tuples (stack context, semantic context, predicted alt) but it was slower +/// than interpreting and much more complicated. Also required a huge amount of +/// memory. The goal is not to create the world's fastest parser anyway. I'd like +/// to keep this algorithm simple. By launching multiple threads, we can improve +/// the speed of parsing across a large number of files.

          +/// +///

          +/// There is no strict ordering between the amount of input used by SLL vs LL, +/// which makes it really hard to build a cache for full context. Let's say that +/// we have input A B C that leads to an SLL conflict with full context X. That +/// implies that using X we might only use A B but we could also use A B C D to +/// resolve conflict. Input A B C D could predict alternative 1 in one position +/// in the input and A B C E could predict alternative 2 in another position in +/// input. The conflicting SLL configurations could still be non-unique in the +/// full context prediction, which would lead us to requiring more input than the +/// original A B C. To make a prediction cache work, we have to track the exact +/// input used during the previous prediction. That amounts to a cache that maps +/// X to a specific DFA for that context.

          +/// +///

          +/// Something should be done for left-recursive expression predictions. They are +/// likely LL(1) + pred eval. Easier to do the whole SLL unless error and retry +/// with full LL thing Sam does.

          +/// +///

          +/// AVOIDING FULL CONTEXT PREDICTION

          +/// +///

          +/// We avoid doing full context retry when the outer context is empty, we did not +/// dip into the outer context by falling off the end of the decision state rule, +/// or when we force SLL mode.

          +/// +///

          +/// As an example of the not dip into outer context case, consider as super +/// constructor calls versus function calls. One grammar might look like +/// this:

          +/// +///
          +/// ctorBody
          +/// : '{' superCall? stat* '}'
          +/// ;
          +/// 
          +/// +///

          +/// Or, you might see something like

          +/// +///
          +/// stat
          +/// : superCall ';'
          +/// | expression ';'
          +/// | ...
          +/// ;
          +/// 
          +/// +///

          +/// In both cases I believe that no closure operations will dip into the outer +/// context. In the first case ctorBody in the worst case will stop at the '}'. +/// In the 2nd case it should stop at the ';'. Both cases should stay within the +/// entry rule and not dip into the outer context.

          +/// +///

          +/// PREDICATES

          +/// +///

          +/// Predicates are always evaluated if present in either SLL or LL both. SLL and +/// LL simulation deals with predicates differently. SLL collects predicates as +/// it performs closure operations like ANTLR v3 did. It delays predicate +/// evaluation until it reaches and accept state. This allows us to cache the SLL +/// ATN simulation whereas, if we had evaluated predicates on-the-fly during +/// closure, the DFA state configuration sets would be different and we couldn't +/// build up a suitable DFA.

          +/// +///

          +/// When building a DFA accept state during ATN simulation, we evaluate any +/// predicates and return the sole semantically valid alternative. If there is +/// more than 1 alternative, we report an ambiguity. If there are 0 alternatives, +/// we throw an exception. Alternatives without predicates act like they have +/// true predicates. The simple way to think about it is to strip away all +/// alternatives with false predicates and choose the minimum alternative that +/// remains.

          +/// +///

          +/// When we start in the DFA and reach an accept state that's predicated, we test +/// those and return the minimum semantically viable alternative. If no +/// alternatives are viable, we throw an exception.

          +/// +///

          +/// During full LL ATN simulation, closure always evaluates predicates and +/// on-the-fly. This is crucial to reducing the configuration set size during +/// closure. It hits a landmine when parsing with the Java grammar, for example, +/// without this on-the-fly evaluation.

          +/// +///

          +/// SHARING DFA

          +/// +///

          +/// All instances of the same parser share the same decision DFAs through a +/// static field. Each instance gets its own ATN simulator but they share the +/// same {@link #decisionToDFA} field. They also share a +/// {@link org.antlr.v4.runtime.atn.PredictionContextCache} object that makes sure that all +/// {@link org.antlr.v4.runtime.atn.PredictionContext} objects are shared among the DFA states. This makes +/// a big size difference.

          +/// +///

          +/// THREAD SAFETY

          +/// +///

          +/// The {@link org.antlr.v4.runtime.atn.ParserATNSimulator} locks on the {@link #decisionToDFA} field when +/// it adds a new DFA object to that array. {@link #addDFAEdge} +/// locks on the DFA for the current decision when setting the +/// {@link org.antlr.v4.runtime.dfa.DFAState#edges} field. {@link #addDFAState} locks on +/// the DFA for the current decision when looking up a DFA state to see if it +/// already exists. We must make sure that all requests to add DFA states that +/// are equivalent result in the same shared DFA object. This is because lots of +/// threads will be trying to update the DFA at once. The +/// {@link #addDFAState} method also locks inside the DFA lock +/// but this time on the shared context cache when it rebuilds the +/// configurations' {@link org.antlr.v4.runtime.atn.PredictionContext} objects using cached +/// subgraphs/nodes. No other locking occurs, even during DFA simulation. This is +/// safe as long as we can guarantee that all threads referencing +/// {@code s.edge[t]} get the same physical target {@link org.antlr.v4.runtime.dfa.DFAState}, or +/// {@code null}. Once into the DFA, the DFA simulation does not reference the +/// {@link org.antlr.v4.runtime.dfa.DFA#states} map. It follows the {@link org.antlr.v4.runtime.dfa.DFAState#edges} field to new +/// targets. The DFA simulator will either find {@link org.antlr.v4.runtime.dfa.DFAState#edges} to be +/// {@code null}, to be non-{@code null} and {@code dfa.edges[t]} null, or +/// {@code dfa.edges[t]} to be non-null. The +/// {@link #addDFAEdge} method could be racing to set the field +/// but in either case the DFA simulator works; if {@code null}, and requests ATN +/// simulation. It could also race trying to get {@code dfa.edges[t]}, but either +/// way it will work because it's not doing a test and set operation.

          +/// +///

          +/// Starting with SLL then failing to combined SLL/LL (Two-Stage +/// Parsing)

          +/// +///

          +/// Sam pointed out that if SLL does not give a syntax error, then there is no +/// point in doing full LL, which is slower. We only have to try LL if we get a +/// syntax error. For maximum speed, Sam starts the parser set to pure SLL +/// mode with the {@link org.antlr.v4.runtime.BailErrorStrategy}:

          +/// +///
          +/// parser.{@link org.antlr.v4.runtime.Parser#getInterpreter() getInterpreter()}.{@link #setPredictionMode setPredictionMode}{@code (}{@link PredictionMode#SLL}{@code )};
          +/// parser.{@link org.antlr.v4.runtime.Parser#setErrorHandler setErrorHandler}(new {@link org.antlr.v4.runtime.BailErrorStrategy}());
          +/// 
          +/// +///

          +/// If it does not get a syntax error, then we're done. If it does get a syntax +/// error, we need to retry with the combined SLL/LL strategy.

          +/// +///

          +/// The reason this works is as follows. If there are no SLL conflicts, then the +/// grammar is SLL (at least for that input set). If there is an SLL conflict, +/// the full LL analysis must yield a set of viable alternatives which is a +/// subset of the alternatives reported by SLL. If the LL set is a singleton, +/// then the grammar is LL but not SLL. If the LL set is the same size as the SLL +/// set, the decision is SLL. If the LL set has size > 1, then that decision +/// is truly ambiguous on the current input. If the LL set is smaller, then the +/// SLL conflict resolution might choose an alternative that the full LL would +/// rule out as a possibility based upon better context information. If that's +/// the case, then the SLL parse will definitely get an error because the full LL +/// analysis says it's not viable. If SLL conflict resolution chooses an +/// alternative within the LL set, them both SLL and LL would choose the same +/// alternative because they both choose the minimum of multiple conflicting +/// alternatives.

          +/// +///

          +/// Let's say we have a set of SLL conflicting alternatives {@code {1, 2, 3}} and +/// a smaller LL set called s. If s is {@code {2, 3}}, then SLL +/// parsing will get an error because SLL will pursue alternative 1. If +/// s is {@code {1, 2}} or {@code {1, 3}} then both SLL and LL will +/// choose the same alternative because alternative one is the minimum of either +/// set. If s is {@code {2}} or {@code {3}} then SLL will get a syntax +/// error. If s is {@code {1}} then SLL will succeed.

          +/// +///

          +/// Of course, if the input is invalid, then we will get an error for sure in +/// both SLL and LL parsing. Erroneous input will therefore require 2 passes over +/// the input.

          import Foundation open class ParserATNSimulator: ATNSimulator { @@ -239,7 +236,7 @@ open class ParserATNSimulator: ATNSimulator { public let debug_list_atn_decisions: Bool = false public let dfa_debug: Bool = false public let retry_debug: Bool = false - /** Just in case this optimization is bad, add an ENV variable to turn it off */ + /// Just in case this optimization is bad, add an ENV variable to turn it off public static let TURN_OFF_LR_LOOP_ENTRY_BRANCH_OPT: Bool = { if let value = ProcessInfo.processInfo.environment["TURN_OFF_LR_LOOP_ENTRY_BRANCH_OPT"] { return NSString(string: value).boolValue @@ -250,18 +247,17 @@ open class ParserATNSimulator: ATNSimulator { public final var decisionToDFA: [DFA] - /** SLL, LL, or LL + exact ambig detection? */ + /// SLL, LL, or LL + exact ambig detection? private var mode: PredictionMode = PredictionMode.LL - /** Each prediction operation uses a cache for merge of prediction contexts. - * Don't keep around as it wastes huge amounts of memory. DoubleKeyMap - * isn't synchronized but we're ok since two threads shouldn't reuse same - * parser/atnsim object because it can only handle one input at a time. - * This maps graphs a and b to merged result c. (a,b)→c. We can avoid - * the merge if we ever see a and b again. Note that (b,a)→c should - * also be examined during cache lookup. - */ + /// Each prediction operation uses a cache for merge of prediction contexts. + /// Don't keep around as it wastes huge amounts of memory. DoubleKeyMap + /// isn't synchronized but we're ok since two threads shouldn't reuse same + /// parser/atnsim object because it can only handle one input at a time. + /// This maps graphs a and b to merged result c. (a,b)→c. We can avoid + /// the merge if we ever see a and b again. Note that (b,a)→c should + /// also be examined during cache lookup. internal final var mergeCache: DoubleKeyMap? // LAME globals to avoid parameters!!!!! I need these down deep in predTransition @@ -270,7 +266,7 @@ open class ParserATNSimulator: ATNSimulator { internal var _outerContext: ParserRuleContext! internal var _dfa: DFA? - /** Testing only! */ + /// Testing only! // public convenience init(_ atn : ATN, _ decisionToDFA : [DFA], // _ sharedContextCache : PredictionContextCache) // { @@ -354,12 +350,11 @@ open class ParserATNSimulator: ATNSimulator { fullCtx) if dfa.isPrecedenceDfa() { - /* If this is a precedence DFA, we use applyPrecedenceFilter - * to convert the computed start state to a precedence start - * state. We then use DFA.setPrecedenceStartState to set the - * appropriate start state for the precedence level rather - * than simply setting DFA.s0. - */ + /// If this is a precedence DFA, we use applyPrecedenceFilter + /// to convert the computed start state to a precedence start + /// state. We then use DFA.setPrecedenceStartState to set the + /// appropriate start state for the precedence level rather + /// than simply setting DFA.s0. //added by janyou 20160224 // dfa.s0!.configs = s0_closure // not used for prediction but useful to know start configs anyway s0_closure = try applyPrecedenceFilter(s0_closure) @@ -386,36 +381,35 @@ open class ParserATNSimulator: ATNSimulator { } - /** Performs ATN simulation to compute a predicted alternative based - * upon the remaining input, but also updates the DFA cache to avoid - * having to traverse the ATN again for the same input sequence. - - There are some key conditions we're looking for after computing a new - set of ATN configs (proposed DFA state): - * if the set is empty, there is no viable alternative for current symbol - * does the state uniquely predict an alternative? - * does the state have a conflict that would prevent us from - putting it on the work list? - - We also have some key operations to do: - * add an edge from previous DFA state to potentially new DFA state, D, - upon current symbol but only if adding to work list, which means in all - cases except no viable alternative (and possibly non-greedy decisions?) - * collecting predicates and adding semantic context to DFA accept states - * adding rule context to context-sensitive DFA accept states - * consuming an input symbol - * reporting a conflict - * reporting an ambiguity - * reporting a context sensitivity - * reporting insufficient predicates - - cover these cases: - dead end - single alt - single alt + preds - conflict - conflict + preds - */ + /// Performs ATN simulation to compute a predicted alternative based + /// upon the remaining input, but also updates the DFA cache to avoid + /// having to traverse the ATN again for the same input sequence. + /// + /// There are some key conditions we're looking for after computing a new + /// set of ATN configs (proposed DFA state): + /// if the set is empty, there is no viable alternative for current symbol + /// does the state uniquely predict an alternative? + /// does the state have a conflict that would prevent us from + /// putting it on the work list? + /// + /// We also have some key operations to do: + /// add an edge from previous DFA state to potentially new DFA state, D, + /// upon current symbol but only if adding to work list, which means in all + /// cases except no viable alternative (and possibly non-greedy decisions?) + /// collecting predicates and adding semantic context to DFA accept states + /// adding rule context to context-sensitive DFA accept states + /// consuming an input symbol + /// reporting a conflict + /// reporting an ambiguity + /// reporting a context sensitivity + /// reporting insufficient predicates + /// + /// cover these cases: + /// dead end + /// single alt + /// single alt + preds + /// conflict + /// conflict + preds final func execATN(_ dfa: DFA, _ s0: DFAState, _ input: TokenStream, _ startIndex: Int, _ outerContext: ParserRuleContext) throws -> Int { @@ -535,17 +529,15 @@ open class ParserATNSimulator: ATNSimulator { } } - /** - * 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, - * this method returns {@code null}. - * - * @param previousD The current DFA state - * @param t The next 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 - * already cached - */ + /// 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, + /// this method returns {@code null}. + /// + /// - parameter previousD: The current DFA state + /// - parameter t: The next input symbol + /// - returns: The existing target DFA state for the given input symbol + /// {@code t}, or {@code null} if the target state for this edge is not + /// already cached func getExistingTargetState(_ previousD: DFAState, _ t: Int) -> DFAState? { var edges: [DFAState?]? = previousD.edges if edges == nil || (t + 1) < 0 || (t + 1) >= (edges!.count) { @@ -555,18 +547,16 @@ open class ParserATNSimulator: ATNSimulator { return edges![t + 1] } - /** - * Compute a target state for an edge in the DFA, and attempt to add the - * computed state and corresponding edge to the DFA. - * - * @param dfa The DFA - * @param previousD The current DFA state - * @param t The next 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 - * returns {@link #ERROR}. - */ + /// Compute a target state for an edge in the DFA, and attempt to add the + /// computed state and corresponding edge to the DFA. + /// + /// - parameter dfa: The DFA + /// - parameter previousD: The current DFA state + /// - parameter t: The next input symbol + /// + /// - returns: 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 + /// returns {@link #ERROR}. func computeTargetState(_ dfa: DFA, _ previousD: DFAState, _ t: Int) throws -> DFAState { let reach: ATNConfigSet? = try computeReachSet(previousD.configs, t, false) @@ -722,30 +712,28 @@ open class ParserATNSimulator: ATNSimulator { // We do not check predicates here because we have checked them // on-the-fly when doing full context prediction. - /* - In non-exact ambiguity detection mode, we might actually be able to - detect an exact ambiguity, but I'm not going to spend the cycles - needed to check. We only emit ambiguity warnings in exact ambiguity - mode. - - For example, we might know that we have conflicting configurations. - But, that does not mean that there is no way forward without a - conflict. It's possible to have nonconflicting alt subsets as in: - - LL altSubSets=[{1, 2}, {1, 2}, {1}, {1, 2}] - - from - - [(17,1,[5 $]), (13,1,[5 10 $]), (21,1,[5 10 $]), (11,1,[$]), - (13,2,[5 10 $]), (21,2,[5 10 $]), (11,2,[$])] - - In this case, (17,1,[5 $]) indicates there is some next sequence that - would resolve this without conflict to alternative 1. Any other viable - next sequence, however, is associated with a conflict. We stop - looking for input because no amount of further lookahead will alter - the fact that we should predict alternative 1. We just can't say for - sure that there is an ambiguity without looking further. - */ + /// In non-exact ambiguity detection mode, we might actually be able to + /// detect an exact ambiguity, but I'm not going to spend the cycles + /// needed to check. We only emit ambiguity warnings in exact ambiguity + /// mode. + /// + /// For example, we might know that we have conflicting configurations. + /// But, that does not mean that there is no way forward without a + /// conflict. It's possible to have nonconflicting alt subsets as in: + /// + /// LL altSubSets=[{1, 2}, {1, 2}, {1}, {1, 2}] + /// + /// from + /// + /// [(17,1,[5 $]), (13,1,[5 10 $]), (21,1,[5 10 $]), (11,1,[$]), + /// (13,2,[5 10 $]), (21,2,[5 10 $]), (11,2,[$])] + /// + /// In this case, (17,1,[5 $]) indicates there is some next sequence that + /// would resolve this without conflict to alternative 1. Any other viable + /// next sequence, however, is associated with a conflict. We stop + /// looking for input because no amount of further lookahead will alter + /// the fact that we should predict alternative 1. We just can't say for + /// sure that there is an ambiguity without looking further. try reportAmbiguity(dfa, D, startIndex, input.index(), foundExactAmbig, reach.getAlts(), reach) } @@ -765,16 +753,15 @@ open class ParserATNSimulator: ATNSimulator { let intermediate: ATNConfigSet = ATNConfigSet(fullCtx) - /* Configurations already in a rule stop state indicate reaching the end - * of the decision rule (local context) or end of the start rule (full - * context). Once reached, these configurations are never updated by a - * closure operation, so they are handled separately for the performance - * advantage of having a smaller intermediate set when calling closure. - * - * For full-context reach operations, separate handling is required to - * ensure that the alternative matching the longest overall sequence is - * chosen when multiple such configurations can match the input. - */ + /// Configurations already in a rule stop state indicate reaching the end + /// of the decision rule (local context) or end of the start rule (full + /// context). Once reached, these configurations are never updated by a + /// closure operation, so they are handled separately for the performance + /// advantage of having a smaller intermediate set when calling closure. + /// + /// For full-context reach operations, separate handling is required to + /// ensure that the alternative matching the longest overall sequence is + /// chosen when multiple such configurations can match the input. var skippedStopStates: Array? = nil // First figure out where we can reach on input t @@ -816,15 +803,14 @@ open class ParserATNSimulator: ATNSimulator { var reach: ATNConfigSet? = nil - /* This block optimizes the reach operation for intermediate sets which - * trivially indicate a termination state for the overall - * adaptivePredict operation. - * - * The conditions assume that intermediate - * contains all configurations relevant to the reach set, but this - * condition is not true when one or more configurations have been - * withheld in skippedStopStates, or when the current symbol is EOF. - */ + /// This block optimizes the reach operation for intermediate sets which + /// trivially indicate a termination state for the overall + /// adaptivePredict operation. + /// + /// The conditions assume that intermediate + /// contains all configurations relevant to the reach set, but this + /// condition is not true when one or more configurations have been + /// withheld in skippedStopStates, or when the current symbol is EOF. if skippedStopStates == nil && t != CommonToken.EOF { if intermediate.size() == 1 { // Don't pursue the closure if there is just one state. @@ -841,9 +827,8 @@ open class ParserATNSimulator: ATNSimulator { } } - /* If the reach set could not be trivially determined, perform a closure - * operation on the intermediate set to compute its initial value. - */ + /// If the reach set could not be trivially determined, perform a closure + /// operation on the intermediate set to compute its initial value. if reach == nil { reach = ATNConfigSet(fullCtx) var closureBusy: Set = Set() @@ -858,34 +843,32 @@ open class ParserATNSimulator: ATNSimulator { } if t == BufferedTokenStream.EOF { - /* After consuming EOF no additional input is possible, so we are - * only interested in configurations which reached the end of the - * decision rule (local context) or end of the start rule (full - * context). Update reach to contain only these configurations. This - * handles both explicit EOF transitions in the grammar and implicit - * EOF transitions following the end of the decision or start rule. - * - * When reach==intermediate, no closure operation was performed. In - * this case, removeAllConfigsNotInRuleStopState needs to check for - * reachable rule stop states as well as configurations already in - * a rule stop state. - * - * This is handled before the configurations in skippedStopStates, - * because any configurations potentially added from that list are - * already guaranteed to meet this condition whether or not it's - * required. - */ + /// After consuming EOF no additional input is possible, so we are + /// only interested in configurations which reached the end of the + /// decision rule (local context) or end of the start rule (full + /// context). Update reach to contain only these configurations. This + /// handles both explicit EOF transitions in the grammar and implicit + /// EOF transitions following the end of the decision or start rule. + /// + /// When reach==intermediate, no closure operation was performed. In + /// this case, removeAllConfigsNotInRuleStopState needs to check for + /// reachable rule stop states as well as configurations already in + /// a rule stop state. + /// + /// This is handled before the configurations in skippedStopStates, + /// because any configurations potentially added from that list are + /// already guaranteed to meet this condition whether or not it's + /// required. reach = try removeAllConfigsNotInRuleStopState(reach!, reach! === intermediate) } - /* If skippedStopStates is not null, then it contains at least one - * configuration. For full-context reach operations, these - * configurations reached the end of the start rule, in which case we - * only add them back to reach if no configuration during the current - * closure operation reached such a state. This ensures adaptivePredict - * chooses an alternative matching the longest overall sequence when - * multiple alternatives are viable. - */ + /// If skippedStopStates is not null, then it contains at least one + /// configuration. For full-context reach operations, these + /// configurations reached the end of the start rule, in which case we + /// only add them back to reach if no configuration during the current + /// closure operation reached such a state. This ensures adaptivePredict + /// chooses an alternative matching the longest overall sequence when + /// multiple alternatives are viable. if let reach = reach { if skippedStopStates != nil && (!fullCtx || !PredictionMode.hasConfigInRuleStopState(reach)) { assert(!skippedStopStates!.isEmpty, "Expected: !skippedStopStates.isEmpty()") @@ -901,26 +884,24 @@ open class ParserATNSimulator: ATNSimulator { return reach } - /** - * Return a configuration set containing only the configurations from - * {@code configs} which are in a {@link org.antlr.v4.runtime.atn.RuleStopState}. If all - * configurations in {@code configs} are already in a rule stop state, this - * method simply returns {@code configs}. - * - *

          When {@code lookToEndOfRule} is true, this method uses - * {@link org.antlr.v4.runtime.atn.ATN#nextTokens} for each configuration in {@code configs} which is - * not already in a rule stop state to see if a rule stop state is reachable - * from the configuration via epsilon-only transitions.

          - * - * @param configs the configuration set to update - * @param lookToEndOfRule when true, this method checks for rule stop states - * reachable by epsilon-only transitions from each configuration in - * {@code configs}. - * - * @return {@code configs} if all configurations in {@code configs} are in a - * rule stop state, otherwise return a new configuration set containing only - * the configurations from {@code configs} which are in a rule stop state - */ + /// Return a configuration set containing only the configurations from + /// {@code configs} which are in a {@link org.antlr.v4.runtime.atn.RuleStopState}. If all + /// configurations in {@code configs} are already in a rule stop state, this + /// method simply returns {@code configs}. + /// + ///

          When {@code lookToEndOfRule} is true, this method uses + /// {@link org.antlr.v4.runtime.atn.ATN#nextTokens} for each configuration in {@code configs} which is + /// not already in a rule stop state to see if a rule stop state is reachable + /// from the configuration via epsilon-only transitions.

          + /// + /// - parameter configs: the configuration set to update + /// - parameter lookToEndOfRule: when true, this method checks for rule stop states + /// reachable by epsilon-only transitions from each configuration in + /// {@code configs}. + /// + /// - returns: {@code configs} if all configurations in {@code configs} are in a + /// rule stop state, otherwise return a new configuration set containing only + /// the configurations from {@code configs} which are in a rule stop state final func removeAllConfigsNotInRuleStopState(_ configs: ATNConfigSet, _ lookToEndOfRule: Bool) throws -> ATNConfigSet { let result = try configs.removeAllConfigsNotInRuleStopState(&mergeCache,lookToEndOfRule,atn) @@ -947,173 +928,170 @@ open class ParserATNSimulator: ATNSimulator { return configs } - /* parrt internal source braindump that doesn't mess up - * external API spec. + /// parrt internal source braindump that doesn't mess up + /// external API spec. + /// + /// applyPrecedenceFilter is an optimization to avoid highly + /// nonlinear prediction of expressions and other left recursive + /// rules. The precedence predicates such as {3>=prec}? Are highly + /// context-sensitive in that they can only be properly evaluated + /// in the context of the proper prec argument. Without pruning, + /// these predicates are normal predicates evaluated when we reach + /// conflict state (or unique prediction). As we cannot evaluate + /// these predicates out of context, the resulting conflict leads + /// to full LL evaluation and nonlinear prediction which shows up + /// very clearly with fairly large expressions. + /// + /// Example grammar: + /// + /// e : e '*' e + /// | e '+' e + /// | INT + /// ; + /// + /// We convert that to the following: + /// + /// e[int prec] + /// : INT + /// ( {3>=prec}? '*' e[4] + /// | {2>=prec}? '+' e[3] + /// )* + /// ; + /// + /// The (..)* loop has a decision for the inner block as well as + /// an enter or exit decision, which is what concerns us here. At + /// the 1st + of input 1+2+3, the loop entry sees both predicates + /// and the loop exit also sees both predicates by falling off the + /// edge of e. This is because we have no stack information with + /// SLL and find the follow of e, which will hit the return states + /// inside the loop after e[4] and e[3], which brings it back to + /// the enter or exit decision. In this case, we know that we + /// cannot evaluate those predicates because we have fallen off + /// the edge of the stack and will in general not know which prec + /// parameter is the right one to use in the predicate. + /// + /// Because we have special information, that these are precedence + /// predicates, we can resolve them without failing over to full + /// LL despite their context sensitive nature. We make an + /// assumption that prec[-1] <= prec[0], meaning that the current + /// precedence level is greater than or equal to the precedence + /// level of recursive invocations above us in the stack. For + /// example, if predicate {3>=prec}? is true of the current prec, + /// then one option is to enter the loop to match it now. The + /// other option is to exit the loop and the left recursive rule + /// to match the current operator in rule invocation further up + /// the stack. But, we know that all of those prec are lower or + /// the same value and so we can decide to enter the loop instead + /// of matching it later. That means we can strip out the other + /// configuration for the exit branch. + /// + /// So imagine we have (14,1,$,{2>=prec}?) and then + /// (14,2,$-dipsIntoOuterContext,{2>=prec}?). The optimization + /// allows us to collapse these two configurations. We know that + /// if {2>=prec}? is true for the current prec parameter, it will + /// also be true for any prec from an invoking e call, indicated + /// by dipsIntoOuterContext. As the predicates are both true, we + /// have the option to evaluate them early in the decision start + /// state. We do this by stripping both predicates and choosing to + /// enter the loop as it is consistent with the notion of operator + /// precedence. It's also how the full LL conflict resolution + /// would work. + /// + /// The solution requires a different DFA start state for each + /// precedence level. + /// + /// The basic filter mechanism is to remove configurations of the + /// form (p, 2, pi) if (p, 1, pi) exists for the same p and pi. In + /// other words, for the same ATN state and predicate context, + /// remove any configuration associated with an exit branch if + /// there is a configuration associated with the enter branch. + /// + /// It's also the case that the filter evaluates precedence + /// predicates and resolves conflicts according to precedence + /// levels. For example, for input 1+2+3 at the first +, we see + /// prediction filtering + /// + /// [(11,1,[$],{3>=prec}?), (14,1,[$],{2>=prec}?), (5,2,[$],up=1), + /// (11,2,[$],up=1), (14,2,[$],up=1)],hasSemanticContext=true,dipsIntoOuterContext + /// + /// to + /// + /// [(11,1,[$]), (14,1,[$]), (5,2,[$],up=1)],dipsIntoOuterContext + /// + /// This filters because {3>=prec}? evals to true and collapses + /// (11,1,[$],{3>=prec}?) and (11,2,[$],up=1) since early conflict + /// resolution based upon rules of operator precedence fits with + /// our usual match first alt upon conflict. + /// + /// We noticed a problem where a recursive call resets precedence + /// to 0. Sam's fix: each config has flag indicating if it has + /// returned from an expr[0] call. then just don't filter any + /// config with that flag set. flag is carried along in + /// closure(). so to avoid adding field, set bit just under sign + /// bit of dipsIntoOuterContext (SUPPRESS_PRECEDENCE_FILTER). + /// With the change you filter "unless (p, 2, pi) was reached + /// after leaving the rule stop state of the LR rule containing + /// state p, corresponding to a rule invocation with precedence + /// level 0" - applyPrecedenceFilter is an optimization to avoid highly - nonlinear prediction of expressions and other left recursive - rules. The precedence predicates such as {3>=prec}? Are highly - context-sensitive in that they can only be properly evaluated - in the context of the proper prec argument. Without pruning, - these predicates are normal predicates evaluated when we reach - conflict state (or unique prediction). As we cannot evaluate - these predicates out of context, the resulting conflict leads - to full LL evaluation and nonlinear prediction which shows up - very clearly with fairly large expressions. - - Example grammar: - - e : e '*' e - | e '+' e - | INT - ; - - We convert that to the following: - - e[int prec] - : INT - ( {3>=prec}? '*' e[4] - | {2>=prec}? '+' e[3] - )* - ; - - The (..)* loop has a decision for the inner block as well as - an enter or exit decision, which is what concerns us here. At - the 1st + of input 1+2+3, the loop entry sees both predicates - and the loop exit also sees both predicates by falling off the - edge of e. This is because we have no stack information with - SLL and find the follow of e, which will hit the return states - inside the loop after e[4] and e[3], which brings it back to - the enter or exit decision. In this case, we know that we - cannot evaluate those predicates because we have fallen off - the edge of the stack and will in general not know which prec - parameter is the right one to use in the predicate. - - Because we have special information, that these are precedence - predicates, we can resolve them without failing over to full - LL despite their context sensitive nature. We make an - assumption that prec[-1] <= prec[0], meaning that the current - precedence level is greater than or equal to the precedence - level of recursive invocations above us in the stack. For - example, if predicate {3>=prec}? is true of the current prec, - then one option is to enter the loop to match it now. The - other option is to exit the loop and the left recursive rule - to match the current operator in rule invocation further up - the stack. But, we know that all of those prec are lower or - the same value and so we can decide to enter the loop instead - of matching it later. That means we can strip out the other - configuration for the exit branch. - - So imagine we have (14,1,$,{2>=prec}?) and then - (14,2,$-dipsIntoOuterContext,{2>=prec}?). The optimization - allows us to collapse these two configurations. We know that - if {2>=prec}? is true for the current prec parameter, it will - also be true for any prec from an invoking e call, indicated - by dipsIntoOuterContext. As the predicates are both true, we - have the option to evaluate them early in the decision start - state. We do this by stripping both predicates and choosing to - enter the loop as it is consistent with the notion of operator - precedence. It's also how the full LL conflict resolution - would work. - - The solution requires a different DFA start state for each - precedence level. - - The basic filter mechanism is to remove configurations of the - form (p, 2, pi) if (p, 1, pi) exists for the same p and pi. In - other words, for the same ATN state and predicate context, - remove any configuration associated with an exit branch if - there is a configuration associated with the enter branch. - - It's also the case that the filter evaluates precedence - predicates and resolves conflicts according to precedence - levels. For example, for input 1+2+3 at the first +, we see - prediction filtering - - [(11,1,[$],{3>=prec}?), (14,1,[$],{2>=prec}?), (5,2,[$],up=1), - (11,2,[$],up=1), (14,2,[$],up=1)],hasSemanticContext=true,dipsIntoOuterContext - - to - - [(11,1,[$]), (14,1,[$]), (5,2,[$],up=1)],dipsIntoOuterContext - - This filters because {3>=prec}? evals to true and collapses - (11,1,[$],{3>=prec}?) and (11,2,[$],up=1) since early conflict - resolution based upon rules of operator precedence fits with - our usual match first alt upon conflict. - - We noticed a problem where a recursive call resets precedence - to 0. Sam's fix: each config has flag indicating if it has - returned from an expr[0] call. then just don't filter any - config with that flag set. flag is carried along in - closure(). so to avoid adding field, set bit just under sign - bit of dipsIntoOuterContext (SUPPRESS_PRECEDENCE_FILTER). - With the change you filter "unless (p, 2, pi) was reached - after leaving the rule stop state of the LR rule containing - state p, corresponding to a rule invocation with precedence - level 0" - */ - - /** - * This method transforms the start state computed by - * {@link #computeStartState} to the special start state used by a - * precedence DFA for a particular precedence value. The transformation - * process applies the following changes to the start state's configuration - * set. - * - *
            - *
          1. Evaluate the precedence predicates for each configuration using - * {@link org.antlr.v4.runtime.atn.SemanticContext#evalPrecedence}.
          2. - *
          3. When {@link org.antlr.v4.runtime.atn.ATNConfig#isPrecedenceFilterSuppressed} is {@code false}, - * remove all configurations which predict an alternative greater than 1, - * for which another configuration that predicts alternative 1 is in the - * same ATN state with the same prediction context. This transformation is - * valid for the following reasons: - *
              - *
            • The closure block cannot contain any epsilon transitions which bypass - * the body of the closure, so all states reachable via alternative 1 are - * part of the precedence alternatives of the transformed left-recursive - * rule.
            • - *
            • The "primary" portion of a left recursive rule cannot contain an - * epsilon transition, so the only way an alternative other than 1 can exist - * in a state that is also reachable via alternative 1 is by nesting calls - * to the left-recursive rule, with the outer calls not being at the - * preferred precedence level. The - * {@link org.antlr.v4.runtime.atn.ATNConfig#isPrecedenceFilterSuppressed} property marks ATN - * configurations which do not meet this condition, and therefore are not - * eligible for elimination during the filtering process.
            • - *
            - *
          4. - *
          - * - *

          - * The prediction context must be considered by this filter to address - * situations like the following. - *

          - * - *
          -    * grammar TA;
          -    * prog: statement* EOF;
          -    * statement: letterA | statement letterA 'b' ;
          -    * letterA: 'a';
          -    * 
          - *
          - *

          - * If the above grammar, the ATN state immediately before the token - * reference {@code 'a'} in {@code letterA} is reachable from the left edge - * of both the primary and closure blocks of the left-recursive rule - * {@code statement}. The prediction context associated with each of these - * configurations distinguishes between them, and prevents the alternative - * which stepped out to {@code prog} (and then back in to {@code statement} - * from being eliminated by the filter. - *

          - * - * @param configs The configuration set computed by - * {@link #computeStartState} as the start state for the DFA. - * @return The transformed configuration set representing the start state - * for a precedence DFA at a particular precedence level (determined by - * calling {@link org.antlr.v4.runtime.Parser#getPrecedence}). - */ + /// This method transforms the start state computed by + /// {@link #computeStartState} to the special start state used by a + /// precedence DFA for a particular precedence value. The transformation + /// process applies the following changes to the start state's configuration + /// set. + /// + ///
            + ///
          1. Evaluate the precedence predicates for each configuration using + /// {@link org.antlr.v4.runtime.atn.SemanticContext#evalPrecedence}.
          2. + ///
          3. When {@link org.antlr.v4.runtime.atn.ATNConfig#isPrecedenceFilterSuppressed} is {@code false}, + /// remove all configurations which predict an alternative greater than 1, + /// for which another configuration that predicts alternative 1 is in the + /// same ATN state with the same prediction context. This transformation is + /// valid for the following reasons: + ///
              + ///
            • The closure block cannot contain any epsilon transitions which bypass + /// the body of the closure, so all states reachable via alternative 1 are + /// part of the precedence alternatives of the transformed left-recursive + /// rule.
            • + ///
            • The "primary" portion of a left recursive rule cannot contain an + /// epsilon transition, so the only way an alternative other than 1 can exist + /// in a state that is also reachable via alternative 1 is by nesting calls + /// to the left-recursive rule, with the outer calls not being at the + /// preferred precedence level. The + /// {@link org.antlr.v4.runtime.atn.ATNConfig#isPrecedenceFilterSuppressed} property marks ATN + /// configurations which do not meet this condition, and therefore are not + /// eligible for elimination during the filtering process.
            • + ///
            + ///
          4. + ///
          + /// + ///

          + /// The prediction context must be considered by this filter to address + /// situations like the following. + ///

          + /// + ///
          +    /// grammar TA;
          +    /// prog: statement* EOF;
          +    /// statement: letterA | statement letterA 'b' ;
          +    /// letterA: 'a';
          +    /// 
          + ///
          + ///

          + /// If the above grammar, the ATN state immediately before the token + /// reference {@code 'a'} in {@code letterA} is reachable from the left edge + /// of both the primary and closure blocks of the left-recursive rule + /// {@code statement}. The prediction context associated with each of these + /// configurations distinguishes between them, and prevents the alternative + /// which stepped out to {@code prog} (and then back in to {@code statement} + /// from being eliminated by the filter. + ///

          + /// + /// - parameter configs: The configuration set computed by + /// {@link #computeStartState} as the start state for the DFA. + /// - returns: The transformed configuration set representing the start state + /// for a precedence DFA at a particular precedence level (determined by + /// calling {@link org.antlr.v4.runtime.Parser#getPrecedence}). final internal func applyPrecedenceFilter(_ configs: ATNConfigSet) throws -> ATNConfigSet { let configSet = try configs.applyPrecedenceFilter(&mergeCache,parser,_outerContext) @@ -1133,17 +1111,16 @@ open class ParserATNSimulator: ATNSimulator { _ configs: ATNConfigSet, _ nalts: Int) throws -> [SemanticContext?]? { // REACH=[1|1|[]|0:0, 1|2|[]|0:1] - /* altToPred starts as an array of all null contexts. The entry at index i - * corresponds to alternative i. altToPred[i] may have one of three values: - * 1. null: no ATNConfig c is found such that c.alt==i - * 2. SemanticContext.NONE: At least one ATNConfig c exists such that - * c.alt==i and c.semanticContext==SemanticContext.NONE. In other words, - * alt i has at least one unpredicated config. - * 3. Non-NONE Semantic Context: There exists at least one, and for all - * ATNConfig c such that c.alt==i, c.semanticContext!=SemanticContext.NONE. - * - * From this, it is clear that NONE||anything==NONE. - */ + /// altToPred starts as an array of all null contexts. The entry at index i + /// corresponds to alternative i. altToPred[i] may have one of three values: + /// 1. null: no ATNConfig c is found such that c.alt==i + /// 2. SemanticContext.NONE: At least one ATNConfig c exists such that + /// c.alt==i and c.semanticContext==SemanticContext.NONE. In other words, + /// alt i has at least one unpredicated config. + /// 3. Non-NONE Semantic Context: There exists at least one, and for all + /// ATNConfig c such that c.alt==i, c.semanticContext!=SemanticContext.NONE. + /// + /// From this, it is clear that NONE||anything==NONE. let altToPred: [SemanticContext?]? = try configs.getPredsForAmbigAlts(ambigAlts,nalts) if debug { @@ -1178,52 +1155,50 @@ open class ParserATNSimulator: ATNSimulator { return pairs ///pairs.toArray(new, DFAState.PredPrediction[pairs.size()]); } - /** - * This method is used to improve the localization of error messages by - * choosing an alternative rather than throwing a - * {@link org.antlr.v4.runtime.NoViableAltException} in particular prediction scenarios where the - * {@link #ERROR} state was reached during ATN simulation. - * - *

          - * The default implementation of this method uses the following - * algorithm to identify an ATN configuration which successfully parsed the - * decision entry rule. Choosing such an alternative ensures that the - * {@link org.antlr.v4.runtime.ParserRuleContext} returned by the calling rule will be complete - * and valid, and the syntax error will be reported later at a more - * localized location.

          - * - *
            - *
          • If a syntactically valid path or paths reach the end of the decision rule and - * they are semantically valid if predicated, return the min associated alt.
          • - *
          • Else, if a semantically invalid but syntactically valid path exist - * or paths exist, return the minimum associated alt. - *
          • - *
          • Otherwise, return {@link org.antlr.v4.runtime.atn.ATN#INVALID_ALT_NUMBER}.
          • - *
          - * - *

          - * In some scenarios, the algorithm described above could predict an - * alternative which will result in a {@link org.antlr.v4.runtime.FailedPredicateException} in - * the parser. Specifically, this could occur if the only configuration - * capable of successfully parsing to the end of the decision rule is - * blocked by a semantic predicate. By choosing this alternative within - * {@link #adaptivePredict} instead of throwing a - * {@link org.antlr.v4.runtime.NoViableAltException}, the resulting - * {@link org.antlr.v4.runtime.FailedPredicateException} in the parser will identify the specific - * predicate which is preventing the parser from successfully parsing the - * decision rule, which helps developers identify and correct logic errors - * in semantic predicates. - *

          - * - * @param configs The ATN configurations which were valid immediately before - * the {@link #ERROR} state was reached - * @param outerContext The is the \gamma_0 initial parser context from the paper - * or the parser stack at the instant before prediction commences. - * - * @return The value to return from {@link #adaptivePredict}, or - * {@link org.antlr.v4.runtime.atn.ATN#INVALID_ALT_NUMBER} if a suitable alternative was not - * identified and {@link #adaptivePredict} should report an error instead. - */ + /// This method is used to improve the localization of error messages by + /// choosing an alternative rather than throwing a + /// {@link org.antlr.v4.runtime.NoViableAltException} in particular prediction scenarios where the + /// {@link #ERROR} state was reached during ATN simulation. + /// + ///

          + /// The default implementation of this method uses the following + /// algorithm to identify an ATN configuration which successfully parsed the + /// decision entry rule. Choosing such an alternative ensures that the + /// {@link org.antlr.v4.runtime.ParserRuleContext} returned by the calling rule will be complete + /// and valid, and the syntax error will be reported later at a more + /// localized location.

          + /// + ///
            + ///
          • If a syntactically valid path or paths reach the end of the decision rule and + /// they are semantically valid if predicated, return the min associated alt.
          • + ///
          • Else, if a semantically invalid but syntactically valid path exist + /// or paths exist, return the minimum associated alt. + ///
          • + ///
          • Otherwise, return {@link org.antlr.v4.runtime.atn.ATN#INVALID_ALT_NUMBER}.
          • + ///
          + /// + ///

          + /// In some scenarios, the algorithm described above could predict an + /// alternative which will result in a {@link org.antlr.v4.runtime.FailedPredicateException} in + /// the parser. Specifically, this could occur if the only configuration + /// capable of successfully parsing to the end of the decision rule is + /// blocked by a semantic predicate. By choosing this alternative within + /// {@link #adaptivePredict} instead of throwing a + /// {@link org.antlr.v4.runtime.NoViableAltException}, the resulting + /// {@link org.antlr.v4.runtime.FailedPredicateException} in the parser will identify the specific + /// predicate which is preventing the parser from successfully parsing the + /// decision rule, which helps developers identify and correct logic errors + /// in semantic predicates. + ///

          + /// + /// - parameter configs: The ATN configurations which were valid immediately before + /// the {@link #ERROR} state was reached + /// - parameter outerContext: The is the \gamma_0 initial parser context from the paper + /// or the parser stack at the instant before prediction commences. + /// + /// - returns: The value to return from {@link #adaptivePredict}, or + /// {@link org.antlr.v4.runtime.atn.ATN#INVALID_ALT_NUMBER} if a suitable alternative was not + /// identified and {@link #adaptivePredict} should report an error instead. final internal func getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(_ configs: ATNConfigSet, _ outerContext: ParserRuleContext) throws -> Int { let sets: (ATNConfigSet, ATNConfigSet) = try @@ -1251,15 +1226,14 @@ open class ParserATNSimulator: ATNSimulator { return try configs.getAltThatFinishedDecisionEntryRule() } - /** Walk the list of configurations and split them according to - * those that have preds evaluating to true/false. If no pred, assume - * true pred and include in succeeded set. Returns Pair of sets. - * - * Create a new set so as not to alter the incoming parameter. - * - * Assumption: the input stream has been restored to the starting point - * prediction, which is where predicates need to evaluate. - */ + /// Walk the list of configurations and split them according to + /// those that have preds evaluating to true/false. If no pred, assume + /// true pred and include in succeeded set. Returns Pair of sets. + /// + /// Create a new set so as not to alter the incoming parameter. + /// + /// Assumption: the input stream has been restored to the starting point + /// prediction, which is where predicates need to evaluate. final internal func splitAccordingToSemanticValidity( _ configs: ATNConfigSet, _ outerContext: ParserRuleContext) throws -> (ATNConfigSet, ATNConfigSet) { @@ -1267,12 +1241,11 @@ open class ParserATNSimulator: ATNSimulator { return try configs.splitAccordingToSemanticValidity(outerContext,evalSemanticContext) } - /** Look through a list of predicate/alt pairs, returning alts for the - * pairs that win. A {@code NONE} predicate indicates an alt containing an - * unpredicated config which behaves as "always true." If !complete - * then we stop at the first predicate that evaluates to true. This - * includes pairs with null predicates. - */ + /// Look through a list of predicate/alt pairs, returning alts for the + /// pairs that win. A {@code NONE} predicate indicates an alt containing an + /// unpredicated config which behaves as "always true." If !complete + /// then we stop at the first predicate that evaluates to true. This + /// includes pairs with null predicates. final internal func evalSemanticContext(_ predPredictions: [DFAState.PredPrediction], _ outerContext: ParserRuleContext, _ complete: Bool) throws -> BitSet { @@ -1306,46 +1279,43 @@ open class ParserATNSimulator: ATNSimulator { return predictions } - /** - * Evaluate a semantic context within a specific parser context. - * - *

          - * This method might not be called for every semantic context evaluated - * during the prediction process. In particular, we currently do not - * evaluate the following but it may change in the future:

          - * - *
            - *
          • Precedence predicates (represented by - * {@link org.antlr.v4.runtime.atn.SemanticContext.PrecedencePredicate}) are not currently evaluated - * through this method.
          • - *
          • Operator predicates (represented by {@link org.antlr.v4.runtime.atn.SemanticContext.AND} and - * {@link org.antlr.v4.runtime.atn.SemanticContext.OR}) are evaluated as a single semantic - * context, rather than evaluating the operands individually. - * Implementations which require evaluation results from individual - * predicates should override this method to explicitly handle evaluation of - * the operands within operator predicates.
          • - *
          - * - * @param pred The semantic context to evaluate - * @param parserCallStack The parser context in which to evaluate the - * semantic context - * @param alt The alternative which is guarded by {@code pred} - * @param fullCtx {@code true} if the evaluation is occurring during LL - * prediction; otherwise, {@code false} if the evaluation is occurring - * during SLL prediction - * - * @since 4.3 - */ + /// Evaluate a semantic context within a specific parser context. + /// + ///

          + /// This method might not be called for every semantic context evaluated + /// during the prediction process. In particular, we currently do not + /// evaluate the following but it may change in the future:

          + /// + ///
            + ///
          • Precedence predicates (represented by + /// {@link org.antlr.v4.runtime.atn.SemanticContext.PrecedencePredicate}) are not currently evaluated + /// through this method.
          • + ///
          • Operator predicates (represented by {@link org.antlr.v4.runtime.atn.SemanticContext.AND} and + /// {@link org.antlr.v4.runtime.atn.SemanticContext.OR}) are evaluated as a single semantic + /// context, rather than evaluating the operands individually. + /// Implementations which require evaluation results from individual + /// predicates should override this method to explicitly handle evaluation of + /// the operands within operator predicates.
          • + ///
          + /// + /// - parameter pred: The semantic context to evaluate + /// - parameter parserCallStack: The parser context in which to evaluate the + /// semantic context + /// - parameter alt: The alternative which is guarded by {@code pred} + /// - parameter fullCtx: {@code true} if the evaluation is occurring during LL + /// prediction; otherwise, {@code false} if the evaluation is occurring + /// during SLL prediction + /// + /// - 4.3 internal func evalSemanticContext(_ pred: SemanticContext, _ parserCallStack: ParserRuleContext, _ alt: Int, _ fullCtx: Bool) throws -> Bool { return try pred.eval(parser, parserCallStack) } - /* TODO: If we are doing predicates, there is no point in pursuing - closure operations if we reach a DFA state that uniquely predicts - alternative. We will not be caching that DFA state and it is a - waste to pursue the closure. Might have to advance when we do - ambig detection thought :( - */ + /// TODO: If we are doing predicates, there is no point in pursuing + /// closure operations if we reach a DFA state that uniquely predicts + /// alternative. We will not be caching that DFA state and it is a + /// waste to pursue the closure. Might have to advance when we do + /// ambig detection thought :( final internal func closure(_ config: ATNConfig, _ configs: ATNConfigSet, @@ -1428,7 +1398,7 @@ open class ParserATNSimulator: ATNSimulator { fullCtx, depth, treatEofAsEpsilon) } - /** Do the actual work of walking epsilon edges */ + /// Do the actual work of walking epsilon edges final internal func closure_(_ config: ATNConfig, _ configs: ATNConfigSet, _ closureBusy: inout Set, @@ -1517,94 +1487,93 @@ open class ParserATNSimulator: ATNSimulator { //print("That took: "+(finishTime-startTime)+ " ms"); } - /** Implements first-edge (loop entry) elimination as an optimization - * during closure operations. See antlr/antlr4#1398. - * - * The optimization is to avoid adding the loop entry config when - * the exit path can only lead back to the same - * StarLoopEntryState after popping context at the rule end state - * (traversing only epsilon edges, so we're still in closure, in - * this same rule). - * - * We need to detect any state that can reach loop entry on - * epsilon w/o exiting rule. We don't have to look at FOLLOW - * links, just ensure that all stack tops for config refer to key - * states in LR rule. - * - * To verify we are in the right situation we must first check - * closure is at a StarLoopEntryState generated during LR removal. - * Then we check that each stack top of context is a return state - * from one of these cases: - * - * 1. 'not' expr, '(' type ')' expr. The return state points at loop entry state - * 2. expr op expr. The return state is the block end of internal block of (...)* - * 3. 'between' expr 'and' expr. The return state of 2nd expr reference. - * That state points at block end of internal block of (...)*. - * 4. expr '?' expr ':' expr. The return state points at block end, - * which points at loop entry state. - * - * If any is true for each stack top, then closure does not add a - * config to the current config set for edge[0], the loop entry branch. - * - * Conditions fail if any context for the current config is: - * - * a. empty (we'd fall out of expr to do a global FOLLOW which could - * even be to some weird spot in expr) or, - * b. lies outside of expr or, - * c. lies within expr but at a state not the BlockEndState - * generated during LR removal - * - * Do we need to evaluate predicates ever in closure for this case? - * - * No. Predicates, including precedence predicates, are only - * evaluated when computing a DFA start state. I.e., only before - * the lookahead (but not parser) consumes a token. - * - * There are no epsilon edges allowed in LR rule alt blocks or in - * the "primary" part (ID here). If closure is in - * StarLoopEntryState any lookahead operation will have consumed a - * token as there are no epsilon-paths that lead to - * StarLoopEntryState. We do not have to evaluate predicates - * therefore if we are in the generated StarLoopEntryState of a LR - * rule. Note that when making a prediction starting at that - * decision point, decision d=2, compute-start-state performs - * closure starting at edges[0], edges[1] emanating from - * StarLoopEntryState. That means it is not performing closure on - * StarLoopEntryState during compute-start-state. - * - * How do we know this always gives same prediction answer? - * - * Without predicates, loop entry and exit paths are ambiguous - * upon remaining input +b (in, say, a+b). Either paths lead to - * valid parses. Closure can lead to consuming + immediately or by - * falling out of this call to expr back into expr and loop back - * again to StarLoopEntryState to match +b. In this special case, - * we choose the more efficient path, which is to take the bypass - * path. - * - * The lookahead language has not changed because closure chooses - * one path over the other. Both paths lead to consuming the same - * remaining input during a lookahead operation. If the next token - * is an operator, lookahead will enter the choice block with - * operators. If it is not, lookahead will exit expr. Same as if - * closure had chosen to enter the choice block immediately. - * - * Closure is examining one config (some loopentrystate, some alt, - * context) which means it is considering exactly one alt. Closure - * always copies the same alt to any derived configs. - * - * How do we know this optimization doesn't mess up precedence in - * our parse trees? - * - * Looking through expr from left edge of stat only has to confirm - * that an input, say, a+b+c; begins with any valid interpretation - * of an expression. The precedence actually doesn't matter when - * making a decision in stat seeing through expr. It is only when - * parsing rule expr that we must use the precedence to get the - * right interpretation and, hence, parse tree. - * - * @since 4.6 - */ + /// Implements first-edge (loop entry) elimination as an optimization + /// during closure operations. See antlr/antlr4#1398. + /// + /// The optimization is to avoid adding the loop entry config when + /// the exit path can only lead back to the same + /// StarLoopEntryState after popping context at the rule end state + /// (traversing only epsilon edges, so we're still in closure, in + /// this same rule). + /// + /// We need to detect any state that can reach loop entry on + /// epsilon w/o exiting rule. We don't have to look at FOLLOW + /// links, just ensure that all stack tops for config refer to key + /// states in LR rule. + /// + /// To verify we are in the right situation we must first check + /// closure is at a StarLoopEntryState generated during LR removal. + /// Then we check that each stack top of context is a return state + /// from one of these cases: + /// + /// 1. 'not' expr, '(' type ')' expr. The return state points at loop entry state + /// 2. expr op expr. The return state is the block end of internal block of (...)* + /// 3. 'between' expr 'and' expr. The return state of 2nd expr reference. + /// That state points at block end of internal block of (...)*. + /// 4. expr '?' expr ':' expr. The return state points at block end, + /// which points at loop entry state. + /// + /// If any is true for each stack top, then closure does not add a + /// config to the current config set for edge[0], the loop entry branch. + /// + /// Conditions fail if any context for the current config is: + /// + /// a. empty (we'd fall out of expr to do a global FOLLOW which could + /// even be to some weird spot in expr) or, + /// b. lies outside of expr or, + /// c. lies within expr but at a state not the BlockEndState + /// generated during LR removal + /// + /// Do we need to evaluate predicates ever in closure for this case? + /// + /// No. Predicates, including precedence predicates, are only + /// evaluated when computing a DFA start state. I.e., only before + /// the lookahead (but not parser) consumes a token. + /// + /// There are no epsilon edges allowed in LR rule alt blocks or in + /// the "primary" part (ID here). If closure is in + /// StarLoopEntryState any lookahead operation will have consumed a + /// token as there are no epsilon-paths that lead to + /// StarLoopEntryState. We do not have to evaluate predicates + /// therefore if we are in the generated StarLoopEntryState of a LR + /// rule. Note that when making a prediction starting at that + /// decision point, decision d=2, compute-start-state performs + /// closure starting at edges[0], edges[1] emanating from + /// StarLoopEntryState. That means it is not performing closure on + /// StarLoopEntryState during compute-start-state. + /// + /// How do we know this always gives same prediction answer? + /// + /// Without predicates, loop entry and exit paths are ambiguous + /// upon remaining input +b (in, say, a+b). Either paths lead to + /// valid parses. Closure can lead to consuming + immediately or by + /// falling out of this call to expr back into expr and loop back + /// again to StarLoopEntryState to match +b. In this special case, + /// we choose the more efficient path, which is to take the bypass + /// path. + /// + /// The lookahead language has not changed because closure chooses + /// one path over the other. Both paths lead to consuming the same + /// remaining input during a lookahead operation. If the next token + /// is an operator, lookahead will enter the choice block with + /// operators. If it is not, lookahead will exit expr. Same as if + /// closure had chosen to enter the choice block immediately. + /// + /// Closure is examining one config (some loopentrystate, some alt, + /// context) which means it is considering exactly one alt. Closure + /// always copies the same alt to any derived configs. + /// + /// How do we know this optimization doesn't mess up precedence in + /// our parse trees? + /// + /// Looking through expr from left edge of stat only has to confirm + /// that an input, say, a+b+c; begins with any valid interpretation + /// of an expression. The precedence actually doesn't matter when + /// making a decision in stat seeing through expr. It is only when + /// parsing rule expr that we must use the precedence to get the + /// right interpretation and, hence, parse tree. + /// + /// - 4.6 internal func canDropLoopEntryEdgeInLeftRecursiveRule(_ config: ATNConfig) -> Bool { if ParserATNSimulator.TURN_OFF_LR_LOOP_ENTRY_BRANCH_OPT { return false @@ -1838,56 +1807,52 @@ open class ParserATNSimulator: ATNSimulator { return ATNConfig(config, t.target, newContext) } - /** - * Gets a {@link java.util.BitSet} containing the alternatives in {@code configs} - * which are part of one or more conflicting alternative subsets. - * - * @param configs The {@link org.antlr.v4.runtime.atn.ATNConfigSet} to analyze. - * @return The alternatives in {@code configs} which are part of one or more - * conflicting alternative subsets. If {@code configs} does not contain any - * conflicting subsets, this method returns an empty {@link java.util.BitSet}. - */ + /// Gets a {@link java.util.BitSet} containing the alternatives in {@code configs} + /// which are part of one or more conflicting alternative subsets. + /// + /// - parameter configs: The {@link org.antlr.v4.runtime.atn.ATNConfigSet} to analyze. + /// - returns: The alternatives in {@code configs} which are part of one or more + /// conflicting alternative subsets. If {@code configs} does not contain any + /// conflicting subsets, this method returns an empty {@link java.util.BitSet}. final func getConflictingAlts(_ configs: ATNConfigSet) throws -> BitSet { let altsets: Array = try PredictionMode.getConflictingAltSubsets(configs) return PredictionMode.getAlts(altsets) } - /** - Sam pointed out a problem with the previous definition, v3, of - ambiguous states. If we have another state associated with conflicting - alternatives, we should keep going. For example, the following grammar - - s : (ID | ID ID?) ';' ; - - When the ATN simulation reaches the state before ';', it has a DFA - state that looks like: [12|1|[], 6|2|[], 12|2|[]]. Naturally - 12|1|[] and 12|2|[] conflict, but we cannot stop processing this node - because alternative to has another way to continue, via [6|2|[]]. - The key is that we have a single state that has config's only associated - with a single alternative, 2, and crucially the state transitions - among the configurations are all non-epsilon transitions. That means - we don't consider any conflicts that include alternative 2. So, we - ignore the conflict between alts 1 and 2. We ignore a set of - conflicting alts when there is an intersection with an alternative - associated with a single alt state in the state→config-list map. - - It's also the case that we might have two conflicting configurations but - also a 3rd nonconflicting configuration for a different alternative: - [1|1|[], 1|2|[], 8|3|[]]. This can come about from grammar: - - a : A | A | A B ; - - 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 - 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 working on this state. In the previous example, we're concerned - with states associated with the conflicting alternatives. Here alt - 3 is not associated with the conflicting configs, but since we can continue - looking for input reasonably, I don't declare the state done. We - ignore a set of conflicting alts when we have an alternative - that we still need to pursue. - */ + /// Sam pointed out a problem with the previous definition, v3, of + /// ambiguous states. If we have another state associated with conflicting + /// alternatives, we should keep going. For example, the following grammar + /// + /// s : (ID | ID ID?) ';' ; + /// + /// When the ATN simulation reaches the state before ';', it has a DFA + /// state that looks like: [12|1|[], 6|2|[], 12|2|[]]. Naturally + /// 12|1|[] and 12|2|[] conflict, but we cannot stop processing this node + /// because alternative to has another way to continue, via [6|2|[]]. + /// The key is that we have a single state that has config's only associated + /// with a single alternative, 2, and crucially the state transitions + /// among the configurations are all non-epsilon transitions. That means + /// we don't consider any conflicts that include alternative 2. So, we + /// ignore the conflict between alts 1 and 2. We ignore a set of + /// conflicting alts when there is an intersection with an alternative + /// associated with a single alt state in the state→config-list map. + /// + /// It's also the case that we might have two conflicting configurations but + /// also a 3rd nonconflicting configuration for a different alternative: + /// [1|1|[], 1|2|[], 8|3|[]]. This can come about from grammar: + /// + /// a : A | A | A B ; + /// + /// 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 + /// 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 working on this state. In the previous example, we're concerned + /// with states associated with the conflicting alternatives. Here alt + /// 3 is not associated with the conflicting configs, but since we can continue + /// looking for input reasonably, I don't declare the state done. We + /// ignore a set of conflicting alts when we have an alternative + /// that we still need to pursue. final func getConflictingAltsOrUniqueAlt(_ configs: ATNConfigSet) throws -> BitSet { var conflictingAlts: BitSet if configs.uniqueAlt != ATN.INVALID_ALT_NUMBER { @@ -1918,10 +1883,9 @@ open class ParserATNSimulator: ATNSimulator { return try getTokenName(input.LA(1)) } - /** Used for debugging in adaptivePredict around execATN but I cut - * it out for clarity now that alg. works well. We can leave this - * "dead" code for a bit. - */ + /// Used for debugging in adaptivePredict around execATN but I cut + /// it out for clarity now that alg. works well. We can leave this + /// "dead" code for a bit. public final func dumpDeadEndConfigs(_ nvae: NoViableAltException) { errPrint("dead end configs: ") for c: ATNConfig in nvae.getDeadEndConfigs()!.configs { @@ -1969,26 +1933,24 @@ open class ParserATNSimulator: ATNSimulator { return alt } - /** - * Add an edge to the DFA, if possible. This method calls - * {@link #addDFAState} to ensure the {@code to} state is present in the - * DFA. If {@code from} is {@code null}, or if {@code t} is outside the - * range of edges that can be represented in the DFA tables, this method - * returns without adding the edge to the DFA. - * - *

          If {@code to} is {@code null}, this method returns {@code null}. - * Otherwise, this method returns the {@link org.antlr.v4.runtime.dfa.DFAState} returned by calling - * {@link #addDFAState} for the {@code to} state.

          - * - * @param dfa The DFA - * @param from The source state for the edge - * @param t The input symbol - * @param to The target state for the edge - * - * @return If {@code to} is {@code null}, this method returns {@code null}; - * otherwise this method returns the result of calling {@link #addDFAState} - * on {@code to} - */ + /// Add an edge to the DFA, if possible. This method calls + /// {@link #addDFAState} to ensure the {@code to} state is present in the + /// DFA. If {@code from} is {@code null}, or if {@code t} is outside the + /// range of edges that can be represented in the DFA tables, this method + /// returns without adding the edge to the DFA. + /// + ///

          If {@code to} is {@code null}, this method returns {@code null}. + /// Otherwise, this method returns the {@link org.antlr.v4.runtime.dfa.DFAState} returned by calling + /// {@link #addDFAState} for the {@code to} state.

          + /// + /// - parameter dfa: The DFA + /// - parameter from: The source state for the edge + /// - parameter t: The input symbol + /// - parameter to: The target state for the edge + /// + /// - returns: If {@code to} is {@code null}, this method returns {@code null}; + /// otherwise this method returns the result of calling {@link #addDFAState} + /// on {@code to} @discardableResult final func addDFAEdge(_ dfa: DFA, _ from: DFAState?, @@ -2027,21 +1989,19 @@ open class ParserATNSimulator: ATNSimulator { return to } - /** - * Add state {@code D} to the DFA if it is not already present, and return - * the actual instance stored in the DFA. If a state equivalent to {@code D} - * is already in the DFA, the existing state is returned. Otherwise this - * method returns {@code D} after adding it to the DFA. - * - *

          If {@code D} is {@link #ERROR}, this method returns {@link #ERROR} and - * does not change the DFA.

          - * - * @param dfa The dfa - * @param D The DFA state to add - * @return The state stored in the DFA. This will be either the existing - * state if {@code D} is already in the DFA, or {@code D} itself if the - * state was not already present. - */ + /// Add state {@code D} to the DFA if it is not already present, and return + /// the actual instance stored in the DFA. If a state equivalent to {@code D} + /// is already in the DFA, the existing state is returned. Otherwise this + /// method returns {@code D} after adding it to the DFA. + /// + ///

          If {@code D} is {@link #ERROR}, this method returns {@link #ERROR} and + /// does not change the DFA.

          + /// + /// - parameter dfa: The dfa + /// - parameter D: The DFA state to add + /// - returns: The state stored in the DFA. This will be either the existing + /// state if {@code D} is already in the DFA, or {@code D} itself if the + /// state was not already present. final func addDFAState(_ dfa: DFA, _ D: DFAState) throws -> DFAState { if D == ATNSimulator.ERROR { return D @@ -2087,7 +2047,7 @@ open class ParserATNSimulator: ATNSimulator { // } } - /** If context sensitive parsing, we know it's ambiguity not conflict */ + /// If context sensitive parsing, we know it's ambiguity not conflict // configs that LL not SLL considered conflictin internal func reportAmbiguity(_ dfa: DFA, _ D: DFAState, // the DFA state from execATN() that had SLL conflicts @@ -2116,9 +2076,7 @@ open class ParserATNSimulator: ATNSimulator { return mode } - /** - * @since 4.3 - */ + /// - 4.3 public final func getParser() -> Parser { return parser } diff --git a/runtime/Swift/Sources/Antlr4/atn/PlusBlockStartState.swift b/runtime/Swift/Sources/Antlr4/atn/PlusBlockStartState.swift index 5fbdf9a7e..92fd46c8f 100644 --- a/runtime/Swift/Sources/Antlr4/atn/PlusBlockStartState.swift +++ b/runtime/Swift/Sources/Antlr4/atn/PlusBlockStartState.swift @@ -1,15 +1,13 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** 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 - * it for completeness. In reality, the {@link org.antlr.v4.runtime.atn.PlusLoopbackState} node is the - * real decision-making note for {@code A+}. - */ +/// 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 +/// it for completeness. In reality, the {@link org.antlr.v4.runtime.atn.PlusLoopbackState} node is the +/// real decision-making note for {@code A+}. public final class PlusBlockStartState: BlockStartState { public var loopBackState: PlusLoopbackState? diff --git a/runtime/Swift/Sources/Antlr4/atn/PlusLoopbackState.swift b/runtime/Swift/Sources/Antlr4/atn/PlusLoopbackState.swift index a324ea992..82011b409 100644 --- a/runtime/Swift/Sources/Antlr4/atn/PlusLoopbackState.swift +++ b/runtime/Swift/Sources/Antlr4/atn/PlusLoopbackState.swift @@ -1,13 +1,11 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** 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. - */ +/// 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. public final class PlusLoopbackState: DecisionState { diff --git a/runtime/Swift/Sources/Antlr4/atn/PrecedencePredicateTransition.swift b/runtime/Swift/Sources/Antlr4/atn/PrecedencePredicateTransition.swift index 289b21361..5628abf10 100644 --- a/runtime/Swift/Sources/Antlr4/atn/PrecedencePredicateTransition.swift +++ b/runtime/Swift/Sources/Antlr4/atn/PrecedencePredicateTransition.swift @@ -1,14 +1,11 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * - * @author Sam Harwell - */ +/// +/// - Sam Harwell public final class PrecedencePredicateTransition: AbstractPredicateTransition, CustomStringConvertible { public final var precedence: Int diff --git a/runtime/Swift/Sources/Antlr4/atn/PredicateEvalInfo.swift b/runtime/Swift/Sources/Antlr4/atn/PredicateEvalInfo.swift index a5e6cf1f6..761bf1086 100644 --- a/runtime/Swift/Sources/Antlr4/atn/PredicateEvalInfo.swift +++ b/runtime/Swift/Sources/Antlr4/atn/PredicateEvalInfo.swift @@ -1,58 +1,47 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * This class represents profiling event information for semantic predicate - * evaluations which occur during prediction. - * - * @see org.antlr.v4.runtime.atn.ParserATNSimulator#evalSemanticContext - * - * @since 4.3 - */ +/// This class represents profiling event information for semantic predicate +/// evaluations which occur during prediction. +/// +/// - seealso: org.antlr.v4.runtime.atn.ParserATNSimulator#evalSemanticContext +/// +/// - 4.3 public class PredicateEvalInfo: DecisionEventInfo { - /** - * The semantic context which was evaluated. - */ + /// The semantic context which was evaluated. public private(set) var semctx: SemanticContext - /** - * The alternative number for the decision which is guarded by the semantic - * context {@link #semctx}. Note that other ATN - * configurations may predict the same alternative which are guarded by - * other semantic contexts and/or {@link org.antlr.v4.runtime.atn.SemanticContext#NONE}. - */ + /// The alternative number for the decision which is guarded by the semantic + /// context {@link #semctx}. Note that other ATN + /// configurations may predict the same alternative which are guarded by + /// other semantic contexts and/or {@link org.antlr.v4.runtime.atn.SemanticContext#NONE}. 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 - /** - * Constructs a new instance of the {@link org.antlr.v4.runtime.atn.PredicateEvalInfo} class with the - * specified detailed predicate evaluation information. - * - * @param decision The decision number - * @param input The input token stream - * @param startIndex The start index for the current prediction - * @param stopIndex The index at which the predicate evaluation was - * triggered. Note that the input stream may be reset to other positions for - * the actual evaluation of individual predicates. - * @param semctx The semantic context which was evaluated - * @param evalResult The results of evaluating the semantic context - * @param predictedAlt The alternative number for the decision which is - * guarded by the semantic context {@code semctx}. See {@link #predictedAlt} - * for more information. - * @param fullCtx {@code true} if the semantic context was - * evaluated during LL prediction; otherwise, {@code false} if the semantic - * context was evaluated during SLL prediction - * - * @see 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.SemanticContext#eval(org.antlr.v4.runtime.Recognizer, org.antlr.v4.runtime.RuleContext) - */ + /// Constructs a new instance of the {@link org.antlr.v4.runtime.atn.PredicateEvalInfo} class with the + /// specified detailed predicate evaluation information. + /// + /// - parameter decision: The decision number + /// - parameter input: The input token stream + /// - parameter startIndex: The start index for the current prediction + /// - parameter stopIndex: The index at which the predicate evaluation was + /// triggered. Note that the input stream may be reset to other positions for + /// the actual evaluation of individual predicates. + /// - parameter semctx: The semantic context which was evaluated + /// - parameter evalResult: The results of evaluating the semantic context + /// - parameter predictedAlt: The alternative number for the decision which is + /// guarded by the semantic context {@code semctx}. See {@link #predictedAlt} + /// for more information. + /// - parameter fullCtx: {@code true} if the semantic context was + /// evaluated during LL prediction; otherwise, {@code false} if the semantic + /// context was evaluated during SLL prediction + /// + /// - seealso: org.antlr.v4.runtime.atn.ParserATNSimulator#evalSemanticContext(org.antlr.v4.runtime.atn.SemanticContext, org.antlr.v4.runtime.ParserRuleContext, int, boolean) + /// - seealso: org.antlr.v4.runtime.atn.SemanticContext#eval(org.antlr.v4.runtime.Recognizer, org.antlr.v4.runtime.RuleContext) public init(_ decision: Int, _ input: TokenStream, _ startIndex: Int, diff --git a/runtime/Swift/Sources/Antlr4/atn/PredicateTransition.swift b/runtime/Swift/Sources/Antlr4/atn/PredicateTransition.swift index bd327dc38..51d3bad50 100644 --- a/runtime/Swift/Sources/Antlr4/atn/PredicateTransition.swift +++ b/runtime/Swift/Sources/Antlr4/atn/PredicateTransition.swift @@ -1,16 +1,14 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** TODO: this is old comment: - * A tree of semantic predicates from the grammar AST if label==SEMPRED. - * In the ATN, labels will always be exactly one predicate, but the DFA - * may have to combine a bunch of them as it collects predicates from - * multiple ATN configurations into a single DFA state. - */ +/// TODO: this is old comment: +/// A tree of semantic predicates from the grammar AST if label==SEMPRED. +/// In the ATN, labels will always be exactly one predicate, but the DFA +/// may have to combine a bunch of them as it collects predicates from +/// multiple ATN configurations into a single DFA state. public final class PredicateTransition: AbstractPredicateTransition { public let ruleIndex: Int diff --git a/runtime/Swift/Sources/Antlr4/atn/PredictionContext.swift b/runtime/Swift/Sources/Antlr4/atn/PredictionContext.swift index 9291ff847..55be60904 100644 --- a/runtime/Swift/Sources/Antlr4/atn/PredictionContext.swift +++ b/runtime/Swift/Sources/Antlr4/atn/PredictionContext.swift @@ -1,23 +1,18 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. import Foundation public class PredictionContext: Hashable, CustomStringConvertible { - /** - * Represents {@code $} in local context prediction, which means wildcard. - * {@code *+x = *}. - */ + /// Represents {@code $} in local context prediction, which means wildcard. + /// {@code *+x = *}. public static let EMPTY: EmptyPredictionContext = EmptyPredictionContext() - /** - * Represents {@code $} in an array in full context mode, when {@code $} - * doesn't mean wildcard: {@code $ + x = [$,x]}. Here, - * {@code $} = {@link #EMPTY_RETURN_STATE}. - */ + /// Represents {@code $} in an array in full context mode, when {@code $} + /// doesn't mean wildcard: {@code $ + x = [$,x]}. Here, + /// {@code $} = {@link #EMPTY_RETURN_STATE}. public static let EMPTY_RETURN_STATE: Int = Int(Int32.max) private static let INITIAL_HASH: Int = 1 @@ -29,36 +24,33 @@ public class PredictionContext: Hashable, CustomStringConvertible { return oldGlobalNodeCount }() - /** - * 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. - * - *
          -     *  private int referenceHashCode() {
          -     *      int hash = {@link org.antlr.v4.runtime.misc.MurmurHash#initialize MurmurHash.initialize}({@link #INITIAL_HASH});
          -     *
          -     *      for (int i = 0; i < {@link #size()}; i++) {
          -     *          hash = {@link org.antlr.v4.runtime.misc.MurmurHash#update MurmurHash.update}(hash, {@link #getParent getParent}(i));
          -     *      }
          -     *
          -     *      for (int i = 0; i < {@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#finish MurmurHash.finish}(hash, 2 * {@link #size()});
          -     *      return 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. + /// + ///
          +    /// private int referenceHashCode() {
          +    /// int hash = {@link org.antlr.v4.runtime.misc.MurmurHash#initialize MurmurHash.initialize}({@link #INITIAL_HASH});
          +    /// 
          +    /// for (int i = 0; i < {@link #size()}; i++) {
          +    /// hash = {@link org.antlr.v4.runtime.misc.MurmurHash#update MurmurHash.update}(hash, {@link #getParent getParent}(i));
          +    /// }
          +    /// 
          +    /// for (int i = 0; i < {@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#finish MurmurHash.finish}(hash, 2 * {@link #size()});
          +    /// return hash;
          +    /// }
          +    /// 
          public let cachedHashCode: Int init(_ cachedHashCode: Int) { self.cachedHashCode = cachedHashCode } - /** 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. - */ + /// 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. public static func fromRuleContext(_ atn: ATN, _ outerContext: RuleContext?) -> PredictionContext { var _outerContext: RuleContext 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 { return self === PredictionContext.EMPTY } @@ -187,33 +179,31 @@ public class PredictionContext: Hashable, CustomStringConvertible { rootIsWildcard, &mergeCache) } - /** - * Merge two {@link org.antlr.v4.runtime.atn.SingletonPredictionContext} instances. - * - *

          Stack tops equal, parents merge is same; return left graph.
          - *

          - * - *

          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 - * merged parents.
          - *

          - * - *

          Different stack tops pointing to same parent. Make array node for the - * root where both element in the root point to the same (original) - * parent.
          - *

          - * - *

          Different stack tops pointing to different parents. Make array node for - * the root where each element points to the corresponding original - * parent.
          - *

          - * - * @param a the first {@link org.antlr.v4.runtime.atn.SingletonPredictionContext} - * @param b the second {@link org.antlr.v4.runtime.atn.SingletonPredictionContext} - * @param rootIsWildcard {@code true} if this is a local-context merge, - * otherwise false to indicate a full-context merge - * @param mergeCache - */ + /// Merge two {@link org.antlr.v4.runtime.atn.SingletonPredictionContext} instances. + /// + ///

          Stack tops equal, parents merge is same; return left graph.
          + ///

          + /// + ///

          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 + /// merged parents.
          + ///

          + /// + ///

          Different stack tops pointing to same parent. Make array node for the + /// root where both element in the root point to the same (original) + /// parent.
          + ///

          + /// + ///

          Different stack tops pointing to different parents. Make array node for + /// the root where each element points to the corresponding original + /// parent.
          + ///

          + /// + /// - parameter a: the first {@link org.antlr.v4.runtime.atn.SingletonPredictionContext} + /// - parameter b: the second {@link org.antlr.v4.runtime.atn.SingletonPredictionContext} + /// - parameter rootIsWildcard: {@code true} if this is a local-context merge, + /// otherwise false to indicate a full-context merge + /// - parameter mergeCache: public static func mergeSingletons( _ a: 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 - * {@link #EMPTY}. In the following diagrams, the symbol {@code $} is used - * to represent {@link #EMPTY}. - * - *

          Local-Context Merges

          - * - *

          These local-context merge operations are used when {@code rootIsWildcard} - * is true.

          - * - *

          {@link #EMPTY} is superset of any graph; return {@link #EMPTY}.
          - *

          - * - *

          {@link #EMPTY} and anything is {@code #EMPTY}, so merged parent is - * {@code #EMPTY}; return left graph.
          - *

          - * - *

          Special case of last merge if local context.
          - *

          - * - *

          Full-Context Merges

          - * - *

          These full-context merge operations are used when {@code rootIsWildcard} - * is false.

          - * - *

          - * - *

          Must keep all contexts; {@link #EMPTY} in array is a special value (and - * null parent).
          - *

          - * - *

          - * - * @param a the first {@link org.antlr.v4.runtime.atn.SingletonPredictionContext} - * @param b the second {@link org.antlr.v4.runtime.atn.SingletonPredictionContext} - * @param rootIsWildcard {@code true} if this is a local-context merge, - * otherwise false to indicate a full-context merge - */ + /// Handle case where at least one of {@code a} or {@code b} is + /// {@link #EMPTY}. In the following diagrams, the symbol {@code $} is used + /// to represent {@link #EMPTY}. + /// + ///

          Local-Context Merges

          + /// + ///

          These local-context merge operations are used when {@code rootIsWildcard} + /// is true.

          + /// + ///

          {@link #EMPTY} is superset of any graph; return {@link #EMPTY}.
          + ///

          + /// + ///

          {@link #EMPTY} and anything is {@code #EMPTY}, so merged parent is + /// {@code #EMPTY}; return left graph.
          + ///

          + /// + ///

          Special case of last merge if local context.
          + ///

          + /// + ///

          Full-Context Merges

          + /// + ///

          These full-context merge operations are used when {@code rootIsWildcard} + /// is false.

          + /// + ///

          + /// + ///

          Must keep all contexts; {@link #EMPTY} in array is a special value (and + /// null parent).
          + ///

          + /// + ///

          + /// + /// - parameter a: the first {@link org.antlr.v4.runtime.atn.SingletonPredictionContext} + /// - parameter b: the second {@link org.antlr.v4.runtime.atn.SingletonPredictionContext} + /// - parameter rootIsWildcard: {@code true} if this is a local-context merge, + /// otherwise false to indicate a full-context merge public static func mergeRoot(_ a: SingletonPredictionContext, _ b: SingletonPredictionContext, _ rootIsWildcard: Bool) -> PredictionContext? { @@ -376,25 +364,23 @@ public class PredictionContext: Hashable, CustomStringConvertible { return nil } - /** - * Merge two {@link org.antlr.v4.runtime.atn.ArrayPredictionContext} instances. - * - *

          Different tops, different parents.
          - *

          - * - *

          Shared top, same parents.
          - *

          - * - *

          Shared top, different parents.
          - *

          - * - *

          Shared top, all shared parents.
          - *

          - * - *

          Equal tops, merge parents and reduce top to - * {@link org.antlr.v4.runtime.atn.SingletonPredictionContext}.
          - *

          - */ + /// Merge two {@link org.antlr.v4.runtime.atn.ArrayPredictionContext} instances. + /// + ///

          Different tops, different parents.
          + ///

          + /// + ///

          Shared top, same parents.
          + ///

          + /// + ///

          Shared top, different parents.
          + ///

          + /// + ///

          Shared top, all shared parents.
          + ///

          + /// + ///

          Equal tops, merge parents and reduce top to + /// {@link org.antlr.v4.runtime.atn.SingletonPredictionContext}.
          + ///

          public static func mergeArrays( _ a: ArrayPredictionContext, _ b: ArrayPredictionContext, @@ -537,10 +523,8 @@ public class PredictionContext: Hashable, CustomStringConvertible { return M } - /** - * Make pass over all M {@code parents}; merge any {@code equals()} - * ones. - */ + /// Make pass over all M {@code parents}; merge any {@code equals()} + /// ones. // internal static func combineCommonParents(inout parents: [PredictionContext?]) { // var uniqueParents: Dictionary = // Dictionary() diff --git a/runtime/Swift/Sources/Antlr4/atn/PredictionContextCache.swift b/runtime/Swift/Sources/Antlr4/atn/PredictionContextCache.swift index 06366116d..b007ed39c 100644 --- a/runtime/Swift/Sources/Antlr4/atn/PredictionContextCache.swift +++ b/runtime/Swift/Sources/Antlr4/atn/PredictionContextCache.swift @@ -1,13 +1,11 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** 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 - * can be used for both lexers and parsers. - */ +/// 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 +/// can be used for both lexers and parsers. public final class PredictionContextCache { //internal final var @@ -15,10 +13,9 @@ public final class PredictionContextCache { HashMap() public init() { } - /** Add a context to the cache and return it. If the context already exists, - * return that one instead and do not add a new context to the cache. - * Protect shared cache from unsafe thread access. - */ + /// Add a context to the cache and return it. If the context already exists, + /// return that one instead and do not add a new context to the cache. + /// Protect shared cache from unsafe thread access. @discardableResult public func add(_ ctx: PredictionContext) -> PredictionContext { if ctx === PredictionContext.EMPTY { diff --git a/runtime/Swift/Sources/Antlr4/atn/PredictionMode.swift b/runtime/Swift/Sources/Antlr4/atn/PredictionMode.swift index 5cc1feb10..11a368482 100644 --- a/runtime/Swift/Sources/Antlr4/atn/PredictionMode.swift +++ b/runtime/Swift/Sources/Antlr4/atn/PredictionMode.swift @@ -1,15 +1,12 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** -* This enumeration defines the prediction modes available in ANTLR 4 along with -* utility methods for analyzing configuration sets for conflicts and/or -* ambiguities. -*/ +/// This enumeration defines the prediction modes available in ANTLR 4 along with +/// utility methods for analyzing configuration sets for conflicts and/or +/// ambiguities. public enum PredictionMode { /** @@ -73,105 +70,102 @@ public enum PredictionMode { case LL_EXACT_AMBIG_DETECTION - /** - * Computes the SLL prediction termination condition. - * - *

          - * This method computes the SLL prediction termination condition for both of - * the following cases.

          - * - *
            - *
          • The usual SLL+LL fallback upon SLL conflict
          • - *
          • Pure SLL without LL fallback
          • - *
          - * - *

          COMBINED SLL+LL PARSING

          - * - *

          When LL-fallback is enabled upon SLL conflict, correct predictions are - * ensured regardless of how the termination condition is computed by this - * method. Due to the substantially higher cost of LL prediction, the - * prediction should only fall back to LL when the additional lookahead - * cannot lead to a unique SLL prediction.

          - * - *

          Assuming combined SLL+LL parsing, an SLL configuration set with only - * conflicting subsets should fall back to full LL, even if the - * 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 - * configuration, SLL could continue with the hopes that more lookahead will - * resolve via one of those non-conflicting configurations.

          - * - *

          Here's the prediction termination rule them: SLL (for SLL+LL parsing) - * stops when it sees only conflicting configuration subsets. In contrast, - * full LL keeps going when there is uncertainty.

          - * - *

          HEURISTIC

          - * - *

          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. - * The single-alt-state thing lets prediction continue upon rules like - * (otherwise, it would admit defeat too soon):

          - * - *

          {@code [12|1|[], 6|2|[], 12|2|[]]. s : (ID | ID ID?) ';' ;}

          - * - *

          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 - * {@code 12|1|[]} and {@code 12|2|[]} conflict, but we cannot stop - * processing this node because alternative to has another way to continue, - * via {@code [6|2|[]]}.

          - * - *

          It also let's us continue for this rule:

          - * - *

          {@code [1|1|[], 1|2|[], 8|3|[]] a : A | A | A B ;}

          - * - *

          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 - * 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 - * working on this state. In the previous example, we're concerned with - * states associated with the conflicting alternatives. Here alt 3 is not - * associated with the conflicting configs, but since we can continue - * looking for input reasonably, don't declare the state done.

          - * - *

          PURE SLL PARSING

          - * - *

          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 - * predicate. From there, we can do the usual SLL termination heuristic.

          - * - *

          PREDICATES IN SLL+LL PARSING

          - * - *

          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 - * semantic situations. In contrast, full LL evaluates predicates collected - * during start state computation so it can ignore predicates thereafter. - * This means that SLL termination detection can totally ignore semantic - * predicates.

          - * - *

          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 - * following.

          - * - *

          {@code (s, 1, x, {}), (s, 1, x', {p})}

          - * - *

          Before testing these configurations against others, we have to merge - * {@code x} and {@code x'} (without modifying the existing configurations). - * For example, we test {@code (x+x')==x''} when looking for conflicts in - * the following configurations.

          - * - *

          {@code (s, 1, x, {}), (s, 1, x', {p}), (s, 2, x'', {})}

          - * - *

          If the configuration set has predicates (as indicated by - * {@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 - * {@link org.antlr.v4.runtime.atn.ATNConfigSet} will merge everything ignoring predicates.

          - */ + /// Computes the SLL prediction termination condition. + /// + ///

          + /// This method computes the SLL prediction termination condition for both of + /// the following cases.

          + /// + ///
            + ///
          • The usual SLL+LL fallback upon SLL conflict
          • + ///
          • Pure SLL without LL fallback
          • + ///
          + /// + ///

          COMBINED SLL+LL PARSING

          + /// + ///

          When LL-fallback is enabled upon SLL conflict, correct predictions are + /// ensured regardless of how the termination condition is computed by this + /// method. Due to the substantially higher cost of LL prediction, the + /// prediction should only fall back to LL when the additional lookahead + /// cannot lead to a unique SLL prediction.

          + /// + ///

          Assuming combined SLL+LL parsing, an SLL configuration set with only + /// conflicting subsets should fall back to full LL, even if the + /// 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 + /// configuration, SLL could continue with the hopes that more lookahead will + /// resolve via one of those non-conflicting configurations.

          + /// + ///

          Here's the prediction termination rule them: SLL (for SLL+LL parsing) + /// stops when it sees only conflicting configuration subsets. In contrast, + /// full LL keeps going when there is uncertainty.

          + /// + ///

          HEURISTIC

          + /// + ///

          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. + /// The single-alt-state thing lets prediction continue upon rules like + /// (otherwise, it would admit defeat too soon):

          + /// + ///

          {@code [12|1|[], 6|2|[], 12|2|[]]. s : (ID | ID ID?) ';' ;}

          + /// + ///

          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 + /// {@code 12|1|[]} and {@code 12|2|[]} conflict, but we cannot stop + /// processing this node because alternative to has another way to continue, + /// via {@code [6|2|[]]}.

          + /// + ///

          It also let's us continue for this rule:

          + /// + ///

          {@code [1|1|[], 1|2|[], 8|3|[]] a : A | A | A B ;}

          + /// + ///

          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 + /// 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 + /// working on this state. In the previous example, we're concerned with + /// states associated with the conflicting alternatives. Here alt 3 is not + /// associated with the conflicting configs, but since we can continue + /// looking for input reasonably, don't declare the state done.

          + /// + ///

          PURE SLL PARSING

          + /// + ///

          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 + /// predicate. From there, we can do the usual SLL termination heuristic.

          + /// + ///

          PREDICATES IN SLL+LL PARSING

          + /// + ///

          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 + /// semantic situations. In contrast, full LL evaluates predicates collected + /// during start state computation so it can ignore predicates thereafter. + /// This means that SLL termination detection can totally ignore semantic + /// predicates.

          + /// + ///

          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 + /// following.

          + /// + ///

          {@code (s, 1, x, {}), (s, 1, x', {p})}

          + /// + ///

          Before testing these configurations against others, we have to merge + /// {@code x} and {@code x'} (without modifying the existing configurations). + /// For example, we test {@code (x+x')==x''} when looking for conflicts in + /// the following configurations.

          + /// + ///

          {@code (s, 1, x, {}), (s, 1, x', {p}), (s, 2, x'', {})}

          + /// + ///

          If the configuration set has predicates (as indicated by + /// {@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 + /// {@link org.antlr.v4.runtime.atn.ATNConfigSet} will merge everything ignoring predicates.

          public static func hasSLLConflictTerminatingPrediction(_ mode: PredictionMode,_ configs: ATNConfigSet) throws -> Bool { var configs = configs - /* Configs in rule stop states indicate reaching the end of the decision - * rule (local context) or end of start rule (full context). If all - * configs meet this condition, then none of the configurations is able - * to match additional input so we terminate prediction. - */ + /// Configs in rule stop states indicate reaching the end of the decision + /// rule (local context) or end of start rule (full context). If all + /// configs meet this condition, then none of the configurations is able + /// to match additional input so we terminate prediction. if allConfigsInRuleStopStates(configs) { return true } @@ -197,201 +191,191 @@ public enum PredictionMode { return heuristic } - /** - * Checks if any configuration in {@code configs} is in a - * {@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 - * context). - * - * @param configs the configuration set to test - * @return {@code true} if any configuration in {@code configs} is in a - * {@link org.antlr.v4.runtime.atn.RuleStopState}, otherwise {@code false} - */ + /// Checks if any configuration in {@code configs} is in a + /// {@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 + /// context). + /// + /// - parameter configs: the configuration set to test + /// - returns: {@code true} if any configuration in {@code configs} is in a + /// {@link org.antlr.v4.runtime.atn.RuleStopState}, otherwise {@code false} public static func hasConfigInRuleStopState(_ configs: ATNConfigSet) -> Bool { return configs.hasConfigInRuleStopState } - /** - * Checks if all configurations in {@code configs} are in a - * {@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 - * context). - * - * @param configs the configuration set to test - * @return {@code true} if all configurations in {@code configs} are in a - * {@link org.antlr.v4.runtime.atn.RuleStopState}, otherwise {@code false} - */ + /// Checks if all configurations in {@code configs} are in a + /// {@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 + /// context). + /// + /// - parameter configs: the configuration set to test + /// - returns: {@code true} if all configurations in {@code configs} are in a + /// {@link org.antlr.v4.runtime.atn.RuleStopState}, otherwise {@code false} public static func allConfigsInRuleStopStates(_ configs: ATNConfigSet) -> Bool { return configs.allConfigsInRuleStopStates } - /** - * Full LL prediction termination. - * - *

          Can we stop looking ahead during ATN simulation or is there some - * uncertainty as to which alternative we will ultimately pick, after - * consuming more input? Even if there are partial conflicts, we might know - * 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 - * other hand, there might be multiple conflicts that resolve to different - * minimums. That means we need more look ahead to decide which of those - * alternatives we should predict.

          - * - *

          The basic idea is to split the set of configurations {@code C}, into - * conflicting subsets {@code (s, _, ctx, _)} and singleton subsets with - * 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 - * 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}.

          - * - *

          Reduce these configuration subsets to the set of possible alternatives. - * You can compute the alternative subsets in one pass as follows:

          - * - *

          {@code A_s,ctx = {i | (s, i, ctx, _)}} for each configuration in - * {@code C} holding {@code s} and {@code ctx} fixed.

          - * - *

          Or in pseudo-code, for each configuration {@code c} in {@code C}:

          - * - *
          -     * 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
          -     * 
          - * - *

          The values in {@code map} are the set of {@code A_s,ctx} sets.

          - * - *

          If {@code |A_s,ctx|=1} then there is no conflict associated with - * {@code s} and {@code ctx}.

          - * - *

          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 - * more lookahead will help us. We will always pick that alternative. If, - * however, there is more than one alternative, then we are uncertain which - * 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 - * conflicting subsets this round.

          - * - *

          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 - * 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 - * might even look until the end of file.

          - * - *

          No special consideration for semantic predicates is required because - * predicates are evaluated on-the-fly for full LL prediction, ensuring that - * no configuration contains a semantic context during the termination - * check.

          - * - *

          CONFLICTING CONFIGS

          - * - *

          Two configurations {@code (s, i, x)} and {@code (s, j, x')}, conflict - * when {@code i!=j} but {@code x=x'}. Because we merge all - * {@code (s, i, _)} configurations together, that means that there are at - * most {@code n} configurations associated with state {@code s} for - * {@code n} possible alternatives in the decision. The merged stacks - * 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 - * 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} - * 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 - * associated with {@code j>i} then at least one stack configuration for - * {@code j} is not in conflict with alternative {@code i}. The algorithm - * should keep going, looking for more lookahead due to the uncertainty.

          - * - *

          For simplicity, I'm doing a equality check between {@code x} and - * {@code x'} that lets the algorithm continue to consume lookahead longer - * 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 - * alternatives that are actually in conflict.

          - * - *

          CONTINUE/STOP RULE

          - * - *

          Continue if union of resolved alternative sets from non-conflicting and - * conflicting alternative subsets has more than one alternative. We are - * uncertain about which alternative to predict.

          - * - *

          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 - * consumed at this point. The conflicting sets let us to strip away - * configurations that won't lead to more states because we resolve - * conflicts to the configuration with a minimum alternate for the - * conflicting set.

          - * - *

          CASES

          - * - *
            - * - *
          • no conflicts and more than 1 alternative in set => continue
          • - * - *
          • {@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 {3}} U conflicting sets {@code min({1,2})} U {@code min({1,2})} = - * {@code {1,3}} => continue - *
          • - * - *
          • {@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 {1}} U conflicting sets {@code min({1,2})} U {@code min({1,2})} = - * {@code {1}} => stop and predict 1
          • - * - *
          • {@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 1, y)}, - * {@code (s', 2, y)} yields conflicting, reduced sets {@code {1}} U - * {@code {1}} = {@code {1}} => stop and predict 1, can announce - * ambiguity {@code {1,2}}
          • - * - *
          • {@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 2, y)}, - * {@code (s', 3, y)} yields conflicting, reduced sets {@code {1}} U - * {@code {2}} = {@code {1,2}} => continue
          • - * - *
          • {@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 3, y)}, - * {@code (s', 4, y)} yields conflicting, reduced sets {@code {1}} U - * {@code {3}} = {@code {1,3}} => continue
          • - * - *
          - * - *

          EXACT AMBIGUITY DETECTION

          - * - *

          If all states report the same conflicting set of alternatives, then we - * know we have the exact ambiguity set.

          - * - *

          |A_i|>1 and - * A_i = A_j for all i, j.

          - * - *

          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 - * {@code A={{1,2}, {1,3}}}, then regular LL prediction would terminate - * 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 - * 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 - * {@code A={{1,2}}} or {@code {{1,2},{1,2}}}, etc...

          - */ + /// Full LL prediction termination. + /// + ///

          Can we stop looking ahead during ATN simulation or is there some + /// uncertainty as to which alternative we will ultimately pick, after + /// consuming more input? Even if there are partial conflicts, we might know + /// 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 + /// other hand, there might be multiple conflicts that resolve to different + /// minimums. That means we need more look ahead to decide which of those + /// alternatives we should predict.

          + /// + ///

          The basic idea is to split the set of configurations {@code C}, into + /// conflicting subsets {@code (s, _, ctx, _)} and singleton subsets with + /// 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 + /// 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}.

          + /// + ///

          Reduce these configuration subsets to the set of possible alternatives. + /// You can compute the alternative subsets in one pass as follows:

          + /// + ///

          {@code A_s,ctx = {i | (s, i, ctx, _)}} for each configuration in + /// {@code C} holding {@code s} and {@code ctx} fixed.

          + /// + ///

          Or in pseudo-code, for each configuration {@code c} in {@code C}:

          + /// + ///
          +    /// 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
          +    /// 
          + /// + ///

          The values in {@code map} are the set of {@code A_s,ctx} sets.

          + /// + ///

          If {@code |A_s,ctx|=1} then there is no conflict associated with + /// {@code s} and {@code ctx}.

          + /// + ///

          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 + /// more lookahead will help us. We will always pick that alternative. If, + /// however, there is more than one alternative, then we are uncertain which + /// 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 + /// conflicting subsets this round.

          + /// + ///

          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 + /// 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 + /// might even look until the end of file.

          + /// + ///

          No special consideration for semantic predicates is required because + /// predicates are evaluated on-the-fly for full LL prediction, ensuring that + /// no configuration contains a semantic context during the termination + /// check.

          + /// + ///

          CONFLICTING CONFIGS

          + /// + ///

          Two configurations {@code (s, i, x)} and {@code (s, j, x')}, conflict + /// when {@code i!=j} but {@code x=x'}. Because we merge all + /// {@code (s, i, _)} configurations together, that means that there are at + /// most {@code n} configurations associated with state {@code s} for + /// {@code n} possible alternatives in the decision. The merged stacks + /// 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 + /// 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} + /// 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 + /// associated with {@code j>i} then at least one stack configuration for + /// {@code j} is not in conflict with alternative {@code i}. The algorithm + /// should keep going, looking for more lookahead due to the uncertainty.

          + /// + ///

          For simplicity, I'm doing a equality check between {@code x} and + /// {@code x'} that lets the algorithm continue to consume lookahead longer + /// 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 + /// alternatives that are actually in conflict.

          + /// + ///

          CONTINUE/STOP RULE

          + /// + ///

          Continue if union of resolved alternative sets from non-conflicting and + /// conflicting alternative subsets has more than one alternative. We are + /// uncertain about which alternative to predict.

          + /// + ///

          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 + /// consumed at this point. The conflicting sets let us to strip away + /// configurations that won't lead to more states because we resolve + /// conflicts to the configuration with a minimum alternate for the + /// conflicting set.

          + /// + ///

          CASES

          + /// + ///
            + /// + ///
          • no conflicts and more than 1 alternative in set => continue
          • + /// + ///
          • {@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 {3}} U conflicting sets {@code min({1,2})} U {@code min({1,2})} = + /// {@code {1,3}} => continue + ///
          • + /// + ///
          • {@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 {1}} U conflicting sets {@code min({1,2})} U {@code min({1,2})} = + /// {@code {1}} => stop and predict 1
          • + /// + ///
          • {@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 1, y)}, + /// {@code (s', 2, y)} yields conflicting, reduced sets {@code {1}} U + /// {@code {1}} = {@code {1}} => stop and predict 1, can announce + /// ambiguity {@code {1,2}}
          • + /// + ///
          • {@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 2, y)}, + /// {@code (s', 3, y)} yields conflicting, reduced sets {@code {1}} U + /// {@code {2}} = {@code {1,2}} => continue
          • + /// + ///
          • {@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 3, y)}, + /// {@code (s', 4, y)} yields conflicting, reduced sets {@code {1}} U + /// {@code {3}} = {@code {1,3}} => continue
          • + /// + ///
          + /// + ///

          EXACT AMBIGUITY DETECTION

          + /// + ///

          If all states report the same conflicting set of alternatives, then we + /// know we have the exact ambiguity set.

          + /// + ///

          |A_i|>1 and + /// A_i = A_j for all i, j.

          + /// + ///

          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 + /// {@code A={{1,2}, {1,3}}}, then regular LL prediction would terminate + /// 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 + /// 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 + /// {@code A={{1,2}}} or {@code {{1,2},{1,2}}}, etc...

          public static func resolvesToJustOneViableAlt(_ altsets: Array) throws -> Int { return try getSingleViableAlt(altsets) } - /** - * Determines if every alternative subset in {@code altsets} contains more - * than one alternative. - * - * @param altsets a collection of alternative subsets - * @return {@code true} if every {@link java.util.BitSet} in {@code altsets} has - * {@link java.util.BitSet#cardinality cardinality} > 1, otherwise {@code false} - */ + /// Determines if every alternative subset in {@code altsets} contains more + /// than one alternative. + /// + /// - parameter altsets: a collection of alternative subsets + /// - returns: {@code true} if every {@link java.util.BitSet} in {@code altsets} has + /// {@link java.util.BitSet#cardinality cardinality} > 1, otherwise {@code false} public static func allSubsetsConflict(_ altsets: Array) -> Bool { return !hasNonConflictingAltSet(altsets) } - /** - * Determines if any single alternative subset in {@code altsets} contains - * exactly one alternative. - * - * @param altsets a collection of alternative subsets - * @return {@code true} if {@code altsets} contains a {@link java.util.BitSet} with - * {@link java.util.BitSet#cardinality cardinality} 1, otherwise {@code false} - */ + /// Determines if any single alternative subset in {@code altsets} contains + /// exactly one alternative. + /// + /// - parameter altsets: a collection of alternative subsets + /// - returns: {@code true} if {@code altsets} contains a {@link java.util.BitSet} with + /// {@link java.util.BitSet#cardinality cardinality} 1, otherwise {@code false} public static func hasNonConflictingAltSet(_ altsets: Array) -> Bool { for alts: BitSet in altsets { if alts.cardinality() == 1 { @@ -401,14 +385,12 @@ public enum PredictionMode { return false } - /** - * Determines if any single alternative subset in {@code altsets} contains - * more than one alternative. - * - * @param altsets a collection of alternative subsets - * @return {@code true} if {@code altsets} contains a {@link java.util.BitSet} with - * {@link java.util.BitSet#cardinality cardinality} > 1, otherwise {@code false} - */ + /// Determines if any single alternative subset in {@code altsets} contains + /// more than one alternative. + /// + /// - parameter altsets: a collection of alternative subsets + /// - returns: {@code true} if {@code altsets} contains a {@link java.util.BitSet} with + /// {@link java.util.BitSet#cardinality cardinality} > 1, otherwise {@code false} public static func hasConflictingAltSet(_ altsets: Array) -> Bool { for alts: BitSet in altsets { if alts.cardinality() > 1 { @@ -418,13 +400,11 @@ public enum PredictionMode { return false } - /** - * Determines if every alternative subset in {@code altsets} is equivalent. - * - * @param altsets a collection of alternative subsets - * @return {@code true} if every member of {@code altsets} is equal to the - * others, otherwise {@code false} - */ + /// Determines if every alternative subset in {@code altsets} is equivalent. + /// + /// - parameter altsets: a collection of alternative subsets + /// - returns: {@code true} if every member of {@code altsets} is equal to the + /// others, otherwise {@code false} public static func allSubsetsEqual(_ altsets: Array) -> Bool { let first: BitSet = altsets[0] @@ -437,13 +417,11 @@ public enum PredictionMode { return true } - /** - * Returns the unique alternative predicted by all alternative subsets in - * {@code altsets}. If no such alternative exists, this method returns - * {@link org.antlr.v4.runtime.atn.ATN#INVALID_ALT_NUMBER}. - * - * @param altsets a collection of alternative subsets - */ + /// Returns the unique alternative predicted by all alternative subsets in + /// {@code altsets}. If no such alternative exists, this method returns + /// {@link org.antlr.v4.runtime.atn.ATN#INVALID_ALT_NUMBER}. + /// + /// - parameter altsets: a collection of alternative subsets public static func getUniqueAlt(_ altsets: Array) throws -> Int { let all: BitSet = getAlts(altsets) if all.cardinality() == 1 { @@ -452,14 +430,12 @@ public enum PredictionMode { return ATN.INVALID_ALT_NUMBER } - /** - * Gets the complete set of represented alternatives for a collection of - * alternative subsets. This method returns the union of each {@link java.util.BitSet} - * in {@code altsets}. - * - * @param altsets a collection of alternative subsets - * @return the set of represented alternatives in {@code altsets} - */ + /// Gets the complete set of represented alternatives for a collection of + /// alternative subsets. This method returns the union of each {@link java.util.BitSet} + /// in {@code altsets}. + /// + /// - parameter altsets: a collection of alternative subsets + /// - returns: the set of represented alternatives in {@code altsets} public static func getAlts(_ altsets: Array) -> BitSet { let all: BitSet = BitSet() for alts: BitSet in altsets { @@ -468,36 +444,32 @@ public enum PredictionMode { 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 { return try configs.getAltBitSet() } - /** - * This function gets the conflicting alt subsets from a configuration set. - * For each configuration {@code c} in {@code configs}: - * - *
          -     * 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
          -     * 
          - */ + /// This function gets the conflicting alt subsets from a configuration set. + /// For each configuration {@code c} in {@code configs}: + /// + ///
          +    /// 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
          +    /// 
          public static func getConflictingAltSubsets(_ configs: ATNConfigSet) throws -> Array { return try configs.getConflictingAltSubsets() } - /** - * Get a map from state to alt subset from a configuration set. For each - * configuration {@code c} in {@code configs}: - * - *
          -     * map[c.{@link org.antlr.v4.runtime.atn.ATNConfig#state state}] U= c.{@link org.antlr.v4.runtime.atn.ATNConfig#alt alt}
          -     * 
          - */ + /// Get a map from state to alt subset from a configuration set. For each + /// configuration {@code c} in {@code configs}: + /// + ///
          +    /// map[c.{@link org.antlr.v4.runtime.atn.ATNConfig#state state}] U= c.{@link org.antlr.v4.runtime.atn.ATNConfig#alt alt}
          +    /// 
          public static func getStateToAltMap(_ configs: ATNConfigSet) throws -> HashMap { return try configs.getStateToAltMap() diff --git a/runtime/Swift/Sources/Antlr4/atn/ProfilingATNSimulator.swift b/runtime/Swift/Sources/Antlr4/atn/ProfilingATNSimulator.swift index 23ef4bee6..193d00f2d 100644 --- a/runtime/Swift/Sources/Antlr4/atn/ProfilingATNSimulator.swift +++ b/runtime/Swift/Sources/Antlr4/atn/ProfilingATNSimulator.swift @@ -1,12 +1,9 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** -* @since 4.3 -*/ +/// - 4.3 import Foundation @@ -20,17 +17,16 @@ public class ProfilingATNSimulator: ParserATNSimulator { internal var currentDecision: Int = 0 internal var currentState: DFAState? - /** 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. - * 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. - * 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 - * 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. - * It may in fact still be a context sensitivity but we don't know by looking at the - * minimum alternatives for the current input. - */ + /// 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. + /// 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. + /// 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 + /// 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. + /// It may in fact still be a context sensitivity but we don't know by looking at the + /// minimum alternatives for the current input. internal var conflictingAltResolvedBySLL: Int = 0 public init(_ parser: Parser) { diff --git a/runtime/Swift/Sources/Antlr4/atn/RangeTransition.swift b/runtime/Swift/Sources/Antlr4/atn/RangeTransition.swift index 1318cd526..f7440e1c1 100644 --- a/runtime/Swift/Sources/Antlr4/atn/RangeTransition.swift +++ b/runtime/Swift/Sources/Antlr4/atn/RangeTransition.swift @@ -1,7 +1,6 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. public final class RangeTransition: Transition, CustomStringConvertible { diff --git a/runtime/Swift/Sources/Antlr4/atn/RuleStartState.swift b/runtime/Swift/Sources/Antlr4/atn/RuleStartState.swift index b2fd854fa..92a45b388 100644 --- a/runtime/Swift/Sources/Antlr4/atn/RuleStartState.swift +++ b/runtime/Swift/Sources/Antlr4/atn/RuleStartState.swift @@ -1,7 +1,6 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. public final class RuleStartState: ATNState { diff --git a/runtime/Swift/Sources/Antlr4/atn/RuleStopState.swift b/runtime/Swift/Sources/Antlr4/atn/RuleStopState.swift index da06b9b62..629e8a5c4 100644 --- a/runtime/Swift/Sources/Antlr4/atn/RuleStopState.swift +++ b/runtime/Swift/Sources/Antlr4/atn/RuleStopState.swift @@ -1,15 +1,13 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** The last node in the ATN for a rule, unless that rule is the start symbol. - * In that case, there is one transition to EOF. Later, we might encode - * references to all calls to this rule to compute FOLLOW sets for - * error handling. - */ +/// The last node in the ATN for a rule, unless that rule is the start symbol. +/// In that case, there is one transition to EOF. Later, we might encode +/// references to all calls to this rule to compute FOLLOW sets for +/// error handling. public final class RuleStopState: ATNState { diff --git a/runtime/Swift/Sources/Antlr4/atn/RuleTransition.swift b/runtime/Swift/Sources/Antlr4/atn/RuleTransition.swift index 4bdd48232..128891835 100644 --- a/runtime/Swift/Sources/Antlr4/atn/RuleTransition.swift +++ b/runtime/Swift/Sources/Antlr4/atn/RuleTransition.swift @@ -1,26 +1,23 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. + -/** */ public final class RuleTransition: Transition { - /** Ptr to the rule definition object for this rule ref */ + /// Ptr to the rule definition object for this rule ref public final var ruleIndex: Int // no Rule object at runtime public final var precedence: Int - /** What node to begin computations following ref to rule */ + /// What node to begin computations following ref to rule public final var followState: ATNState - /** - * @deprecated Use - * {@link #RuleTransition(org.antlr.v4.runtime.atn.RuleStartState, int, int, org.antlr.v4.runtime.atn.ATNState)} instead. - */ + /// - Use + /// {@link #RuleTransition(org.antlr.v4.runtime.atn.RuleStartState, int, int, org.antlr.v4.runtime.atn.ATNState)} instead. //@Deprecated public convenience init(_ ruleStart: RuleStartState, _ ruleIndex: Int, diff --git a/runtime/Swift/Sources/Antlr4/atn/SemanticContext.swift b/runtime/Swift/Sources/Antlr4/atn/SemanticContext.swift index 6704a2133..c64eaef01 100644 --- a/runtime/Swift/Sources/Antlr4/atn/SemanticContext.swift +++ b/runtime/Swift/Sources/Antlr4/atn/SemanticContext.swift @@ -1,63 +1,55 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** A tree structure used to record the semantic context in which -* an ATN configuration is valid. It's either a single predicate, -* a conjunction {@code p1&&p2}, or a sum of products {@code p1||p2}. -* -*

          I have scoped the {@link org.antlr.v4.runtime.atn.SemanticContext.AND}, {@link org.antlr.v4.runtime.atn.SemanticContext.OR}, and {@link org.antlr.v4.runtime.atn.SemanticContext.Predicate} subclasses of -* {@link org.antlr.v4.runtime.atn.SemanticContext} within the scope of this outer class.

          -*/ +/// A tree structure used to record the semantic context in which +/// an ATN configuration is valid. It's either a single predicate, +/// a conjunction {@code p1&&p2}, or a sum of products {@code p1||p2}. +/// +///

          I have scoped the {@link org.antlr.v4.runtime.atn.SemanticContext.AND}, {@link org.antlr.v4.runtime.atn.SemanticContext.OR}, and {@link org.antlr.v4.runtime.atn.SemanticContext.Predicate} subclasses of +/// {@link org.antlr.v4.runtime.atn.SemanticContext} within the scope of this outer class.

          import Foundation public class SemanticContext: Hashable, CustomStringConvertible { - /** - * The default {@link org.antlr.v4.runtime.atn.SemanticContext}, which is semantically equivalent to - * a predicate of the form {@code {true}?}. - */ + /// The default {@link org.antlr.v4.runtime.atn.SemanticContext}, which is semantically equivalent to + /// a predicate of the form {@code {true}?}. public static let NONE: SemanticContext = Predicate() - /** - * For context independent predicates, we evaluate them without a local - * context (i.e., null context). That way, we can evaluate them without - * having to create proper rule-specific context during prediction (as - * opposed to the parser, which creates them naturally). In a practical - * sense, this avoids a cast exception from RuleContext to myruleContext. - * - *

          For context dependent predicates, we must pass in a local context so that - * references such as $arg evaluate properly as _localctx.arg. We only - * capture context dependent predicates in the context in which we begin - * prediction, so we passed in the outer context here in case of context - * dependent predicate evaluation.

          - */ + /// For context independent predicates, we evaluate them without a local + /// context (i.e., null context). That way, we can evaluate them without + /// having to create proper rule-specific context during prediction (as + /// opposed to the parser, which creates them naturally). In a practical + /// sense, this avoids a cast exception from RuleContext to myruleContext. + /// + ///

          For context dependent predicates, we must pass in a local context so that + /// references such as $arg evaluate properly as _localctx.arg. We only + /// capture context dependent predicates in the context in which we begin + /// prediction, so we passed in the outer context here in case of context + /// dependent predicate evaluation.

          public func eval(_ parser: Recognizer, _ parserCallStack: RuleContext) throws -> Bool { RuntimeException(#function + " must be overridden") return false } - /** - * Evaluate the precedence predicates for the context and reduce the result. - * - * @param parser The parser instance. - * @param parserCallStack - * @return The simplified semantic context after precedence predicates are - * evaluated, which will be one of the following values. - *
            - *
          • {@link #NONE}: if the predicate simplifies to {@code true} after - * precedence predicates are evaluated.
          • - *
          • {@code null}: if the predicate simplifies to {@code false} after - * precedence predicates are evaluated.
          • - *
          • {@code this}: if the semantic context is not changed as a result of - * precedence predicate evaluation.
          • - *
          • A non-{@code null} {@link org.antlr.v4.runtime.atn.SemanticContext}: the new simplified - * semantic context after precedence predicates are evaluated.
          • - *
          - */ + /// Evaluate the precedence predicates for the context and reduce the result. + /// + /// - parameter parser: The parser instance. + /// - parameter parserCallStack: + /// - returns: The simplified semantic context after precedence predicates are + /// evaluated, which will be one of the following values. + ///
            + ///
          • {@link #NONE}: if the predicate simplifies to {@code true} after + /// precedence predicates are evaluated.
          • + ///
          • {@code null}: if the predicate simplifies to {@code false} after + /// precedence predicates are evaluated.
          • + ///
          • {@code this}: if the semantic context is not changed as a result of + /// precedence predicate evaluation.
          • + ///
          • A non-{@code null} {@link org.antlr.v4.runtime.atn.SemanticContext}: the new simplified + /// semantic context after precedence predicates are evaluated.
          • + ///
          public func evalPrecedence(_ parser: Recognizer, _ parserCallStack: RuleContext) throws -> SemanticContext? { return self } @@ -154,22 +146,18 @@ public class SemanticContext: Hashable, CustomStringConvertible { } } - /** - * This is the base class for semantic context "operators", which operate on - * a collection of semantic context "operands". - * - * @since 4.3 - */ + /// This is the base class for semantic context "operators", which operate on + /// a collection of semantic context "operands". + /// + /// - 4.3 public class Operator: SemanticContext { - /** - * Gets the operands for the semantic context operator. - * - * @return a collection of {@link org.antlr.v4.runtime.atn.SemanticContext} operands for the - * operator. - * - * @since 4.3 - */ + /// Gets the operands for the semantic context operator. + /// + /// - returns: a collection of {@link org.antlr.v4.runtime.atn.SemanticContext} operands for the + /// operator. + /// + /// - 4.3 public func getOperands() -> Array { RuntimeException(" must overriden ") @@ -177,10 +165,8 @@ public class SemanticContext: Hashable, CustomStringConvertible { } } - /** - * A semantic context which is true whenever none of the contained contexts - * is false. - */ + /// A semantic context which is true whenever none of the contained contexts + /// is false. public class AND: Operator { public let opnds: [SemanticContext] @@ -228,13 +214,11 @@ public class SemanticContext: Hashable, CustomStringConvertible { return MurmurHash.hashCode(opnds, seed) } - /** - * {@inheritDoc} - * - *

          - * The evaluation of predicates by this context is short-circuiting, but - * unordered.

          - */ + /// {@inheritDoc} + /// + ///

          + /// The evaluation of predicates by this context is short-circuiting, but + /// unordered.

          override public func eval(_ parser: Recognizer, _ parserCallStack: RuleContext) throws -> Bool { for opnd: SemanticContext in opnds { @@ -295,10 +279,8 @@ public class SemanticContext: Hashable, CustomStringConvertible { } } - /** - * A semantic context which is true whenever at least one of the contained - * contexts is true. - */ + /// A semantic context which is true whenever at least one of the contained + /// contexts is true. public class OR: Operator { public final var opnds: [SemanticContext] @@ -343,13 +325,11 @@ public class SemanticContext: Hashable, CustomStringConvertible { return MurmurHash.hashCode(opnds, NSStringFromClass(OR.self).hashValue) } - /** - * {@inheritDoc} - * - *

          - * The evaluation of predicates by this context is short-circuiting, but - * unordered.

          - */ + /// {@inheritDoc} + /// + ///

          + /// The evaluation of predicates by this context is short-circuiting, but + /// unordered.

          override public func eval(_ parser: Recognizer, _ parserCallStack: RuleContext) throws -> Bool { for opnd: SemanticContext in opnds { @@ -425,10 +405,8 @@ public class SemanticContext: Hashable, CustomStringConvertible { return result } - /** - * - * @see org.antlr.v4.runtime.atn.ParserATNSimulator#getPredsForAmbigAlts - */ + /// + /// - seealso: org.antlr.v4.runtime.atn.ParserATNSimulator#getPredsForAmbigAlts public static func or(_ a: SemanticContext?, _ b: SemanticContext?) -> SemanticContext { if a == nil { return b! diff --git a/runtime/Swift/Sources/Antlr4/atn/SetTransition.swift b/runtime/Swift/Sources/Antlr4/atn/SetTransition.swift index cd6972456..5bf467be6 100644 --- a/runtime/Swift/Sources/Antlr4/atn/SetTransition.swift +++ b/runtime/Swift/Sources/Antlr4/atn/SetTransition.swift @@ -1,11 +1,10 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** A transition containing a set of values. */ +/// A transition containing a set of values. public class SetTransition: Transition, CustomStringConvertible { public final var set: IntervalSet diff --git a/runtime/Swift/Sources/Antlr4/atn/SingletonPredictionContext.swift b/runtime/Swift/Sources/Antlr4/atn/SingletonPredictionContext.swift index 060c36b9c..bd4247057 100644 --- a/runtime/Swift/Sources/Antlr4/atn/SingletonPredictionContext.swift +++ b/runtime/Swift/Sources/Antlr4/atn/SingletonPredictionContext.swift @@ -1,7 +1,6 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. diff --git a/runtime/Swift/Sources/Antlr4/atn/StarBlockStartState.swift b/runtime/Swift/Sources/Antlr4/atn/StarBlockStartState.swift index f81c03e9a..68ad8ac77 100644 --- a/runtime/Swift/Sources/Antlr4/atn/StarBlockStartState.swift +++ b/runtime/Swift/Sources/Antlr4/atn/StarBlockStartState.swift @@ -1,11 +1,10 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** The block that begins a closure loop. */ +/// The block that begins a closure loop. public final class StarBlockStartState: BlockStartState { diff --git a/runtime/Swift/Sources/Antlr4/atn/StarLoopEntryState.swift b/runtime/Swift/Sources/Antlr4/atn/StarLoopEntryState.swift index 94cf0157c..0af7521d9 100644 --- a/runtime/Swift/Sources/Antlr4/atn/StarLoopEntryState.swift +++ b/runtime/Swift/Sources/Antlr4/atn/StarLoopEntryState.swift @@ -1,22 +1,19 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. public final class StarLoopEntryState: DecisionState { public var loopBackState: StarLoopbackState? - /** - * Indicates whether this state can benefit from a precedence DFA during SLL - * decision making. - * - *

          This is a computed property that is calculated during ATN deserialization - * and stored for use in {@link org.antlr.v4.runtime.atn.ParserATNSimulator} and - * {@link org.antlr.v4.runtime.ParserInterpreter}.

          - * - * @see org.antlr.v4.runtime.dfa.DFA#isPrecedenceDfa() - */ + /// Indicates whether this state can benefit from a precedence DFA during SLL + /// decision making. + /// + ///

          This is a computed property that is calculated during ATN deserialization + /// and stored for use in {@link org.antlr.v4.runtime.atn.ParserATNSimulator} and + /// {@link org.antlr.v4.runtime.ParserInterpreter}.

          + /// + /// - seealso: org.antlr.v4.runtime.dfa.DFA#isPrecedenceDfa() public var precedenceRuleDecision: Bool = false override diff --git a/runtime/Swift/Sources/Antlr4/atn/StarLoopbackState.swift b/runtime/Swift/Sources/Antlr4/atn/StarLoopbackState.swift index 5360d5736..d977ac4d2 100644 --- a/runtime/Swift/Sources/Antlr4/atn/StarLoopbackState.swift +++ b/runtime/Swift/Sources/Antlr4/atn/StarLoopbackState.swift @@ -1,7 +1,6 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. public final class StarLoopbackState: ATNState { diff --git a/runtime/Swift/Sources/Antlr4/atn/TokensStartState.swift b/runtime/Swift/Sources/Antlr4/atn/TokensStartState.swift index 26c2412cb..edbc30318 100644 --- a/runtime/Swift/Sources/Antlr4/atn/TokensStartState.swift +++ b/runtime/Swift/Sources/Antlr4/atn/TokensStartState.swift @@ -1,10 +1,9 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** The Tokens rule start state linking to each lexer rule start state */ +/// The Tokens rule start state linking to each lexer rule start state public final class TokensStartState: DecisionState { diff --git a/runtime/Swift/Sources/Antlr4/atn/Transition.swift b/runtime/Swift/Sources/Antlr4/atn/Transition.swift index e2e394d22..971d95807 100644 --- a/runtime/Swift/Sources/Antlr4/atn/Transition.swift +++ b/runtime/Swift/Sources/Antlr4/atn/Transition.swift @@ -1,21 +1,19 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** An ATN transition between any two ATN states. Subclasses define -* atom, set, epsilon, action, predicate, rule transitions. -* -*

          This is a one way link. It emanates from a state (usually via a list of -* transitions) and has a target state.

          -* -*

          Since we never have to change the ATN transitions once we construct it, -* we can fix these transitions as specific classes. The DFA transitions -* on the other hand need to update the labels as it adds transitions to -* the states. We'll use the term Edge for the DFA to distinguish them from -* ATN transitions.

          -*/ +/// An ATN transition between any two ATN states. Subclasses define +/// atom, set, epsilon, action, predicate, rule transitions. +/// +///

          This is a one way link. It emanates from a state (usually via a list of +/// transitions) and has a target state.

          +/// +///

          Since we never have to change the ATN transitions once we construct it, +/// we can fix these transitions as specific classes. The DFA transitions +/// on the other hand need to update the labels as it adds transitions to +/// the states. We'll use the term Edge for the DFA to distinguish them from +/// ATN transitions.

          import Foundation @@ -67,7 +65,7 @@ public class Transition { ] - /** The target of this transition. */ + /// The target of this transition. public final var target: ATNState @@ -82,15 +80,13 @@ public class Transition { fatalError() } - /** - * Determines if the transition is an "epsilon" transition. - * - *

          The default implementation returns {@code false}.

          - * - * @return {@code true} if traversing this transition in the ATN does not - * consume an input symbol; otherwise, {@code false} if traversing this - * transition consumes (matches) an input symbol. - */ + /// Determines if the transition is an "epsilon" transition. + /// + ///

          The default implementation returns {@code false}.

          + /// + /// - returns: {@code true} if traversing this transition in the ATN does not + /// consume an input symbol; otherwise, {@code false} if traversing this + /// transition consumes (matches) an input symbol. public func isEpsilon() -> Bool { return false } diff --git a/runtime/Swift/Sources/Antlr4/atn/WildcardTransition.swift b/runtime/Swift/Sources/Antlr4/atn/WildcardTransition.swift index 4c02d77e3..a2da3c71a 100644 --- a/runtime/Swift/Sources/Antlr4/atn/WildcardTransition.swift +++ b/runtime/Swift/Sources/Antlr4/atn/WildcardTransition.swift @@ -1,7 +1,6 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. final public class WildcardTransition: Transition, CustomStringConvertible { diff --git a/runtime/Swift/Sources/Antlr4/dfa/DFA.swift b/runtime/Swift/Sources/Antlr4/dfa/DFA.swift index 2330c4fe2..7ceeec33f 100644 --- a/runtime/Swift/Sources/Antlr4/dfa/DFA.swift +++ b/runtime/Swift/Sources/Antlr4/dfa/DFA.swift @@ -1,13 +1,11 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. public class DFA: CustomStringConvertible { - /** A set of all DFA states. Use {@link java.util.Map} so we can get old state back - * ({@link java.util.Set} only allows you to see if it's there). - */ + /// A set of all DFA states. Use {@link java.util.Map} so we can get old state back + /// ({@link java.util.Set} only allows you to see if it's there). public final var states: HashMap = HashMap() @@ -15,14 +13,12 @@ public class DFA: CustomStringConvertible { public final var decision: Int - /** From which ATN state did we create this DFA? */ + /// From which ATN state did we create this DFA? public let atnStartState: DecisionState - /** - * {@code true} if this DFA is for a precedence decision; otherwise, - * {@code false}. This is the backing field for {@link #isPrecedenceDfa}. - */ + /// {@code true} if this DFA is for a precedence decision; otherwise, + /// {@code false}. This is the backing field for {@link #isPrecedenceDfa}. private final var precedenceDfa: Bool public convenience init(_ atnStartState: DecisionState) { @@ -48,31 +44,27 @@ public class DFA: CustomStringConvertible { self.precedenceDfa = precedenceDfa } - /** - * Gets whether this DFA is a precedence DFA. Precedence DFAs use a special - * start state {@link #s0} which is not stored in {@link #states}. The - * {@link org.antlr.v4.runtime.dfa.DFAState#edges} array for this start state contains outgoing edges - * supplying individual start states corresponding to specific precedence - * values. - * - * @return {@code true} if this is a precedence DFA; otherwise, - * {@code false}. - * @see org.antlr.v4.runtime.Parser#getPrecedence() - */ + /// Gets whether this DFA is a precedence DFA. Precedence DFAs use a special + /// start state {@link #s0} which is not stored in {@link #states}. The + /// {@link org.antlr.v4.runtime.dfa.DFAState#edges} array for this start state contains outgoing edges + /// supplying individual start states corresponding to specific precedence + /// values. + /// + /// - returns: {@code true} if this is a precedence DFA; otherwise, + /// {@code false}. + /// - seealso: org.antlr.v4.runtime.Parser#getPrecedence() public final func isPrecedenceDfa() -> Bool { return precedenceDfa } - /** - * Get the start state for a specific precedence value. - * - * @param precedence The current precedence. - * @return The start state corresponding to the specified precedence, or - * {@code null} if no start state exists for the specified precedence. - * - * @throws IllegalStateException if this is not a precedence DFA. - * @see #isPrecedenceDfa() - */ + /// Get the start state for a specific precedence value. + /// + /// - parameter precedence: The current precedence. + /// - returns: The start state corresponding to the specified precedence, or + /// {@code null} if no start state exists for the specified precedence. + /// + /// - IllegalStateException if this is not a precedence DFA. + /// - seealso: #isPrecedenceDfa() ////@SuppressWarnings("null") public final func getPrecedenceStartState(_ precedence: Int) throws -> DFAState? { if !isPrecedenceDfa() { @@ -90,16 +82,14 @@ public class DFA: CustomStringConvertible { return s0!.edges![precedence] } - /** - * Set the start state for a specific precedence value. - * - * @param precedence The current precedence. - * @param startState The start state corresponding to the specified - * precedence. - * - * @throws IllegalStateException if this is not a precedence DFA. - * @see #isPrecedenceDfa() - */ + /// Set the start state for a specific precedence value. + /// + /// - parameter precedence: The current precedence. + /// - parameter startState: The start state corresponding to the specified + /// precedence. + /// + /// - IllegalStateException if this is not a precedence DFA. + /// - seealso: #isPrecedenceDfa() ////@SuppressWarnings({"SynchronizeOnNonFinalField", "null"}) public final func setPrecedenceStartState(_ precedence: Int, _ startState: DFAState) throws { if !isPrecedenceDfa() { @@ -125,17 +115,15 @@ public class DFA: CustomStringConvertible { } } - /** - * Sets whether this is a precedence DFA. - * - * @param precedenceDfa {@code true} if this is a precedence DFA; otherwise, - * {@code false} - * - * @throws UnsupportedOperationException if {@code precedenceDfa} does not - * match the value of {@link #isPrecedenceDfa} for the current DFA. - * - * @deprecated This method no longer performs any action. - */ + /// Sets whether this is a precedence DFA. + /// + /// - parameter precedenceDfa: {@code true} if this is a precedence DFA; otherwise, + /// {@code false} + /// + /// - UnsupportedOperationException if {@code precedenceDfa} does not + /// match the value of {@link #isPrecedenceDfa} for the current DFA. + /// + /// - This method no longer performs any action. ////@Deprecated public final func setPrecedenceDfa(_ precedenceDfa: Bool) throws { if precedenceDfa != isPrecedenceDfa() { @@ -144,9 +132,7 @@ public class DFA: CustomStringConvertible { } } - /** - * Return a list of all states in this DFA, ordered by state number. - */ + /// Return a list of all states in this DFA, ordered by state number. public func getStates() -> Array { var result: Array = Array(states.keys) @@ -167,9 +153,7 @@ public class DFA: CustomStringConvertible { return description } - /** - * @deprecated Use {@link #toString(org.antlr.v4.runtime.Vocabulary)} instead. - */ + /// - Use {@link #toString(org.antlr.v4.runtime.Vocabulary)} instead. ////@Deprecated public func toString(_ tokenNames: [String?]?) -> String { if s0 == nil { diff --git a/runtime/Swift/Sources/Antlr4/dfa/DFASerializer.swift b/runtime/Swift/Sources/Antlr4/dfa/DFASerializer.swift index 74e01379b..2d56b13fe 100644 --- a/runtime/Swift/Sources/Antlr4/dfa/DFASerializer.swift +++ b/runtime/Swift/Sources/Antlr4/dfa/DFASerializer.swift @@ -1,10 +1,9 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** A DFA walker that knows how to dump them to serialized strings. */ +/// A DFA walker that knows how to dump them to serialized strings. public class DFASerializer: CustomStringConvertible { @@ -12,9 +11,7 @@ public class DFASerializer: CustomStringConvertible { private let vocabulary: Vocabulary - /** - * @deprecated Use {@link #DFASerializer(org.antlr.v4.runtime.dfa.DFA, org.antlr.v4.runtime.Vocabulary)} instead. - */ + /// - Use {@link #DFASerializer(org.antlr.v4.runtime.dfa.DFA, org.antlr.v4.runtime.Vocabulary)} instead. //@Deprecated public convenience init(_ dfa: DFA, _ tokenNames: [String?]?) { self.init(dfa, Vocabulary.fromTokenNames(tokenNames)) diff --git a/runtime/Swift/Sources/Antlr4/dfa/DFAState.swift b/runtime/Swift/Sources/Antlr4/dfa/DFAState.swift index 5433fc4bd..cd76bebfe 100644 --- a/runtime/Swift/Sources/Antlr4/dfa/DFAState.swift +++ b/runtime/Swift/Sources/Antlr4/dfa/DFAState.swift @@ -1,33 +1,31 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** A DFA state represents a set of possible ATN configurations. -* As Aho, Sethi, Ullman p. 117 says "The DFA uses its state -* to keep track of all possible states the ATN can be in after -* reading each input symbol. That is to say, after reading -* input a1a2..an, the DFA is in a state that represents the -* subset T of the states of the ATN that are reachable from the -* ATN's start state along some path labeled a1a2..an." -* In conventional NFA→DFA conversion, therefore, the subset T -* would be a bitset representing the set of states the -* ATN could be in. We need to track the alt predicted by each -* state as well, however. More importantly, we need to maintain -* a stack of states, tracking the closure operations as they -* jump from rule to rule, emulating rule invocations (method calls). -* I have to add a stack to simulate the proper lookahead sequences for -* the underlying LL grammar from which the ATN was derived. -* -*

          I use a set of ATNConfig objects not simple states. An ATNConfig -* is both a state (ala normal conversion) and a RuleContext describing -* the chain of rules (if any) followed to arrive at that state.

          -* -*

          A DFA state may have multiple references to a particular state, -* but with different ATN contexts (with same or different alts) -* meaning that state was reached via a different set of rule invocations.

          -*/ +/// A DFA state represents a set of possible ATN configurations. +/// As Aho, Sethi, Ullman p. 117 says "The DFA uses its state +/// to keep track of all possible states the ATN can be in after +/// reading each input symbol. That is to say, after reading +/// input a1a2..an, the DFA is in a state that represents the +/// subset T of the states of the ATN that are reachable from the +/// ATN's start state along some path labeled a1a2..an." +/// In conventional NFA→DFA conversion, therefore, the subset T +/// would be a bitset representing the set of states the +/// ATN could be in. We need to track the alt predicted by each +/// state as well, however. More importantly, we need to maintain +/// a stack of states, tracking the closure operations as they +/// jump from rule to rule, emulating rule invocations (method calls). +/// I have to add a stack to simulate the proper lookahead sequences for +/// the underlying LL grammar from which the ATN was derived. +/// +///

          I use a set of ATNConfig objects not simple states. An ATNConfig +/// is both a state (ala normal conversion) and a RuleContext describing +/// the chain of rules (if any) followed to arrive at that state.

          +/// +///

          A DFA state may have multiple references to a particular state, +/// but with different ATN contexts (with same or different alts) +/// meaning that state was reached via a different set of rule invocations.

          public class DFAState: Hashable, CustomStringConvertible { public var stateNumber: Int = -1 @@ -35,46 +33,41 @@ public class DFAState: Hashable, CustomStringConvertible { public var configs: ATNConfigSet = ATNConfigSet() - /** {@code edges[symbol]} points to target of symbol. Shift up by 1 so (-1) - * {@link org.antlr.v4.runtime.Token#EOF} maps to {@code edges[0]}. - */ + /// {@code edges[symbol]} points to target of symbol. Shift up by 1 so (-1) + /// {@link org.antlr.v4.runtime.Token#EOF} maps to {@code edges[0]}. public var edges: [DFAState?]! public var isAcceptState: Bool = false - /** if accept state, what ttype do we match or alt do we predict? - * This is set to {@link org.antlr.v4.runtime.atn.ATN#INVALID_ALT_NUMBER} when {@link #predicates}{@code !=null} or - * {@link #requiresFullContext}. - */ + /// if accept state, what ttype do we match or alt do we predict? + /// This is set to {@link org.antlr.v4.runtime.atn.ATN#INVALID_ALT_NUMBER} when {@link #predicates}{@code !=null} or + /// {@link #requiresFullContext}. public var prediction: Int! = 0 public var lexerActionExecutor: LexerActionExecutor! - /** - * Indicates that this state was created during SLL prediction that - * discovered a conflict between the configurations in the state. Future - * {@link org.antlr.v4.runtime.atn.ParserATNSimulator#execATN} invocations immediately jumped doing - * full context prediction if this field is true. - */ + /// Indicates that this state was created during SLL prediction that + /// discovered a conflict between the configurations in the state. Future + /// {@link org.antlr.v4.runtime.atn.ParserATNSimulator#execATN} invocations immediately jumped doing + /// full context prediction if this field is true. public var requiresFullContext: Bool = false - /** During SLL parsing, this is a list of predicates associated with the - * ATN configurations of the DFA state. When we have predicates, - * {@link #requiresFullContext} is {@code false} since full context prediction evaluates predicates - * on-the-fly. If this is not null, then {@link #prediction} is - * {@link org.antlr.v4.runtime.atn.ATN#INVALID_ALT_NUMBER}. - * - *

          We only use these for non-{@link #requiresFullContext} but conflicting states. That - * means we know from the context (it's $ or we don't dip into outer - * context) that it's an ambiguity not a conflict.

          - * - *

          This list is computed by {@link org.antlr.v4.runtime.atn.ParserATNSimulator#predicateDFAState}.

          - */ + /// During SLL parsing, this is a list of predicates associated with the + /// ATN configurations of the DFA state. When we have predicates, + /// {@link #requiresFullContext} is {@code false} since full context prediction evaluates predicates + /// on-the-fly. If this is not null, then {@link #prediction} is + /// {@link org.antlr.v4.runtime.atn.ATN#INVALID_ALT_NUMBER}. + /// + ///

          We only use these for non-{@link #requiresFullContext} but conflicting states. That + /// means we know from the context (it's $ or we don't dip into outer + /// context) that it's an ambiguity not a conflict.

          + /// + ///

          This list is computed by {@link org.antlr.v4.runtime.atn.ParserATNSimulator#predicateDFAState}.

          public var predicates: [PredPrediction]? - /** Map a predicate to a predicted alternative. */ + /// Map a predicate to a predicted alternative. public class PredPrediction: CustomStringConvertible { @@ -105,9 +98,8 @@ public class DFAState: Hashable, CustomStringConvertible { self.configs = configs } - /** Get the set of all alts mentioned by all ATN configurations in this - * DFA state. - */ + /// Get the set of all alts mentioned by all ATN configurations in this + /// DFA state. public func getAltSet() -> Set? { let alts = configs.getAltSet() @@ -123,19 +115,17 @@ public class DFAState: Hashable, CustomStringConvertible { return hash } - /** - * Two {@link org.antlr.v4.runtime.dfa.DFAState} instances are equal if their ATN configuration sets - * are the same. This method is used to see if a state already exists. - * - *

          Because the number of alternatives and number of ATN configurations are - * finite, there is a finite number of DFA states that can be processed. - * This is necessary to show that the algorithm terminates.

          - * - *

          Cannot test the DFA state numbers here because in - * {@link org.antlr.v4.runtime.atn.ParserATNSimulator#addDFAState} we need to know if any other state - * exists that has this exact set of ATN configurations. The - * {@link #stateNumber} is irrelevant.

          - */ + /// Two {@link org.antlr.v4.runtime.dfa.DFAState} instances are equal if their ATN configuration sets + /// are the same. This method is used to see if a state already exists. + /// + ///

          Because the number of alternatives and number of ATN configurations are + /// finite, there is a finite number of DFA states that can be processed. + /// This is necessary to show that the algorithm terminates.

          + /// + ///

          Cannot test the DFA state numbers here because in + /// {@link org.antlr.v4.runtime.atn.ParserATNSimulator#addDFAState} we need to know if any other state + /// exists that has this exact set of ATN configurations. The + /// {@link #stateNumber} is irrelevant.

          public var description: String { let buf: StringBuilder = StringBuilder() diff --git a/runtime/Swift/Sources/Antlr4/dfa/LexerDFASerializer.swift b/runtime/Swift/Sources/Antlr4/dfa/LexerDFASerializer.swift index 09aca3f0c..2038d6b56 100644 --- a/runtime/Swift/Sources/Antlr4/dfa/LexerDFASerializer.swift +++ b/runtime/Swift/Sources/Antlr4/dfa/LexerDFASerializer.swift @@ -1,7 +1,6 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. public class LexerDFASerializer: DFASerializer { diff --git a/runtime/Swift/Sources/Antlr4/misc/ArrayList.swift b/runtime/Swift/Sources/Antlr4/misc/ArrayList.swift index 4b08c558d..010fa4e06 100644 --- a/runtime/Swift/Sources/Antlr4/misc/ArrayList.swift +++ b/runtime/Swift/Sources/Antlr4/misc/ArrayList.swift @@ -1,7 +1,6 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. // // ArrayList.swift diff --git a/runtime/Swift/Sources/Antlr4/misc/ArrayWrapper.swift b/runtime/Swift/Sources/Antlr4/misc/ArrayWrapper.swift index 69f287e60..28df143e5 100644 --- a/runtime/Swift/Sources/Antlr4/misc/ArrayWrapper.swift +++ b/runtime/Swift/Sources/Antlr4/misc/ArrayWrapper.swift @@ -1,7 +1,6 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. // // ArrayWrapper.swift diff --git a/runtime/Swift/Sources/Antlr4/misc/BitSet.swift b/runtime/Swift/Sources/Antlr4/misc/BitSet.swift index 097793446..b3ca6b3ba 100644 --- a/runtime/Swift/Sources/Antlr4/misc/BitSet.swift +++ b/runtime/Swift/Sources/Antlr4/misc/BitSet.swift @@ -1,7 +1,6 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. // // BitSet.swift @@ -13,93 +12,77 @@ import Foundation -/** -* This class implements a vector of bits that grows as needed. Each -* component of the bit set has a {@code boolean} value. The -* bits of a {@code BitSet} are indexed by nonnegative integers. -* Individual indexed bits can be examined, set, or cleared. One -* {@code BitSet} may be used to modify the contents of another -* {@code BitSet} through logical AND, logical inclusive OR, and -* logical exclusive OR operations. -* -*

          By default, all bits in the set initially have the value -* {@code false}. -* -*

          Every bit set has a current size, which is the number of bits -* of space currently in use by the bit set. Note that the size is -* related to the implementation of a bit set, so it may change with -* implementation. The length of a bit set relates to logical length -* of a bit set and is defined independently of implementation. -* -*

          Unless otherwise noted, passing a null parameter to any of the -* methods in a {@code BitSet} will result in a -* {@code NullPointerException}. -* -*

          A {@code BitSet} is not safe for multithreaded use without -* external synchronization. -* -* @author Arthur van Hoff -* @author Michael McCloskey -* @author Martin Buchholz -* @since JDK1.0 -*/ +/// This class implements a vector of bits that grows as needed. Each +/// component of the bit set has a {@code boolean} value. The +/// bits of a {@code BitSet} are indexed by nonnegative integers. +/// Individual indexed bits can be examined, set, or cleared. One +/// {@code BitSet} may be used to modify the contents of another +/// {@code BitSet} through logical AND, logical inclusive OR, and +/// logical exclusive OR operations. +/// +///

          By default, all bits in the set initially have the value +/// {@code false}. +/// +///

          Every bit set has a current size, which is the number of bits +/// of space currently in use by the bit set. Note that the size is +/// related to the implementation of a bit set, so it may change with +/// implementation. The length of a bit set relates to logical length +/// of a bit set and is defined independently of implementation. +/// +///

          Unless otherwise noted, passing a null parameter to any of the +/// methods in a {@code BitSet} will result in a +/// {@code NullPointerException}. +/// +///

          A {@code BitSet} is not safe for multithreaded use without +/// external synchronization. +/// +/// - Arthur van Hoff +/// - Michael McCloskey +/// - Martin Buchholz +/// - JDK1.0 public class BitSet: Hashable, CustomStringConvertible { - /* - * BitSets are packed into arrays of "words." Currently a word is - * a long, which consists of 64 bits, requiring 6 address bits. - * The choice of word size is determined purely by performance concerns. - */ + /// BitSets are packed into arrays of "words." Currently a word is + /// a long, which consists of 64 bits, requiring 6 address bits. + /// The choice of word size is determined purely by performance concerns. private static let ADDRESS_BITS_PER_WORD: Int = 6 private static let BITS_PER_WORD: Int = 1 << ADDRESS_BITS_PER_WORD private static let BIT_INDEX_MASK: Int = BITS_PER_WORD - 1 - /* Used to shift left or right for a partial word mask */ + /// Used to shift left or right for a partial word mask private static let WORD_MASK: Int64 = Int64.max //0xfffffffffffffff//-1 // 0xffffffffffffffffL; - /** - * @serialField bits long[] - * - * The bits in this BitSet. The ith bit is stored in bits[i/64] at - * bit position i % 64 (where bit position 0 refers to the least - * significant bit and 63 refers to the most significant bit). - */ + /// - bits long[] + /// + /// The bits in this BitSet. The ith bit is stored in bits[i/64] at + /// bit position i % 64 (where bit position 0 refers to the least + /// significant bit and 63 refers to the most significant bit). - /** - * The internal field corresponding to the serialField "bits". - */ + /// The internal field corresponding to the serialField "bits". fileprivate var words: [Int64] - /** - * The number of words in the logical size of this BitSet. - */ + /// The number of words in the logical size of this BitSet. fileprivate var wordsInUse: Int = 0 //transient - /** - * Whether the size of "words" is user-specified. If so, we assume - * the user knows what he's doing and try harder to preserve it. - */ + /// Whether the size of "words" is user-specified. If so, we assume + /// the user knows what he's doing and try harder to preserve it. private var sizeIsSticky: Bool = false //transient - /* use serialVersionUID from JDK 1.0.2 for interoperability */ + /// use serialVersionUID from JDK 1.0.2 for interoperability private let serialVersionUID: Int64 = 7997698588986878753 //L; - /** - * Given a bit index, return word index containing it. - */ + /// Given a bit index, return word index containing it. private static func wordIndex(_ bitIndex: Int) -> Int { return bitIndex >> ADDRESS_BITS_PER_WORD } - /** - * Every public method must preserve these invariants. - */ + /// Every public method must preserve these invariants. fileprivate func checkInvariants() { assert((wordsInUse == 0 || words[wordsInUse - 1] != 0), "Expected: (wordsInUse==0||words[wordsInUse-1]!=0)") assert((wordsInUse >= 0 && wordsInUse <= words.count), "Expected: (wordsInUse>=0&&wordsInUse<=words.length)") @@ -107,11 +90,9 @@ public class BitSet: Hashable, CustomStringConvertible { assert((wordsInUse == words.count || words[wordsInUse] == 0), "Expected: (wordsInUse==words.count||words[wordsInUse]==0)") } - /** - * Sets the field wordsInUse to the logical size in words of the bit set. - * WARNING:This method assumes that the number of words actually in use is - * less than or equal to the current value of wordsInUse! - */ + /// Sets the field wordsInUse to the logical size in words of the bit set. + /// WARNING:This method assumes that the number of words actually in use is + /// less than or equal to the current value of wordsInUse! private func recalculateWordsInUse() { // Traverse the bitset until a used word is found var i: Int = wordsInUse - 1 @@ -125,9 +106,7 @@ public class BitSet: Hashable, CustomStringConvertible { wordsInUse = i + 1 // The new logical size } - /** - * Creates a new bit set. All bits are initially {@code false}. - */ + /// Creates a new bit set. All bits are initially {@code false}. public init() { sizeIsSticky = false words = [Int64](repeating: Int64(0), count: BitSet.wordIndex(BitSet.BITS_PER_WORD - 1) + 1) @@ -135,15 +114,13 @@ public class BitSet: Hashable, CustomStringConvertible { } - /** - * Creates a bit set whose initial size is large enough to explicitly - * represent bits with indices in the range {@code 0} through - * {@code nbits-1}. All bits are initially {@code false}. - * - * @param nbits the initial size of the bit set - * @throws NegativeArraySizeException if the specified initial size - * is negative - */ + /// Creates a bit set whose initial size is large enough to explicitly + /// represent bits with indices in the range {@code 0} through + /// {@code nbits-1}. All bits are initially {@code false}. + /// + /// - parameter nbits: the initial size of the bit set + /// - NegativeArraySizeException if the specified initial size + /// is negative public init(_ nbits: Int) throws { // nbits can't be negative; size 0 is OK @@ -162,10 +139,8 @@ public class BitSet: Hashable, CustomStringConvertible { // words = [BitSet.wordIndex(nbits-1) + 1]; } - /** - * Creates a bit set using words as the internal representation. - * The last word (if there is one) must be non-zero. - */ + /// Creates a bit set using words as the internal representation. + /// The last word (if there is one) must be non-zero. private init(_ words: [Int64]) { self.words = words self.wordsInUse = words.count @@ -173,19 +148,17 @@ public class BitSet: Hashable, CustomStringConvertible { } - /** - * Returns a new long array containing all the bits in this bit set. - * - *

          More precisely, if - *
          {@code long[] longs = s.toLongArray();} - *
          then {@code longs.length == (s.length()+63)/64} and - *
          {@code s.get(n) == ((longs[n/64] & (1L<<(n%64))) != 0)} - *
          for all {@code n < 64 * longs.length}. - * - * @return a long array containing a little-endian representation - * of all the bits in this bit set - * @since 1.7 - */ + /// Returns a new long array containing all the bits in this bit set. + /// + ///

          More precisely, if + ///
          {@code long[] longs = s.toLongArray();} + ///
          then {@code longs.length == (s.length()+63)/64} and + ///
          {@code s.get(n) == ((longs[n/64] & (1L<<(n%64))) != 0)} + ///
          for all {@code n < 64 * longs.length}. + /// + /// - returns: a long array containing a little-endian representation + /// of all the bits in this bit set + /// - 1.7 public func toLongArray() -> [Int64] { return copyOf(words, wordsInUse) } @@ -196,10 +169,8 @@ public class BitSet: Hashable, CustomStringConvertible { newWords[0 ..< length] = words[0 ..< length] return newWords } - /** - * Ensures that the BitSet can hold enough words. - * @param wordsRequired the minimum acceptable number of words. - */ + /// Ensures that the BitSet can hold enough words. + /// - parameter wordsRequired: the minimum acceptable number of words. private func ensureCapacity(_ wordsRequired: Int) { if words.count < wordsRequired { // Allocate larger of doubled size or required size @@ -209,13 +180,11 @@ public class BitSet: Hashable, CustomStringConvertible { } } - /** - * Ensures that the BitSet can accommodate a given wordIndex, - * temporarily violating the invariants. The caller must - * restore the invariants before returning to the user, - * possibly using recalculateWordsInUse(). - * @param wordIndex the index to be accommodated. - */ + /// Ensures that the BitSet can accommodate a given wordIndex, + /// temporarily violating the invariants. The caller must + /// restore the invariants before returning to the user, + /// possibly using recalculateWordsInUse(). + /// - parameter wordIndex: the index to be accommodated. private func expandTo(_ wordIndex: Int) { let wordsRequired: Int = wordIndex + 1 if wordsInUse < wordsRequired { @@ -224,9 +193,7 @@ public class BitSet: Hashable, CustomStringConvertible { } } - /** - * Checks that fromIndex ... toIndex is a valid range of bit indices. - */ + /// Checks that fromIndex ... toIndex is a valid range of bit indices. private static func checkRange(_ fromIndex: Int, _ toIndex: Int) throws { if fromIndex < 0 { throw ANTLRError.indexOutOfBounds(msg: "fromIndex < 0: \(fromIndex)") @@ -243,14 +210,12 @@ public class BitSet: Hashable, CustomStringConvertible { } } - /** - * Sets the bit at the specified index to the complement of its - * current value. - * - * @param bitIndex the index of the bit to flip - * @throws IndexOutOfBoundsException if the specified index is negative - * @since 1.4 - */ + /// Sets the bit at the specified index to the complement of its + /// current value. + /// + /// - parameter bitIndex: the index of the bit to flip + /// - IndexOutOfBoundsException if the specified index is negative + /// - 1.4 public func flip(_ bitIndex: Int) throws { if bitIndex < 0 { throw ANTLRError.indexOutOfBounds(msg: "bitIndex < 0: \(bitIndex)") @@ -266,18 +231,16 @@ public class BitSet: Hashable, CustomStringConvertible { checkInvariants() } - /** - * Sets each bit from the specified {@code fromIndex} (inclusive) to the - * specified {@code toIndex} (exclusive) to the complement of its current - * value. - * - * @param fromIndex index of the first bit to flip - * @param toIndex index after the last bit to flip - * @throws IndexOutOfBoundsException if {@code fromIndex} is negative, - * or {@code toIndex} is negative, or {@code fromIndex} is - * larger than {@code toIndex} - * @since 1.4 - */ + /// Sets each bit from the specified {@code fromIndex} (inclusive) to the + /// specified {@code toIndex} (exclusive) to the complement of its current + /// value. + /// + /// - parameter fromIndex: index of the first bit to flip + /// - parameter toIndex: index after the last bit to flip + /// - IndexOutOfBoundsException if {@code fromIndex} is negative, + /// or {@code toIndex} is negative, or {@code fromIndex} is + /// larger than {@code toIndex} + /// - 1.4 public func flip(_ fromIndex: Int, _ toIndex: Int) throws { try BitSet.checkRange(fromIndex, toIndex) @@ -314,13 +277,11 @@ public class BitSet: Hashable, CustomStringConvertible { checkInvariants() } - /** - * Sets the bit at the specified index to {@code true}. - * - * @param bitIndex a bit index - * @throws IndexOutOfBoundsException if the specified index is negative - * @since JDK1.0 - */ + /// Sets the bit at the specified index to {@code true}. + /// + /// - parameter bitIndex: a bit index + /// - IndexOutOfBoundsException if the specified index is negative + /// - JDK1.0 public func set(_ bitIndex: Int) throws { if bitIndex < 0 { throw ANTLRError.indexOutOfBounds(msg: "bitIndex < 0: \(bitIndex)") @@ -335,14 +296,12 @@ public class BitSet: Hashable, CustomStringConvertible { checkInvariants() } - /** - * Sets the bit at the specified index to the specified value. - * - * @param bitIndex a bit index - * @param value a boolean value to set - * @throws IndexOutOfBoundsException if the specified index is negative - * @since 1.4 - */ + /// Sets the bit at the specified index to the specified value. + /// + /// - parameter bitIndex: a bit index + /// - parameter value: a boolean value to set + /// - IndexOutOfBoundsException if the specified index is negative + /// - 1.4 public func set(_ bitIndex: Int, _ value: Bool) throws { if value { try set(bitIndex) @@ -351,17 +310,15 @@ public class BitSet: Hashable, CustomStringConvertible { } } - /** - * Sets the bits from the specified {@code fromIndex} (inclusive) to the - * specified {@code toIndex} (exclusive) to {@code true}. - * - * @param fromIndex index of the first bit to be set - * @param toIndex index after the last bit to be set - * @throws IndexOutOfBoundsException if {@code fromIndex} is negative, - * or {@code toIndex} is negative, or {@code fromIndex} is - * larger than {@code toIndex} - * @since 1.4 - */ + /// Sets the bits from the specified {@code fromIndex} (inclusive) to the + /// specified {@code toIndex} (exclusive) to {@code true}. + /// + /// - parameter fromIndex: index of the first bit to be set + /// - parameter toIndex: index after the last bit to be set + /// - IndexOutOfBoundsException if {@code fromIndex} is negative, + /// or {@code toIndex} is negative, or {@code fromIndex} is + /// larger than {@code toIndex} + /// - 1.4 public func set(_ fromIndex: Int, _ toIndex: Int) throws { try BitSet.checkRange(fromIndex, toIndex) @@ -398,18 +355,16 @@ public class BitSet: Hashable, CustomStringConvertible { checkInvariants() } - /** - * Sets the bits from the specified {@code fromIndex} (inclusive) to the - * specified {@code toIndex} (exclusive) to the specified value. - * - * @param fromIndex index of the first bit to be set - * @param toIndex index after the last bit to be set - * @param value value to set the selected bits to - * @throws IndexOutOfBoundsException if {@code fromIndex} is negative, - * or {@code toIndex} is negative, or {@code fromIndex} is - * larger than {@code toIndex} - * @since 1.4 - */ + /// Sets the bits from the specified {@code fromIndex} (inclusive) to the + /// specified {@code toIndex} (exclusive) to the specified value. + /// + /// - parameter fromIndex: index of the first bit to be set + /// - parameter toIndex: index after the last bit to be set + /// - parameter value: value to set the selected bits to + /// - IndexOutOfBoundsException if {@code fromIndex} is negative, + /// or {@code toIndex} is negative, or {@code fromIndex} is + /// larger than {@code toIndex} + /// - 1.4 public func set(_ fromIndex: Int, _ toIndex: Int, _ value: Bool) throws { if value { try set(fromIndex, toIndex) @@ -418,13 +373,11 @@ public class BitSet: Hashable, CustomStringConvertible { } } - /** - * Sets the bit specified by the index to {@code false}. - * - * @param bitIndex the index of the bit to be cleared - * @throws IndexOutOfBoundsException if the specified index is negative - * @since JDK1.0 - */ + /// Sets the bit specified by the index to {@code false}. + /// + /// - parameter bitIndex: the index of the bit to be cleared + /// - IndexOutOfBoundsException if the specified index is negative + /// - JDK1.0 public func clear(_ bitIndex: Int) throws { if bitIndex < 0 { throw ANTLRError.indexOutOfBounds(msg: "bitIndex < 0: \(bitIndex)") @@ -440,17 +393,15 @@ public class BitSet: Hashable, CustomStringConvertible { checkInvariants() } - /** - * Sets the bits from the specified {@code fromIndex} (inclusive) to the - * specified {@code toIndex} (exclusive) to {@code false}. - * - * @param fromIndex index of the first bit to be cleared - * @param toIndex index after the last bit to be cleared - * @throws IndexOutOfBoundsException if {@code fromIndex} is negative, - * or {@code toIndex} is negative, or {@code fromIndex} is - * larger than {@code toIndex} - * @since 1.4 - */ + /// Sets the bits from the specified {@code fromIndex} (inclusive) to the + /// specified {@code toIndex} (exclusive) to {@code false}. + /// + /// - parameter fromIndex: index of the first bit to be cleared + /// - parameter toIndex: index after the last bit to be cleared + /// - IndexOutOfBoundsException if {@code fromIndex} is negative, + /// or {@code toIndex} is negative, or {@code fromIndex} is + /// larger than {@code toIndex} + /// - 1.4 public func clear(_ fromIndex: Int, _ toIndex: Int) throws { var toIndex = toIndex try BitSet.checkRange(fromIndex, toIndex) @@ -495,11 +446,9 @@ public class BitSet: Hashable, CustomStringConvertible { checkInvariants() } - /** - * Sets all of the bits in this BitSet to {@code false}. - * - * @since 1.4 - */ + /// Sets all of the bits in this BitSet to {@code false}. + /// + /// - 1.4 public func clear() { while wordsInUse > 0 { wordsInUse -= 1 @@ -507,16 +456,14 @@ public class BitSet: Hashable, CustomStringConvertible { } } - /** - * Returns the value of the bit with the specified index. The value - * is {@code true} if the bit with the index {@code bitIndex} - * is currently set in this {@code BitSet}; otherwise, the result - * is {@code false}. - * - * @param bitIndex the bit index - * @return the value of the bit with the specified index - * @throws IndexOutOfBoundsException if the specified index is negative - */ + /// Returns the value of the bit with the specified index. The value + /// is {@code true} if the bit with the index {@code bitIndex} + /// is currently set in this {@code BitSet}; otherwise, the result + /// is {@code false}. + /// + /// - parameter bitIndex: the bit index + /// - returns: the value of the bit with the specified index + /// - IndexOutOfBoundsException if the specified index is negative public func get(_ bitIndex: Int) throws -> Bool { if bitIndex < 0 { throw ANTLRError.indexOutOfBounds(msg: "bitIndex < 0: \(bitIndex)") @@ -530,18 +477,16 @@ public class BitSet: Hashable, CustomStringConvertible { && ((words[index] & ((Int64(1) << Int64(bitIndex % 64)))) != 0) } - /** - * Returns a new {@code BitSet} composed of bits from this {@code BitSet} - * from {@code fromIndex} (inclusive) to {@code toIndex} (exclusive). - * - * @param fromIndex index of the first bit to include - * @param toIndex index after the last bit to include - * @return a new {@code BitSet} from a range of this {@code BitSet} - * @throws IndexOutOfBoundsException if {@code fromIndex} is negative, - * or {@code toIndex} is negative, or {@code fromIndex} is - * larger than {@code toIndex} - * @since 1.4 - */ + /// Returns a new {@code BitSet} composed of bits from this {@code BitSet} + /// from {@code fromIndex} (inclusive) to {@code toIndex} (exclusive). + /// + /// - parameter fromIndex: index of the first bit to include + /// - parameter toIndex: index after the last bit to include + /// - returns: a new {@code BitSet} from a range of this {@code BitSet} + /// - IndexOutOfBoundsException if {@code fromIndex} is negative, + /// or {@code toIndex} is negative, or {@code fromIndex} is + /// larger than {@code toIndex} + /// - 1.4 public func get(_ fromIndex: Int, _ toIndex: Int) throws -> BitSet { var toIndex = toIndex try BitSet.checkRange(fromIndex, toIndex) @@ -602,25 +547,23 @@ public class BitSet: Hashable, CustomStringConvertible { return result } - /** - * Returns the index of the first bit that is set to {@code true} - * that occurs on or after the specified starting index. If no such - * bit exists then {@code -1} is returned. - * - *

          To iterate over the {@code true} bits in a {@code BitSet}, - * use the following loop: - * - *

           {@code
          -    * for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
          -    *     // operate on index i here
          -    * }}
          - * - * @param fromIndex the index to start checking from (inclusive) - * @return the index of the next set bit, or {@code -1} if there - * is no such bit - * @throws IndexOutOfBoundsException if the specified index is negative - * @since 1.4 - */ + /// Returns the index of the first bit that is set to {@code true} + /// that occurs on or after the specified starting index. If no such + /// bit exists then {@code -1} is returned. + /// + ///

          To iterate over the {@code true} bits in a {@code BitSet}, + /// use the following loop: + /// + ///

           {@code
          +    /// for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
          +    /// // operate on index i here
          +    /// }}
          + /// + /// - parameter fromIndex: the index to start checking from (inclusive) + /// - returns: the index of the next set bit, or {@code -1} if there + /// is no such bit + /// - IndexOutOfBoundsException if the specified index is negative + /// - 1.4 public func nextSetBit(_ fromIndex: Int) throws -> Int { if fromIndex < 0 { throw ANTLRError.indexOutOfBounds(msg: "fromIndex < 0: \(fromIndex)") @@ -686,15 +629,13 @@ public class BitSet: Hashable, CustomStringConvertible { return n - ((x << 1) >>> 31) } - /** - * Returns the index of the first bit that is set to {@code false} - * that occurs on or after the specified starting index. - * - * @param fromIndex the index to start checking from (inclusive) - * @return the index of the next clear bit - * @throws IndexOutOfBoundsException if the specified index is negative - * @since 1.4 - */ + /// Returns the index of the first bit that is set to {@code false} + /// that occurs on or after the specified starting index. + /// + /// - parameter fromIndex: the index to start checking from (inclusive) + /// - returns: the index of the next clear bit + /// - IndexOutOfBoundsException if the specified index is negative + /// - 1.4 public func nextClearBit(_ fromIndex: Int) throws -> Int { // Neither spec nor implementation handle bitsets of maximal length. // See 4816253. @@ -724,27 +665,25 @@ public class BitSet: Hashable, CustomStringConvertible { } } - /** - * Returns the index of the nearest bit that is set to {@code true} - * that occurs on or before the specified starting index. - * If no such bit exists, or if {@code -1} is given as the - * starting index, then {@code -1} is returned. - * - *

          To iterate over the {@code true} bits in a {@code BitSet}, - * use the following loop: - * - *

           {@code
          -    * for (int i = bs.length(); (i = bs.previousSetBit(i-1)) >= 0; ) {
          -    *     // operate on index i here
          -    * }}
          - * - * @param fromIndex the index to start checking from (inclusive) - * @return the index of the previous set bit, or {@code -1} if there - * is no such bit - * @throws IndexOutOfBoundsException if the specified index is less - * than {@code -1} - * @since 1.7 - */ + /// Returns the index of the nearest bit that is set to {@code true} + /// that occurs on or before the specified starting index. + /// If no such bit exists, or if {@code -1} is given as the + /// starting index, then {@code -1} is returned. + /// + ///

          To iterate over the {@code true} bits in a {@code BitSet}, + /// use the following loop: + /// + ///

           {@code
          +    /// for (int i = bs.length(); (i = bs.previousSetBit(i-1)) >= 0; ) {
          +    /// // operate on index i here
          +    /// }}
          + /// + /// - parameter fromIndex: the index to start checking from (inclusive) + /// - returns: the index of the previous set bit, or {@code -1} if there + /// is no such bit + /// - IndexOutOfBoundsException if the specified index is less + /// than {@code -1} + /// - 1.7 public func previousSetBit(_ fromIndex: Int) throws -> Int { if fromIndex < 0 { if fromIndex == -1 { @@ -774,19 +713,17 @@ public class BitSet: Hashable, CustomStringConvertible { } } - /** - * Returns the index of the nearest bit that is set to {@code false} - * that occurs on or before the specified starting index. - * If no such bit exists, or if {@code -1} is given as the - * starting index, then {@code -1} is returned. - * - * @param fromIndex the index to start checking from (inclusive) - * @return the index of the previous clear bit, or {@code -1} if there - * is no such bit - * @throws IndexOutOfBoundsException if the specified index is less - * than {@code -1} - * @since 1.7 - */ + /// Returns the index of the nearest bit that is set to {@code false} + /// that occurs on or before the specified starting index. + /// If no such bit exists, or if {@code -1} is given as the + /// starting index, then {@code -1} is returned. + /// + /// - parameter fromIndex: the index to start checking from (inclusive) + /// - returns: the index of the previous clear bit, or {@code -1} if there + /// is no such bit + /// - IndexOutOfBoundsException if the specified index is less + /// than {@code -1} + /// - 1.7 public func previousClearBit(_ fromIndex: Int) throws -> Int { if fromIndex < 0 { if fromIndex == -1 { @@ -849,14 +786,12 @@ public class BitSet: Hashable, CustomStringConvertible { return Int(n) } - /** - * Returns the "logical size" of this {@code BitSet}: the index of - * the highest set bit in the {@code BitSet} plus one. Returns zero - * if the {@code BitSet} contains no set bits. - * - * @return the logical size of this {@code BitSet} - * @since 1.2 - */ + /// Returns the "logical size" of this {@code BitSet}: the index of + /// the highest set bit in the {@code BitSet} plus one. Returns zero + /// if the {@code BitSet} contains no set bits. + /// + /// - returns: the logical size of this {@code BitSet} + /// - 1.2 public func length() -> Int { if wordsInUse == 0 { return 0 @@ -866,26 +801,22 @@ public class BitSet: Hashable, CustomStringConvertible { (BitSet.BITS_PER_WORD - BitSet.numberOfLeadingZeros(words[wordsInUse - 1])) } - /** - * Returns true if this {@code BitSet} contains no bits that are set - * to {@code true}. - * - * @return boolean indicating whether this {@code BitSet} is empty - * @since 1.4 - */ + /// Returns true if this {@code BitSet} contains no bits that are set + /// to {@code true}. + /// + /// - returns: boolean indicating whether this {@code BitSet} is empty + /// - 1.4 public func isEmpty() -> Bool { return wordsInUse == 0 } - /** - * Returns true if the specified {@code BitSet} has any bits set to - * {@code true} that are also set to {@code true} in this {@code BitSet}. - * - * @param set {@code BitSet} to intersect with - * @return boolean indicating whether this {@code BitSet} intersects - * the specified {@code BitSet} - * @since 1.4 - */ + /// Returns true if the specified {@code BitSet} has any bits set to + /// {@code true} that are also set to {@code true} in this {@code BitSet}. + /// + /// - parameter set: {@code BitSet} to intersect with + /// - returns: boolean indicating whether this {@code BitSet} intersects + /// the specified {@code BitSet} + /// - 1.4 public func intersects(_ set: BitSet) -> Bool { var i: Int = min(wordsInUse, set.wordsInUse) - 1 while i >= 0 { @@ -897,12 +828,10 @@ public class BitSet: Hashable, CustomStringConvertible { return false } - /** - * Returns the number of bits set to {@code true} in this {@code BitSet}. - * - * @return the number of bits set to {@code true} in this {@code BitSet} - * @since 1.4 - */ + /// Returns the number of bits set to {@code true} in this {@code BitSet}. + /// + /// - returns: the number of bits set to {@code true} in this {@code BitSet} + /// - 1.4 public func cardinality() -> Int { var sum: Int = 0 for i in 0..AND of this target bit set with the - * argument bit set. This bit set is modified so that each bit in it - * has the value {@code true} if and only if it both initially - * had the value {@code true} and the corresponding bit in the - * bit set argument also had the value {@code true}. - * - * @param set a bit set - */ + /// Performs a logical AND of this target bit set with the + /// argument bit set. This bit set is modified so that each bit in it + /// has the value {@code true} if and only if it both initially + /// had the value {@code true} and the corresponding bit in the + /// bit set argument also had the value {@code true}. + /// + /// - parameter set: a bit set public func and(_ set: BitSet) { if self == set { return @@ -952,15 +879,13 @@ public class BitSet: Hashable, CustomStringConvertible { checkInvariants() } - /** - * Performs a logical OR of this bit set with the bit set - * argument. This bit set is modified so that a bit in it has the - * value {@code true} if and only if it either already had the - * value {@code true} or the corresponding bit in the bit set - * argument has the value {@code true}. - * - * @param set a bit set - */ + /// Performs a logical OR of this bit set with the bit set + /// argument. This bit set is modified so that a bit in it has the + /// value {@code true} if and only if it either already had the + /// value {@code true} or the corresponding bit in the bit set + /// argument has the value {@code true}. + /// + /// - parameter set: a bit set public func or(_ set: BitSet) { if self == set { return @@ -988,20 +913,18 @@ public class BitSet: Hashable, CustomStringConvertible { checkInvariants() } - /** - * Performs a logical XOR of this bit set with the bit set - * argument. This bit set is modified so that a bit in it has the - * value {@code true} if and only if one of the following - * statements holds: - *
            - *
          • The bit initially has the value {@code true}, and the - * corresponding bit in the argument has the value {@code false}. - *
          • The bit initially has the value {@code false}, and the - * corresponding bit in the argument has the value {@code true}. - *
          - * - * @param set a bit set - */ + /// Performs a logical XOR of this bit set with the bit set + /// argument. This bit set is modified so that a bit in it has the + /// value {@code true} if and only if one of the following + /// statements holds: + ///
            + ///
          • The bit initially has the value {@code true}, and the + /// corresponding bit in the argument has the value {@code false}. + ///
          • The bit initially has the value {@code false}, and the + /// corresponding bit in the argument has the value {@code true}. + ///
          + /// + /// - parameter set: a bit set public func xor(_ set: BitSet) { let wordsInCommon: Int = min(wordsInUse, set.wordsInUse) @@ -1026,14 +949,12 @@ public class BitSet: Hashable, CustomStringConvertible { checkInvariants() } - /** - * Clears all of the bits in this {@code BitSet} whose corresponding - * bit is set in the specified {@code BitSet}. - * - * @param set the {@code BitSet} with which to mask this - * {@code BitSet} - * @since 1.2 - */ + /// Clears all of the bits in this {@code BitSet} whose corresponding + /// bit is set in the specified {@code BitSet}. + /// + /// - parameter set: the {@code BitSet} with which to mask this + /// {@code BitSet} + /// - 1.2 public func andNot(_ set: BitSet) { // Perform logical (a & !b) on words in common var i: Int = min(wordsInUse, set.wordsInUse) - 1 @@ -1046,24 +967,22 @@ public class BitSet: Hashable, CustomStringConvertible { checkInvariants() } - /** - * Returns the hash code value for this bit set. The hash code depends - * only on which bits are set within this {@code BitSet}. - * - *

          The hash code is defined to be the result of the following - * calculation: - *

           {@code
          -    * public int hashCode() {
          -    *     long h = 1234;
          -    *     long[] words = toLongArray();
          -    *     for (int i = words.length; --i >= 0; )
          -    *         h ^= words[i] * (i + 1);
          -    *     return (int)((h >> 32) ^ h);
          -    * }}
          - * Note that the hash code changes if the set of bits is altered. - * - * @return the hash code value for this bit set - */ + /// Returns the hash code value for this bit set. The hash code depends + /// only on which bits are set within this {@code BitSet}. + /// + ///

          The hash code is defined to be the result of the following + /// calculation: + ///

           {@code
          +    /// public int hashCode() {
          +    /// long h = 1234;
          +    /// long[] words = toLongArray();
          +    /// for (int i = words.length; --i >= 0; )
          +    /// h ^= words[i] * (i + 1);
          +    /// return (int)((h >> 32) ^ h);
          +    /// }}
          + /// Note that the hash code changes if the set of bits is altered. + /// + /// - returns: the hash code value for this bit set public var hashValue: Int { var h: Int64 = 1234 var i: Int = wordsInUse @@ -1076,13 +995,11 @@ public class BitSet: Hashable, CustomStringConvertible { return Int(Int32((h >> 32) ^ h)) } - /** - * Returns the number of bits of space actually in use by this - * {@code BitSet} to represent bit values. - * The maximum element in the set is the size - 1st element. - * - * @return the number of bits currently in this bit set - */ + /// Returns the number of bits of space actually in use by this + /// {@code BitSet} to represent bit values. + /// The maximum element in the set is the size - 1st element. + /// + /// - returns: the number of bits currently in this bit set public func size() -> Int { return words.count * BitSet.BITS_PER_WORD } @@ -1091,11 +1008,9 @@ public class BitSet: Hashable, CustomStringConvertible { - /** - * Attempts to reduce internal storage used for the bits in this bit set. - * Calling this method may, but is not required to, affect the value - * returned by a subsequent call to the {@link #size()} method. - */ + /// Attempts to reduce internal storage used for the bits in this bit set. + /// Calling this method may, but is not required to, affect the value + /// returned by a subsequent call to the {@link #size()} method. private func trimToSize() { if wordsInUse != words.count { words = copyOf(words, wordsInUse) @@ -1104,29 +1019,27 @@ public class BitSet: Hashable, CustomStringConvertible { } - /** - * Returns a string representation of this bit set. For every index - * for which this {@code BitSet} contains a bit in the set - * state, the decimal representation of that index is included in - * the result. Such indices are listed in order from lowest to - * highest, separated by ", " (a comma and a space) and - * surrounded by braces, resulting in the usual mathematical - * notation for a set of integers. - * - *

          Example: - *

          -    * BitSet drPepper = new BitSet();
          - * Now {@code drPepper.toString()} returns "{@code {}}". - *
          -    * drPepper.set(2);
          - * Now {@code drPepper.toString()} returns "{@code {2}}". - *
          -    * drPepper.set(4);
          -    * drPepper.set(10);
          - * Now {@code drPepper.toString()} returns "{@code {2, 4, 10}}". - * - * @return a string representation of this bit set - */ + /// Returns a string representation of this bit set. For every index + /// for which this {@code BitSet} contains a bit in the set + /// state, the decimal representation of that index is included in + /// the result. Such indices are listed in order from lowest to + /// highest, separated by ", " (a comma and a space) and + /// surrounded by braces, resulting in the usual mathematical + /// notation for a set of integers. + /// + ///

          Example: + ///

          +    /// BitSet drPepper = new BitSet();
          + /// Now {@code drPepper.toString()} returns "{@code {}}". + ///
          +    /// drPepper.set(2);
          + /// Now {@code drPepper.toString()} returns "{@code {2}}". + ///
          +    /// drPepper.set(4);
          +    /// drPepper.set(10);
          + /// Now {@code drPepper.toString()} returns "{@code {2, 4, 10}}". + /// + /// - returns: a string representation of this bit set public var description: String { checkInvariants() diff --git a/runtime/Swift/Sources/Antlr4/misc/DoubleKeyMap.swift b/runtime/Swift/Sources/Antlr4/misc/DoubleKeyMap.swift index 56d4df4b4..a45a6c64c 100644 --- a/runtime/Swift/Sources/Antlr4/misc/DoubleKeyMap.swift +++ b/runtime/Swift/Sources/Antlr4/misc/DoubleKeyMap.swift @@ -1,14 +1,12 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** Sometimes we need to map a key to a value but key is two pieces of data. - * This nested hash table saves creating a single key each time we access - * map; avoids mem creation. - */ +/// Sometimes we need to map a key to a value but key is two pieces of data. +/// This nested hash table saves creating a single key each time we access +/// map; avoids mem creation. public struct DoubleKeyMap { private var data: HashMap> = HashMap>() diff --git a/runtime/Swift/Sources/Antlr4/misc/HashMap.swift b/runtime/Swift/Sources/Antlr4/misc/HashMap.swift index f84c06875..8e77cacf5 100644 --- a/runtime/Swift/Sources/Antlr4/misc/HashMap.swift +++ b/runtime/Swift/Sources/Antlr4/misc/HashMap.swift @@ -1,7 +1,6 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. final class Entry: CustomStringConvertible { final var key: K @@ -9,9 +8,7 @@ final class Entry: CustomStringConvertible { final var next: Entry! final var hash: Int - /** - * Creates new entry. - */ + /// Creates new entry. init(_ h: Int, _ k: K, _ v: V, _ n: Entry!) { value = v next = n @@ -70,53 +67,37 @@ func == (lhs: Entry, rhs: Entry) -> Bool public final class HashMap: Sequence { - /** - * The default initial capacity - MUST be a power of two. - */ + /// The default initial capacity - MUST be a power of two. let DEFAULT_INITIAL_CAPACITY: Int = 16 - /** - * The maximum capacity, used if a higher value is implicitly specified - * by either of the constructors with arguments. - * MUST be a power of two <= 1<<30. - */ + /// The maximum capacity, used if a higher value is implicitly specified + /// by either of the constructors with arguments. + /// MUST be a power of two <= 1<<30. let MAXIMUM_CAPACITY: Int = 1 << 30 - /** - * The load factor used when none specified in constructor. - */ + /// The load factor used when none specified in constructor. let DEFAULT_LOAD_FACTOR: Float = 0.75 - /** - * The table, resized as necessary. Length MUST Always be a power of two. - */ + /// The table, resized as necessary. Length MUST Always be a power of two. var table: [Entry?] - /** - * The number of key-value mappings contained in this map. - */ + /// The number of key-value mappings contained in this map. var size: Int = 0 - /** - * The next size value at which to resize (capacity * load factor). - * @serial - */ + /// The next size value at which to resize (capacity * load factor). + /// - var threshold: Int = 0 - /** - * The load factor for the hash table. - * - * @serial - */ + /// The load factor for the hash table. + /// + /// - var loadFactor: Float = 0 - /** - * The number of times this HashMap has been structurally modified - * Structural modifications are those that change the number of mappings in - * the HashMap or otherwise modify its internal structure (e.g., - * rehash). This field is used to make iterators on Collection-views of - * the HashMap fail-fast. (See ConcurrentModificationException). - */ + /// The number of times this HashMap has been structurally modified + /// Structural modifications are those that change the number of mappings in + /// the HashMap or otherwise modify its internal structure (e.g., + /// rehash). This field is used to make iterators on Collection-views of + /// the HashMap fail-fast. (See ConcurrentModificationException). var modCount: Int = 0 public init(count: Int) { @@ -156,18 +137,14 @@ public final class HashMap: Sequence return h ^ (h >>> 7) ^ (h >>> 4) } - /** - * Returns index for hash code h. - */ + /// Returns index for hash code h. static func indexFor(_ h: Int, _ length: Int) -> Int { return h & (length-1) } - /** - * Returns true if this map contains no key-value mappings. - * - * @return true if this map contains no key-value mappings - */ + /// Returns true if this map contains no key-value mappings. + /// + /// - returns: true if this map contains no key-value mappings public final var isEmpty: Bool { return size == 0 } @@ -187,23 +164,21 @@ public final class HashMap: Sequence public final var count: Int { return size } - /** - * Returns the value to which the specified key is mapped, - * or {@code null} if this map contains no mapping for the key. - * - *

          More formally, if this map contains a mapping from a key - * {@code k} to a value {@code v} such that {@code (key==null ? k==null : - * key.equals(k))}, then this method returns {@code v}; otherwise - * it returns {@code null}. (There can be at most one such mapping.) - * - *

          A return value of {@code null} does not necessarily - * indicate that the map contains no mapping for the key; it's also - * possible that the map explicitly maps the key to {@code null}. - * The {@link #containsKey containsKey} operation may be used to - * distinguish these two cases. - * - * @see #put(Object, Object) - */ + /// Returns the value to which the specified key is mapped, + /// or {@code null} if this map contains no mapping for the key. + /// + ///

          More formally, if this map contains a mapping from a key + /// {@code k} to a value {@code v} such that {@code (key==null ? k==null : + /// key.equals(k))}, then this method returns {@code v}; otherwise + /// it returns {@code null}. (There can be at most one such mapping.) + /// + ///

          A return value of {@code null} does not necessarily + /// indicate that the map contains no mapping for the key; it's also + /// possible that the map explicitly maps the key to {@code null}. + /// The {@link #containsKey containsKey} operation may be used to + /// distinguish these two cases. + /// + /// - seealso: #put(Object, Object) public final func get(_ key: K) -> V? { let hash: Int = HashMap.hash(key.hashValue) var e = table[HashMap.indexFor(hash, table.count)] @@ -217,23 +192,19 @@ public final class HashMap: Sequence return nil } - /** - * Returns true if this map contains a mapping for the - * specified key. - * - * @param key The key whose presence in this map is to be tested - * @return true if this map contains a mapping for the specified - * key. - */ + /// Returns true if this map contains a mapping for the + /// specified key. + /// + /// - parameter key: The key whose presence in this map is to be tested + /// - returns: true if this map contains a mapping for the specified + /// key. public final func containsKey(_ key: K) -> Bool { return getEntry(key) != nil } - /** - * Returns the entry associated with the specified key in the - * HashMap. Returns null if the HashMap contains no mapping - * for the key. - */ + /// Returns the entry associated with the specified key in the + /// HashMap. Returns null if the HashMap contains no mapping + /// for the key. final func getEntry(_ key: K) -> Entry! { let hash: Int = HashMap.hash(key.hashValue) var e = table[HashMap.indexFor(hash, table.count)] @@ -249,18 +220,16 @@ public final class HashMap: Sequence } - /** - * Associates the specified value with the specified key in this map. - * If the map previously contained a mapping for the key, the old - * value is replaced. - * - * @param key key with which the specified value is to be associated - * @param value value to be associated with the specified key - * @return the previous value associated with key, or - * null if there was no mapping for key. - * (A null return can also indicate that the map - * previously associated null with key.) - */ + /// Associates the specified value with the specified key in this map. + /// If the map previously contained a mapping for the key, the old + /// value is replaced. + /// + /// - parameter key: key with which the specified value is to be associated + /// - parameter value: value to be associated with the specified key + /// - returns: the previous value associated with key, or + /// null if there was no mapping for key. + /// (A null return can also indicate that the map + /// previously associated null with key.) @discardableResult public final func put(_ key: K, _ value: V) -> V? { @@ -282,13 +251,11 @@ public final class HashMap: Sequence return nil } - /** - * Adds a new entry with the specified key, value and hash code to - * the specified bucket. It is the responsibility of this - * method to resize the table if appropriate. - * - * Subclass overrides this to alter the behavior of put method. - */ + /// Adds a new entry with the specified key, value and hash code to + /// the specified bucket. It is the responsibility of this + /// method to resize the table if appropriate. + /// + /// Subclass overrides this to alter the behavior of put method. final func addEntry(_ hash: Int, _ key: K, _ value: V, _ bucketIndex: Int) { let e = table[bucketIndex] table[bucketIndex] = Entry(hash, key, value, e) @@ -298,20 +265,18 @@ public final class HashMap: Sequence resize(2 * table.count) } } - /** - * Rehashes the contents of this map into a new array with a - * larger capacity. This method is called automatically when the - * number of keys in this map reaches its threshold. - * - * If current capacity is MAXIMUM_CAPACITY, this method does not - * resize the map, but sets threshold to Integer.MAX_VALUE. - * This has the effect of preventing future calls. - * - * @param newCapacity the new capacity, MUST be a power of two; - * must be greater than current capacity unless current - * capacity is MAXIMUM_CAPACITY (in which case value - * is irrelevant). - */ + /// Rehashes the contents of this map into a new array with a + /// larger capacity. This method is called automatically when the + /// number of keys in this map reaches its threshold. + /// + /// If current capacity is MAXIMUM_CAPACITY, this method does not + /// resize the map, but sets threshold to Integer.MAX_VALUE. + /// This has the effect of preventing future calls. + /// + /// - parameter newCapacity: the new capacity, MUST be a power of two; + /// must be greater than current capacity unless current + /// capacity is MAXIMUM_CAPACITY (in which case value + /// is irrelevant). final func resize(_ newCapacity: Int) { let oldCapacity: Int = table.count if oldCapacity == MAXIMUM_CAPACITY { @@ -325,9 +290,7 @@ public final class HashMap: Sequence threshold = Int(Float(newCapacity) * loadFactor) } - /** - * Transfers all entries from current table to newTable. - */ + /// Transfers all entries from current table to newTable. final func transfer(_ newTable: inout [Entry?]) { let newCapacity: Int = newTable.count @@ -346,10 +309,8 @@ public final class HashMap: Sequence } } } - /** - * Removes all of the mappings from this map. - * The map will be empty after this call returns. - */ + /// Removes all of the mappings from this map. + /// The map will be empty after this call returns. public final func clear() { modCount += 1 let length = table.count diff --git a/runtime/Swift/Sources/Antlr4/misc/IntSet.swift b/runtime/Swift/Sources/Antlr4/misc/IntSet.swift index 964c16292..a4498525d 100644 --- a/runtime/Swift/Sources/Antlr4/misc/IntSet.swift +++ b/runtime/Swift/Sources/Antlr4/misc/IntSet.swift @@ -1,170 +1,139 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * A generic set of integers. - * - * @see org.antlr.v4.runtime.misc.IntervalSet - */ +/// A generic set of integers. +/// +/// - seealso: org.antlr.v4.runtime.misc.IntervalSet public protocol IntSet { - /** - * Adds the specified value to the current set. - * - * @param el the value to add - * - * @exception IllegalStateException if the current set is read-only - */ + /// Adds the specified value to the current set. + /// + /// - parameter el: the value to add + /// + /// - IllegalStateException if the current set is read-only func add(_ el: Int) throws - /** - * Modify the current {@link org.antlr.v4.runtime.misc.IntSet} object to contain all elements that are - * present in itself, the specified {@code set}, or both. - * - * @param set The set to add to the current set. A {@code null} argument is - * treated as though it were an empty set. - * @return {@code this} (to support chained calls) - * - * @exception IllegalStateException if the current set is read-only - */ + /// Modify the current {@link org.antlr.v4.runtime.misc.IntSet} object to contain all elements that are + /// present in itself, the specified {@code set}, or both. + /// + /// - parameter set: The set to add to the current set. A {@code null} argument is + /// treated as though it were an empty set. + /// - returns: {@code this} (to support chained calls) + /// + /// - IllegalStateException if the current set is read-only func addAll(_ set: IntSet?) throws -> IntSet - /** - * Return a new {@link org.antlr.v4.runtime.misc.IntSet} object containing all elements that are - * present in both the current set and the specified set {@code a}. - * - * @param a The set to intersect with the current set. A {@code null} - * argument is treated as though it were an empty set. - * @return A new {@link org.antlr.v4.runtime.misc.IntSet} instance containing the intersection of the - * current set and {@code a}. The value {@code null} may be returned in - * place of an empty result set. - */ + /// Return a new {@link org.antlr.v4.runtime.misc.IntSet} object containing all elements that are + /// present in both the current set and the specified set {@code a}. + /// + /// - parameter a: The set to intersect with the current set. A {@code null} + /// argument is treated as though it were an empty set. + /// - returns: A new {@link org.antlr.v4.runtime.misc.IntSet} instance containing the intersection of the + /// current set and {@code a}. The value {@code null} may be returned in + /// place of an empty result set. func and(_ a: IntSet?) throws -> IntSet? - /** - * Return a new {@link org.antlr.v4.runtime.misc.IntSet} object containing all elements that are - * present in {@code elements} but not present in the current set. The - * following expressions are equivalent for input non-null {@link org.antlr.v4.runtime.misc.IntSet} - * instances {@code x} and {@code y}. - * - *

            - *
          • {@code x.complement(y)}
          • - *
          • {@code y.subtract(x)}
          • - *
          - * - * @param elements The set to compare with the current set. A {@code null} - * argument is treated as though it were an empty set. - * @return A new {@link org.antlr.v4.runtime.misc.IntSet} instance containing the elements present in - * {@code elements} but not present in the current set. The value - * {@code null} may be returned in place of an empty result set. - */ + /// Return a new {@link org.antlr.v4.runtime.misc.IntSet} object containing all elements that are + /// present in {@code elements} but not present in the current set. The + /// following expressions are equivalent for input non-null {@link org.antlr.v4.runtime.misc.IntSet} + /// instances {@code x} and {@code y}. + /// + ///
            + ///
          • {@code x.complement(y)}
          • + ///
          • {@code y.subtract(x)}
          • + ///
          + /// + /// - parameter elements: The set to compare with the current set. A {@code null} + /// argument is treated as though it were an empty set. + /// - returns: A new {@link org.antlr.v4.runtime.misc.IntSet} instance containing the elements present in + /// {@code elements} but not present in the current set. The value + /// {@code null} may be returned in place of an empty result set. func complement(_ elements: IntSet?) throws -> IntSet? - /** - * Return a new {@link org.antlr.v4.runtime.misc.IntSet} object containing all elements that are - * present in the current set, the specified set {@code a}, or both. - * - *

          - * This method is similar to {@link #addAll(org.antlr.v4.runtime.misc.IntSet)}, but returns a new - * {@link org.antlr.v4.runtime.misc.IntSet} instance instead of modifying the current set.

          - * - * @param a The set to union with the current set. A {@code null} argument - * is treated as though it were an empty set. - * @return A new {@link org.antlr.v4.runtime.misc.IntSet} instance containing the union of the current - * set and {@code a}. The value {@code null} may be returned in place of an - * empty result set. - */ + /// Return a new {@link org.antlr.v4.runtime.misc.IntSet} object containing all elements that are + /// present in the current set, the specified set {@code a}, or both. + /// + ///

          + /// This method is similar to {@link #addAll(org.antlr.v4.runtime.misc.IntSet)}, but returns a new + /// {@link org.antlr.v4.runtime.misc.IntSet} instance instead of modifying the current set.

          + /// + /// - parameter a: The set to union with the current set. A {@code null} argument + /// is treated as though it were an empty set. + /// - returns: A new {@link org.antlr.v4.runtime.misc.IntSet} instance containing the union of the current + /// set and {@code a}. The value {@code null} may be returned in place of an + /// empty result set. func or(_ a: IntSet) throws -> IntSet - /** - * Return a new {@link org.antlr.v4.runtime.misc.IntSet} object containing all elements that are - * present in the current set but not present in the input set {@code a}. - * The following expressions are equivalent for input non-null - * {@link org.antlr.v4.runtime.misc.IntSet} instances {@code x} and {@code y}. - * - *
            - *
          • {@code y.subtract(x)}
          • - *
          • {@code x.complement(y)}
          • - *
          - * - * @param a The set to compare with the current set. A {@code null} - * argument is treated as though it were an empty set. - * @return A new {@link org.antlr.v4.runtime.misc.IntSet} instance containing the elements present in - * {@code elements} but not present in the current set. The value - * {@code null} may be returned in place of an empty result set. - */ + /// Return a new {@link org.antlr.v4.runtime.misc.IntSet} object containing all elements that are + /// present in the current set but not present in the input set {@code a}. + /// The following expressions are equivalent for input non-null + /// {@link org.antlr.v4.runtime.misc.IntSet} instances {@code x} and {@code y}. + /// + ///
            + ///
          • {@code y.subtract(x)}
          • + ///
          • {@code x.complement(y)}
          • + ///
          + /// + /// - parameter a: The set to compare with the current set. A {@code null} + /// argument is treated as though it were an empty set. + /// - returns: A new {@link org.antlr.v4.runtime.misc.IntSet} instance containing the elements present in + /// {@code elements} but not present in the current set. The value + /// {@code null} may be returned in place of an empty result set. func subtract(_ a: IntSet?) throws -> IntSet - /** - * Return the total number of elements represented by the current set. - * - * @return the total number of elements represented by the current set, - * regardless of the manner in which the elements are stored. - */ + /// Return the total number of elements represented by the current set. + /// + /// - returns: the total number of elements represented by the current set, + /// regardless of the manner in which the elements are stored. func size() -> Int - /** - * Returns {@code true} if this set contains no elements. - * - * @return {@code true} if the current set contains no elements; otherwise, - * {@code false}. - */ + /// Returns {@code true} if this set contains no elements. + /// + /// - returns: {@code true} if the current set contains no elements; otherwise, + /// {@code false}. func isNil() -> Bool - /** - * {@inheritDoc} - */ + /// {@inheritDoc} //func equals(obj : AnyObject) -> Bool; - /** - * Returns the single value contained in the set, if {@link #size} is 1; - * otherwise, returns {@link org.antlr.v4.runtime.Token#INVALID_TYPE}. - * - * @return the single value contained in the set, if {@link #size} is 1; - * otherwise, returns {@link org.antlr.v4.runtime.Token#INVALID_TYPE}. - */ + /// Returns the single value contained in the set, if {@link #size} is 1; + /// otherwise, returns {@link org.antlr.v4.runtime.Token#INVALID_TYPE}. + /// + /// - returns: the single value contained in the set, if {@link #size} is 1; + /// otherwise, returns {@link org.antlr.v4.runtime.Token#INVALID_TYPE}. func getSingleElement() -> Int - /** - * Returns {@code true} if the set contains the specified element. - * - * @param el The element to check for. - * @return {@code true} if the set contains {@code el}; otherwise {@code false}. - */ + /// Returns {@code true} if the set contains the specified element. + /// + /// - parameter el: The element to check for. + /// - returns: {@code true} if the set contains {@code el}; otherwise {@code false}. func contains(_ el: Int) -> Bool - /** - * Removes the specified value from the current set. If the current set does - * not contain the element, no changes are made. - * - * @param el the value to remove - * - * @exception IllegalStateException if the current set is read-only - */ + /// Removes the specified value from the current set. If the current set does + /// not contain the element, no changes are made. + /// + /// - parameter el: the value to remove + /// + /// - IllegalStateException if the current set is read-only func remove(_ el: Int) throws - /** - * Return a list containing the elements represented by the current set. The - * list is returned in ascending numerical order. - * - * @return A list containing all element present in the current set, sorted - * in ascending numerical order. - */ + /// Return a list containing the elements represented by the current set. The + /// list is returned in ascending numerical order. + /// + /// - returns: A list containing all element present in the current set, sorted + /// in ascending numerical order. func toList() -> Array - /** - * {@inheritDoc} - */ + /// {@inheritDoc} func toString() -> String } diff --git a/runtime/Swift/Sources/Antlr4/misc/Interval.swift b/runtime/Swift/Sources/Antlr4/misc/Interval.swift index d27d6a7fc..d2bd7b8ae 100644 --- a/runtime/Swift/Sources/Antlr4/misc/Interval.swift +++ b/runtime/Swift/Sources/Antlr4/misc/Interval.swift @@ -1,10 +1,9 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** An immutable inclusive interval a..b */ +/// An immutable inclusive interval a..b public class Interval: Hashable { public static let INTERVAL_POOL_MAX_VALUE: Int = 1000 @@ -28,12 +27,11 @@ public class Interval: Hashable { self.b = b } - /** Interval objects are used readonly so share all with the - * same single value a==b up to some max size. Use an array as a perfect hash. - * Return shared object for 0..INTERVAL_POOL_MAX_VALUE or a new - * Interval object with a..a in it. On Java.g4, 218623 IntervalSets - * have a..a (set with 1 element). - */ + /// Interval objects are used readonly so share all with the + /// same single value a==b up to some max size. Use an array as a perfect hash. + /// Return shared object for 0..INTERVAL_POOL_MAX_VALUE or a new + /// Interval object with a..a in it. On Java.g4, 218623 IntervalSets + /// have a..a (set with 1 element). public static func of(_ a: Int, _ b: Int) -> Interval { // cache just a..a if a != b || a < 0 || a > INTERVAL_POOL_MAX_VALUE { @@ -46,9 +44,8 @@ public class Interval: Hashable { return cache[a]! } - /** return number of elements between a and b inclusively. x..x is length 1. - * if b < a, then length is 0. 9..10 has length 2. - */ + /// return number of elements between a and b inclusively. x..x is length 1. + /// if b < a, then length is 0. 9..10 has length 2. public func length() -> Int { if b < a { return 0 @@ -63,37 +60,37 @@ public class Interval: Hashable { hash = hash * 31 + b return hash } - /** Does this start completely before other? Disjoint */ + /// Does this start completely before other? Disjoint public func startsBeforeDisjoint(_ other: Interval) -> Bool { return self.a < other.a && self.b < other.a } - /** Does this start at or before other? Nondisjoint */ + /// Does this start at or before other? Nondisjoint public func startsBeforeNonDisjoint(_ other: Interval) -> Bool { return self.a <= other.a && self.b >= other.a } - /** Does this.a start after other.b? May or may not be disjoint */ + /// Does this.a start after other.b? May or may not be disjoint public func startsAfter(_ other: Interval) -> Bool { return self.a > other.a } - /** Does this start completely after other? Disjoint */ + /// Does this start completely after other? Disjoint public func startsAfterDisjoint(_ other: Interval) -> Bool { return self.a > other.b } - /** Does this start after other? NonDisjoint */ + /// Does this start after other? NonDisjoint public func startsAfterNonDisjoint(_ other: Interval) -> Bool { return self.a > other.a && self.a <= other.b // this.b>=other.b implied } - /** Are both ranges disjoint? I.e., no overlap? */ + /// Are both ranges disjoint? I.e., no overlap? public func disjoint(_ other: Interval) -> Bool { return startsBeforeDisjoint(other) || startsAfterDisjoint(other) } - /** Are two intervals adjacent such as 0..41 and 42..42? */ + /// Are two intervals adjacent such as 0..41 and 42..42? public func adjacent(_ other: Interval) -> Bool { return self.a == other.b + 1 || self.b == other.a - 1 } @@ -102,21 +99,20 @@ public class Interval: Hashable { return other.a >= self.a && other.b <= self.b } - /** Return the interval computed from combining this and other */ + /// Return the interval computed from combining this and other public func union(_ other: Interval) -> Interval { return Interval.of(min(a, other.a), max(b, other.b)) } - /** Return the interval in common between this and o */ + /// Return the interval in common between this and o public func intersection(_ other: Interval) -> Interval { return Interval.of(max(a, other.a), min(b, other.b)) } - /** Return the interval with elements from this not in other; - * other must not be totally enclosed (properly contained) - * within this, which would result in two disjoint intervals - * instead of the single one returned by this method. - */ + /// Return the interval with elements from this not in other; + /// other must not be totally enclosed (properly contained) + /// within this, which would result in two disjoint intervals + /// instead of the single one returned by this method. public func differenceNotProperlyContained(_ other: Interval) -> Interval? { var diff: Interval? = nil // other.a to left of this.a (or same) diff --git a/runtime/Swift/Sources/Antlr4/misc/IntervalSet.swift b/runtime/Swift/Sources/Antlr4/misc/IntervalSet.swift index 4283d950c..8cc5c77c4 100644 --- a/runtime/Swift/Sources/Antlr4/misc/IntervalSet.swift +++ b/runtime/Swift/Sources/Antlr4/misc/IntervalSet.swift @@ -1,21 +1,18 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. -/** - * This class implements the {@link org.antlr.v4.runtime.misc.IntSet} backed by a sorted array of - * non-overlapping intervals. It is particularly efficient for representing - * large collections of numbers, where the majority of elements appear as part - * of a sequential range of numbers that are all part of the set. For example, - * the set { 1, 2, 3, 4, 7, 8 } may be represented as { [1, 4], [7, 8] }. - * - *

          - * This class is able to represent sets containing any combination of values in - * the range {@link Integer#MIN_VALUE} to {@link Integer#MAX_VALUE} - * (inclusive).

          - */ +/// This class implements the {@link org.antlr.v4.runtime.misc.IntSet} backed by a sorted array of +/// non-overlapping intervals. It is particularly efficient for representing +/// large collections of numbers, where the majority of elements appear as part +/// of a sequential range of numbers that are all part of the set. For example, +/// the set { 1, 2, 3, 4, 7, 8 } may be represented as { [1, 4], [7, 8] }. +/// +///

          +/// This class is able to represent sets containing any combination of values in +/// the range {@link Integer#MIN_VALUE} to {@link Integer#MAX_VALUE} +/// (inclusive).

          public class IntervalSet: IntSet, Hashable, CustomStringConvertible { public static let COMPLETE_CHAR_SET: IntervalSet = @@ -32,7 +29,7 @@ public class IntervalSet: IntSet, Hashable, CustomStringConvertible { }() - /** The list of sorted, disjoint intervals. */ + /// The list of sorted, disjoint intervals. internal var intervals: Array internal var readonly: Bool = false @@ -58,7 +55,7 @@ public class IntervalSet: IntSet, Hashable, CustomStringConvertible { } } - /** Create a set with a single element, el. */ + /// Create a set with a single element, el. public static func of(_ a: Int) throws -> IntervalSet { let s: IntervalSet = try IntervalSet() @@ -66,7 +63,7 @@ public class IntervalSet: IntSet, Hashable, CustomStringConvertible { return s } - /** Create a set with all ints within range [a..b] (inclusive) */ + /// Create a set with all ints within range [a..b] (inclusive) public static func of(_ a: Int, _ b: Int) throws -> IntervalSet { let s: IntervalSet = try IntervalSet() try s.add(a, b) @@ -80,9 +77,8 @@ public class IntervalSet: IntSet, Hashable, CustomStringConvertible { intervals.removeAll() } - /** Add a single element to the set. An isolated element is stored - * as a range el..el. - */ + /// Add a single element to the set. An isolated element is stored + /// as a range el..el. public func add(_ el: Int) throws { if readonly { @@ -91,13 +87,12 @@ public class IntervalSet: IntSet, Hashable, CustomStringConvertible { try add(el, el) } - /** Add interval; i.e., add all integers from a to b to set. - * If b<a, do nothing. - * Keep list in sorted order (by left range value). - * If overlap, combine ranges. For example, - * If this is {1..5, 10..20}, adding 6..7 yields - * {1..5, 6..7, 10..20}. Adding 4..8 yields {1..8, 10..20}. - */ + /// Add interval; i.e., add all integers from a to b to set. + /// If b<a, do nothing. + /// Keep list in sorted order (by left range value). + /// If overlap, combine ranges. For example, + /// If this is {1..5, 10..20}, adding 6..7 yields + /// {1..5, 6..7, 10..20}. Adding 4..8 yields {1..8, 10..20}. public func add(_ a: Int, _ b: Int) throws { try add(Interval.of(a, b)) } @@ -137,10 +132,10 @@ public class IntervalSet: IntSet, Hashable, CustomStringConvertible { } // if we bump up against or overlap next, merge - /*iter.remove(); // remove this one - iter.previous(); // move backwards to what we just set - iter.set(bigger.union(next)); // set to 3 merged ones - iter.next(); // first call to next after previous duplicates the result*/ + /// iter.remove(); // remove this one + /// iter.previous(); // move backwards to what we just set + /// iter.set(bigger.union(next)); // set to 3 merged ones + /// iter.next(); // first call to next after previous duplicates the resul intervals.remove(at: i) i -= 1 intervals[i] = bigger.union(next) @@ -164,7 +159,7 @@ public class IntervalSet: IntSet, Hashable, CustomStringConvertible { intervals.append(addition) } - /** combine all sets in the array returned the or'd value */ + /// combine all sets in the array returned the or'd value public func or(_ sets: [IntervalSet]) throws -> IntSet { let r: IntervalSet = try IntervalSet() for s: IntervalSet in sets { @@ -200,7 +195,7 @@ public class IntervalSet: IntSet, Hashable, CustomStringConvertible { return try self.complement(IntervalSet.of(minElement, maxElement)) } - /** {@inheritDoc} */ + /// {@inheritDoc} public func complement(_ vocabulary: IntSet?) throws -> IntSet? { guard let vocabulary = vocabulary , !vocabulary.isNil() else { @@ -231,11 +226,9 @@ public class IntervalSet: IntSet, Hashable, CustomStringConvertible { return try subtract(self, other) } - /** - * Compute the set difference between two interval sets. The specific - * operation is {@code left - right}. If either of the input sets is - * {@code null}, it is treated as though it was an empty set. - */ + /// Compute the set difference between two interval sets. The specific + /// operation is {@code left - right}. If either of the input sets is + /// {@code null}, it is treated as though it was an empty set. public func subtract(_ left: IntervalSet?, _ right: IntervalSet?) throws -> IntervalSet { @@ -322,7 +315,7 @@ public class IntervalSet: IntSet, Hashable, CustomStringConvertible { return o } - /** {@inheritDoc} */ + /// {@inheritDoc} public func and(_ other: IntSet?) throws -> IntSet? { if other == nil { @@ -399,7 +392,7 @@ public class IntervalSet: IntSet, Hashable, CustomStringConvertible { return intersection } - /** {@inheritDoc} */ + /// {@inheritDoc} public func contains(_ el: Int) -> Bool { let n: Int = intervals.count @@ -415,27 +408,25 @@ public class IntervalSet: IntSet, Hashable, CustomStringConvertible { } } return false -/* - for (ListIterator iter = intervals.listIterator(); iter.hasNext();) { - Interval I = (Interval) iter.next(); - if ( el=I.a && el<=I.b ) { - return true; // found in this interval - } - } - return false; - */ +/// for (ListIterator iter = intervals.listIterator(); iter.hasNext();) { +/// Interval I = (Interval) iter.next(); +/// if ( el=I.a && el<=I.b ) { +/// return true; // found in this interval +/// } +/// } +/// return false; } - /** {@inheritDoc} */ + /// {@inheritDoc} public func isNil() -> Bool { return intervals.isEmpty } - /** {@inheritDoc} */ + /// {@inheritDoc} public func getSingleElement() -> Int { //intervals=nil && intervals.count==1 ) @@ -448,12 +439,10 @@ public class IntervalSet: IntSet, Hashable, CustomStringConvertible { return CommonToken.INVALID_TYPE } - /** - * Returns the maximum value contained in the set. - * - * @return the maximum value contained in the set. If the set is empty, this - * method returns {@link org.antlr.v4.runtime.Token#INVALID_TYPE}. - */ + /// Returns the maximum value contained in the set. + /// + /// - returns: the maximum value contained in the set. If the set is empty, this + /// method returns {@link org.antlr.v4.runtime.Token#INVALID_TYPE}. public func getMaxElement() -> Int { if isNil() { return CommonToken.INVALID_TYPE @@ -462,12 +451,10 @@ public class IntervalSet: IntSet, Hashable, CustomStringConvertible { return last.b } - /** - * Returns the minimum value contained in the set. - * - * @return the minimum value contained in the set. If the set is empty, this - * method returns {@link org.antlr.v4.runtime.Token#INVALID_TYPE}. - */ + /// Returns the minimum value contained in the set. + /// + /// - returns: the minimum value contained in the set. If the set is empty, this + /// method returns {@link org.antlr.v4.runtime.Token#INVALID_TYPE}. public func getMinElement() -> Int { if isNil() { return CommonToken.INVALID_TYPE @@ -476,7 +463,7 @@ public class IntervalSet: IntSet, Hashable, CustomStringConvertible { return intervals[0].a } - /** Return a list of Interval objects. */ + /// Return a list of Interval objects. public func getIntervals() -> Array { return intervals } @@ -502,19 +489,17 @@ public class IntervalSet: IntSet, Hashable, CustomStringConvertible { hash = MurmurHash.finish(hash, intervals.count * 2) return hash } - /** Are two IntervalSets equal? Because all intervals are sorted - * and disjoint, equals is a simple linear walk over both lists - * to make sure they are the same. Interval.equals() is used - * by the List.equals() method to check the ranges. - */ + /// Are two IntervalSets equal? Because all intervals are sorted + /// and disjoint, equals is a simple linear walk over both lists + /// to make sure they are the same. Interval.equals() is used + /// by the List.equals() method to check the ranges. - /* public func equals(obj : AnyObject) -> Bool { - if ( obj==nil || !(obj is IntervalSet) ) { - return false; - } - var other : IntervalSet = obj as! IntervalSet; - return self.intervals.equals(other.intervals); - }*/ + /// public func equals(obj : AnyObject) -> Bool { + /// if ( obj==nil || !(obj is IntervalSet) ) { + /// return false; + /// } + /// var other : IntervalSet = obj as! IntervalSet; + /// return self.intervals.equals(other.intervals); public var description: String { return toString(false) @@ -570,9 +555,7 @@ public class IntervalSet: IntSet, Hashable, CustomStringConvertible { return buf.toString() } - /** - * @deprecated Use {@link #toString(org.antlr.v4.runtime.Vocabulary)} instead. - */ + /// - Use {@link #toString(org.antlr.v4.runtime.Vocabulary)} instead. ////@Deprecated public func toString(_ tokenNames: [String?]?) -> String { return toString(Vocabulary.fromTokenNames(tokenNames)) @@ -615,9 +598,7 @@ public class IntervalSet: IntSet, Hashable, CustomStringConvertible { return buf.toString() } - /** - * @deprecated Use {@link #elementName(org.antlr.v4.runtime.Vocabulary, int)} instead. - */ + /// - Use {@link #elementName(org.antlr.v4.runtime.Vocabulary, int)} instead. ////@Deprecated internal func elementName(_ tokenNames: [String?]?, _ a: Int) -> String { return elementName(Vocabulary.fromTokenNames(tokenNames), a) @@ -696,10 +677,9 @@ public class IntervalSet: IntSet, Hashable, CustomStringConvertible { return s } - /** Get the ith element of ordered set. Used only by RandomPhrase so - * don't bother to implement if you're not doing that for a new - * ANTLR code gen target. - */ + /// Get the ith element of ordered set. Used only by RandomPhrase so + /// don't bother to implement if you're not doing that for a new + /// ANTLR code gen target. public func get(_ i: Int) -> Int { let n: Int = intervals.count var index: Int = 0 diff --git a/runtime/Swift/Sources/Antlr4/misc/MultiMap.swift b/runtime/Swift/Sources/Antlr4/misc/MultiMap.swift index 28e6d9248..6e989dd5e 100644 --- a/runtime/Swift/Sources/Antlr4/misc/MultiMap.swift +++ b/runtime/Swift/Sources/Antlr4/misc/MultiMap.swift @@ -1,7 +1,6 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. public class MultiMap { diff --git a/runtime/Swift/Sources/Antlr4/misc/exception/ANTLRError.swift b/runtime/Swift/Sources/Antlr4/misc/exception/ANTLRError.swift index 8ddab6dba..29d2c3a0c 100644 --- a/runtime/Swift/Sources/Antlr4/misc/exception/ANTLRError.swift +++ b/runtime/Swift/Sources/Antlr4/misc/exception/ANTLRError.swift @@ -1,7 +1,6 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. // // ANTLRError.swift diff --git a/runtime/Swift/Sources/Antlr4/misc/exception/ANTLRException.swift b/runtime/Swift/Sources/Antlr4/misc/exception/ANTLRException.swift index 9400cb687..d7202d847 100644 --- a/runtime/Swift/Sources/Antlr4/misc/exception/ANTLRException.swift +++ b/runtime/Swift/Sources/Antlr4/misc/exception/ANTLRException.swift @@ -1,7 +1,6 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. // // ANTLRException.swift diff --git a/runtime/Swift/Sources/Antlr4/misc/extension/ArrayExtension.swift b/runtime/Swift/Sources/Antlr4/misc/extension/ArrayExtension.swift index 785d1289b..2c2fdfd6b 100644 --- a/runtime/Swift/Sources/Antlr4/misc/extension/ArrayExtension.swift +++ b/runtime/Swift/Sources/Antlr4/misc/extension/ArrayExtension.swift @@ -1,7 +1,6 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. import Foundation @@ -30,19 +29,15 @@ extension Array { } - /** - Removes the last element from self and returns it. - - :returns: The removed element - */ + /// Removes the last element from self and returns it. + /// + /// :returns: The removed element mutating func pop() -> Element { return removeLast() } - /** - Same as append. - - :param: newElement Element to append - */ + /// Same as append. + /// + /// :param: newElement Element to append mutating func push(_ newElement: Element) { return append(newElement) } @@ -58,12 +53,10 @@ extension Array { } - /** - Checks if test returns true for all the elements in self - - :param: test Function to call for each element - :returns: True if test returns true for all the elements in self - */ + /// Checks if test returns true for all the elements in self + /// + /// :param: test Function to call for each element + /// :returns: True if test returns true for all the elements in self func every(_ test: (Element) -> Bool) -> Bool { for item in self { if !test(item) { @@ -74,12 +67,10 @@ extension Array { return true } - /** - Checks if test returns true for any element of self. - - :param: test Function to call for each element - :returns: true if test returns true for any element of self - */ + /// Checks if test returns true for any element of self. + /// + /// :param: test Function to call for each element + /// :returns: true if test returns true for any element of self func any(_ test: (Element) -> Bool) -> Bool { for item in self { if test(item) { @@ -92,12 +83,11 @@ extension Array { - /* slice array - :param: index slice index - :param: isClose is close array - :param: first First array - :param: second Second array - */ + /// slice array + /// :param: index slice index + /// :param: isClose is close array + /// :param: first First array + /// :param: second Second array //func slice(startIndex startIndex:Int, endIndex:Int) -> Slice { func slice(startIndex: Int, endIndex: Int) -> ArraySlice { diff --git a/runtime/Swift/Sources/Antlr4/misc/extension/CharacterExtension.swift b/runtime/Swift/Sources/Antlr4/misc/extension/CharacterExtension.swift index bc47e21f8..5c5a2cdc1 100644 --- a/runtime/Swift/Sources/Antlr4/misc/extension/CharacterExtension.swift +++ b/runtime/Swift/Sources/Antlr4/misc/extension/CharacterExtension.swift @@ -1,7 +1,6 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. // // CharacterEextension.swift diff --git a/runtime/Swift/Sources/Antlr4/misc/extension/IntStreamExtension.swift b/runtime/Swift/Sources/Antlr4/misc/extension/IntStreamExtension.swift index 41eece9c0..b86ec93c3 100644 --- a/runtime/Swift/Sources/Antlr4/misc/extension/IntStreamExtension.swift +++ b/runtime/Swift/Sources/Antlr4/misc/extension/IntStreamExtension.swift @@ -1,7 +1,6 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. // // IntStreamExtension.swift @@ -14,18 +13,14 @@ import Foundation extension IntStream { - /** - * The value returned by {@link #LA LA()} when the end of the stream is - * reached. - */ + /// The value returned by {@link #LA LA()} when the end of the stream is + /// reached. public static var EOF: Int { return -1 } - /** - * The value returned by {@link #getSourceName} when the actual name of the - * underlying source is not known. - */ + /// The value returned by {@link #getSourceName} when the actual name of the + /// underlying source is not known. public static var UNKNOWN_SOURCE_NAME: String { return "" } diff --git a/runtime/Swift/Sources/Antlr4/misc/extension/NSUUIDExtension.swift b/runtime/Swift/Sources/Antlr4/misc/extension/NSUUIDExtension.swift index 34b417f18..d5a1dd44f 100644 --- a/runtime/Swift/Sources/Antlr4/misc/extension/NSUUIDExtension.swift +++ b/runtime/Swift/Sources/Antlr4/misc/extension/NSUUIDExtension.swift @@ -1,7 +1,6 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. // // NSUUIDExtension.swift diff --git a/runtime/Swift/Sources/Antlr4/misc/extension/StirngExtension.swift b/runtime/Swift/Sources/Antlr4/misc/extension/StirngExtension.swift index f8868189d..b628c7004 100644 --- a/runtime/Swift/Sources/Antlr4/misc/extension/StirngExtension.swift +++ b/runtime/Swift/Sources/Antlr4/misc/extension/StirngExtension.swift @@ -1,7 +1,6 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. //import Cocoa diff --git a/runtime/Swift/Sources/Antlr4/misc/extension/TokenExtension.swift b/runtime/Swift/Sources/Antlr4/misc/extension/TokenExtension.swift index 6056d588f..601af78f0 100644 --- a/runtime/Swift/Sources/Antlr4/misc/extension/TokenExtension.swift +++ b/runtime/Swift/Sources/Antlr4/misc/extension/TokenExtension.swift @@ -1,7 +1,6 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. // // TokenExtension.swift @@ -18,9 +17,8 @@ extension Token { return 0 } - /** During lookahead operations, this "token" signifies we hit rule end ATN state - * and did not follow it despite needing to. - */ + /// During lookahead operations, this "token" signifies we hit rule end ATN state + /// and did not follow it despite needing to. static public var EPSILON: Int { return -2 @@ -35,32 +33,28 @@ extension Token { return -1 } //IntStream.EOF - /** All tokens go to the parser (unless skip() is called in that rule) - * on a particular "channel". The parser tunes to a particular channel - * so that whitespace etc... can go to the parser on a "hidden" channel. - */ + /// All tokens go to the parser (unless skip() is called in that rule) + /// on a particular "channel". The parser tunes to a particular channel + /// so that whitespace etc... can go to the parser on a "hidden" channel. static public var DEFAULT_CHANNEL: Int { return 0 } - /** Anything on different channel than DEFAULT_CHANNEL is not parsed - * by parser. - */ + /// Anything on different channel than DEFAULT_CHANNEL is not parsed + /// by parser. static public var HIDDEN_CHANNEL: Int { return 1 } - /** - * This is the minimum constant value which can be assigned to a - * user-defined token channel. - * - *

          - * The non-negative numbers less than {@link #MIN_USER_CHANNEL_VALUE} are - * assigned to the predefined channels {@link #DEFAULT_CHANNEL} and - * {@link #HIDDEN_CHANNEL}.

          - * - * @see org.antlr.v4.runtime.Token#getChannel() - */ + /// This is the minimum constant value which can be assigned to a + /// user-defined token channel. + /// + ///

          + /// The non-negative numbers less than {@link #MIN_USER_CHANNEL_VALUE} are + /// assigned to the predefined channels {@link #DEFAULT_CHANNEL} and + /// {@link #HIDDEN_CHANNEL}.

          + /// + /// - seealso: org.antlr.v4.runtime.Token#getChannel() static public var MIN_USER_CHANNEL_VALUE: Int { return 2 diff --git a/runtime/Swift/Tests/Antlr4Tests/Antlr4Tests.swift b/runtime/Swift/Tests/Antlr4Tests/Antlr4Tests.swift index c46975204..ad3db025c 100644 --- a/runtime/Swift/Tests/Antlr4Tests/Antlr4Tests.swift +++ b/runtime/Swift/Tests/Antlr4Tests/Antlr4Tests.swift @@ -1,7 +1,6 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ +/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +/// 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. // // Antlr4Tests.swift diff --git a/runtime/Swift/Tests/Antlr4Tests/BaseTest.swift b/runtime/Swift/Tests/Antlr4Tests/BaseTest.swift deleted file mode 100644 index 507da7ba6..000000000 --- a/runtime/Swift/Tests/Antlr4Tests/BaseTest.swift +++ /dev/null @@ -1,40 +0,0 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ - -// -// BaseTest.swift -// Antlr4 -// -// Created by janyou on 15/10/13. -// - -import XCTest -@testable import Antlr4 - -class BaseTest: XCTestCase { - - override func setUp() { - super.setUp() - // Put setup code here. This method is called before the invocation of each test method in the class. - } - - override func tearDown() { - // Put teardown code here. This method is called after the invocation of each test method in the class. - super.tearDown() - } - - func testExample() { - // This is an example of a functional test case. - // Use XCTAssert and related functions to verify your tests produce the correct results. - } - - func testPerformanceExample() { - // This is an example of a performance test case. - self.measure { - // Put the code you want to measure the time of here. - } - } - -} diff --git a/runtime/Swift/Tests/Antlr4Tests/HashMapTest.swift b/runtime/Swift/Tests/Antlr4Tests/HashMapTest.swift deleted file mode 100644 index 77c4ccaf8..000000000 --- a/runtime/Swift/Tests/Antlr4Tests/HashMapTest.swift +++ /dev/null @@ -1,68 +0,0 @@ -/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. - * 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. - */ - -// -// HashMapTest.swift -// Antlr4 -// -// Created by janyou on 16/4/8. -// - -import XCTest -import Antlr4 -class HashMapTest: XCTestCase { - - override func setUp() { - super.setUp() - // Put setup code here. This method is called before the invocation of each test method in the class. - } - - override func tearDown() { - // Put teardown code here. This method is called after the invocation of each test method in the class. - super.tearDown() - } - - func testExample() { - let map = HashMap() - map["a"] = 1 - map["b"] = 2 - XCTAssert(map["a"] == 1) - XCTAssert(map["b"] == 2) - - for (k,v) in map { - print("\(k) : \(v)") - } - for k in map.keys { - print("key:\(k) ") - } - for v in map.values { - print("value:\(v) ") - } - print("isEmpty:\(map.isEmpty) ") - XCTAssert(map.isEmpty == false) - print("\(map)") - - map.remove("a") - print("\(map.count)") - - map["b"] = nil - - print("\(map.count)") - for (k,v) in map { - print("\(k) : \(v)") - } - - // This is an example of a functional test case. - // Use XCTAssert and related functions to verify your tests produce the correct results. - } - - func testPerformanceExample() { - // This is an example of a performance test case. - self.measure { - // Put the code you want to measure the time of here. - } - } - -}