Fixed some TODOs + exceptions.

- Reworked the exception hierarchy to conform with the Java hierarchy (where we mimic that). Ultimative base class is std::exception, which uses std::string (char* actually) for messages, so all exceptions use std::string for that as well. Consider that as first step to rework the entire lib to use std::string instead of std::wstring (with utf-8 for full Unicode support).
- Removed ASSERTException + TODOException and fixed the places where they were used.
- Removed ANTLRException, which was only an intermediate layer without an equivalent on Java side.
- Replaced some equals() calls by == (with defined operator overloading).
- Enhanced Arrays::equals() to ensure it compiles only if the actual types being compared support the != operator (both value + reference types).
- Made the Recognizer class template free by using plain polymorphism. Some adjustments were need also in the Cpp template to support that. Could convert the .inl file to .cpp then.
This commit is contained in:
Mike Lischke 2016-03-31 18:32:44 +02:00
parent 29dedd17c4
commit 1ca5b38868
73 changed files with 889 additions and 1005 deletions

View File

@ -101,7 +101,7 @@ using namespace org::antlr::v4::runtime::misc;
XCTFail();
} catch (const IllegalStateException &e) {
// Expected.
XCTAssertEqual(e.getMessage(), L"cannot consume EOF");
XCTAssertEqual(e.getMessage(), "cannot consume EOF");
}
XCTAssertEqual(stream.index(), text.size());

View File

@ -227,10 +227,10 @@ using namespace org::antlr::v4::runtime::misc;
XCTAssert(Interval(1000, 2000).intersection(Interval(10, 100)) == Interval(1000, 100));
XCTAssert(Interval(500, 2000).intersection(Interval(10, 1000)) == Interval(500, 1000));
XCTAssert(Interval().toString() == L"-1..-2");
XCTAssert(Interval(10, 10).toString() == L"10..10");
XCTAssert(Interval(1000, 2000).toString() == L"1000..2000");
XCTAssert(Interval(500, INT_MAX).toString() == L"500.." + std::to_wstring(INT_MAX));
XCTAssert(Interval().toString() == "-1..-2");
XCTAssert(Interval(10, 10).toString() == "10..10");
XCTAssert(Interval(1000, 2000).toString() == "1000..2000");
XCTAssert(Interval(500, INT_MAX).toString() == "500.." + std::to_string(INT_MAX));
}
- (void)testIntervalSet {

View File

@ -13,6 +13,8 @@
2747A70D1CA691310030247B /* ConfigLookup.h in Headers */ = {isa = PBXBuildFile; fileRef = 2747A7091CA691310030247B /* ConfigLookup.h */; };
2747A7131CA6C46C0030247B /* InputHandlingTests.mm in Sources */ = {isa = PBXBuildFile; fileRef = 2747A7121CA6C46C0030247B /* InputHandlingTests.mm */; };
274FC6D91CA96B6C008D4374 /* MiscClassTests.mm in Sources */ = {isa = PBXBuildFile; fileRef = 274FC6D81CA96B6C008D4374 /* MiscClassTests.mm */; };
276901A91CAD7E66005CEC6A /* Recognizer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27C666991C9584050021E494 /* Recognizer.cpp */; };
276901AA1CAD7E67005CEC6A /* Recognizer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27C666991C9584050021E494 /* Recognizer.cpp */; };
276927241C9ED49100E4EBF8 /* antlrcpp-Prefix.h in Headers */ = {isa = PBXBuildFile; fileRef = 276927231C9ED49100E4EBF8 /* antlrcpp-Prefix.h */; };
276927251C9ED49100E4EBF8 /* antlrcpp-Prefix.h in Headers */ = {isa = PBXBuildFile; fileRef = 276927231C9ED49100E4EBF8 /* antlrcpp-Prefix.h */; };
278A66FB1C95838E002D667E /* ANTLRErrorListener.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 278A66FA1C95838E002D667E /* ANTLRErrorListener.cpp */; };
@ -636,10 +638,10 @@
27C666751C9584050021E494 /* DefaultErrorStrategy.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = DefaultErrorStrategy.h; path = ../../runtime/DefaultErrorStrategy.h; sourceTree = SOURCE_ROOT; };
27C666761C9584050021E494 /* DiagnosticErrorListener.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = DiagnosticErrorListener.cpp; path = ../../runtime/DiagnosticErrorListener.cpp; sourceTree = SOURCE_ROOT; wrapsLines = 0; };
27C666771C9584050021E494 /* DiagnosticErrorListener.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = DiagnosticErrorListener.h; path = ../../runtime/DiagnosticErrorListener.h; sourceTree = SOURCE_ROOT; wrapsLines = 0; };
27C666781C9584050021E494 /* Exceptions.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = Exceptions.cpp; path = ../../runtime/Exceptions.cpp; sourceTree = SOURCE_ROOT; };
27C666791C9584050021E494 /* Exceptions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Exceptions.h; path = ../../runtime/Exceptions.h; sourceTree = SOURCE_ROOT; };
27C6667A1C9584050021E494 /* FailedPredicateException.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = FailedPredicateException.cpp; path = ../../runtime/FailedPredicateException.cpp; sourceTree = SOURCE_ROOT; };
27C6667B1C9584050021E494 /* FailedPredicateException.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = FailedPredicateException.h; path = ../../runtime/FailedPredicateException.h; sourceTree = SOURCE_ROOT; };
27C666781C9584050021E494 /* Exceptions.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = Exceptions.cpp; path = ../../runtime/Exceptions.cpp; sourceTree = SOURCE_ROOT; wrapsLines = 0; };
27C666791C9584050021E494 /* Exceptions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Exceptions.h; path = ../../runtime/Exceptions.h; sourceTree = SOURCE_ROOT; wrapsLines = 0; };
27C6667A1C9584050021E494 /* FailedPredicateException.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = FailedPredicateException.cpp; path = ../../runtime/FailedPredicateException.cpp; sourceTree = SOURCE_ROOT; wrapsLines = 0; };
27C6667B1C9584050021E494 /* FailedPredicateException.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = FailedPredicateException.h; path = ../../runtime/FailedPredicateException.h; sourceTree = SOURCE_ROOT; wrapsLines = 0; };
27C6667D1C9584050021E494 /* InputMismatchException.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = InputMismatchException.cpp; path = ../../runtime/InputMismatchException.cpp; sourceTree = SOURCE_ROOT; };
27C6667E1C9584050021E494 /* InputMismatchException.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = InputMismatchException.h; path = ../../runtime/InputMismatchException.h; sourceTree = SOURCE_ROOT; };
27C6667F1C9584050021E494 /* InterpreterRuleContext.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = InterpreterRuleContext.cpp; path = ../../runtime/InterpreterRuleContext.cpp; sourceTree = SOURCE_ROOT; wrapsLines = 0; };
@ -651,7 +653,7 @@
27C666851C9584050021E494 /* Lexer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Lexer.h; path = ../../runtime/Lexer.h; sourceTree = SOURCE_ROOT; };
27C666861C9584050021E494 /* LexerInterpreter.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = LexerInterpreter.cpp; path = ../../runtime/LexerInterpreter.cpp; sourceTree = SOURCE_ROOT; };
27C666871C9584050021E494 /* LexerInterpreter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = LexerInterpreter.h; path = ../../runtime/LexerInterpreter.h; sourceTree = SOURCE_ROOT; };
27C666881C9584050021E494 /* LexerNoViableAltException.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = LexerNoViableAltException.cpp; path = ../../runtime/LexerNoViableAltException.cpp; sourceTree = SOURCE_ROOT; };
27C666881C9584050021E494 /* LexerNoViableAltException.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = LexerNoViableAltException.cpp; path = ../../runtime/LexerNoViableAltException.cpp; sourceTree = SOURCE_ROOT; wrapsLines = 0; };
27C666891C9584050021E494 /* LexerNoViableAltException.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = LexerNoViableAltException.h; path = ../../runtime/LexerNoViableAltException.h; sourceTree = SOURCE_ROOT; };
27C6668A1C9584050021E494 /* ListTokenSource.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = ListTokenSource.cpp; path = ../../runtime/ListTokenSource.cpp; sourceTree = SOURCE_ROOT; wrapsLines = 0; };
27C6668B1C9584050021E494 /* ListTokenSource.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ListTokenSource.h; path = ../../runtime/ListTokenSource.h; sourceTree = SOURCE_ROOT; };
@ -666,9 +668,9 @@
27C666941C9584050021E494 /* ProxyErrorListener.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = ProxyErrorListener.cpp; path = ../../runtime/ProxyErrorListener.cpp; sourceTree = SOURCE_ROOT; wrapsLines = 0; };
27C666951C9584050021E494 /* ProxyErrorListener.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ProxyErrorListener.h; path = ../../runtime/ProxyErrorListener.h; sourceTree = SOURCE_ROOT; wrapsLines = 0; };
27C666961C9584050021E494 /* RecognitionException.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = RecognitionException.cpp; path = ../../runtime/RecognitionException.cpp; sourceTree = SOURCE_ROOT; wrapsLines = 0; };
27C666971C9584050021E494 /* RecognitionException.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = RecognitionException.h; path = ../../runtime/RecognitionException.h; sourceTree = SOURCE_ROOT; };
27C666971C9584050021E494 /* RecognitionException.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = RecognitionException.h; path = ../../runtime/RecognitionException.h; sourceTree = SOURCE_ROOT; wrapsLines = 0; };
27C666981C9584050021E494 /* Recognizer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Recognizer.h; path = ../../runtime/Recognizer.h; sourceTree = SOURCE_ROOT; };
27C666991C9584050021E494 /* Recognizer.inl */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = Recognizer.inl; path = ../../runtime/Recognizer.inl; sourceTree = SOURCE_ROOT; };
27C666991C9584050021E494 /* Recognizer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = Recognizer.cpp; path = ../../runtime/Recognizer.cpp; sourceTree = SOURCE_ROOT; };
27C6669A1C9584050021E494 /* RuleContext.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = RuleContext.cpp; path = ../../runtime/RuleContext.cpp; sourceTree = SOURCE_ROOT; wrapsLines = 0; };
27C6669B1C9584050021E494 /* RuleContext.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = RuleContext.h; path = ../../runtime/RuleContext.h; sourceTree = SOURCE_ROOT; };
27C6669C1C9584050021E494 /* Token.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = Token.cpp; path = ../../runtime/Token.cpp; sourceTree = SOURCE_ROOT; };
@ -681,7 +683,7 @@
27C666A31C9584050021E494 /* TokenStream.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TokenStream.h; path = ../../runtime/TokenStream.h; sourceTree = SOURCE_ROOT; };
27C666A41C9584050021E494 /* TokenStreamRewriter.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TokenStreamRewriter.cpp; path = ../../runtime/TokenStreamRewriter.cpp; sourceTree = SOURCE_ROOT; wrapsLines = 0; };
27C666A51C9584050021E494 /* TokenStreamRewriter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TokenStreamRewriter.h; path = ../../runtime/TokenStreamRewriter.h; sourceTree = SOURCE_ROOT; wrapsLines = 0; };
27C666A61C9584050021E494 /* UnbufferedCharStream.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = UnbufferedCharStream.cpp; path = ../../runtime/UnbufferedCharStream.cpp; sourceTree = SOURCE_ROOT; };
27C666A61C9584050021E494 /* UnbufferedCharStream.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = UnbufferedCharStream.cpp; path = ../../runtime/UnbufferedCharStream.cpp; sourceTree = SOURCE_ROOT; wrapsLines = 0; };
27C666A71C9584050021E494 /* UnbufferedCharStream.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = UnbufferedCharStream.h; path = ../../runtime/UnbufferedCharStream.h; sourceTree = SOURCE_ROOT; };
27C666A81C9584050021E494 /* UnbufferedTokenStream.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = UnbufferedTokenStream.h; path = ../../runtime/UnbufferedTokenStream.h; sourceTree = SOURCE_ROOT; };
27C666A91C9584050021E494 /* UnbufferedTokenStream.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = UnbufferedTokenStream.cpp; path = ../../runtime/UnbufferedTokenStream.cpp; sourceTree = SOURCE_ROOT; wrapsLines = 0; };
@ -703,7 +705,7 @@
27C667541C95846E0021E494 /* ATNDeserializationOptions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ATNDeserializationOptions.h; sourceTree = "<group>"; };
27C667551C95846E0021E494 /* ATNDeserializer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ATNDeserializer.cpp; sourceTree = "<group>"; wrapsLines = 0; };
27C667561C95846E0021E494 /* ATNDeserializer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ATNDeserializer.h; sourceTree = "<group>"; wrapsLines = 0; };
27C667571C95846E0021E494 /* ATNSerializer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ATNSerializer.cpp; sourceTree = "<group>"; };
27C667571C95846E0021E494 /* ATNSerializer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ATNSerializer.cpp; sourceTree = "<group>"; wrapsLines = 0; };
27C667581C95846E0021E494 /* ATNSerializer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ATNSerializer.h; sourceTree = "<group>"; };
27C667591C95846E0021E494 /* ATNSimulator.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ATNSimulator.cpp; sourceTree = "<group>"; wrapsLines = 0; };
27C6675A1C95846E0021E494 /* ATNSimulator.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ATNSimulator.h; sourceTree = "<group>"; wrapsLines = 0; };
@ -763,7 +765,7 @@
27C667911C95846E0021E494 /* RuleStopState.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RuleStopState.h; sourceTree = "<group>"; };
27C667921C95846E0021E494 /* RuleTransition.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = RuleTransition.cpp; sourceTree = "<group>"; };
27C667931C95846E0021E494 /* RuleTransition.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RuleTransition.h; sourceTree = "<group>"; };
27C667941C95846E0021E494 /* SemanticContext.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SemanticContext.cpp; sourceTree = "<group>"; };
27C667941C95846E0021E494 /* SemanticContext.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SemanticContext.cpp; sourceTree = "<group>"; wrapsLines = 0; };
27C667951C95846E0021E494 /* SemanticContext.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SemanticContext.h; sourceTree = "<group>"; };
27C667961C95846E0021E494 /* SetTransition.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SetTransition.cpp; sourceTree = "<group>"; };
27C667971C95846E0021E494 /* SetTransition.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SetTransition.h; sourceTree = "<group>"; };
@ -783,7 +785,7 @@
27C667A51C95846E0021E494 /* WildcardTransition.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WildcardTransition.h; sourceTree = "<group>"; };
27C668651C9584B60021E494 /* DFA.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = DFA.cpp; sourceTree = "<group>"; wrapsLines = 0; };
27C668661C9584B60021E494 /* DFA.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DFA.h; sourceTree = "<group>"; };
27C668671C9584B60021E494 /* DFASerializer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = DFASerializer.cpp; sourceTree = "<group>"; };
27C668671C9584B60021E494 /* DFASerializer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = DFASerializer.cpp; sourceTree = "<group>"; wrapsLines = 0; };
27C668681C9584B60021E494 /* DFASerializer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DFASerializer.h; sourceTree = "<group>"; };
27C668691C9584B60021E494 /* DFAState.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = DFAState.cpp; sourceTree = "<group>"; };
27C6686A1C9584B60021E494 /* DFAState.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DFAState.h; sourceTree = "<group>"; };
@ -1286,7 +1288,7 @@
27C666961C9584050021E494 /* RecognitionException.cpp */,
27C666971C9584050021E494 /* RecognitionException.h */,
27C666981C9584050021E494 /* Recognizer.h */,
27C666991C9584050021E494 /* Recognizer.inl */,
27C666991C9584050021E494 /* Recognizer.cpp */,
27C6669A1C9584050021E494 /* RuleContext.cpp */,
27C6669B1C9584050021E494 /* RuleContext.h */,
27C6669C1C9584050021E494 /* Token.cpp */,
@ -1874,6 +1876,7 @@
27C667071C9584050021E494 /* ListTokenSource.cpp in Sources */,
27C6681D1C95846E0021E494 /* PrecedencePredicateTransition.cpp in Sources */,
27C66A0F1C958AB30021E494 /* TokenTagToken.cpp in Sources */,
276901AA1CAD7E67005CEC6A /* Recognizer.cpp in Sources */,
27C667031C9584050021E494 /* LexerNoViableAltException.cpp in Sources */,
27C666CB1C9584050021E494 /* CommonToken.cpp in Sources */,
27C66A431C958AC10021E494 /* XPathTokenElement.cpp in Sources */,
@ -2015,6 +2018,7 @@
27C668181C95846E0021E494 /* PlusLoopbackState.cpp in Sources */,
27C668401C95846E0021E494 /* SemanticContext.cpp in Sources */,
27C66A0E1C958AB30021E494 /* TokenTagToken.cpp in Sources */,
276901A91CAD7E66005CEC6A /* Recognizer.cpp in Sources */,
27C669AF1C9585B80021E494 /* SyntaxTree.cpp in Sources */,
27C667DA1C95846E0021E494 /* BasicBlockStartState.cpp in Sources */,
27C66A421C958AC10021E494 /* XPathTokenElement.cpp in Sources */,

View File

