From 7dc17ace6e1624ba08e3e2e322b60aa6617f5666 Mon Sep 17 00:00:00 2001
From: Ivan Kochurkin cannot find tokens file filename rule reference rule is not currently supported in a set
+// You can insert stuff, replace, and delete chunks. Note that the operations +// are done lazily--only if you convert the buffer to a {@link String} with +// {@link TokenStream#getText()}. This is very efficient because you are not +// moving data around all the time. As the buffer of tokens is converted to +// strings, the {@link #getText()} method(s) scan the input token stream and +// check to see if there is an operation at the current index. If so, the +// operation is done and then normal {@link String} rendering continues on the +// buffer. This is like having multiple Turing machine instruction streams +// (programs) operating on a single input tape. :)
+// +//+// This rewriter makes no modifications to the token stream. It does not ask the +// stream to fill itself up nor does it advance the input cursor. The token +// stream {@link TokenStream#index()} will return the same value before and +// after any {@link #getText()} call.
+// +//+// The rewriter only works on tokens that you have in the buffer and ignores the +// current input cursor. If you are buffering tokens on-demand, calling +// {@link #getText()} halfway through the input will only do rewrites for those +// tokens in the first half of the file.
+// +//+// Since the operations are done lazily at {@link #getText}-time, operations do +// not screw up the token index values. That is, an insert operation at token +// index {@code i} does not change the index values for tokens +// {@code i}+1..n-1.
+// +//+// Because operations never actually alter the buffer, you may always get the +// original token stream back without undoing anything. Since the instructions +// are queued up, you can easily simulate transactions and roll back any changes +// if there is an error just by removing instructions. For example,
+// +//+// CharStream input = new ANTLRFileStream("input"); +// TLexer lex = new TLexer(input); +// CommonTokenStream tokens = new CommonTokenStream(lex); +// T parser = new T(tokens); +// TokenStreamRewriter rewriter = new TokenStreamRewriter(tokens); +// parser.startRule(); +//+// +//
+// Then in the rules, you can execute (assuming rewriter is visible):
+// +//+// Token t,u; +// ... +// rewriter.insertAfter(t, "text to put after t");} +// rewriter.insertAfter(u, "text after u");} +// System.out.println(rewriter.getText()); +//+// +//
+// You can also have multiple "instruction streams" and get multiple rewrites +// from a single pass over the input. Just name the instruction streams and use +// that name again when printing the buffer. This could be useful for generating +// a C file and also its header file--all from the same buffer:
+// +//+// rewriter.insertAfter("pass1", t, "text to put after t");} +// rewriter.insertAfter("pass2", u, "text after u");} +// System.out.println(rewriter.getText("pass1")); +// System.out.println(rewriter.getText("pass2")); +//+// +//
+// If you don't use named rewrite streams, a "default" stream is used as the +// first example shows.
+// /augmentation or other manipulations on it. +// +//+// You can insert stuff, replace, and delete chunks. Note that the operations +// are done lazily--only if you convert the buffer to a {@link String} with +// {@link TokenStream#getText()}. This is very efficient because you are not +// moving data around all the time. As the buffer of tokens is converted to +// strings, the {@link #getText()} method(s) scan the input token stream and +// check to see if there is an operation at the current index. If so, the +// operation is done and then normal {@link String} rendering continues on the +// buffer. This is like having multiple Turing machine instruction streams +// (programs) operating on a single input tape. :)
+// +//+// This rewriter makes no modifications to the token stream. It does not ask the +// stream to fill itself up nor does it advance the input cursor. The token +// stream {@link TokenStream#index()} will return the same value before and +// after any {@link #getText()} call.
+// +//+// The rewriter only works on tokens that you have in the buffer and ignores the +// current input cursor. If you are buffering tokens on-demand, calling +// {@link #getText()} halfway through the input will only do rewrites for those +// tokens in the first half of the file.
+// +//+// Since the operations are done lazily at {@link #getText}-time, operations do +// not screw up the token index values. That is, an insert operation at token +// index {@code i} does not change the index values for tokens +// {@code i}+1..n-1.
+// +//+// Because operations never actually alter the buffer, you may always get the +// original token stream back without undoing anything. Since the instructions +// are queued up, you can easily simulate transactions and roll back any changes +// if there is an error just by removing instructions. For example,
+// +//+// CharStream input = new ANTLRFileStream("input"); +// TLexer lex = new TLexer(input); +// CommonTokenStream tokens = new CommonTokenStream(lex); +// T parser = new T(tokens); +// TokenStreamRewriter rewriter = new TokenStreamRewriter(tokens); +// parser.startRule(); +//+// +//
+// Then in the rules, you can execute (assuming rewriter is visible):
+// +//+// Token t,u; +// ... +// rewriter.insertAfter(t, "text to put after t");} +// rewriter.insertAfter(u, "text after u");} +// System.out.println(rewriter.getText()); +//+// +//
+// You can also have multiple "instruction streams" and get multiple rewrites +// from a single pass over the input. Just name the instruction streams and use +// that name again when printing the buffer. This could be useful for generating +// a C file and also its header file--all from the same buffer:
+// +//+// rewriter.insertAfter("pass1", t, "text to put after t");} +// rewriter.insertAfter("pass2", u, "text after u");} +// System.out.println(rewriter.getText("pass1")); +// System.out.println(rewriter.getText("pass2")); +//+// +//
+// If you don't use named rewrite streams, a "default" stream is used as the +// first example shows.
+// + +const( + Default_Program_Name = "default" + Program_Init_Size = 100 + Min_Token_Index = 0 +) + +// Define the rewrite operation hierarchy + +type RewriteOperation interface { + // Execute the rewrite operation by possibly adding to the buffer. + // Return the index of the next token to operate on. + Execute(buffer *bytes.Buffer) int + String() string + GetInstructionIndex() int + GetIndex() int + GetText() string + GetOpName() string + GetTokens() TokenStream + SetInstructionIndex(val int) + SetIndex(int) + SetText(string) + SetOpName(string) + SetTokens(TokenStream) +} + +type BaseRewriteOperation struct { + //Current index of rewrites list + instruction_index int + //Token buffer index + index int + //Substitution text + text string + //Actual operation name + op_name string + //Pointer to token steam + tokens TokenStream +} + +func (op *BaseRewriteOperation)GetInstructionIndex() int{ + return op.instruction_index +} + +func (op *BaseRewriteOperation)GetIndex() int{ + return op.index +} + +func (op *BaseRewriteOperation)GetText() string{ + return op.text +} + +func (op *BaseRewriteOperation)GetOpName() string{ + return op.op_name +} + +func (op *BaseRewriteOperation)GetTokens() TokenStream{ + return op.tokens +} + +func (op *BaseRewriteOperation)SetInstructionIndex(val int){ + op.instruction_index = val +} + +func (op *BaseRewriteOperation)SetIndex(val int) { + op.index = val +} + +func (op *BaseRewriteOperation)SetText(val string){ + op.text = val +} + +func (op *BaseRewriteOperation)SetOpName(val string){ + op.op_name = val +} + +func (op *BaseRewriteOperation)SetTokens(val TokenStream) { + op.tokens = val +} + + +func (op *BaseRewriteOperation) Execute(buffer *bytes.Buffer) int{ + return op.index +} + +func (op *BaseRewriteOperation) String() string { + return fmt.Sprintf("<%s@%d:\"%s\">", + op.op_name, + op.tokens.Get(op.GetIndex()), + op.text, + ) + +} + + +type InsertBeforeOp struct { + BaseRewriteOperation +} + +func NewInsertBeforeOp(index int, text string, stream TokenStream) *InsertBeforeOp{ + return &InsertBeforeOp{BaseRewriteOperation:BaseRewriteOperation{ + index:index, + text:text, + op_name:"InsertBeforeOp", + tokens:stream, + }} +} + +func (op *InsertBeforeOp) Execute(buffer *bytes.Buffer) int{ + buffer.WriteString(op.text) + if op.tokens.Get(op.index).GetTokenType() != TokenEOF{ + buffer.WriteString(op.tokens.Get(op.index).GetText()) + } + return op.index+1 +} + +func (op *InsertBeforeOp) String() string { + return op.BaseRewriteOperation.String() +} + +// Distinguish between insert after/before to do the "insert afters" +// first and then the "insert befores" at same index. Implementation +// of "insert after" is "insert before index+1". + +type InsertAfterOp struct { + BaseRewriteOperation +} + +func NewInsertAfterOp(index int, text string, stream TokenStream) *InsertAfterOp{ + return &InsertAfterOp{BaseRewriteOperation:BaseRewriteOperation{ + index:index+1, + text:text, + tokens:stream, + }} +} + +func (op *InsertAfterOp) Execute(buffer *bytes.Buffer) int { + buffer.WriteString(op.text) + if op.tokens.Get(op.index).GetTokenType() != TokenEOF{ + buffer.WriteString(op.tokens.Get(op.index).GetText()) + } + return op.index+1 +} + +func (op *InsertAfterOp) String() string { + return op.BaseRewriteOperation.String() +} + +// I'm going to try replacing range from x..y with (y-x)+1 ReplaceOp +// instructions. +type ReplaceOp struct{ + BaseRewriteOperation + LastIndex int +} + +func NewReplaceOp(from, to int, text string, stream TokenStream)*ReplaceOp { + return &ReplaceOp{ + BaseRewriteOperation:BaseRewriteOperation{ + index:from, + text:text, + op_name:"ReplaceOp", + tokens:stream, + }, + LastIndex:to, + } +} + +func (op *ReplaceOp)Execute(buffer *bytes.Buffer) int{ + if op.text != ""{ + buffer.WriteString(op.text) + } + return op.LastIndex +1 +} + +func (op *ReplaceOp) String() string { + if op.text == "" { + return fmt.Sprintf("a
a", "DistinguishBetweenInsertAfterAndInsertBeforeToPreserverOrder2", + func(r *TokenStreamRewriter){ + r.InsertBeforeDefault(0, "") + r.InsertBeforeDefault(0, "") + r.InsertAfterDefault(0, "
") + r.InsertAfterDefault(0, "") + r.InsertBeforeDefault(1, "") + r.InsertAfterDefault(1,"") + }), + NewLexerTest("ab", "a
")
+ r.InsertBeforeDefault(0, "")
+ r.InsertBeforeDefault(0, "
// You can insert stuff, replace, and delete chunks. Note that the operations // are done lazily--only if you convert the buffer to a {@link String} with @@ -24,31 +23,31 @@ import ( // operation is done and then normal {@link String} rendering continues on the // buffer. This is like having multiple Turing machine instruction streams // (programs) operating on a single input tape. :)
-// //+ // This rewriter makes no modifications to the token stream. It does not ask the // stream to fill itself up nor does it advance the input cursor. The token // stream {@link TokenStream#index()} will return the same value before and // after any {@link #getText()} call.
-// + //// The rewriter only works on tokens that you have in the buffer and ignores the // current input cursor. If you are buffering tokens on-demand, calling // {@link #getText()} halfway through the input will only do rewrites for those // tokens in the first half of the file.
-// + //// Since the operations are done lazily at {@link #getText}-time, operations do // not screw up the token index values. That is, an insert operation at token // index {@code i} does not change the index values for tokens // {@code i}+1..n-1.
-// + //// Because operations never actually alter the buffer, you may always get the // original token stream back without undoing anything. Since the instructions // are queued up, you can easily simulate transactions and roll back any changes // if there is an error just by removing instructions. For example,
-// + //// CharStream input = new ANTLRFileStream("input"); // TLexer lex = new TLexer(input); @@ -57,10 +56,10 @@ import ( // TokenStreamRewriter rewriter = new TokenStreamRewriter(tokens); // parser.startRule(); //-// + //
// Then in the rules, you can execute (assuming rewriter is visible):
-// + //// Token t,u; // ... @@ -68,97 +67,25 @@ import ( // rewriter.insertAfter(u, "text after u");} // System.out.println(rewriter.getText()); //-// + //
// You can also have multiple "instruction streams" and get multiple rewrites // from a single pass over the input. Just name the instruction streams and use // that name again when printing the buffer. This could be useful for generating // a C file and also its header file--all from the same buffer:
-// + //// rewriter.insertAfter("pass1", t, "text to put after t");} // rewriter.insertAfter("pass2", u, "text after u");} // System.out.println(rewriter.getText("pass1")); // System.out.println(rewriter.getText("pass2")); //-// + //
// If you don't use named rewrite streams, a "default" stream is used as the // first example shows.
-// /augmentation or other manipulations on it. -// -//-// You can insert stuff, replace, and delete chunks. Note that the operations -// are done lazily--only if you convert the buffer to a {@link String} with -// {@link TokenStream#getText()}. This is very efficient because you are not -// moving data around all the time. As the buffer of tokens is converted to -// strings, the {@link #getText()} method(s) scan the input token stream and -// check to see if there is an operation at the current index. If so, the -// operation is done and then normal {@link String} rendering continues on the -// buffer. This is like having multiple Turing machine instruction streams -// (programs) operating on a single input tape. :)
-// -//-// This rewriter makes no modifications to the token stream. It does not ask the -// stream to fill itself up nor does it advance the input cursor. The token -// stream {@link TokenStream#index()} will return the same value before and -// after any {@link #getText()} call.
-// -//-// The rewriter only works on tokens that you have in the buffer and ignores the -// current input cursor. If you are buffering tokens on-demand, calling -// {@link #getText()} halfway through the input will only do rewrites for those -// tokens in the first half of the file.
-// -//-// Since the operations are done lazily at {@link #getText}-time, operations do -// not screw up the token index values. That is, an insert operation at token -// index {@code i} does not change the index values for tokens -// {@code i}+1..n-1.
-// -//-// Because operations never actually alter the buffer, you may always get the -// original token stream back without undoing anything. Since the instructions -// are queued up, you can easily simulate transactions and roll back any changes -// if there is an error just by removing instructions. For example,
-// -//-// CharStream input = new ANTLRFileStream("input"); -// TLexer lex = new TLexer(input); -// CommonTokenStream tokens = new CommonTokenStream(lex); -// T parser = new T(tokens); -// TokenStreamRewriter rewriter = new TokenStreamRewriter(tokens); -// parser.startRule(); -//-// -//
-// Then in the rules, you can execute (assuming rewriter is visible):
-// -//-// Token t,u; -// ... -// rewriter.insertAfter(t, "text to put after t");} -// rewriter.insertAfter(u, "text after u");} -// System.out.println(rewriter.getText()); -//-// -//
-// You can also have multiple "instruction streams" and get multiple rewrites -// from a single pass over the input. Just name the instruction streams and use -// that name again when printing the buffer. This could be useful for generating -// a C file and also its header file--all from the same buffer:
-// -//-// rewriter.insertAfter("pass1", t, "text to put after t");} -// rewriter.insertAfter("pass2", u, "text after u");} -// System.out.println(rewriter.getText("pass1")); -// System.out.println(rewriter.getText("pass2")); -//-// -//
-// If you don't use named rewrite streams, a "default" stream is used as the -// first example shows.
-// + + const( Default_Program_Name = "default" @@ -172,12 +99,12 @@ type RewriteOperation interface { // Execute the rewrite operation by possibly adding to the buffer. // Return the index of the next token to operate on. Execute(buffer *bytes.Buffer) int - String() string - GetInstructionIndex() int - GetIndex() int - GetText() string - GetOpName() string - GetTokens() TokenStream + String() string + GetInstructionIndex() int + GetIndex() int + GetText() string + GetOpName() string + GetTokens() TokenStream SetInstructionIndex(val int) SetIndex(int) SetText(string) @@ -187,7 +114,7 @@ type RewriteOperation interface { type BaseRewriteOperation struct { //Current index of rewrites list - instruction_index int + instruction_index int //Token buffer index index int //Substitution text From dced604c7cfe337a6370b83e3bd25a8f173a1b00 Mon Sep 17 00:00:00 2001 From: Arshinskiy MikeThe {@link org.antlr.v4.runtime.RecognitionException} is non-null for all syntax errors except + ///
The {@link 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).
@@ -40,7 +40,7 @@ public protocol ANTLRErrorListener: class { _ line: Int, _ charPositionInLine: Int, _ msg: String, - _ e: AnyObject?// RecognitionException? + _ e: AnyObject? ) /// This method is called by the parser when a full-context prediction diff --git a/runtime/Swift/Sources/Antlr4/ANTLRErrorStrategy.swift b/runtime/Swift/Sources/Antlr4/ANTLRErrorStrategy.swift index 541a2a3b4..3ee9ce972 100644 --- a/runtime/Swift/Sources/Antlr4/ANTLRErrorStrategy.swift +++ b/runtime/Swift/Sources/Antlr4/ANTLRErrorStrategy.swift @@ -36,10 +36,10 @@ public protocol ANTLRErrorStrategy { /// 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 + /// - throws: _RecognitionException_ if the error strategy was not able to /// recover from the unexpected input symbol @discardableResult - func recoverInline(_ recognizer: Parser) throws -> Token // RecognitionException; + func recoverInline(_ recognizer: Parser) throws -> Token /// This method is called to recover from exception {@code e}. This method is /// called after {@link #reportError} by the default exception handler @@ -49,9 +49,9 @@ public protocol ANTLRErrorStrategy { /// /// - 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 + /// - throws: _RecognitionException_ if the error strategy could not recover from /// the recognition exception - func recover(_ recognizer: Parser, _ e: AnyObject) throws // RecognitionException; + func recover(_ recognizer: Parser, _ e: AnyObject) throws /// This method provides the error handler with an opportunity to handle /// syntactic or semantic errors in the input stream before they result in a @@ -67,10 +67,10 @@ public protocol ANTLRErrorStrategy { /// - 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 + /// - throws: _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; + func sync(_ recognizer: Parser) throws /// Tests whether or not recognizer} is in the process of recovering /// from an error. In error recovery mode, {@link org.antlr.v4.runtime.Parser#consume} adds diff --git a/runtime/Swift/Sources/Antlr4/ANTLRFileStream.swift b/runtime/Swift/Sources/Antlr4/ANTLRFileStream.swift index 053b6348d..96623d1d2 100644 --- a/runtime/Swift/Sources/Antlr4/ANTLRFileStream.swift +++ b/runtime/Swift/Sources/Antlr4/ANTLRFileStream.swift @@ -10,7 +10,6 @@ public class ANTLRFileStream: ANTLRInputStream { internal var fileName: String public convenience override init(_ fileName: String) { - // throws; IOException self.init(fileName, nil) } diff --git a/runtime/Swift/Sources/Antlr4/ANTLRInputStream.swift b/runtime/Swift/Sources/Antlr4/ANTLRInputStream.swift index 3b73981fd..f57902d74 100644 --- a/runtime/Swift/Sources/Antlr4/ANTLRInputStream.swift +++ b/runtime/Swift/Sources/Antlr4/ANTLRInputStream.swift @@ -39,76 +39,11 @@ public class ANTLRInputStream: CharStream { 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 func reset() { p = 0 } - public func consume() throws { if p >= n { assert(LA(1) == ANTLRInputStream.EOF, "Expected: LA(1)==IntStream.EOF") @@ -124,7 +59,6 @@ public class ANTLRInputStream: CharStream { } } - public func LA(_ i: Int) -> Int { var i = i if i == 0 { @@ -186,7 +120,6 @@ public class ANTLRInputStream: CharStream { } } - public func getText(_ interval: Interval) -> String { let start: Int = interval.a var stop: Int = interval.b @@ -201,7 +134,6 @@ public class ANTLRInputStream: CharStream { return String(data[start ..< (start + count)]) } - public func getSourceName() -> String { guard let name = name , !name.isEmpty else { return ANTLRInputStream.UNKNOWN_SOURCE_NAME @@ -209,7 +141,6 @@ public class ANTLRInputStream: CharStream { return name } - public func toString() -> String { return String(data) } diff --git a/runtime/Swift/Sources/Antlr4/BaseErrorListener.swift b/runtime/Swift/Sources/Antlr4/BaseErrorListener.swift index 5a4292c4e..725fd01a6 100644 --- a/runtime/Swift/Sources/Antlr4/BaseErrorListener.swift +++ b/runtime/Swift/Sources/Antlr4/BaseErrorListener.swift @@ -18,7 +18,7 @@ open class BaseErrorListener: ANTLRErrorListener { _ line: Int, _ charPositionInLine: Int, _ msg: String, - _ e: AnyObject?//RecognitionException + _ e: AnyObject? ) { } diff --git a/runtime/Swift/Sources/Antlr4/BufferedTokenStream.swift b/runtime/Swift/Sources/Antlr4/BufferedTokenStream.swift index 8ea114821..abc010c72 100644 --- a/runtime/Swift/Sources/Antlr4/BufferedTokenStream.swift +++ b/runtime/Swift/Sources/Antlr4/BufferedTokenStream.swift @@ -69,7 +69,6 @@ public class BufferedTokenStream: TokenStream { return 0 } - public func release(_ marker: Int) { // no resources to release } @@ -108,8 +107,6 @@ public class BufferedTokenStream: TokenStream { if try !skipEofCheck && LA(1) == BufferedTokenStream.EOF { throw ANTLRError.illegalState(msg: "cannot consume EOF") - //RuntimeException("cannot consume EOF") - //throw ANTLRError.IllegalState /* throw IllegalStateException("cannot consume EOF"); */ } if try sync(p + 1) { @@ -159,7 +156,6 @@ public class BufferedTokenStream: TokenStream { return n } - public func get(_ i: Int) throws -> Token { if i < 0 || i >= tokens.count { let index = tokens.count - 1 @@ -394,8 +390,6 @@ public class BufferedTokenStream: TokenStream { try lazyInit() if tokenIndex < 0 || tokenIndex >= tokens.count { throw ANTLRError.indexOutOfBounds(msg: "\(tokenIndex) not in 0..\(tokens.count - 1)") - //RuntimeException("\(tokenIndex) not in 0..\(tokens.count-1)") - //throw ANTLRError.IndexOutOfBounds /* throw IndexOutOfBoundsException(tokenIndex+" not in 0.."+(tokens.count-1)); */ } if tokenIndex == 0 { @@ -447,13 +441,10 @@ public class BufferedTokenStream: TokenStream { } /// Get the text of all tokens in this buffer. - - public func getText() throws -> String { return try getText(Interval.of(0, size() - 1)) } - public func getText(_ interval: Interval) throws -> String { let start: Int = interval.a var stop: Int = interval.b diff --git a/runtime/Swift/Sources/Antlr4/CharStream.swift b/runtime/Swift/Sources/Antlr4/CharStream.swift index c4895112e..fa63600ed 100644 --- a/runtime/Swift/Sources/Antlr4/CharStream.swift +++ b/runtime/Swift/Sources/Antlr4/CharStream.swift @@ -14,11 +14,11 @@ public protocol CharStream: IntStream { /// - 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 + /// - throws: _ANTLRError.nullPointer_ if {@code interval} is {@code null} + /// - throws: _ANTLRError.illegalArgument_ 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 + /// - throws: _ANTLRError.unsupportedOperation_ 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/DefaultErrorStrategy.swift b/runtime/Swift/Sources/Antlr4/DefaultErrorStrategy.swift index a7221b8dc..50303b2de 100644 --- a/runtime/Swift/Sources/Antlr4/DefaultErrorStrategy.swift +++ b/runtime/Swift/Sources/Antlr4/DefaultErrorStrategy.swift @@ -2,8 +2,6 @@ /// Use 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. @@ -26,11 +24,8 @@ public class DefaultErrorStrategy: ANTLRErrorStrategy { internal var lastErrorStates: IntervalSet? - /// {@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) } @@ -43,8 +38,6 @@ public class DefaultErrorStrategy: ANTLRErrorStrategy { errorRecoveryMode = true } - /// {@inheritDoc} - public func inErrorRecoveryMode(_ recognizer: Parser) -> Bool { return errorRecoveryMode } @@ -59,15 +52,11 @@ public class DefaultErrorStrategy: ANTLRErrorStrategy { lastErrorIndex = -1 } - /// {@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} @@ -84,7 +73,6 @@ public class DefaultErrorStrategy: ANTLRErrorStrategy { ///
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()+ // " index="+getTokenStream(recognizer).index()+ @@ -507,7 +491,6 @@ public class DefaultErrorStrategy: ANTLRErrorStrategy { /// 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 } diff --git a/runtime/Swift/Sources/Antlr4/IntStream.swift b/runtime/Swift/Sources/Antlr4/IntStream.swift index 69af63969..8e7fde515 100644 --- a/runtime/Swift/Sources/Antlr4/IntStream.swift +++ b/runtime/Swift/Sources/Antlr4/IntStream.swift @@ -45,7 +45,7 @@ public protocol IntStream: class { /// 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 + /// - throws: _ANTLRError.illegalState_ 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 @@ -80,7 +80,7 @@ public protocol IntStream: class { /// calls to {@link #consume consume()} have occurred from the beginning of /// the stream before calling this method. /// - /// - UnsupportedOperationException if the stream does not support + /// - throws: _ANTLRError.unsupportedOperation_ if the stream does not support /// retrieving the value of the specified symbol func LA(_ i: Int) throws -> Int @@ -173,21 +173,20 @@ public protocol IntStream: class { /// /// - parameter index: The absolute index to seek to. /// - /// - IllegalArgumentException if {@code index} is less than 0 - /// - UnsupportedOperationException if the stream does not support + /// - throws: _ANTLRError.illegalArgument_ if {@code index} is less than 0 + /// - throws: _ANTLRError.unsupportedOperation_ if the stream does not support /// seeking to the specified index func seek(_ index: Int) throws /// Returns the total number of symbols in the stream, including a single EOF /// symbol. /// - /// - UnsupportedOperationException if the size of the stream is + /// - throws: _ANTLRError.unsupportedOperation_ if the size of the stream is /// unknown. func size() -> Int /// Gets the name of the underlying symbol source. This method returns a /// non-null, non-empty string. If such a name is not known, this method /// returns {@link #UNKNOWN_SOURCE_NAME}. - func getSourceName() -> String } diff --git a/runtime/Swift/Sources/Antlr4/Lexer.swift b/runtime/Swift/Sources/Antlr4/Lexer.swift index 9c251ba66..2af2140fe 100644 --- a/runtime/Swift/Sources/Antlr4/Lexer.swift +++ b/runtime/Swift/Sources/Antlr4/Lexer.swift @@ -384,9 +384,6 @@ open class Lexer: RecognizerUnless otherwise noted, passing a null parameter to any of the /// methods in a {@code BitSet} will result in a -/// {@code NullPointerException}. +/// {@code ANTLRError.nullPointer}. /// ///
A {@code BitSet} is not safe for multithreaded use without
/// external synchronization.
///
-/// - Arthur van Hoff
-/// - Michael McCloskey
-/// - Martin Buchholz
-/// - JDK1.0
+/// - note: Arthur van Hoff
+/// - note: Michael McCloskey
+/// - note: Martin Buchholz
+/// - note: JDK1.0
public class BitSet: Hashable, CustomStringConvertible {
/// BitSets are packed into arrays of "words." Currently a word is
@@ -119,7 +119,7 @@ public class BitSet: Hashable, CustomStringConvertible {
/// {@code nbits-1}. All bits are initially {@code false}.
///
/// - parameter nbits: the initial size of the bit set
- /// - NegativeArraySizeException if the specified initial size
+ /// - throws: _ANTLRError.negativeArraySize_ if the specified initial size
/// is negative
public init(_ nbits: Int) throws {
// nbits can't be negative; size 0 is OK
@@ -158,7 +158,6 @@ public class BitSet: Hashable, CustomStringConvertible {
///
/// - 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)
}
@@ -214,8 +213,7 @@ public class BitSet: Hashable, CustomStringConvertible {
/// current value.
///
/// - parameter bitIndex: the index of the bit to flip
- /// - IndexOutOfBoundsException if the specified index is negative
- /// - 1.4
+ /// - throws: _ANTLRError.IndexOutOfBounds_ if the specified index is negative
public func flip(_ bitIndex: Int) throws {
if bitIndex < 0 {
throw ANTLRError.indexOutOfBounds(msg: "bitIndex < 0: \(bitIndex)")
@@ -237,10 +235,9 @@ public class BitSet: Hashable, CustomStringConvertible {
///
/// - parameter fromIndex: index of the first bit to flip
/// - parameter toIndex: index after the last bit to flip
- /// - IndexOutOfBoundsException if {@code fromIndex} is negative,
+ /// - throws: _ANTLRError.IndexOutOfBounds_ 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)
@@ -280,8 +277,7 @@ public class BitSet: Hashable, CustomStringConvertible {
/// Sets the bit at the specified index to {@code true}.
///
/// - parameter bitIndex: a bit index
- /// - IndexOutOfBoundsException if the specified index is negative
- /// - JDK1.0
+ /// - throws: _ANTLRError.IndexOutOfBounds_ if the specified index is negative
public func set(_ bitIndex: Int) throws {
if bitIndex < 0 {
throw ANTLRError.indexOutOfBounds(msg: "bitIndex < 0: \(bitIndex)")
@@ -300,8 +296,7 @@ public class BitSet: Hashable, CustomStringConvertible {
///
/// - parameter bitIndex: a bit index
/// - parameter value: a boolean value to set
- /// - IndexOutOfBoundsException if the specified index is negative
- /// - 1.4
+ /// - throws: _ANTLRError.IndexOutOfBounds_ if the specified index is negative
public func set(_ bitIndex: Int, _ value: Bool) throws {
if value {
try set(bitIndex)
@@ -315,10 +310,9 @@ public class BitSet: Hashable, CustomStringConvertible {
///
/// - 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,
+ /// - throws: _ANTLRError.IndexOutOfBounds_ 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)
@@ -361,10 +355,9 @@ public class BitSet: Hashable, CustomStringConvertible {
/// - 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,
+ /// - throws: _ANTLRError.IndexOutOfBounds_ 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)
@@ -376,7 +369,7 @@ public class BitSet: Hashable, CustomStringConvertible {
/// 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
+ /// - throws: _ANTLRError.IndexOutOfBounds_ if the specified index is negative
/// - JDK1.0
public func clear(_ bitIndex: Int) throws {
if bitIndex < 0 {
@@ -398,10 +391,9 @@ public class BitSet: Hashable, CustomStringConvertible {
///
/// - 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,
+ /// - throws: _ANTLRError.IndexOutOfBounds_ 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)
@@ -447,8 +439,6 @@ public class BitSet: Hashable, CustomStringConvertible {
}
/// Sets all of the bits in this BitSet to {@code false}.
- ///
- /// - 1.4
public func clear() {
while wordsInUse > 0 {
wordsInUse -= 1
@@ -463,7 +453,7 @@ public class BitSet: Hashable, CustomStringConvertible {
///
/// - parameter bitIndex: the bit index
/// - returns: the value of the bit with the specified index
- /// - IndexOutOfBoundsException if the specified index is negative
+ /// - throws: _ANTLRError.IndexOutOfBounds_ if the specified index is negative
public func get(_ bitIndex: Int) throws -> Bool {
if bitIndex < 0 {
throw ANTLRError.indexOutOfBounds(msg: "bitIndex < 0: \(bitIndex)")
@@ -483,10 +473,9 @@ public class BitSet: Hashable, CustomStringConvertible {
/// - 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,
+ /// - throws: _ANTLRError.IndexOutOfBounds_ 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)
@@ -562,8 +551,7 @@ public class BitSet: Hashable, CustomStringConvertible {
/// - 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
+ /// - throws: _ANTLRError.IndexOutOfBounds_ if the specified index is negative
public func nextSetBit(_ fromIndex: Int) throws -> Int {
if fromIndex < 0 {
throw ANTLRError.indexOutOfBounds(msg: "fromIndex < 0: \(fromIndex)")
@@ -634,8 +622,7 @@ public class BitSet: Hashable, CustomStringConvertible {
///
/// - 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
+ /// - throws: _ANTLRError.IndexOutOfBounds if the specified index is negative
public func nextClearBit(_ fromIndex: Int) throws -> Int {
// Neither spec nor implementation handle bitsets of maximal length.
// See 4816253.
@@ -681,9 +668,9 @@ public class BitSet: Hashable, CustomStringConvertible {
/// - 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
+ /// - throws: _ANTLRError.IndexOutOfBounds if the specified index is less
/// than {@code -1}
- /// - 1.7
+ /// - note: 1.7
public func previousSetBit(_ fromIndex: Int) throws -> Int {
if fromIndex < 0 {
if fromIndex == -1 {
@@ -721,9 +708,9 @@ public class BitSet: Hashable, CustomStringConvertible {
/// - 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
+ /// - throws: _ANTLRError.IndexOutOfBounds if the specified index is less
/// than {@code -1}
- /// - 1.7
+ /// - note: 1.7
public func previousClearBit(_ fromIndex: Int) throws -> Int {
if fromIndex < 0 {
if fromIndex == -1 {
@@ -791,7 +778,6 @@ public class BitSet: Hashable, CustomStringConvertible {
/// 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
@@ -805,7 +791,6 @@ public class BitSet: Hashable, CustomStringConvertible {
/// to {@code true}.
///
/// - returns: boolean indicating whether this {@code BitSet} is empty
- /// - 1.4
public func isEmpty() -> Bool {
return wordsInUse == 0
}
@@ -816,7 +801,6 @@ public class BitSet: Hashable, CustomStringConvertible {
/// - 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 {
@@ -831,7 +815,6 @@ public class BitSet: Hashable, CustomStringConvertible {
/// 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.. Rule tag tokens are always placed on the {@link #DEFAULT_CHANNEL}. This method returns the rule tag formatted with {@code <} and {@code >}
* delimiters. Rule tag tokens have types assigned according to the rule bypass
* transitions created during ATN deserialization. The implementation for {@link org.antlr.v4.runtime.tree.pattern.RuleTagToken} always returns 0. The implementation for {@link org.antlr.v4.runtime.tree.pattern.RuleTagToken} always returns -1. The implementation for {@link org.antlr.v4.runtime.tree.pattern.RuleTagToken} always returns -1. The implementation for {@link org.antlr.v4.runtime.tree.pattern.RuleTagToken} always returns -1. The implementation for {@link org.antlr.v4.runtime.tree.pattern.RuleTagToken} always returns -1. The implementation for {@link org.antlr.v4.runtime.tree.pattern.RuleTagToken} always returns {@code null}. The implementation for {@link org.antlr.v4.runtime.tree.pattern.RuleTagToken} always returns {@code null}. The implementation for {@link org.antlr.v4.runtime.tree.pattern.RuleTagToken} returns a string of the form
* {@code ruleName:bypassTokenType}. Each full-context prediction which does not result in a syntax error
+ /// 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
+ /// 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
+ /// 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
+ /// 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
+ /// 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. TODO: what to do about lexers This method handles the consumption of any tokens - the caller should
- /// not call {@link org.antlr.v4.runtime.Parser#consume} after a successful recovery.
-///
+/// * 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}.
///
///
Note that the calling code will not report an error if this method /// returns successfully. The error strategy implementation is responsible diff --git a/runtime/Swift/Sources/Antlr4/BailErrorStrategy.swift b/runtime/Swift/Sources/Antlr4/BailErrorStrategy.swift index eca1de705..996b8429a 100644 --- a/runtime/Swift/Sources/Antlr4/BailErrorStrategy.swift +++ b/runtime/Swift/Sources/Antlr4/BailErrorStrategy.swift @@ -3,42 +3,38 @@ /// 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.
+/// This error strategy is useful in the following scenarios. /// -///-/// {@code myparser.setErrorHandler(new BailErrorStrategy());}
+/// {@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}. - override - public func recover(_ recognizer: Parser, _ e: AnyObject) throws { + override public func recover(_ recognizer: Parser, _ e: AnyObject) throws { var context: ParserRuleContext? = recognizer.getContext() while let contextWrap = context{ contextWrap.exception = e diff --git a/runtime/Swift/Sources/Antlr4/BufferedTokenStream.swift b/runtime/Swift/Sources/Antlr4/BufferedTokenStream.swift index abc010c72..57628212c 100644 --- a/runtime/Swift/Sources/Antlr4/BufferedTokenStream.swift +++ b/runtime/Swift/Sources/Antlr4/BufferedTokenStream.swift @@ -40,13 +40,12 @@ public class BufferedTokenStream: TokenStream { /// {@link #tokenSource} and added to {@link #tokens}. This field improves /// performance for the following cases: /// - ////// This implementation prints messages to {@link System#err} containing the /// values of {@code line}, {@code charPositionInLine}, and {@code msg} using - /// the following format.
+ /// the following format. /// - ///- /// line line:charPositionInLine msg - ///- override - public func syntaxError
The default implementation returns immediately if the handler is already + /// 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.
+ /// according to the following table. /// - ///ORIGINS
+ ///__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 @@ -343,7 +341,7 @@ public class DefaultErrorStrategy: ANTLRErrorStrategy { /// recovery attempt fails, this method throws an /// {@link org.antlr.v4.runtime.InputMismatchException}.
/// - ///EXTRA TOKEN (single token deletion)
+ ///__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 @@ -352,7 +350,7 @@ public class DefaultErrorStrategy: ANTLRErrorStrategy { /// ///
This recovery strategy is implemented by {@link #singleTokenDeletion}.
/// - ///MISSING TOKEN (single token insertion)
+ ///__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 @@ -362,7 +360,7 @@ public class DefaultErrorStrategy: ANTLRErrorStrategy { /// ///
This recovery strategy is implemented by {@link #singleTokenInsertion}.
/// - ///EXAMPLE
+ ///__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 @@ -442,7 +440,7 @@ public class DefaultErrorStrategy: ANTLRErrorStrategy { /// 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 + /// {@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 diff --git a/runtime/Swift/Sources/Antlr4/DiagnosticErrorListener.swift b/runtime/Swift/Sources/Antlr4/DiagnosticErrorListener.swift index 75681f617..5af013b1a 100644 --- a/runtime/Swift/Sources/Antlr4/DiagnosticErrorListener.swift +++ b/runtime/Swift/Sources/Antlr4/DiagnosticErrorListener.swift @@ -8,18 +8,16 @@ /// are made by calling {@link org.antlr.v4.runtime.Parser#notifyErrorListeners} with the appropriate /// message. /// -///
Initializing Methods: Some methods in this interface have +/// __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:
+/// the stream was constructed. The following is a list of initializing methods: /// -///This method is guaranteed to succeed if any of the following are true:
+ /// This method is guaranteed to succeed if any of the following are true: /// - ///If {@code i} represents a position at or beyond the end of the stream, - /// this method returns {@link #EOF}.
+ /// 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} + /// 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.
+ /// the stream before calling this method. /// /// - throws: _ANTLRError.unsupportedOperation_ if the stream does not support /// retrieving the value of the specified symbol @@ -156,14 +142,12 @@ public protocol IntStream: class { /// returns without throwing an exception, then at least one of the following /// will be true. /// - ///To support output-preserving grammar transformations (including but not + * To support output-preserving grammar transformations (including but not * limited to left-recursion removal, automated left-factoring, and * optimized code generation), calls to listener methods during the parse * may differ substantially from calls made by * {@link org.antlr.v4.runtime.tree.ParseTreeWalker#DEFAULT} used after the parse is complete. In * particular, rule entry and exit events may occur in a different order * during the parse than after the parser. In addition, calls to certain - * rule entry methods may be omitted.
+ * rule entry methods may be omitted. * - *With the following specific exceptions, calls to listener events are - * deterministic, i.e. for identical input the calls to listener - * methods will be the same.
+ * With the following specific exceptions, calls to listener events are + * __deterministic__, i.e. for identical input the calls to listener + * methods will be the same. * - ** This compile-time constant value allows generated parsers and other * libraries to include a literal reference to the version of the ANTLR 4 * runtime library the code was compiled against. At each release, we - * change this value.
+ * change this value. * - *Version numbers are assumed to have the form + * Version numbers are assumed to have the form * - * major.minor.patch.revision-suffix, + * __major__.__minor__.__patch__.__revision__-__suffix__, * * with the individual components defined as follows.
* - ** The version check is designed to detect the following two specific - * scenarios.
+ * scenarios. * - ** Starting with ANTLR 4.3, the code generator emits a call to this method * using two constants in each generated lexer and parser: a hard-coded * constant indicating the version of the tool used to generate the parser * and a reference to the compile-time constant {@link #VERSION}. At * runtime, this method is called during the initialization of the generated * parser to detect mismatched versions, and notify the registered listeners - * prior to creating instances of the parser.
+ * prior to creating instances of the parser. * - ** This method does not perform any detection or filtering of semantic * changes between tool and runtime versions. It simply checks for a * version match and emits an error to stderr if a difference - * is detected.
+ * is detected. * - ** Note that some breaking changes between releases could result in other * types of runtime exceptions, such as a {@link LinkageError}, prior to * calling this method. In these cases, the underlying version mismatch will @@ -123,15 +114,14 @@ public class RuntimeMetaData { * result in binary compatibility problems which would be detected by the * class loader. As with semantic changes, changes that break binary * compatibility between releases are mentioned in the release notes - * accompanying the affected release.
+ * accompanying the affected release. * - *- * Additional note for target developers: The version check + * __ Additional note for target developers:__ The version check * implemented by this class is designed to address specific compatibility * concerns that may arise during the execution of Java applications. Other * targets should consider the implementation of this method in the context * of that target's known execution environment, which may or may not - * resemble the design provided for the Java target.
+ * resemble the design provided for the Java target. * * @param generatingToolVersion The version of the tool used to generate a parser. * This value may be null when called from user code that was not generated @@ -169,7 +159,7 @@ public class RuntimeMetaData { * E.g., from x.y.z return x.y. * * @param version The complete version string. - * @return A string of the form major.minor containing + * @return A string of the form __major__.__minor__ containing * only the major and minor components of the version string. */ public static func getMajorMinorVersion(_ version: String) -> String { diff --git a/runtime/Swift/Sources/Antlr4/atn/ATNConfig.swift b/runtime/Swift/Sources/Antlr4/atn/ATNConfig.swift index 9ee49ecd1..a3a6f0d46 100644 --- a/runtime/Swift/Sources/Antlr4/atn/ATNConfig.swift +++ b/runtime/Swift/Sources/Antlr4/atn/ATNConfig.swift @@ -47,7 +47,7 @@ public class ATNConfig: Hashable, CustomStringConvertible { /// 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. + /// __completely__ unaffected by the change. public final var reachesIntoOuterContext: Int = 0 //=0 intital by janyou diff --git a/runtime/Swift/Sources/Antlr4/atn/ATNState.swift b/runtime/Swift/Sources/Antlr4/atn/ATNState.swift index d6c7c2aa4..2db6929c9 100644 --- a/runtime/Swift/Sources/Antlr4/atn/ATNState.swift +++ b/runtime/Swift/Sources/Antlr4/atn/ATNState.swift @@ -3,66 +3,64 @@ /// 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. /// -///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 + /// 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.
diff --git a/runtime/Swift/Sources/Antlr4/atn/ParserATNSimulator.swift b/runtime/Swift/Sources/Antlr4/atn/ParserATNSimulator.swift index 81f55fc35..797deca16 100644 --- a/runtime/Swift/Sources/Antlr4/atn/ParserATNSimulator.swift +++ b/runtime/Swift/Sources/Antlr4/atn/ParserATNSimulator.swift @@ -43,7 +43,7 @@ /// ATN each time we get that input. /// ///-/// CACHING FULL CONTEXT PREDICTIONS
+/// __CACHING FULL CONTEXT PREDICTIONS__ /// ////// We could cache results from full context to predicted alternative easily and @@ -75,7 +75,7 @@ /// with full LL thing Sam does.
/// ///-/// AVOIDING FULL CONTEXT PREDICTION
+/// __AVOIDING FULL CONTEXT PREDICTION__ /// ////// We avoid doing full context retry when the outer context is empty, we did not @@ -111,7 +111,7 @@ /// entry rule and not dip into the outer context.
/// ///-/// PREDICATES
+/// __PREDICATES__ /// ////// Predicates are always evaluated if present in either SLL or LL both. SLL and @@ -143,7 +143,7 @@ /// without this on-the-fly evaluation.
/// ///-/// SHARING DFA
+/// __SHARING DFA__ /// ////// All instances of the same parser share the same decision DFAs through a @@ -154,7 +154,7 @@ /// a big size difference.
/// ///-/// THREAD SAFETY
+/// __THREAD SAFETY__ /// ////// The {@link org.antlr.v4.runtime.atn.ParserATNSimulator} locks on the {@link #decisionToDFA} field when @@ -182,8 +182,8 @@ /// 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)
+/// __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 @@ -218,12 +218,12 @@ /// ///
/// 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 +/// 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 +/// __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.
+/// 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 @@ -1045,44 +1045,35 @@ open class ParserATNSimulator: ATNSimulator { /// process applies the following changes to the start state's configuration /// set. /// - ///
/// 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 @@ -1090,7 +1081,6 @@ open class ParserATNSimulator: ATNSimulator { /// 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. @@ -1165,27 +1155,22 @@ open class ParserATNSimulator: ATNSimulator { /// {@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.
+ /// localized location. /// - ////// 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 + /// 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 @@ -1194,7 +1179,6 @@ open class ParserATNSimulator: ATNSimulator { /// 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 @@ -1286,22 +1270,19 @@ open class ParserATNSimulator: ATNSimulator { /// 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:
+ /// evaluate the following but it may change in the future: /// - ///@@ -76,12 +76,10 @@ public enum PredictionMode { /// This method computes the SLL prediction termination condition for both of /// the following cases.
/// - ///COMBINED SLL+LL PARSING
+ ///__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 @@ -100,7 +98,7 @@ public enum PredictionMode { /// stops when it sees only conflicting configuration subsets. In contrast, /// full LL keeps going when there is uncertainty.
/// - ///HEURISTIC
+ ///__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. @@ -128,13 +126,13 @@ public enum PredictionMode { /// associated with the conflicting configs, but since we can continue /// looking for input reasonably, don't declare the state done.
/// - ///PURE SLL PARSING
+ ///__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
+ ///__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 @@ -272,7 +270,7 @@ public enum PredictionMode { /// no configuration contains a semantic context during the termination /// check.
/// - ///CONFLICTING CONFIGS
+ ///__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 @@ -295,67 +293,63 @@ public enum PredictionMode { /// simplicity but also because that is the test you need to detect the /// alternatives that are actually in conflict.
/// - ///CONTINUE/STOP RULE
+ ///__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 + /// 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.
+ /// conflicting set. /// - ///CASES
+ /// __CASES__ /// - ///EXACT AMBIGUITY DETECTION
+ /// __EXACT AMBIGUITY DETECTION__ /// - ///If all states report the same conflicting set of alternatives, then we - /// know we have the exact ambiguity set.
+ /// 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} + /// 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...
+ /// {@code A={{1,2}}} or {@code {{1,2},{1,2}}}, etc... public static func resolvesToJustOneViableAlt(_ altsets: ArrayDelimiters are {@code <} and {@code >}, with {@code \} as the escape string * by default, but you can set them to whatever you want using diff --git a/runtime/Swift/Sources/Antlr4/tree/pattern/TagChunk.swift b/runtime/Swift/Sources/Antlr4/tree/pattern/TagChunk.swift index 11449b1bd..5b0b56fdd 100644 --- a/runtime/Swift/Sources/Antlr4/tree/pattern/TagChunk.swift +++ b/runtime/Swift/Sources/Antlr4/tree/pattern/TagChunk.swift @@ -8,17 +8,14 @@ * Represents a placeholder tag in a tree pattern. A tag can have any of the * following forms. * - *
The {@link RecognitionException} is non-null for all syntax errors except + /// + /// The _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).
- /// + /// token insertion and deletion mechanism). + /// /// - parameter recognizer: /// What parser got the error. From this /// object, you can access the context as well @@ -22,7 +25,7 @@ public protocol ANTLRErrorListener: class { /// - 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 + /// no viable alternative error, `e` has token at which we /// started production for the decision. /// - parameter line: /// The line number in the input where the error occurred. @@ -35,6 +38,7 @@ public protocol ANTLRErrorListener: class { /// 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 syntaxErrorIf one or more configurations in {@code configs} contains a semantic + /// + /// If one or more configurations in `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.
- /// + /// evaluated is reported in `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 + /// `null`, the conflicting alternatives are all alternatives + /// represented in `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, @@ -117,34 +125,35 @@ 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 + /// + /// Each full-context prediction which does not result in a syntax error + /// will call either _#reportContextSensitivity_ or + /// _#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 + /// _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 + /// grammars. + /// + /// `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}. + /// is passed as the `prediction` argument. + /// + /// Note that the definition of "context sensitivity" in this method + /// differs from the concept in _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.
- /// + /// 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 @@ -153,6 +162,7 @@ public protocol ANTLRErrorListener: class { /// - 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 418228c7f..325418b5e 100644 --- a/runtime/Swift/Sources/Antlr4/ANTLRErrorStrategy.swift +++ b/runtime/Swift/Sources/Antlr4/ANTLRErrorStrategy.swift @@ -1,101 +1,119 @@ -/// +/// +/// /// Copyright (c) 2012-2017 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
+/// _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}. + /// + /// Reset the error handler state for the specified `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 + /// inline match operation, such as _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 + /// returns the _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 + /// + /// This method handles the consumption of any tokens - the caller should + /// __not__ call _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.
- /// + /// for calling _org.antlr.v4.runtime.Parser#notifyErrorListeners_ as appropriate. + /// /// - parameter recognizer: the parser instance /// - throws: _RecognitionException_ if the error strategy was not able to /// recover from the unexpected input symbol + /// @discardableResult func recoverInline(_ recognizer: Parser) throws -> Token - /// This method is called to recover from exception {@code e}. This method is - /// called after {@link #reportError} by the default exception handler + /// + /// This method is called to recover from exception `e`. This method is + /// called after _#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 /// - throws: _RecognitionException_ if the error strategy could not recover from /// the recognition exception + /// func recover(_ recognizer: Parser, _ e: AnyObject) throws + /// /// 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}.
- /// + /// _org.antlr.v4.runtime.RecognitionException_. + /// + /// The generated code currently contains calls to _#sync_ after + /// entering the decision state of a closure block (`(...)*` or + /// `(...)+`). + /// + /// For an implementation based on Jim Idle's "magic sync" mechanism, see + /// _org.antlr.v4.runtime.DefaultErrorStrategy#sync_. + /// /// - seealso: org.antlr.v4.runtime.DefaultErrorStrategy#sync - /// + /// /// - parameter recognizer: the parser instance /// - throws: _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 + /// /// Tests whether or not recognizer} is in the process of recovering - /// from an error. In error recovery mode, {@link org.antlr.v4.runtime.Parser#consume} adds + /// from an error. In error recovery mode, _org.antlr.v4.runtime.Parser#consume_ adds /// symbols to the parse tree by calling - /// {@link Parser#createErrorNode(ParserRuleContext, Token)} then - /// {@link ParserRuleContext#addErrorNode(ErrorNode)} instead of - /// {@link Parser#createTerminalNode(ParserRuleContext, Token)}. - /// + /// _Parser#createErrorNode(ParserRuleContext, Token)_ then + /// _ParserRuleContext#addErrorNode(ErrorNode)_ instead of + /// _Parser#createTerminalNode(ParserRuleContext, Token)_. + /// /// - parameter recognizer: the parser instance - /// - returns: {@code true} if the parser is currently recovering from a parse - /// error, otherwise {@code false} + /// - returns: `true` if the parser is currently recovering from a parse + /// error, otherwise `false` + /// func inErrorRecoveryMode(_ recognizer: Parser) -> Bool + /// /// 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 + /// + /// Report any kind of _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 96623d1d2..9ed7ac9ef 100644 --- a/runtime/Swift/Sources/Antlr4/ANTLRFileStream.swift +++ b/runtime/Swift/Sources/Antlr4/ANTLRFileStream.swift @@ -1,8 +1,10 @@ +/// /// Copyright (c) 2012-2017 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 +/// This is an _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 f57902d74..17bbd8096 100644 --- a/runtime/Swift/Sources/Antlr4/ANTLRInputStream.swift +++ b/runtime/Swift/Sources/Antlr4/ANTLRInputStream.swift @@ -1,26 +1,36 @@ +/// /// Copyright (c) 2012-2017 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.
+/// Vacuum all input from a _java.io.Reader_/_java.io.InputStream_ and then treat it +/// like a `char[]` buffer. Can also pass in a _String_ or +/// `char[]` to use. +/// +/// If you need encoding, pass in stream/reader with correct encoding. +/// public class ANTLRInputStream: CharStream { public static let READ_BUFFER_SIZE: Int = 1024 public static let INITIAL_BUFFER_SIZE: Int = 1024 + /// /// The data being scanned + /// internal var data: [Character] + /// /// How many characters are actually in the buffer + /// internal var n: Int + /// /// 0..n-1 index into string of next char + /// internal var p: Int = 0 + /// /// What is name or source of this char stream? + /// public var name: String? public init() { @@ -28,13 +38,17 @@ public class ANTLRInputStream: CharStream { data = [Character]() } + /// /// 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 + /// public init(_ data: [Character], _ numberOfActualCharsInArray: Int) { self.data = data self.n = numberOfActualCharsInArray @@ -84,9 +98,11 @@ 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). + /// public func index() -> Int { return p } @@ -95,7 +111,9 @@ public class ANTLRInputStream: CharStream { return n } + /// /// mark/release do nothing; we have entire buffer + /// public func mark() -> Int { return -1 @@ -104,8 +122,10 @@ 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 + /// 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 996b8429a..1753fa751 100644 --- a/runtime/Swift/Sources/Antlr4/BailErrorStrategy.swift +++ b/runtime/Swift/Sources/Antlr4/BailErrorStrategy.swift @@ -1,39 +1,45 @@ +/// /// Copyright (c) 2012-2017 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 +/// +/// +/// This implementation of _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 +/// _org.antlr.v4.runtime.misc.ParseCancellationException_. The implementation ensures that the +/// _org.antlr.v4.runtime.ParserRuleContext#exception_ field is set for all parse tree nodes /// that were not completed prior to encountering the error. -/// +/// /// This error strategy is useful in the following scenarios. -/// +/// /// * __Two-stage parsing:__ This error strategy allows the first /// stage of two-stage parsing to immediately terminate if an error is /// encountered, and immediately fall back to the second stage. In addition to /// avoiding wasted work by attempting to recover from errors here, the empty -/// implementation of {@link org.antlr.v4.runtime.BailErrorStrategy#sync} improves the performance of +/// implementation of _org.antlr.v4.runtime.BailErrorStrategy#sync_ improves the performance of /// the first stage. -/// +/// /// * __Silent validation:__ When syntax errors are not being /// reported or logged, and the parse result is simply ignored if errors occur, -/// the {@link org.antlr.v4.runtime.BailErrorStrategy} avoids wasting work on recovering from errors +/// the _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());} -/// +/// +/// `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 `e`, re-throw it wrapped + /// in a _org.antlr.v4.runtime.misc.ParseCancellationException_ so it is not caught by the + /// rule function catches. Use _Exception#getCause()_ to get the + /// original _org.antlr.v4.runtime.RecognitionException_. + /// override public func recover(_ recognizer: Parser, _ e: AnyObject) throws { var context: ParserRuleContext? = recognizer.getContext() while let contextWrap = context{ @@ -44,8 +50,10 @@ 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. + /// override public func recoverInline(_ recognizer: Parser) throws -> Token { let e: InputMismatchException = try InputMismatchException(recognizer) @@ -59,7 +67,9 @@ public class BailErrorStrategy: DefaultErrorStrategy { } + /// /// 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 725fd01a6..75d3cad8c 100644 --- a/runtime/Swift/Sources/Antlr4/BaseErrorListener.swift +++ b/runtime/Swift/Sources/Antlr4/BaseErrorListener.swift @@ -1,13 +1,17 @@ +/// /// Copyright (c) 2012-2017 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 +/// +/// Provides an empty default implementation of _org.antlr.v4.runtime.ANTLRErrorListener_. The /// default implementation of each method does nothing, but can be overridden as /// necessary. -/// +/// /// - Sam Harwell +/// open class BaseErrorListener: ANTLRErrorListener { public init() { diff --git a/runtime/Swift/Sources/Antlr4/BufferedTokenStream.swift b/runtime/Swift/Sources/Antlr4/BufferedTokenStream.swift index 57628212c..cbf40b3cc 100644 --- a/runtime/Swift/Sources/Antlr4/BufferedTokenStream.swift +++ b/runtime/Swift/Sources/Antlr4/BufferedTokenStream.swift @@ -1,51 +1,63 @@ +/// /// Copyright (c) 2012-2017 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 +/// +/// This implementation of _org.antlr.v4.runtime.TokenStream_ loads tokens from a +/// _org.antlr.v4.runtime.TokenSource_ on-demand, and places the tokens in a buffer to provide /// access to any previous token by index. -/// -///-/// This token stream ignores the value of {@link org.antlr.v4.runtime.Token#getChannel}. If your +/// +/// +/// This token stream ignores the value of _org.antlr.v4.runtime.Token#getChannel_. If your /// parser requires the token stream filter tokens to only those on a particular -/// channel, such as {@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}.
+/// channel, such as _org.antlr.v4.runtime.Token#DEFAULT_CHANNEL_ or +/// _org.antlr.v4.runtime.Token#HIDDEN_CHANNEL_, use a filtering token stream such a +/// _org.antlr.v4.runtime.CommonTokenStream_. +/// public class BufferedTokenStream: TokenStream { - /// The {@link org.antlr.v4.runtime.TokenSource} from which tokens for this stream are fetched. + /// + /// The _org.antlr.v4.runtime.TokenSource_ from which tokens for this stream are fetched. + /// internal var tokenSource: TokenSource + /// /// A collection of all tokens fetched from the token source. The list is - /// considered a complete view of the input once {@link #fetchedEOF} is set - /// to {@code true}. + /// considered a complete view of the input once _#fetchedEOF_ is set + /// to `true`. + /// internal var tokens: Array