From 15aa407757b9f98475cf2e33a25f272a00ccf04c Mon Sep 17 00:00:00 2001 From: Peter Boyer Date: Tue, 15 Dec 2015 21:01:08 -0500 Subject: [PATCH] Banish instanceof to hell --- runtime/Go/src/antlr4/BufferedTokenStream.go | 47 +++-- runtime/Go/src/antlr4/LL1Analyzer.go | 2 +- runtime/Go/src/antlr4/Parser.go | 2 +- runtime/Go/src/antlr4/ParserRuleContext.go | 16 +- runtime/Go/src/antlr4/PredictionContext.go | 30 +++- runtime/Go/src/antlr4/Recognizer.go | 15 +- runtime/Go/src/antlr4/RuleContext.go | 29 ++- runtime/Go/src/antlr4/Utils.go | 2 +- runtime/Go/src/antlr4/atn/ATN.go | 2 +- runtime/Go/src/antlr4/atn/ATNConfig.go | 6 +- runtime/Go/src/antlr4/atn/ATNConfigSet.go | 2 +- runtime/Go/src/antlr4/atn/ATNDeserializer.go | 36 ++-- runtime/Go/src/antlr4/atn/ATNSimulator.go | 5 + .../Go/src/antlr4/atn/LexerATNSimulator.go | 24 +-- runtime/Go/src/antlr4/atn/LexerAction.go | 12 +- .../Go/src/antlr4/atn/LexerActionExecutor.go | 4 +- .../Go/src/antlr4/atn/ParserATNSimulator.go | 123 +++++++------ runtime/Go/src/antlr4/atn/PredictionMode.go | 170 +++++++++--------- runtime/Go/src/antlr4/atn/SemanticContext.go | 18 +- runtime/Go/src/antlr4/dfa/DFAState.go | 2 +- runtime/Go/src/antlr4/error/ErrorStrategy.go | 4 +- runtime/Go/src/antlr4/error/Errors.go | 2 +- runtime/Go/src/antlr4/tree/Tree.go | 2 +- runtime/Go/src/antlr4/tree/Trees.go | 8 +- 24 files changed, 299 insertions(+), 264 deletions(-) diff --git a/runtime/Go/src/antlr4/BufferedTokenStream.go b/runtime/Go/src/antlr4/BufferedTokenStream.go index 950bee736..d73cf596a 100644 --- a/runtime/Go/src/antlr4/BufferedTokenStream.go +++ b/runtime/Go/src/antlr4/BufferedTokenStream.go @@ -71,7 +71,7 @@ func (bt *BufferedTokenStream) mark() int { return 0 } -func (bt *BufferedTokenStream) release(marker) { +func (bt *BufferedTokenStream) release(marker int) { // no resources to release } @@ -118,7 +118,7 @@ func (bt *BufferedTokenStream) consume() { // {@code false}. // @see //get(int i) // / -func (bt *BufferedTokenStream) sync(i) { +func (bt *BufferedTokenStream) sync(i int) { var n = i - len(bt.tokens) + 1 // how many more elements we need? if (n > 0) { var fetched = bt.fetch(n) @@ -132,7 +132,7 @@ func (bt *BufferedTokenStream) sync(i) { // @return The actual number of elements added to the buffer. // / func (bt *BufferedTokenStream) fetch(n int) int { - if (bt.fetchedEOF) { + if bt.fetchedEOF { return 0 } @@ -140,7 +140,7 @@ func (bt *BufferedTokenStream) fetch(n int) int { var t = bt.tokenSource.nextToken() t.tokenIndex = len(bt.tokens) bt.tokens.push(t) - if (t.type == TokenEOF) { + if (t.tokenType == TokenEOF) { bt.fetchedEOF = true return i + 1 } @@ -149,10 +149,8 @@ func (bt *BufferedTokenStream) fetch(n int) int { } // Get all tokens from start..stop inclusively/// -func (bt *BufferedTokenStream) getTokens(start, stop, types) { - if (types == undefined) { - types = nil - } +func (bt *BufferedTokenStream) getTokens(start int, stop int, types []int) []Token { + if (start < 0 || stop < 0) { return nil } @@ -163,28 +161,28 @@ func (bt *BufferedTokenStream) getTokens(start, stop, types) { } for i := start; i < stop; i++ { var t = bt.tokens[i] - if (t.type == TokenEOF) { + if (t.tokenType == TokenEOF) { break } - if (types == nil || types.contains(t.type)) { + if (types == nil || types.contains(t.tokenType)) { subset.push(t) } } return subset } -func (bt *BufferedTokenStream) LA(i) { - return bt.LT(i).type +func (bt *BufferedTokenStream) LA(i int) int { + return bt.LT(i).tokenType } -func (bt *BufferedTokenStream) LB(k) { +func (bt *BufferedTokenStream) LB(k int) Token { if (bt.index - k < 0) { return nil } return bt.tokens[bt.index - k] } -func (bt *BufferedTokenStream) LT(k) { +func (bt *BufferedTokenStream) LT(k int) Token { bt.lazyInit() if (k == 0) { return nil @@ -214,7 +212,7 @@ func (bt *BufferedTokenStream) LT(k) { // @param i The target token index. // @return The adjusted target token index. -func (bt *BufferedTokenStream) adjustSeekIndex(i) { +func (bt *BufferedTokenStream) adjustSeekIndex(i int) int { return i } @@ -230,7 +228,7 @@ func (bt *BufferedTokenStream) setup() { } // Reset bt token stream by setting its token source./// -func (bt *BufferedTokenStream) setTokenSource(tokenSource) { +func (bt *BufferedTokenStream) setTokenSource(tokenSource *TokenSource) { bt.tokenSource = tokenSource bt.tokens = [] bt.index = -1 @@ -272,15 +270,11 @@ func (bt *BufferedTokenStream) previousTokenOnChannel(i, channel int) { // the current token up until we see a token on DEFAULT_TOKEN_CHANNEL or // EOF. If channel is -1, find any non default channel token. func (bt *BufferedTokenStream) getHiddenTokensToRight(tokenIndex, channel int) { - if (channel == undefined) { - channel = -1 - } bt.lazyInit() if (bt.tokenIndex < 0 || tokenIndex >= len(bt.tokens)) { panic( "" + tokenIndex + " not in 0.." + len(bt.tokens) - 1 } - var nextOnChannel = bt.nextTokenOnChannel(tokenIndex + 1, - LexerDefaultTokenChannel) + var nextOnChannel = bt.nextTokenOnChannel(tokenIndex + 1, LexerDefaultTokenChannel) var from_ = tokenIndex + 1 // if none onchannel to right, nextOnChannel=-1 so set to = last token var to = nextOnChannel == -1 ? len(bt.tokens) - 1 : nextOnChannel @@ -298,8 +292,7 @@ func (bt *BufferedTokenStream) getHiddenTokensToLeft(tokenIndex, channel int) { if (tokenIndex < 0 || tokenIndex >= len(bt.tokens)) { panic( "" + tokenIndex + " not in 0.." + len(bt.tokens) - 1 } - var prevOnChannel = bt.previousTokenOnChannel(tokenIndex - 1, - LexerDefaultTokenChannel) + var prevOnChannel = bt.previousTokenOnChannel(tokenIndex - 1, LexerDefaultTokenChannel) if (prevOnChannel == tokenIndex - 1) { return nil } @@ -315,7 +308,7 @@ func (bt *BufferedTokenStream) filterForChannel(left, right, channel int) { var t = bt.tokens[i] if (channel == -1) { if (t.channel != LexerDefaultTokenChannel) { - hidden.push(t) + append(hidden, t) } } else if (t.channel == channel) { hidden.push(t) @@ -339,11 +332,11 @@ func (bt *BufferedTokenStream) getText(interval *Interval) string { interval = NewInterval(0, len(bt.tokens) - 1) } var start = interval.start - if (start instanceof Token) { + if _, ok := start.(Token); ok { start = start.tokenIndex } var stop = interval.stop - if (stop instanceof Token) { + if _, ok := stop.(Token); ok { stop = stop.tokenIndex } if (start == nil || stop == nil || start < 0 || stop < 0) { @@ -355,7 +348,7 @@ func (bt *BufferedTokenStream) getText(interval *Interval) string { var s = "" for i := start; i < stop + 1; i++ { var t = bt.tokens[i] - if (t.type == TokenEOF) { + if (t.tokenType == TokenEOF) { break } s = s + t.text diff --git a/runtime/Go/src/antlr4/LL1Analyzer.go b/runtime/Go/src/antlr4/LL1Analyzer.go index 515d7aecf..9dbdfa6bf 100644 --- a/runtime/Go/src/antlr4/LL1Analyzer.go +++ b/runtime/Go/src/antlr4/LL1Analyzer.go @@ -190,7 +190,7 @@ func (la *LL1Analyzer) _LOOK(s, stopState , ctx, look, lookBusy, calledRuleStack } else { var set = t.label if (set != nil) { - if (t instanceof NotSetTransition) { + if _, ok := t.(NotSetTransition); ok { set = set.complement(TokenMinUserTokenType, la.atn.maxTokenType) } look.addSet(set) diff --git a/runtime/Go/src/antlr4/Parser.go b/runtime/Go/src/antlr4/Parser.go index ee937bdab..7735a4120 100644 --- a/runtime/Go/src/antlr4/Parser.go +++ b/runtime/Go/src/antlr4/Parser.go @@ -289,7 +289,7 @@ func (p.*Parser) compileParseTreePattern(pattern, patternRuleIndex, lexer) { if (lexer == nil) { if (p.getTokenStream() != nil) { var tokenSource = p.getTokenStream().tokenSource - if (tokenSource instanceof Lexer) { + if _, ok := tokenSource.(Lexer); ok { lexer = tokenSource } } diff --git a/runtime/Go/src/antlr4/ParserRuleContext.go b/runtime/Go/src/antlr4/ParserRuleContext.go index 58d3fc950..e971c8791 100644 --- a/runtime/Go/src/antlr4/ParserRuleContext.go +++ b/runtime/Go/src/antlr4/ParserRuleContext.go @@ -118,7 +118,7 @@ func (prc *ParserRuleContext) getChild(i, type) { } else { for(var j=0 j= 0 && ri < ruleNames.length) ? ruleNames[ri] - : "" + ri + var ruleName = (ri >= 0 && ri < ruleNames.length) ? ruleNames[ri] : "" + ri s += ruleName } if (p.parentCtx != nil && (ruleNames != nil || !p.parentCtx.isEmpty())) { diff --git a/runtime/Go/src/antlr4/Utils.go b/runtime/Go/src/antlr4/Utils.go index 84def2695..eea6bf95c 100644 --- a/runtime/Go/src/antlr4/Utils.go +++ b/runtime/Go/src/antlr4/Utils.go @@ -119,7 +119,7 @@ func (this *BitSet) hashString() { } func (this *BitSet) equals(other) { - if(!(other instanceof BitSet)) { + if(!_, ok := other.(BitSet); ok) { return false } return this.hashString()==other.hashString() diff --git a/runtime/Go/src/antlr4/atn/ATN.go b/runtime/Go/src/antlr4/atn/ATN.go index 63415b7a8..277ba21a2 100644 --- a/runtime/Go/src/antlr4/atn/ATN.go +++ b/runtime/Go/src/antlr4/atn/ATN.go @@ -16,7 +16,7 @@ type ATN struct { modeToStartState } -func NewATN(grammarType , maxTokenType) ATN { +func NewATN(grammarType , maxTokenType) *ATN { atn := new(ATN) diff --git a/runtime/Go/src/antlr4/atn/ATNConfig.go b/runtime/Go/src/antlr4/atn/ATNConfig.go index 52edd3b5f..6f7a5b77e 100644 --- a/runtime/Go/src/antlr4/atn/ATNConfig.go +++ b/runtime/Go/src/antlr4/atn/ATNConfig.go @@ -74,7 +74,7 @@ func (this *ATNConfig) checkContext(params, config) { func (this *ATNConfig) equals(other) { if (this == other) { return true - } else if (! (other instanceof ATNConfig)) { + } else if (! _, ok := other.(ATNConfig); ok) { return false } else { return this.state.stateNumber==other.state.stateNumber && @@ -129,7 +129,7 @@ func (this *LexerATNConfig) hashString() { func (this *LexerATNConfig) equals(other) { if (this == other) { return true - } else if (!(other instanceof LexerATNConfig)) { + } else if (!_, ok := other.(LexerATNConfig); ok) { return false } else if (this.passedThroughNonGreedyDecision != other.passedThroughNonGreedyDecision) { return false @@ -144,7 +144,7 @@ func (this *LexerATNConfig) equals(other) { func (this *LexerATNConfig) checkNonGreedyDecision(source, target) { return source.passedThroughNonGreedyDecision || - (target instanceof DecisionState) && target.nonGreedy + _, ok := target.(DecisionState); ok && target.nonGreedy } diff --git a/runtime/Go/src/antlr4/atn/ATNConfigSet.go b/runtime/Go/src/antlr4/atn/ATNConfigSet.go index 322abe2a3..6044af035 100644 --- a/runtime/Go/src/antlr4/atn/ATNConfigSet.go +++ b/runtime/Go/src/antlr4/atn/ATNConfigSet.go @@ -162,7 +162,7 @@ func (this *ATNConfigSet) addAll(coll) { func (this *ATNConfigSet) equals(other) { if (this == other) { return true - } else if (!(other instanceof ATNConfigSet)) { + } else if (!_, ok := other.(ATNConfigSet); ok) { return false } return this.configs != nil && this.configs.equals(other.configs) && diff --git a/runtime/Go/src/antlr4/atn/ATNDeserializer.go b/runtime/Go/src/antlr4/atn/ATNDeserializer.go index 5955c8823..01f66f72b 100644 --- a/runtime/Go/src/antlr4/atn/ATNDeserializer.go +++ b/runtime/Go/src/antlr4/atn/ATNDeserializer.go @@ -172,7 +172,7 @@ func (this *ATNDeserializer) readStates(atn) { if (stype == ATNStateLOOP_END) { // special case var loopBackStateNumber = this.readInt() loopBackStateNumbers.push([s, loopBackStateNumber]) - } else if(s instanceof BlockStartState) { + } else if_, ok := s.(BlockStartState); ok { var endStateNumber = this.readInt() endStateNumbers.push([s, endStateNumber]) } @@ -225,7 +225,7 @@ func (this *ATNDeserializer) readRules(atn) { atn.ruleToStopState = initArray(nrules, 0) for (i=0 i= 0) } else { - this.checkCondition(state.transitions.length <= 1 || (state instanceof RuleStopState)) + this.checkCondition(state.transitions.length <= 1 || _, ok := state.(RuleStopState); ok) } } } diff --git a/runtime/Go/src/antlr4/atn/ATNSimulator.go b/runtime/Go/src/antlr4/atn/ATNSimulator.go index 8d171519b..b9454afd6 100644 --- a/runtime/Go/src/antlr4/atn/ATNSimulator.go +++ b/runtime/Go/src/antlr4/atn/ATNSimulator.go @@ -4,6 +4,11 @@ package atn //var ATNConfigSet = require('./ATNConfigSet').ATNConfigSet //var getCachedPredictionContext = require('./../PredictionContext').getCachedPredictionContext +type ATNSimulator struct { + atn *ATN + sharedContextCache +} + func ATNSimulator(atn, sharedContextCache) { // The context cache maps all PredictionContext objects that are == diff --git a/runtime/Go/src/antlr4/atn/LexerATNSimulator.go b/runtime/Go/src/antlr4/atn/LexerATNSimulator.go index 410e75c8e..44c5281b2 100644 --- a/runtime/Go/src/antlr4/atn/LexerATNSimulator.go +++ b/runtime/Go/src/antlr4/atn/LexerATNSimulator.go @@ -117,7 +117,7 @@ func (this *LexerATNSimulator) matchATN(input) { var startState = this.atn.modeToStartState[this.mode] if (this.debug) { - console.log("matchATN mode " + this.mode + " start: " + startState) + fmt.Println("matchATN mode " + this.mode + " start: " + startState) } var old_mode = this.mode var s0_closure = this.computeStartState(input, startState) @@ -132,14 +132,14 @@ func (this *LexerATNSimulator) matchATN(input) { var predict = this.execATN(input, next) if (this.debug) { - console.log("DFA after matchATN: " + this.decisionToDFA[old_mode].toLexerString()) + fmt.Println("DFA after matchATN: " + this.decisionToDFA[old_mode].toLexerString()) } return predict } LexerATNSimulator.prototype.execATN = function(input, ds0) { if (this.debug) { - console.log("start state closure=" + ds0.configs) + fmt.Println("start state closure=" + ds0.configs) } if (ds0.isAcceptState) { // allow zero-length tokens @@ -150,7 +150,7 @@ LexerATNSimulator.prototype.execATN = function(input, ds0) { for (true) { // while more work if (this.debug) { - console.log("execATN loop starting closure: " + s.configs) + fmt.Println("execATN loop starting closure: " + s.configs) } // As we move src->trg, src->trg, we keep track of the previous trg to @@ -218,7 +218,7 @@ func (this *LexerATNSimulator) getExistingTargetState(s, t) { target = nil } if (this.debug && target != nil) { - console.log("reuse state " + s.stateNumber + " edge to " + target.stateNumber) + fmt.Println("reuse state " + s.stateNumber + " edge to " + target.stateNumber) } return target } @@ -282,7 +282,7 @@ func (this *LexerATNSimulator) getReachableConfigSet(input, closure, continue } if (this.debug) { - console.log("testing %s at %s\n", this.getTokenName(t), cfg + fmt.Println("testing %s at %s\n", this.getTokenName(t), cfg .toString(this.recog, true)) } for j := 0; j < len(cfg.state.transitions); j++ { @@ -309,7 +309,7 @@ func (this *LexerATNSimulator) getReachableConfigSet(input, closure, func (this *LexerATNSimulator) accept(input, lexerActionExecutor, startIndex, index, line, charPos) { if (this.debug) { - console.log("ACTION %s\n", lexerActionExecutor) + fmt.Println("ACTION %s\n", lexerActionExecutor) } // seek to after last char in token input.seek(index) @@ -351,14 +351,14 @@ func (this *LexerATNSimulator) closure(input, config, configs, currentAltReachedAcceptState, speculative, treatEofAsEpsilon) { var cfg = nil if (this.debug) { - console.log("closure(" + config.toString(this.recog, true) + ")") + fmt.Println("closure(" + config.toString(this.recog, true) + ")") } if (config.state instanceof RuleStopState) { if (this.debug) { if (this.recog != nil) { - console.log("closure at %s rule stop %s\n", this.recog.getRuleNames()[config.state.ruleIndex], config) + fmt.Println("closure at %s rule stop %s\n", this.recog.getRuleNames()[config.state.ruleIndex], config) } else { - console.log("closure at rule stop %s\n", config) + fmt.Println("closure at rule stop %s\n", config) } } if (config.context == nil || config.context.hasEmptyPath()) { @@ -430,7 +430,7 @@ func (this *LexerATNSimulator) getEpsilonTarget(input, config, trans, // test them, we cannot cash the DFA state target of ID. if (this.debug) { - console.log("EVAL rule " + trans.ruleIndex + ":" + trans.predIndex) + fmt.Println("EVAL rule " + trans.ruleIndex + ":" + trans.predIndex) } configs.hasSemanticContext = true if (this.evaluatePredicate(input, trans.ruleIndex, trans.predIndex, speculative)) { @@ -556,7 +556,7 @@ func (this *LexerATNSimulator) addDFAEdge(from_, tk, to, cfgs) { return to } if (this.debug) { - console.log("EDGE " + from_ + " -> " + to + " upon " + tk) + fmt.Println("EDGE " + from_ + " -> " + to + " upon " + tk) } if (from_.edges == nil) { // make room for tokens 1..n and -1 masquerading as index 0 diff --git a/runtime/Go/src/antlr4/atn/LexerAction.go b/runtime/Go/src/antlr4/atn/LexerAction.go index 9adc0f840..152a5cadc 100644 --- a/runtime/Go/src/antlr4/atn/LexerAction.go +++ b/runtime/Go/src/antlr4/atn/LexerAction.go @@ -81,7 +81,7 @@ func (this *LexerTypeAction) hashString() { func (this *LexerTypeAction) equals(other) { if(this == other) { return true - } else if (! (other instanceof LexerTypeAction)) { + } else if (! _, ok := other.(LexerTypeAction); ok) { return false } else { return this.type == other.type @@ -116,7 +116,7 @@ func (this *LexerPushModeAction) hashString() { func (this *LexerPushModeAction) equals(other) { if (this == other) { return true - } else if (! (other instanceof LexerPushModeAction)) { + } else if (! _, ok := other.(LexerPushModeAction); ok) { return false } else { return this.mode == other.mode @@ -199,7 +199,7 @@ func (this *LexerModeAction) hashString() { func (this *LexerModeAction) equals(other) { if (this == other) { return true - } else if (! (other instanceof LexerModeAction)) { + } else if (! _, ok := other.(LexerModeAction); ok) { return false } else { return this.mode == other.mode @@ -252,7 +252,7 @@ func (this *LexerCustomAction) hashString() { func (this *LexerCustomAction) equals(other) { if (this == other) { return true - } else if (! (other instanceof LexerCustomAction)) { + } else if (! _, ok := other.(LexerCustomAction); ok) { return false } else { return this.ruleIndex == other.ruleIndex && this.actionIndex == other.actionIndex @@ -285,7 +285,7 @@ func (this *LexerChannelAction) hashString() { func (this *LexerChannelAction) equals(other) { if (this == other) { return true - } else if (! (other instanceof LexerChannelAction)) { + } else if (! _, ok := other.(LexerChannelAction); ok) { return false } else { return this.channel == other.channel @@ -341,7 +341,7 @@ func (this *LexerIndexedCustomAction) hashString() { func (this *LexerIndexedCustomAction) equals(other) { if (this == other) { return true - } else if (! (other instanceof LexerIndexedCustomAction)) { + } else if (! _, ok := other.(LexerIndexedCustomAction); ok) { return false } else { return this.offset == other.offset && this.action == other.action diff --git a/runtime/Go/src/antlr4/atn/LexerActionExecutor.go b/runtime/Go/src/antlr4/atn/LexerActionExecutor.go index 52547bee1..c9f03af92 100644 --- a/runtime/Go/src/antlr4/atn/LexerActionExecutor.go +++ b/runtime/Go/src/antlr4/atn/LexerActionExecutor.go @@ -110,7 +110,7 @@ func (this *LexerActionExecutor) execute(lexer, input, startIndex) { try { for i := 0; i < len(this.lexerActions); i++ { var lexerAction = this.lexerActions[i] - if (lexerAction instanceof LexerIndexedCustomAction) { + if _, ok := lexerAction.(LexerIndexedCustomAction); ok { var offset = lexerAction.offset input.seek(startIndex + offset) lexerAction = lexerAction.action @@ -135,7 +135,7 @@ func (this *LexerActionExecutor) hashString() { func (this *LexerActionExecutor) equals(other) { if (this == other) { return true - } else if (!(other instanceof LexerActionExecutor)) { + } else if (!_, ok := other.(LexerActionExecutor); ok) { return false } else { return this.hashString == other.hashString && diff --git a/runtime/Go/src/antlr4/atn/ParserATNSimulator.go b/runtime/Go/src/antlr4/atn/ParserATNSimulator.go index 1008d5cc4..cd76ca110 100644 --- a/runtime/Go/src/antlr4/atn/ParserATNSimulator.go +++ b/runtime/Go/src/antlr4/atn/ParserATNSimulator.go @@ -263,7 +263,7 @@ func ParserATNSimulator(parser, atn, decisionToDFA, sharedContextCache) { this.parser = parser this.decisionToDFA = decisionToDFA // SLL, LL, or LL + exact ambig detection?// - this.predictionMode = PredictionMode.LL + this.predictionMode = PredictionModeLL // LAME globals to avoid parameters!!!!! I need these down deep in predTransition this._input = nil this._startIndex = 0 @@ -289,13 +289,12 @@ ParserATNSimulator.prototype.debug_list_atn_decisions = false ParserATNSimulator.prototype.dfa_debug = false ParserATNSimulator.prototype.retry_debug = false - func (this *ParserATNSimulator) reset() { } func (this *ParserATNSimulator) adaptivePredict(input, decision, outerContext) { if (this.debug || this.debug_list_atn_decisions) { - console.log("adaptivePredict decision " + decision + + fmt.Println("adaptivePredict decision " + decision + " exec LA(1)==" + this.getLookaheadName(input) + " line " + input.LT(1).line + ":" + input.LT(1).column) @@ -326,7 +325,7 @@ func (this *ParserATNSimulator) adaptivePredict(input, decision, outerContext) { outerContext = RuleContext.EMPTY } if (this.debug || this.debug_list_atn_decisions) { - console.log("predictATN decision " + dfa.decision + + fmt.Println("predictATN decision " + dfa.decision + " exec LA(1)==" + this.getLookaheadName(input) + ", outerContext=" + outerContext.toString(this.parser.ruleNames)) } @@ -360,7 +359,7 @@ func (this *ParserATNSimulator) adaptivePredict(input, decision, outerContext) { } var alt = this.execATN(dfa, s0, input, index, outerContext) if (this.debug) { - console.log("DFA after predictATN: " + dfa.toString(this.parser.literalNames)) + fmt.Println("DFA after predictATN: " + dfa.toString(this.parser.literalNames)) } return alt } finally { @@ -402,7 +401,7 @@ func (this *ParserATNSimulator) adaptivePredict(input, decision, outerContext) { // ParserATNSimulator.prototype.execATN = function(dfa, s0, input, startIndex, outerContext ) { if (this.debug || this.debug_list_atn_decisions) { - console.log("execATN decision " + dfa.decision + + fmt.Println("execATN decision " + dfa.decision + " exec LA(1)==" + this.getLookaheadName(input) + " line " + input.LT(1).line + ":" + input.LT(1).column) } @@ -410,7 +409,7 @@ ParserATNSimulator.prototype.execATN = function(dfa, s0, input, startIndex, oute var previousD = s0 if (this.debug) { - console.log("s0 = " + s0) + fmt.Println("s0 = " + s0) } var t = input.LA(1) while(true) { // while more work @@ -437,12 +436,12 @@ ParserATNSimulator.prototype.execATN = function(dfa, s0, input, startIndex, oute panic e } } - if(D.requiresFullContext && this.predictionMode != PredictionMode.SLL) { + if(D.requiresFullContext && this.predictionMode != PredictionModeSLL) { // IF PREDS, MIGHT RESOLVE TO SINGLE ALT => SLL (or syntax error) var conflictingAlts = nil if (D.predicates!=nil) { if (this.debug) { - console.log("DFA state has preds in DFA sim LL failover") + fmt.Println("DFA state has preds in DFA sim LL failover") } var conflictIndex = input.index if(conflictIndex != startIndex) { @@ -451,7 +450,7 @@ ParserATNSimulator.prototype.execATN = function(dfa, s0, input, startIndex, oute conflictingAlts = this.evalSemanticContext(D.predicates, outerContext, true) if (conflictingAlts.length==1) { if(this.debug) { - console.log("Full LL avoided") + fmt.Println("Full LL avoided") } return conflictingAlts.minValue() } @@ -462,7 +461,7 @@ ParserATNSimulator.prototype.execATN = function(dfa, s0, input, startIndex, oute } } if (this.dfa_debug) { - console.log("ctx sensitive state " + outerContext +" in " + D) + fmt.Println("ctx sensitive state " + outerContext +" in " + D) } var fullCtx = true var s0_closure = this.computeStartState(dfa.atnStartState, outerContext, fullCtx) @@ -538,13 +537,13 @@ func (this *ParserATNSimulator) computeTargetState(dfa, previousD, t) { var predictedAlt = this.getUniqueAlt(reach) if (this.debug) { - var altSubSets = PredictionMode.getConflictingAltSubsets(reach) - console.log("SLL altSubSets=" + Utils.arrayToString(altSubSets) + + var altSubSets = PredictionModegetConflictingAltSubsets(reach) + fmt.Println("SLL altSubSets=" + Utils.arrayToString(altSubSets) + ", previous=" + previousD.configs + ", configs=" + reach + ", predict=" + predictedAlt + ", allSubsetsConflict=" + - PredictionMode.allSubsetsConflict(altSubSets) + ", conflictingAlts=" + + PredictionModeallSubsetsConflict(altSubSets) + ", conflictingAlts=" + this.getConflictingAlts(reach)) } if (predictedAlt!=ATN.INVALID_ALT_NUMBER) { @@ -552,7 +551,7 @@ func (this *ParserATNSimulator) computeTargetState(dfa, previousD, t) { D.isAcceptState = true D.configs.uniqueAlt = predictedAlt D.prediction = predictedAlt - } else if (PredictionMode.hasSLLConflictTerminatingPrediction(this.predictionMode, reach)) { + } else if (PredictionModehasSLLConflictTerminatingPrediction(this.predictionMode, reach)) { // MORE THAN ONE VIABLE ALTERNATIVE D.configs.conflictingAlts = this.getConflictingAlts(reach) D.requiresFullContext = true @@ -597,7 +596,7 @@ ParserATNSimulator.prototype.execATNWithFullContext = function(dfa, D, // how fa startIndex, outerContext) { if (this.debug || this.debug_list_atn_decisions) { - console.log("execATNWithFullContext "+s0) + fmt.Println("execATNWithFullContext "+s0) } var fullCtx = true var foundExactAmbig = false @@ -627,28 +626,28 @@ ParserATNSimulator.prototype.execATNWithFullContext = function(dfa, D, // how fa panic e } } - var altSubSets = PredictionMode.getConflictingAltSubsets(reach) + var altSubSets = PredictionModegetConflictingAltSubsets(reach) if(this.debug) { - console.log("LL altSubSets=" + altSubSets + ", predict=" + - PredictionMode.getUniqueAlt(altSubSets) + ", resolvesToJustOneViableAlt=" + - PredictionMode.resolvesToJustOneViableAlt(altSubSets)) + fmt.Println("LL altSubSets=" + altSubSets + ", predict=" + + PredictionModegetUniqueAlt(altSubSets) + ", resolvesToJustOneViableAlt=" + + PredictionModeresolvesToJustOneViableAlt(altSubSets)) } reach.uniqueAlt = this.getUniqueAlt(reach) // unique prediction? if(reach.uniqueAlt!=ATN.INVALID_ALT_NUMBER) { predictedAlt = reach.uniqueAlt break - } else if (this.predictionMode != PredictionMode.LL_EXACT_AMBIG_DETECTION) { - predictedAlt = PredictionMode.resolvesToJustOneViableAlt(altSubSets) + } else if (this.predictionMode != PredictionModeLL_EXACT_AMBIG_DETECTION) { + predictedAlt = PredictionModeresolvesToJustOneViableAlt(altSubSets) if(predictedAlt != ATN.INVALID_ALT_NUMBER) { break } } else { // In exact ambiguity mode, we never try to terminate early. // Just keeps scarfing until we know what the conflict is - if (PredictionMode.allSubsetsConflict(altSubSets) && PredictionMode.allSubsetsEqual(altSubSets)) { + if (PredictionModeallSubsetsConflict(altSubSets) && PredictionModeallSubsetsEqual(altSubSets)) { foundExactAmbig = true - predictedAlt = PredictionMode.getSingleViableAlt(altSubSets) + predictedAlt = PredictionModegetSingleViableAlt(altSubSets) break } // else there are multiple non-conflicting subsets or @@ -702,7 +701,7 @@ ParserATNSimulator.prototype.execATNWithFullContext = function(dfa, D, // how fa func (this *ParserATNSimulator) computeReachSet(closure, t, fullCtx) { if (this.debug) { - console.log("in computeReachSet, starting closure: " + closure) + fmt.Println("in computeReachSet, starting closure: " + closure) } if( this.mergeCache==nil) { this.mergeCache = NewDoubleDict() @@ -725,7 +724,7 @@ func (this *ParserATNSimulator) computeReachSet(closure, t, fullCtx) { for (var i=0 i50) { panic "problem" } @@ -1222,7 +1221,7 @@ func (this *ParserATNSimulator) closureCheckingStopState(config, configs, closur } else { // we have no context info, just chase follow links (if greedy) if (this.debug) { - console.log("FALLING off rule " + this.getRuleName(config.state.ruleIndex)) + fmt.Println("FALLING off rule " + this.getRuleName(config.state.ruleIndex)) } this.closure_(config, configs, closureBusy, collectPredicates, fullCtx, depth, treatEofAsEpsilon) @@ -1247,7 +1246,7 @@ func (this *ParserATNSimulator) closureCheckingStopState(config, configs, closur } else { // else if we have no context info, just chase follow links (if greedy) if (this.debug) { - console.log("FALLING off rule " + this.getRuleName(config.state.ruleIndex)) + fmt.Println("FALLING off rule " + this.getRuleName(config.state.ruleIndex)) } } } @@ -1265,7 +1264,7 @@ func (this *ParserATNSimulator) closure_(config, configs, closureBusy, collectPr } for(var i = 0i= 0) { newDepth += 1 @@ -1346,17 +1345,17 @@ func (this *ParserATNSimulator) getEpsilonTarget(config, t, collectPredicates, i func (this *ParserATNSimulator) actionTransition(config, t) { if (this.debug) { - console.log("ACTION edge " + t.ruleIndex + ":" + t.actionIndex) + fmt.Println("ACTION edge " + t.ruleIndex + ":" + t.actionIndex) } return NewATNConfig({state:t.target}, config) } func (this *ParserATNSimulator) precedenceTransition(config, pt, collectPredicates, inContext, fullCtx) { if (this.debug) { - console.log("PRED (collectPredicates=" + collectPredicates + ") " + + fmt.Println("PRED (collectPredicates=" + collectPredicates + ") " + pt.precedence + ">=_p, ctx dependent=true") if (this.parser!=nil) { - console.log("context surrounding pred is " + Utils.arrayToString(this.parser.getRuleInvocationStack())) + fmt.Println("context surrounding pred is " + Utils.arrayToString(this.parser.getRuleInvocationStack())) } } var c = nil @@ -1381,17 +1380,17 @@ func (this *ParserATNSimulator) precedenceTransition(config, pt, collectPredica c = NewATNConfig({state:pt.target}, config) } if (this.debug) { - console.log("config from pred transition=" + c) + fmt.Println("config from pred transition=" + c) } return c } func (this *ParserATNSimulator) predTransition(config, pt, collectPredicates, inContext, fullCtx) { if (this.debug) { - console.log("PRED (collectPredicates=" + collectPredicates + ") " + pt.ruleIndex + + fmt.Println("PRED (collectPredicates=" + collectPredicates + ") " + pt.ruleIndex + ":" + pt.predIndex + ", ctx dependent=" + pt.isCtxDependent) if (this.parser!=nil) { - console.log("context surrounding pred is " + Utils.arrayToString(this.parser.getRuleInvocationStack())) + fmt.Println("context surrounding pred is " + Utils.arrayToString(this.parser.getRuleInvocationStack())) } } var c = nil @@ -1416,14 +1415,14 @@ func (this *ParserATNSimulator) predTransition(config, pt, collectPredicates, in c = NewATNConfig({state:pt.target}, config) } if (this.debug) { - console.log("config from pred transition=" + c) + fmt.Println("config from pred transition=" + c) } return c } func (this *ParserATNSimulator) ruleTransition(config, t) { if (this.debug) { - console.log("CALL rule " + this.getRuleName(t.target.ruleIndex) + ", ctx=" + config.context) + fmt.Println("CALL rule " + this.getRuleName(t.target.ruleIndex) + ", ctx=" + config.context) } var returnState = t.followState var newContext = SingletonPredictionContext.create(config.context, returnState.stateNumber) @@ -1431,8 +1430,8 @@ func (this *ParserATNSimulator) ruleTransition(config, t) { } func (this *ParserATNSimulator) getConflictingAlts(configs) { - var altsets = PredictionMode.getConflictingAltSubsets(configs) - return PredictionMode.getAlts(altsets) + var altsets = PredictionModegetConflictingAltSubsets(configs) + return PredictionModegetAlts(altsets) } // Sam pointed out a problem with the previous definition, v3, of @@ -1488,8 +1487,8 @@ func (this *ParserATNSimulator) getTokenName( t) { } if( this.parser!=nil && this.parser.literalNames!=nil) { if (t >= this.parser.literalNames.length) { - console.log("" + t + " ttype out of range: " + this.parser.literalNames) - console.log("" + this.parser.getInputStream().getTokens()) + fmt.Println("" + t + " ttype out of range: " + this.parser.literalNames) + fmt.Println("" + this.parser.getInputStream().getTokens()) } else { return this.parser.literalNames[t] + "<" + t + ">" } @@ -1506,17 +1505,17 @@ func (this *ParserATNSimulator) getLookaheadName(input) { // "dead" code for a bit. // func (this *ParserATNSimulator) dumpDeadEndConfigs(nvae) { - console.log("dead end configs: ") + fmt.Println("dead end configs: ") var decs = nvae.getDeadEndConfigs() for(var i=0 i0) { var t = c.state.transitions[0] - if (t instanceof AtomTransition) { + if _, ok := t.(AtomTransition); ok { trans = "Atom "+ this.getTokenName(t.label) - } else if (t instanceof SetTransition) { - var neg = (t instanceof NotSetTransition) + } else if _, ok := t.(SetTransition); ok { + var neg = _, ok := t.(NotSetTransition); ok trans = (neg ? "~" : "") + "Set " + t.set } } @@ -1563,7 +1562,7 @@ func (this *ParserATNSimulator) getUniqueAlt(configs) { // func (this *ParserATNSimulator) addDFAEdge(dfa, from_, t, to) { if( this.debug) { - console.log("EDGE " + from_ + " -> " + to + " upon " + this.getTokenName(t)) + fmt.Println("EDGE " + from_ + " -> " + to + " upon " + this.getTokenName(t)) } if (to==nil) { return nil @@ -1579,7 +1578,7 @@ func (this *ParserATNSimulator) addDFAEdge(dfa, from_, t, to) { if (this.debug) { var names = this.parser==nil ? nil : this.parser.literalNames - console.log("DFA=\n" + dfa.toString(names)) + fmt.Println("DFA=\n" + dfa.toString(names)) } return to } @@ -1614,7 +1613,7 @@ func (this *ParserATNSimulator) addDFAState(dfa, D) { } dfa.states[hash] = D if (this.debug) { - console.log("adding NewDFA state: " + D) + fmt.Println("adding NewDFA state: " + D) } return D } @@ -1622,7 +1621,7 @@ func (this *ParserATNSimulator) addDFAState(dfa, D) { func (this *ParserATNSimulator) reportAttemptingFullContext(dfa, conflictingAlts, configs, startIndex, stopIndex) { if (this.debug || this.retry_debug) { var interval = NewInterval(startIndex, stopIndex + 1) - console.log("reportAttemptingFullContext decision=" + dfa.decision + ":" + configs + + fmt.Println("reportAttemptingFullContext decision=" + dfa.decision + ":" + configs + ", input=" + this.parser.getTokenStream().getText(interval)) } if (this.parser!=nil) { @@ -1633,7 +1632,7 @@ func (this *ParserATNSimulator) reportAttemptingFullContext(dfa, conflictingAlts func (this *ParserATNSimulator) reportContextSensitivity(dfa, prediction, configs, startIndex, stopIndex) { if (this.debug || this.retry_debug) { var interval = NewInterval(startIndex, stopIndex + 1) - console.log("reportContextSensitivity decision=" + dfa.decision + ":" + configs + + fmt.Println("reportContextSensitivity decision=" + dfa.decision + ":" + configs + ", input=" + this.parser.getTokenStream().getText(interval)) } if (this.parser!=nil) { @@ -1646,7 +1645,7 @@ func (this *ParserATNSimulator) reportAmbiguity(dfa, D, startIndex, stopIndex, exact, ambigAlts, configs ) { if (this.debug || this.retry_debug) { var interval = NewInterval(startIndex, stopIndex + 1) - console.log("reportAmbiguity " + ambigAlts + ":" + configs + + fmt.Println("reportAmbiguity " + ambigAlts + ":" + configs + ", input=" + this.parser.getTokenStream().getText(interval)) } if (this.parser!=nil) { diff --git a/runtime/Go/src/antlr4/atn/PredictionMode.go b/runtime/Go/src/antlr4/atn/PredictionMode.go index 99354784c..669a39b00 100644 --- a/runtime/Go/src/antlr4/atn/PredictionMode.go +++ b/runtime/Go/src/antlr4/atn/PredictionMode.go @@ -12,69 +12,75 @@ package atn //var RuleStopState = require('./ATNState').RuleStopState type PredictionMode struct { - return this + } -// -// The SLL(*) prediction mode. This prediction mode ignores the current -// parser context when making predictions. This is the fastest prediction -// mode, and provides correct results for many grammars. This prediction -// mode is more powerful than the prediction mode provided by ANTLR 3, but -// may result in syntax errors for grammar and input combinations which are -// not SLL. -// -//

-// When using this prediction mode, the parser will either return a correct -// parse tree (i.e. the same parse tree that would be returned with the -// {@link //LL} prediction mode), or it will report a syntax error. If a -// syntax error is encountered when using the {@link //SLL} prediction mode, -// it may be due to either an actual syntax error in the input or indicate -// that the particular combination of grammar and input requires the more -// powerful {@link //LL} prediction abilities to complete successfully.

-// -//

-// This prediction mode does not provide any guarantees for prediction -// behavior for syntactically-incorrect inputs.

-// -PredictionMode.SLL = 0 -// -// The LL(*) prediction mode. This prediction mode allows the current parser -// context to be used for resolving SLL conflicts that occur during -// prediction. This is the fastest prediction mode that guarantees correct -// parse results for all combinations of grammars with syntactically correct -// inputs. -// -//

-// When using this prediction mode, the parser will make correct decisions -// for all syntactically-correct grammar and input combinations. However, in -// cases where the grammar is truly ambiguous this prediction mode might not -// report a precise answer for exactly which alternatives are -// ambiguous.

-// -//

-// This prediction mode does not provide any guarantees for prediction -// behavior for syntactically-incorrect inputs.

-// -PredictionMode.LL = 1 -// -// The LL(*) prediction mode with exact ambiguity detection. In addition to -// the correctness guarantees provided by the {@link //LL} prediction mode, -// this prediction mode instructs the prediction algorithm to determine the -// complete and exact set of ambiguous alternatives for every ambiguous -// decision encountered while parsing. -// -//

-// This prediction mode may be used for diagnosing ambiguities during -// grammar development. Due to the performance overhead of calculating sets -// of ambiguous alternatives, this prediction mode should be avoided when -// the exact results are not necessary.

-// -//

-// This prediction mode does not provide any guarantees for prediction -// behavior for syntactically-incorrect inputs.

-// -PredictionMode.LL_EXACT_AMBIG_DETECTION = 2 +func NewPredictionMode() *PredictionMode { + return new(PredictionMode) +} +const ( + // + // The SLL(*) prediction mode. This prediction mode ignores the current + // parser context when making predictions. This is the fastest prediction + // mode, and provides correct results for many grammars. This prediction + // mode is more powerful than the prediction mode provided by ANTLR 3, but + // may result in syntax errors for grammar and input combinations which are + // not SLL. + // + //

+ // When using this prediction mode, the parser will either return a correct + // parse tree (i.e. the same parse tree that would be returned with the + // {@link //LL} prediction mode), or it will report a syntax error. If a + // syntax error is encountered when using the {@link //SLL} prediction mode, + // it may be due to either an actual syntax error in the input or indicate + // that the particular combination of grammar and input requires the more + // powerful {@link //LL} prediction abilities to complete successfully.

+ // + //

+ // This prediction mode does not provide any guarantees for prediction + // behavior for syntactically-incorrect inputs.

+ // + PredictionModeSLL = 0 + // + // The LL(*) prediction mode. This prediction mode allows the current parser + // context to be used for resolving SLL conflicts that occur during + // prediction. This is the fastest prediction mode that guarantees correct + // parse results for all combinations of grammars with syntactically correct + // inputs. + // + //

+ // When using this prediction mode, the parser will make correct decisions + // for all syntactically-correct grammar and input combinations. However, in + // cases where the grammar is truly ambiguous this prediction mode might not + // report a precise answer for exactly which alternatives are + // ambiguous.

+ // + //

+ // This prediction mode does not provide any guarantees for prediction + // behavior for syntactically-incorrect inputs.

+ // + PredictionModeLL = 1 + // + // The LL(*) prediction mode with exact ambiguity detection. In addition to + // the correctness guarantees provided by the {@link //LL} prediction mode, + // this prediction mode instructs the prediction algorithm to determine the + // complete and exact set of ambiguous alternatives for every ambiguous + // decision encountered while parsing. + // + //

+ // This prediction mode may be used for diagnosing ambiguities during + // grammar development. Due to the performance overhead of calculating sets + // of ambiguous alternatives, this prediction mode should be avoided when + // the exact results are not necessary.

+ // + //

+ // This prediction mode does not provide any guarantees for prediction + // behavior for syntactically-incorrect inputs.

+ // + PredictionModeLL_EXACT_AMBIG_DETECTION = 2 + +) // // Computes the SLL prediction termination condition. @@ -168,17 +174,17 @@ PredictionMode.LL_EXACT_AMBIG_DETECTION = 2 // the configurations to strip out all of the predicates so that a standard // {@link ATNConfigSet} will merge everything ignoring predicates.

// -PredictionMode.hasSLLConflictTerminatingPrediction = function( mode, configs) { +PredictionModehasSLLConflictTerminatingPrediction = function( mode, configs) { // Configs in rule stop states indicate reaching the end of the decision // rule (local context) or end of start rule (full context). If all // configs meet this condition, then none of the configurations is able // to match additional input so we terminate prediction. // - if (PredictionMode.allConfigsInRuleStopStates(configs)) { + if (PredictionModeallConfigsInRuleStopStates(configs)) { return true } // pure SLL mode parsing - if (mode == PredictionMode.SLL) { + if (mode == PredictionModeSLL) { // Don't bother with combining configs from different semantic // contexts if we can fail over to full LL costs more time // since we'll often fail over anyway. @@ -195,8 +201,8 @@ PredictionMode.hasSLLConflictTerminatingPrediction = function( mode, configs) { // now we have combined contexts for configs with dissimilar preds } // pure SLL or combined SLL+LL mode parsing - var altsets = PredictionMode.getConflictingAltSubsets(configs) - return PredictionMode.hasConflictingAltSet(altsets) && !PredictionMode.hasStateAssociatedWithOneAlt(configs) + var altsets = PredictionModegetConflictingAltSubsets(configs) + return PredictionModehasConflictingAltSet(altsets) && !PredictionModehasStateAssociatedWithOneAlt(configs) } // Checks if any configuration in {@code configs} is in a @@ -207,7 +213,7 @@ PredictionMode.hasSLLConflictTerminatingPrediction = function( mode, configs) { // @param configs the configuration set to test // @return {@code true} if any configuration in {@code configs} is in a // {@link RuleStopState}, otherwise {@code false} -PredictionMode.hasConfigInRuleStopState = function(configs) { +PredictionModehasConfigInRuleStopState = function(configs) { for(var i=0i // -PredictionMode.resolvesToJustOneViableAlt = function(altsets) { - return PredictionMode.getSingleViableAlt(altsets) +PredictionModeresolvesToJustOneViableAlt = function(altsets) { + return PredictionModegetSingleViableAlt(altsets) } // @@ -388,8 +394,8 @@ PredictionMode.resolvesToJustOneViableAlt = function(altsets) { // @return {@code true} if every {@link BitSet} in {@code altsets} has // {@link BitSet//cardinality cardinality} > 1, otherwise {@code false} // -PredictionMode.allSubsetsConflict = function(altsets) { - return ! PredictionMode.hasNonConflictingAltSet(altsets) +PredictionModeallSubsetsConflict = function(altsets) { + return ! PredictionModehasNonConflictingAltSet(altsets) } // // Determines if any single alternative subset in {@code altsets} contains @@ -399,7 +405,7 @@ PredictionMode.allSubsetsConflict = function(altsets) { // @return {@code true} if {@code altsets} contains a {@link BitSet} with // {@link BitSet//cardinality cardinality} 1, otherwise {@code false} // -PredictionMode.hasNonConflictingAltSet = function(altsets) { +PredictionModehasNonConflictingAltSet = function(altsets) { for(var i=0i1) { @@ -434,7 +440,7 @@ PredictionMode.hasConflictingAltSet = function(altsets) { // @return {@code true} if every member of {@code altsets} is equal to the // others, otherwise {@code false} // -PredictionMode.allSubsetsEqual = function(altsets) { +PredictionModeallSubsetsEqual = function(altsets) { var first = nil for(var i=0i // -PredictionMode.getConflictingAltSubsets = function(configs) { +PredictionModegetConflictingAltSubsets = function(configs) { var configToAlts = {} for(var i=0i // -PredictionMode.getStateToAltMap = function(configs) { +PredictionModegetStateToAltMap = function(configs) { var m = NewAltDict() configs.items.map(function(c) { var alts = m.get(c.state) @@ -528,8 +534,8 @@ PredictionMode.getStateToAltMap = function(configs) { return m } -PredictionMode.hasStateAssociatedWithOneAlt = function(configs) { - var values = PredictionMode.getStateToAltMap(configs).values() +PredictionModehasStateAssociatedWithOneAlt = function(configs) { + var values = PredictionModegetStateToAltMap(configs).values() for(var i=0i