Banish instanceof to hell

This commit is contained in:
Peter Boyer 2015-12-15 21:01:08 -05:00
parent dc5cf284ed
commit 15aa407757
24 changed files with 299 additions and 264 deletions

View File

@ -71,7 +71,7 @@ func (bt *BufferedTokenStream) mark() int {
return 0 return 0
} }
func (bt *BufferedTokenStream) release(marker) { func (bt *BufferedTokenStream) release(marker int) {
// no resources to release // no resources to release
} }
@ -118,7 +118,7 @@ func (bt *BufferedTokenStream) consume() {
// {@code false}. // {@code false}.
// @see //get(int i) // @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? var n = i - len(bt.tokens) + 1 // how many more elements we need?
if (n > 0) { if (n > 0) {
var fetched = bt.fetch(n) var fetched = bt.fetch(n)
@ -132,7 +132,7 @@ func (bt *BufferedTokenStream) sync(i) {
// @return The actual number of elements added to the buffer. // @return The actual number of elements added to the buffer.
// / // /
func (bt *BufferedTokenStream) fetch(n int) int { func (bt *BufferedTokenStream) fetch(n int) int {
if (bt.fetchedEOF) { if bt.fetchedEOF {
return 0 return 0
} }
@ -140,7 +140,7 @@ func (bt *BufferedTokenStream) fetch(n int) int {
var t = bt.tokenSource.nextToken() var t = bt.tokenSource.nextToken()
t.tokenIndex = len(bt.tokens) t.tokenIndex = len(bt.tokens)
bt.tokens.push(t) bt.tokens.push(t)
if (t.type == TokenEOF) { if (t.tokenType == TokenEOF) {
bt.fetchedEOF = true bt.fetchedEOF = true
return i + 1 return i + 1
} }
@ -149,10 +149,8 @@ func (bt *BufferedTokenStream) fetch(n int) int {
} }
// Get all tokens from start..stop inclusively/// // Get all tokens from start..stop inclusively///
func (bt *BufferedTokenStream) getTokens(start, stop, types) { func (bt *BufferedTokenStream) getTokens(start int, stop int, types []int) []Token {
if (types == undefined) {
types = nil
}
if (start < 0 || stop < 0) { if (start < 0 || stop < 0) {
return nil return nil
} }
@ -163,28 +161,28 @@ func (bt *BufferedTokenStream) getTokens(start, stop, types) {
} }
for i := start; i < stop; i++ { for i := start; i < stop; i++ {
var t = bt.tokens[i] var t = bt.tokens[i]
if (t.type == TokenEOF) { if (t.tokenType == TokenEOF) {
break break
} }
if (types == nil || types.contains(t.type)) { if (types == nil || types.contains(t.tokenType)) {
subset.push(t) subset.push(t)
} }
} }
return subset return subset
} }
func (bt *BufferedTokenStream) LA(i) { func (bt *BufferedTokenStream) LA(i int) int {
return bt.LT(i).type return bt.LT(i).tokenType
} }
func (bt *BufferedTokenStream) LB(k) { func (bt *BufferedTokenStream) LB(k int) Token {
if (bt.index - k < 0) { if (bt.index - k < 0) {
return nil return nil
} }
return bt.tokens[bt.index - k] return bt.tokens[bt.index - k]
} }
func (bt *BufferedTokenStream) LT(k) { func (bt *BufferedTokenStream) LT(k int) Token {
bt.lazyInit() bt.lazyInit()
if (k == 0) { if (k == 0) {
return nil return nil
@ -214,7 +212,7 @@ func (bt *BufferedTokenStream) LT(k) {
// @param i The target token index. // @param i The target token index.
// @return The adjusted target token index. // @return The adjusted target token index.
func (bt *BufferedTokenStream) adjustSeekIndex(i) { func (bt *BufferedTokenStream) adjustSeekIndex(i int) int {
return i return i
} }
@ -230,7 +228,7 @@ func (bt *BufferedTokenStream) setup() {
} }
// Reset bt token stream by setting its token source./// // Reset bt token stream by setting its token source.///
func (bt *BufferedTokenStream) setTokenSource(tokenSource) { func (bt *BufferedTokenStream) setTokenSource(tokenSource *TokenSource) {
bt.tokenSource = tokenSource bt.tokenSource = tokenSource
bt.tokens = [] bt.tokens = []
bt.index = -1 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 // the current token up until we see a token on DEFAULT_TOKEN_CHANNEL or
// EOF. If channel is -1, find any non default channel token. // EOF. If channel is -1, find any non default channel token.
func (bt *BufferedTokenStream) getHiddenTokensToRight(tokenIndex, channel int) { func (bt *BufferedTokenStream) getHiddenTokensToRight(tokenIndex, channel int) {
if (channel == undefined) {
channel = -1
}
bt.lazyInit() bt.lazyInit()
if (bt.tokenIndex < 0 || tokenIndex >= len(bt.tokens)) { if (bt.tokenIndex < 0 || tokenIndex >= len(bt.tokens)) {
panic( "" + tokenIndex + " not in 0.." + len(bt.tokens) - 1 panic( "" + tokenIndex + " not in 0.." + len(bt.tokens) - 1
} }
var nextOnChannel = bt.nextTokenOnChannel(tokenIndex + 1, var nextOnChannel = bt.nextTokenOnChannel(tokenIndex + 1, LexerDefaultTokenChannel)
LexerDefaultTokenChannel)
var from_ = tokenIndex + 1 var from_ = tokenIndex + 1
// if none onchannel to right, nextOnChannel=-1 so set to = last token // if none onchannel to right, nextOnChannel=-1 so set to = last token
var to = nextOnChannel == -1 ? len(bt.tokens) - 1 : nextOnChannel 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)) { if (tokenIndex < 0 || tokenIndex >= len(bt.tokens)) {
panic( "" + tokenIndex + " not in 0.." + len(bt.tokens) - 1 panic( "" + tokenIndex + " not in 0.." + len(bt.tokens) - 1
} }
var prevOnChannel = bt.previousTokenOnChannel(tokenIndex - 1, var prevOnChannel = bt.previousTokenOnChannel(tokenIndex - 1, LexerDefaultTokenChannel)
LexerDefaultTokenChannel)
if (prevOnChannel == tokenIndex - 1) { if (prevOnChannel == tokenIndex - 1) {
return nil return nil
} }
@ -315,7 +308,7 @@ func (bt *BufferedTokenStream) filterForChannel(left, right, channel int) {
var t = bt.tokens[i] var t = bt.tokens[i]
if (channel == -1) { if (channel == -1) {
if (t.channel != LexerDefaultTokenChannel) { if (t.channel != LexerDefaultTokenChannel) {
hidden.push(t) append(hidden, t)
} }
} else if (t.channel == channel) { } else if (t.channel == channel) {
hidden.push(t) hidden.push(t)
@ -339,11 +332,11 @@ func (bt *BufferedTokenStream) getText(interval *Interval) string {
interval = NewInterval(0, len(bt.tokens) - 1) interval = NewInterval(0, len(bt.tokens) - 1)
} }
var start = interval.start var start = interval.start
if (start instanceof Token) { if _, ok := start.(Token); ok {
start = start.tokenIndex start = start.tokenIndex
} }
var stop = interval.stop var stop = interval.stop
if (stop instanceof Token) { if _, ok := stop.(Token); ok {
stop = stop.tokenIndex stop = stop.tokenIndex
} }
if (start == nil || stop == nil || start < 0 || stop < 0) { if (start == nil || stop == nil || start < 0 || stop < 0) {
@ -355,7 +348,7 @@ func (bt *BufferedTokenStream) getText(interval *Interval) string {
var s = "" var s = ""
for i := start; i < stop + 1; i++ { for i := start; i < stop + 1; i++ {
var t = bt.tokens[i] var t = bt.tokens[i]
if (t.type == TokenEOF) { if (t.tokenType == TokenEOF) {
break break
} }
s = s + t.text s = s + t.text

View File

@ -190,7 +190,7 @@ func (la *LL1Analyzer) _LOOK(s, stopState , ctx, look, lookBusy, calledRuleStack
} else { } else {
var set = t.label var set = t.label
if (set != nil) { if (set != nil) {
if (t instanceof NotSetTransition) { if _, ok := t.(NotSetTransition); ok {
set = set.complement(TokenMinUserTokenType, la.atn.maxTokenType) set = set.complement(TokenMinUserTokenType, la.atn.maxTokenType)
} }
look.addSet(set) look.addSet(set)

View File

@ -289,7 +289,7 @@ func (p.*Parser) compileParseTreePattern(pattern, patternRuleIndex, lexer) {
if (lexer == nil) { if (lexer == nil) {
if (p.getTokenStream() != nil) { if (p.getTokenStream() != nil) {
var tokenSource = p.getTokenStream().tokenSource var tokenSource = p.getTokenStream().tokenSource
if (tokenSource instanceof Lexer) { if _, ok := tokenSource.(Lexer); ok {
lexer = tokenSource lexer = tokenSource
} }
} }

View File

@ -118,7 +118,7 @@ func (prc *ParserRuleContext) getChild(i, type) {
} else { } else {
for(var j=0 j<len(prc.children) j++) { for(var j=0 j<len(prc.children) j++) {
var child = prc.children[j] var child = prc.children[j]
if(child instanceof type) { if_, ok := child.(type); ok {
if(i==0) { if(i==0) {
return child return child
} else { } else {
@ -131,10 +131,10 @@ func (prc *ParserRuleContext) getChild(i, type) {
} }
func (prc *ParserRuleContext) getToken(ttype, i) { func (prc *ParserRuleContext) getToken(ttype, i int) {
for(var j=0 j<len(prc.children) j++) { for j :=0; j<len(prc.children); j++ {
var child = prc.children[j] var child = prc.children[j]
if (child instanceof TerminalNode) { if _, ok := child.(TerminalNode); ok {
if (child.symbol.type == ttype) { if (child.symbol.type == ttype) {
if(i==0) { if(i==0) {
return child return child
@ -147,14 +147,14 @@ func (prc *ParserRuleContext) getToken(ttype, i) {
return nil return nil
} }
func (prc *ParserRuleContext) getTokens(ttype ) { func (prc *ParserRuleContext) getTokens(ttype int) {
if (prc.children== nil) { if (prc.children== nil) {
return [] return []
} else { } else {
var tokens = [] var tokens = []
for(var j=0 j<len(prc.children) j++) { for j:=0; j<len(prc.children); j++ {
var child = prc.children[j] var child = prc.children[j]
if (child instanceof TerminalNode) { if _, ok := child.(TerminalNode); ok {
if (child.symbol.type == ttype) { if (child.symbol.type == ttype) {
tokens.push(child) tokens.push(child)
} }
@ -175,7 +175,7 @@ func (prc *ParserRuleContext) getTypedRuleContexts(ctxType) {
var contexts = [] var contexts = []
for(var j=0 j<len(prc.children) j++) { for(var j=0 j<len(prc.children) j++) {
var child = prc.children[j] var child = prc.children[j]
if (child instanceof ctxType) { if _, ok := child.(ctxType); ok {
contexts.push(child) contexts.push(child)
} }
} }

View File

@ -2,14 +2,26 @@ package antlr4
//var RuleContext = require('./RuleContext').RuleContext //var RuleContext = require('./RuleContext').RuleContext
func PredictionContext(cachedHashString) { type PredictionContext struct {
this.cachedHashString = cachedHashString cachedHashString string
}
func NewPredictionContext(cachedHashString string) *PredictionContext {
pc := new(PredictionContext)
pc.cachedHashString = cachedHashString
return pc
} }
// Represents {@code $} in local context prediction, which means wildcard. // Represents {@code $} in local context prediction, which means wildcard.
// {@code//+x =//}. // {@code//+x =//}.
// / // /
PredictionContext.EMPTY = nil const (
PredictionContext.EMPTY = nil
)
// Represents {@code $} in an array in full context mode, when {@code $} // Represents {@code $} in an array in full context mode, when {@code $}
// doesn't mean wildcard: {@code $ + x = [$,x]}. Here, // doesn't mean wildcard: {@code $ + x = [$,x]}. Here,
@ -138,7 +150,7 @@ func (this *SingletonPredictionContext) getReturnState(index) {
func (this *SingletonPredictionContext) equals(other) { func (this *SingletonPredictionContext) equals(other) {
if (this == other) { if (this == other) {
return true return true
} else if (!(other instanceof SingletonPredictionContext)) { } else if (!_, ok := other.(SingletonPredictionContext); ok) {
return false return false
} else if (this.hashString() != other.hashString()) { } else if (this.hashString() != other.hashString()) {
return false // can't be same if hash is different return false // can't be same if hash is different
@ -237,7 +249,7 @@ func (this *ArrayPredictionContext) getReturnState(index) {
func (this *ArrayPredictionContext) equals(other) { func (this *ArrayPredictionContext) equals(other) {
if (this == other) { if (this == other) {
return true return true
} else if (!(other instanceof ArrayPredictionContext)) { } else if (!_, ok := other.(ArrayPredictionContext); ok) {
return false return false
} else if (this.hashString != other.hashString()) { } else if (this.hashString != other.hashString()) {
return false // can't be same if hash is different return false // can't be same if hash is different
@ -312,18 +324,18 @@ func merge(a, b, rootIsWildcard, mergeCache) {
// At least one of a or b is array // At least one of a or b is array
// If one is $ and rootIsWildcard, return $ as// wildcard // If one is $ and rootIsWildcard, return $ as// wildcard
if (rootIsWildcard) { if (rootIsWildcard) {
if (a instanceof EmptyPredictionContext) { if _, ok := a.(EmptyPredictionContext); ok {
return a return a
} }
if (b instanceof EmptyPredictionContext) { if _, ok := b.(EmptyPredictionContext); ok {
return b return b
} }
} }
// convert singleton so both are arrays to normalize // convert singleton so both are arrays to normalize
if (a instanceof SingletonPredictionContext) { if _, ok := a.(SingletonPredictionContext); ok {
a = NewArrayPredictionContext([a.getParent()], [a.returnState]) a = NewArrayPredictionContext([a.getParent()], [a.returnState])
} }
if (b instanceof SingletonPredictionContext) { if _, ok := b.(SingletonPredictionContext); ok {
b = NewArrayPredictionContext([b.getParent()], [b.returnState]) b = NewArrayPredictionContext([b.getParent()], [b.returnState])
} }
return mergeArrays(a, b, rootIsWildcard, mergeCache) return mergeArrays(a, b, rootIsWildcard, mergeCache)

View File

@ -1,23 +1,32 @@
package antlr4 package antlr4
import (
"fmt"
)
//var Token = require('./Token').Token //var Token = require('./Token').Token
//var ConsoleErrorListener = require('./error/ErrorListener').ConsoleErrorListener //var ConsoleErrorListener = require('./error/ErrorListener').ConsoleErrorListener
//var ProxyErrorListener = require('./error/ErrorListener').ProxyErrorListener //var ProxyErrorListener = require('./error/ErrorListener').ProxyErrorListener
type Recognizer struct {
_listeners []Listener
_interp
state int
}
type Recognizer struct { type Recognizer struct {
this._listeners = [ ConsoleErrorListener.INSTANCE ] this._listeners = [ ConsoleErrorListener.INSTANCE ]
this._interp = nil this._interp = nil
this._stateNumber = -1 this.state = -1
return this return this
} }
Recognizer.tokenTypeMapCache = {} Recognizer.tokenTypeMapCache = {}
Recognizer.ruleIndexMapCache = {} Recognizer.ruleIndexMapCache = {}
func (this *Recognizer) checkVersion(toolVersion) { func (this *Recognizer) checkVersion(toolVersion string) {
var runtimeVersion = "4.5.1" var runtimeVersion = "4.5.1"
if (runtimeVersion!=toolVersion) { if (runtimeVersion!=toolVersion) {
console.log("ANTLR runtime and generated code versions disagree: "+runtimeVersion+"!="+toolVersion) fmt.Println("ANTLR runtime and generated code versions disagree: "+runtimeVersion+"!="+toolVersion)
} }
} }

View File

@ -1,5 +1,9 @@
package antlr4 package antlr4
import (
"antlr4/tree"
)
// A rule context is a record of a single rule invocation. It knows // A rule context is a record of a single rule invocation. It knows
// which context invoked it, if any. If there is no parent context, then // which context invoked it, if any. If there is no parent context, then
// naturally the invoking state is not valid. The parent link // naturally the invoking state is not valid. The parent link
@ -24,15 +28,23 @@ package antlr4
//var RuleNode = require('./tree/Tree').RuleNode //var RuleNode = require('./tree/Tree').RuleNode
var INVALID_INTERVAL = require('./tree/Tree').INVALID_INTERVAL var INVALID_INTERVAL = require('./tree/Tree').INVALID_INTERVAL
func RuleContext(parent, invokingState) { type RuleContext struct {
RuleNode
parentCtx *RuleContext
invokingState int
}
func NewRuleContext(parent *RuleContext, invokingState int) *RuleContext {
RuleNode.call(this) RuleNode.call(this)
rn := new(RuleContext)
// What context invoked this rule? // What context invoked this rule?
this.parentCtx = parent || nil rn.parentCtx = parent || nil
// What state invoked the rule associated with this context? // What state invoked the rule associated with this context?
// The "return address" is the followState of invokingState // The "return address" is the followState of invokingState
// If parent is nil, this should be -1. // If parent is nil, this should be -1.
this.invokingState = invokingState || -1 rn.invokingState = invokingState || -1
return this return rn
} }
//RuleContext.prototype = Object.create(RuleNode.prototype) //RuleContext.prototype = Object.create(RuleNode.prototype)
@ -60,11 +72,11 @@ func (this *RuleContext) getSourceInterval() {
return INVALID_INTERVAL return INVALID_INTERVAL
} }
func (this *RuleContext) getRuleContext() { func (this *RuleContext) getRuleContext() *RuleContext {
return this return this
} }
func (this *RuleContext) getPayload() { func (this *RuleContext) getPayload() *RuleContext {
return this return this
} }
@ -93,7 +105,7 @@ func (this *RuleContext) getChildCount() {
return 0 return 0
} }
func (this *RuleContext) accept(visitor) { func (this *RuleContext) accept(visitor *tree.TreeNodeVisitor) {
return visitor.visitChildren(this) return visitor.visitChildren(this)
} }
@ -122,8 +134,7 @@ func (this *RuleContext) toString(ruleNames, stop) {
} }
} else { } else {
var ri = p.ruleIndex var ri = p.ruleIndex
var ruleName = (ri >= 0 && ri < ruleNames.length) ? ruleNames[ri] var ruleName = (ri >= 0 && ri < ruleNames.length) ? ruleNames[ri] : "" + ri
: "" + ri
s += ruleName s += ruleName
} }
if (p.parentCtx != nil && (ruleNames != nil || !p.parentCtx.isEmpty())) { if (p.parentCtx != nil && (ruleNames != nil || !p.parentCtx.isEmpty())) {

View File

@ -119,7 +119,7 @@ func (this *BitSet) hashString() {
} }
func (this *BitSet) equals(other) { func (this *BitSet) equals(other) {
if(!(other instanceof BitSet)) { if(!_, ok := other.(BitSet); ok) {
return false return false
} }
return this.hashString()==other.hashString() return this.hashString()==other.hashString()

View File

@ -16,7 +16,7 @@ type ATN struct {
modeToStartState modeToStartState
} }
func NewATN(grammarType , maxTokenType) ATN { func NewATN(grammarType , maxTokenType) *ATN {
atn := new(ATN) atn := new(ATN)

View File

@ -74,7 +74,7 @@ func (this *ATNConfig) checkContext(params, config) {
func (this *ATNConfig) equals(other) { func (this *ATNConfig) equals(other) {
if (this == other) { if (this == other) {
return true return true
} else if (! (other instanceof ATNConfig)) { } else if (! _, ok := other.(ATNConfig); ok) {
return false return false
} else { } else {
return this.state.stateNumber==other.state.stateNumber && return this.state.stateNumber==other.state.stateNumber &&
@ -129,7 +129,7 @@ func (this *LexerATNConfig) hashString() {
func (this *LexerATNConfig) equals(other) { func (this *LexerATNConfig) equals(other) {
if (this == other) { if (this == other) {
return true return true
} else if (!(other instanceof LexerATNConfig)) { } else if (!_, ok := other.(LexerATNConfig); ok) {
return false return false
} else if (this.passedThroughNonGreedyDecision != other.passedThroughNonGreedyDecision) { } else if (this.passedThroughNonGreedyDecision != other.passedThroughNonGreedyDecision) {
return false return false
@ -144,7 +144,7 @@ func (this *LexerATNConfig) equals(other) {
func (this *LexerATNConfig) checkNonGreedyDecision(source, target) { func (this *LexerATNConfig) checkNonGreedyDecision(source, target) {
return source.passedThroughNonGreedyDecision || return source.passedThroughNonGreedyDecision ||
(target instanceof DecisionState) && target.nonGreedy _, ok := target.(DecisionState); ok && target.nonGreedy
} }

View File

@ -162,7 +162,7 @@ func (this *ATNConfigSet) addAll(coll) {
func (this *ATNConfigSet) equals(other) { func (this *ATNConfigSet) equals(other) {
if (this == other) { if (this == other) {
return true return true
} else if (!(other instanceof ATNConfigSet)) { } else if (!_, ok := other.(ATNConfigSet); ok) {
return false return false
} }
return this.configs != nil && this.configs.equals(other.configs) && return this.configs != nil && this.configs.equals(other.configs) &&

View File

@ -172,7 +172,7 @@ func (this *ATNDeserializer) readStates(atn) {
if (stype == ATNStateLOOP_END) { // special case if (stype == ATNStateLOOP_END) { // special case
var loopBackStateNumber = this.readInt() var loopBackStateNumber = this.readInt()
loopBackStateNumbers.push([s, loopBackStateNumber]) loopBackStateNumbers.push([s, loopBackStateNumber])
} else if(s instanceof BlockStartState) { } else if_, ok := s.(BlockStartState); ok {
var endStateNumber = this.readInt() var endStateNumber = this.readInt()
endStateNumbers.push([s, endStateNumber]) endStateNumbers.push([s, endStateNumber])
} }
@ -225,7 +225,7 @@ func (this *ATNDeserializer) readRules(atn) {
atn.ruleToStopState = initArray(nrules, 0) atn.ruleToStopState = initArray(nrules, 0)
for (i=0 i<atn.states.length i++) { for (i=0 i<atn.states.length i++) {
var state = atn.states[i] var state = atn.states[i]
if (!(state instanceof RuleStopState)) { if (!_, ok := state.(RuleStopState); ok) {
continue continue
} }
atn.ruleToStopState[state.ruleIndex] = state atn.ruleToStopState[state.ruleIndex] = state
@ -280,7 +280,7 @@ func (this *ATNDeserializer) readEdges(atn, sets) {
state = atn.states[i] state = atn.states[i]
for (j=0 j<state.transitions.length j++) { for (j=0 j<state.transitions.length j++) {
var t = state.transitions[j] var t = state.transitions[j]
if (!(t instanceof RuleTransition)) { if (!_, ok := t.(RuleTransition); ok) {
continue continue
} }
var outermostPrecedenceReturn = -1 var outermostPrecedenceReturn = -1
@ -297,7 +297,7 @@ func (this *ATNDeserializer) readEdges(atn, sets) {
for (i=0 i<atn.states.length i++) { for (i=0 i<atn.states.length i++) {
state = atn.states[i] state = atn.states[i]
if (state instanceof BlockStartState) { if _, ok := state.(BlockStartState); ok {
// we need to know the end state to set its start state // we need to know the end state to set its start state
if (state.endState == nil) { if (state.endState == nil) {
panic ("IllegalState") panic ("IllegalState")
@ -309,17 +309,17 @@ func (this *ATNDeserializer) readEdges(atn, sets) {
} }
state.endState.startState = state state.endState.startState = state
} }
if (state instanceof PlusLoopbackState) { if _, ok := state.(PlusLoopbackState); ok {
for (j=0 j<state.transitions.length j++) { for (j=0 j<state.transitions.length j++) {
target = state.transitions[j].target target = state.transitions[j].target
if (target instanceof PlusBlockStartState) { if _, ok := target.(PlusBlockStartState); ok {
target.loopBackState = state target.loopBackState = state
} }
} }
} else if (state instanceof StarLoopbackState) { } else if _, ok := state.(StarLoopbackState); ok {
for (j=0 j<state.transitions.length j++) { for (j=0 j<state.transitions.length j++) {
target = state.transitions[j].target target = state.transitions[j].target
if (target instanceof StarLoopEntryState) { if _, ok := target.(StarLoopEntryState); ok {
target.loopBackState = state target.loopBackState = state
} }
} }
@ -475,7 +475,7 @@ func (this *ATNDeserializer) markPrecedenceDecisions(atn) {
// //
if ( atn.ruleToStartState[state.ruleIndex].isPrecedenceRule) { if ( atn.ruleToStartState[state.ruleIndex].isPrecedenceRule) {
var maybeLoopEndState = state.transitions[state.transitions.length - 1].target var maybeLoopEndState = state.transitions[state.transitions.length - 1].target
if (maybeLoopEndState instanceof LoopEndState) { if _, ok := maybeLoopEndState.(LoopEndState); ok {
if ( maybeLoopEndState.epsilonOnlyTransitions && if ( maybeLoopEndState.epsilonOnlyTransitions &&
(maybeLoopEndState.transitions[0].target instanceof RuleStopState)) { (maybeLoopEndState.transitions[0].target instanceof RuleStopState)) {
state.precedenceRuleDecision = true state.precedenceRuleDecision = true
@ -496,9 +496,9 @@ func (this *ATNDeserializer) verifyATN(atn) {
continue continue
} }
this.checkCondition(state.epsilonOnlyTransitions || state.transitions.length <= 1) this.checkCondition(state.epsilonOnlyTransitions || state.transitions.length <= 1)
if (state instanceof PlusBlockStartState) { if _, ok := state.(PlusBlockStartState); ok {
this.checkCondition(state.loopBackState != nil) this.checkCondition(state.loopBackState != nil)
} else if (state instanceof StarLoopEntryState) { } else if _, ok := state.(StarLoopEntryState); ok {
this.checkCondition(state.loopBackState != nil) this.checkCondition(state.loopBackState != nil)
this.checkCondition(state.transitions.length == 2) this.checkCondition(state.transitions.length == 2)
if (state.transitions[0].target instanceof StarBlockStartState) { if (state.transitions[0].target instanceof StarBlockStartState) {
@ -510,21 +510,21 @@ func (this *ATNDeserializer) verifyATN(atn) {
} else { } else {
panic("IllegalState") panic("IllegalState")
} }
} else if (state instanceof StarLoopbackState) { } else if _, ok := state.(StarLoopbackState); ok {
this.checkCondition(state.transitions.length == 1) this.checkCondition(state.transitions.length == 1)
this.checkCondition(state.transitions[0].target instanceof StarLoopEntryState) this.checkCondition(state.transitions[0].target instanceof StarLoopEntryState)
} else if (state instanceof LoopEndState) { } else if _, ok := state.(LoopEndState); ok {
this.checkCondition(state.loopBackState != nil) this.checkCondition(state.loopBackState != nil)
} else if (state instanceof RuleStartState) { } else if _, ok := state.(RuleStartState); ok {
this.checkCondition(state.stopState != nil) this.checkCondition(state.stopState != nil)
} else if (state instanceof BlockStartState) { } else if _, ok := state.(BlockStartState); ok {
this.checkCondition(state.endState != nil) this.checkCondition(state.endState != nil)
} else if (state instanceof BlockEndState) { } else if _, ok := state.(BlockEndState); ok {
this.checkCondition(state.startState != nil) this.checkCondition(state.startState != nil)
} else if (state instanceof DecisionState) { } else if _, ok := state.(DecisionState); ok {
this.checkCondition(state.transitions.length <= 1 || state.decision >= 0) this.checkCondition(state.transitions.length <= 1 || state.decision >= 0)
} else { } else {
this.checkCondition(state.transitions.length <= 1 || (state instanceof RuleStopState)) this.checkCondition(state.transitions.length <= 1 || _, ok := state.(RuleStopState); ok)
} }
} }
} }

View File

@ -4,6 +4,11 @@ package atn
//var ATNConfigSet = require('./ATNConfigSet').ATNConfigSet //var ATNConfigSet = require('./ATNConfigSet').ATNConfigSet
//var getCachedPredictionContext = require('./../PredictionContext').getCachedPredictionContext //var getCachedPredictionContext = require('./../PredictionContext').getCachedPredictionContext
type ATNSimulator struct {
atn *ATN
sharedContextCache
}
func ATNSimulator(atn, sharedContextCache) { func ATNSimulator(atn, sharedContextCache) {
// The context cache maps all PredictionContext objects that are == // The context cache maps all PredictionContext objects that are ==

View File

@ -117,7 +117,7 @@ func (this *LexerATNSimulator) matchATN(input) {
var startState = this.atn.modeToStartState[this.mode] var startState = this.atn.modeToStartState[this.mode]
if (this.debug) { 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 old_mode = this.mode
var s0_closure = this.computeStartState(input, startState) var s0_closure = this.computeStartState(input, startState)
@ -132,14 +132,14 @@ func (this *LexerATNSimulator) matchATN(input) {
var predict = this.execATN(input, next) var predict = this.execATN(input, next)
if (this.debug) { 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 return predict
} }
LexerATNSimulator.prototype.execATN = function(input, ds0) { LexerATNSimulator.prototype.execATN = function(input, ds0) {
if (this.debug) { if (this.debug) {
console.log("start state closure=" + ds0.configs) fmt.Println("start state closure=" + ds0.configs)
} }
if (ds0.isAcceptState) { if (ds0.isAcceptState) {
// allow zero-length tokens // allow zero-length tokens
@ -150,7 +150,7 @@ LexerATNSimulator.prototype.execATN = function(input, ds0) {
for (true) { // while more work for (true) { // while more work
if (this.debug) { 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 // 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 target = nil
} }
if (this.debug && 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 return target
} }
@ -282,7 +282,7 @@ func (this *LexerATNSimulator) getReachableConfigSet(input, closure,
continue continue
} }
if (this.debug) { 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)) .toString(this.recog, true))
} }
for j := 0; j < len(cfg.state.transitions); j++ { 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, func (this *LexerATNSimulator) accept(input, lexerActionExecutor,
startIndex, index, line, charPos) { startIndex, index, line, charPos) {
if (this.debug) { if (this.debug) {
console.log("ACTION %s\n", lexerActionExecutor) fmt.Println("ACTION %s\n", lexerActionExecutor)
} }
// seek to after last char in token // seek to after last char in token
input.seek(index) input.seek(index)
@ -351,14 +351,14 @@ func (this *LexerATNSimulator) closure(input, config, configs,
currentAltReachedAcceptState, speculative, treatEofAsEpsilon) { currentAltReachedAcceptState, speculative, treatEofAsEpsilon) {
var cfg = nil var cfg = nil
if (this.debug) { 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 (config.state instanceof RuleStopState) {
if (this.debug) { if (this.debug) {
if (this.recog != nil) { 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 { } 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()) { 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. // test them, we cannot cash the DFA state target of ID.
if (this.debug) { if (this.debug) {
console.log("EVAL rule " + trans.ruleIndex + ":" + trans.predIndex) fmt.Println("EVAL rule " + trans.ruleIndex + ":" + trans.predIndex)
} }
configs.hasSemanticContext = true configs.hasSemanticContext = true
if (this.evaluatePredicate(input, trans.ruleIndex, trans.predIndex, speculative)) { if (this.evaluatePredicate(input, trans.ruleIndex, trans.predIndex, speculative)) {
@ -556,7 +556,7 @@ func (this *LexerATNSimulator) addDFAEdge(from_, tk, to, cfgs) {
return to return to
} }
if (this.debug) { if (this.debug) {
console.log("EDGE " + from_ + " -> " + to + " upon " + tk) fmt.Println("EDGE " + from_ + " -> " + to + " upon " + tk)
} }
if (from_.edges == nil) { if (from_.edges == nil) {
// make room for tokens 1..n and -1 masquerading as index 0 // make room for tokens 1..n and -1 masquerading as index 0

View File

@ -81,7 +81,7 @@ func (this *LexerTypeAction) hashString() {
func (this *LexerTypeAction) equals(other) { func (this *LexerTypeAction) equals(other) {
if(this == other) { if(this == other) {
return true return true
} else if (! (other instanceof LexerTypeAction)) { } else if (! _, ok := other.(LexerTypeAction); ok) {
return false return false
} else { } else {
return this.type == other.type return this.type == other.type
@ -116,7 +116,7 @@ func (this *LexerPushModeAction) hashString() {
func (this *LexerPushModeAction) equals(other) { func (this *LexerPushModeAction) equals(other) {
if (this == other) { if (this == other) {
return true return true
} else if (! (other instanceof LexerPushModeAction)) { } else if (! _, ok := other.(LexerPushModeAction); ok) {
return false return false
} else { } else {
return this.mode == other.mode return this.mode == other.mode
@ -199,7 +199,7 @@ func (this *LexerModeAction) hashString() {
func (this *LexerModeAction) equals(other) { func (this *LexerModeAction) equals(other) {
if (this == other) { if (this == other) {
return true return true
} else if (! (other instanceof LexerModeAction)) { } else if (! _, ok := other.(LexerModeAction); ok) {
return false return false
} else { } else {
return this.mode == other.mode return this.mode == other.mode
@ -252,7 +252,7 @@ func (this *LexerCustomAction) hashString() {
func (this *LexerCustomAction) equals(other) { func (this *LexerCustomAction) equals(other) {
if (this == other) { if (this == other) {
return true return true
} else if (! (other instanceof LexerCustomAction)) { } else if (! _, ok := other.(LexerCustomAction); ok) {
return false return false
} else { } else {
return this.ruleIndex == other.ruleIndex && this.actionIndex == other.actionIndex return this.ruleIndex == other.ruleIndex && this.actionIndex == other.actionIndex
@ -285,7 +285,7 @@ func (this *LexerChannelAction) hashString() {
func (this *LexerChannelAction) equals(other) { func (this *LexerChannelAction) equals(other) {
if (this == other) { if (this == other) {
return true return true
} else if (! (other instanceof LexerChannelAction)) { } else if (! _, ok := other.(LexerChannelAction); ok) {
return false return false
} else { } else {
return this.channel == other.channel return this.channel == other.channel
@ -341,7 +341,7 @@ func (this *LexerIndexedCustomAction) hashString() {
func (this *LexerIndexedCustomAction) equals(other) { func (this *LexerIndexedCustomAction) equals(other) {
if (this == other) { if (this == other) {
return true return true
} else if (! (other instanceof LexerIndexedCustomAction)) { } else if (! _, ok := other.(LexerIndexedCustomAction); ok) {
return false return false
} else { } else {
return this.offset == other.offset && this.action == other.action return this.offset == other.offset && this.action == other.action

View File

@ -110,7 +110,7 @@ func (this *LexerActionExecutor) execute(lexer, input, startIndex) {
try { try {
for i := 0; i < len(this.lexerActions); i++ { for i := 0; i < len(this.lexerActions); i++ {
var lexerAction = this.lexerActions[i] var lexerAction = this.lexerActions[i]
if (lexerAction instanceof LexerIndexedCustomAction) { if _, ok := lexerAction.(LexerIndexedCustomAction); ok {
var offset = lexerAction.offset var offset = lexerAction.offset
input.seek(startIndex + offset) input.seek(startIndex + offset)
lexerAction = lexerAction.action lexerAction = lexerAction.action
@ -135,7 +135,7 @@ func (this *LexerActionExecutor) hashString() {
func (this *LexerActionExecutor) equals(other) { func (this *LexerActionExecutor) equals(other) {
if (this == other) { if (this == other) {
return true return true
} else if (!(other instanceof LexerActionExecutor)) { } else if (!_, ok := other.(LexerActionExecutor); ok) {
return false return false
} else { } else {
return this.hashString == other.hashString && return this.hashString == other.hashString &&

View File

@ -263,7 +263,7 @@ func ParserATNSimulator(parser, atn, decisionToDFA, sharedContextCache) {
this.parser = parser this.parser = parser
this.decisionToDFA = decisionToDFA this.decisionToDFA = decisionToDFA
// SLL, LL, or LL + exact ambig detection?// // 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 // LAME globals to avoid parameters!!!!! I need these down deep in predTransition
this._input = nil this._input = nil
this._startIndex = 0 this._startIndex = 0
@ -289,13 +289,12 @@ ParserATNSimulator.prototype.debug_list_atn_decisions = false
ParserATNSimulator.prototype.dfa_debug = false ParserATNSimulator.prototype.dfa_debug = false
ParserATNSimulator.prototype.retry_debug = false ParserATNSimulator.prototype.retry_debug = false
func (this *ParserATNSimulator) reset() { func (this *ParserATNSimulator) reset() {
} }
func (this *ParserATNSimulator) adaptivePredict(input, decision, outerContext) { func (this *ParserATNSimulator) adaptivePredict(input, decision, outerContext) {
if (this.debug || this.debug_list_atn_decisions) { if (this.debug || this.debug_list_atn_decisions) {
console.log("adaptivePredict decision " + decision + fmt.Println("adaptivePredict decision " + decision +
" exec LA(1)==" + this.getLookaheadName(input) + " exec LA(1)==" + this.getLookaheadName(input) +
" line " + input.LT(1).line + ":" + " line " + input.LT(1).line + ":" +
input.LT(1).column) input.LT(1).column)
@ -326,7 +325,7 @@ func (this *ParserATNSimulator) adaptivePredict(input, decision, outerContext) {
outerContext = RuleContext.EMPTY outerContext = RuleContext.EMPTY
} }
if (this.debug || this.debug_list_atn_decisions) { 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) + " exec LA(1)==" + this.getLookaheadName(input) +
", outerContext=" + outerContext.toString(this.parser.ruleNames)) ", 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) var alt = this.execATN(dfa, s0, input, index, outerContext)
if (this.debug) { 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 return alt
} finally { } finally {
@ -402,7 +401,7 @@ func (this *ParserATNSimulator) adaptivePredict(input, decision, outerContext) {
// //
ParserATNSimulator.prototype.execATN = function(dfa, s0, input, startIndex, outerContext ) { ParserATNSimulator.prototype.execATN = function(dfa, s0, input, startIndex, outerContext ) {
if (this.debug || this.debug_list_atn_decisions) { 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) + " exec LA(1)==" + this.getLookaheadName(input) +
" line " + input.LT(1).line + ":" + input.LT(1).column) " 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 var previousD = s0
if (this.debug) { if (this.debug) {
console.log("s0 = " + s0) fmt.Println("s0 = " + s0)
} }
var t = input.LA(1) var t = input.LA(1)
while(true) { // while more work while(true) { // while more work
@ -437,12 +436,12 @@ ParserATNSimulator.prototype.execATN = function(dfa, s0, input, startIndex, oute
panic e 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) // IF PREDS, MIGHT RESOLVE TO SINGLE ALT => SLL (or syntax error)
var conflictingAlts = nil var conflictingAlts = nil
if (D.predicates!=nil) { if (D.predicates!=nil) {
if (this.debug) { 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 var conflictIndex = input.index
if(conflictIndex != startIndex) { if(conflictIndex != startIndex) {
@ -451,7 +450,7 @@ ParserATNSimulator.prototype.execATN = function(dfa, s0, input, startIndex, oute
conflictingAlts = this.evalSemanticContext(D.predicates, outerContext, true) conflictingAlts = this.evalSemanticContext(D.predicates, outerContext, true)
if (conflictingAlts.length==1) { if (conflictingAlts.length==1) {
if(this.debug) { if(this.debug) {
console.log("Full LL avoided") fmt.Println("Full LL avoided")
} }
return conflictingAlts.minValue() return conflictingAlts.minValue()
} }
@ -462,7 +461,7 @@ ParserATNSimulator.prototype.execATN = function(dfa, s0, input, startIndex, oute
} }
} }
if (this.dfa_debug) { if (this.dfa_debug) {
console.log("ctx sensitive state " + outerContext +" in " + D) fmt.Println("ctx sensitive state " + outerContext +" in " + D)
} }
var fullCtx = true var fullCtx = true
var s0_closure = this.computeStartState(dfa.atnStartState, outerContext, fullCtx) 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) var predictedAlt = this.getUniqueAlt(reach)
if (this.debug) { if (this.debug) {
var altSubSets = PredictionMode.getConflictingAltSubsets(reach) var altSubSets = PredictionModegetConflictingAltSubsets(reach)
console.log("SLL altSubSets=" + Utils.arrayToString(altSubSets) + fmt.Println("SLL altSubSets=" + Utils.arrayToString(altSubSets) +
", previous=" + previousD.configs + ", previous=" + previousD.configs +
", configs=" + reach + ", configs=" + reach +
", predict=" + predictedAlt + ", predict=" + predictedAlt +
", allSubsetsConflict=" + ", allSubsetsConflict=" +
PredictionMode.allSubsetsConflict(altSubSets) + ", conflictingAlts=" + PredictionModeallSubsetsConflict(altSubSets) + ", conflictingAlts=" +
this.getConflictingAlts(reach)) this.getConflictingAlts(reach))
} }
if (predictedAlt!=ATN.INVALID_ALT_NUMBER) { if (predictedAlt!=ATN.INVALID_ALT_NUMBER) {
@ -552,7 +551,7 @@ func (this *ParserATNSimulator) computeTargetState(dfa, previousD, t) {
D.isAcceptState = true D.isAcceptState = true
D.configs.uniqueAlt = predictedAlt D.configs.uniqueAlt = predictedAlt
D.prediction = predictedAlt D.prediction = predictedAlt
} else if (PredictionMode.hasSLLConflictTerminatingPrediction(this.predictionMode, reach)) { } else if (PredictionModehasSLLConflictTerminatingPrediction(this.predictionMode, reach)) {
// MORE THAN ONE VIABLE ALTERNATIVE // MORE THAN ONE VIABLE ALTERNATIVE
D.configs.conflictingAlts = this.getConflictingAlts(reach) D.configs.conflictingAlts = this.getConflictingAlts(reach)
D.requiresFullContext = true D.requiresFullContext = true
@ -597,7 +596,7 @@ ParserATNSimulator.prototype.execATNWithFullContext = function(dfa, D, // how fa
startIndex, startIndex,
outerContext) { outerContext) {
if (this.debug || this.debug_list_atn_decisions) { if (this.debug || this.debug_list_atn_decisions) {
console.log("execATNWithFullContext "+s0) fmt.Println("execATNWithFullContext "+s0)
} }
var fullCtx = true var fullCtx = true
var foundExactAmbig = false var foundExactAmbig = false
@ -627,28 +626,28 @@ ParserATNSimulator.prototype.execATNWithFullContext = function(dfa, D, // how fa
panic e panic e
} }
} }
var altSubSets = PredictionMode.getConflictingAltSubsets(reach) var altSubSets = PredictionModegetConflictingAltSubsets(reach)
if(this.debug) { if(this.debug) {
console.log("LL altSubSets=" + altSubSets + ", predict=" + fmt.Println("LL altSubSets=" + altSubSets + ", predict=" +
PredictionMode.getUniqueAlt(altSubSets) + ", resolvesToJustOneViableAlt=" + PredictionModegetUniqueAlt(altSubSets) + ", resolvesToJustOneViableAlt=" +
PredictionMode.resolvesToJustOneViableAlt(altSubSets)) PredictionModeresolvesToJustOneViableAlt(altSubSets))
} }
reach.uniqueAlt = this.getUniqueAlt(reach) reach.uniqueAlt = this.getUniqueAlt(reach)
// unique prediction? // unique prediction?
if(reach.uniqueAlt!=ATN.INVALID_ALT_NUMBER) { if(reach.uniqueAlt!=ATN.INVALID_ALT_NUMBER) {
predictedAlt = reach.uniqueAlt predictedAlt = reach.uniqueAlt
break break
} else if (this.predictionMode != PredictionMode.LL_EXACT_AMBIG_DETECTION) { } else if (this.predictionMode != PredictionModeLL_EXACT_AMBIG_DETECTION) {
predictedAlt = PredictionMode.resolvesToJustOneViableAlt(altSubSets) predictedAlt = PredictionModeresolvesToJustOneViableAlt(altSubSets)
if(predictedAlt != ATN.INVALID_ALT_NUMBER) { if(predictedAlt != ATN.INVALID_ALT_NUMBER) {
break break
} }
} else { } else {
// In exact ambiguity mode, we never try to terminate early. // In exact ambiguity mode, we never try to terminate early.
// Just keeps scarfing until we know what the conflict is // Just keeps scarfing until we know what the conflict is
if (PredictionMode.allSubsetsConflict(altSubSets) && PredictionMode.allSubsetsEqual(altSubSets)) { if (PredictionModeallSubsetsConflict(altSubSets) && PredictionModeallSubsetsEqual(altSubSets)) {
foundExactAmbig = true foundExactAmbig = true
predictedAlt = PredictionMode.getSingleViableAlt(altSubSets) predictedAlt = PredictionModegetSingleViableAlt(altSubSets)
break break
} }
// else there are multiple non-conflicting subsets or // 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) { func (this *ParserATNSimulator) computeReachSet(closure, t, fullCtx) {
if (this.debug) { if (this.debug) {
console.log("in computeReachSet, starting closure: " + closure) fmt.Println("in computeReachSet, starting closure: " + closure)
} }
if( this.mergeCache==nil) { if( this.mergeCache==nil) {
this.mergeCache = NewDoubleDict() this.mergeCache = NewDoubleDict()
@ -725,7 +724,7 @@ func (this *ParserATNSimulator) computeReachSet(closure, t, fullCtx) {
for (var i=0 i<closure.items.lengthi++) { for (var i=0 i<closure.items.lengthi++) {
var c = closure.items[i] var c = closure.items[i]
if(this.debug) { if(this.debug) {
console.log("testing " + this.getTokenName(t) + " at " + c) fmt.Println("testing " + this.getTokenName(t) + " at " + c)
} }
if (c.state instanceof RuleStopState) { if (c.state instanceof RuleStopState) {
if (fullCtx || t == TokenEOF) { if (fullCtx || t == TokenEOF) {
@ -734,7 +733,7 @@ func (this *ParserATNSimulator) computeReachSet(closure, t, fullCtx) {
} }
skippedStopStates.push(c) skippedStopStates.push(c)
if(this.debug) { if(this.debug) {
console.log("added " + c + " to skippedStopStates") fmt.Println("added " + c + " to skippedStopStates")
} }
} }
continue continue
@ -746,7 +745,7 @@ func (this *ParserATNSimulator) computeReachSet(closure, t, fullCtx) {
var cfg = NewATNConfig({state:target}, c) var cfg = NewATNConfig({state:target}, c)
intermediate.add(cfg, this.mergeCache) intermediate.add(cfg, this.mergeCache)
if(this.debug) { if(this.debug) {
console.log("added " + cfg + " to intermediate") fmt.Println("added " + cfg + " to intermediate")
} }
} }
} }
@ -815,7 +814,7 @@ func (this *ParserATNSimulator) computeReachSet(closure, t, fullCtx) {
// chooses an alternative matching the longest overall sequence when // chooses an alternative matching the longest overall sequence when
// multiple alternatives are viable. // multiple alternatives are viable.
// //
if (skippedStopStates!=nil && ( (! fullCtx) || (! PredictionMode.hasConfigInRuleStopState(reach)))) { if (skippedStopStates!=nil && ( (! fullCtx) || (! PredictionModehasConfigInRuleStopState(reach)))) {
for (var l=0 l<skippedStopStates.lengthl++) { for (var l=0 l<skippedStopStates.lengthl++) {
reach.add(skippedStopStates[l], this.mergeCache) reach.add(skippedStopStates[l], this.mergeCache)
} }
@ -847,7 +846,7 @@ func (this *ParserATNSimulator) computeReachSet(closure, t, fullCtx) {
// the configurations from {@code configs} which are in a rule stop state // the configurations from {@code configs} which are in a rule stop state
// //
func (this *ParserATNSimulator) removeAllConfigsNotInRuleStopState(configs, lookToEndOfRule) { func (this *ParserATNSimulator) removeAllConfigsNotInRuleStopState(configs, lookToEndOfRule) {
if (PredictionMode.allConfigsInRuleStopStates(configs)) { if (PredictionModeallConfigsInRuleStopStates(configs)) {
return configs return configs
} }
var result = NewATNConfigSet(configs.fullCtx) var result = NewATNConfigSet(configs.fullCtx)
@ -1022,7 +1021,7 @@ func (this *ParserATNSimulator) getPredsForAmbigAlts(ambigAlts, configs, nalts)
altToPred = nil altToPred = nil
} }
if (this.debug) { if (this.debug) {
console.log("getPredsForAmbigAlts result " + Utils.arrayToString(altToPred)) fmt.Println("getPredsForAmbigAlts result " + Utils.arrayToString(altToPred))
} }
return altToPred return altToPred
} }
@ -1173,11 +1172,11 @@ func (this *ParserATNSimulator) evalSemanticContext(predPredictions, outerContex
} }
var predicateEvaluationResult = pair.pred.evaluate(this.parser, outerContext) var predicateEvaluationResult = pair.pred.evaluate(this.parser, outerContext)
if (this.debug || this.dfa_debug) { if (this.debug || this.dfa_debug) {
console.log("eval pred " + pair + "=" + predicateEvaluationResult) fmt.Println("eval pred " + pair + "=" + predicateEvaluationResult)
} }
if (predicateEvaluationResult) { if (predicateEvaluationResult) {
if (this.debug || this.dfa_debug) { if (this.debug || this.dfa_debug) {
console.log("PREDICT " + pair.alt) fmt.Println("PREDICT " + pair.alt)
} }
predictions.add(pair.alt) predictions.add(pair.alt)
if (! complete) { if (! complete) {
@ -1204,8 +1203,8 @@ func (this *ParserATNSimulator) closure(config, configs, closureBusy, collectPre
func (this *ParserATNSimulator) closureCheckingStopState(config, configs, closureBusy, collectPredicates, fullCtx, depth, treatEofAsEpsilon) { func (this *ParserATNSimulator) closureCheckingStopState(config, configs, closureBusy, collectPredicates, fullCtx, depth, treatEofAsEpsilon) {
if (this.debug) { if (this.debug) {
console.log("closure(" + config.toString(this.parser,true) + ")") fmt.Println("closure(" + config.toString(this.parser,true) + ")")
console.log("configs(" + configs.toString() + ")") fmt.Println("configs(" + configs.toString() + ")")
if(config.reachesIntoOuterContext>50) { if(config.reachesIntoOuterContext>50) {
panic "problem" panic "problem"
} }
@ -1222,7 +1221,7 @@ func (this *ParserATNSimulator) closureCheckingStopState(config, configs, closur
} else { } else {
// we have no context info, just chase follow links (if greedy) // we have no context info, just chase follow links (if greedy)
if (this.debug) { 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, this.closure_(config, configs, closureBusy, collectPredicates,
fullCtx, depth, treatEofAsEpsilon) fullCtx, depth, treatEofAsEpsilon)
@ -1247,7 +1246,7 @@ func (this *ParserATNSimulator) closureCheckingStopState(config, configs, closur
} else { } else {
// else if we have no context info, just chase follow links (if greedy) // else if we have no context info, just chase follow links (if greedy)
if (this.debug) { 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<p.transitions.length i++) { for(var i = 0i<p.transitions.length i++) {
var t = p.transitions[i] var t = p.transitions[i]
var continueCollecting = collectPredicates && !(t instanceof ActionTransition) var continueCollecting = collectPredicates && !_, ok := t.(ActionTransition); ok
var c = this.getEpsilonTarget(config, t, continueCollecting, depth == 0, fullCtx, treatEofAsEpsilon) var c = this.getEpsilonTarget(config, t, continueCollecting, depth == 0, fullCtx, treatEofAsEpsilon)
if (c!=nil) { if (c!=nil) {
if (!t.isEpsilon && closureBusy.add(c)!=c){ if (!t.isEpsilon && closureBusy.add(c)!=c){
@ -1295,9 +1294,9 @@ func (this *ParserATNSimulator) closure_(config, configs, closureBusy, collectPr
configs.dipsIntoOuterContext = true // TODO: can remove? only care when we add to set per middle of this method configs.dipsIntoOuterContext = true // TODO: can remove? only care when we add to set per middle of this method
newDepth -= 1 newDepth -= 1
if (this.debug) { if (this.debug) {
console.log("dips into outer ctx: " + c) fmt.Println("dips into outer ctx: " + c)
} }
} else if (t instanceof RuleTransition) { } else if _, ok := t.(RuleTransition); ok {
// latch when newDepth goes negative - once we step out of the entry context we can't return // latch when newDepth goes negative - once we step out of the entry context we can't return
if (newDepth >= 0) { if (newDepth >= 0) {
newDepth += 1 newDepth += 1
@ -1346,17 +1345,17 @@ func (this *ParserATNSimulator) getEpsilonTarget(config, t, collectPredicates, i
func (this *ParserATNSimulator) actionTransition(config, t) { func (this *ParserATNSimulator) actionTransition(config, t) {
if (this.debug) { 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) return NewATNConfig({state:t.target}, config)
} }
func (this *ParserATNSimulator) precedenceTransition(config, pt, collectPredicates, inContext, fullCtx) { func (this *ParserATNSimulator) precedenceTransition(config, pt, collectPredicates, inContext, fullCtx) {
if (this.debug) { if (this.debug) {
console.log("PRED (collectPredicates=" + collectPredicates + ") " + fmt.Println("PRED (collectPredicates=" + collectPredicates + ") " +
pt.precedence + ">=_p, ctx dependent=true") pt.precedence + ">=_p, ctx dependent=true")
if (this.parser!=nil) { 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 var c = nil
@ -1381,17 +1380,17 @@ func (this *ParserATNSimulator) precedenceTransition(config, pt, collectPredica
c = NewATNConfig({state:pt.target}, config) c = NewATNConfig({state:pt.target}, config)
} }
if (this.debug) { if (this.debug) {
console.log("config from pred transition=" + c) fmt.Println("config from pred transition=" + c)
} }
return c return c
} }
func (this *ParserATNSimulator) predTransition(config, pt, collectPredicates, inContext, fullCtx) { func (this *ParserATNSimulator) predTransition(config, pt, collectPredicates, inContext, fullCtx) {
if (this.debug) { if (this.debug) {
console.log("PRED (collectPredicates=" + collectPredicates + ") " + pt.ruleIndex + fmt.Println("PRED (collectPredicates=" + collectPredicates + ") " + pt.ruleIndex +
":" + pt.predIndex + ", ctx dependent=" + pt.isCtxDependent) ":" + pt.predIndex + ", ctx dependent=" + pt.isCtxDependent)
if (this.parser!=nil) { 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 var c = nil
@ -1416,14 +1415,14 @@ func (this *ParserATNSimulator) predTransition(config, pt, collectPredicates, in
c = NewATNConfig({state:pt.target}, config) c = NewATNConfig({state:pt.target}, config)
} }
if (this.debug) { if (this.debug) {
console.log("config from pred transition=" + c) fmt.Println("config from pred transition=" + c)
} }
return c return c
} }
func (this *ParserATNSimulator) ruleTransition(config, t) { func (this *ParserATNSimulator) ruleTransition(config, t) {
if (this.debug) { 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 returnState = t.followState
var newContext = SingletonPredictionContext.create(config.context, returnState.stateNumber) var newContext = SingletonPredictionContext.create(config.context, returnState.stateNumber)
@ -1431,8 +1430,8 @@ func (this *ParserATNSimulator) ruleTransition(config, t) {
} }
func (this *ParserATNSimulator) getConflictingAlts(configs) { func (this *ParserATNSimulator) getConflictingAlts(configs) {
var altsets = PredictionMode.getConflictingAltSubsets(configs) var altsets = PredictionModegetConflictingAltSubsets(configs)
return PredictionMode.getAlts(altsets) return PredictionModegetAlts(altsets)
} }
// Sam pointed out a problem with the previous definition, v3, of // 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( this.parser!=nil && this.parser.literalNames!=nil) {
if (t >= this.parser.literalNames.length) { if (t >= this.parser.literalNames.length) {
console.log("" + t + " ttype out of range: " + this.parser.literalNames) fmt.Println("" + t + " ttype out of range: " + this.parser.literalNames)
console.log("" + this.parser.getInputStream().getTokens()) fmt.Println("" + this.parser.getInputStream().getTokens())
} else { } else {
return this.parser.literalNames[t] + "<" + t + ">" return this.parser.literalNames[t] + "<" + t + ">"
} }
@ -1506,17 +1505,17 @@ func (this *ParserATNSimulator) getLookaheadName(input) {
// "dead" code for a bit. // "dead" code for a bit.
// //
func (this *ParserATNSimulator) dumpDeadEndConfigs(nvae) { func (this *ParserATNSimulator) dumpDeadEndConfigs(nvae) {
console.log("dead end configs: ") fmt.Println("dead end configs: ")
var decs = nvae.getDeadEndConfigs() var decs = nvae.getDeadEndConfigs()
for(var i=0 i<decs.length i++) { for(var i=0 i<decs.length i++) {
var c = decs[i] var c = decs[i]
var trans = "no edges" var trans = "no edges"
if (c.state.transitions.length>0) { if (c.state.transitions.length>0) {
var t = c.state.transitions[0] var t = c.state.transitions[0]
if (t instanceof AtomTransition) { if _, ok := t.(AtomTransition); ok {
trans = "Atom "+ this.getTokenName(t.label) trans = "Atom "+ this.getTokenName(t.label)
} else if (t instanceof SetTransition) { } else if _, ok := t.(SetTransition); ok {
var neg = (t instanceof NotSetTransition) var neg = _, ok := t.(NotSetTransition); ok
trans = (neg ? "~" : "") + "Set " + t.set trans = (neg ? "~" : "") + "Set " + t.set
} }
} }
@ -1563,7 +1562,7 @@ func (this *ParserATNSimulator) getUniqueAlt(configs) {
// //
func (this *ParserATNSimulator) addDFAEdge(dfa, from_, t, to) { func (this *ParserATNSimulator) addDFAEdge(dfa, from_, t, to) {
if( this.debug) { if( this.debug) {
console.log("EDGE " + from_ + " -> " + to + " upon " + this.getTokenName(t)) fmt.Println("EDGE " + from_ + " -> " + to + " upon " + this.getTokenName(t))
} }
if (to==nil) { if (to==nil) {
return nil return nil
@ -1579,7 +1578,7 @@ func (this *ParserATNSimulator) addDFAEdge(dfa, from_, t, to) {
if (this.debug) { if (this.debug) {
var names = this.parser==nil ? nil : this.parser.literalNames 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 return to
} }
@ -1614,7 +1613,7 @@ func (this *ParserATNSimulator) addDFAState(dfa, D) {
} }
dfa.states[hash] = D dfa.states[hash] = D
if (this.debug) { if (this.debug) {
console.log("adding NewDFA state: " + D) fmt.Println("adding NewDFA state: " + D)
} }
return D return D
} }
@ -1622,7 +1621,7 @@ func (this *ParserATNSimulator) addDFAState(dfa, D) {
func (this *ParserATNSimulator) reportAttemptingFullContext(dfa, conflictingAlts, configs, startIndex, stopIndex) { func (this *ParserATNSimulator) reportAttemptingFullContext(dfa, conflictingAlts, configs, startIndex, stopIndex) {
if (this.debug || this.retry_debug) { if (this.debug || this.retry_debug) {
var interval = NewInterval(startIndex, stopIndex + 1) 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)) ", input=" + this.parser.getTokenStream().getText(interval))
} }
if (this.parser!=nil) { if (this.parser!=nil) {
@ -1633,7 +1632,7 @@ func (this *ParserATNSimulator) reportAttemptingFullContext(dfa, conflictingAlts
func (this *ParserATNSimulator) reportContextSensitivity(dfa, prediction, configs, startIndex, stopIndex) { func (this *ParserATNSimulator) reportContextSensitivity(dfa, prediction, configs, startIndex, stopIndex) {
if (this.debug || this.retry_debug) { if (this.debug || this.retry_debug) {
var interval = NewInterval(startIndex, stopIndex + 1) 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)) ", input=" + this.parser.getTokenStream().getText(interval))
} }
if (this.parser!=nil) { if (this.parser!=nil) {
@ -1646,7 +1645,7 @@ func (this *ParserATNSimulator) reportAmbiguity(dfa, D, startIndex, stopIndex,
exact, ambigAlts, configs ) { exact, ambigAlts, configs ) {
if (this.debug || this.retry_debug) { if (this.debug || this.retry_debug) {
var interval = NewInterval(startIndex, stopIndex + 1) var interval = NewInterval(startIndex, stopIndex + 1)
console.log("reportAmbiguity " + ambigAlts + ":" + configs + fmt.Println("reportAmbiguity " + ambigAlts + ":" + configs +
", input=" + this.parser.getTokenStream().getText(interval)) ", input=" + this.parser.getTokenStream().getText(interval))
} }
if (this.parser!=nil) { if (this.parser!=nil) {

View File

@ -12,69 +12,75 @@ package atn
//var RuleStopState = require('./ATNState').RuleStopState //var RuleStopState = require('./ATNState').RuleStopState
type PredictionMode struct { type PredictionMode struct {
return this
} }
// func NewPredictionMode() *PredictionMode {
// The SLL(*) prediction mode. This prediction mode ignores the current return new(PredictionMode)
// 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.
//
// <p>
// 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.</p>
//
// <p>
// This prediction mode does not provide any guarantees for prediction
// behavior for syntactically-incorrect inputs.</p>
//
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.
//
// <p>
// 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 <em>exactly which</em> alternatives are
// ambiguous.</p>
//
// <p>
// This prediction mode does not provide any guarantees for prediction
// behavior for syntactically-incorrect inputs.</p>
//
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.
//
// <p>
// 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.</p>
//
// <p>
// This prediction mode does not provide any guarantees for prediction
// behavior for syntactically-incorrect inputs.</p>
//
PredictionMode.LL_EXACT_AMBIG_DETECTION = 2
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.
//
// <p>
// 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.</p>
//
// <p>
// This prediction mode does not provide any guarantees for prediction
// behavior for syntactically-incorrect inputs.</p>
//
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.
//
// <p>
// 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 <em>exactly which</em> alternatives are
// ambiguous.</p>
//
// <p>
// This prediction mode does not provide any guarantees for prediction
// behavior for syntactically-incorrect inputs.</p>
//
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.
//
// <p>
// 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.</p>
//
// <p>
// This prediction mode does not provide any guarantees for prediction
// behavior for syntactically-incorrect inputs.</p>
//
PredictionModeLL_EXACT_AMBIG_DETECTION = 2
)
// //
// Computes the SLL prediction termination condition. // 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 // the configurations to strip out all of the predicates so that a standard
// {@link ATNConfigSet} will merge everything ignoring predicates.</p> // {@link ATNConfigSet} will merge everything ignoring predicates.</p>
// //
PredictionMode.hasSLLConflictTerminatingPrediction = function( mode, configs) { PredictionModehasSLLConflictTerminatingPrediction = function( mode, configs) {
// Configs in rule stop states indicate reaching the end of the decision // Configs in rule stop states indicate reaching the end of the decision
// rule (local context) or end of start rule (full context). If all // rule (local context) or end of start rule (full context). If all
// configs meet this condition, then none of the configurations is able // configs meet this condition, then none of the configurations is able
// to match additional input so we terminate prediction. // to match additional input so we terminate prediction.
// //
if (PredictionMode.allConfigsInRuleStopStates(configs)) { if (PredictionModeallConfigsInRuleStopStates(configs)) {
return true return true
} }
// pure SLL mode parsing // pure SLL mode parsing
if (mode == PredictionMode.SLL) { if (mode == PredictionModeSLL) {
// Don't bother with combining configs from different semantic // Don't bother with combining configs from different semantic
// contexts if we can fail over to full LL costs more time // contexts if we can fail over to full LL costs more time
// since we'll often fail over anyway. // 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 // now we have combined contexts for configs with dissimilar preds
} }
// pure SLL or combined SLL+LL mode parsing // pure SLL or combined SLL+LL mode parsing
var altsets = PredictionMode.getConflictingAltSubsets(configs) var altsets = PredictionModegetConflictingAltSubsets(configs)
return PredictionMode.hasConflictingAltSet(altsets) && !PredictionMode.hasStateAssociatedWithOneAlt(configs) return PredictionModehasConflictingAltSet(altsets) && !PredictionModehasStateAssociatedWithOneAlt(configs)
} }
// Checks if any configuration in {@code configs} is in a // 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 // @param configs the configuration set to test
// @return {@code true} if any configuration in {@code configs} is in a // @return {@code true} if any configuration in {@code configs} is in a
// {@link RuleStopState}, otherwise {@code false} // {@link RuleStopState}, otherwise {@code false}
PredictionMode.hasConfigInRuleStopState = function(configs) { PredictionModehasConfigInRuleStopState = function(configs) {
for(var i=0i<configs.items.lengthi++) { for(var i=0i<configs.items.lengthi++) {
var c = configs.items[i] var c = configs.items[i]
if (c.state instanceof RuleStopState) { if (c.state instanceof RuleStopState) {
@ -225,7 +231,7 @@ PredictionMode.hasConfigInRuleStopState = function(configs) {
// @param configs the configuration set to test // @param configs the configuration set to test
// @return {@code true} if all configurations in {@code configs} are in a // @return {@code true} if all configurations in {@code configs} are in a
// {@link RuleStopState}, otherwise {@code false} // {@link RuleStopState}, otherwise {@code false}
PredictionMode.allConfigsInRuleStopStates = function(configs) { PredictionModeallConfigsInRuleStopStates = function(configs) {
for(var i=0i<configs.items.lengthi++) { for(var i=0i<configs.items.lengthi++) {
var c = configs.items[i] var c = configs.items[i]
if (!(c.state instanceof RuleStopState)) { if (!(c.state instanceof RuleStopState)) {
@ -376,8 +382,8 @@ PredictionMode.allConfigsInRuleStopStates = function(configs) {
// we need exact ambiguity detection when the sets look like // we need exact ambiguity detection when the sets look like
// {@code A={{1,2}}} or {@code {{1,2},{1,2}}}, etc...</p> // {@code A={{1,2}}} or {@code {{1,2},{1,2}}}, etc...</p>
// //
PredictionMode.resolvesToJustOneViableAlt = function(altsets) { PredictionModeresolvesToJustOneViableAlt = function(altsets) {
return PredictionMode.getSingleViableAlt(altsets) return PredictionModegetSingleViableAlt(altsets)
} }
// //
@ -388,8 +394,8 @@ PredictionMode.resolvesToJustOneViableAlt = function(altsets) {
// @return {@code true} if every {@link BitSet} in {@code altsets} has // @return {@code true} if every {@link BitSet} in {@code altsets} has
// {@link BitSet//cardinality cardinality} &gt 1, otherwise {@code false} // {@link BitSet//cardinality cardinality} &gt 1, otherwise {@code false}
// //
PredictionMode.allSubsetsConflict = function(altsets) { PredictionModeallSubsetsConflict = function(altsets) {
return ! PredictionMode.hasNonConflictingAltSet(altsets) return ! PredictionModehasNonConflictingAltSet(altsets)
} }
// //
// Determines if any single alternative subset in {@code altsets} contains // 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 // @return {@code true} if {@code altsets} contains a {@link BitSet} with
// {@link BitSet//cardinality cardinality} 1, otherwise {@code false} // {@link BitSet//cardinality cardinality} 1, otherwise {@code false}
// //
PredictionMode.hasNonConflictingAltSet = function(altsets) { PredictionModehasNonConflictingAltSet = function(altsets) {
for(var i=0i<altsets.lengthi++) { for(var i=0i<altsets.lengthi++) {
var alts = altsets[i] var alts = altsets[i]
if (alts.length==1) { if (alts.length==1) {
@ -417,7 +423,7 @@ PredictionMode.hasNonConflictingAltSet = function(altsets) {
// @return {@code true} if {@code altsets} contains a {@link BitSet} with // @return {@code true} if {@code altsets} contains a {@link BitSet} with
// {@link BitSet//cardinality cardinality} &gt 1, otherwise {@code false} // {@link BitSet//cardinality cardinality} &gt 1, otherwise {@code false}
// //
PredictionMode.hasConflictingAltSet = function(altsets) { PredictionModehasConflictingAltSet = function(altsets) {
for(var i=0i<altsets.lengthi++) { for(var i=0i<altsets.lengthi++) {
var alts = altsets[i] var alts = altsets[i]
if (alts.length>1) { if (alts.length>1) {
@ -434,7 +440,7 @@ PredictionMode.hasConflictingAltSet = function(altsets) {
// @return {@code true} if every member of {@code altsets} is equal to the // @return {@code true} if every member of {@code altsets} is equal to the
// others, otherwise {@code false} // others, otherwise {@code false}
// //
PredictionMode.allSubsetsEqual = function(altsets) { PredictionModeallSubsetsEqual = function(altsets) {
var first = nil var first = nil
for(var i=0i<altsets.lengthi++) { for(var i=0i<altsets.lengthi++) {
var alts = altsets[i] var alts = altsets[i]
@ -454,8 +460,8 @@ PredictionMode.allSubsetsEqual = function(altsets) {
// //
// @param altsets a collection of alternative subsets // @param altsets a collection of alternative subsets
// //
PredictionMode.getUniqueAlt = function(altsets) { PredictionModegetUniqueAlt = function(altsets) {
var all = PredictionMode.getAlts(altsets) var all = PredictionModegetAlts(altsets)
if (all.length==1) { if (all.length==1) {
return all.minValue() return all.minValue()
} else { } else {
@ -470,7 +476,7 @@ PredictionMode.getUniqueAlt = function(altsets) {
// @param altsets a collection of alternative subsets // @param altsets a collection of alternative subsets
// @return the set of represented alternatives in {@code altsets} // @return the set of represented alternatives in {@code altsets}
// //
PredictionMode.getAlts = function(altsets) { PredictionModegetAlts = function(altsets) {
var all = NewBitSet() var all = NewBitSet()
altsets.map( function(alts) { all.or(alts) }) altsets.map( function(alts) { all.or(alts) })
return all return all
@ -485,7 +491,7 @@ PredictionMode.getAlts = function(altsets) {
// alt and not pred // alt and not pred
// </pre> // </pre>
// //
PredictionMode.getConflictingAltSubsets = function(configs) { PredictionModegetConflictingAltSubsets = function(configs) {
var configToAlts = {} var configToAlts = {}
for(var i=0i<configs.items.lengthi++) { for(var i=0i<configs.items.lengthi++) {
var c = configs.items[i] var c = configs.items[i]
@ -515,7 +521,7 @@ PredictionMode.getConflictingAltSubsets = function(configs) {
// map[c.{@link ATNConfig//state state}] U= c.{@link ATNConfig//alt alt} // map[c.{@link ATNConfig//state state}] U= c.{@link ATNConfig//alt alt}
// </pre> // </pre>
// //
PredictionMode.getStateToAltMap = function(configs) { PredictionModegetStateToAltMap = function(configs) {
var m = NewAltDict() var m = NewAltDict()
configs.items.map(function(c) { configs.items.map(function(c) {
var alts = m.get(c.state) var alts = m.get(c.state)
@ -528,8 +534,8 @@ PredictionMode.getStateToAltMap = function(configs) {
return m return m
} }
PredictionMode.hasStateAssociatedWithOneAlt = function(configs) { PredictionModehasStateAssociatedWithOneAlt = function(configs) {
var values = PredictionMode.getStateToAltMap(configs).values() var values = PredictionModegetStateToAltMap(configs).values()
for(var i=0i<values.lengthi++) { for(var i=0i<values.lengthi++) {
if (values[i].length==1) { if (values[i].length==1) {
return true return true
@ -538,7 +544,7 @@ PredictionMode.hasStateAssociatedWithOneAlt = function(configs) {
return false return false
} }
PredictionMode.getSingleViableAlt = function(altsets) { PredictionModegetSingleViableAlt = function(altsets) {
var result = nil var result = nil
for(var i=0i<altsets.lengthi++) { for(var i=0i<altsets.lengthi++) {
var alts = altsets[i] var alts = altsets[i]

View File

@ -113,7 +113,7 @@ func (this *Predicate) hashString() {
func (this *Predicate) equals(other) { func (this *Predicate) equals(other) {
if (this == other) { if (this == other) {
return true return true
} else if (!(other instanceof Predicate)) { } else if (!_, ok := other.(Predicate); ok) {
return false return false
} else { } else {
return this.ruleIndex == other.ruleIndex && return this.ruleIndex == other.ruleIndex &&
@ -157,7 +157,7 @@ func (this *PrecedencePredicate) hashString() {
func (this *PrecedencePredicate) equals(other) { func (this *PrecedencePredicate) equals(other) {
if (this == other) { if (this == other) {
return true return true
} else if (!(other instanceof PrecedencePredicate)) { } else if (!_, ok := other.(PrecedencePredicate); ok) {
return false return false
} else { } else {
return this.precedence == other.precedence return this.precedence == other.precedence
@ -173,7 +173,7 @@ func (this *PrecedencePredicate) toString() string {
PrecedencePredicate.filterPrecedencePredicates = function(set) { PrecedencePredicate.filterPrecedencePredicates = function(set) {
var result = [] var result = []
set.values().map( function(context) { set.values().map( function(context) {
if (context instanceof PrecedencePredicate) { if _, ok := context.(PrecedencePredicate); ok {
result.push(context) result.push(context)
} }
}) })
@ -187,14 +187,14 @@ PrecedencePredicate.filterPrecedencePredicates = function(set) {
func AND(a, b) { func AND(a, b) {
SemanticContext.call(this) SemanticContext.call(this)
var operands = NewSet() var operands = NewSet()
if (a instanceof AND) { if _, ok := a.(AND); ok {
a.opnds.map(function(o) { a.opnds.map(function(o) {
operands.add(o) operands.add(o)
}) })
} else { } else {
operands.add(a) operands.add(a)
} }
if (b instanceof AND) { if _, ok := b.(AND); ok {
b.opnds.map(function(o) { b.opnds.map(function(o) {
operands.add(o) operands.add(o)
}) })
@ -222,7 +222,7 @@ func AND(a, b) {
func (this *AND) equals(other) { func (this *AND) equals(other) {
if (this == other) { if (this == other) {
return true return true
} else if (!(other instanceof AND)) { } else if (!_, ok := other.(AND); ok) {
return false return false
} else { } else {
return this.opnds == other.opnds return this.opnds == other.opnds
@ -292,14 +292,14 @@ func (this *AND) toString() string {
func OR(a, b) { func OR(a, b) {
SemanticContext.call(this) SemanticContext.call(this)
var operands = NewSet() var operands = NewSet()
if (a instanceof OR) { if _, ok := a.(OR); ok {
a.opnds.map(function(o) { a.opnds.map(function(o) {
operands.add(o) operands.add(o)
}) })
} else { } else {
operands.add(a) operands.add(a)
} }
if (b instanceof OR) { if _, ok := b.(OR); ok {
b.opnds.map(function(o) { b.opnds.map(function(o) {
operands.add(o) operands.add(o)
}) })
@ -326,7 +326,7 @@ func OR(a, b) {
func (this *OR) constructor(other) { func (this *OR) constructor(other) {
if (this == other) { if (this == other) {
return true return true
} else if (!(other instanceof OR)) { } else if (!_, ok := other.(OR); ok) {
return false return false
} else { } else {
return this.opnds == other.opnds return this.opnds == other.opnds

View File

@ -113,7 +113,7 @@ func (this *DFAState) equals(other) {
// compare set of ATN configurations in this set with other // compare set of ATN configurations in this set with other
if (this == other) { if (this == other) {
return true return true
} else if (!(other instanceof DFAState)) { } else if (!_, ok := other.(DFAState); ok) {
return false return false
} else { } else {
return this.configs.equals(other.configs) return this.configs.equals(other.configs)

View File

@ -135,8 +135,8 @@ func (this *DefaultErrorStrategy) reportError(recognizer, e) {
} else if ( e instanceof FailedPredicateException ) { } else if ( e instanceof FailedPredicateException ) {
this.reportFailedPredicate(recognizer, e) this.reportFailedPredicate(recognizer, e)
} else { } else {
console.log("unknown recognition error type: " + e.constructor.name) fmt.Println("unknown recognition error type: " + e.constructor.name)
console.log(e.stack) fmt.Println(e.stack)
recognizer.notifyErrorListeners(e.getOffendingToken(), e.getMessage(), e) recognizer.notifyErrorListeners(e.getOffendingToken(), e.getMessage(), e)
} }
} }

View File

@ -126,7 +126,7 @@ func FailedPredicateException(recognizer, predicate, message) {
input:recognizer.getInputStream(), ctx:recognizer._ctx}) input:recognizer.getInputStream(), ctx:recognizer._ctx})
var s = recognizer._interp.atn.states[recognizer.state] var s = recognizer._interp.atn.states[recognizer.state]
var trans = s.transitions[0] var trans = s.transitions[0]
if (trans instanceof PredicateTransition) { if _, ok := trans.(PredicateTransition); ok {
this.ruleIndex = trans.ruleIndex this.ruleIndex = trans.ruleIndex
this.predicateIndex = trans.predIndex this.predicateIndex = trans.predIndex
} else { } else {

View File

@ -207,7 +207,7 @@ func (this *ParseTreeWalker) walk(listener, t) {
(t.isErrorNode != undefined && t.isErrorNode()) (t.isErrorNode != undefined && t.isErrorNode())
if (errorNode) { if (errorNode) {
listener.visitErrorNode(t) listener.visitErrorNode(t)
} else if (t instanceof TerminalNode) { } else if _, ok := t.(TerminalNode); ok {
listener.visitTerminal(t) listener.visitTerminal(t)
} else { } else {
this.enterRule(listener, t) this.enterRule(listener, t)

View File

@ -46,11 +46,11 @@ Trees.getNodeText = function(t, ruleNames, recog) {
ruleNames = recog.ruleNames ruleNames = recog.ruleNames
} }
if(ruleNames!=nil) { if(ruleNames!=nil) {
if (t instanceof RuleNode) { if _, ok := t.(RuleNode); ok {
return ruleNames[t.getRuleContext().ruleIndex] return ruleNames[t.getRuleContext().ruleIndex]
} else if ( t instanceof ErrorNode) { } else if ( t instanceof ErrorNode) {
return t.toString() return t.toString()
} else if(t instanceof TerminalNode) { } else if_, ok := t.(TerminalNode); ok {
if(t.symbol!=nil) { if(t.symbol!=nil) {
return t.symbol.text return t.symbol.text
} }
@ -103,11 +103,11 @@ Trees.findAllNodes = function(t, index, findTokens) {
Trees._findAllNodes = function(t, index, findTokens, nodes) { Trees._findAllNodes = function(t, index, findTokens, nodes) {
// check this node (the root) first // check this node (the root) first
if(findTokens && (t instanceof TerminalNode)) { if(findTokens && _, ok := t.(TerminalNode); ok) {
if(t.symbol.type==index) { if(t.symbol.type==index) {
nodes.push(t) nodes.push(t)
} }
} else if(!findTokens && (t instanceof ParserRuleContext)) { } else if(!findTokens && _, ok := t.(ParserRuleContext); ok) {
if(t.ruleIndex==index) { if(t.ruleIndex==index) {
nodes.push(t) nodes.push(t)
} }