diff --git a/runtime/Go/src/antlr4/ATN.go b/runtime/Go/src/antlr4/ATN.go
index a5e01cd62..e629726b8 100644
--- a/runtime/Go/src/antlr4/ATN.go
+++ b/runtime/Go/src/antlr4/ATN.go
@@ -1,105 +1,106 @@
package antlr4
type ATN struct {
- grammarType int
- maxTokenType int
- states []IATNState
- decisionToState []*DecisionState
- ruleToStartState []*RuleStartState
- ruleToStopState []*RuleStopState
- modeNameToStartState map[string]*TokensStartState
- modeToStartState []*TokensStartState
- ruleToTokenType []int
- lexerActions []ILexerAction
+ DecisionToState []*DecisionState
+
+ grammarType int
+ maxTokenType int
+ states []IATNState
+ ruleToStartState []*RuleStartState
+ ruleToStopState []*RuleStopState
+ modeNameToStartState map[string]*TokensStartState
+ modeToStartState []*TokensStartState
+ ruleToTokenType []int
+ lexerActions []ILexerAction
}
func NewATN(grammarType int, maxTokenType int) *ATN {
- atn := new(ATN)
+ atn := new(ATN)
- // Used for runtime deserialization of ATNs from strings///
- // The type of the ATN.
- atn.grammarType = grammarType
- // The maximum value for any symbol recognized by a transition in the ATN.
- atn.maxTokenType = maxTokenType
- atn.states = make([]IATNState,0)
- // Each subrule/rule is a decision point and we must track them so we
- // can go back later and build DFA predictors for them. This includes
- // all the rules, subrules, optional blocks, ()+, ()* etc...
- atn.decisionToState = make([]*DecisionState, 0)
- // Maps from rule index to starting state number.
- atn.ruleToStartState = make([]*RuleStartState, 0)
- // Maps from rule index to stop state number.
- atn.ruleToStopState = nil
- atn.modeNameToStartState = make( map[string]*TokensStartState )
- // For lexer ATNs, atn.maps the rule index to the resulting token type.
- // For parser ATNs, atn.maps the rule index to the generated bypass token
- // type if the
- // {@link ATNDeserializationOptions//isGenerateRuleBypassTransitions}
- // deserialization option was specified otherwise, atn.is {@code nil}.
- atn.ruleToTokenType = nil
- // For lexer ATNs, atn.is an array of {@link LexerAction} objects which may
- // be referenced by action transitions in the ATN.
- atn.lexerActions = nil
- atn.modeToStartState = make([]*TokensStartState, 0)
+ // Used for runtime deserialization of ATNs from strings///
+ // The type of the ATN.
+ atn.grammarType = grammarType
+ // The maximum value for any symbol recognized by a transition in the ATN.
+ atn.maxTokenType = maxTokenType
+ atn.states = make([]IATNState, 0)
+ // Each subrule/rule is a decision point and we must track them so we
+ // can go back later and build DFA predictors for them. This includes
+ // all the rules, subrules, optional blocks, ()+, ()* etc...
+ atn.DecisionToState = make([]*DecisionState, 0)
+ // Maps from rule index to starting state number.
+ atn.ruleToStartState = make([]*RuleStartState, 0)
+ // Maps from rule index to stop state number.
+ atn.ruleToStopState = nil
+ atn.modeNameToStartState = make(map[string]*TokensStartState)
+ // For lexer ATNs, atn.maps the rule index to the resulting token type.
+ // For parser ATNs, atn.maps the rule index to the generated bypass token
+ // type if the
+ // {@link ATNDeserializationOptions//isGenerateRuleBypassTransitions}
+ // deserialization option was specified otherwise, atn.is {@code nil}.
+ atn.ruleToTokenType = nil
+ // For lexer ATNs, atn.is an array of {@link LexerAction} objects which may
+ // be referenced by action transitions in the ATN.
+ atn.lexerActions = nil
+ atn.modeToStartState = make([]*TokensStartState, 0)
- return atn
+ return atn
}
-
+
// Compute the set of valid tokens that can occur starting in state {@code s}.
// If {@code ctx} is nil, the set of tokens will not include what can follow
// the rule surrounding {@code s}. In other words, the set will be
// restricted to tokens reachable staying within {@code s}'s rule.
func (this *ATN) nextTokensInContext(s IATNState, ctx IRuleContext) *IntervalSet {
- var anal = NewLL1Analyzer(this)
- return anal.LOOK(s, nil, ctx)
+ var anal = NewLL1Analyzer(this)
+ return anal.LOOK(s, nil, ctx)
}
// Compute the set of valid tokens that can occur starting in {@code s} and
// staying in same rule. {@link Token//EPSILON} is in set if we reach end of
// rule.
func (this *ATN) nextTokensNoContext(s IATNState) *IntervalSet {
- if (s.getNextTokenWithinRule() != nil ) {
- return s.getNextTokenWithinRule()
- }
- s.setNextTokenWithinRule( this.nextTokensInContext(s, nil) )
- s.getNextTokenWithinRule().readOnly = true
- return s.getNextTokenWithinRule()
+ if s.getNextTokenWithinRule() != nil {
+ return s.getNextTokenWithinRule()
+ }
+ s.setNextTokenWithinRule(this.nextTokensInContext(s, nil))
+ s.getNextTokenWithinRule().readOnly = true
+ return s.getNextTokenWithinRule()
}
func (this *ATN) nextTokens(s IATNState, ctx IRuleContext) *IntervalSet {
- if ( ctx==nil ) {
- return this.nextTokensNoContext(s)
- } else {
- return this.nextTokensInContext(s, ctx)
- }
+ if ctx == nil {
+ return this.nextTokensNoContext(s)
+ } else {
+ return this.nextTokensInContext(s, ctx)
+ }
}
-func (this *ATN) addState( state IATNState ) {
- if ( state != nil ) {
- state.setATN(this)
- state.setStateNumber(len(this.states))
- }
- this.states = append(this.states, state)
+func (this *ATN) addState(state IATNState) {
+ if state != nil {
+ state.setATN(this)
+ state.setStateNumber(len(this.states))
+ }
+ this.states = append(this.states, state)
}
-func (this *ATN) removeState( state IATNState ) {
- this.states[state.getStateNumber()] = nil // just free mem, don't shift states in list
+func (this *ATN) removeState(state IATNState) {
+ this.states[state.getStateNumber()] = nil // just free mem, don't shift states in list
}
-func (this *ATN) defineDecisionState( s *DecisionState ) int {
- this.decisionToState = append( this.decisionToState, s)
- s.decision = len(this.decisionToState)-1
- return s.decision
+func (this *ATN) defineDecisionState(s *DecisionState) int {
+ this.DecisionToState = append(this.DecisionToState, s)
+ s.decision = len(this.DecisionToState) - 1
+ return s.decision
}
-func (this *ATN) getDecisionState( decision int) *DecisionState {
- if (len(this.decisionToState)==0) {
- return nil
- } else {
- return this.decisionToState[decision]
- }
+func (this *ATN) getDecisionState(decision int) *DecisionState {
+ if len(this.DecisionToState) == 0 {
+ return nil
+ } else {
+ return this.DecisionToState[decision]
+ }
}
// Computes the set of input symbols which could follow ATN state number
@@ -122,31 +123,30 @@ func (this *ATN) getDecisionState( decision int) *DecisionState {
//var Token = require('./../Token').Token
-func (this *ATN) getExpectedTokens( stateNumber int, ctx IRuleContext ) *IntervalSet {
- if ( stateNumber < 0 || stateNumber >= len(this.states) ) {
- panic("Invalid state number.")
- }
- var s = this.states[stateNumber]
- var following = this.nextTokens(s, nil)
- if (!following.contains(TokenEpsilon)) {
- return following
- }
- var expected = NewIntervalSet()
- expected.addSet(following)
- expected.removeOne(TokenEpsilon)
- for (ctx != nil && ctx.getInvokingState() >= 0 && following.contains(TokenEpsilon)) {
- var invokingState = this.states[ctx.getInvokingState()]
- var rt = invokingState.getTransitions()[0]
- following = this.nextTokens(rt.(*RuleTransition).followState, nil)
- expected.addSet(following)
- expected.removeOne(TokenEpsilon)
- ctx = ctx.getParent().(IRuleContext)
- }
- if (following.contains(TokenEpsilon)) {
- expected.addOne(TokenEOF)
- }
- return expected
+func (this *ATN) getExpectedTokens(stateNumber int, ctx IRuleContext) *IntervalSet {
+ if stateNumber < 0 || stateNumber >= len(this.states) {
+ panic("Invalid state number.")
+ }
+ var s = this.states[stateNumber]
+ var following = this.nextTokens(s, nil)
+ if !following.contains(TokenEpsilon) {
+ return following
+ }
+ var expected = NewIntervalSet()
+ expected.addSet(following)
+ expected.removeOne(TokenEpsilon)
+ for ctx != nil && ctx.getInvokingState() >= 0 && following.contains(TokenEpsilon) {
+ var invokingState = this.states[ctx.getInvokingState()]
+ var rt = invokingState.getTransitions()[0]
+ following = this.nextTokens(rt.(*RuleTransition).followState, nil)
+ expected.addSet(following)
+ expected.removeOne(TokenEpsilon)
+ ctx = ctx.getParent().(IRuleContext)
+ }
+ if following.contains(TokenEpsilon) {
+ expected.addOne(TokenEOF)
+ }
+ return expected
}
var ATNINVALID_ALT_NUMBER = 0
-
diff --git a/runtime/Go/src/antlr4/ATNConfig.go b/runtime/Go/src/antlr4/ATNConfig.go
index 6fc2b64c9..7f7651e19 100644
--- a/runtime/Go/src/antlr4/ATNConfig.go
+++ b/runtime/Go/src/antlr4/ATNConfig.go
@@ -1,8 +1,8 @@
package antlr4
import (
- "reflect"
"fmt"
+ "reflect"
"strconv"
)
@@ -33,25 +33,25 @@ type IATNConfig interface {
type ATNConfig struct {
precedenceFilterSuppressed bool
- state IATNState
- alt int
- context IPredictionContext
- semanticContext SemanticContext
- reachesIntoOuterContext int
+ state IATNState
+ alt int
+ context IPredictionContext
+ semanticContext SemanticContext
+ reachesIntoOuterContext int
}
func NewATNConfig7(old *ATNConfig) *ATNConfig { // dup
a := new(ATNConfig)
- a.state = old.state;
- a.alt = old.alt;
- a.context = old.context;
- a.semanticContext = old.semanticContext;
- a.reachesIntoOuterContext = old.reachesIntoOuterContext;
+ a.state = old.state
+ a.alt = old.alt
+ a.context = old.context
+ a.semanticContext = old.semanticContext
+ a.reachesIntoOuterContext = old.reachesIntoOuterContext
return a
}
func NewATNConfig6(state IATNState, alt int, context IPredictionContext) *ATNConfig {
- return NewATNConfig5(state, alt, context, SemanticContextNONE);
+ return NewATNConfig5(state, alt, context, SemanticContextNONE)
}
func NewATNConfig5(state IATNState, alt int, context IPredictionContext, semanticContext SemanticContext) *ATNConfig {
@@ -61,23 +61,23 @@ func NewATNConfig5(state IATNState, alt int, context IPredictionContext, semanti
return a
}
-func NewATNConfig4(c IATNConfig , state IATNState) *ATNConfig {
- return NewATNConfig(c, state, c.getContext(), c.getSemanticContext());
+func NewATNConfig4(c IATNConfig, state IATNState) *ATNConfig {
+ return NewATNConfig(c, state, c.getContext(), c.getSemanticContext())
}
-func NewATNConfig3(c IATNConfig , state IATNState, semanticContext SemanticContext) *ATNConfig {
- return NewATNConfig(c, state, c.getContext(), semanticContext);
+func NewATNConfig3(c IATNConfig, state IATNState, semanticContext SemanticContext) *ATNConfig {
+ return NewATNConfig(c, state, c.getContext(), semanticContext)
}
-func NewATNConfig2(c IATNConfig , semanticContext SemanticContext) *ATNConfig {
- return NewATNConfig(c, c.getState(), c.getContext(), semanticContext);
+func NewATNConfig2(c IATNConfig, semanticContext SemanticContext) *ATNConfig {
+ return NewATNConfig(c, c.getState(), c.getContext(), semanticContext)
}
-func NewATNConfig1(c IATNConfig , state IATNState, context IPredictionContext) *ATNConfig {
- return NewATNConfig(c, state, context, c.getSemanticContext());
+func NewATNConfig1(c IATNConfig, state IATNState, context IPredictionContext) *ATNConfig {
+ return NewATNConfig(c, state, context, c.getSemanticContext())
}
-func NewATNConfig(c IATNConfig , state IATNState, context IPredictionContext, semanticContext SemanticContext) *ATNConfig {
+func NewATNConfig(c IATNConfig, state IATNState, context IPredictionContext, semanticContext SemanticContext) *ATNConfig {
a := new(ATNConfig)
a.InitATNConfig(c, state, context, semanticContext)
@@ -119,23 +119,22 @@ func (this *ATNConfig) setReachesIntoOuterContext(v int) {
this.reachesIntoOuterContext = v
}
+func (a *ATNConfig) InitATNConfig(c IATNConfig, state IATNState, context IPredictionContext, semanticContext SemanticContext) {
-func (a *ATNConfig) InitATNConfig(c IATNConfig, state IATNState, context IPredictionContext, semanticContext SemanticContext) {
-
- a.state = state;
- a.alt = c.getAlt();
- a.context = context;
- a.semanticContext = semanticContext;
- a.reachesIntoOuterContext = c.getReachesIntoOuterContext();
+ a.state = state
+ a.alt = c.getAlt()
+ a.context = context
+ a.semanticContext = semanticContext
+ a.reachesIntoOuterContext = c.getReachesIntoOuterContext()
}
func (a *ATNConfig) InitATNConfig2(state IATNState, alt int, context IPredictionContext, semanticContext SemanticContext) {
- a.state = state;
- a.alt = alt;
- a.context = context;
- a.semanticContext = semanticContext;
+ a.state = state
+ a.alt = alt
+ a.context = context
+ a.semanticContext = semanticContext
}
@@ -144,57 +143,55 @@ func (a *ATNConfig) InitATNConfig2(state IATNState, alt int, context IPrediction
// syntactic/semantic contexts are the same.
///
func (this *ATNConfig) equals(other interface{}) bool {
- if (this == other) {
- return true
- } else if _, ok := other.(*ATNConfig); !ok {
- return false
- } else {
- return reflect.DeepEqual(this, other)
- }
+ if this == other {
+ return true
+ } else if _, ok := other.(*ATNConfig); !ok {
+ return false
+ } else {
+ return reflect.DeepEqual(this, other)
+ }
}
func (this *ATNConfig) shortHashString() string {
- return "" + strconv.Itoa(this.state.getStateNumber()) + "/" + strconv.Itoa(this.alt) + "/" + this.semanticContext.toString()
+ return "" + strconv.Itoa(this.state.getStateNumber()) + "/" + strconv.Itoa(this.alt) + "/" + this.semanticContext.toString()
}
func (this *ATNConfig) hashString() string {
var c string
- if (this.context == nil){
+ if this.context == nil {
c = ""
} else {
c = this.context.hashString()
}
- return "" + strconv.Itoa(this.state.getStateNumber()) + "/" + strconv.Itoa(this.alt) + "/" + c + "/" + this.semanticContext.toString()
+ return "" + strconv.Itoa(this.state.getStateNumber()) + "/" + strconv.Itoa(this.alt) + "/" + c + "/" + this.semanticContext.toString()
}
func (this *ATNConfig) toString() string {
var a string
- if (this.context != nil){
+ if this.context != nil {
a = ",[" + fmt.Sprint(this.context) + "]"
}
var b string
- if (this.semanticContext != SemanticContextNONE){
+ if this.semanticContext != SemanticContextNONE {
b = ("," + fmt.Sprint(this.semanticContext))
}
var c string
- if (this.reachesIntoOuterContext > 0){
+ if this.reachesIntoOuterContext > 0 {
c = ",up=" + fmt.Sprint(this.reachesIntoOuterContext)
}
- return "(" + fmt.Sprint(this.state) + "," + strconv.Itoa(this.alt) + a + b + c + ")"
+ return "(" + fmt.Sprint(this.state) + "," + strconv.Itoa(this.alt) + a + b + c + ")"
}
-
-
type LexerATNConfig struct {
ATNConfig
- lexerActionExecutor *LexerActionExecutor
+ lexerActionExecutor *LexerActionExecutor
passedThroughNonGreedyDecision bool
}
@@ -219,7 +216,7 @@ func NewLexerATNConfig5(state IATNState, alt int, context IPredictionContext, le
return this
}
-func NewLexerATNConfig4(c *LexerATNConfig, state IATNState) *LexerATNConfig {
+func NewLexerATNConfig4(c *LexerATNConfig, state IATNState) *LexerATNConfig {
this := new(LexerATNConfig)
@@ -239,7 +236,7 @@ func NewLexerATNConfig3(c *LexerATNConfig, state IATNState, lexerActionExecutor
return this
}
-func NewLexerATNConfig2(c *LexerATNConfig, state IATNState, context IPredictionContext) *LexerATNConfig {
+func NewLexerATNConfig2(c *LexerATNConfig, state IATNState, context IPredictionContext) *LexerATNConfig {
this := new(LexerATNConfig)
@@ -249,21 +246,19 @@ func NewLexerATNConfig2(c *LexerATNConfig, state IATNState, context IPrediction
return this
}
-
-func NewLexerATNConfig1( state IATNState, alt int, context IPredictionContext) *LexerATNConfig {
+func NewLexerATNConfig1(state IATNState, alt int, context IPredictionContext) *LexerATNConfig {
this := new(LexerATNConfig)
// c IATNConfig , state IATNState, context IPredictionContext, semanticContext SemanticContext
this.InitATNConfig2(state, alt, context, SemanticContextNONE)
- this.lexerActionExecutor = nil
- this.passedThroughNonGreedyDecision = false
+ this.lexerActionExecutor = nil
+ this.passedThroughNonGreedyDecision = false
- return this
+ return this
}
-
func (this *LexerATNConfig) hashString() string {
var f string
@@ -273,7 +268,7 @@ func (this *LexerATNConfig) hashString() string {
f = "0"
}
- return "" + strconv.Itoa(this.state.getStateNumber()) + strconv.Itoa(this.alt) + fmt.Sprint(this.context) +
+ return "" + strconv.Itoa(this.state.getStateNumber()) + strconv.Itoa(this.alt) + fmt.Sprint(this.context) +
fmt.Sprint(this.semanticContext) + f + fmt.Sprint(this.lexerActionExecutor)
}
@@ -281,27 +276,27 @@ func (this *LexerATNConfig) equals(other interface{}) bool {
othert, ok := other.(*LexerATNConfig)
- if (this == other) {
- return true
- } else if !ok {
- return false
- } else if (this.passedThroughNonGreedyDecision != othert.passedThroughNonGreedyDecision) {
- return false
- }
+ if this == other {
+ return true
+ } else if !ok {
+ return false
+ } else if this.passedThroughNonGreedyDecision != othert.passedThroughNonGreedyDecision {
+ return false
+ }
var b bool
- if (this.lexerActionExecutor != nil){
- b = !this.lexerActionExecutor.equals(othert.lexerActionExecutor)
+ if this.lexerActionExecutor != nil {
+ b = !this.lexerActionExecutor.equals(othert.lexerActionExecutor)
} else {
b = othert.lexerActionExecutor != nil
}
- if (b) {
- return false
- } else {
+ if b {
+ return false
+ } else {
panic("Not implemented")
-// return ATNConfig.prototype.equals.call(this, other)
- }
+ // return ATNConfig.prototype.equals.call(this, other)
+ }
}
func checkNonGreedyDecision(source *LexerATNConfig, target IATNState) bool {
diff --git a/runtime/Go/src/antlr4/ATNConfigSet.go b/runtime/Go/src/antlr4/ATNConfigSet.go
index 45d1f5add..76956645b 100644
--- a/runtime/Go/src/antlr4/ATNConfigSet.go
+++ b/runtime/Go/src/antlr4/ATNConfigSet.go
@@ -1,4 +1,5 @@
package antlr4
+
import (
"fmt"
)
@@ -14,27 +15,27 @@ func hashATNConfig(c interface{}) string {
}
func equalATNConfigs(a, b interface{}) bool {
- if ( a==b ) {
+ if a == b {
return true
}
- if ( a==nil || b==nil ) {
+ if a == nil || b == nil {
return false
}
- return a.(*ATNConfig).state.getStateNumber()==b.(*ATNConfig).state.getStateNumber() &&
- a.(*ATNConfig).alt==b.(*ATNConfig).alt &&
+ return a.(*ATNConfig).state.getStateNumber() == b.(*ATNConfig).state.getStateNumber() &&
+ a.(*ATNConfig).alt == b.(*ATNConfig).alt &&
a.(*ATNConfig).semanticContext.equals(b.(*ATNConfig).semanticContext)
}
type ATNConfigSet struct {
- readOnly bool
- fullCtx bool
- configLookup *Set
- conflictingAlts *BitSet
- cachedHashString string
- hasSemanticContext bool
+ readOnly bool
+ fullCtx bool
+ configLookup *Set
+ conflictingAlts *BitSet
+ cachedHashString string
+ hasSemanticContext bool
dipsIntoOuterContext bool
- configs []IATNConfig
- uniqueAlt int
+ configs []IATNConfig
+ uniqueAlt int
}
func NewATNConfigSet(fullCtx bool) *ATNConfigSet {
@@ -98,19 +99,19 @@ func (a *ATNConfigSet) InitATNConfigSet(fullCtx bool) {
// /
func (this *ATNConfigSet) add(config IATNConfig, mergeCache *DoubleDict) bool {
- if (this.readOnly) {
+ if this.readOnly {
panic("This set is readonly")
}
- if (config.getSemanticContext() != SemanticContextNONE) {
+ if config.getSemanticContext() != SemanticContextNONE {
this.hasSemanticContext = true
}
- if (config.getReachesIntoOuterContext() > 0) {
+ if config.getReachesIntoOuterContext() > 0 {
this.dipsIntoOuterContext = true
}
var existing = this.configLookup.add(config).(IATNConfig)
- if (existing == config) {
+ if existing == config {
this.cachedHashString = "-1"
- this.configs = append( this.configs, config )// track order here
+ this.configs = append(this.configs, config) // track order here
return true
}
// a previous (s,i,pi,_), merge with it and save result
@@ -119,17 +120,17 @@ func (this *ATNConfigSet) add(config IATNConfig, mergeCache *DoubleDict) bool {
// no need to check for existing.context, config.context in cache
// since only way to create Newgraphs is "call rule" and here. We
// cache at both places.
- existing.setReachesIntoOuterContext( intMax( existing.getReachesIntoOuterContext(), config.getReachesIntoOuterContext()) )
+ existing.setReachesIntoOuterContext(intMax(existing.getReachesIntoOuterContext(), config.getReachesIntoOuterContext()))
// make sure to preserve the precedence filter suppression during the merge
- if (config.getPrecedenceFilterSuppressed()) {
- existing.setPrecedenceFilterSuppressed( true )
+ if config.getPrecedenceFilterSuppressed() {
+ existing.setPrecedenceFilterSuppressed(true)
}
- existing.setContext( merged )// replace context no need to alt mapping
+ existing.setContext(merged) // replace context no need to alt mapping
return true
}
func (this *ATNConfigSet) getStates() *Set {
- var states = NewSet(nil,nil)
+ var states = NewSet(nil, nil)
for i := 0; i < len(this.configs); i++ {
states.add(this.configs[i].getState())
}
@@ -137,10 +138,10 @@ func (this *ATNConfigSet) getStates() *Set {
}
func (this *ATNConfigSet) getPredicates() []SemanticContext {
- var preds = make([]SemanticContext,0)
+ var preds = make([]SemanticContext, 0)
for i := 0; i < len(this.configs); i++ {
c := this.configs[i].getSemanticContext()
- if (c != SemanticContextNONE) {
+ if c != SemanticContextNONE {
preds = append(preds, c)
}
}
@@ -152,10 +153,10 @@ func (this *ATNConfigSet) getItems() []IATNConfig {
}
func (this *ATNConfigSet) optimizeConfigs(interpreter *ATNSimulator) {
- if (this.readOnly) {
+ if this.readOnly {
panic("This set is readonly")
}
- if (this.configLookup.length() == 0) {
+ if this.configLookup.length() == 0 {
return
}
for i := 0; i < len(this.configs); i++ {
@@ -164,15 +165,15 @@ func (this *ATNConfigSet) optimizeConfigs(interpreter *ATNSimulator) {
}
}
-func (this *ATNConfigSet) addAll(coll []*ATNConfig) bool{
+func (this *ATNConfigSet) addAll(coll []*ATNConfig) bool {
for i := 0; i < len(coll); i++ {
- this.add(coll[i],nil)
+ this.add(coll[i], nil)
}
return false
}
func (this *ATNConfigSet) equals(other interface{}) bool {
- if (this == other) {
+ if this == other {
return true
} else if _, ok := other.(*ATNConfigSet); !ok {
return false
@@ -181,17 +182,17 @@ func (this *ATNConfigSet) equals(other interface{}) bool {
other2 := other.(*ATNConfigSet)
return this.configs != nil &&
-// this.configs.equals(other2.configs) && // TODO is this necessary?
- this.fullCtx == other2.fullCtx &&
- this.uniqueAlt == other2.uniqueAlt &&
- this.conflictingAlts == other2.conflictingAlts &&
- this.hasSemanticContext == other2.hasSemanticContext &&
- this.dipsIntoOuterContext == other2.dipsIntoOuterContext
+ // this.configs.equals(other2.configs) && // TODO is this necessary?
+ this.fullCtx == other2.fullCtx &&
+ this.uniqueAlt == other2.uniqueAlt &&
+ this.conflictingAlts == other2.conflictingAlts &&
+ this.hasSemanticContext == other2.hasSemanticContext &&
+ this.dipsIntoOuterContext == other2.dipsIntoOuterContext
}
func (this *ATNConfigSet) hashString() string {
- if (this.readOnly) {
- if (this.cachedHashString == "-1") {
+ if this.readOnly {
+ if this.cachedHashString == "-1" {
this.cachedHashString = this.hashConfigs()
}
return this.cachedHashString
@@ -216,22 +217,22 @@ func (this *ATNConfigSet) isEmpty() bool {
return len(this.configs) == 0
}
-func (this *ATNConfigSet) contains(item *ATNConfig ) bool {
- if (this.configLookup == nil) {
+func (this *ATNConfigSet) contains(item *ATNConfig) bool {
+ if this.configLookup == nil {
panic("This method is not implemented for readonly sets.")
}
return this.configLookup.contains(item)
}
-func (this *ATNConfigSet) containsFast(item *ATNConfig ) bool {
- if (this.configLookup == nil) {
+func (this *ATNConfigSet) containsFast(item *ATNConfig) bool {
+ if this.configLookup == nil {
panic("This method is not implemented for readonly sets.")
}
return this.configLookup.contains(item) // TODO containsFast is not implemented for Set
}
func (this *ATNConfigSet) clear() {
- if (this.readOnly) {
+ if this.readOnly {
panic("This set is readonly")
}
this.configs = make([]IATNConfig, 0)
@@ -241,7 +242,7 @@ func (this *ATNConfigSet) clear() {
func (this *ATNConfigSet) setReadonly(readOnly bool) {
this.readOnly = readOnly
- if (readOnly) {
+ if readOnly {
this.configLookup = nil // can't mod, no need for lookup cache
}
}
@@ -249,18 +250,17 @@ func (this *ATNConfigSet) setReadonly(readOnly bool) {
func (this *ATNConfigSet) toString() string {
panic("not implemented")
return ""
-// return Utils.arrayToString(this.configs) +
-// (this.hasSemanticContext ? ",hasSemanticContext=" + this.hasSemanticContext : "") +
-// (this.uniqueAlt != ATN.INVALID_ALT_NUMBER ? ",uniqueAlt=" + this.uniqueAlt : "") +
-// (this.conflictingAlts != nil ? ",conflictingAlts=" + this.conflictingAlts : "") +
-// (this.dipsIntoOuterContext ? ",dipsIntoOuterContext" : "")
+ // return Utils.arrayToString(this.configs) +
+ // (this.hasSemanticContext ? ",hasSemanticContext=" + this.hasSemanticContext : "") +
+ // (this.uniqueAlt != ATN.INVALID_ALT_NUMBER ? ",uniqueAlt=" + this.uniqueAlt : "") +
+ // (this.conflictingAlts != nil ? ",conflictingAlts=" + this.conflictingAlts : "") +
+ // (this.dipsIntoOuterContext ? ",dipsIntoOuterContext" : "")
}
type OrderedATNConfigSet struct {
*ATNConfigSet
}
-
func NewOrderedATNConfigSet() *OrderedATNConfigSet {
this := new(OrderedATNConfigSet)
@@ -270,6 +270,3 @@ func NewOrderedATNConfigSet() *OrderedATNConfigSet {
return this
}
-
-
-
diff --git a/runtime/Go/src/antlr4/ATNDeserializationOptions.go b/runtime/Go/src/antlr4/ATNDeserializationOptions.go
index 8bf4b4852..e021cfb20 100644
--- a/runtime/Go/src/antlr4/ATNDeserializationOptions.go
+++ b/runtime/Go/src/antlr4/ATNDeserializationOptions.go
@@ -1,23 +1,21 @@
package antlr4
type ATNDeserializationOptions struct {
- readOnly bool
- verifyATN bool
+ readOnly bool
+ verifyATN bool
generateRuleBypassTransitions bool
}
func NewATNDeserializationOptions(copyFrom *ATNDeserializationOptions) *ATNDeserializationOptions {
o := new(ATNDeserializationOptions)
- if (copyFrom != nil){
+ if copyFrom != nil {
o.readOnly = copyFrom.readOnly
o.verifyATN = copyFrom.verifyATN
o.generateRuleBypassTransitions = copyFrom.generateRuleBypassTransitions
}
- return o
+ return o
}
-var ATNDeserializationOptionsdefaultOptions = &ATNDeserializationOptions{true,false,false}
-
-
+var ATNDeserializationOptionsdefaultOptions = &ATNDeserializationOptions{true, false, false}
diff --git a/runtime/Go/src/antlr4/ATNDeserializer.go b/runtime/Go/src/antlr4/ATNDeserializer.go
index a4c450f02..a33ed5073 100644
--- a/runtime/Go/src/antlr4/ATNDeserializer.go
+++ b/runtime/Go/src/antlr4/ATNDeserializer.go
@@ -1,9 +1,10 @@
package antlr4
+
import (
- "strings"
- "fmt"
- "encoding/hex"
- "strconv"
+ "encoding/hex"
+ "fmt"
+ "strconv"
+ "strings"
)
// This is the earliest supported serialized UUID.
@@ -12,43 +13,41 @@ var BASE_SERIALIZED_UUID = "AADB8D7E-AEEF-4415-AD2B-8204D6CF042E"
// This list contains all of the currently supported UUIDs, ordered by when
// the feature first appeared in this branch.
-var SUPPORTED_UUIDS = []string{ BASE_SERIALIZED_UUID }
+var SUPPORTED_UUIDS = []string{BASE_SERIALIZED_UUID}
var SERIALIZED_VERSION = 3
// This is the current serialized UUID.
var SERIALIZED_UUID = BASE_SERIALIZED_UUID
-func initIntArray( length, value int) []int {
+func initIntArray(length, value int) []int {
var tmp = make([]int, length)
- for i := range tmp {
- tmp[i] = value
- }
+ for i := range tmp {
+ tmp[i] = value
+ }
return tmp
}
type ATNDeserializer struct {
-
- deserializationOptions *ATNDeserializationOptions
- data []rune
- pos int
- uuid string
-
+ deserializationOptions *ATNDeserializationOptions
+ data []rune
+ pos int
+ uuid string
}
-func NewATNDeserializer (options *ATNDeserializationOptions) *ATNDeserializer {
-
- if ( options == nil ) {
- options = ATNDeserializationOptionsdefaultOptions
- }
+func NewATNDeserializer(options *ATNDeserializationOptions) *ATNDeserializer {
- this := new(ATNDeserializer)
+ if options == nil {
+ options = ATNDeserializationOptionsdefaultOptions
+ }
- this.deserializationOptions = options
-
- return this
+ this := new(ATNDeserializer)
+
+ this.deserializationOptions = options
+
+ return this
}
// Determines if a particular serialized representation of an ATN supports
@@ -64,411 +63,411 @@ func NewATNDeserializer (options *ATNDeserializationOptions) *ATNDeserializer {
// introduced otherwise, {@code false}.
func stringInSlice(a string, list []string) int {
- for i, b := range list {
- if b == a {
- return i
- }
- }
- return -1
+ for i, b := range list {
+ if b == a {
+ return i
+ }
+ }
+ return -1
}
func (this *ATNDeserializer) isFeatureSupported(feature, actualUuid string) bool {
- var idx1 = stringInSlice( feature, SUPPORTED_UUIDS )
- if (idx1 < 0) {
- return false
- }
- var idx2 = stringInSlice( actualUuid, SUPPORTED_UUIDS )
- return idx2 >= idx1
+ var idx1 = stringInSlice(feature, SUPPORTED_UUIDS)
+ if idx1 < 0 {
+ return false
+ }
+ var idx2 = stringInSlice(actualUuid, SUPPORTED_UUIDS)
+ return idx2 >= idx1
}
-func (this *ATNDeserializer) deserialize(data []rune) *ATN {
+func (this *ATNDeserializer) Deserialize(data []rune) *ATN {
- this.reset(data)
- this.checkVersion()
- this.checkUUID()
- var atn = this.readATN()
- this.readStates(atn)
- this.readRules(atn)
- this.readModes(atn)
- var sets = this.readSets(atn)
- this.readEdges(atn, sets)
- this.readDecisions(atn)
- this.readLexerActions(atn)
- this.markPrecedenceDecisions(atn)
- this.verifyATN(atn)
- if (this.deserializationOptions.generateRuleBypassTransitions && atn.grammarType == ATNTypeParser ) {
- this.generateRuleBypassTransitions(atn)
- // re-verify after modification
- this.verifyATN(atn)
- }
- return atn
+ this.reset(data)
+ this.checkVersion()
+ this.checkUUID()
+ var atn = this.readATN()
+ this.readStates(atn)
+ this.readRules(atn)
+ this.readModes(atn)
+ var sets = this.readSets(atn)
+ this.readEdges(atn, sets)
+ this.readDecisions(atn)
+ this.readLexerActions(atn)
+ this.markPrecedenceDecisions(atn)
+ this.verifyATN(atn)
+ if this.deserializationOptions.generateRuleBypassTransitions && atn.grammarType == ATNTypeParser {
+ this.generateRuleBypassTransitions(atn)
+ // re-verify after modification
+ this.verifyATN(atn)
+ }
+ return atn
}
func (this *ATNDeserializer) reset(data []rune) {
- // TODO not sure the copy is necessary here
- temp := make([]rune, len(data))
+ // TODO not sure the copy is necessary here
+ temp := make([]rune, len(data))
- for i, c := range data {
- // don't adjust the first value since that's the version number
- if (i == 0) {
- temp[i] = c
- } else if c > 1 {
- temp[i] = c-2
- } else {
- temp[i] = -1
- }
- }
+ for i, c := range data {
+ // don't adjust the first value since that's the version number
+ if i == 0 {
+ temp[i] = c
+ } else if c > 1 {
+ temp[i] = c - 2
+ } else {
+ temp[i] = -1
+ }
+ }
-// var adjust = func(c) {
-// var v = c.charCodeAt(0)
-// return v>1 ? v-2 : -1
-// }
+ // var adjust = func(c) {
+ // var v = c.charCodeAt(0)
+ // return v>1 ? v-2 : -1
+ // }
-// var temp = data.split("").map(adjust)
-// // don't adjust the first value since that's the version number
-// temp[0] = data.charCodeAt(0)
+ // var temp = data.split("").map(adjust)
+ // // don't adjust the first value since that's the version number
+ // temp[0] = data.charCodeAt(0)
- this.data = temp
- this.pos = 0
+ this.data = temp
+ this.pos = 0
}
func (this *ATNDeserializer) checkVersion() {
- var version = this.readInt()
- if ( version != SERIALIZED_VERSION ) {
- panic("Could not deserialize ATN with version " + strconv.Itoa(version) + " (expected " + strconv.Itoa(SERIALIZED_VERSION) + ").")
- }
+ var version = this.readInt()
+ if version != SERIALIZED_VERSION {
+ panic("Could not deserialize ATN with version " + strconv.Itoa(version) + " (expected " + strconv.Itoa(SERIALIZED_VERSION) + ").")
+ }
}
func (this *ATNDeserializer) checkUUID() {
- var uuid = this.readUUID()
- if ( stringInSlice(uuid, SUPPORTED_UUIDS ) <0 ) {
- panic("Could not deserialize ATN with UUID: " + uuid + " (expected " + SERIALIZED_UUID + " or a legacy UUID).")
- }
- this.uuid = uuid
+ var uuid = this.readUUID()
+ if stringInSlice(uuid, SUPPORTED_UUIDS) < 0 {
+ panic("Could not deserialize ATN with UUID: " + uuid + " (expected " + SERIALIZED_UUID + " or a legacy UUID).")
+ }
+ this.uuid = uuid
}
func (this *ATNDeserializer) readATN() *ATN {
- var grammarType = this.readInt()
- var maxTokenType = this.readInt()
- return NewATN(grammarType, maxTokenType)
+ var grammarType = this.readInt()
+ var maxTokenType = this.readInt()
+ return NewATN(grammarType, maxTokenType)
}
type LoopEndStateIntPair struct {
- item0 *LoopEndState
- item1 int
+ item0 *LoopEndState
+ item1 int
}
type BlockStartStateIntPair struct {
- item0 *BlockStartState
- item1 int
+ item0 *BlockStartState
+ item1 int
}
func (this *ATNDeserializer) readStates(atn *ATN) {
- var loopBackStateNumbers = make([]LoopEndStateIntPair,0)
- var endStateNumbers = make([]BlockStartStateIntPair,0)
+ var loopBackStateNumbers = make([]LoopEndStateIntPair, 0)
+ var endStateNumbers = make([]BlockStartStateIntPair, 0)
- var nstates = this.readInt()
- for i :=0; i This cache makes a huge difference in memory and a little bit in speed.
- // For the Java grammar on java.*, it dropped the memory requirements
- // at the end from 25M to 16M. We don't store any of the full context
- // graphs in the DFA because they are limited to local context only,
- // but apparently there's a lot of repetition there as well. We optimize
- // the config contexts before storing the config set in the DFA states
- // by literally rebuilding them with cached subgraphs only. I tried a cache for use during closure operations, that was
- // whacked after each adaptivePredict(). It cost a little bit
- // more time I think and doesn't save on the overall footprint
- // so it's not worth the complexity. This cache makes a huge difference in memory and a little bit in speed.
+ // For the Java grammar on java.*, it dropped the memory requirements
+ // at the end from 25M to 16M. We don't store any of the full context
+ // graphs in the DFA because they are limited to local context only,
+ // but apparently there's a lot of repetition there as well. We optimize
+ // the config contexts before storing the config set in the DFA states
+ // by literally rebuilding them with cached subgraphs only. I tried a cache for use during closure operations, that was
+ // whacked after each adaptivePredict(). It cost a little bit
+ // more time I think and doesn't save on the overall footprint
+ // so it's not worth the complexity.
- // The default value is {@code false} to avoid the performance and memory - // overhead of copying text for every token unless explicitly requested.
- // - tf.copyText = copyText + // Indicates whether {@link CommonToken//setText} should be called after + // constructing tokens to explicitly set the text. This is useful for cases + // where the input stream might not be able to provide arbitrary substrings + // of text from the input after the lexer creates a token (e.g. the + // implementation of {@link CharStream//getText} in + // {@link UnbufferedCharStream} panics an + // {@link UnsupportedOperationException}). Explicitly setting the token text + // allows {@link Token//getText} to be called at any time regardless of the + // input stream implementation. + // + //+ // The default value is {@code false} to avoid the performance and memory + // overhead of copying text for every token unless explicitly requested.
+ // + tf.copyText = copyText return tf } @@ -46,21 +46,19 @@ func NewCommonTokenFactory(copyText bool) *CommonTokenFactory { var CommonTokenFactoryDEFAULT = NewCommonTokenFactory(false) func (this *CommonTokenFactory) create(source *TokenSourceCharStreamPair, ttype int, text string, channel, start, stop, line, column int) *Token { - var t = NewCommonToken(source, ttype, channel, start, stop) - t.line = line - t.column = column - if (text != "") { - t.setText( text ) - } else if (this.copyText && source.charStream != nil) { - t.setText( source.charStream.getTextFromInterval(NewInterval(start,stop))) - } - return t.Token + var t = NewCommonToken(source, ttype, channel, start, stop) + t.line = line + t.column = column + if text != "" { + t.setText(text) + } else if this.copyText && source.charStream != nil { + t.setText(source.charStream.getTextFromInterval(NewInterval(start, stop))) + } + return t.Token } func (this *CommonTokenFactory) createThin(ttype int, text string) *Token { - var t = NewCommonToken(nil, ttype, TokenDefaultChannel, -1, -1) - t.setText( text ) - return t.Token + var t = NewCommonToken(nil, ttype, TokenDefaultChannel, -1, -1) + t.setText(text) + return t.Token } - - diff --git a/runtime/Go/src/antlr4/CommonTokenStream.go b/runtime/Go/src/antlr4/CommonTokenStream.go index e6e24ca69..f360b0b0f 100644 --- a/runtime/Go/src/antlr4/CommonTokenStream.go +++ b/runtime/Go/src/antlr4/CommonTokenStream.go @@ -26,75 +26,74 @@ package antlr4 type CommonTokenStream struct { - *BufferedTokenStream + *BufferedTokenStream } func NewCommonTokenStream(lexer ILexer, channel int) *CommonTokenStream { - ts := new(CommonTokenStream) - ts.InitBufferedTokenStream(lexer) + ts := new(CommonTokenStream) + ts.InitBufferedTokenStream(lexer) - ts.channel = channel + ts.channel = channel - return ts + return ts } func (ts *CommonTokenStream) adjustSeekIndex(i int) int { - return ts.nextTokenOnChannel(i, ts.channel) + return ts.nextTokenOnChannel(i, ts.channel) } func (ts *CommonTokenStream) LB(k int) *Token { - if (k==0 || ts.index-k<0) { - return nil - } - var i = ts.index - var n = 1 - // find k good tokens looking backwards - for (n <= k) { - // skip off-channel tokens - i = ts.previousTokenOnChannel(i - 1, ts.channel) - n += 1 - } - if (i < 0) { - return nil - } - return ts.tokens[i] + if k == 0 || ts.index-k < 0 { + return nil + } + var i = ts.index + var n = 1 + // find k good tokens looking backwards + for n <= k { + // skip off-channel tokens + i = ts.previousTokenOnChannel(i-1, ts.channel) + n += 1 + } + if i < 0 { + return nil + } + return ts.tokens[i] } func (ts *CommonTokenStream) LT(k int) *Token { - ts.lazyInit() - if (k == 0) { - return nil - } - if (k < 0) { - return ts.LB(-k) - } - var i = ts.index - var n = 1 // we know tokens[pos] is a good one - // find k good tokens - for n < k { - // skip off-channel tokens, but make sure to not look past EOF - if (ts.sync(i + 1)) { - i = ts.nextTokenOnChannel(i + 1, ts.channel) - } - n += 1 - } - return ts.tokens[i] + ts.lazyInit() + if k == 0 { + return nil + } + if k < 0 { + return ts.LB(-k) + } + var i = ts.index + var n = 1 // we know tokens[pos] is a good one + // find k good tokens + for n < k { + // skip off-channel tokens, but make sure to not look past EOF + if ts.sync(i + 1) { + i = ts.nextTokenOnChannel(i+1, ts.channel) + } + n += 1 + } + return ts.tokens[i] } // Count EOF just once./// func (ts *CommonTokenStream) getNumberOfOnChannelTokens() int { - var n = 0 - ts.fill() - for i := 0; i < len(ts.tokens); i++ { - var t = ts.tokens[i] - if t.channel==ts.channel { - n += 1 - } - if t.tokenType==TokenEOF { - break - } - } - return n + var n = 0 + ts.fill() + for i := 0; i < len(ts.tokens); i++ { + var t = ts.tokens[i] + if t.channel == ts.channel { + n += 1 + } + if t.tokenType == TokenEOF { + break + } + } + return n } - diff --git a/runtime/Go/src/antlr4/DFA.go b/runtime/Go/src/antlr4/DFA.go index e28efb406..37a56f695 100644 --- a/runtime/Go/src/antlr4/DFA.go +++ b/runtime/Go/src/antlr4/DFA.go @@ -2,9 +2,9 @@ package antlr4 type DFA struct { atnStartState *DecisionState - decision int - _states map[string]*DFAState - s0 *DFAState + decision int + _states map[string]*DFAState + s0 *DFAState precedenceDfa bool } @@ -37,11 +37,11 @@ func NewDFA(atnStartState *DecisionState, decision int) *DFA { // @see //isPrecedenceDfa() func (this *DFA) getPrecedenceStartState(precedence int) *DFAState { - if (!(this.precedenceDfa)) { + if !(this.precedenceDfa) { panic("Only precedence DFAs may contain a precedence start state.") } // s0.edges is never nil for a precedence DFA - if (precedence < 0 || precedence >= len(this.s0.edges)) { + if precedence < 0 || precedence >= len(this.s0.edges) { return nil } return this.s0.edges[precedence] @@ -56,11 +56,11 @@ func (this *DFA) getPrecedenceStartState(precedence int) *DFAState { // @panics IllegalStateException if this is not a precedence DFA. // @see //isPrecedenceDfa() // -func (this *DFA) setPrecedenceStartState(precedence int, startState *DFAState) { - if (!(this.precedenceDfa)) { - panic ("Only precedence DFAs may contain a precedence start state.") +func (this *DFA) setPrecedenceStartState(precedence int, startState *DFAState) { + if !(this.precedenceDfa) { + panic("Only precedence DFAs may contain a precedence start state.") } - if (precedence < 0) { + if precedence < 0 { return } @@ -88,11 +88,11 @@ func (this *DFA) setPrecedenceStartState(precedence int, startState *DFAState) // {@code false} func (this *DFA) setPrecedenceDfa(precedenceDfa bool) { - if (this.precedenceDfa!=precedenceDfa) { + if this.precedenceDfa != precedenceDfa { this._states = make(map[string]*DFAState) - if (precedenceDfa) { + if precedenceDfa { var precedenceState = NewDFAState(-1, NewATNConfigSet(false)) - precedenceState.edges = make([]*DFAState,0) + precedenceState.edges = make([]*DFAState, 0) precedenceState.isAcceptState = false precedenceState.requiresFullContext = false this.s0 = precedenceState @@ -114,18 +114,18 @@ func (this *DFA) sortedStates() []*DFAState { return nil // states_ is a map of state/state, where key=value -// var keys = Object.keys(this._states) -// var list = [] -// for i:=0; iThe default implementation simply calls {@link //endErrorCondition} to // ensure that the handler is not in error recovery mode.
func (this *DefaultErrorStrategy) reset(recognizer IParser) { - this.endErrorCondition(recognizer) + this.endErrorCondition(recognizer) } // @@ -94,11 +94,11 @@ func (this *DefaultErrorStrategy) reset(recognizer IParser) { // @param recognizer the parser instance // func (this *DefaultErrorStrategy) beginErrorCondition(recognizer IParser) { - this.errorRecoveryMode = true + this.errorRecoveryMode = true } func (this *DefaultErrorStrategy) inErrorRecoveryMode(recognizer IParser) bool { - return this.errorRecoveryMode + return this.errorRecoveryMode } // @@ -108,9 +108,9 @@ func (this *DefaultErrorStrategy) inErrorRecoveryMode(recognizer IParser) bool { // @param recognizer // func (this *DefaultErrorStrategy) endErrorCondition(recognizer IParser) { - this.errorRecoveryMode = false - this.lastErrorStates = nil - this.lastErrorIndex = -1 + this.errorRecoveryMode = false + this.lastErrorStates = nil + this.lastErrorIndex = -1 } // @@ -119,7 +119,7 @@ func (this *DefaultErrorStrategy) endErrorCondition(recognizer IParser) { //The default implementation simply calls {@link //endErrorCondition}.
// func (this *DefaultErrorStrategy) reportMatch(recognizer IParser) { - this.endErrorCondition(recognizer) + this.endErrorCondition(recognizer) } // @@ -142,25 +142,25 @@ func (this *DefaultErrorStrategy) reportMatch(recognizer IParser) { // // func (this *DefaultErrorStrategy) reportError(recognizer IParser, e IRecognitionException) { - // if we've already reported an error and have not matched a token - // yet successfully, don't report any errors. - if(this.inErrorRecoveryMode(recognizer)) { - return // don't report spurious errors - } - this.beginErrorCondition(recognizer) + // if we've already reported an error and have not matched a token + // yet successfully, don't report any errors. + if this.inErrorRecoveryMode(recognizer) { + return // don't report spurious errors + } + this.beginErrorCondition(recognizer) - switch t := e.(type) { - default: - fmt.Println("unknown recognition error type: " + reflect.TypeOf(e).Name()) -// fmt.Println(e.stack) - recognizer.notifyErrorListeners(e.getMessage(), e.getOffendingToken(), e) - case *NoViableAltException: - this.reportNoViableAlternative(recognizer, t) - case *InputMismatchException: - this.reportInputMismatch(recognizer, t) - case *FailedPredicateException: - this.reportFailedPredicate(recognizer, t) - } + switch t := e.(type) { + default: + fmt.Println("unknown recognition error type: " + reflect.TypeOf(e).Name()) + // fmt.Println(e.stack) + recognizer.notifyErrorListeners(e.getMessage(), e.getOffendingToken(), e) + case *NoViableAltException: + this.reportNoViableAlternative(recognizer, t) + case *InputMismatchException: + this.reportInputMismatch(recognizer, t) + case *FailedPredicateException: + this.reportFailedPredicate(recognizer, t) + } } // @@ -172,21 +172,21 @@ func (this *DefaultErrorStrategy) reportError(recognizer IParser, e IRecognition // func (this *DefaultErrorStrategy) recover(recognizer IParser, e IRecognitionException) { - if (this.lastErrorIndex==recognizer.getInputStream().index() && - this.lastErrorStates != nil && this.lastErrorStates.contains(recognizer.getState())) { + if this.lastErrorIndex == recognizer.getInputStream().index() && + this.lastErrorStates != nil && this.lastErrorStates.contains(recognizer.getState()) { // uh oh, another error at same token index and previously-visited // state in ATN must be a case where LT(1) is in the recovery // token set so nothing got consumed. Consume a single token // at least to prevent an infinite loop this is a failsafe. recognizer.consume() - } - this.lastErrorIndex = recognizer.getInputStream().index() - if (this.lastErrorStates == nil) { - this.lastErrorStates = NewIntervalSet() - } - this.lastErrorStates.addOne(recognizer.getState()) - var followSet = this.getErrorRecoverySet(recognizer) - this.consumeUntil(recognizer, followSet) + } + this.lastErrorIndex = recognizer.getInputStream().index() + if this.lastErrorStates == nil { + this.lastErrorStates = NewIntervalSet() + } + this.lastErrorStates.addOne(recognizer.getState()) + var followSet = this.getErrorRecoverySet(recognizer) + this.consumeUntil(recognizer, followSet) } // The default implementation of {@link ANTLRErrorStrategy//sync} makes sure @@ -235,43 +235,43 @@ func (this *DefaultErrorStrategy) recover(recognizer IParser, e IRecognitionExce // functionality by simply overriding this method as a blank { }. // func (this *DefaultErrorStrategy) sync(recognizer IParser) { - // If already recovering, don't try to sync - if (this.inErrorRecoveryMode(recognizer)) { - return - } - var s = recognizer.getInterpreter().atn.states[recognizer.getState()] - var la = recognizer.getTokenStream().LA(1) - // try cheaper subset first might get lucky. seems to shave a wee bit off - if (la==TokenEOF || recognizer.getATN().nextTokens(s,nil).contains(la)) { - return - } - // Return but don't end recovery. only do that upon valid token match - if(recognizer.isExpectedToken(la)) { - return - } - switch (s.getStateType()) { - case ATNStateBLOCK_START: - case ATNStateSTAR_BLOCK_START: - case ATNStatePLUS_BLOCK_START: - case ATNStateSTAR_LOOP_ENTRY: - // report error and recover if possible - if( this.singleTokenDeletion(recognizer) != nil) { - return - } else { - panic(NewInputMismatchException(recognizer)) - } - break - case ATNStatePLUS_LOOP_BACK: - case ATNStateSTAR_LOOP_BACK: - this.reportUnwantedToken(recognizer) - var expecting = NewIntervalSet() - expecting.addSet(recognizer.getExpectedTokens()) - var whatFollowsLoopIterationOrRule = expecting.addSet(this.getErrorRecoverySet(recognizer)) - this.consumeUntil(recognizer, whatFollowsLoopIterationOrRule) - break - default: - // do nothing if we can't identify the exact kind of ATN state - } + // If already recovering, don't try to sync + if this.inErrorRecoveryMode(recognizer) { + return + } + var s = recognizer.getInterpreter().atn.states[recognizer.getState()] + var la = recognizer.getTokenStream().LA(1) + // try cheaper subset first might get lucky. seems to shave a wee bit off + if la == TokenEOF || recognizer.getATN().nextTokens(s, nil).contains(la) { + return + } + // Return but don't end recovery. only do that upon valid token match + if recognizer.isExpectedToken(la) { + return + } + switch s.getStateType() { + case ATNStateBLOCK_START: + case ATNStateSTAR_BLOCK_START: + case ATNStatePLUS_BLOCK_START: + case ATNStateSTAR_LOOP_ENTRY: + // report error and recover if possible + if this.singleTokenDeletion(recognizer) != nil { + return + } else { + panic(NewInputMismatchException(recognizer)) + } + break + case ATNStatePLUS_LOOP_BACK: + case ATNStateSTAR_LOOP_BACK: + this.reportUnwantedToken(recognizer) + var expecting = NewIntervalSet() + expecting.addSet(recognizer.getExpectedTokens()) + var whatFollowsLoopIterationOrRule = expecting.addSet(this.getErrorRecoverySet(recognizer)) + this.consumeUntil(recognizer, whatFollowsLoopIterationOrRule) + break + default: + // do nothing if we can't identify the exact kind of ATN state + } } // This is called by {@link //reportError} when the exception is a @@ -283,19 +283,19 @@ func (this *DefaultErrorStrategy) sync(recognizer IParser) { // @param e the recognition exception // func (this *DefaultErrorStrategy) reportNoViableAlternative(recognizer IParser, e *NoViableAltException) { - var tokens = recognizer.getTokenStream() - var input string - if(tokens != nil) { - if (e.startToken.tokenType==TokenEOF) { - input = "The default implementation attempts to recover from the mismatched input
@@ -435,20 +436,20 @@ func (this *DefaultErrorStrategy) reportMissingToken(recognizer IParser) {
// in rule {@code atom}. It can assume that you forgot the {@code ')'}.
//
func (this *DefaultErrorStrategy) recoverInline(recognizer IParser) *Token {
- // SINGLE TOKEN DELETION
- var matchedSymbol = this.singleTokenDeletion(recognizer)
- if (matchedSymbol != nil) {
- // we have deleted the extra token.
- // now, move past ttype token as if all were ok
- recognizer.consume()
- return matchedSymbol
- }
- // SINGLE TOKEN INSERTION
- if (this.singleTokenInsertion(recognizer)) {
- return this.getMissingSymbol(recognizer)
- }
- // even that didn't work must panic the exception
- panic(NewInputMismatchException(recognizer))
+ // SINGLE TOKEN DELETION
+ var matchedSymbol = this.singleTokenDeletion(recognizer)
+ if matchedSymbol != nil {
+ // we have deleted the extra token.
+ // now, move past ttype token as if all were ok
+ recognizer.consume()
+ return matchedSymbol
+ }
+ // SINGLE TOKEN INSERTION
+ if this.singleTokenInsertion(recognizer) {
+ return this.getMissingSymbol(recognizer)
+ }
+ // even that didn't work must panic the exception
+ panic(NewInputMismatchException(recognizer))
}
//
@@ -469,20 +470,20 @@ func (this *DefaultErrorStrategy) recoverInline(recognizer IParser) *Token {
// strategy for the current mismatched input, otherwise {@code false}
//
func (this *DefaultErrorStrategy) singleTokenInsertion(recognizer IParser) bool {
- var currentSymbolType = recognizer.getTokenStream().LA(1)
- // if current token is consistent with what could come after current
- // ATN state, then we know we're missing a token error recovery
- // is free to conjure up and insert the missing token
- var atn = recognizer.getInterpreter().atn
- var currentState = atn.states[recognizer.getState()]
- var next = currentState.getTransitions()[0].getTarget()
- var expectingAtLL2 = atn.nextTokens(next, recognizer.getParserRuleContext())
- if (expectingAtLL2.contains(currentSymbolType) ){
- this.reportMissingToken(recognizer)
- return true
- } else {
- return false
- }
+ var currentSymbolType = recognizer.getTokenStream().LA(1)
+ // if current token is consistent with what could come after current
+ // ATN state, then we know we're missing a token error recovery
+ // is free to conjure up and insert the missing token
+ var atn = recognizer.getInterpreter().atn
+ var currentState = atn.states[recognizer.getState()]
+ var next = currentState.getTransitions()[0].getTarget()
+ var expectingAtLL2 = atn.nextTokens(next, recognizer.getParserRuleContext())
+ if expectingAtLL2.contains(currentSymbolType) {
+ this.reportMissingToken(recognizer)
+ return true
+ } else {
+ return false
+ }
}
// This method implements the single-token deletion inline error recovery
@@ -504,22 +505,22 @@ func (this *DefaultErrorStrategy) singleTokenInsertion(recognizer IParser) bool
// {@code nil}
//
func (this *DefaultErrorStrategy) singleTokenDeletion(recognizer IParser) *Token {
- var nextTokenType = recognizer.getTokenStream().LA(2)
- var expecting = this.getExpectedTokens(recognizer)
- if (expecting.contains(nextTokenType)) {
- this.reportUnwantedToken(recognizer)
- // print("recoverFromMismatchedToken deleting " \
- // + str(recognizer.getTokenStream().LT(1)) \
- // + " since " + str(recognizer.getTokenStream().LT(2)) \
- // + " is what we want", file=sys.stderr)
- recognizer.consume() // simply delete extra token
- // we want to return the token we're actually matching
- var matchedSymbol = recognizer.getCurrentToken()
- this.reportMatch(recognizer) // we know current token is correct
- return matchedSymbol
- } else {
- return nil
- }
+ var nextTokenType = recognizer.getTokenStream().LA(2)
+ var expecting = this.getExpectedTokens(recognizer)
+ if expecting.contains(nextTokenType) {
+ this.reportUnwantedToken(recognizer)
+ // print("recoverFromMismatchedToken deleting " \
+ // + str(recognizer.getTokenStream().LT(1)) \
+ // + " since " + str(recognizer.getTokenStream().LT(2)) \
+ // + " is what we want", file=sys.stderr)
+ recognizer.consume() // simply delete extra token
+ // we want to return the token we're actually matching
+ var matchedSymbol = recognizer.getCurrentToken()
+ this.reportMatch(recognizer) // we know current token is correct
+ return matchedSymbol
+ } else {
+ return nil
+ }
}
// Conjure up a missing token during error recovery.
@@ -542,27 +543,27 @@ func (this *DefaultErrorStrategy) singleTokenDeletion(recognizer IParser) *Token
// override this method to create the appropriate tokens.
//
func (this *DefaultErrorStrategy) getMissingSymbol(recognizer IParser) *Token {
- var currentSymbol = recognizer.getCurrentToken()
- var expecting = this.getExpectedTokens(recognizer)
- var expectedTokenType = expecting.first()
- var tokenText string
- if (expectedTokenType==TokenEOF) {
- tokenText = " The {@code skip} command does not have any parameters, so this action is
// implemented as a singleton instance exposed by {@link //INSTANCE}. This action is implemented by calling {@link Lexer//pushMode} with the
// value provided by {@link //getMode}. The {@code popMode} command does not have any parameters, so this action is
// implemented as a singleton instance exposed by {@link //INSTANCE}. This action is implemented by calling {@link Lexer//popMode}.
This action is implemented by calling {@link Lexer//popMode}.
func (this *LexerMoreAction) execute(lexer ILexer) { - lexer.more() + lexer.more() } func (this *LexerMoreAction) toString() string { - return "more" + return "more" } - // Implements the {@code mode} lexer action by calling {@link Lexer//mode} with // the assigned mode. type LexerModeAction struct { *LexerAction - mode int + mode int } func NewLexerModeAction(mode int) *LexerModeAction { this := new(LexerModeAction) - this.InitLexerAction( LexerActionTypeMODE ) - this.mode = mode - return this + this.InitLexerAction(LexerActionTypeMODE) + this.mode = mode + return this } //This action is implemented by calling {@link Lexer//mode} with the // value provided by {@link //getMode}.
func (this *LexerModeAction) execute(lexer ILexer) { - lexer.mode(this.mode) + lexer.mode(this.mode) } func (this *LexerModeAction) hashString() string { @@ -242,17 +242,17 @@ func (this *LexerModeAction) hashString() string { } func (this *LexerModeAction) equals(other ILexerAction) bool { - if (this == other) { - return true - } else if _, ok := other.(*LexerModeAction); !ok { - return false - } else { - return this.mode == other.(*LexerModeAction).mode - } + if this == other { + return true + } else if _, ok := other.(*LexerModeAction); !ok { + return false + } else { + return this.mode == other.(*LexerModeAction).mode + } } func (this *LexerModeAction) toString() string { - return "mode(" + strconv.Itoa(this.mode) + ")" + return "mode(" + strconv.Itoa(this.mode) + ")" } // Executes a custom lexer action by calling {@link Recognizer//action} with the @@ -274,36 +274,36 @@ func (this *LexerModeAction) toString() string { type LexerCustomAction struct { *LexerAction - ruleIndex, actionIndex int + ruleIndex, actionIndex int } func NewLexerCustomAction(ruleIndex, actionIndex int) *LexerCustomAction { this := new(LexerCustomAction) - this.InitLexerAction( LexerActionTypeCUSTOM ) - this.ruleIndex = ruleIndex - this.actionIndex = actionIndex - this.isPositionDependent = true - return this + this.InitLexerAction(LexerActionTypeCUSTOM) + this.ruleIndex = ruleIndex + this.actionIndex = actionIndex + this.isPositionDependent = true + return this } //Custom actions are implemented by calling {@link Lexer//action} with the // appropriate rule and action indexes.
func (this *LexerCustomAction) execute(lexer ILexer) { - lexer.action(nil, this.ruleIndex, this.actionIndex) + lexer.action(nil, this.ruleIndex, this.actionIndex) } func (this *LexerCustomAction) hashString() string { - return strconv.Itoa(this.actionType) + strconv.Itoa(this.ruleIndex) + strconv.Itoa(this.actionIndex) + return strconv.Itoa(this.actionType) + strconv.Itoa(this.ruleIndex) + strconv.Itoa(this.actionIndex) } func (this *LexerCustomAction) equals(other ILexerAction) bool { - if (this == other) { - return true - } else if _, ok := other.(*LexerCustomAction); !ok { - return false - } else { - return this.ruleIndex == other.(*LexerCustomAction).ruleIndex && this.actionIndex == other.(*LexerCustomAction).actionIndex - } + if this == other { + return true + } else if _, ok := other.(*LexerCustomAction); !ok { + return false + } else { + return this.ruleIndex == other.(*LexerCustomAction).ruleIndex && this.actionIndex == other.(*LexerCustomAction).actionIndex + } } // Implements the {@code channel} lexer action by calling @@ -313,38 +313,38 @@ func (this *LexerCustomAction) equals(other ILexerAction) bool { type LexerChannelAction struct { *LexerAction - channel int + channel int } func NewLexerChannelAction(channel int) *LexerChannelAction { this := new(LexerChannelAction) - this.InitLexerAction( LexerActionTypeCHANNEL ) - this.channel = channel - return this + this.InitLexerAction(LexerActionTypeCHANNEL) + this.channel = channel + return this } //This action is implemented by calling {@link Lexer//setChannel} with the // value provided by {@link //getChannel}.
func (this *LexerChannelAction) execute(lexer ILexer) { - lexer.setChannel(this.channel) + lexer.setChannel(this.channel) } func (this *LexerChannelAction) hashString() string { - return strconv.Itoa(this.actionType) + strconv.Itoa(this.channel) + return strconv.Itoa(this.actionType) + strconv.Itoa(this.channel) } func (this *LexerChannelAction) equals(other ILexerAction) bool { - if (this == other) { - return true - } else if _, ok := other.(*LexerChannelAction); !ok { - return false - } else { - return this.channel == other.(*LexerChannelAction).channel - } + if this == other { + return true + } else if _, ok := other.(*LexerChannelAction); !ok { + return false + } else { + return this.channel == other.(*LexerChannelAction).channel + } } func (this *LexerChannelAction) toString() string { - return "channel(" + strconv.Itoa(this.channel) + ")" + return "channel(" + strconv.Itoa(this.channel) + ")" } // This implementation of {@link LexerAction} is used for tracking input offsets @@ -370,51 +370,40 @@ func (this *LexerChannelAction) toString() string { type LexerIndexedCustomAction struct { *LexerAction - offset int - lexerAction ILexerAction - isPositionDependent bool + offset int + lexerAction ILexerAction + isPositionDependent bool } func NewLexerIndexedCustomAction(offset int, lexerAction ILexerAction) *LexerIndexedCustomAction { - this := new(LexerIndexedCustomAction) - this.InitLexerAction( lexerAction.getActionType() ) + this := new(LexerIndexedCustomAction) + this.InitLexerAction(lexerAction.getActionType()) - this.offset = offset - this.lexerAction = lexerAction - this.isPositionDependent = true + this.offset = offset + this.lexerAction = lexerAction + this.isPositionDependent = true - return this + return this } //This method calls {@link //execute} on the result of {@link //getAction} // using the provided {@code lexer}.
func (this *LexerIndexedCustomAction) execute(lexer ILexer) { - // assume the input stream position was properly set by the calling code - this.lexerAction.execute(lexer) + // assume the input stream position was properly set by the calling code + this.lexerAction.execute(lexer) } func (this *LexerIndexedCustomAction) hashString() string { - return strconv.Itoa(this.actionType) + strconv.Itoa(this.offset) + this.lexerAction.hashString() + return strconv.Itoa(this.actionType) + strconv.Itoa(this.offset) + this.lexerAction.hashString() } func (this *LexerIndexedCustomAction) equals(other ILexerAction) bool { - if (this == other) { - return true - } else if _, ok := other.(*LexerIndexedCustomAction); !ok { - return false - } else { - return this.offset == other.(*LexerIndexedCustomAction).offset && this.lexerAction == other.(*LexerIndexedCustomAction).lexerAction - } + if this == other { + return true + } else if _, ok := other.(*LexerIndexedCustomAction); !ok { + return false + } else { + return this.offset == other.(*LexerIndexedCustomAction).offset && this.lexerAction == other.(*LexerIndexedCustomAction).lexerAction + } } - - - - - - - - - - - diff --git a/runtime/Go/src/antlr4/LexerActionExecutor.go b/runtime/Go/src/antlr4/LexerActionExecutor.go index acc57af01..4fe8486d7 100644 --- a/runtime/Go/src/antlr4/LexerActionExecutor.go +++ b/runtime/Go/src/antlr4/LexerActionExecutor.go @@ -8,13 +8,13 @@ package antlr4 // not cause bloating of the {@link DFA} created for the lexer. type LexerActionExecutor struct { - lexerActions []ILexerAction + lexerActions []ILexerAction cachedHashString string } func NewLexerActionExecutor(lexerActions []ILexerAction) *LexerActionExecutor { - if (lexerActions == nil){ + if lexerActions == nil { lexerActions = make([]ILexerAction, 0) } @@ -49,13 +49,13 @@ func NewLexerActionExecutor(lexerActions []ILexerAction) *LexerActionExecutor { // @return A {@link LexerActionExecutor} for executing the combine actions // of {@code lexerActionExecutor} and {@code lexerAction}. func LexerActionExecutorappend(lexerActionExecutor *LexerActionExecutor, lexerAction ILexerAction) *LexerActionExecutor { - if (lexerActionExecutor == nil) { + if lexerActionExecutor == nil { return NewLexerActionExecutor([]ILexerAction{lexerAction}) } - var lexerActions = append(lexerActionExecutor.lexerActions, lexerAction ) + var lexerActions = append(lexerActionExecutor.lexerActions, lexerAction) -// var lexerActions = lexerActionExecutor.lexerActions.concat([ lexerAction ]) + // var lexerActions = lexerActionExecutor.lexerActions.concat([ lexerAction ]) return NewLexerActionExecutor(lexerActions) } @@ -91,11 +91,11 @@ func (this *LexerActionExecutor) fixOffsetBeforeMatch(offset int) *LexerActionEx var updatedLexerActions []ILexerAction = nil for i := 0; i < len(this.lexerActions); i++ { _, ok := this.lexerActions[i].(*LexerIndexedCustomAction) - if (this.lexerActions[i].getIsPositionDependent() && !ok){ - if (updatedLexerActions == nil) { - updatedLexerActions = make([]ILexerAction,0) + if this.lexerActions[i].getIsPositionDependent() && !ok { + if updatedLexerActions == nil { + updatedLexerActions = make([]ILexerAction, 0) - for _,a:= range this.lexerActions { + for _, a := range this.lexerActions { updatedLexerActions = append(updatedLexerActions, a) } } @@ -103,7 +103,7 @@ func (this *LexerActionExecutor) fixOffsetBeforeMatch(offset int) *LexerActionEx updatedLexerActions[i] = NewLexerIndexedCustomAction(offset, this.lexerActions[i]) } } - if (updatedLexerActions == nil) { + if updatedLexerActions == nil { return this } else { return NewLexerActionExecutor(updatedLexerActions) @@ -132,8 +132,8 @@ func (this *LexerActionExecutor) execute(lexer *Lexer, input CharStream, startIn var requiresSeek = false var stopIndex = input.index() - defer func(){ - if (requiresSeek) { + defer func() { + if requiresSeek { input.seek(stopIndex) } }() @@ -145,7 +145,7 @@ func (this *LexerActionExecutor) execute(lexer *Lexer, input CharStream, startIn input.seek(startIndex + offset) lexerAction = la.lexerAction requiresSeek = (startIndex + offset) != stopIndex - } else if (lexerAction.getIsPositionDependent()) { + } else if lexerAction.getIsPositionDependent() { input.seek(stopIndex) requiresSeek = false } @@ -158,14 +158,12 @@ func (this *LexerActionExecutor) hashString() string { } func (this *LexerActionExecutor) equals(other interface{}) bool { - if (this == other) { + if this == other { return true } else if _, ok := other.(*LexerActionExecutor); !ok { return false } else { return this.cachedHashString == other.(*LexerActionExecutor).cachedHashString && - &this.lexerActions == &other.(*LexerActionExecutor).lexerActions + &this.lexerActions == &other.(*LexerActionExecutor).lexerActions } } - - diff --git a/runtime/Go/src/antlr4/Parser.go b/runtime/Go/src/antlr4/Parser.go index bd4b25093..42a101977 100644 --- a/runtime/Go/src/antlr4/Parser.go +++ b/runtime/Go/src/antlr4/Parser.go @@ -2,7 +2,7 @@ package antlr4 import ( "fmt" - ) +) type TraceListener struct { parser *Parser @@ -10,7 +10,7 @@ type TraceListener struct { func NewTraceListener(parser *Parser) *TraceListener { tl := new(TraceListener) - tl.parser = parser + tl.parser = parser return tl } @@ -21,7 +21,7 @@ func (this *TraceListener) enterEveryRule(ctx IParserRuleContext) { fmt.Println("enter " + this.parser.getRuleNames()[ctx.getRuleIndex()] + ", LT(1)=" + this.parser._input.LT(1).text()) } -func (this *TraceListener) visitTerminal( node TerminalNode ) { +func (this *TraceListener) visitTerminal(node TerminalNode) { fmt.Println("consume " + fmt.Sprint(node.getSymbol()) + " rule " + this.parser.getRuleNames()[this.parser._ctx.getRuleIndex()]) } @@ -46,23 +46,23 @@ type IParser interface { isExpectedToken(symbol int) bool getPrecedence() int getRuleInvocationStack(IParserRuleContext) []string - } type Parser struct { *Recognizer - _input TokenStream - _errHandler IErrorStrategy - _precedenceStack IntStack - _ctx IParserRuleContext - buildParseTrees bool - _tracer *TraceListener - _parseListeners []ParseTreeListener - _syntaxErrors int - _interp *ParserATNSimulator + Interpreter *ParserATNSimulator - literalNames []string + _input TokenStream + _errHandler IErrorStrategy + _precedenceStack IntStack + _ctx IParserRuleContext + buildParseTrees bool + _tracer *TraceListener + _parseListeners []ParseTreeListener + _syntaxErrors int + + literalNames []string symbolicNames []string } @@ -72,6 +72,13 @@ func NewParser(input TokenStream) *Parser { p := new(Parser) + p.InitParser(input) + + return p +} + +func (p *Parser) InitParser(input TokenStream) { + p.InitRecognizer() // The input stream. @@ -100,8 +107,6 @@ func NewParser(input TokenStream) *Parser { // incremented each time {@link //notifyErrorListeners} is called. p._syntaxErrors = 0 p.setInputStream(input) - - return p } // p.field maps from the serialized ATN string to the deserialized {@link @@ -114,7 +119,7 @@ var bypassAltsAtnCache = make(map[string]int) // reset the parser's state// func (p *Parser) reset() { - if (p._input != nil) { + if p._input != nil { p._input.seek(0) } p._errHandler.reset(p) @@ -123,8 +128,8 @@ func (p *Parser) reset() { p.setTrace(nil) p._precedenceStack = make([]int, 0) p._precedenceStack.Push(0) - if (p._interp != nil) { - p._interp.reset() + if p.Interpreter != nil { + p.Interpreter.reset() } } @@ -147,12 +152,12 @@ func (p *Parser) reset() { func (p *Parser) match(ttype int) *Token { var t = p.getCurrentToken() - if (t.tokenType == ttype) { + if t.tokenType == ttype { p._errHandler.reportMatch(p) p.consume() } else { t = p._errHandler.recoverInline(p) - if (p.buildParseTrees && t.tokenIndex == -1) { + if p.buildParseTrees && t.tokenIndex == -1 { // we must have conjured up a Newtoken during single token // insertion // if it's not the current symbol @@ -161,6 +166,7 @@ func (p *Parser) match(ttype int) *Token { } return t } + // Match current input symbol as a wildcard. If the symbol type matches // (i.e. has a value greater than 0), {@link ANTLRErrorStrategy//reportMatch} // and {@link //consume} are called to complete the match process. @@ -179,12 +185,12 @@ func (p *Parser) match(ttype int) *Token { func (p *Parser) matchWildcard() *Token { var t = p.getCurrentToken() - if (t.tokenType > 0) { + if t.tokenType > 0 { p._errHandler.reportMatch(p) p.consume() } else { t = p._errHandler.recoverInline(p) - if (p.buildParseTrees && t.tokenIndex == -1) { + if p.buildParseTrees && t.tokenIndex == -1 { // we must have conjured up a Newtoken during single token // insertion // if it's not the current symbol @@ -199,8 +205,8 @@ func (p *Parser) getParserRuleContext() IParserRuleContext { } func (p *Parser) getParseListeners() []ParseTreeListener { - if (p._parseListeners == nil){ - return make([]ParseTreeListener,0) + if p._parseListeners == nil { + return make([]ParseTreeListener, 0) } return p._parseListeners } @@ -234,10 +240,10 @@ func (p *Parser) getParseListeners() []ParseTreeListener { // @panics nilPointerException if {@code} listener is {@code nil} // func (p *Parser) addParseListener(listener ParseTreeListener) { - if (listener == nil) { + if listener == nil { panic("listener") } - if (p._parseListeners == nil) { + if p._parseListeners == nil { p._parseListeners = make([]ParseTreeListener, 0) } p._parseListeners = append(p._parseListeners, listener) @@ -252,15 +258,15 @@ func (p *Parser) addParseListener(listener ParseTreeListener) { // func (p *Parser) removeParseListener(listener ParseTreeListener) { panic("Not implemented!") -// if (p._parseListeners != nil) { -// var idx = p._parseListeners.indexOf(listener) -// if (idx >= 0) { -// p._parseListeners.splice(idx, 1) -// } -// if (len(p._parseListeners) == 0) { -// p._parseListeners = nil -// } -// } + // if (p._parseListeners != nil) { + // var idx = p._parseListeners.indexOf(listener) + // if (idx >= 0) { + // p._parseListeners.splice(idx, 1) + // } + // if (len(p._parseListeners) == 0) { + // p._parseListeners = nil + // } + // } } // Remove all parse listeners. @@ -270,9 +276,9 @@ func (p *Parser) removeParseListeners() { // Notify any parse listeners of an enter rule event. func (p *Parser) triggerEnterRuleEvent() { - if (p._parseListeners != nil) { - var ctx = p._ctx - for _,listener := range p._parseListeners { + if p._parseListeners != nil { + var ctx = p._ctx + for _, listener := range p._parseListeners { listener.enterEveryRule(ctx) ctx.enterRule(listener) } @@ -285,9 +291,9 @@ func (p *Parser) triggerEnterRuleEvent() { // @see //addParseListener // func (p *Parser) triggerExitRuleEvent() { - if (p._parseListeners != nil) { + if p._parseListeners != nil { // reverse order walk of listeners - ctx := p._ctx + ctx := p._ctx l := len(p._parseListeners) - 1 for i := range p._parseListeners { @@ -307,11 +313,11 @@ func (this *Parser) getSymbolicNames() []string { } func (this *Parser) getInterpreter() *ParserATNSimulator { - return this._interp + return this.Interpreter } func (this *Parser) getATN() *ATN { - return this._interp.atn + return this.Interpreter.atn } func (p *Parser) getTokenFactory() TokenFactory { @@ -320,7 +326,7 @@ func (p *Parser) getTokenFactory() TokenFactory { // Tell our token source and error strategy about a Newway to create tokens.// func (p *Parser) setTokenFactory(factory TokenFactory) { - p._input.getTokenSource().setTokenFactory( factory ) + p._input.getTokenSource().setTokenFactory(factory) } // The ATN with bypass alternatives is expensive to create so we create it @@ -334,18 +340,18 @@ func (p *Parser) getATNWithBypassAlts() { // TODO panic("Not implemented!") -// var serializedAtn = p.getSerializedATN() -// if (serializedAtn == nil) { -// panic("The current parser does not support an ATN with bypass alternatives.") -// } -// var result = p.bypassAltsAtnCache[serializedAtn] -// if (result == nil) { -// var deserializationOptions = NewATNDeserializationOptions(nil) -// deserializationOptions.generateRuleBypassTransitions = true -// result = NewATNDeserializer(deserializationOptions).deserialize(serializedAtn) -// p.bypassAltsAtnCache[serializedAtn] = result -// } -// return result + // var serializedAtn = p.getSerializedATN() + // if (serializedAtn == nil) { + // panic("The current parser does not support an ATN with bypass alternatives.") + // } + // var result = p.bypassAltsAtnCache[serializedAtn] + // if (result == nil) { + // var deserializationOptions = NewATNDeserializationOptions(nil) + // deserializationOptions.generateRuleBypassTransitions = true + // result = NewATNDeserializer(deserializationOptions).deserialize(serializedAtn) + // p.bypassAltsAtnCache[serializedAtn] = result + // } + // return result } // The preferred method of getting a tree pattern. For example, here's a @@ -362,21 +368,21 @@ func (p *Parser) getATNWithBypassAlts() { func (p *Parser) compileParseTreePattern(pattern, patternRuleIndex, lexer ILexer) { panic("NewParseTreePatternMatcher not implemented!") -// -// if (lexer == nil) { -// if (p.getTokenStream() != nil) { -// var tokenSource = p.getTokenStream().getTokenSource() -// if _, ok := tokenSource.(ILexer); ok { -// lexer = tokenSource -// } -// } -// } -// if (lexer == nil) { -// panic("Parser can't discover a lexer to use") -// } + // + // if (lexer == nil) { + // if (p.getTokenStream() != nil) { + // var tokenSource = p.getTokenStream().getTokenSource() + // if _, ok := tokenSource.(ILexer); ok { + // lexer = tokenSource + // } + // } + // } + // if (lexer == nil) { + // panic("Parser can't discover a lexer to use") + // } -// var m = NewParseTreePatternMatcher(lexer, p) -// return m.compile(pattern, patternRuleIndex) + // var m = NewParseTreePatternMatcher(lexer, p) + // return m.compile(pattern, patternRuleIndex) } func (p *Parser) getInputStream() CharStream { @@ -406,7 +412,7 @@ func (p *Parser) getCurrentToken() *Token { } func (p *Parser) notifyErrorListeners(msg string, offendingToken *Token, err IRecognitionException) { - if (offendingToken == nil) { + if offendingToken == nil { offendingToken = p.getCurrentToken() } p._syntaxErrors += 1 @@ -418,28 +424,28 @@ func (p *Parser) notifyErrorListeners(msg string, offendingToken *Token, err IRe func (p *Parser) consume() *Token { var o = p.getCurrentToken() - if (o.tokenType != TokenEOF) { + if o.tokenType != TokenEOF { p.getInputStream().consume() } var hasListener = p._parseListeners != nil && len(p._parseListeners) > 0 - if (p.buildParseTrees || hasListener) { - if (p._errHandler.inErrorRecoveryMode(p)) { + if p.buildParseTrees || hasListener { + if p._errHandler.inErrorRecoveryMode(p) { var node = p._ctx.addErrorNode(o) - if (p._parseListeners != nil) { + if p._parseListeners != nil { for _, l := range p._parseListeners { - l.visitErrorNode(node); + l.visitErrorNode(node) } } } else { - node := p._ctx.addTokenNode(o); - if (p._parseListeners != nil) { + node := p._ctx.addTokenNode(o) + if p._parseListeners != nil { for _, l := range p._parseListeners { l.visitTerminal(node) } } } -// node.invokingState = p.state + // node.invokingState = p.state } return o @@ -447,27 +453,27 @@ func (p *Parser) consume() *Token { func (p *Parser) addContextToParseTree() { // add current context to parent if we have a parent - if (p._ctx.getParent() != nil) { - p._ctx.getParent().setChildren( append(p._ctx.getParent().getChildren(), p._ctx) ) + if p._ctx.getParent() != nil { + p._ctx.getParent().setChildren(append(p._ctx.getParent().getChildren(), p._ctx)) } } func (p *Parser) enterRule(localctx IParserRuleContext, state, ruleIndex int) { p.state = state p._ctx = localctx - p._ctx.setStart( p._input.LT(1) ) - if (p.buildParseTrees) { + p._ctx.setStart(p._input.LT(1)) + if p.buildParseTrees { p.addContextToParseTree() } - if (p._parseListeners != nil) { + if p._parseListeners != nil { p.triggerEnterRuleEvent() } } func (p *Parser) exitRule() { - p._ctx.setStop( p._input.LT(-1) ) + p._ctx.setStop(p._input.LT(-1)) // trigger event on _ctx, before it reverts to parent - if (p._parseListeners != nil) { + if p._parseListeners != nil { p.triggerExitRuleEvent() } p.state = p._ctx.getInvokingState() @@ -477,8 +483,8 @@ func (p *Parser) exitRule() { func (p *Parser) enterOuterAlt(localctx IParserRuleContext, altNum int) { // if we have Newlocalctx, make sure we replace existing ctx // that is previous child of parse tree - if (p.buildParseTrees && p._ctx != localctx) { - if (p._ctx.getParent() != nil) { + if p.buildParseTrees && p._ctx != localctx { + if p._ctx.getParent() != nil { p._ctx.getParent().(IParserRuleContext).removeLastChild() p._ctx.getParent().(IParserRuleContext).addChild(localctx) } @@ -492,10 +498,10 @@ func (p *Parser) enterOuterAlt(localctx IParserRuleContext, altNum int) { // the parser context is not nested within a precedence rule. func (p *Parser) getPrecedence() int { - if ( len(p._precedenceStack) == 0) { + if len(p._precedenceStack) == 0 { return -1 } else { - return p._precedenceStack[ len(p._precedenceStack) -1] + return p._precedenceStack[len(p._precedenceStack)-1] } } @@ -503,10 +509,10 @@ func (p *Parser) enterRecursionRule(localctx IParserRuleContext, state, ruleInde p.state = state p._precedenceStack.Push(precedence) p._ctx = localctx - p._ctx.setStart( p._input.LT(1) ) - if (p._parseListeners != nil) { + p._ctx.setStart(p._input.LT(1)) + if p._parseListeners != nil { p.triggerEnterRuleEvent() // simulates rule entry for - // left-recursive rules + // left-recursive rules } } @@ -515,28 +521,28 @@ func (p *Parser) enterRecursionRule(localctx IParserRuleContext, state, ruleInde func (p *Parser) pushNewRecursionContext(localctx IParserRuleContext, state, ruleIndex int) { var previous = p._ctx - previous.setParent( localctx ) - previous.setInvokingState( state ) - previous.setStart( p._input.LT(-1) ) + previous.setParent(localctx) + previous.setInvokingState(state) + previous.setStart(p._input.LT(-1)) p._ctx = localctx - p._ctx.setStart( previous.getStart() ) - if (p.buildParseTrees) { + p._ctx.setStart(previous.getStart()) + if p.buildParseTrees { p._ctx.addChild(previous) } - if (p._parseListeners != nil) { + if p._parseListeners != nil { p.triggerEnterRuleEvent() // simulates rule entry for - // left-recursive rules + // left-recursive rules } } func (p *Parser) unrollRecursionContexts(parentCtx IParserRuleContext) { p._precedenceStack.Pop() - p._ctx.setStop( p._input.LT(-1) ) + p._ctx.setStop(p._input.LT(-1)) var retCtx = p._ctx // save current ctx (return value) // unroll so _ctx is as it was before call to recursive method - if (p._parseListeners != nil) { - for (p._ctx != parentCtx) { + if p._parseListeners != nil { + for p._ctx != parentCtx { p.triggerExitRuleEvent() p._ctx = p._ctx.getParent().(IParserRuleContext) } @@ -544,8 +550,8 @@ func (p *Parser) unrollRecursionContexts(parentCtx IParserRuleContext) { p._ctx = parentCtx } // hook into tree - retCtx.setParent( parentCtx ) - if (p.buildParseTrees && parentCtx != nil) { + retCtx.setParent(parentCtx) + if p.buildParseTrees && parentCtx != nil { // add return ctx into invoking rule's tree parentCtx.addChild(retCtx) } @@ -553,8 +559,8 @@ func (p *Parser) unrollRecursionContexts(parentCtx IParserRuleContext) { func (p *Parser) getInvokingContext(ruleIndex int) IParserRuleContext { var ctx = p._ctx - for (ctx != nil) { - if (ctx.getRuleIndex() == ruleIndex) { + for ctx != nil { + if ctx.getRuleIndex() == ruleIndex { return ctx } ctx = ctx.getParent().(IParserRuleContext) @@ -563,7 +569,7 @@ func (p *Parser) getInvokingContext(ruleIndex int) IParserRuleContext { } func (p *Parser) precpred(localctx IRuleContext, precedence int) bool { - return precedence >= p._precedenceStack[ len(p._precedenceStack) -1] + return precedence >= p._precedenceStack[len(p._precedenceStack)-1] } func (p *Parser) inContext(context IParserRuleContext) bool { @@ -586,26 +592,26 @@ func (p *Parser) inContext(context IParserRuleContext) bool { // the ATN, otherwise {@code false}. func (p *Parser) isExpectedToken(symbol int) bool { - var atn *ATN = p._interp.atn + var atn *ATN = p.Interpreter.atn var ctx = p._ctx var s = atn.states[p.state] - var following = atn.nextTokens(s,nil) - if (following.contains(symbol)) { + var following = atn.nextTokens(s, nil) + if following.contains(symbol) { return true } - if (!following.contains(TokenEpsilon)) { + if !following.contains(TokenEpsilon) { return false } - for (ctx != nil && ctx.getInvokingState() >= 0 && following.contains(TokenEpsilon)) { + for ctx != nil && ctx.getInvokingState() >= 0 && following.contains(TokenEpsilon) { var invokingState = atn.states[ctx.getInvokingState()] var rt = invokingState.getTransitions()[0] - following = atn.nextTokens(rt.(*RuleTransition).followState,nil) - if (following.contains(symbol)) { + following = atn.nextTokens(rt.(*RuleTransition).followState, nil) + if following.contains(symbol) { return true } ctx = ctx.getParent().(IParserRuleContext) } - if (following.contains(TokenEpsilon) && symbol == TokenEOF) { + if following.contains(TokenEpsilon) && symbol == TokenEOF { return true } else { return false @@ -619,19 +625,19 @@ func (p *Parser) isExpectedToken(symbol int) bool { // @see ATN//getExpectedTokens(int, RuleContext) // func (p *Parser) getExpectedTokens() *IntervalSet { - return p._interp.atn.getExpectedTokens(p.state, p._ctx) + return p.Interpreter.atn.getExpectedTokens(p.state, p._ctx) } func (p *Parser) getExpectedTokensWithinCurrentRule() *IntervalSet { - var atn = p._interp.atn + var atn = p.Interpreter.atn var s = atn.states[p.state] - return atn.nextTokens(s,nil) + return atn.nextTokens(s, nil) } // Get a rule's index (i.e., {@code RULE_ruleName} field) or -1 if not found.// func (p *Parser) getRuleIndex(ruleName string) int { var ruleIndex, ok = p.getRuleIndexMap()[ruleName] - if (ok) { + if ok { return ruleIndex } else { return -1 @@ -646,45 +652,45 @@ func (p *Parser) getRuleIndex(ruleName string) int { // this very useful for error messages. func (this *Parser) getRuleInvocationStack(p IParserRuleContext) []string { - if (p == nil) { - p = this._ctx; + if p == nil { + p = this._ctx } - var stack = make([]string,0) - for (p != nil) { + var stack = make([]string, 0) + for p != nil { // compute what follows who invoked us - var ruleIndex = p.getRuleIndex(); - if (ruleIndex < 0) { + var ruleIndex = p.getRuleIndex() + if ruleIndex < 0 { stack = append(stack, "n/a") } else { - stack = append(stack, this.getRuleNames()[ruleIndex]); + stack = append(stack, this.getRuleNames()[ruleIndex]) } - p = p.getParent().(IParserRuleContext); + p = p.getParent().(IParserRuleContext) } - return stack; -}; + return stack +} // For debugging and other purposes.// func (p *Parser) getDFAStrings() { panic("dumpDFA Not implemented!") -// return p._interp.decisionToDFA.toString() + // return p._interp.decisionToDFA.toString() } // For debugging and other purposes.// func (p *Parser) dumpDFA() { panic("dumpDFA Not implemented!") -// var seenOne = false -// for i := 0; i < p._interp.decisionToDFA.length; i++ { -// var dfa = p._interp.decisionToDFA[i] -// if ( len(dfa.states) > 0) { -// if (seenOne) { -// fmt.Println() -// } -// p.printer.println("Decision " + dfa.decision + ":") -// p.printer.print(dfa.toString(p.literalNames, p.symbolicNames)) -// seenOne = true -// } -// } + // var seenOne = false + // for i := 0; i < p._interp.decisionToDFA.length; i++ { + // var dfa = p._interp.decisionToDFA[i] + // if ( len(dfa.states) > 0) { + // if (seenOne) { + // fmt.Println() + // } + // p.printer.println("Decision " + dfa.decision + ":") + // p.printer.print(dfa.toString(p.literalNames, p.symbolicNames)) + // seenOne = true + // } + // } } /* @@ -702,15 +708,14 @@ func (p *Parser) getSourceName() string { // events as well as token matches. p.is for quick and dirty debugging. // func (p *Parser) setTrace(trace *TraceListener) { - if (trace == nil) { + if trace == nil { p.removeParseListener(p._tracer) p._tracer = nil } else { - if (p._tracer != nil) { + if p._tracer != nil { p.removeParseListener(p._tracer) } p._tracer = NewTraceListener(p) p.addParseListener(p._tracer) } } - diff --git a/runtime/Go/src/antlr4/ParserATNSimulator.go b/runtime/Go/src/antlr4/ParserATNSimulator.go index 8c9c690a8..62fd3382b 100644 --- a/runtime/Go/src/antlr4/ParserATNSimulator.go +++ b/runtime/Go/src/antlr4/ParserATNSimulator.go @@ -1,55 +1,55 @@ package antlr4 import ( - "fmt" - "strconv" - "strings" + "fmt" + "strconv" + "strings" ) type ParserATNSimulator struct { - *ATNSimulator + *ATNSimulator - parser IParser - predictionMode int - _input TokenStream - _startIndex int - _dfa *DFA - decisionToDFA []*DFA - mergeCache *DoubleDict - _outerContext IParserRuleContext + parser IParser + predictionMode int + _input TokenStream + _startIndex int + _dfa *DFA + decisionToDFA []*DFA + mergeCache *DoubleDict + _outerContext IParserRuleContext } func NewParserATNSimulator(parser IParser, atn *ATN, decisionToDFA []*DFA, sharedContextCache *PredictionContextCache) *ParserATNSimulator { - this := new(ParserATNSimulator) + this := new(ParserATNSimulator) - this.InitParserATNSimulator(parser, atn, decisionToDFA, sharedContextCache) + this.InitParserATNSimulator(parser, atn, decisionToDFA, sharedContextCache) - return this + return this } func (this *ParserATNSimulator) InitParserATNSimulator(parser IParser, atn *ATN, decisionToDFA []*DFA, sharedContextCache *PredictionContextCache) { - this.InitATNSimulator(atn, sharedContextCache) + this.InitATNSimulator(atn, sharedContextCache) - this.parser = parser - this.decisionToDFA = decisionToDFA - // SLL, LL, or LL + exact ambig detection?// - this.predictionMode = PredictionModeLL - // LAME globals to avoid parameters!!!!! I need these down deep in predTransition - this._input = nil - this._startIndex = 0 - this._outerContext = nil - this._dfa = nil - // Each prediction operation uses a cache for merge of prediction contexts. - // Don't keep around as it wastes huge amounts of memory. DoubleKeyMap - // isn't synchronized but we're ok since two threads shouldn't reuse same - // parser/atnsim object because it can only handle one input at a time. - // This maps graphs a and b to merged result c. (a,b)&rarrc. We can avoid - // the merge if we ever see a and b again. Note that (b,a)&rarrc should - // also be examined during cache lookup. - // - this.mergeCache = nil + this.parser = parser + this.decisionToDFA = decisionToDFA + // SLL, LL, or LL + exact ambig detection?// + this.predictionMode = PredictionModeLL + // LAME globals to avoid parameters!!!!! I need these down deep in predTransition + this._input = nil + this._startIndex = 0 + this._outerContext = nil + this._dfa = nil + // Each prediction operation uses a cache for merge of prediction contexts. + // Don't keep around as it wastes huge amounts of memory. DoubleKeyMap + // isn't synchronized but we're ok since two threads shouldn't reuse same + // parser/atnsim object because it can only handle one input at a time. + // This maps graphs a and b to merged result c. (a,b)&rarrc. We can avoid + // the merge if we ever see a and b again. Note that (b,a)&rarrc should + // also be examined during cache lookup. + // + this.mergeCache = nil } @@ -63,85 +63,85 @@ func (this *ParserATNSimulator) reset() { func (this *ParserATNSimulator) adaptivePredict(input TokenStream, decision int, outerContext IParserRuleContext) int { - if (ParserATNSimulatorprototypedebug || ParserATNSimulatorprototypedebug_list_atn_decisions) { - fmt.Println("adaptivePredict decision " + strconv.Itoa(decision) + - " exec LA(1)==" + this.getLookaheadName(input) + - " line " + strconv.Itoa(input.LT(1).line) + ":" + - strconv.Itoa( input.LT(1).column) ) - } + if ParserATNSimulatorprototypedebug || ParserATNSimulatorprototypedebug_list_atn_decisions { + fmt.Println("adaptivePredict decision " + strconv.Itoa(decision) + + " exec LA(1)==" + this.getLookaheadName(input) + + " line " + strconv.Itoa(input.LT(1).line) + ":" + + strconv.Itoa(input.LT(1).column)) + } - this._input = input - this._startIndex = input.index() - this._outerContext = outerContext - - var dfa = this.decisionToDFA[decision] - this._dfa = dfa - var m = input.mark() - var index = input.index() + this._input = input + this._startIndex = input.index() + this._outerContext = outerContext - defer func(){ - this._dfa = nil - this.mergeCache = nil // wack cache after each prediction - input.seek(index) - input.release(m) - }() + var dfa = this.decisionToDFA[decision] + this._dfa = dfa + var m = input.mark() + var index = input.index() - // Now we are certain to have a specific decision's DFA - // But, do we still need an initial state? - var s0 *DFAState - if (dfa.precedenceDfa) { - // the start state for a precedence DFA depends on the current - // parser precedence, and is provided by a DFA method. - s0 = dfa.getPrecedenceStartState(this.parser.getPrecedence()) - } else { - // the start state for a "regular" DFA is just s0 - s0 = dfa.s0 - } + defer func() { + this._dfa = nil + this.mergeCache = nil // wack cache after each prediction + input.seek(index) + input.release(m) + }() - if (s0==nil) { - if (outerContext==nil) { - outerContext = RuleContextEMPTY - } - if (ParserATNSimulatorprototypedebug || ParserATNSimulatorprototypedebug_list_atn_decisions) { - fmt.Println("predictATN decision " + strconv.Itoa(dfa.decision) + - " exec LA(1)==" + this.getLookaheadName(input) + - ", outerContext=" + outerContext.toString(this.parser.getRuleNames(), nil)) - } - // If this is not a precedence DFA, we check the ATN start state - // to determine if this ATN start state is the decision for the - // closure block that determines whether a precedence rule - // should continue or complete. + // Now we are certain to have a specific decision's DFA + // But, do we still need an initial state? + var s0 *DFAState + if dfa.precedenceDfa { + // the start state for a precedence DFA depends on the current + // parser precedence, and is provided by a DFA method. + s0 = dfa.getPrecedenceStartState(this.parser.getPrecedence()) + } else { + // the start state for a "regular" DFA is just s0 + s0 = dfa.s0 + } - var t2 IATNState = dfa.atnStartState - t, ok := t2.(*StarLoopEntryState) - if (!dfa.precedenceDfa && ok) { - if (t.precedenceRuleDecision) { - dfa.setPrecedenceDfa(true) - } - } - var fullCtx = false - var s0_closure = this.computeStartState(dfa.atnStartState, RuleContextEMPTY, fullCtx) + if s0 == nil { + if outerContext == nil { + outerContext = RuleContextEMPTY + } + if ParserATNSimulatorprototypedebug || ParserATNSimulatorprototypedebug_list_atn_decisions { + fmt.Println("predictATN decision " + strconv.Itoa(dfa.decision) + + " exec LA(1)==" + this.getLookaheadName(input) + + ", outerContext=" + outerContext.toString(this.parser.getRuleNames(), nil)) + } + // If this is not a precedence DFA, we check the ATN start state + // to determine if this ATN start state is the decision for the + // closure block that determines whether a precedence rule + // should continue or complete. - if( dfa.precedenceDfa) { - // If this is a precedence DFA, we use applyPrecedenceFilter - // to convert the computed start state to a precedence start - // state. We then use DFA.setPrecedenceStartState to set the - // appropriate start state for the precedence level rather - // than simply setting DFA.s0. - // - s0_closure = this.applyPrecedenceFilter(s0_closure) - s0 = this.addDFAState(dfa, NewDFAState(-1, s0_closure)) - dfa.setPrecedenceStartState(this.parser.getPrecedence(), s0) - } else { - s0 = this.addDFAState(dfa, NewDFAState(-1, s0_closure)) - dfa.s0 = s0 - } - } - var alt = this.execATN(dfa, s0, input, index, outerContext) - if (ParserATNSimulatorprototypedebug) { - fmt.Println("DFA after predictATN: " + dfa.toString(this.parser.getLiteralNames(), nil)) - } - return alt + var t2 IATNState = dfa.atnStartState + t, ok := t2.(*StarLoopEntryState) + if !dfa.precedenceDfa && ok { + if t.precedenceRuleDecision { + dfa.setPrecedenceDfa(true) + } + } + var fullCtx = false + var s0_closure = this.computeStartState(dfa.atnStartState, RuleContextEMPTY, fullCtx) + + if dfa.precedenceDfa { + // If this is a precedence DFA, we use applyPrecedenceFilter + // to convert the computed start state to a precedence start + // state. We then use DFA.setPrecedenceStartState to set the + // appropriate start state for the precedence level rather + // than simply setting DFA.s0. + // + s0_closure = this.applyPrecedenceFilter(s0_closure) + s0 = this.addDFAState(dfa, NewDFAState(-1, s0_closure)) + dfa.setPrecedenceStartState(this.parser.getPrecedence(), s0) + } else { + s0 = this.addDFAState(dfa, NewDFAState(-1, s0_closure)) + dfa.s0 = s0 + } + } + var alt = this.execATN(dfa, s0, input, index, outerContext) + if ParserATNSimulatorprototypedebug { + fmt.Println("DFA after predictATN: " + dfa.toString(this.parser.getLiteralNames(), nil)) + } + return alt } @@ -151,22 +151,22 @@ func (this *ParserATNSimulator) adaptivePredict(input TokenStream, decision int, // There are some key conditions we're looking for after computing a new // set of ATN configs (proposed DFA state): - // if the set is empty, there is no viable alternative for current symbol - // does the state uniquely predict an alternative? - // does the state have a conflict that would prevent us from - // putting it on the work list? +// if the set is empty, there is no viable alternative for current symbol +// does the state uniquely predict an alternative? +// does the state have a conflict that would prevent us from +// putting it on the work list? // We also have some key operations to do: - // add an edge from previous DFA state to potentially NewDFA state, D, - // upon current symbol but only if adding to work list, which means in all - // cases except no viable alternative (and possibly non-greedy decisions?) - // collecting predicates and adding semantic context to DFA accept states - // adding rule context to context-sensitive DFA accept states - // consuming an input symbol - // reporting a conflict - // reporting an ambiguity - // reporting a context sensitivity - // reporting insufficient predicates +// add an edge from previous DFA state to potentially NewDFA state, D, +// upon current symbol but only if adding to work list, which means in all +// cases except no viable alternative (and possibly non-greedy decisions?) +// collecting predicates and adding semantic context to DFA accept states +// adding rule context to context-sensitive DFA accept states +// consuming an input symbol +// reporting a conflict +// reporting an ambiguity +// reporting a context sensitivity +// reporting insufficient predicates // cover these cases: // dead end @@ -175,103 +175,103 @@ func (this *ParserATNSimulator) adaptivePredict(input TokenStream, decision int, // conflict // conflict + preds // -func (this *ParserATNSimulator) execATN(dfa *DFA, s0 *DFAState, input TokenStream, startIndex int, outerContext IParserRuleContext ) int { +func (this *ParserATNSimulator) execATN(dfa *DFA, s0 *DFAState, input TokenStream, startIndex int, outerContext IParserRuleContext) int { - if (ParserATNSimulatorprototypedebug || ParserATNSimulatorprototypedebug_list_atn_decisions) { - fmt.Println("execATN decision " + strconv.Itoa(dfa.decision) + - " exec LA(1)==" + this.getLookaheadName(input) + - " line " + strconv.Itoa(input.LT(1).line) + ":" + strconv.Itoa(input.LT(1).column)) - } + if ParserATNSimulatorprototypedebug || ParserATNSimulatorprototypedebug_list_atn_decisions { + fmt.Println("execATN decision " + strconv.Itoa(dfa.decision) + + " exec LA(1)==" + this.getLookaheadName(input) + + " line " + strconv.Itoa(input.LT(1).line) + ":" + strconv.Itoa(input.LT(1).column)) + } - var previousD = s0 + var previousD = s0 - if (ParserATNSimulatorprototypedebug) { - fmt.Println("s0 = " + s0.toString()) - } - var t = input.LA(1) - for(true) { // for more work - var D = this.getExistingTargetState(previousD, t) - if(D==nil) { - D = this.computeTargetState(dfa, previousD, t) - } - if(D==ATNSimulatorERROR) { - // if any configs in previous dipped into outer context, that - // means that input up to t actually finished entry rule - // at least for SLL decision. Full LL doesn't dip into outer - // so don't need special case. - // We will get an error no matter what so delay until after - // decision better error message. Also, no reachable target - // ATN states in SLL implies LL will also get nowhere. - // If conflict in states that dip out, choose min since we - // will get error no matter what. - e := this.noViableAlt(input, outerContext, previousD.configs, startIndex) - input.seek(startIndex) - alt := this.getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(previousD.configs, outerContext) - if(alt != ATNINVALID_ALT_NUMBER) { - return alt - } else { - panic(e) - } - } - if(D.requiresFullContext && this.predictionMode != PredictionModeSLL) { - // IF PREDS, MIGHT RESOLVE TO SINGLE ALT => SLL (or syntax error) - var conflictingAlts *BitSet = D.configs.conflictingAlts - if (D.predicates!=nil) { - if (ParserATNSimulatorprototypedebug) { - fmt.Println("DFA state has preds in DFA sim LL failover") - } - var conflictIndex = input.index() - if(conflictIndex != startIndex) { - input.seek(startIndex) - } - conflictingAlts = this.evalSemanticContext(D.predicates, outerContext, true) - if (conflictingAlts.length()==1) { - if(ParserATNSimulatorprototypedebug) { - fmt.Println("Full LL avoided") - } - return conflictingAlts.minValue() - } - if (conflictIndex != startIndex) { - // restore the index so reporting the fallback to full - // context occurs with the index at the correct spot - input.seek(conflictIndex) - } - } - if (ParserATNSimulatorprototypedfa_debug) { - fmt.Println("ctx sensitive state " + outerContext.toString(nil,nil) +" in " + D.toString()) - } - var fullCtx = true - var s0_closure = this.computeStartState(dfa.atnStartState, outerContext, fullCtx) - this.reportAttemptingFullContext(dfa, conflictingAlts, D.configs, startIndex, input.index()) - alt := this.execATNWithFullContext(dfa, D, s0_closure, input, startIndex, outerContext) - return alt - } - if (D.isAcceptState) { - if (D.predicates==nil) { - return D.prediction - } - var stopIndex = input.index() - input.seek(startIndex) - var alts = this.evalSemanticContext(D.predicates, outerContext, true) - if (alts.length()==0) { - panic(this.noViableAlt(input, outerContext, D.configs, startIndex)) - } else if (alts.length()==1) { - return alts.minValue() - } else { - // report ambiguity after predicate evaluation to make sure the correct set of ambig alts is reported. - this.reportAmbiguity(dfa, D, startIndex, stopIndex, false, alts, D.configs) - return alts.minValue() - } - } - previousD = D + if ParserATNSimulatorprototypedebug { + fmt.Println("s0 = " + s0.toString()) + } + var t = input.LA(1) + for true { // for more work + var D = this.getExistingTargetState(previousD, t) + if D == nil { + D = this.computeTargetState(dfa, previousD, t) + } + if D == ATNSimulatorERROR { + // if any configs in previous dipped into outer context, that + // means that input up to t actually finished entry rule + // at least for SLL decision. Full LL doesn't dip into outer + // so don't need special case. + // We will get an error no matter what so delay until after + // decision better error message. Also, no reachable target + // ATN states in SLL implies LL will also get nowhere. + // If conflict in states that dip out, choose min since we + // will get error no matter what. + e := this.noViableAlt(input, outerContext, previousD.configs, startIndex) + input.seek(startIndex) + alt := this.getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(previousD.configs, outerContext) + if alt != ATNINVALID_ALT_NUMBER { + return alt + } else { + panic(e) + } + } + if D.requiresFullContext && this.predictionMode != PredictionModeSLL { + // IF PREDS, MIGHT RESOLVE TO SINGLE ALT => SLL (or syntax error) + var conflictingAlts *BitSet = D.configs.conflictingAlts + if D.predicates != nil { + if ParserATNSimulatorprototypedebug { + fmt.Println("DFA state has preds in DFA sim LL failover") + } + var conflictIndex = input.index() + if conflictIndex != startIndex { + input.seek(startIndex) + } + conflictingAlts = this.evalSemanticContext(D.predicates, outerContext, true) + if conflictingAlts.length() == 1 { + if ParserATNSimulatorprototypedebug { + fmt.Println("Full LL avoided") + } + return conflictingAlts.minValue() + } + if conflictIndex != startIndex { + // restore the index so reporting the fallback to full + // context occurs with the index at the correct spot + input.seek(conflictIndex) + } + } + if ParserATNSimulatorprototypedfa_debug { + fmt.Println("ctx sensitive state " + outerContext.toString(nil, nil) + " in " + D.toString()) + } + var fullCtx = true + var s0_closure = this.computeStartState(dfa.atnStartState, outerContext, fullCtx) + this.reportAttemptingFullContext(dfa, conflictingAlts, D.configs, startIndex, input.index()) + alt := this.execATNWithFullContext(dfa, D, s0_closure, input, startIndex, outerContext) + return alt + } + if D.isAcceptState { + if D.predicates == nil { + return D.prediction + } + var stopIndex = input.index() + input.seek(startIndex) + var alts = this.evalSemanticContext(D.predicates, outerContext, true) + if alts.length() == 0 { + panic(this.noViableAlt(input, outerContext, D.configs, startIndex)) + } else if alts.length() == 1 { + return alts.minValue() + } else { + // report ambiguity after predicate evaluation to make sure the correct set of ambig alts is reported. + this.reportAmbiguity(dfa, D, startIndex, stopIndex, false, alts, D.configs) + return alts.minValue() + } + } + previousD = D - if (t != TokenEOF) { - input.consume() - t = input.LA(1) - } - } + if t != TokenEOF { + input.consume() + t = input.LA(1) + } + } - panic("Should not have reached this state") + panic("Should not have reached this state") } // Get an existing target state for an edge in the DFA. If the target state @@ -285,12 +285,12 @@ func (this *ParserATNSimulator) execATN(dfa *DFA, s0 *DFAState, input TokenStrea // already cached func (this *ParserATNSimulator) getExistingTargetState(previousD *DFAState, t int) *DFAState { - var edges = previousD.edges - if (edges==nil) { - return nil - } else { - return edges[t + 1] - } + var edges = previousD.edges + if edges == nil { + return nil + } else { + return edges[t+1] + } } // Compute a target state for an edge in the DFA, and attempt to add the @@ -305,310 +305,311 @@ func (this *ParserATNSimulator) getExistingTargetState(previousD *DFAState, t in // returns {@link //ERROR}. func (this *ParserATNSimulator) computeTargetState(dfa *DFA, previousD *DFAState, t int) *DFAState { - var reach = this.computeReachSet(previousD.configs, t, false) + var reach = this.computeReachSet(previousD.configs, t, false) - if(reach==nil) { - this.addDFAEdge(dfa, previousD, t, ATNSimulatorERROR) - return ATNSimulatorERROR - } - // create Newtarget state we'll add to DFA after it's complete - var D = NewDFAState(-1, reach) + if reach == nil { + this.addDFAEdge(dfa, previousD, t, ATNSimulatorERROR) + return ATNSimulatorERROR + } + // create Newtarget state we'll add to DFA after it's complete + var D = NewDFAState(-1, reach) - var predictedAlt = this.getUniqueAlt(reach) + var predictedAlt = this.getUniqueAlt(reach) - if (ParserATNSimulatorprototypedebug) { - var altSubSets = PredictionModegetConflictingAltSubsets(reach) - fmt.Println("SLL altSubSets=" + fmt.Sprint(altSubSets) + - ", previous=" + previousD.configs.toString() + - ", configs=" + reach.toString() + - ", predict=" + strconv.Itoa(predictedAlt) + - ", allSubsetsConflict=" + - fmt.Sprint(PredictionModeallSubsetsConflict(altSubSets)) + - ", conflictingAlts=" + this.getConflictingAlts(reach).toString()) - } - if (predictedAlt!=ATNINVALID_ALT_NUMBER) { - // NO CONFLICT, UNIQUELY PREDICTED ALT - D.isAcceptState = true - D.configs.uniqueAlt = predictedAlt - D.prediction = predictedAlt - } else if (PredictionModehasSLLConflictTerminatingPrediction(this.predictionMode, reach)) { - // MORE THAN ONE VIABLE ALTERNATIVE - D.configs.conflictingAlts = this.getConflictingAlts(reach) - D.requiresFullContext = true - // in SLL-only mode, we will stop at this state and return the minimum alt - D.isAcceptState = true - D.prediction = D.configs.conflictingAlts.minValue() - } - if (D.isAcceptState && D.configs.hasSemanticContext) { - this.predicateDFAState(D, this.atn.getDecisionState(dfa.decision)) - if( D.predicates!=nil) { - D.prediction = ATNINVALID_ALT_NUMBER - } - } - // all adds to dfa are done after we've created full D state - D = this.addDFAEdge(dfa, previousD, t, D) - return D + if ParserATNSimulatorprototypedebug { + var altSubSets = PredictionModegetConflictingAltSubsets(reach) + fmt.Println("SLL altSubSets=" + fmt.Sprint(altSubSets) + + ", previous=" + previousD.configs.toString() + + ", configs=" + reach.toString() + + ", predict=" + strconv.Itoa(predictedAlt) + + ", allSubsetsConflict=" + + fmt.Sprint(PredictionModeallSubsetsConflict(altSubSets)) + + ", conflictingAlts=" + this.getConflictingAlts(reach).toString()) + } + if predictedAlt != ATNINVALID_ALT_NUMBER { + // NO CONFLICT, UNIQUELY PREDICTED ALT + D.isAcceptState = true + D.configs.uniqueAlt = predictedAlt + D.prediction = predictedAlt + } else if PredictionModehasSLLConflictTerminatingPrediction(this.predictionMode, reach) { + // MORE THAN ONE VIABLE ALTERNATIVE + D.configs.conflictingAlts = this.getConflictingAlts(reach) + D.requiresFullContext = true + // in SLL-only mode, we will stop at this state and return the minimum alt + D.isAcceptState = true + D.prediction = D.configs.conflictingAlts.minValue() + } + if D.isAcceptState && D.configs.hasSemanticContext { + this.predicateDFAState(D, this.atn.getDecisionState(dfa.decision)) + if D.predicates != nil { + D.prediction = ATNINVALID_ALT_NUMBER + } + } + // all adds to dfa are done after we've created full D state + D = this.addDFAEdge(dfa, previousD, t, D) + return D } func (this *ParserATNSimulator) predicateDFAState(dfaState *DFAState, decisionState *DecisionState) { - // We need to test all predicates, even in DFA states that - // uniquely predict alternative. - var nalts = len(decisionState.getTransitions()) - // Update DFA so reach becomes accept state with (predicate,alt) - // pairs if preds found for conflicting alts - var altsToCollectPredsFrom = this.getConflictingAltsOrUniqueAlt(dfaState.configs) - var altToPred = this.getPredsForAmbigAlts(altsToCollectPredsFrom, dfaState.configs, nalts) - if (altToPred!=nil) { - dfaState.predicates = this.getPredicatePredictions(altsToCollectPredsFrom, altToPred) - dfaState.prediction = ATNINVALID_ALT_NUMBER // make sure we use preds - } else { - // There are preds in configs but they might go away - // when OR'd together like {p}? || NONE == NONE. If neither - // alt has preds, resolve to min alt - dfaState.prediction = altsToCollectPredsFrom.minValue() - } + // We need to test all predicates, even in DFA states that + // uniquely predict alternative. + var nalts = len(decisionState.getTransitions()) + // Update DFA so reach becomes accept state with (predicate,alt) + // pairs if preds found for conflicting alts + var altsToCollectPredsFrom = this.getConflictingAltsOrUniqueAlt(dfaState.configs) + var altToPred = this.getPredsForAmbigAlts(altsToCollectPredsFrom, dfaState.configs, nalts) + if altToPred != nil { + dfaState.predicates = this.getPredicatePredictions(altsToCollectPredsFrom, altToPred) + dfaState.prediction = ATNINVALID_ALT_NUMBER // make sure we use preds + } else { + // There are preds in configs but they might go away + // when OR'd together like {p}? || NONE == NONE. If neither + // alt has preds, resolve to min alt + dfaState.prediction = altsToCollectPredsFrom.minValue() + } } // comes back with reach.uniqueAlt set to a valid alt -func (this *ParserATNSimulator) execATNWithFullContext(dfa *DFA, D *DFAState, s0 *ATNConfigSet, input TokenStream, startIndex int, outerContext IParserRuleContext) int{ +func (this *ParserATNSimulator) execATNWithFullContext(dfa *DFA, D *DFAState, s0 *ATNConfigSet, input TokenStream, startIndex int, outerContext IParserRuleContext) int { - if (ParserATNSimulatorprototypedebug || ParserATNSimulatorprototypedebug_list_atn_decisions) { - fmt.Println("execATNWithFullContext "+ s0.toString()) - } + if ParserATNSimulatorprototypedebug || ParserATNSimulatorprototypedebug_list_atn_decisions { + fmt.Println("execATNWithFullContext " + s0.toString()) + } - var fullCtx = true - var foundExactAmbig = false - var reach *ATNConfigSet = nil - var previous = s0 - input.seek(startIndex) - var t = input.LA(1) - var predictedAlt = -1 + var fullCtx = true + var foundExactAmbig = false + var reach *ATNConfigSet = nil + var previous = s0 + input.seek(startIndex) + var t = input.LA(1) + var predictedAlt = -1 - for (true) { // for more work - reach = this.computeReachSet(previous, t, fullCtx) - if (reach==nil) { - // if any configs in previous dipped into outer context, that - // means that input up to t actually finished entry rule - // at least for LL decision. Full LL doesn't dip into outer - // so don't need special case. - // We will get an error no matter what so delay until after - // decision better error message. Also, no reachable target - // ATN states in SLL implies LL will also get nowhere. - // If conflict in states that dip out, choose min since we - // will get error no matter what. - var e = this.noViableAlt(input, outerContext, previous, startIndex) - input.seek(startIndex) - var alt = this.getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(previous, outerContext) - if(alt!=ATNINVALID_ALT_NUMBER) { - return alt - } else { - panic(e) - } - } - var altSubSets = PredictionModegetConflictingAltSubsets(reach) - if(ParserATNSimulatorprototypedebug) { - fmt.Println("LL altSubSets=" + fmt.Sprint(altSubSets) + ", predict=" + - strconv.Itoa(PredictionModegetUniqueAlt(altSubSets)) + ", resolvesToJustOneViableAlt=" + - fmt.Sprint(PredictionModeresolvesToJustOneViableAlt(altSubSets))) - } - reach.uniqueAlt = this.getUniqueAlt(reach) - // unique prediction? - if(reach.uniqueAlt!=ATNINVALID_ALT_NUMBER) { - predictedAlt = reach.uniqueAlt - break - } else if (this.predictionMode != PredictionModeLL_EXACT_AMBIG_DETECTION) { - predictedAlt = PredictionModeresolvesToJustOneViableAlt(altSubSets) - if(predictedAlt != ATNINVALID_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 (PredictionModeallSubsetsConflict(altSubSets) && PredictionModeallSubsetsEqual(altSubSets)) { - foundExactAmbig = true - predictedAlt = PredictionModegetSingleViableAlt(altSubSets) - break - } - // else there are multiple non-conflicting subsets or - // we're not sure what the ambiguity is yet. - // So, keep going. - } - previous = reach - if( t != TokenEOF) { - input.consume() - t = input.LA(1) - } - } - // If the configuration set uniquely predicts an alternative, - // without conflict, then we know that it's a full LL decision - // not SLL. - if (reach.uniqueAlt != ATNINVALID_ALT_NUMBER ) { - this.reportContextSensitivity(dfa, predictedAlt, reach, startIndex, input.index()) - return predictedAlt - } - // We do not check predicates here because we have checked them - // on-the-fly when doing full context prediction. + for true { // for more work + reach = this.computeReachSet(previous, t, fullCtx) + if reach == nil { + // if any configs in previous dipped into outer context, that + // means that input up to t actually finished entry rule + // at least for LL decision. Full LL doesn't dip into outer + // so don't need special case. + // We will get an error no matter what so delay until after + // decision better error message. Also, no reachable target + // ATN states in SLL implies LL will also get nowhere. + // If conflict in states that dip out, choose min since we + // will get error no matter what. + var e = this.noViableAlt(input, outerContext, previous, startIndex) + input.seek(startIndex) + var alt = this.getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(previous, outerContext) + if alt != ATNINVALID_ALT_NUMBER { + return alt + } else { + panic(e) + } + } + var altSubSets = PredictionModegetConflictingAltSubsets(reach) + if ParserATNSimulatorprototypedebug { + fmt.Println("LL altSubSets=" + fmt.Sprint(altSubSets) + ", predict=" + + strconv.Itoa(PredictionModegetUniqueAlt(altSubSets)) + ", resolvesToJustOneViableAlt=" + + fmt.Sprint(PredictionModeresolvesToJustOneViableAlt(altSubSets))) + } + reach.uniqueAlt = this.getUniqueAlt(reach) + // unique prediction? + if reach.uniqueAlt != ATNINVALID_ALT_NUMBER { + predictedAlt = reach.uniqueAlt + break + } else if this.predictionMode != PredictionModeLL_EXACT_AMBIG_DETECTION { + predictedAlt = PredictionModeresolvesToJustOneViableAlt(altSubSets) + if predictedAlt != ATNINVALID_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 PredictionModeallSubsetsConflict(altSubSets) && PredictionModeallSubsetsEqual(altSubSets) { + foundExactAmbig = true + predictedAlt = PredictionModegetSingleViableAlt(altSubSets) + break + } + // else there are multiple non-conflicting subsets or + // we're not sure what the ambiguity is yet. + // So, keep going. + } + previous = reach + if t != TokenEOF { + input.consume() + t = input.LA(1) + } + } + // If the configuration set uniquely predicts an alternative, + // without conflict, then we know that it's a full LL decision + // not SLL. + if reach.uniqueAlt != ATNINVALID_ALT_NUMBER { + this.reportContextSensitivity(dfa, predictedAlt, reach, startIndex, input.index()) + return predictedAlt + } + // We do not check predicates here because we have checked them + // on-the-fly when doing full context prediction. - // - // In non-exact ambiguity detection mode, we might actually be able to - // detect an exact ambiguity, but I'm not going to spend the cycles - // needed to check. We only emit ambiguity warnings in exact ambiguity - // mode. - // - // For example, we might know that we have conflicting configurations. - // But, that does not mean that there is no way forward without a - // conflict. It's possible to have nonconflicting alt subsets as in: + // + // In non-exact ambiguity detection mode, we might actually be able to + // detect an exact ambiguity, but I'm not going to spend the cycles + // needed to check. We only emit ambiguity warnings in exact ambiguity + // mode. + // + // For example, we might know that we have conflicting configurations. + // But, that does not mean that there is no way forward without a + // conflict. It's possible to have nonconflicting alt subsets as in: - // altSubSets=[{1, 2}, {1, 2}, {1}, {1, 2}] + // altSubSets=[{1, 2}, {1, 2}, {1}, {1, 2}] - // from - // - // [(17,1,[5 $]), (13,1,[5 10 $]), (21,1,[5 10 $]), (11,1,[$]), - // (13,2,[5 10 $]), (21,2,[5 10 $]), (11,2,[$])] - // - // In this case, (17,1,[5 $]) indicates there is some next sequence that - // would resolve this without conflict to alternative 1. Any other viable - // next sequence, however, is associated with a conflict. We stop - // looking for input because no amount of further lookahead will alter - // the fact that we should predict alternative 1. We just can't say for - // sure that there is an ambiguity without looking further. + // from + // + // [(17,1,[5 $]), (13,1,[5 10 $]), (21,1,[5 10 $]), (11,1,[$]), + // (13,2,[5 10 $]), (21,2,[5 10 $]), (11,2,[$])] + // + // In this case, (17,1,[5 $]) indicates there is some next sequence that + // would resolve this without conflict to alternative 1. Any other viable + // next sequence, however, is associated with a conflict. We stop + // looking for input because no amount of further lookahead will alter + // the fact that we should predict alternative 1. We just can't say for + // sure that there is an ambiguity without looking further. - this.reportAmbiguity(dfa, D, startIndex, input.index(), foundExactAmbig, nil, reach) + this.reportAmbiguity(dfa, D, startIndex, input.index(), foundExactAmbig, nil, reach) - return predictedAlt + return predictedAlt } func (this *ParserATNSimulator) computeReachSet(closure *ATNConfigSet, t int, fullCtx bool) *ATNConfigSet { - if (ParserATNSimulatorprototypedebug) { - fmt.Println("in computeReachSet, starting closure: " + closure.toString()) - } - if( this.mergeCache==nil) { - this.mergeCache = NewDoubleDict() - } - var intermediate = NewATNConfigSet(fullCtx) + if ParserATNSimulatorprototypedebug { + fmt.Println("in computeReachSet, starting closure: " + closure.toString()) + } + if this.mergeCache == nil { + this.mergeCache = NewDoubleDict() + } + var intermediate = NewATNConfigSet(fullCtx) - // Configurations already in a rule stop state indicate reaching the end - // of the decision rule (local context) or end of the start rule (full - // context). Once reached, these configurations are never updated by a - // closure operation, so they are handled separately for the performance - // advantage of having a smaller intermediate set when calling closure. - // - // For full-context reach operations, separate handling is required to - // ensure that the alternative matching the longest overall sequence is - // chosen when multiple such configurations can match the input. - - var skippedStopStates []*ATNConfig = nil + // Configurations already in a rule stop state indicate reaching the end + // of the decision rule (local context) or end of the start rule (full + // context). Once reached, these configurations are never updated by a + // closure operation, so they are handled separately for the performance + // advantage of having a smaller intermediate set when calling closure. + // + // For full-context reach operations, separate handling is required to + // ensure that the alternative matching the longest overall sequence is + // chosen when multiple such configurations can match the input. - // First figure out where we can reach on input t - for i:=0; i
} catch( error) {
- if(error instanceof error.RecognitionException) {
+ if(error instanceof IRecognitionException) {
localctx.exception = error
p._errHandler.reportError(p, error)
p._errHandler.recover(p, error)
@@ -441,7 +434,7 @@ case +1:
Sync(s) ::= "sync()"
-ThrowNoViableAlt(t) ::= "panic(new error.NoViableAltException(p))"
+ThrowNoViableAlt(t) ::= "panic(NewNoViableAltException(p))"
TestSetInline(s) ::= <<
}; separator=" || ">
@@ -519,7 +512,7 @@ ArgAction(a, chunks) ::= ""
SemPred(p, chunks, failChunks) ::= <<
p.state =
if !( ) {
- panic( error.FailedPredicateException(p, , , ))
+ panic( FailedPredicateException(p, , , ))
}
>>
@@ -564,13 +557,13 @@ TokenPropertyRef_int(t) ::= "(. == null ? 0 : parseInt(
RulePropertyRef_start(r) ::= "(.==null ? null : ..start)"
RulePropertyRef_stop(r) ::= "(.==null ? null : ..stop)"
-RulePropertyRef_text(r) ::= "(.==null ? null : p._input.getText(new Interval(..start,..stop)))"
+RulePropertyRef_text(r) ::= "(.==null ? null : p._input.getText(NewInterval(..start,..stop)))"
RulePropertyRef_ctx(r) ::= "."
RulePropertyRef_parser(r) ::= "this"
ThisRulePropertyRef_start(r) ::= "localctx.start"
ThisRulePropertyRef_stop(r) ::= "localctx.stop"
-ThisRulePropertyRef_text(r) ::= "p._input.getText(new Interval(localctx.start, p._input.LT(-1)))"
+ThisRulePropertyRef_text(r) ::= "p._input.getText(NewInterval(localctx.start, p._input.LT(-1)))"
ThisRulePropertyRef_ctx(r) ::= "localctx"
ThisRulePropertyRef_parser(r) ::= "p"
@@ -653,20 +646,19 @@ StructDecl(struct,ctorAttrs,attrs,getters,dispatchMethods,interfaces,extensionMe
superClass={ParserRuleContext}) ::= <<
type struct {
- *ParserRuleContext
+ *antlr4.ParserRuleContext
- parent *ParserRuleContext
- parser *Parser
- ruleIndex
+ parser antlr4.IParser
}
-func New(parser *Parser, parent *ParserRuleContext, invokingState int}>) {
+func New(parser antlr4.IParser, parent antlr4.IParserRuleContext, invokingState int}>) {
var p = new()
+
p.InitParserRuleContext( parent, invokingState )
p.parser = parser
- p.ruleIndex = RULE_
+ p.RuleIndex = RULE_
}; separator="\n">
= || null;}; separator="\n">
return p
@@ -688,18 +680,16 @@ func (s *) copyFrom(ctx ) {
AltLabelStructDecl(struct,attrs,getters,dispatchMethods) ::= <<
type struct {
- parent *ParserRuleContext
- parser *Parser
- ruleIndex int
+ parent antlr4.IParserRuleContext
+ parser antlr4.IParser
}
-func New(parser *Parser, ctx *ParserRuleContext) {
+func New(parser antlr4.IParser, ctx antlr4.IParserRuleContext) {
var p = new()
Context.call(this, parser)
-
;}; separator="\n">
Context.prototype.copyFrom.call(this, ctx)
@@ -713,25 +703,23 @@ func New(parser *Parser, ctx *ParserRuleContext) {
ListenerDispatchMethod(method) ::= <<
-func (s *) enterexitRule(listener *ParseTreeListener) {
- // TODO
- switch t := listener.(type) {
- case *Listener:
- listener.enterexit(s)
- }
+func (s *) enterexitRule(listener antlr4.ParseTreeListener) {
+
+ listener.(*Listener).enterexit(s)
+
}
>>
VisitorDispatchMethod(method) ::= <<
-func (s *) accept(visitor *ParseTreeVisitor) {
+func (s *) accept(visitor antlr4.ParseTreeVisitor) interface{} {
switch t := listener.(type) {
case *Listener:
- return visitor.visit(s)
+ return t.visit(s)
default:
- return visitor.visitChildren(s)
+ return t.visitChildren(s)
}
}
@@ -754,13 +742,13 @@ recRuleSetReturnAction(src,name) ::= "$=$."
recRuleSetStopToken() ::= "p._ctx.stop = p._input.LT(-1);"
recRuleAltStartAction(ruleName, ctxName, label) ::= <<
-localctx = new Context(this, _parentctx, _parentState)
+localctx = NewContext(this, _parentctx, _parentState)
localctx.