@ -86,7 +86,7 @@ void ANTLRInputStream::reset() {
void ANTLRInputStream::consume() {
if (p >= data.size()) {
assert(LA(1) == IntStream::_EOF);
throw IllegalStateException(L"cannot consume EOF");
throw IllegalStateException("cannot consume EOF");
}
if (p < data.size()) {

View File

@ -34,6 +34,7 @@
#include "RuleContext.h"
#include "Interval.h"
#include "StringBuilder.h"
#include "Exceptions.h"
#include "BufferedTokenStream.h"
@ -42,7 +43,7 @@ using namespace org::antlr::v4::runtime;
BufferedTokenStream::BufferedTokenStream(TokenSource *tokenSource) {
InitializeInstanceFields();
if (tokenSource == nullptr) {
throw new NullPointerException(L"tokenSource cannot be null");
throw new NullPointerException("tokenSource cannot be null");
}
this->tokenSource = tokenSource;
}
@ -78,7 +79,7 @@ size_t BufferedTokenStream::size() {
void BufferedTokenStream::consume() {
if (LA(1) == _EOF) {
throw new IllegalStateException(L"cannot consume EOF");
throw new IllegalStateException("cannot consume EOF");
}
if (sync(p + 1)) {
@ -119,10 +120,10 @@ size_t BufferedTokenStream::fetch(size_t n) {
Token *BufferedTokenStream::get(size_t i) const {
if (i >= tokens.size()) {
throw IndexOutOfBoundsException(std::wstring(L"token index ") +
std::to_wstring(i) +
std::wstring(L" out of range 0..") +
std::to_wstring(tokens.size() - 1));
throw IndexOutOfBoundsException(std::string("token index ") +
std::to_string(i) +
std::string(" out of range 0..") +
std::to_string(tokens.size() - 1));
}
return tokens[i];
}
@ -212,12 +213,12 @@ std::vector<Token*> BufferedTokenStream::getTokens(int start, int stop) {
std::vector<Token*> BufferedTokenStream::getTokens(int start, int stop, std::vector<int> *types) {
lazyInit();
if (start < 0 || stop >= (int)tokens.size() || stop < 0 || (int)start >= (int)tokens.size()) {
throw new IndexOutOfBoundsException(std::wstring(L"start ") +
std::to_wstring(start) +
std::wstring(L" or stop ") +
std::to_wstring(stop) +
std::wstring(L" not in 0..") +
std::to_wstring(tokens.size() - 1));
throw new IndexOutOfBoundsException(std::string("start ") +
std::to_string(start) +
std::string(" or stop ") +
std::to_string(stop) +
std::string(" not in 0..") +
std::to_string(tokens.size() - 1));
}
if (start > stop) {
return std::vector<Token*>();
@ -280,9 +281,9 @@ ssize_t BufferedTokenStream::previousTokenOnChannel(size_t i, int channel) const
std::vector<Token*> BufferedTokenStream::getHiddenTokensToRight(size_t tokenIndex, int channel) {
lazyInit();
if (tokenIndex >= tokens.size()) {
throw new IndexOutOfBoundsException(std::to_wstring(tokenIndex) +
std::wstring(L" not in 0..") +
std::to_wstring(tokens.size() - 1));
throw new IndexOutOfBoundsException(std::to_string(tokenIndex) +
std::string(" not in 0..") +
std::to_string(tokens.size() - 1));
}
ssize_t nextOnChannel = nextTokenOnChannel(tokenIndex + 1, Lexer::DEFAULT_TOKEN_CHANNEL);
@ -305,9 +306,9 @@ std::vector<Token*> BufferedTokenStream::getHiddenTokensToRight(size_t tokenInde
std::vector<Token*> BufferedTokenStream::getHiddenTokensToLeft(size_t tokenIndex, int channel) {
lazyInit();
if (tokenIndex >= tokens.size()) {
throw new IndexOutOfBoundsException(std::to_wstring(tokenIndex) +
std::wstring(L" not in 0..") +
std::to_wstring(tokens.size() - 1));
throw new IndexOutOfBoundsException(std::to_string(tokenIndex) +
std::string(" not in 0..") +
std::to_string(tokens.size() - 1));
}
ssize_t prevOnChannel = previousTokenOnChannel(tokenIndex - 1, Lexer::DEFAULT_TOKEN_CHANNEL);

View File

@ -39,6 +39,7 @@
#include "ATN.h"
#include "ATNState.h"
#include "Parser.h"
#include "Strings.h"
#include "DefaultErrorStrategy.h"
@ -84,10 +85,9 @@ void DefaultErrorStrategy::reportError(Parser *recognizer, RecognitionException
// This is really bush league, I hate libraries that gratuitiously print
// stuff out
std::wcerr << std::wstring(L"unknown recognition error type: " +
antlrcpp::s2ws(typeid(e).name()));
std::cerr << std::string("unknown recognition error type: ") + typeid(e).name();
recognizer->notifyErrorListeners(e->getOffendingToken(), antlrcpp::s2ws(e->what()), e);
recognizer->notifyErrorListeners(e->getOffendingToken().get(), antlrcpp::s2ws(e->what()), e);
}
}
@ -112,7 +112,7 @@ void DefaultErrorStrategy::recover(Parser *recognizer, RecognitionException *e)
}
void DefaultErrorStrategy::sync(Parser *recognizer) {
atn::ATNState *s = recognizer->getInterpreter()->atn.states[(size_t)recognizer->getState()];
atn::ATNState *s = recognizer->getInterpreter<atn::ATNSimulator>()->atn.states[(size_t)recognizer->getState()];
// If already recovering, don't try to sync
if (inErrorRecoveryMode(recognizer)) {
@ -167,24 +167,24 @@ void DefaultErrorStrategy::reportNoViableAlternative(Parser *recognizer, NoViabl
if (e->getStartToken()->getType() == Token::_EOF) {
input = L"<EOF>";
} else {
input = tokens->getText(e->getStartToken(), e->getOffendingToken());
input = tokens->getText(e->getStartToken().get(), e->getOffendingToken().get());
}
} else {
input = L"<unknown input>";
}
std::wstring msg = std::wstring(L"no viable alternative at input ") + escapeWSAndQuote(input);
recognizer->notifyErrorListeners(e->getOffendingToken(), msg, e);
recognizer->notifyErrorListeners(e->getOffendingToken().get(), msg, e);
}
void DefaultErrorStrategy::reportInputMismatch(Parser *recognizer, InputMismatchException *e) {
std::wstring msg = std::wstring(L"mismatched input ") + getTokenErrorDisplay(e->getOffendingToken()) + std::wstring(L" expecting ") + e->getExpectedTokens().toString(recognizer->getTokenNames());
recognizer->notifyErrorListeners(e->getOffendingToken(), msg, e);
std::wstring msg = std::wstring(L"mismatched input ") + getTokenErrorDisplay(e->getOffendingToken().get()) + std::wstring(L" expecting ") + e->getExpectedTokens().toString(recognizer->getTokenNames());
recognizer->notifyErrorListeners(e->getOffendingToken().get(), msg, e);
}
void DefaultErrorStrategy::reportFailedPredicate(Parser *recognizer, FailedPredicateException *e) {
const std::wstring& ruleName = recognizer->getRuleNames()[(size_t)recognizer->ctx->getRuleIndex()];
std::wstring msg = std::wstring(L"rule ") + ruleName + std::wstring(L" ") + e->getMessage();
recognizer->notifyErrorListeners(e->getOffendingToken(), msg, e);
std::wstring msg = std::wstring(L"rule ") + ruleName + std::wstring(L" ") + antlrcpp::s2ws(e->getMessage());
recognizer->notifyErrorListeners(e->getOffendingToken().get(), msg, e);
}
void DefaultErrorStrategy::reportUnwantedToken(Parser *recognizer) {
@ -241,9 +241,9 @@ bool DefaultErrorStrategy::singleTokenInsertion(Parser *recognizer) {
// if current token is consistent with what could come after current
// ATN state, then we know we're missing a token; error recovery
// is free to conjure up and insert the missing token
atn::ATNState *currentState = recognizer->getInterpreter()->atn.states[(size_t)recognizer->getState()];
atn::ATNState *currentState = recognizer->getInterpreter<atn::ATNSimulator>()->atn.states[(size_t)recognizer->getState()];
atn::ATNState *next = currentState->transition(0)->target;
const atn::ATN &atn = recognizer->getInterpreter()->atn;
const atn::ATN &atn = recognizer->getInterpreter<atn::ATNSimulator>()->atn;
misc::IntervalSet expectingAtLL2 = atn.nextTokens(next, recognizer->ctx);
if (expectingAtLL2.contains((int)currentSymbolType)) {
reportMissingToken(recognizer);
@ -322,7 +322,7 @@ std::wstring DefaultErrorStrategy::escapeWSAndQuote(std::wstring &s) {
}
misc::IntervalSet DefaultErrorStrategy::getErrorRecoverySet(Parser *recognizer) {
const atn::ATN &atn = recognizer->getInterpreter()->atn;
const atn::ATN &atn = recognizer->getInterpreter<atn::ATNSimulator>()->atn;
RuleContext *ctx = recognizer->ctx;
misc::IntervalSet recoverSet;
while (ctx != nullptr && ctx->invokingState >= 0) {

View File

@ -31,3 +31,40 @@
#include "Exceptions.h"
using namespace org::antlr::v4::runtime;
RuntimeException::RuntimeException(RuntimeException *cause) : RuntimeException("", cause) {
}
RuntimeException::RuntimeException(const std::string &msg, RuntimeException *cause)
: std::exception(), _message(msg), _cause(cause) {
}
std::string RuntimeException::getMessage() const {
return _message;
}
std::shared_ptr<RuntimeException> RuntimeException::getCause() const {
return _cause;
}
const char* RuntimeException::what() const noexcept {
return _message.c_str();
}
//------------------ IOException ---------------------------------------------------------------------------------------
IOException::IOException(RuntimeException *cause) : IOException("", cause) {
}
IOException::IOException(const std::string &msg, RuntimeException *cause) : std::exception(), _message(msg), _cause(cause) {
}
std::string IOException::getMessage() const {
return _message;
}
std::shared_ptr<RuntimeException> IOException::getCause() const {
return _cause;
}
const char* IOException::what() const noexcept {
return _message.c_str();
}

View File

@ -35,73 +35,67 @@ namespace antlr {
namespace v4 {
namespace runtime {
class ANTLRException : public std::exception {
// An exception hierarchy modelled loosely after java.lang.* exceptions.
class RuntimeException : public std::exception {
private:
std::wstring errormsg;
std::string _message;
std::shared_ptr<RuntimeException> _cause; // Optionally assigned if this exception is wrapping another one.
public:
ANTLRException() {}
ANTLRException(const std::wstring msg) {
this->errormsg = msg;
}
std::wstring getMessage() const {
return errormsg;
}
RuntimeException(RuntimeException *cause = nullptr);
RuntimeException(const std::string &msg, RuntimeException *cause = nullptr);
std::string getMessage() const;
std::shared_ptr<RuntimeException> getCause() const;
virtual const char* what() const noexcept override;
};
class IllegalClassException : public ANTLRException {
class IllegalStateException : public RuntimeException {
public:
IllegalClassException(const std::wstring msg) : ANTLRException(msg) {};
IllegalClassException() {};
IllegalStateException(RuntimeException *cause = nullptr) : IllegalStateException("", cause) {};
IllegalStateException(const std::string &msg, RuntimeException *cause = nullptr) : RuntimeException(msg, cause) {};
};
class IllegalStateException : public ANTLRException {
class IllegalArgumentException : public RuntimeException {
public:
IllegalStateException(const std::wstring msg) : ANTLRException(msg) {};
IllegalStateException(){};
IllegalArgumentException(RuntimeException *cause = nullptr) : IllegalArgumentException("", cause) {};
IllegalArgumentException(const std::string &msg, RuntimeException *cause = nullptr) : RuntimeException(msg, cause) {};
};
class IllegalArgumentException : public ANTLRException {
class NullPointerException : public RuntimeException {
public:
IllegalArgumentException(const std::wstring msg) : ANTLRException(msg) {};
IllegalArgumentException(const std::wstring msg, std::exception e);
IllegalArgumentException(){};
NullPointerException(RuntimeException *cause = nullptr) : NullPointerException("", cause) {};
NullPointerException(const std::string &msg, RuntimeException *cause = nullptr) : RuntimeException(msg, cause) {};
};
class NoSuchElementException : public ANTLRException {
class IndexOutOfBoundsException : public RuntimeException {
public:
NoSuchElementException(const std::wstring msg) : ANTLRException(msg) {};
NoSuchElementException(){};
IndexOutOfBoundsException(RuntimeException *cause = nullptr) : IndexOutOfBoundsException("", cause) {};
IndexOutOfBoundsException(const std::string &msg, RuntimeException *cause = nullptr) : RuntimeException(msg, cause) {};
};
class NullPointerException : public ANTLRException {
class UnsupportedOperationException : public RuntimeException {
public:
NullPointerException(const std::wstring msg) : ANTLRException(msg) {};
NullPointerException(){};
UnsupportedOperationException(RuntimeException *cause = nullptr) : UnsupportedOperationException("", cause) {};
UnsupportedOperationException(const std::string &msg, RuntimeException *cause = nullptr) : RuntimeException(msg, cause) {};
};
class IndexOutOfBoundsException : public ANTLRException {
public:
IndexOutOfBoundsException(const std::wstring msg) : ANTLRException(msg) {};
IndexOutOfBoundsException(){};
};
// IOException is not a runtime exception (in the java hierarchy).
// Hence we have to duplicate the RuntimeException implementation.
class IOException : public std::exception {
private:
std::string _message;
std::shared_ptr<RuntimeException> _cause; // Optionally assigned if this exception is wrapping another one.
class UnsupportedOperationException : public ANTLRException {
public:
UnsupportedOperationException(const std::wstring msg) : ANTLRException(msg) {};
UnsupportedOperationException(){};
};
IOException(RuntimeException *cause = nullptr);
IOException(const std::string &msg, RuntimeException *cause = nullptr);
class IOException : public ANTLRException {
public:
IOException(const std::wstring msg) : ANTLRException(msg) {};
IOException(){};
};
std::string getMessage() const;
std::shared_ptr<RuntimeException> getCause() const;
class ASSERTException : public ANTLRException {
public:
ASSERTException(const std::wstring location, const std::wstring condition) : ANTLRException(location + L" condition= " + condition) {};
virtual const char* what() const noexcept override;
};
} // namespace runtime

View File

@ -39,46 +39,38 @@
using namespace org::antlr::v4::runtime;
FailedPredicateException::FailedPredicateException(Parser *recognizer) : RecognitionException() {
FailedPredicateException::FailedPredicateException(Parser *recognizer) : FailedPredicateException(recognizer, "", "") {
}
FailedPredicateException::FailedPredicateException(Parser *recognizer, const std::wstring &predicate): RecognitionException() {
FailedPredicateException::FailedPredicateException(Parser *recognizer, const std::string &predicate): FailedPredicateException(recognizer, predicate, "") {
}
FailedPredicateException::FailedPredicateException(Parser *recognizer, const std::wstring &predicate, const std::wstring &message)
#ifdef TODO
// Huston, a problem. "trans" isn't defined until below
: RecognitionException(formatMessage(predicate, message), recognizer, recognizer->getInputStream(), recognizer->_ctx), ruleIndex((static_cast<atn::PredicateTransition*>(trans))->ruleIndex), predicateIndex((static_cast<atn::PredicateTransition*>(trans))->predIndex), predicate(predicate)
#endif
FailedPredicateException::FailedPredicateException(Parser *recognizer, const std::string &predicate, const std::string &message)
: RecognitionException(!message.empty() ? message : "failed predicate: " + predicate + "?", recognizer,
recognizer->getInputStream(), recognizer->ctx, recognizer->getCurrentToken()) {
{
atn::ATNState *s = recognizer->getInterpreter()->atn.states[(size_t)recognizer->getState()];
atn::AbstractPredicateTransition *trans = static_cast<atn::AbstractPredicateTransition*>(s->transition(0));
if (dynamic_cast<atn::PredicateTransition*>(trans) != nullptr) {
} else {
this->ruleIndex = 0;
this->predicateIndex = 0;
atn::ATNState *s = recognizer->getInterpreter<atn::ATNSimulator>()->atn.states[(size_t)recognizer->getState()];
atn::Transition *transition = s->transition(0);
if (dynamic_cast<atn::PredicateTransition*>(transition) != nullptr) {
_ruleIndex = ((atn::PredicateTransition *)transition)->ruleIndex;
_predicateIndex = ((atn::PredicateTransition *)transition)->predIndex;
}
else {
_ruleIndex = 0;
_predicateIndex = 0;
}
this->setOffendingToken(recognizer->getCurrentToken());
_predicate = predicate;
}
int FailedPredicateException::getRuleIndex() {
return ruleIndex;
return _ruleIndex;
}
int FailedPredicateException::getPredIndex() {
return predicateIndex;
return _predicateIndex;
}
std::wstring FailedPredicateException::getPredicate() {
return predicate;
}
std::wstring FailedPredicateException::formatMessage(const std::wstring &predicate, const std::wstring &message) {
if (message != L"") {
return message;
}
return L"failed predicate: " + predicate + L"?";
std::string FailedPredicateException::getPredicate() {
return _predicate;
}

View File

@ -38,33 +38,24 @@ namespace antlr {
namespace v4 {
namespace runtime {
/// <summary>
/// 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.
/// </summary>
/// occurs when normally parsing the alternative just like matching a token.
/// Disambiguating predicate evaluation occurs when we test a predicate during
/// prediction.
class FailedPredicateException : public RecognitionException {
private:
int ruleIndex;
int predicateIndex;
const std::wstring predicate;
public:
FailedPredicateException(Parser *recognizer); //this(recognizer, nullptr);
FailedPredicateException(Parser *recognizer, const std::wstring &predicate); //this(recognizer, predicate, nullptr);
FailedPredicateException(Parser *recognizer, const std::wstring &predicate, const std::wstring &message);
FailedPredicateException(Parser *recognizer);
FailedPredicateException(Parser *recognizer, const std::string &predicate);
FailedPredicateException(Parser *recognizer, const std::string &predicate, const std::string &message);
virtual int getRuleIndex();
virtual int getPredIndex();
virtual std::wstring getPredicate();
virtual std::string getPredicate();
private:
static std::wstring formatMessage(const std::wstring &predicate, const std::wstring &message);
int _ruleIndex;
int _predicateIndex;
std::string _predicate;
};
} // namespace runtime

View File

@ -36,6 +36,5 @@
using namespace org::antlr::v4::runtime;
InputMismatchException::InputMismatchException(Parser *recognizer)
: RecognitionException(recognizer, recognizer->getInputStream(), recognizer->ctx) {
this->setOffendingToken(recognizer->getCurrentToken());
: RecognitionException(recognizer, recognizer->getInputStream(), recognizer->ctx, recognizer->getCurrentToken()) {
}

View File

@ -58,7 +58,7 @@ namespace runtime {
/// reached.
/// </summary>
public:
// EOF Conflict with OS X, change to _EOF
// EOF Conflict with OS X, change to _EOF
static const size_t _EOF = std::ios::eofbit;
/// <summary>

View File

@ -36,6 +36,7 @@
#include "LexerNoViableAltException.h"
#include "stringconverter.h"
#include "StringBuilder.h"
#include "ANTLRErrorListener.h"
#include "Lexer.h"
@ -68,12 +69,12 @@ void Lexer::reset() {
_mode = Lexer::DEFAULT_MODE;
_modeStack.clear();
getInterpreter()->reset();
getInterpreter<atn::LexerATNSimulator>()->reset();
}
Token *Lexer::nextToken() {
if (_input == nullptr) {
throw new IllegalStateException(L"nextToken requires a non-null input stream.");
throw new IllegalStateException("nextToken requires a non-null input stream.");
}
// Mark start location in char stream so unbuffered streams are
@ -90,17 +91,14 @@ Token *Lexer::nextToken() {
delete _token;
_channel = Token::DEFAULT_CHANNEL;
_tokenStartCharIndex = (int)_input->index();
_tokenStartCharPositionInLine = getInterpreter()->getCharPositionInLine();
_tokenStartLine = (int)getInterpreter()->getLine();
_tokenStartCharPositionInLine = getInterpreter<atn::LexerATNSimulator>()->getCharPositionInLine();
_tokenStartLine = (int)getInterpreter<atn::LexerATNSimulator>()->getLine();
_text = L"";
do {
_type = Token::INVALID_TYPE;
// System.out.println("nextToken line "+tokenStartLine+" at "+((char)input.LA(1))+
// " in mode "+mode+
// " at index "+input.index());
int ttype;
try {
ttype = getInterpreter()->match(_input, (size_t)_mode);
ttype = getInterpreter<atn::LexerATNSimulator>()->match(_input, (size_t)_mode);
} catch (LexerNoViableAltException *e) {
notifyListeners(e); // report error
recover(e);
@ -214,19 +212,19 @@ Token *Lexer::emitEOF() {
}
size_t Lexer::getLine() const {
return getInterpreter()->getLine();
return getInterpreter<atn::LexerATNSimulator>()->getLine();
}
int Lexer::getCharPositionInLine() {
return getInterpreter()->getCharPositionInLine();
return getInterpreter<atn::LexerATNSimulator>()->getCharPositionInLine();
}
void Lexer::setLine(size_t line) {
getInterpreter()->setLine(line);
getInterpreter<atn::LexerATNSimulator>()->setLine(line);
}
void Lexer::setCharPositionInLine(int charPositionInLine) {
getInterpreter()->setCharPositionInLine(charPositionInLine);
getInterpreter<atn::LexerATNSimulator>()->setCharPositionInLine(charPositionInLine);
}
int Lexer::getCharIndex() {
@ -237,7 +235,7 @@ std::wstring Lexer::getText() {
if (_text != L"") {
return _text;
}
return getInterpreter()->getText(_input);
return getInterpreter<atn::LexerATNSimulator>()->getText(_input);
}
void Lexer::setText(const std::wstring &text) {
@ -281,7 +279,7 @@ std::vector<Token*> Lexer::getAllTokens() {
void Lexer::recover(LexerNoViableAltException *e) {
if (_input->LA(1) != IntStream::_EOF) {
// skip a char and try again
getInterpreter()->consume(_input);
getInterpreter<atn::LexerATNSimulator>()->consume(_input);
}
}

View File

@ -34,19 +34,18 @@
#include "Recognizer.h"
#include "TokenSource.h"
#include "CharStream.h"
#include "Token.h"
namespace org {
namespace antlr {
namespace v4 {
namespace runtime {
/// <summary>
/// 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.
/// </summary>
class Lexer : public Recognizer<atn::LexerATNSimulator>, public TokenSource {
class Lexer : public Recognizer, public TokenSource {
public:
static const int DEFAULT_MODE = 0;
static const int MORE = -2;
@ -110,10 +109,8 @@ namespace runtime {
std::vector<int> _modeStack;
int _mode;
/// <summary>
/// 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.
/// </summary>
/// the input char buffer. Use setText() or can set this instance var.
std::wstring _text;
Lexer();
@ -122,19 +119,14 @@ namespace runtime {
virtual void reset();
/// <summary>
/// Return a token from this source; i.e., match a token on the char
/// stream.
/// </summary>
/// Return a token from this source; i.e., match a token on the char stream.
virtual Token *nextToken() override;
/// <summary>
/// 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.
/// </summary>
/// 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.
virtual void skip();
virtual void more();

View File

@ -34,6 +34,7 @@
#include "DFA.h"
#include "PredictionContextCache.h"
#include "EmptyPredictionContext.h"
#include "Exceptions.h"
#include "LexerInterpreter.h"
@ -42,7 +43,7 @@ using namespace org::antlr::v4::runtime;
LexerInterpreter::LexerInterpreter(const std::wstring &grammarFileName, std::vector<std::wstring> *tokenNames, std::vector<std::wstring> *ruleNames, std::vector<std::wstring> *modeNames, const atn::ATN &atn, CharStream *input) : Lexer(input), grammarFileName(grammarFileName), _atn(atn), _sharedContextCache(new atn::PredictionContextCache()) {
if (_atn.grammarType != atn::ATNType::LEXER) {
throw new IllegalArgumentException(L"The ATN must be a lexer ATN.");
throw new IllegalArgumentException("The ATN must be a lexer ATN.");
}

View File

@ -32,30 +32,28 @@
#include "Interval.h"
#include "CPPUtils.h"
#include "CharStream.h"
#include "Lexer.h"
#include "LexerNoViableAltException.h"
using namespace org::antlr::v4::runtime;
LexerNoViableAltException::LexerNoViableAltException(Lexer *lexer, CharStream *input, size_t startIndex, atn::ATNConfigSet *deadEndConfigs) : RecognitionException()/*TODO RecognitionException(lexer, input, nullptr)*/, startIndex(startIndex), deadEndConfigs(deadEndConfigs) {
LexerNoViableAltException::LexerNoViableAltException(Lexer *lexer, CharStream *input, size_t startIndex, atn::ATNConfigSet *deadEndConfigs)
: RecognitionException(lexer, input, nullptr, nullptr), _startIndex(startIndex), _deadEndConfigs(deadEndConfigs) {
}
size_t LexerNoViableAltException::getStartIndex() {
return startIndex;
return _startIndex;
}
atn::ATNConfigSet *LexerNoViableAltException::getDeadEndConfigs() {
return deadEndConfigs;
}
CharStream *LexerNoViableAltException::getInputStream() {
return (CharStream*)(RecognitionException::getInputStream());
std::shared_ptr<atn::ATNConfigSet> LexerNoViableAltException::getDeadEndConfigs() {
return _deadEndConfigs;
}
std::wstring LexerNoViableAltException::toString() {
std::wstring symbol = L"";
if (startIndex < getInputStream()->size()) {
symbol = getInputStream()->getText(misc::Interval((int)startIndex, (int)startIndex));
std::wstring symbol;
if (_startIndex < getInputStream()->size()) {
symbol = ((CharStream *)getInputStream().get())->getText(misc::Interval((int)_startIndex, (int)_startIndex));
symbol = antlrcpp::escapeWhitespace(symbol, false);
}
std::wstring format = L"LexerNoViableAltException('" + symbol + L"')";

View File

@ -32,7 +32,7 @@
#pragma once
#include "RecognitionException.h"
#include "CharStream.h"
#include "ATNConfigSet.h"
namespace org {
namespace antlr {
@ -40,25 +40,20 @@ namespace v4 {
namespace runtime {
class LexerNoViableAltException : public RecognitionException {
/// <summary>
/// Matching attempted at what input index? </summary>
private:
const size_t startIndex;
/// <summary>
/// Which configurations did we try at input.index() that couldn't match input.LA(1)? </summary>
atn::ATNConfigSet *const deadEndConfigs;
public:
LexerNoViableAltException(Lexer *lexer, CharStream *input, size_t startIndex, atn::ATNConfigSet *deadEndConfigs);
virtual size_t getStartIndex();
virtual atn::ATNConfigSet *getDeadEndConfigs();
virtual CharStream *getInputStream() override;
virtual std::shared_ptr<atn::ATNConfigSet> getDeadEndConfigs();
virtual std::wstring toString();
private:
/// Matching attempted at what input index?
const size_t _startIndex;
/// Which configurations did we try at input.index() that couldn't match input.LA(1)?
std::shared_ptr<atn::ATNConfigSet> _deadEndConfigs;
};
} // namespace runtime

View File

@ -35,19 +35,20 @@
using namespace org::antlr::v4::runtime;
NoViableAltException::NoViableAltException(Parser *recognizer) :deadEndConfigs(nullptr), startToken(nullptr) {
NoViableAltException::NoViableAltException(Parser *recognizer)
: NoViableAltException(recognizer, recognizer->getInputStream(), recognizer->getCurrentToken(), recognizer->getCurrentToken(),
nullptr, recognizer->ctx) {
}
NoViableAltException::NoViableAltException(Parser *recognizer, TokenStream *input, Token *startToken,
Token *offendingToken, atn::ATNConfigSet *deadEndConfigs, ParserRuleContext *ctx)
: RecognitionException(recognizer, input, ctx), deadEndConfigs(deadEndConfigs), startToken(startToken) {
this->setOffendingToken(offendingToken);
: RecognitionException(recognizer, input, ctx, offendingToken), deadEndConfigs(deadEndConfigs), startToken(startToken) {
}
Token *NoViableAltException::getStartToken() {
std::shared_ptr<Token> NoViableAltException::getStartToken() {
return startToken;
}
atn::ATNConfigSet *NoViableAltException::getDeadEndConfigs() {
std::shared_ptr<atn::ATNConfigSet> NoViableAltException::getDeadEndConfigs() {
return deadEndConfigs;
}

View File

@ -32,41 +32,36 @@
#pragma once
#include "RecognitionException.h"
#include "Token.h"
#include "ATNConfigSet.h"
namespace org {
namespace antlr {
namespace v4 {
namespace runtime {
/// <summary>
/// Indicates that the parser could not decide which of two or more paths
/// to take based upon the remaining input. It tracks the starting token
/// of the offending input and also knows where the parser was
/// in the various paths when the error. Reported by reportNoViableAlternative()
/// </summary>
/// to take based upon the remaining input. It tracks the starting token
/// of the offending input and also knows where the parser was
/// in the various paths when the error. Reported by reportNoViableAlternative()
class NoViableAltException : public RecognitionException {
/// <summary>
/// Which configurations did we try at input.index() that couldn't match input.LT(1)? </summary>
private:
atn::ATNConfigSet *const deadEndConfigs;
/// Which configurations did we try at input.index() that couldn't match input.LT(1)?
std::shared_ptr<atn::ATNConfigSet> deadEndConfigs;
/// <summary>
/// The token object at the start index; the input stream might
/// not be buffering tokens so get a reference to it. (At the
/// time the error occurred, of course the stream needs to keep a
/// buffer all of the tokens but later we might not have access to those.)
/// </summary>
Token *const startToken;
/// not be buffering tokens so get a reference to it. (At the
/// time the error occurred, of course the stream needs to keep a
/// buffer all of the tokens but later we might not have access to those.)
std::shared_ptr<Token> startToken;
public:
NoViableAltException(Parser *recognizer); // LL(1) error - this(recognizer, recognizer.getInputStream(), recognizer.getCurrentToken(), recognizer.getCurrentToken(), nullptr, recognizer._ctx);
NoViableAltException(Parser *recognizer); // LL(1) error
NoViableAltException(Parser *recognizer, TokenStream *input, Token *startToken, Token *offendingToken,
atn::ATNConfigSet *deadEndConfigs, ParserRuleContext *ctx);
virtual Token *getStartToken();
virtual atn::ATNConfigSet *getDeadEndConfigs();
virtual std::shared_ptr<Token> getStartToken();
virtual std::shared_ptr<atn::ATNConfigSet> getDeadEndConfigs();
};

View File

@ -42,6 +42,9 @@
#include "ATNDeserializer.h"
#include "RuleTransition.h"
#include "ATN.h"
#include "Strings.h"
#include "Exceptions.h"
#include "ANTLRErrorListener.h"
#include "Parser.h"
@ -111,7 +114,7 @@ void Parser::reset() {
setTrace(false);
_precedenceStack.clear();
_precedenceStack.push_back(0);
atn::ATNSimulator *interpreter = getInterpreter();
atn::ATNSimulator *interpreter = getInterpreter<atn::ParserATNSimulator>();
if (interpreter != nullptr) {
interpreter->reset();
}
@ -185,7 +188,7 @@ std::vector<tree::ParseTreeListener*> Parser::getParseListeners() {
void Parser::addParseListener(tree::ParseTreeListener *listener) {
if (listener == nullptr) {
throw NullPointerException(L"listener");
throw NullPointerException("listener");
}
if (_parseListeners.empty()) {
@ -236,7 +239,7 @@ TokenFactory<CommonToken*> *Parser::getTokenFactory() {
const atn::ATN& Parser::getATNWithBypassAlts() {
std::wstring serializedAtn = getSerializedATN();
if (serializedAtn.empty()) {
throw UnsupportedOperationException(L"The current parser does not support an ATN with bypass alternatives.");
throw UnsupportedOperationException("The current parser does not support an ATN with bypass alternatives.");
}
std::lock_guard<std::mutex> lck(mtx);
@ -263,7 +266,7 @@ tree::pattern::ParseTreePattern *Parser::compileParseTreePattern(const std::wstr
return compileParseTreePattern(pattern, patternRuleIndex, lexer);
}
}
throw UnsupportedOperationException(L"Parser can't discover a lexer to use");
throw UnsupportedOperationException("Parser can't discover a lexer to use");
}
tree::pattern::ParseTreePattern *Parser::compileParseTreePattern(const std::wstring &pattern, int patternRuleIndex, Lexer *lexer) {
@ -470,7 +473,7 @@ bool Parser::inContext(const std::wstring &context) {
}
bool Parser::isExpectedToken(int symbol) {
const atn::ATN &atn = getInterpreter()->atn;
const atn::ATN &atn = getInterpreter<atn::ParserATNSimulator>()->atn;
ParserRuleContext *ctx = ctx;
atn::ATNState *s = atn.states[(size_t)getState()];
misc::IntervalSet following = atn.nextTokens(s);
@ -506,7 +509,7 @@ misc::IntervalSet Parser::getExpectedTokens() {
}
misc::IntervalSet Parser::getExpectedTokensWithinCurrentRule() {
const atn::ATN &atn = getInterpreter()->atn;
const atn::ATN &atn = getInterpreter<atn::ParserATNSimulator>()->atn;
atn::ATNState *s = atn.states[(size_t)getState()];
return atn.nextTokens(s);
}
@ -544,11 +547,13 @@ std::vector<std::wstring> Parser::getRuleInvocationStack(RuleContext *p) {
}
std::vector<std::wstring> Parser::getDFAStrings() {
if (!_interpreter->_decisionToDFA.empty()) {
atn::ParserATNSimulator *simulator = getInterpreter<atn::ParserATNSimulator>();
if (!simulator->_decisionToDFA.empty()) {
std::lock_guard<std::mutex> lck(mtx);
std::vector<std::wstring> s = std::vector<std::wstring>();
for (size_t d = 0; d < _interpreter->_decisionToDFA.size(); d++) {
dfa::DFA *dfa = _interpreter->_decisionToDFA[d];
std::vector<std::wstring> s;
for (size_t d = 0; d < simulator->_decisionToDFA.size(); d++) {
dfa::DFA *dfa = simulator->_decisionToDFA[d];
s.push_back(dfa->toString(getTokenNames()));
}
return s;
@ -557,12 +562,12 @@ std::vector<std::wstring> Parser::getDFAStrings() {
}
void Parser::dumpDFA() {
if (!_interpreter->_decisionToDFA.empty()) {
atn::ParserATNSimulator *simulator = getInterpreter<atn::ParserATNSimulator>();
if (!simulator->_decisionToDFA.empty()) {
std::lock_guard<std::mutex> lck(mtx);
bool seenOne = false;
for (size_t d = 0; d < _interpreter->_decisionToDFA.size(); d++) {
dfa::DFA *dfa = _interpreter->_decisionToDFA[d];
for (size_t d = 0; d < simulator->_decisionToDFA.size(); d++) {
dfa::DFA *dfa = simulator->_decisionToDFA[d];
if (!dfa->states->empty()) {
if (seenOne) {
std::cout << std::endl;

View File

@ -42,15 +42,11 @@ namespace antlr {
namespace v4 {
namespace runtime {
/// <summary>
/// This is all the parsing support code essentially; most of it is error recovery stuff. </summary>
class Parser : public Recognizer<atn::ParserATNSimulator> {
/// This is all the parsing support code essentially; most of it is error recovery stuff.
class Parser : public Recognizer {
public:
class TraceListener : public tree::ParseTreeListener {
private:
Parser *const outerInstance;
public:
TraceListener(Parser *outerInstance);
virtual ~TraceListener() {};
@ -59,6 +55,9 @@ namespace runtime {
virtual void visitTerminal(tree::TerminalNode *node) override;
virtual void visitErrorNode(tree::ErrorNode *node) override;
virtual void exitEveryRule(ParserRuleContext *ctx) override;
private:
Parser *const outerInstance;
};
class TrimToSizeListener : public tree::ParseTreeListener {

View File

@ -45,6 +45,7 @@
#include "ActionTransition.h"
#include "ATN.h"
#include "RuleStopState.h"
#include "Token.h"
#include "ParserInterpreter.h"
@ -52,8 +53,8 @@ using namespace org::antlr::v4::runtime;
ParserInterpreter::ParserInterpreter(const std::wstring &grammarFileName, const std::vector<std::wstring>& tokenNames,
const std::vector<std::wstring>& ruleNames, const atn::ATN& atn, TokenStream *input)
: Parser(input), grammarFileName(grammarFileName), _tokenNames(tokenNames), _atn(atn), _ruleNames(ruleNames), pushRecursionContextStates(new antlrcpp::BitSet()), sharedContextCache(new atn::PredictionContextCache()), _parentContextStack(new std::deque<std::pair<ParserRuleContext *, int>*>()) {
: Parser(input), grammarFileName(grammarFileName),
_tokenNames(tokenNames), _atn(atn), _ruleNames(ruleNames), sharedContextCache(new atn::PredictionContextCache()), _parentContextStack(new std::deque<std::pair<ParserRuleContext *, int>*>()) {
for (int i = 0; i < _atn.getNumberOfDecisions(); i++) {
_decisionToDFA.push_back(new dfa::DFA(_atn.getDecisionState(i), i));
@ -76,7 +77,7 @@ ParserInterpreter::ParserInterpreter(const std::wstring &grammarFileName, const
}
if (maybeLoopEndState->epsilonOnlyTransitions && dynamic_cast<atn::RuleStopState*>(maybeLoopEndState->transition(0)->target) != nullptr) {
this->pushRecursionContextStates->set((size_t)state->stateNumber);
_pushRecursionContextStates.set((size_t)state->stateNumber);
}
}
@ -146,7 +147,7 @@ atn::ATNState *ParserInterpreter::getATNState() {
void ParserInterpreter::visitState(atn::ATNState *p) {
int edge;
if (p->getNumberOfTransitions() > 1) {
edge = getInterpreter()->adaptivePredict(_input, ((atn::DecisionState*)p)->decision, ctx);
edge = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, ((atn::DecisionState*)p)->decision, ctx);
} else {
edge = 1;
}
@ -154,7 +155,7 @@ void ParserInterpreter::visitState(atn::ATNState *p) {
atn::Transition *transition = p->transition((size_t)edge - 1);
switch (transition->getSerializationType()) {
case atn::Transition::EPSILON:
if (pushRecursionContextStates->data[(size_t)p->stateNumber] == 1 && !(dynamic_cast<atn::LoopEndState*>(transition->target) != nullptr)) {
if (_pushRecursionContextStates.data[(size_t)p->stateNumber] == 1 && !(dynamic_cast<atn::LoopEndState*>(transition->target) != nullptr)) {
InterpreterRuleContext *ruleContext = new InterpreterRuleContext(_parentContextStack->front()->first, _parentContextStack->front()->second, ctx->getRuleIndex());
pushNewRecursionContext(ruleContext, _atn.ruleToStartState[(size_t)p->ruleIndex]->stateNumber, (int)ruleContext->getRuleIndex());
}
@ -209,13 +210,13 @@ void ParserInterpreter::visitState(atn::ATNState *p) {
case atn::Transition::PRECEDENCE:
{
if (!precpred(ctx, ((atn::PrecedencePredicateTransition*)(transition))->precedence)) {
throw new FailedPredicateException(this, L"precpred(_ctx, " + std::to_wstring(((atn::PrecedencePredicateTransition*)(transition))->precedence) + L")");
throw new FailedPredicateException(this, "precpred(_ctx, " + std::to_string(((atn::PrecedencePredicateTransition*)(transition))->precedence) + ")");
}
}
break;
default:
throw UnsupportedOperationException(L"Unrecognized ATN transition type.");
throw UnsupportedOperationException("Unrecognized ATN transition type.");
}
setState(transition->target->stateNumber);

View File

@ -33,6 +33,7 @@
#include "Parser.h"
#include "ATN.h"
#include "BitSet.h"
namespace org {
namespace antlr {
@ -63,7 +64,7 @@ namespace runtime {
const atn::ATN &_atn;
std::vector<std::wstring> _ruleNames;
antlrcpp::BitSet *const pushRecursionContextStates;
antlrcpp::BitSet _pushRecursionContextStates;
std::vector<dfa::DFA *> _decisionToDFA; // not shared like it is for generated parsers
atn::PredictionContextCache *const sharedContextCache;
@ -83,18 +84,16 @@ namespace runtime {
virtual std::wstring getGrammarFileName() const override;
/// <summary>
/// Begin parsing at startRuleIndex </summary>
/// Begin parsing at startRuleIndex
virtual ParserRuleContext *parse(int startRuleIndex);
virtual void enterRecursionRule(ParserRuleContext *localctx, int state, int ruleIndex, int precedence) override;
protected:
virtual atn::ATNState *getATNState();
virtual void visitState(atn::ATNState *p);
virtual void visitRuleStopState(atn::ATNState *p);
};
} // namespace runtime

View File

@ -32,6 +32,8 @@
#include "ErrorNodeImpl.h"
#include "Interval.h"
#include "Parser.h"
#include "Token.h"
#include "CPPUtils.h"
#include "ParserRuleContext.h"

View File

@ -39,12 +39,9 @@ namespace antlr {
namespace v4 {
namespace runtime {
/// <summary>
/// This implementation of <seealso cref="ANTLRErrorListener"/> dispatches all calls to a
/// This implementation of ANTLRErrorListener dispatches all calls to a
/// collection of delegate listeners. This reduces the effort required to support multiple
/// listeners.
/// </summary>
class ProxyErrorListener : public ANTLRErrorListener {
private:
std::vector<ANTLRErrorListener*> *const delegates;
@ -53,9 +50,8 @@ namespace runtime {
template<typename T1> //where T1 : ANTLRErrorListener
ProxyErrorListener(std::vector<T1> *delegates) : delegates(delegates) {
if (delegates == nullptr) {
throw new NullPointerException(L"delegates");
throw new NullPointerException("delegates");
}
}
void syntaxError(IRecognizer *recognizer, void *offendingSymbol, size_t line, int charPositionInLine,

View File

@ -31,20 +31,20 @@
#include "ATN.h"
#include "Recognizer.h"
#include "Strings.h"
#include "ParserRuleContext.h"
#include "RecognitionException.h"
using namespace org::antlr::v4::runtime;
RecognitionException::RecognitionException() : RecognitionException(L"", nullptr, nullptr, nullptr) {
RecognitionException::RecognitionException(IRecognizer *recognizer, IntStream *input, ParserRuleContext *ctx, Token *offendingToken)
: RecognitionException("", recognizer, input, ctx, offendingToken) {
}
RecognitionException::RecognitionException(IRecognizer *recognizer, IntStream *input, ParserRuleContext * const ctx)
: RecognitionException(L"", recognizer, input, ctx) {
}
RecognitionException::RecognitionException(const std::wstring &message, IRecognizer *recognizer, IntStream *input, ParserRuleContext *ctx)
: _message(message), _recognizer(recognizer), _input(input), _ctx((RuleContext * const)ctx) {
RecognitionException::RecognitionException(const std::string &message, IRecognizer *recognizer, IntStream *input,
ParserRuleContext *ctx, Token *offendingToken)
: RuntimeException(message), _recognizer(recognizer), _input(input), _offendingToken(offendingToken), _ctx(ctx) {
InitializeInstanceFields();
if (recognizer != nullptr) {
_offendingState = recognizer->getState();
@ -60,32 +60,41 @@ void RecognitionException::setOffendingState(int offendingState) {
}
misc::IntervalSet RecognitionException::getExpectedTokens() {
if (_recognizer != nullptr) {
return _recognizer->getATN().getExpectedTokens(_offendingState, _ctx);
if (_recognizer) {
return _recognizer->getATN().getExpectedTokens(_offendingState, _ctx.get());
}
return misc::IntervalSet::EMPTY_SET;
}
RuleContext *RecognitionException::getCtx() {
std::shared_ptr<RuleContext> RecognitionException::getCtx() {
return _ctx;
}
IntStream *RecognitionException::getInputStream() {
std::shared_ptr<IntStream> RecognitionException::getInputStream() {
return _input;
}
Token *RecognitionException::getOffendingToken() {
std::shared_ptr<Token> RecognitionException::getOffendingToken() {
return _offendingToken;
}
void RecognitionException::setOffendingToken(Token *offendingToken) {
_offendingToken = offendingToken;
}
IRecognizer *RecognitionException::getRecognizer() {
std::shared_ptr<IRecognizer> RecognitionException::getRecognizer() {
return _recognizer;
}
void RecognitionException::InitializeInstanceFields() {
_offendingState = -1;
}
//------------------ ParseCancellationException ------------------------------------------------------------------------
ParseCancellationException::ParseCancellationException() : ParseCancellationException("", nullptr) {
}
ParseCancellationException::ParseCancellationException(RecognitionException *cause)
: ParseCancellationException("", cause) {
}
ParseCancellationException::ParseCancellationException(const std::string &msg, RecognitionException *cause)
: IllegalStateException(msg, cause) {
}

View File

@ -33,73 +33,60 @@
#include "Exceptions.h"
#include "IntervalSet.h"
#include "IRecognizer.h"
#include "IntStream.h"
#include "RuleContext.h"
#include "Token.h"
namespace org {
namespace antlr {
namespace v4 {
namespace runtime {
class RuntimeException : public ANTLRException {
public:
RuntimeException(const std::wstring msg) : ANTLRException(msg) {}
RuntimeException() {};
};
/// <summary>
/// The root of the ANTLR exception hierarchy. In general, ANTLR tracks just
/// 3 kinds of errors: prediction errors, failed predicate errors, and
/// mismatched input errors. In each case, the parser knows where it is
/// in the input, where it is in the ATN, the rule invocation stack,
/// and what kind of problem occurred.
/// </summary>
/// 3 kinds of errors: prediction errors, failed predicate errors, and
/// mismatched input errors. In each case, the parser knows where it is
/// in the input, where it is in the ATN, the rule invocation stack,
/// and what kind of problem occurred.
class RecognitionException : public RuntimeException {
/// <summary>
/// The <seealso cref="Recognizer"/> where this exception originated. </summary>
private:
// Hairy wildcard generics from Java, attempt to fix with a raw void*
// Recognizer<void, void> *const recognizer;
IRecognizer *_recognizer;
IntStream * const _input;
RuleContext * const _ctx;
const std::wstring _message;
/// The Recognizer where this exception originated.
std::shared_ptr<IRecognizer> _recognizer;
std::shared_ptr<IntStream> _input;
std::shared_ptr<RuleContext> _ctx;
/// <summary>
/// The current <seealso cref="Token"/> when an error occurred. Since not all streams
/// support accessing symbols by index, we have to track the <seealso cref="Token"/>
/// The current Token when an error occurred. Since not all streams
/// support accessing symbols by index, we have to track the Token
/// instance itself.
/// </summary>
Token *_offendingToken;
std::shared_ptr<Token> _offendingToken;
int _offendingState;
public:
RecognitionException();
RecognitionException(IRecognizer *recognizer, IntStream *input, ParserRuleContext * const ctx);
RecognitionException(const std::wstring &message, IRecognizer *recognizer, IntStream *input, ParserRuleContext *ctx);
RecognitionException(IRecognizer *recognizer, IntStream *input, ParserRuleContext *ctx, Token *offendingToken = nullptr);
RecognitionException(const std::string &message, IRecognizer *recognizer, IntStream *input, ParserRuleContext *ctx,
Token *offendingToken = nullptr);
/// <summary>
/// Get the ATN state number the parser was in at the time the error
/// occurred. For <seealso cref="NoViableAltException"/> and
/// <seealso cref="LexerNoViableAltException"/> exceptions, this is the
/// <seealso cref="DecisionState"/> number. For others, it is the state whose outgoing
/// occurred. For NoViableAltException and
/// LexerNoViableAltException exceptions, this is the
/// DecisionState number. For others, it is the state whose outgoing
/// edge we couldn't match.
/// <p/>
///
/// If the state number is not known, this method returns -1.
/// </summary>
virtual int getOffendingState();
protected:
void setOffendingState(int offendingState);
/// <summary>
/// Gets the set of input symbols which could potentially follow the
/// previously matched symbol at the time this exception was thrown.
/// <p/>
///
/// If the set of expected tokens is not known and could not be computed,
/// this method returns {@code null}.
/// </summary>
/// <returns> The set of token types that could potentially follow the current
/// state in the ATN, or {@code null} if the information is not available. </returns>
/// this method returns an empty set.
///
/// @returns The set of token types that could potentially follow the current
/// state in the ATN, or an empty set if the information is not available.
public:
virtual misc::IntervalSet getExpectedTokens();
@ -110,7 +97,7 @@ namespace runtime {
/// </summary>
/// <returns> The <seealso cref="RuleContext"/> at the time this exception was thrown.
/// If the context is not available, this method returns {@code null}. </returns>
virtual RuleContext *getCtx();
virtual std::shared_ptr<RuleContext> getCtx();
/// <summary>
/// Gets the input stream which is the symbol source for the recognizer where
@ -121,12 +108,9 @@ namespace runtime {
/// <returns> The input stream which is the symbol source for the recognizer
/// where this exception was thrown, or {@code null} if the stream is not
/// available. </returns>
virtual IntStream *getInputStream();
virtual std::shared_ptr<IntStream> getInputStream();
virtual Token *getOffendingToken();
protected:
void setOffendingToken(Token *offendingToken);
virtual std::shared_ptr<Token> getOffendingToken();
/// <summary>
/// Gets the <seealso cref="Recognizer"/> where this exception occurred.
@ -135,26 +119,28 @@ namespace runtime {
/// </summary>
/// <returns> The recognizer where this exception occurred, or {@code null} if
/// the recognizer is not available. </returns>
public:
virtual IRecognizer *getRecognizer();
virtual std::shared_ptr<IRecognizer> getRecognizer();
private:
void InitializeInstanceFields();
};
// Recognition exceptions, TODO fill out the code
class ParseCancellationException : public RecognitionException {
/**
* This exception is thrown to cancel a parsing operation. This exception does
* not extend RecognitionException, allowing it to bypass the standard
* error recovery mechanisms. BailErrorStrategy throws this exception in
* response to a parse error.
*/
class ParseCancellationException : public IllegalStateException {
public:
ParseCancellationException(const std::wstring msg) {};
ParseCancellationException(RecognitionException*) {};
ParseCancellationException() {};
ParseCancellationException();
ParseCancellationException(RecognitionException *cause);
ParseCancellationException(const std::string &msg, RecognitionException *cause = nullptr);
};
class EmptyStackException : public RecognitionException {
class EmptyStackException : public RuntimeException {
public:
EmptyStackException(const std::wstring msg) {}
EmptyStackException() {};
EmptyStackException() : RuntimeException() {};
};
} // namespace runtime

View File

@ -0,0 +1,173 @@
/*
* [The "BSD license"]
* Copyright (c) 2016 Mike Lischke
* Copyright (c) 2013 Terence Parr
* Copyright (c) 2013 Dan McLaughlin
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "RecognitionException.h"
#include "CPPUtils.h"
#include "Strings.h"
#include "ProxyErrorListener.h"
#include "Token.h"
#include "CPPUtils.h"
#include "Recognizer.h"
using namespace org::antlr::v4::runtime;
std::map<std::vector<std::wstring>, std::map<std::wstring, int>> Recognizer::_tokenTypeMapCache;
std::map<std::vector<std::wstring>, std::map<std::wstring, int>> Recognizer::_ruleIndexMapCache;
std::map<std::wstring, int> Recognizer::getTokenTypeMap() {
const std::vector<std::wstring>& tokenNames = getTokenNames();
if (tokenNames.empty()) {
throw L"The current recognizer does not provide a list of token names.";
}
std::lock_guard<std::mutex> lck(mtx);
std::map<std::wstring, int> result;
auto iterator = _tokenTypeMapCache.find(tokenNames);
if (iterator != _tokenTypeMapCache.end()) {
result = iterator->second;
} else {
result = antlrcpp::toMap(tokenNames);
result[L"EOF"] = Token::_EOF;
_tokenTypeMapCache[tokenNames] = result;
}
return result;
}
std::map<std::wstring, int> Recognizer::getRuleIndexMap() {
const std::vector<std::wstring>& ruleNames = getRuleNames();
if (ruleNames.empty()) {
throw L"The current recognizer does not provide a list of rule names.";
}
std::lock_guard<std::mutex> lck(mtx);
std::map<std::wstring, int> result;
auto iterator = _ruleIndexMapCache.find(ruleNames);
if (iterator != _ruleIndexMapCache.end()) {
result = iterator->second;
} else {
result = antlrcpp::toMap(ruleNames);
_ruleIndexMapCache[ruleNames] = result;
}
return result;
}
int Recognizer::getTokenType(const std::wstring &tokenName) {
const std::map<std::wstring, int> &map = getTokenTypeMap();
auto iterator = map.find(tokenName);
if (iterator == map.end())
return Token::INVALID_TYPE;
return iterator->second;
}
std::wstring Recognizer::getErrorHeader(RecognitionException *e) {
// We're having issues with cross header dependencies, these two classes will need to be
// rewritten to remove that.
int line = e->getOffendingToken()->getLine();
int charPositionInLine = e->getOffendingToken()->getCharPositionInLine();
return std::wstring(L"line ") + std::to_wstring(line) + std::wstring(L":") + std::to_wstring(charPositionInLine);
}
std::wstring Recognizer::getTokenErrorDisplay(Token *t) {
if (t == nullptr) {
return L"<no token>";
}
std::wstring s = t->getText();
if (s == L"") {
if (t->getType() == Token::_EOF) {
s = L"<EOF>";
} else {
s = std::wstring(L"<") + std::to_wstring(t->getType()) + std::wstring(L">");
}
}
antlrcpp::replaceAll(s, L"\n", L"\\n");
antlrcpp::replaceAll(s, L"\r",L"\\r");
antlrcpp::replaceAll(s, L"\t", L"\\t");
return std::wstring(L"'") + s + std::wstring(L"'");
}
void Recognizer::addErrorListener(ANTLRErrorListener *listener) {
if (listener == nullptr) {
throw L"listener cannot be null.";
}
_listeners.insert(_listeners.end(), listener);
}
void Recognizer::removeErrorListener(ANTLRErrorListener *listener) {
//_listeners.remove(listener); does this work the same way?
std::vector<ANTLRErrorListener*>::iterator it;
it = std::find(_listeners.begin(), _listeners.end(), listener);
_listeners.erase(it);
}
void Recognizer::removeErrorListeners() {
_listeners.clear();
}
ANTLRErrorListener *Recognizer::getErrorListenerDispatch() {
return (ANTLRErrorListener *)new ProxyErrorListener(getErrorListeners());
}
bool Recognizer::sempred(RuleContext *_localctx, int ruleIndex, int actionIndex) {
return true;
}
bool Recognizer::precpred(RuleContext *localctx, int precedence) {
return true;
}
void Recognizer::action(RuleContext *_localctx, int ruleIndex, int actionIndex) {
}
int Recognizer::getState() {
return _stateNumber;
}
void Recognizer::setState(int atnState) {
_stateNumber = atnState;
// if ( traceATNStates ) _ctx.trace(atnState);
}
void Recognizer::InitializeInstanceFields() {
_stateNumber = -1;
_interpreter = nullptr;
_listeners = std::vector<ANTLRErrorListener*>();
}
Recognizer::Recognizer() {
InitializeInstanceFields();
}

View File

@ -38,7 +38,6 @@ namespace antlr {
namespace v4 {
namespace runtime {
template<typename ATNInterpreter>
class Recognizer : public IRecognizer {
public:
static const int _EOF = -1;
@ -55,7 +54,7 @@ namespace runtime {
std::mutex mtx;
protected:
ATNInterpreter *_interpreter; // Set and deleted in descendants.
atn::ATNSimulator *_interpreter; // Set and deleted in descendants.
private:
int _stateNumber;
@ -103,12 +102,11 @@ namespace runtime {
/// </summary>
virtual std::wstring getGrammarFileName() const = 0;
/// <summary>
/// Get the ATN interpreter used by the recognizer for prediction.
/// </summary>
/// <returns> The ATN interpreter used by the recognizer for prediction. </returns>
virtual ATNInterpreter* getInterpreter() const {
return _interpreter;
/// Get the ATN interpreter (in fact one of it's descendants) used by the recognizer for prediction.
/// @returns The ATN interpreter used by the recognizer for prediction.
template <class T>
T* getInterpreter() const {
return dynamic_cast<T *>(_interpreter);
}
/// <summary>
@ -177,7 +175,3 @@ namespace runtime {
} // namespace v4
} // namespace antlr
} // namespace org
#include "Recognizer.inl"

View File

@ -1,205 +0,0 @@
/*
* [The "BSD license"]
* Copyright (c) 2016 Mike Lischke
* Copyright (c) 2013 Terence Parr
* Copyright (c) 2013 Dan McLaughlin
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include "RecognitionException.h"
#include "CPPUtils.h"
#include "Strings.h"
#include "ProxyErrorListener.h"
#include "Token.h"
#include "CPPUtils.h"
namespace org {
namespace antlr {
namespace v4 {
namespace runtime {
template<typename ATNInterpreter>
std::map<std::vector<std::wstring>, std::map<std::wstring, int>> Recognizer<ATNInterpreter>::_tokenTypeMapCache;
template<typename ATNInterpreter>
std::map<std::vector<std::wstring>, std::map<std::wstring, int>> Recognizer<ATNInterpreter>::_ruleIndexMapCache;
template<typename ATNInterpreter>
std::map<std::wstring, int> Recognizer<ATNInterpreter>::getTokenTypeMap() {
const std::vector<std::wstring>& tokenNames = getTokenNames();
if (tokenNames.empty()) {
throw L"The current recognizer does not provide a list of token names.";
}
std::lock_guard<std::mutex> lck(mtx);
std::map<std::wstring, int> result;
auto iterator = _tokenTypeMapCache.find(tokenNames);
if (iterator != _tokenTypeMapCache.end()) {
result = iterator->second;
} else {
result = antlrcpp::toMap(tokenNames);
result[L"EOF"] = Token::_EOF;
_tokenTypeMapCache[tokenNames] = result;
}
return result;
}
template<typename ATNInterpreter>
std::map<std::wstring, int> Recognizer<ATNInterpreter>::getRuleIndexMap() {
const std::vector<std::wstring>& ruleNames = getRuleNames();
if (ruleNames.empty()) {
throw L"The current recognizer does not provide a list of rule names.";
}
std::lock_guard<std::mutex> lck(mtx);
std::map<std::wstring, int> result;
auto iterator = _ruleIndexMapCache.find(ruleNames);
if (iterator != _ruleIndexMapCache.end()) {
result = iterator->second;
} else {
result = antlrcpp::toMap(ruleNames);
_ruleIndexMapCache[ruleNames] = result;
}
return result;
}
template<typename ATNInterpreter>
int Recognizer<ATNInterpreter>::getTokenType(const std::wstring &tokenName) {
const std::map<std::wstring, int> &map = getTokenTypeMap();
int ttype = map.at(tokenName);
if (ttype != Token::INVALID_TYPE) {
return ttype;
}
return Token::INVALID_TYPE;
}
template<typename ATNInterpreter>
std::wstring Recognizer<ATNInterpreter>::getErrorHeader(RecognitionException *e) {
// We're having issues with cross header dependencies, these two classes will need to be
// rewritten to remove that.
int line = e->getOffendingToken()->getLine();
int charPositionInLine = e->getOffendingToken()->getCharPositionInLine();
return std::wstring(L"line ") + std::to_wstring(line) + std::wstring(L":") + std::to_wstring(charPositionInLine);
}
template<typename ATNInterpreter>
std::wstring Recognizer<ATNInterpreter>::getTokenErrorDisplay(Token *t) {
if (t == nullptr) {
return L"<no token>";
}
std::wstring s = t->getText();
if (s == L"") {
if (t->getType() == Token::_EOF) {
s = L"<EOF>";
} else {
s = std::wstring(L"<") + std::to_wstring(t->getType()) + std::wstring(L">");
}
}
antlrcpp::replaceAll(s, L"\n", L"\\n");
antlrcpp::replaceAll(s, L"\r",L"\\r");
antlrcpp::replaceAll(s, L"\t", L"\\t");
return std::wstring(L"'") + s + std::wstring(L"'");
}
template<typename ATNInterpreter>
void Recognizer<ATNInterpreter>::addErrorListener(ANTLRErrorListener *listener) {
if (listener == nullptr) {
throw L"listener cannot be null.";
}
_listeners.insert(_listeners.end(), listener);
}
template<typename ATNInterpreter>
void Recognizer<ATNInterpreter>::removeErrorListener(ANTLRErrorListener *listener) {
//_listeners.remove(listener); does this work the same way?
std::vector<ANTLRErrorListener*>::iterator it;
it = std::find(_listeners.begin(), _listeners.end(), listener);
_listeners.erase(it);
}
template<typename ATNInterpreter>
void Recognizer<ATNInterpreter>::removeErrorListeners() {
_listeners.clear();
}
template<typename ATNInterpreter>
ANTLRErrorListener *Recognizer<ATNInterpreter>::getErrorListenerDispatch() {
return (ANTLRErrorListener *)new ProxyErrorListener(getErrorListeners());
}
template<typename ATNInterpreter>
bool Recognizer<ATNInterpreter>::sempred(RuleContext *_localctx, int ruleIndex, int actionIndex) {
return true;
}
template<typename ATNInterpreter>
bool Recognizer<ATNInterpreter>::precpred(RuleContext *localctx, int precedence) {
return true;
}
template<typename ATNInterpreter>
void Recognizer<ATNInterpreter>::action(RuleContext *_localctx, int ruleIndex, int actionIndex) {
}
template<typename ATNInterpreter>
int Recognizer<ATNInterpreter>::getState() {
return _stateNumber;
}
template<typename ATNInterpreter>
void Recognizer<ATNInterpreter>::setState(int atnState) {
_stateNumber = atnState;
// if ( traceATNStates ) _ctx.trace(atnState);
}
template<typename ATNInterpreter>
void Recognizer<ATNInterpreter>::InitializeInstanceFields() {
_stateNumber = -1;
_interpreter = nullptr;
_listeners = std::vector<ANTLRErrorListener*>();
}
template<typename ATNInterpreter>
Recognizer<ATNInterpreter>::Recognizer() {
InitializeInstanceFields();
}
} // namespace runtime
} // namespace v4
} // namespace antlr
} // namespace org

View File

@ -206,6 +206,18 @@ std::wstring RuleContext::toString() {
return L"TODO";
};
std::wstring RuleContext::toString(Recognizer *recog) {
return toString(recog, ParserRuleContext::EMPTY);
}
std::wstring RuleContext::toString(Recognizer *recog, RuleContext *stop) {
return toString(recog->getRuleNames(), stop);
}
std::wstring RuleContext::toString(Token *, atn::ParserATNSimulator *) {
return L"TODO";
}
void RuleContext::InitializeInstanceFields() {
invokingState = -1;
}

View File

@ -135,28 +135,13 @@ namespace runtime {
virtual std::wstring toStringTree(std::vector<std::wstring> &ruleNames);
virtual std::wstring toStringTree() override;
virtual std::wstring toString() override;
template<typename ATNInterpreter>
std::wstring toString(Recognizer<ATNInterpreter> *recog) {
// Circular include issue, TODO
//return toString(recog, ParserRuleContext::EMPTY);
return toString(recog, nullptr);
}
std::wstring toString(Recognizer *recog);
std::wstring toString(const std::vector<std::wstring> &ruleNames);
// recog null unless ParserRuleContext, in which case we use subclass toString(...)
template<typename ATNInterpreter>
std::wstring toString(Recognizer<ATNInterpreter> *recog, RuleContext *stop) {
return toString(recog->getRuleNames(), stop);
}
std::wstring toString(Token *, atn::ParserATNSimulator *) {
return L"TODO";
}
std::wstring toString(Recognizer *recog, RuleContext *stop);
std::wstring toString(Token *, atn::ParserATNSimulator *);
virtual std::wstring toString(const std::vector<std::wstring> &ruleNames, RuleContext *stop);

View File

@ -33,6 +33,7 @@
#include "Interval.h"
#include "Token.h"
#include "TokenStream.h"
#include "Strings.h"
#include "TokenStreamRewriter.h"
@ -186,8 +187,8 @@ void TokenStreamRewriter::replace(Token *from, Token *to, const std::wstring& te
void TokenStreamRewriter::replace(const std::wstring &programName, size_t from, size_t to, const std::wstring& text) {
if (from > to || to >= tokens->size()) {
throw IllegalArgumentException(L"replace: range invalid: " + std::to_wstring(from) + L".." + std::to_wstring(to) +
L"(size=" + std::to_wstring(tokens->size()) + L")");
throw IllegalArgumentException("replace: range invalid: " + std::to_string(from) + ".." + std::to_string(to) +
"(size = " + std::to_string(tokens->size()) + ")");
}
RewriteOperation *op = new ReplaceOp(this, from, to, text);
std::vector<RewriteOperation*> rewrites = getProgram(programName);
@ -368,7 +369,8 @@ std::unordered_map<int, TokenStreamRewriter::RewriteOperation*> *TokenStreamRewr
std::wcout << L"new rop " << rop << std::endl;
}
else if (!disjoint && !same) {
throw IllegalArgumentException(L"replace op boundaries of " + rop->toString() + L" overlap with previous " + prevRop->toString());
throw IllegalArgumentException("replace op boundaries of " + antlrcpp::ws2s(rop->toString()) +
" overlap with previous " + antlrcpp::ws2s(prevRop->toString()));
}
}
}
@ -407,11 +409,11 @@ std::unordered_map<int, TokenStreamRewriter::RewriteOperation*> *TokenStreamRewr
continue;
}
if (iop->index >= rop->index && iop->index <= rop->lastIndex) {
throw IllegalArgumentException(L"insert op " + iop->toString() + L" within boundaries of previous " + rop->toString());
throw IllegalArgumentException("insert op " + antlrcpp::ws2s(iop->toString()) + " within boundaries of previous " + antlrcpp::ws2s(rop->toString()));
}
}
}
// System.out.println("rewrites after="+rewrites);
std::unordered_map<int, TokenStreamRewriter::RewriteOperation*> *m = new std::unordered_map<int, TokenStreamRewriter::RewriteOperation*>();
for (TokenStreamRewriter::RewriteOperation *op : rewrites) {
if (op == nullptr) { // ignore deleted ops
@ -419,11 +421,11 @@ std::unordered_map<int, TokenStreamRewriter::RewriteOperation*> *TokenStreamRewr
}
if (m->at((int)op->index) != nullptr) {
// TODO: use a specific exception rather than a generic type here?
throw new ANTLRException(L"should only be one op per index");
throw new RuntimeException("should only be one op per index");
}
m->emplace(op->index, op);
}
//System.out.println("index to op: "+m);
return m;
}

View File

@ -55,7 +55,7 @@ UnbufferedCharStream::UnbufferedCharStream(std::ifstream *input, int bufferSize)
void UnbufferedCharStream::consume() {
if (LA(1) == IntStream::_EOF) {
throw IllegalStateException(L"cannot consume EOF");
throw IllegalStateException("cannot consume EOF");
}
// buf always has at least data[p==0] in this method due to ctor
@ -140,7 +140,7 @@ ssize_t UnbufferedCharStream::mark() {
void UnbufferedCharStream::release(ssize_t marker) {
ssize_t expectedMark = -(ssize_t)numMarkers;
if (marker != expectedMark) {
throw IllegalStateException(L"release() called with an invalid marker.");
throw IllegalStateException("release() called with an invalid marker.");
}
numMarkers--;
@ -169,9 +169,11 @@ void UnbufferedCharStream::seek(size_t index) {
// index == to bufferStartIndex should set p to 0
ssize_t i = (ssize_t)index - (ssize_t)getBufferStartIndex();
if (i < 0) {
throw IllegalArgumentException(std::wstring(L"cannot seek to negative index ") + std::to_wstring(index));
throw IllegalArgumentException(std::string("cannot seek to negative index ") + std::to_string(index));
} else if (i >= (ssize_t)n) {
throw UnsupportedOperationException(std::wstring(L"seek to index outside buffer: ") + std::to_wstring(index) + std::wstring(L" not in ") + std::to_wstring(getBufferStartIndex()) + std::wstring(L"..") + std::to_wstring(getBufferStartIndex() + n));
throw UnsupportedOperationException(std::string("seek to index outside buffer: ") + std::to_string(index) +
std::string(" not in ") + std::to_string(getBufferStartIndex()) + ".." +
std::to_string(getBufferStartIndex() + n));
}
p = (size_t)i;
@ -184,7 +186,7 @@ void UnbufferedCharStream::seek(size_t index) {
}
size_t UnbufferedCharStream::size() {
throw UnsupportedOperationException(std::wstring(L"Unbuffered stream cannot know its size"));
throw UnsupportedOperationException("Unbuffered stream cannot know its size");
}
std::string UnbufferedCharStream::getSourceName() {
@ -193,18 +195,19 @@ std::string UnbufferedCharStream::getSourceName() {
std::wstring UnbufferedCharStream::getText(const misc::Interval &interval) {
if (interval.a < 0 || interval.b < interval.a - 1) {
throw IllegalArgumentException(std::wstring(L"invalid interval"));
throw IllegalArgumentException("invalid interval");
}
size_t bufferStartIndex = getBufferStartIndex();
if (n > 0 && data[n - 1] == WCHAR_MAX) {
if ((size_t)(interval.a + interval.length()) > bufferStartIndex + n) {
throw IllegalArgumentException(std::wstring(L"the interval extends past the end of the stream"));
throw IllegalArgumentException("the interval extends past the end of the stream");
}
}
if ((size_t)interval.a < bufferStartIndex || (size_t)interval.b >= bufferStartIndex + n) {
throw UnsupportedOperationException(std::wstring(L"interval ") + interval.toString() + std::wstring(L" outside buffer: ") + std::to_wstring(bufferStartIndex) + std::wstring(L"..") + std::to_wstring(bufferStartIndex + n - 1));
throw UnsupportedOperationException(std::string("interval ") + interval.toString() + " outside buffer: " +
std::to_string(bufferStartIndex) + ".." + std::to_string(bufferStartIndex + n - 1));
}
// convert from absolute to local index
size_t i = (size_t)interval.a - bufferStartIndex;

View File

@ -37,6 +37,7 @@
#include "DecisionState.h"
#include "Recognizer.h"
#include "ATNType.h"
#include "Exceptions.h"
#include "ATN.h"
@ -96,7 +97,7 @@ int ATN::getNumberOfDecisions() const {
misc::IntervalSet ATN::getExpectedTokens(int stateNumber, RuleContext *context) const {
if (stateNumber < 0 || stateNumber >= (int)states.size()) {
throw new IllegalArgumentException(L"Invalid state number.");
throw new IllegalArgumentException("Invalid state number.");
}
RuleContext *ctx = context;

View File

@ -87,7 +87,7 @@ bool ATNConfig::operator == (const ATNConfig& other) const
{
return this->state->stateNumber == other.state->stateNumber && this->alt == other.alt &&
(this->context == other.context || (this->context != nullptr && this->context == other.context)) &&
this->semanticContext->equals(other.semanticContext);
this->semanticContext == other.semanticContext;
}
std::wstring ATNConfig::toString() {

View File

@ -32,6 +32,7 @@
#include "PredictionContext.h"
#include "ATNConfig.h"
#include "ATNSimulator.h"
#include "Exceptions.h"
#include "ATNConfigSet.h"
@ -45,13 +46,13 @@ size_t SimpleATNConfigHasher::operator()(const ATNConfig &k) const {
return hashCode;
}
bool SimpleATNConfigComparer::operator()(const ATNConfig &lhs, const ATNConfig &rhs) const {
bool SimpleATNConfigComparer::operator () (const ATNConfig &lhs, const ATNConfig &rhs) const {
if (&lhs == &rhs) { // Shortcut: same address = same object.
return true;
}
return lhs.state->stateNumber == rhs.state->stateNumber && lhs.alt == rhs.alt &&
lhs.semanticContext->equals(rhs.semanticContext);
lhs.semanticContext == rhs.semanticContext;
}
//------------------ ATNConfigSet --------------------------------------------------------------------------------------
@ -79,7 +80,7 @@ bool ATNConfigSet::add(ATNConfig *config) {
bool ATNConfigSet::add(ATNConfig *config, misc::DoubleKeyMap<PredictionContext*, PredictionContext*, PredictionContext*> *mergeCache) {
if (_readonly) {
throw new IllegalStateException(L"This set is readonly");
throw new IllegalStateException("This set is readonly");
}
if (config->semanticContext != SemanticContext::NONE) {
hasSemanticContext = true;
@ -141,7 +142,7 @@ ATNConfig* ATNConfigSet::get(size_t i) const {
void ATNConfigSet::optimizeConfigs(ATNSimulator *interpreter) {
if (_readonly) {
throw IllegalStateException(L"This set is readonly");
throw IllegalStateException("This set is readonly");
}
if (configLookup->isEmpty()) {
return;
@ -202,7 +203,7 @@ bool ATNConfigSet::isEmpty() {
bool ATNConfigSet::contains(ATNConfig *o) {
if (configLookup == nullptr) {
throw UnsupportedOperationException(L"This method is not implemented for readonly sets.");
throw UnsupportedOperationException("This method is not implemented for readonly sets.");
}
return configLookup->contains(o);
@ -210,7 +211,7 @@ bool ATNConfigSet::contains(ATNConfig *o) {
void ATNConfigSet::clear() {
if (_readonly) {
throw new IllegalStateException(L"This set is readonly");
throw new IllegalStateException("This set is readonly");
}
configs.clear();
_cachedHashCode = 0;

View File

@ -59,12 +59,13 @@
#include "SetTransition.h"
#include "NotSetTransition.h"
#include "WildcardTransition.h"
#include "Token.h"
#include "IntervalSet.h"
#include "Exceptions.h"
#include "ATNDeserializer.h"
using namespace antlrcpp;
using namespace org::antlr::v4::runtime::atn;
const size_t ATNDeserializer::SERIALIZED_VERSION = 3;
@ -109,7 +110,7 @@ ATN ATNDeserializer::deserialize(const std::wstring& input) {
int p = 0;
int version = data[p++];
if (version != SERIALIZED_VERSION) {
std::wstring reason = L"Could not deserialize ATN with version" + std::to_wstring(version) + L"(expected " + std::to_wstring(SERIALIZED_VERSION) + L").";
std::string reason = "Could not deserialize ATN with version" + std::to_string(version) + "(expected " + std::to_string(SERIALIZED_VERSION) + ").";
throw UnsupportedOperationException(reason);
}
@ -118,9 +119,8 @@ ATN ATNDeserializer::deserialize(const std::wstring& input) {
auto uuidIterator = std::find(SUPPORTED_UUIDS.begin(), SUPPORTED_UUIDS.end(), uuid);
p += 8;
if (uuidIterator == SUPPORTED_UUIDS.end()) {
std::wstring reason = L"Could not deserialize ATN with UUID " +
s2ws(uuid.toString()) + L" (expected " + s2ws(SERIALIZED_UUID.toString()) +
L" or a legacy UUID).";
std::string reason = "Could not deserialize ATN with UUID " + uuid.toString() + " (expected " +
SERIALIZED_UUID.toString() + " or a legacy UUID).";
throw UnsupportedOperationException(reason);
}
@ -384,7 +384,7 @@ ATN ATNDeserializer::deserialize(const std::wstring& input) {
}
if (endState == nullptr) {
throw UnsupportedOperationException(L"Couldn't identify final state of the precedence rule prefix section.");
throw UnsupportedOperationException("Couldn't identify final state of the precedence rule prefix section.");
}
@ -492,10 +492,10 @@ void ATNDeserializer::verifyATN(const ATN &atn) {
}
void ATNDeserializer::checkCondition(bool condition) {
checkCondition(condition, L"");
checkCondition(condition, "");
}
void ATNDeserializer::checkCondition(bool condition, const std::wstring &message) {
void ATNDeserializer::checkCondition(bool condition, const std::string &message) {
if (!condition) {
throw IllegalStateException(message);
}
@ -540,7 +540,7 @@ Transition *ATNDeserializer::edgeFactory(const ATN &atn, int type, int src, int
return new WildcardTransition(target);
}
throw IllegalArgumentException(L"The specified transition type is not valid.");
throw IllegalArgumentException("The specified transition type is not valid.");
}
ATNState *ATNDeserializer::stateFactory(int type, int ruleIndex) {
@ -585,8 +585,7 @@ ATNState *ATNDeserializer::stateFactory(int type, int ruleIndex) {
s = new LoopEndState();
break;
default :
std::wstring message = L"The specified state type " +
std::to_wstring(type) + L" is not valid.";
std::string message = "The specified state type " + std::to_string(type) + " is not valid.";
throw IllegalArgumentException(message);
}

View File

@ -103,7 +103,7 @@ namespace atn {
virtual void checkCondition(bool condition);
virtual void checkCondition(bool condition, const std::wstring &message);
virtual void checkCondition(bool condition, const std::string &message);
static Guid toUUID(const wchar_t *data, int offset);

View File

@ -54,6 +54,8 @@
#include "stringconverter.h"
#include "TokensStartState.h"
#include "Exceptions.h"
#include "CPPUtils.h"
#include "ATNSerializer.h"
@ -92,12 +94,12 @@ std::vector<size_t>* ATNSerializer::serialize() {
int stateType = s->getStateType();
if (dynamic_cast<DecisionState *>(s) != nullptr &&
(static_cast<DecisionState *>(s))->nonGreedy) {
(static_cast<DecisionState *>(s))->nonGreedy) {
nonGreedyStates.push_back(s->stateNumber);
}
if (dynamic_cast<RuleStartState *>(s) != nullptr &&
(static_cast<RuleStartState *>(s))->isPrecedenceRule) {
(static_cast<RuleStartState *>(s))->isPrecedenceRule) {
precedenceStates.push_back(s->stateNumber);
}
@ -129,8 +131,8 @@ std::vector<size_t>* ATNSerializer::serialize() {
if (edgeType == Transition::SET || edgeType == Transition::NOT_SET) {
SetTransition *st = static_cast<SetTransition *>(t);
if (setIndices.find(st->set) != setIndices.end()) {
sets.push_back(st->set);
setIndices.insert({ st->set, sets.size() - 1 });
sets.push_back(st->set);
setIndices.insert({ st->set, sets.size() - 1 });
}
}
}
@ -221,7 +223,7 @@ std::vector<size_t>* ATNSerializer::serialize() {
Transition *t = s->transition(i);
if (atn->states[(size_t)t->target->stateNumber] == nullptr) {
throw IllegalStateException(L"Cannot serialize a transition to a removed state.");
throw IllegalStateException("Cannot serialize a transition to a removed state.");
}
int src = s->stateNumber;
@ -231,28 +233,28 @@ std::vector<size_t>* ATNSerializer::serialize() {
int arg2 = 0;
int arg3 = 0;
switch (edgeType) {
case Transition::RULE:
case Transition::RULE:
trg = (static_cast<RuleTransition *>(t))->followState->stateNumber;
arg1 = (static_cast<RuleTransition *>(t))->target->stateNumber;
arg2 = (static_cast<RuleTransition *>(t))->ruleIndex;
arg3 = (static_cast<RuleTransition *>(t))->precedence;
break;
case Transition::PRECEDENCE:
{
PrecedencePredicateTransition *ppt =
static_cast<PrecedencePredicateTransition *>(t);
arg1 = ppt->precedence;
}
case Transition::PRECEDENCE:
{
PrecedencePredicateTransition *ppt =
static_cast<PrecedencePredicateTransition *>(t);
arg1 = ppt->precedence;
}
break;
case Transition::PREDICATE:
{
PredicateTransition *pt = static_cast<PredicateTransition *>(t);
arg1 = pt->ruleIndex;
arg2 = pt->predIndex;
arg3 = pt->isCtxDependent ? 1 : 0;
}
case Transition::PREDICATE:
{
PredicateTransition *pt = static_cast<PredicateTransition *>(t);
arg1 = pt->ruleIndex;
arg2 = pt->predIndex;
arg3 = pt->isCtxDependent ? 1 : 0;
}
break;
case Transition::RANGE:
case Transition::RANGE:
arg1 = (static_cast<RangeTransition *>(t))->from;
arg2 = (static_cast<RangeTransition *>(t))->to;
if (arg1 == Token::_EOF) {
@ -261,7 +263,7 @@ std::vector<size_t>* ATNSerializer::serialize() {
}
break;
case Transition::ATOM:
case Transition::ATOM:
arg1 = (static_cast<AtomTransition *>(t))->_label;
if (arg1 == Token::_EOF) {
arg1 = 0;
@ -269,26 +271,26 @@ std::vector<size_t>* ATNSerializer::serialize() {
}
break;
case Transition::ACTION:
{
ActionTransition *at = static_cast<ActionTransition *>(t);
arg1 = at->ruleIndex;
arg2 = at->actionIndex;
if (arg2 == -1) {
arg2 = 0xFFFF;
}
case Transition::ACTION:
{
ActionTransition *at = static_cast<ActionTransition *>(t);
arg1 = at->ruleIndex;
arg2 = at->actionIndex;
if (arg2 == -1) {
arg2 = 0xFFFF;
}
arg3 = at->isCtxDependent ? 1 : 0;
}
arg3 = at->isCtxDependent ? 1 : 0;
}
break;
case Transition::SET:
case Transition::SET:
arg1 = setIndices[(static_cast<SetTransition *>(t))->set];
break;
case Transition::NOT_SET:
arg1 = setIndices[(static_cast<SetTransition *>(t))->set];
break;
case Transition::WILDCARD:
case Transition::WILDCARD:
break;
}
@ -309,7 +311,7 @@ std::vector<size_t>* ATNSerializer::serialize() {
// don't adjust the first value since that's the version number
for (size_t i = 1; i < data->size(); i++) {
if ((wchar_t)data->at(i) < WCHAR_MIN || data->at(i) > WCHAR_MAX) {
throw UnsupportedOperationException(L"Serialized ATN data element out of range.");
throw UnsupportedOperationException("Serialized ATN data element out of range.");
}
size_t value = (data->at(i) + 2) & 0xFFFF;
@ -334,25 +336,17 @@ std::wstring ATNSerializer::decode(const std::wstring& inpdata) {
int p = 0;
size_t version = (size_t)data[p++];
if (version != ATNDeserializer::SERIALIZED_VERSION) {
std::wstring reason =
L"Could not deserialize ATN with version "
+ std::to_wstring(version)
+ L"(expected "
+ std::to_wstring(ATNDeserializer::SERIALIZED_VERSION)
+ L").";
throw UnsupportedOperationException(L"ATN Serializer" + reason);
std::string reason = "Could not deserialize ATN with version " + std::to_string(version) + "(expected " +
std::to_string(ATNDeserializer::SERIALIZED_VERSION) + ").";
throw UnsupportedOperationException("ATN Serializer" + reason);
}
Guid uuid = ATNDeserializer::toUUID(data, p);
p += 8;
if (uuid != ATNDeserializer::SERIALIZED_UUID) {
std::wstring reason =
L"Could not deserialize ATN with UUID "
+ s2ws(uuid.toString())
+ L" (expected "
+ s2ws(ATNDeserializer::SERIALIZED_UUID.toString())
+ L").";
throw UnsupportedOperationException(L"ATN Serializer" + reason);
std::string reason = "Could not deserialize ATN with UUID " + uuid.toString() + " (expected " +
ATNDeserializer::SERIALIZED_UUID.toString() + ").";
throw UnsupportedOperationException("ATN Serializer" + reason);
}
p++; // skip grammarType
@ -498,30 +492,30 @@ std::wstring ATNSerializer::getTokenName(ssize_t t) {
t <= WCHAR_MAX) {
switch (t) {
case L'\n':
return L"'\\n'";
return L"'\\n'";
case L'\r':
return L"'\\r'";
return L"'\\r'";
case L'\t':
return L"'\\t'";
return L"'\\t'";
case L'\b':
return L"'\\b'";
return L"'\\b'";
case L'\f':
return L"'\\f'";
return L"'\\f'";
case L'\\':
return L"'\\\\'";
return L"'\\\\'";
case L'\'':
return L"'\\''";
return L"'\\''";
default:
std::wstring s_hex = antlrcpp::toHexString((int)t);
if (s_hex >= L"0" && s_hex <= L"7F" &&
!iscntrl((int)t)) {
return L"'" + std::to_wstring(t) + L"'";
}
// turn on the bit above max "\uFFFF" value so that we pad with zeros
// then only take last 4 digits
std::wstring hex = antlrcpp::toHexString((int)t | 0x10000).substr(1, 4);
std::wstring unicodeStr = std::wstring(L"'\\u") + hex + std::wstring(L"'");
return unicodeStr;
std::wstring s_hex = antlrcpp::toHexString((int)t);
if (s_hex >= L"0" && s_hex <= L"7F" &&
!iscntrl((int)t)) {
return L"'" + std::to_wstring(t) + L"'";
}
// turn on the bit above max "\uFFFF" value so that we pad with zeros
// then only take last 4 digits
std::wstring hex = antlrcpp::toHexString((int)t | 0x10000).substr(1, 4);
std::wstring unicodeStr = std::wstring(L"'\\u") + hex + std::wstring(L"'");
return unicodeStr;
}
}

View File

@ -76,8 +76,8 @@ void ATNSimulator::checkCondition(bool condition) {
(new ATNDeserializer())->checkCondition(condition);
}
void ATNSimulator::checkCondition(bool condition, const std::wstring &message) {
(new ATNDeserializer())->checkCondition(condition, message);
void ATNSimulator::checkCondition(bool condition, const std::string &message) {
ATNDeserializer().checkCondition(condition, message);
}
Transition *ATNSimulator::edgeFactory(const ATN &atn, int type, int src, int trg, int arg1, int arg2, int arg3,

View File

@ -42,16 +42,42 @@ namespace atn {
class ATNSimulator {
public:
virtual ~ATNSimulator() {};
//Mutex to manage synchronized access for multithreading
std::mutex mtx;
ATNSimulator();
/// <summary>
/// Must distinguish between missing edge and edge we know leads nowhere </summary>
/// Must distinguish between missing edge and edge we know leads nowhere.
static dfa::DFAState ERROR;
ATN atn;
ATNSimulator(const ATN &atn, PredictionContextCache *sharedContextCache);
virtual void reset() = 0;
virtual PredictionContextCache *getSharedContextCache();
virtual PredictionContext *getCachedContext(PredictionContext *context);
/// @deprecated Use <seealso cref="ATNDeserializer#deserialize"/> instead.
static ATN deserialize(const std::wstring &data);
/// @deprecated Use <seealso cref="ATNDeserializer#checkCondition(boolean)"/> instead.
static void checkCondition(bool condition);
/// @deprecated Use <seealso cref="ATNDeserializer#checkCondition(boolean, String)"/> instead.
static void checkCondition(bool condition, const std::string &message);
/// @deprecated Use <seealso cref="ATNDeserializer#edgeFactory"/> instead.
static Transition *edgeFactory(const ATN &atn, int type, int src, int trg, int arg1, int arg2, int arg3,
const std::vector<misc::IntervalSet> &sets);
/// @deprecated Use <seealso cref="ATNDeserializer#stateFactory"/> instead.
static ATNState *stateFactory(int type, int ruleIndex);
protected:
// Mutex to manage synchronized access for multithreading
std::mutex mtx;
/// <summary>
/// The context cache maps all PredictionContext objects that are equals()
/// to a single cached copy. This cache is shared across all contexts
@ -73,46 +99,8 @@ namespace atn {
/// more time I think and doesn't save on the overall footprint
/// so it's not worth the complexity.
/// </summary>
protected:
PredictionContextCache * sharedContextCache;
public:
ATNSimulator(const ATN &atn, PredictionContextCache *sharedContextCache);
virtual void reset() = 0;
virtual PredictionContextCache *getSharedContextCache();
virtual PredictionContext *getCachedContext(PredictionContext *context);
/// @deprecated Use <seealso cref="ATNDeserializer#deserialize"/> instead.
static ATN deserialize(const std::wstring &data);
/// @deprecated Use <seealso cref="ATNDeserializer#checkCondition(boolean)"/> instead.
static void checkCondition(bool condition);
/// @deprecated Use <seealso cref="ATNDeserializer#checkCondition(boolean, String)"/> instead.
static void checkCondition(bool condition, const std::wstring &message);
/// @deprecated Use <seealso cref="ATNDeserializer#edgeFactory"/> instead.
static Transition *edgeFactory(const ATN &atn, int type, int src, int trg, int arg1, int arg2, int arg3,
const std::vector<misc::IntervalSet> &sets);
/// @deprecated Use <seealso cref="ATNDeserializer#stateFactory"/> instead.
static ATNState *stateFactory(int type, int ruleIndex);
/*
public static void dump(DFA dfa, Grammar g) {
DOTGenerator dot = new DOTGenerator(g);
String output = dot.getDOT(dfa, false);
System.out.println(output);
}
public static void dump(DFA dfa) {
dump(dfa, null);
}
*/
};
} // namespace atn

View File

@ -63,12 +63,12 @@ int ArrayPredictionContext::getReturnState(size_t index) const {
return returnStates[index];
}
bool ArrayPredictionContext::operator == (PredictionContext *o) const {
if (this == o) {
bool ArrayPredictionContext::operator == (const PredictionContext &o) const {
if (this == &o) {
return true;
}
ArrayPredictionContext *other = dynamic_cast<ArrayPredictionContext*>(o);
const ArrayPredictionContext *other = dynamic_cast<const ArrayPredictionContext*>(&o);
if (other == nullptr || hashCode() != other->hashCode()) {
return false; // can't be same if hash is different
}

View File

@ -59,7 +59,7 @@ namespace atn {
virtual size_t size() const override;
virtual PredictionContext *getParent(size_t index) const override;
virtual int getReturnState(size_t index) const override;
bool operator == (PredictionContext *o) const override;
bool operator == (const PredictionContext &o) const override;
virtual std::wstring toString();
};

View File

@ -52,8 +52,8 @@ int EmptyPredictionContext::getReturnState(size_t index) const {
return returnState;
}
bool EmptyPredictionContext::operator == (PredictionContext *o) const {
return this == o;
bool EmptyPredictionContext::operator == (const PredictionContext &o) const {
return this == &o;
}
std::wstring EmptyPredictionContext::toString() const {

View File

@ -49,7 +49,7 @@ namespace atn {
virtual int getReturnState(size_t index) const override;
virtual std::wstring toString() const override;
virtual bool operator == (PredictionContext *o) const override;
virtual bool operator == (const PredictionContext &o) const override;
};
} // namespace atn

View File

@ -388,7 +388,7 @@ atn::LexerATNConfig *LexerATNSimulator::getEpsilonTarget(CharStream *input, Lexe
case Transition::PRECEDENCE:
//{
throw new UnsupportedOperationException(L"Precedence predicates are not supported in lexers.");
throw new UnsupportedOperationException("Precedence predicates are not supported in lexers.");
//}
break;

View File

@ -52,6 +52,7 @@
#include "ATNConfig.h"
#include "stringconverter.h"
#include "Interval.h"
#include "ANTLRErrorListener.h"
#include "Arrays.h"
@ -453,11 +454,8 @@ atn::ATNConfigSet *ParserATNSimulator::computeReachSet(ATNConfigSet *closure, si
}
if (dynamic_cast<RuleStopState*>(c->state) != nullptr) {
if (c->context->isEmpty()) {
// Converted assert, shouldn't happen
throw new ASSERTException(L"ParserATNSimulator::computeReachSet",
L"c->context->isEmpty()");
}
assert(c->context->isEmpty());
if (fullCtx || t == IntStream::_EOF) {
if (skippedStopStates.empty()) {
skippedStopStates = std::vector<ATNConfig*>();
@ -548,11 +546,8 @@ atn::ATNConfigSet *ParserATNSimulator::computeReachSet(ATNConfigSet *closure, si
* multiple alternatives are viable.
*/
if (skippedStopStates.size() > 0 && (!fullCtx || !PredictionModeClass::hasConfigInRuleStopState(reach))) {
if (!skippedStopStates.empty()) {
// Shouldn't happen, converted assert
throw new ASSERTException(L"ParserATNSimulator::computeReachSet",
L"skippedStopStates.size() > 0 && (!fullCtx || !PredictionModeClass::hasConfigInRuleStopState(reach)))");
}
assert(!skippedStopStates.empty());
for (auto c : skippedStopStates) {
reach->add(c, mergeCache);
}
@ -667,11 +662,7 @@ std::vector<dfa::DFAState::PredPrediction *> ParserATNSimulator::getPredicatePre
SemanticContext *pred = altToPred[i];
// unpredicted is indicated by SemanticContext.NONE
if(pred != nullptr) {
// Converted assert, shouldn't happen
throw new ASSERTException(L"arserATNSimulator::getPredicatePredictions",
L"pred != nullptr");
}
assert(pred != nullptr);
if (ambigAlts != nullptr && ambigAlts->data.test(i)) {
pairs.push_back(new dfa::DFAState::PredPrediction(pred, (int)i));
@ -734,11 +725,8 @@ BitSet *ParserATNSimulator::evalSemanticContext(std::vector<dfa::DFAState::PredP
void ParserATNSimulator::closure(ATNConfig *config, ATNConfigSet *configs, std::set<ATNConfig*> *closureBusy, bool collectPredicates, bool fullCtx) {
const int initialDepth = 0;
closureCheckingStopState(config, configs, closureBusy, collectPredicates, fullCtx, initialDepth);
if (!fullCtx || !configs->dipsIntoOuterContext) {
// Converted assert, shouldn't happen
throw new ASSERTException(L"ParserATNSimulator::closure",
L"!fullCtx || !configs->dipsIntoOuterContext");
}
assert(!fullCtx || !configs->dipsIntoOuterContext);
}
void ParserATNSimulator::closureCheckingStopState(ATNConfig *config, ATNConfigSet *configs, std::set<ATNConfig*> *closureBusy, bool collectPredicates, bool fullCtx, int depth) {
@ -771,11 +759,8 @@ void ParserATNSimulator::closureCheckingStopState(ATNConfig *config, ATNConfigSe
// gotten that context AFTER having falling off a rule.
// Make sure we track that we are now out of context.
c->reachesIntoOuterContext = config->reachesIntoOuterContext;
if (depth > INT_MIN) {
// Converted assert, shouldn't happen
throw new ASSERTException(L"ParserATNSimulator::closureCheckingStopState",
L"depth > INT_MIN");
}
assert(depth > INT_MIN);
closureCheckingStopState(c, configs, closureBusy, collectPredicates, fullCtx, depth - 1);
}
return;
@ -809,11 +794,8 @@ void ParserATNSimulator::closure_(ATNConfig *config, ATNConfigSet *configs, std:
if (c != nullptr) {
int newDepth = depth;
if (dynamic_cast<RuleStopState*>(config->state) != nullptr) {
if(!fullCtx) {
// Converted assert, shouldn't happen
throw new ASSERTException(L"ParserATNSimulator::closure_",
L"!fullCtx");
}
assert(!fullCtx);
// target fell off end of rule; mark resulting c as having dipped into outer context
// We can't get here if incoming config was rule stop and we had context
// track how far we dip into outer context. Might
@ -827,11 +809,8 @@ void ParserATNSimulator::closure_(ATNConfig *config, ATNConfigSet *configs, std:
c->reachesIntoOuterContext++;
configs->dipsIntoOuterContext = true; // TODO: can remove? only care when we add to set per middle of this method
if(newDepth > INT_MIN) {
// Converted assert, shouldn't happen
throw new ASSERTException(L"ParserATNSimulator::closure_",
L"newDepth > INT_MIN");
}
assert(newDepth > INT_MIN);
newDepth--;
if (debug) {
std::wcout << L"dips into outer ctx: " << c << std::endl;

View File

@ -40,10 +40,6 @@ namespace v4 {
namespace runtime {
namespace atn {
///
/// <summary>
/// @author Sam Harwell
/// </summary>
class PrecedencePredicateTransition final : public AbstractPredicateTransition {
public:
const int precedence;

View File

@ -74,6 +74,10 @@ PredictionContext *PredictionContext::fromRuleContext(const ATN &atn, RuleContex
return SingletonPredictionContext::create(parent, transition->followState->stateNumber);
}
bool PredictionContext::operator != (const PredictionContext &o) const {
return !(*this == o);
};
bool PredictionContext::isEmpty() const {
return this == EMPTY;
}
@ -116,10 +120,7 @@ size_t PredictionContext::calculateHashCode(const std::vector<PredictionContext*
PredictionContext *PredictionContext::merge(PredictionContext *a, PredictionContext *b,
bool rootIsWildcard, misc::DoubleKeyMap<PredictionContext*, PredictionContext*, PredictionContext*> *mergeCache) {
if (a != nullptr && b != nullptr) {
throw new ASSERTException(L"PredictionContext::merge",
L"a != nullptr && b != nullptr");
};
assert(a != nullptr && b != nullptr);
// share same graph if both same
if (a == b) {
@ -549,3 +550,80 @@ std::wstring PredictionContext::toString() {
// for now.)
return L"TODO PredictionContext::toString()";
}
std::wstring PredictionContext::toString(Recognizer *recog) {
return toString();
}
std::vector<std::wstring> PredictionContext::toStrings(Recognizer *recognizer, int currentState) {
return toStrings(recognizer, EMPTY, currentState);
}
std::vector<std::wstring> PredictionContext::toStrings(Recognizer *recognizer, PredictionContext *stop, int currentState) {
std::vector<std::wstring> result;
for (size_t perm = 0; ; perm++) {
size_t offset = 0;
bool last = true;
PredictionContext *p = this;
int stateNumber = currentState;
antlrcpp::StringBuilder *localBuffer = new antlrcpp::StringBuilder();
localBuffer->append(L"[");
bool outerContinue = false;
while (!p->isEmpty() && p != stop) {
size_t index = 0;
if (p->size() > 0) {
size_t bits = 1;
while ((1 << bits) < p->size()) {
bits++;
}
size_t mask = (1 << bits) - 1;
index = (perm >> offset) & mask;
last &= index >= p->size() - 1;
if (index >= p->size()) {
outerContinue = true;
break;
}
offset += bits;
}
if (recognizer != nullptr) {
if (localBuffer->length() > 1) {
// first char is '[', if more than that this isn't the first rule
localBuffer->append(L' ');
}
const ATN &atn = recognizer->getATN();
ATNState *s = atn.states[(size_t)stateNumber];
std::wstring ruleName = recognizer->getRuleNames()[(size_t)s->ruleIndex];
localBuffer->append(ruleName);
} else if (p->getReturnState(index) != EMPTY_RETURN_STATE) {
if (!p->isEmpty()) {
if (localBuffer->length() > 1) {
// first char is '[', if more than that this isn't the first rule
localBuffer->append(L' ');
}
localBuffer->append(p->getReturnState(index));
}
}
stateNumber = p->getReturnState(index);
p = p->getParent(index);
}
if (outerContinue)
continue;
localBuffer->append(L"]");
result.push_back(localBuffer->toString());
if (last) {
break;
}
}
return result;
}

View File

@ -99,7 +99,9 @@ namespace atn {
virtual size_t size() const = 0;
virtual PredictionContext *getParent(size_t index) const = 0;
virtual int getReturnState(size_t index) const = 0;
virtual bool operator == (PredictionContext *o) const = 0;
virtual bool operator == (const PredictionContext &o) const = 0;
virtual bool operator != (const PredictionContext &o) const;
/// This means only the EMPTY context is in set.
virtual bool isEmpty() const;
@ -273,85 +275,10 @@ namespace atn {
static void getAllContextNodes_(PredictionContext *context, std::vector<PredictionContext*> &nodes, std::map<PredictionContext*, PredictionContext*> *visited);
std::wstring toString();
std::wstring toString(Recognizer *recog);
template<typename ATNInterpreter>
std::wstring toString(Recognizer<ATNInterpreter> *recog) {
return toString();
// return toString(recog, ParserRuleContext.EMPTY);
}
template<typename ATNInterpreter>
std::wstring *toStrings(Recognizer<ATNInterpreter> *recognizer, int currentState) {
return toStrings(recognizer, EMPTY, currentState);
}
// FROM SAM
template<typename ATNInterpreter>
std::wstring *toStrings(Recognizer<ATNInterpreter> *recognizer, PredictionContext *stop, int currentState) {
std::vector<std::wstring> result = std::vector<std::wstring>();
for (size_t perm = 0; ; perm++) {
size_t offset = 0;
bool last = true;
PredictionContext *p = this;
int stateNumber = currentState;
antlrcpp::StringBuilder *localBuffer = new antlrcpp::StringBuilder();
localBuffer->append(L"[");
while (!p->isEmpty() && p != stop) {
size_t index = 0;
if (p->size() > 0) {
size_t bits = 1;
while ((1 << bits) < p->size()) {
bits++;
}
size_t mask = (1 << bits) - 1;
index = (perm >> offset) & mask;
last &= index >= p->size() - 1;
if (index >= p->size()) {
goto outerContinue;
}
offset += bits;
}
if (recognizer != nullptr) {
if (localBuffer->length() > 1) {
// first char is '[', if more than that this isn't the first rule
localBuffer->append(L' ');
}
ATN *atn = recognizer->getATN();
ATNState *s = atn->states[(size_t)stateNumber];
std::wstring ruleName = recognizer->getRuleNames()[s->ruleIndex];
localBuffer->append(ruleName);
} else if (p->getReturnState(index) != EMPTY_RETURN_STATE) {
if (!p->isEmpty()) {
if (localBuffer->length() > 1) {
// first char is '[', if more than that this isn't the first rule
localBuffer->append(L' ');
}
localBuffer->append(p->getReturnState(index));
}
}
stateNumber = p->getReturnState(index);
p = p->getParent(index);
}
localBuffer->append(L"]");
result.push_back(localBuffer->toString());
if (last) {
break;
}
outerContinue:
continue;
}
outerBreak:
// TODO: return result.toArray(new std::wstring[result.size()]);
return nullptr;
}
std::vector<std::wstring> toStrings(Recognizer *recognizer, int currentState);
std::vector<std::wstring> toStrings(Recognizer *recognizer, PredictionContext *stop, int currentState);
};
} // namespace atn

View File

@ -35,28 +35,13 @@
using namespace org::antlr::v4::runtime::atn;
SemanticContext::Predicate::Predicate() : ruleIndex(-1), predIndex(-1), isCtxDependent(false) {
SemanticContext::Predicate::Predicate() : Predicate(-1, -1, false) {
}
SemanticContext::Predicate::Predicate(int ruleIndex, int predIndex, bool isCtxDependent) : ruleIndex(ruleIndex), predIndex(predIndex), isCtxDependent(isCtxDependent) {
SemanticContext::Predicate::Predicate(int ruleIndex, int predIndex, bool isCtxDependent)
: ruleIndex(ruleIndex), predIndex(predIndex), isCtxDependent(isCtxDependent) {
}
std::wstring SemanticContext::toString() const {
// This is a pure virtual function, why does it need an impl?
throw new ASSERTException(L"SemanticContext::toString", L"Should never be called, abstract class");
}
size_t SemanticContext::hashCode() {
// This is a pure virtual function, why does it need an impl?
throw new ASSERTException(L"SemanticContext::hashCode", L"Should never be called, abstract class");
}
bool SemanticContext::equals(void *obj) {
// "SemanticContext::equals should have been called on a daughter class"
throw new ASSERTException(L"SemanticContext::equals", L"Should never be called, abstract class");
}
size_t SemanticContext::Predicate::hashCode() {
size_t hashCode = misc::MurmurHash::initialize();
hashCode = misc::MurmurHash::update(hashCode, (size_t)ruleIndex);
@ -66,15 +51,16 @@ size_t SemanticContext::Predicate::hashCode() {
return hashCode;
}
bool SemanticContext::Predicate::equals(void *obj) {
if (!((Predicate*)obj != nullptr)) {
return false;
}
if (this == obj) {
bool SemanticContext::Predicate::operator == (const SemanticContext &other) const {
if (this == &other) {
return true;
}
Predicate *p = static_cast<Predicate*>(obj);
return this->ruleIndex == p->ruleIndex && this->predIndex == p->predIndex && this->isCtxDependent == p->isCtxDependent;
const Predicate *p = dynamic_cast<const Predicate*>(&other);
if (p == nullptr)
return false;
return ruleIndex == p->ruleIndex && predIndex == p->predIndex && isCtxDependent == p->isCtxDependent;
}
std::wstring SemanticContext::Predicate::toString() const {
@ -97,22 +83,17 @@ size_t SemanticContext::PrecedencePredicate::hashCode() {
return hashCode;
}
bool SemanticContext::PrecedencePredicate::equals(void *obj) {
// TODO: this is wrong
if (!((Predicate*)obj/*dynamic_cast<PrecedencePredicate*>(obj)*/ != nullptr)) {
return false;
}
if (this == obj) {
bool SemanticContext::PrecedencePredicate::operator == (const SemanticContext &other) const {
if (this == &other) {
return true;
}
PrecedencePredicate *other = static_cast<PrecedencePredicate*>(obj);
return this->precedence == other->precedence;
const PrecedencePredicate *predicate = dynamic_cast<const PrecedencePredicate *>(&other);
return precedence == predicate->precedence;
}
std::wstring SemanticContext::PrecedencePredicate::toString() const {
return SemanticContext::toString();
return L"Precedence: " + std::to_wstring(precedence);
}
@ -136,8 +117,7 @@ SemanticContext::AND::AND(SemanticContext *a, SemanticContext *b) {
operands->insert(operands->end(), b);
}
std::vector<PrecedencePredicate*> precedencePredicates =
filterPrecedencePredicates<SemanticContext*>(operands);
std::vector<PrecedencePredicate*> precedencePredicates = filterPrecedencePredicates<SemanticContext*>(operands);
if (!precedencePredicates.empty()) {
// interested in the transition with the lowest precedence
@ -153,15 +133,13 @@ SemanticContext::AND::AND(SemanticContext *a, SemanticContext *b) {
}
bool SemanticContext::AND::equals(void *obj) {
if (this == obj) {
bool SemanticContext::AND::operator == (const SemanticContext &other) const {
if (this == &other) {
return true;
}
if (!((AND*)obj != nullptr)) {
return false;
}
AND *other = static_cast<AND*>(obj);
return (this->opnds == other->opnds);
const AND *context = dynamic_cast<const AND *>(&other);
return opnds == context->opnds;
}
@ -173,8 +151,8 @@ size_t SemanticContext::AND::hashCode() {
std::wstring SemanticContext::AND::toString() const {
std::wstring tmp;
for(auto var : opnds) {
tmp += var->toString() + L"&&";
for (auto var : opnds) {
tmp += var->toString() + L" && ";
}
return tmp;
}
@ -214,18 +192,14 @@ SemanticContext::OR::OR(SemanticContext *a, SemanticContext *b){
}
}
bool SemanticContext::OR::equals(SemanticContext *obj) {
if (this == obj) {
bool SemanticContext::OR::operator == (const SemanticContext &other) const {
if (this == &other) {
return true;
}
if (obj == nullptr || typeid(*obj) != typeid(*this)) {
return false;
}
const OR *context = dynamic_cast<const OR *>(&other);
OR *other = static_cast<OR*>(obj);
return this->opnds == other->opnds;
return opnds == context->opnds;
}
size_t SemanticContext::OR::hashCode() {
@ -236,7 +210,7 @@ size_t SemanticContext::OR::hashCode() {
std::wstring SemanticContext::OR::toString() const {
std::wstring tmp;
for(auto var : opnds) {
tmp += var->toString() + L"||";
tmp += var->toString() + L" || ";
}
return tmp;
}

View File

@ -48,22 +48,13 @@ namespace atn {
/// <seealso cref="SemanticContext"/> within the scope of this outer class.
/// </summary>
class SemanticContext {
public:
SemanticContext *parent;
static SemanticContext *const NONE;
virtual size_t hashCode() = 0;
class Predicate;
class PrecedencePredicate;
class AND;
class OR;
SemanticContext *parent;
virtual std::wstring toString() const = 0;
virtual bool equals(void *obj);
virtual bool operator == (const SemanticContext &other) const = 0;
/// <summary>
/// For context independent predicates, we evaluate them without a local
@ -78,22 +69,18 @@ namespace atn {
/// prediction, so we passed in the outer context here in case of context
/// dependent predicate evaluation.
/// </summary>
// Abstract
template<typename ATNInterpreter>
bool eval(Recognizer<ATNInterpreter> *parser, RuleContext *outerContext) {
// In the original Java this is abstract, but
// C++ complains with a link error, and we
// cannot make a template function abstract
throw new ASSERTException(L"SemanticContext::eval", L"Should never be called, abstract class");
}
virtual bool eval(Recognizer *parser, RuleContext *outerContext) = 0;
static SemanticContext *And(SemanticContext *a, SemanticContext *b);
///
/// <seealso cref= ParserATNSimulator#getPredsForAmbigAlts </seealso>
/// See also: ParserATNSimulator::getPredsForAmbigAlts.
static SemanticContext *Or(SemanticContext *a, SemanticContext *b);
class Predicate;
class PrecedencePredicate;
class AND;
class OR;
private:
template<typename T1> // where T1 : SemanticContext
static std::vector<PrecedencePredicate*> filterPrecedencePredicates(std::vector<T1> *collection) {
@ -125,16 +112,13 @@ namespace atn {
public:
Predicate(int ruleIndex, int predIndex, bool isCtxDependent);
template<typename ATNInterpreter>
bool eval(Recognizer<ATNInterpreter> *parser, RuleContext *outerContext) {
virtual bool eval(Recognizer *parser, RuleContext *outerContext) override {
RuleContext *localctx = isCtxDependent ? outerContext : nullptr;
return parser->sempred(localctx, ruleIndex, predIndex);
}
virtual size_t hashCode() override;
virtual bool equals(void *obj) override;
virtual bool operator == (const SemanticContext &other) const override;
virtual std::wstring toString() const override;
};
@ -148,21 +132,16 @@ namespace atn {
public:
PrecedencePredicate(int precedence);
template<typename ATNInterpreter>
bool eval(Recognizer<ATNInterpreter> *parser, RuleContext *outerContext) {
virtual bool eval(Recognizer *parser, RuleContext *outerContext) override {
return parser->precpred(outerContext, precedence);
}
virtual int compareTo(PrecedencePredicate *o);
virtual size_t hashCode() override;
virtual bool equals(void *obj) override;
virtual bool operator == (const SemanticContext &other) const override;
virtual std::wstring toString() const override;
static bool lessThan(const PrecedencePredicate &a,
const PrecedencePredicate &b) {
static bool lessThan(const PrecedencePredicate &a, const PrecedencePredicate &b) {
return a.precedence < b.precedence;
}
static bool greaterThan(const PrecedencePredicate &a,
@ -177,12 +156,10 @@ namespace atn {
AND(SemanticContext *a, SemanticContext *b);
virtual bool equals(void *obj) override;
virtual bool operator == (const SemanticContext &other) const override;
virtual size_t hashCode() override;
template<typename ATNInterpreter>
bool eval(Recognizer<ATNInterpreter> *parser, RuleContext *outerContext) {
virtual bool eval(Recognizer *parser, RuleContext *outerContext) override {
for (auto opnd : opnds) {
if (!opnd->eval(parser, outerContext)) {
return false;
@ -201,12 +178,10 @@ namespace atn {
OR(SemanticContext *a, SemanticContext *b);
virtual bool equals(SemanticContext *obj);
virtual bool operator == (const SemanticContext &other) const override;
virtual size_t hashCode() override;
template<typename ATNInterpreter>
bool eval(Recognizer<ATNInterpreter> *parser, RuleContext *outerContext) {
virtual bool eval(Recognizer *parser, RuleContext *outerContext) override {
for (auto opnd : opnds) {
if (opnd->eval(parser, outerContext)) {
return true;

View File

@ -61,12 +61,12 @@ int SingletonPredictionContext::getReturnState(size_t index) const {
return returnState;
}
bool SingletonPredictionContext::operator == (PredictionContext *o) const {
if (this == o) {
bool SingletonPredictionContext::operator == (const PredictionContext &o) const {
if (this == &o) {
return true;
}
SingletonPredictionContext *other = dynamic_cast<SingletonPredictionContext*>(o);
const SingletonPredictionContext *other = dynamic_cast<const SingletonPredictionContext*>(&o);
if (other == nullptr) {
return false;
}

View File

@ -51,7 +51,7 @@ namespace atn {
virtual size_t size() const override;
virtual PredictionContext *getParent(size_t index) const override;
virtual int getReturnState(size_t index) const override;
virtual bool operator == (PredictionContext *o) const override;
virtual bool operator == (const PredictionContext &o) const override;
virtual std::wstring toString() const;
};

View File

@ -45,7 +45,7 @@ const std::vector<std::wstring> Transition::serializationNames = {
Transition::Transition(ATNState *target) {
if (target == nullptr) {
throw NullPointerException(L"target cannot be null.");
throw NullPointerException("target cannot be null.");
}
this->target = target;

View File

@ -39,8 +39,7 @@
using namespace org::antlr::v4::runtime::dfa;
// TODO -- Make sure this reference doesn't go away prematurely.
DFASerializer::DFASerializer(DFA *dfa, const std::vector<std::wstring>& tokenNames) : dfa(dfa), tokenNames_(tokenNames) {
DFASerializer::DFASerializer(DFA *dfa, const std::vector<std::wstring>& tnames) : dfa(dfa), tokenNames(tnames) {
}
std::wstring DFASerializer::toString() {
@ -64,7 +63,7 @@ std::wstring DFASerializer::toString() {
if (output.length() == 0) {
return L"";
}
//return Utils.sortLinesInString(output);
return output;
}
@ -73,8 +72,8 @@ std::wstring DFASerializer::getEdgeLabel(size_t i) {
if (i == 0) {
return L"EOF";
}
if (!tokenNames_.empty()) {
label = tokenNames_[i - 1];
if (!tokenNames.empty()) {
label = tokenNames[i - 1];
} else {
label = antlrcpp::StringConverterHelper::toString(i - 1);
}
@ -91,9 +90,9 @@ std::wstring DFASerializer::getStateString(DFAState *s) {
for (size_t i = 0; i < s->predicates.size(); i++) {
buf.append(s->predicates[i]->toString());
}
return baseStateStr + std::wstring(L"=>") + buf;
return baseStateStr + L" => " + buf;
} else {
return baseStateStr + std::wstring(L"=>") + std::to_wstring(s->prediction);
return baseStateStr + L" => " + std::to_wstring(s->prediction);
}
} else {
return baseStateStr;

View File

@ -37,20 +37,18 @@ namespace v4 {
namespace runtime {
namespace dfa {
/// <summary>
/// A DFA walker that knows how to dump them to serialized strings. </summary>
/// A DFA walker that knows how to dump them to serialized strings.
class DFASerializer {
public:
DFA *const dfa;
const std::vector<std::wstring>& tokenNames_;
const std::vector<std::wstring>& tokenNames;
DFASerializer(DFA *dfa, const std::vector<std::wstring>& tokenNames);
DFASerializer(DFA *dfa, const std::vector<std::wstring>& tnames);
virtual std::wstring toString();
protected:
virtual std::wstring getEdgeLabel(size_t i);
virtual std::wstring getStateString(DFAState *s);
};

View File

@ -106,6 +106,6 @@ Interval Interval::intersection(const Interval &other) const {
return Interval(std::max(a, other.a), std::min(b, other.b));
}
std::wstring Interval::toString() const {
return std::to_wstring(a) + L".." + std::to_wstring(b);
std::string Interval::toString() const {
return std::to_string(a) + ".." + std::to_string(b);
}

View File

@ -101,7 +101,7 @@ namespace misc {
/// Return the interval in common between this and o </summary>
virtual Interval intersection(const Interval &other) const;
virtual std::wstring toString() const;
virtual std::string toString() const;
private:
};

View File

@ -32,6 +32,7 @@
#include "MurmurHash.h"
#include "Lexer.h"
#include "StringBuilder.h"
#include "Exceptions.h"
#include "IntervalSet.h"
@ -71,14 +72,14 @@ IntervalSet IntervalSet::of(int a, int b) {
void IntervalSet::clear() {
if (_readonly) {
throw new IllegalStateException(L"can't alter read only IntervalSet");
throw new IllegalStateException("can't alter read only IntervalSet");
}
_intervals.clear();
}
void IntervalSet::add(int el) {
if (_readonly) {
throw new IllegalStateException(L"can't alter read only IntervalSet");
throw new IllegalStateException("can't alter read only IntervalSet");
}
add(el, el);
}
@ -89,7 +90,7 @@ void IntervalSet::add(int a, int b) {
void IntervalSet::add(const Interval &addition) {
if (_readonly) {
throw new IllegalStateException(L"can't alter read only IntervalSet");
throw new IllegalStateException("can't alter read only IntervalSet");
}
if (addition.b < addition.a) {
@ -483,7 +484,7 @@ int IntervalSet::get(int i) const {
void IntervalSet::remove(int el) {
if (_readonly) {
throw IllegalStateException(L"can't alter read only IntervalSet");
throw IllegalStateException("can't alter read only IntervalSet");
}
for (size_t i = 0; i < _intervals.size(); ++i) {

View File

@ -36,6 +36,7 @@ namespace antlrcpp {
class Arrays {
public:
static std::wstring listToString(const std::vector<std::wstring> &list, const std::wstring &separator);
template <typename T>
@ -44,12 +45,24 @@ namespace antlrcpp {
return false;
for (size_t i = 0; i < a.size(); ++i)
if (a[i] != b[i]) // Requires that the == operator is supported by the template type.
if (a[i] != b[i]) // Requires that the != operator is supported by the template type.
return false;
return true;
}
template <typename T>
static bool equals(const std::vector<T *> &a, const std::vector<T *> &b) {
if (a.size() != b.size())
return false;
for (size_t i = 0; i < a.size(); ++i)
if (*a[i] != *b[i]) // Requires that the != operator is supported by the template type.
return false;
return true;
}
template <typename T>
static std::vector<T> copyOf(const std::vector<T> &source, size_t count) {
std::vector<T> result;

View File

@ -80,7 +80,7 @@ namespace org {
class ParserRuleContext;
class ProxyErrorListener;
class RecognitionException;
template<typename ATNInterpreter> class Recognizer;
class Recognizer;
class RuleContext;
class Token;
template<typename Symbol> class TokenFactory;

View File

@ -32,6 +32,7 @@
#include "ErrorNode.h"
#include "Parser.h"
#include "StringBuilder.h"
#include "CPPUtils.h"
#include "Trees.h"

View File

@ -34,6 +34,7 @@
#include "TerminalNode.h"
#include "ParserRuleContext.h"
#include "Recognizer.h"
#include "Token.h"
namespace org {
namespace antlr {

View File

@ -39,15 +39,15 @@ using namespace org::antlr::v4::runtime::tree::pattern;
ParseTreeMatch::ParseTreeMatch(ParseTree *tree, ParseTreePattern *pattern, misc::MultiMap<std::wstring, ParseTree*> *labels, ParseTree *mismatchedNode) : tree(tree), pattern(pattern), labels(labels), mismatchedNode(mismatchedNode) {
if (tree == nullptr) {
throw IllegalArgumentException(L"tree cannot be null");
throw IllegalArgumentException("tree cannot be null");
}
if (pattern == nullptr) {
throw IllegalArgumentException(L"pattern cannot be null");
throw IllegalArgumentException("pattern cannot be null");
}
if (labels == nullptr) {
throw IllegalArgumentException(L"labels cannot be null");
throw IllegalArgumentException("labels cannot be null");
}
}

View File

@ -46,6 +46,8 @@
#include "ANTLRInputStream.h"
#include "Arrays.h"
#include "MultiMap.h"
#include "Exceptions.h"
#include "Strings.h"
#include "ParseTreePatternMatcher.h"
@ -62,11 +64,11 @@ ParseTreePatternMatcher::ParseTreePatternMatcher(Lexer *lexer, Parser *parser) :
void ParseTreePatternMatcher::setDelimiters(const std::wstring &start, const std::wstring &stop, const std::wstring &escapeLeft) {
if (start == L"" || start.length() == 0) {
throw new IllegalArgumentException(L"start cannot be null or empty");
throw new IllegalArgumentException("start cannot be null or empty");
}
if (stop == L"" || stop.length() == 0) {
throw new IllegalArgumentException(L"stop cannot be null or empty");
throw new IllegalArgumentException("stop cannot be null or empty");
}
this->start = start;
@ -126,11 +128,11 @@ Parser *ParseTreePatternMatcher::getParser() {
tree::ParseTree *ParseTreePatternMatcher::matchImpl(ParseTree *tree, ParseTree *patternTree, misc::MultiMap<std::wstring, ParseTree*> *labels) {
if (tree == nullptr) {
throw new IllegalArgumentException(L"tree cannot be null");
throw new IllegalArgumentException("tree cannot be null");
}
if (patternTree == nullptr) {
throw IllegalArgumentException(L"patternTree cannot be null");
throw IllegalArgumentException("patternTree cannot be null");
}
// x and <ID>, x and y, or x and x; or could be mismatched types
@ -238,19 +240,19 @@ std::vector<Token*> ParseTreePatternMatcher::tokenize(const std::wstring &patter
if (isupper(tagChunk->getTag()[0])) {
int ttype = parser->getTokenType(tagChunk->getTag());
if (ttype == Token::INVALID_TYPE) {
throw IllegalArgumentException(std::wstring(L"Unknown token ") + tagChunk->getTag() + std::wstring(L" in pattern: ") + pattern);
throw IllegalArgumentException(std::string("Unknown token ") + antlrcpp::ws2s(tagChunk->getTag()) + std::string(" in pattern: ") + antlrcpp::ws2s(pattern));
}
TokenTagToken *t = new TokenTagToken(tagChunk->getTag(), ttype, tagChunk->getLabel());
tokens.push_back(t);
} else if (islower(tagChunk->getTag()[0])) {
int ruleIndex = parser->getRuleIndex(tagChunk->getTag());
if (ruleIndex == -1) {
throw IllegalArgumentException(std::wstring(L"Unknown rule ") + tagChunk->getTag() + std::wstring(L" in pattern: ") + pattern);
throw IllegalArgumentException(std::string("Unknown rule ") + antlrcpp::ws2s(tagChunk->getTag()) + " in pattern: " + antlrcpp::ws2s(pattern));
}
int ruleImaginaryTokenType = parser->getATNWithBypassAlts().ruleToTokenType[(size_t)ruleIndex];
tokens.push_back(new RuleTagToken(tagChunk->getTag(), ruleImaginaryTokenType, tagChunk->getLabel()));
} else {
throw IllegalArgumentException(std::wstring(L"invalid tag: ") + tagChunk->getTag() + std::wstring(L" in pattern: ") + pattern);
throw IllegalArgumentException(std::string("invalid tag: ") + antlrcpp::ws2s(tagChunk->getTag()) + " in pattern: " + antlrcpp::ws2s(pattern));
}
} else {
TextChunk *textChunk = static_cast<TextChunk*>(chunk);
@ -292,21 +294,18 @@ std::vector<Chunk*> ParseTreePatternMatcher::split(const std::wstring &pattern)
}
}
// System.out.println("");
// System.out.println(starts);
// System.out.println(stops);
if (starts.size() > stops.size()) {
throw IllegalArgumentException(std::wstring(L"unterminated tag in pattern: ") + pattern);
throw IllegalArgumentException(std::string("unterminated tag in pattern: ") + antlrcpp::ws2s(pattern));
}
if (starts.size() < stops.size()) {
throw IllegalArgumentException(std::wstring(L"missing start tag in pattern: ") + pattern);
throw IllegalArgumentException(std::string("missing start tag in pattern: ") + antlrcpp::ws2s(pattern));
}
size_t ntags = starts.size();
for (size_t i = 0; i < ntags; i++) {
if (starts[i] >= stops[i]) {
throw IllegalArgumentException(std::wstring(L"tag delimiters out of order in pattern: ") + pattern);
throw IllegalArgumentException(std::string("tag delimiters out of order in pattern: ") + antlrcpp::ws2s(pattern));
}
}

View File

@ -39,8 +39,8 @@ RuleTagToken::RuleTagToken(const std::wstring &ruleName, int _bypassTokenType) :
}
RuleTagToken::RuleTagToken(const std::wstring &ruleName, int bypassTokenType, const std::wstring &label) : ruleName(ruleName), bypassTokenType(bypassTokenType), label(label) {
if (ruleName == L"" || ruleName.length() == 0) {
throw IllegalArgumentException(L"ruleName cannot be null or empty.");
if (ruleName.empty()) {
throw IllegalArgumentException("ruleName cannot be null or empty.");
}
}

View File

@ -35,28 +35,28 @@
using namespace org::antlr::v4::runtime::tree::pattern;
TagChunk::TagChunk(const std::wstring &tag) {
TagChunk::TagChunk(const std::wstring &tag) : TagChunk(L"", tag) {
}
TagChunk::TagChunk(const std::wstring &label, const std::wstring &tag) : tag(tag), label(label) {
if (tag == L"" || tag.length() == 0) {
throw IllegalArgumentException(L"tag cannot be null or empty");
TagChunk::TagChunk(const std::wstring &label, const std::wstring &tag) : _tag(tag), _label(label) {
if (tag.empty()) {
throw IllegalArgumentException("tag cannot be null or empty");
}
}
std::wstring TagChunk::getTag() {
return tag;
return _tag;
}
std::wstring TagChunk::getLabel() {
return label;
return _label;
}
std::wstring TagChunk::toString() {
if (label != L"") {
return label + std::wstring(L":") + tag;
if (!_label.empty()) {
return _label + L":" + _tag;
}
return tag;
return _tag;
}

View File

@ -59,11 +59,11 @@ namespace pattern {
/// This is the backing field for <seealso cref="#getTag"/>.
/// </summary>
private:
const std::wstring tag;
const std::wstring _tag;
/// <summary>
/// This is the backing field for <seealso cref="#getLabel"/>.
/// </summary>
const std::wstring label;
const std::wstring _label;
/// <summary>
/// Construct a new instance of <seealso cref="TagChunk"/> using the specified tag and

View File

@ -37,7 +37,7 @@ using namespace org::antlr::v4::runtime::tree::pattern;
TextChunk::TextChunk(const std::wstring &text) : text(text) {
if (text == L"") {
throw IllegalArgumentException(L"text cannot be null");
throw IllegalArgumentException("text cannot be null");
}
}

View File

@ -655,7 +655,7 @@ setState(<choice.stateNumber>);
_errHandler->sync(this);
<! TODO: untested !><if (choice.label)><labelref(choice.label)> = _input->LT(1);<endif>
<! TODO: untested !><preamble; separator = "\n">
switch (getInterpreter()->adaptivePredict(_input, <choice.decision>, ctx)) {
switch (getInterpreter\<atn::ParserATNSimulator>()->adaptivePredict(_input, <choice.decision>, ctx)) {
<alts: {alt | case <i>:
<alt>
break;
@ -668,7 +668,7 @@ OptionalBlock(choice, alts, error) ::= <<
setState(<choice.stateNumber>);
_errHandler->sync(this);
switch (getInterpreter()->adaptivePredict(_input, <choice.decision>, ctx)) {
switch (getInterpreter\<atn::ParserATNSimulator>()->adaptivePredict(_input, <choice.decision>, ctx)) {
<alts: {alt | case <i><if (!choice.ast.greedy)>+1<endif>:
<alt>
break;
@ -680,7 +680,7 @@ StarBlockHeader(choice, alts, sync, iteration) ::= "<! Unused but must be presen
StarBlock(choice, alts, sync, iteration) ::= <<
setState(<choice.stateNumber>);
_errHandler->sync(this);
alt = getInterpreter()->adaptivePredict(_input, <choice.decision>, ctx);
alt = getInterpreter\<atn::ParserATNSimulator>()->adaptivePredict(_input, <choice.decision>, ctx);
while (alt != <choice.exitAlt> && alt != -1) {
if ( alt == 1 <if(!choice.ast.greedy)>+ 1<endif>) {
<iteration>
@ -688,7 +688,7 @@ while (alt != <choice.exitAlt> && alt != -1) {
}
setState(<choice.loopBackStateNumber>);
_errHandler->sync(this);
alt = getInterpreter()->adaptivePredict(_input, <choice.decision>, ctx);
alt = getInterpreter\<atn::ParserATNSimulator>()->adaptivePredict(_input, <choice.decision>, ctx);
}
>>
@ -696,7 +696,7 @@ PlusBlockHeader(choice, alts, error) ::= "<! Required to exist, but unused. !>"
PlusBlock(choice, alts, error) ::= <<
setState(<choice.blockStartStateNumber>); <! alt block decision !>
_errHandler->sync(this);
alt = getInterpreter()->adaptivePredict(_input, <choice.decision>, ctx);
alt = getInterpreter\<atn::ParserATNSimulator>()->adaptivePredict(_input, <choice.decision>, ctx);
do {
switch (alt) {
<alts: {alt | case <i><if (!choice.ast.greedy)> + 1<endif>:
@ -708,7 +708,7 @@ do {
}
setState(<choice.loopBackStateNumber>); <! loopback/exit decision !>
_errHandler->sync(this);
alt = getInterpreter()->adaptivePredict(_input, <choice.decision>, ctx);
alt = getInterpreter\<atn::ParserATNSimulator>()->adaptivePredict(_input, <choice.decision>, ctx);
} while (alt != <choice.exitAlt> && alt != -1);
>>
@ -797,7 +797,7 @@ SemPred(p, chunks, failChunks) ::= <<
setState(<p.stateNumber>);
<! TODO: failChunks + p.msg untested !>
if (!(<chunks>)) throw new FailedPredicateException(this, L<p.predicate><if (failChunks)>, <failChunks><elseif (p.msg)>, L<p.msg><endif>);
if (!(<chunks>)) throw new FailedPredicateException(this, <p.predicate><if (failChunks)>, <failChunks><elseif (p.msg)>, L<p.msg><endif>);
>>
ExceptionClauseHeader(e, catchArg, catchAction) ::= "<! Required but unused. !>"

View File

@ -70,7 +70,7 @@ LexerFile(file, lexer, namedActions) ::= <<
#include "<file.factory.grammar.name>.h"
using namespace org::antlr::v4::runtime;
using namespace antlrcpp;
<if (file.genPackage)>using namespace <file.genPackage>;<endif>
<lexer>
@ -84,6 +84,7 @@ ParserFileHeader(file, parser, namedActions) ::= <<
#include "Parser.h"
#include "ParserRuleContext.h"
#include "CPPUtils.h"
//#include "<file.grammarName>Visitor.h"
using namespace org::antlr::v4::runtime;