Some refactoring and cleanup

This commit is contained in:
Peter Boyer 2015-12-31 15:01:37 -05:00
parent 89427b7f45
commit 0726f4c2bb
21 changed files with 480 additions and 421 deletions

View File

@ -5,6 +5,14 @@ import (
"parser"
)
type MyErrorListener struct {
*MyErrorListener
}
func main() {
a := antlr4.NewFileStream("foo.txt")
@ -21,6 +29,8 @@ func main() {
}

View File

@ -14,7 +14,7 @@ import (
// an ATN state.
//
type IATNConfig interface {
type ATNConfig interface {
Hasher
getPrecedenceFilterSuppressed() bool
@ -35,7 +35,7 @@ type IATNConfig interface {
shortHash() string
}
type ATNConfig struct {
type BaseATNConfig struct {
precedenceFilterSuppressed bool
state IATNState
alt int
@ -44,8 +44,8 @@ type ATNConfig struct {
reachesIntoOuterContext int
}
func NewATNConfig7(old *ATNConfig) *ATNConfig { // dup
a := new(ATNConfig)
func NewATNConfig7(old *BaseATNConfig) *BaseATNConfig { // dup
a := new(BaseATNConfig)
a.state = old.state
a.alt = old.alt
a.context = old.context
@ -54,12 +54,12 @@ func NewATNConfig7(old *ATNConfig) *ATNConfig { // dup
return a
}
func NewATNConfig6(state IATNState, alt int, context IPredictionContext) *ATNConfig {
func NewATNConfig6(state IATNState, alt int, context IPredictionContext) *BaseATNConfig {
return NewATNConfig5(state, alt, context, SemanticContextNONE)
}
func NewATNConfig5(state IATNState, alt int, context IPredictionContext, semanticContext SemanticContext) *ATNConfig {
a := new(ATNConfig)
func NewATNConfig5(state IATNState, alt int, context IPredictionContext, semanticContext SemanticContext) *BaseATNConfig {
a := new(BaseATNConfig)
if (semanticContext == nil){
panic("SemanticContext cannot be null!")
@ -73,24 +73,24 @@ func NewATNConfig5(state IATNState, alt int, context IPredictionContext, semanti
return a
}
func NewATNConfig4(c IATNConfig, state IATNState) *ATNConfig {
func NewATNConfig4(c ATNConfig, state IATNState) *BaseATNConfig {
return NewATNConfig(c, state, c.GetContext(), c.GetSemanticContext())
}
func NewATNConfig3(c IATNConfig, state IATNState, semanticContext SemanticContext) *ATNConfig {
func NewATNConfig3(c ATNConfig, state IATNState, semanticContext SemanticContext) *BaseATNConfig {
return NewATNConfig(c, state, c.GetContext(), semanticContext)
}
func NewATNConfig2(c IATNConfig, semanticContext SemanticContext) *ATNConfig {
func NewATNConfig2(c ATNConfig, semanticContext SemanticContext) *BaseATNConfig {
return NewATNConfig(c, c.GetState(), c.GetContext(), semanticContext)
}
func NewATNConfig1(c IATNConfig, state IATNState, context IPredictionContext) *ATNConfig {
func NewATNConfig1(c ATNConfig, state IATNState, context IPredictionContext) *BaseATNConfig {
return NewATNConfig(c, state, context, c.GetSemanticContext())
}
func NewATNConfig(c IATNConfig, state IATNState, context IPredictionContext, semanticContext SemanticContext) *ATNConfig {
a := new(ATNConfig)
func NewATNConfig(c ATNConfig, state IATNState, context IPredictionContext, semanticContext SemanticContext) *BaseATNConfig {
a := new(BaseATNConfig)
if (semanticContext == nil){
panic("SemanticContext cannot be null!")
@ -105,38 +105,38 @@ func NewATNConfig(c IATNConfig, state IATNState, context IPredictionContext, sem
return a
}
func (this *ATNConfig) getPrecedenceFilterSuppressed() bool {
func (this *BaseATNConfig) getPrecedenceFilterSuppressed() bool {
return this.precedenceFilterSuppressed
}
func (this *ATNConfig) setPrecedenceFilterSuppressed(v bool) {
func (this *BaseATNConfig) setPrecedenceFilterSuppressed(v bool) {
this.precedenceFilterSuppressed = v
}
func (this *ATNConfig) GetState() IATNState {
func (this *BaseATNConfig) GetState() IATNState {
return this.state
}
func (this *ATNConfig) GetAlt() int {
func (this *BaseATNConfig) GetAlt() int {
return this.alt
}
func (this *ATNConfig) SetContext(v IPredictionContext) {
func (this *BaseATNConfig) SetContext(v IPredictionContext) {
this.context = v
}
func (this *ATNConfig) GetContext() IPredictionContext {
func (this *BaseATNConfig) GetContext() IPredictionContext {
return this.context
}
func (this *ATNConfig) GetSemanticContext() SemanticContext {
func (this *BaseATNConfig) GetSemanticContext() SemanticContext {
return this.semanticContext
}
func (this *ATNConfig) GetReachesIntoOuterContext() int {
func (this *BaseATNConfig) GetReachesIntoOuterContext() int {
return this.reachesIntoOuterContext
}
func (this *ATNConfig) SetReachesIntoOuterContext(v int) {
func (this *BaseATNConfig) SetReachesIntoOuterContext(v int) {
this.reachesIntoOuterContext = v
}
@ -144,21 +144,21 @@ func (this *ATNConfig) SetReachesIntoOuterContext(v int) {
// the same state, they predict the same alternative, and
// syntactic/semantic contexts are the same.
///
func (this *ATNConfig) equals(other interface{}) bool {
func (this *BaseATNConfig) equals(other interface{}) bool {
if this == other {
return true
} else if _, ok := other.(*ATNConfig); !ok {
} else if _, ok := other.(*BaseATNConfig); !ok {
return false
} else {
return reflect.DeepEqual(this, other)
}
}
func (this *ATNConfig) shortHash() string {
func (this *BaseATNConfig) shortHash() string {
return strconv.Itoa(this.state.GetStateNumber()) + "/" + strconv.Itoa(this.alt) + "/" + this.semanticContext.String()
}
func (this *ATNConfig) Hash() string {
func (this *BaseATNConfig) Hash() string {
var c string
if this.context == nil {
@ -170,7 +170,7 @@ func (this *ATNConfig) Hash() string {
return strconv.Itoa(this.state.GetStateNumber()) + "/" + strconv.Itoa(this.alt) + "/" + c + "/" + this.semanticContext.String()
}
func (this *ATNConfig) String() string {
func (this *BaseATNConfig) String() string {
var a string
if this.context != nil {
@ -195,7 +195,7 @@ func (this *ATNConfig) String() string {
type LexerATNConfig struct {
*ATNConfig
*BaseATNConfig
lexerActionExecutor *LexerActionExecutor
passedThroughNonGreedyDecision bool
@ -205,7 +205,7 @@ func NewLexerATNConfig6(state IATNState, alt int, context IPredictionContext) *L
this := new(LexerATNConfig)
this.ATNConfig = NewATNConfig5(state, alt, context, SemanticContextNONE)
this.BaseATNConfig = NewATNConfig5(state, alt, context, SemanticContextNONE)
this.passedThroughNonGreedyDecision = false
this.lexerActionExecutor = nil
@ -216,7 +216,7 @@ func NewLexerATNConfig5(state IATNState, alt int, context IPredictionContext, le
this := new(LexerATNConfig)
this.ATNConfig = NewATNConfig5(state, alt, context, SemanticContextNONE)
this.BaseATNConfig = NewATNConfig5(state, alt, context, SemanticContextNONE)
this.lexerActionExecutor = lexerActionExecutor
this.passedThroughNonGreedyDecision = false
return this
@ -226,7 +226,7 @@ func NewLexerATNConfig4(c *LexerATNConfig, state IATNState) *LexerATNConfig {
this := new(LexerATNConfig)
this.ATNConfig = NewATNConfig(c, state, c.GetContext(), c.GetSemanticContext())
this.BaseATNConfig = NewATNConfig(c, state, c.GetContext(), c.GetSemanticContext())
this.lexerActionExecutor = c.lexerActionExecutor
this.passedThroughNonGreedyDecision = checkNonGreedyDecision(c, state)
return this
@ -236,7 +236,7 @@ func NewLexerATNConfig3(c *LexerATNConfig, state IATNState, lexerActionExecutor
this := new(LexerATNConfig)
this.ATNConfig = NewATNConfig(c, state, c.GetContext(), c.GetSemanticContext())
this.BaseATNConfig = NewATNConfig(c, state, c.GetContext(), c.GetSemanticContext())
this.lexerActionExecutor = lexerActionExecutor
this.passedThroughNonGreedyDecision = checkNonGreedyDecision(c, state)
return this
@ -246,7 +246,7 @@ func NewLexerATNConfig2(c *LexerATNConfig, state IATNState, context IPredictionC
this := new(LexerATNConfig)
this.ATNConfig = NewATNConfig(c, state, context, c.GetSemanticContext())
this.BaseATNConfig = NewATNConfig(c, state, context, c.GetSemanticContext())
this.lexerActionExecutor = c.lexerActionExecutor
this.passedThroughNonGreedyDecision = checkNonGreedyDecision(c, state)
return this
@ -256,7 +256,7 @@ func NewLexerATNConfig1(state IATNState, alt int, context IPredictionContext) *L
this := new(LexerATNConfig)
this.ATNConfig = NewATNConfig5(state, alt, context, SemanticContextNONE)
this.BaseATNConfig = NewATNConfig5(state, alt, context, SemanticContextNONE)
this.lexerActionExecutor = nil
this.passedThroughNonGreedyDecision = false

View File

@ -4,54 +4,64 @@ import (
"fmt"
)
//
type ATNConfigSet interface {
Hasher
Add(config ATNConfig, mergeCache *DoubleDict) bool
AddAll(coll []ATNConfig) bool
GetStates() *Set
GetPredicates() []SemanticContext
GetItems() []ATNConfig
OptimizeConfigs(interpreter *ATNSimulator)
Equals(other interface{}) bool
Length() int
IsEmpty() bool
Contains(item *BaseATNConfig) bool
ContainsFast(item *BaseATNConfig) bool
Clear()
String() string
HasSemanticContext() bool
SetHasSemanticContext(v bool)
ReadOnly() bool
SetReadOnly(bool)
GetConflictingAlts() *BitSet
SetConflictingAlts(*BitSet)
FullContext() bool
GetUniqueAlt() int
SetUniqueAlt(int)
GetDipsIntoOuterContext() bool
SetDipsIntoOuterContext(bool)
}
// Specialized {@link Set}{@code <}{@link ATNConfig}{@code >} that can track
// info about the set, with support for combining similar configurations using a
// graph-structured stack.
///
func hashATNConfig(c interface{}) string {
return c.(IATNConfig).shortHash()
}
func equalATNConfigs(a, b interface{}) bool {
if a == nil || b == nil {
return false
}
if a == b {
return true
}
ai,ok := a.(IATNConfig)
bi,ok1 := b.(IATNConfig)
if (!ok || !ok1) {
return false
}
return ai.GetState().GetStateNumber() == bi.GetState().GetStateNumber() &&
ai.GetAlt() == bi.GetAlt() &&
ai.GetSemanticContext().equals(bi.GetSemanticContext())
}
type ATNConfigSet struct {
type BaseATNConfigSet struct {
readOnly bool
fullCtx bool
configLookup *Set
conflictingAlts *BitSet
cachedHashString string
hasSemanticContext bool``
hasSemanticContext bool
dipsIntoOuterContext bool
configs []IATNConfig
configs []ATNConfig
uniqueAlt int
}
func NewATNConfigSet(fullCtx bool) *ATNConfigSet {
func NewBaseATNConfigSet(fullCtx bool) *BaseATNConfigSet {
a := new(ATNConfigSet)
a := new(BaseATNConfigSet)
// The reason that we need a.is because we don't want the hash map to use
// the standard hash code and equals. We need all configurations with the
@ -75,7 +85,7 @@ func NewATNConfigSet(fullCtx bool) *ATNConfigSet {
// we've made a.readonly.
a.readOnly = false
// Track the elements as they are added to the set supports Get(i)///
a.configs = make([]IATNConfig, 0)
a.configs = make([]ATNConfig, 0)
// TODO: these fields make me pretty uncomfortable but nice to pack up info
// together, saves recomputation
@ -103,7 +113,7 @@ func NewATNConfigSet(fullCtx bool) *ATNConfigSet {
// <p>This method updates {@link //dipsIntoOuterContext} and
// {@link //hasSemanticContext} when necessary.</p>
// /
func (this *ATNConfigSet) add(config IATNConfig, mergeCache *DoubleDict) bool {
func (this *BaseATNConfigSet) Add(config ATNConfig, mergeCache *DoubleDict) bool {
if this.readOnly {
panic("This set is readonly")
@ -114,7 +124,7 @@ func (this *ATNConfigSet) add(config IATNConfig, mergeCache *DoubleDict) bool {
if config.GetReachesIntoOuterContext() > 0 {
this.dipsIntoOuterContext = true
}
var existing = this.configLookup.add(config).(IATNConfig)
var existing = this.configLookup.add(config).(ATNConfig)
if existing == config {
this.cachedHashString = "-1"
this.configs = append(this.configs, config) // track order here
@ -136,7 +146,7 @@ func (this *ATNConfigSet) add(config IATNConfig, mergeCache *DoubleDict) bool {
return true
}
func (this *ATNConfigSet) GetStates() *Set {
func (this *BaseATNConfigSet) GetStates() *Set {
var states = NewSet(nil, nil)
for i := 0; i < len(this.configs); i++ {
states.add(this.configs[i].GetState())
@ -144,7 +154,15 @@ func (this *ATNConfigSet) GetStates() *Set {
return states
}
func (this *ATNConfigSet) getPredicates() []SemanticContext {
func (this *BaseATNConfigSet) HasSemanticContext() bool {
return this.hasSemanticContext
}
func (this *BaseATNConfigSet) SetHasSemanticContext(v bool) {
this.hasSemanticContext = v
}
func (this *BaseATNConfigSet) GetPredicates() []SemanticContext {
var preds = make([]SemanticContext, 0)
for i := 0; i < len(this.configs); i++ {
c := this.configs[i].GetSemanticContext()
@ -155,11 +173,11 @@ func (this *ATNConfigSet) getPredicates() []SemanticContext {
return preds
}
func (this *ATNConfigSet) getItems() []IATNConfig {
func (this *BaseATNConfigSet) GetItems() []ATNConfig {
return this.configs
}
func (this *ATNConfigSet) optimizeConfigs(interpreter *ATNSimulator) {
func (this *BaseATNConfigSet) OptimizeConfigs(interpreter *ATNSimulator) {
if this.readOnly {
panic("This set is readonly")
}
@ -172,32 +190,32 @@ func (this *ATNConfigSet) optimizeConfigs(interpreter *ATNSimulator) {
}
}
func (this *ATNConfigSet) addAll(coll []*ATNConfig) bool {
func (this *BaseATNConfigSet) 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 {
func (this *BaseATNConfigSet) Equals(other interface{}) bool {
if this == other {
return true
} else if _, ok := other.(*ATNConfigSet); !ok {
} else if _, ok := other.(*BaseATNConfigSet); !ok {
return false
}
other2 := other.(*ATNConfigSet)
other2 := other.(*BaseATNConfigSet)
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) Hash() string {
func (this *BaseATNConfigSet) Hash() string {
if this.readOnly {
if this.cachedHashString == "-1" {
this.cachedHashString = this.hashConfigs()
@ -208,7 +226,7 @@ func (this *ATNConfigSet) Hash() string {
}
}
func (this *ATNConfigSet) hashConfigs() string {
func (this *BaseATNConfigSet) hashConfigs() string {
var s = ""
for _, c := range this.configs {
s += fmt.Sprint(c)
@ -216,45 +234,77 @@ func (this *ATNConfigSet) hashConfigs() string {
return s
}
func (this *ATNConfigSet) length() int {
func (this *BaseATNConfigSet) Length() int {
return len(this.configs)
}
func (this *ATNConfigSet) isEmpty() bool {
func (this *BaseATNConfigSet) IsEmpty() bool {
return len(this.configs) == 0
}
func (this *ATNConfigSet) contains(item *ATNConfig) bool {
func (this *BaseATNConfigSet) Contains(item *BaseATNConfig) 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 {
func (this *BaseATNConfigSet) ContainsFast(item *BaseATNConfig) 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() {
func (this *BaseATNConfigSet) Clear() {
if this.readOnly {
panic("This set is readonly")
}
this.configs = make([]IATNConfig, 0)
this.configs = make([]ATNConfig, 0)
this.cachedHashString = "-1"
this.configLookup = NewSet(hashATNConfig, equalATNConfigs)
}
func (this *ATNConfigSet) setReadonly(readOnly bool) {
func (this *BaseATNConfigSet) FullContext() bool {
return this.fullCtx
}
func (this *BaseATNConfigSet) GetDipsIntoOuterContext() bool {
return this.dipsIntoOuterContext
}
func (this *BaseATNConfigSet) SetDipsIntoOuterContext(v bool) {
this.dipsIntoOuterContext = v
}
func (this *BaseATNConfigSet) GetUniqueAlt() int {
return this.uniqueAlt
}
func (this *BaseATNConfigSet) SetUniqueAlt(v int) {
this.uniqueAlt = v
}
func (this *BaseATNConfigSet) GetConflictingAlts() *BitSet {
return this.conflictingAlts
}
func (this *BaseATNConfigSet) SetConflictingAlts(v *BitSet) {
this.conflictingAlts = v
}
func (this *BaseATNConfigSet) ReadOnly() bool {
return this.readOnly
}
func (this *BaseATNConfigSet) SetReadOnly(readOnly bool) {
this.readOnly = readOnly
if readOnly {
this.configLookup = nil // can't mod, no need for lookup cache
}
}
func (this *ATNConfigSet) String() string {
func (this *BaseATNConfigSet) String() string {
s := "["
for i,c := range this.configs {
@ -289,15 +339,42 @@ func (this *ATNConfigSet) String() string {
type OrderedATNConfigSet struct {
*ATNConfigSet
*BaseATNConfigSet
}
func NewOrderedATNConfigSet() *OrderedATNConfigSet {
this := new(OrderedATNConfigSet)
this.ATNConfigSet = NewATNConfigSet(false)
// this.configLookup = NewSet(nil, nil) // TODO not sure why this would be overriden
this.BaseATNConfigSet = NewBaseATNConfigSet(false)
// this.configLookup = NewSet(nil, nil) // TODO not sure why this would be overriden
return this
}
func hashATNConfig(c interface{}) string {
return c.(ATNConfig).shortHash()
}
func equalATNConfigs(a, b interface{}) bool {
if a == nil || b == nil {
return false
}
if a == b {
return true
}
ai,ok := a.(ATNConfig)
bi,ok1 := b.(ATNConfig)
if (!ok || !ok1) {
return false
}
return ai.GetState().GetStateNumber() == bi.GetState().GetStateNumber() &&
ai.GetAlt() == bi.GetAlt() &&
ai.GetSemanticContext().equals(bi.GetSemanticContext())
}

View File

@ -15,7 +15,7 @@ func NewATNSimulator(atn *ATN, sharedContextCache *PredictionContextCache) *ATNS
return this
}
var ATNSimulatorERROR = NewDFAState(0x7FFFFFFF, NewATNConfigSet(false))
var ATNSimulatorERROR = NewDFAState(0x7FFFFFFF, NewBaseATNConfigSet(false))
func (this *ATNSimulator) getCachedContext(context IPredictionContext) IPredictionContext {
if this.sharedContextCache == nil {

View File

@ -92,7 +92,7 @@ func (this *DFA) setPrecedenceDfa(precedenceDfa bool) {
if this.precedenceDfa != precedenceDfa {
this._states = make(map[string]*DFAState)
if precedenceDfa {
var precedenceState = NewDFAState(-1, NewATNConfigSet(false))
var precedenceState = NewDFAState(-1, NewBaseATNConfigSet(false))
precedenceState.edges = make([]*DFAState, 0)
precedenceState.isAcceptState = false
precedenceState.requiresFullContext = false

View File

@ -52,7 +52,7 @@ func (this *PredPrediction) String() string {
type DFAState struct {
stateNumber int
configs *ATNConfigSet
configs ATNConfigSet
edges []*DFAState
isAcceptState bool
prediction int
@ -61,10 +61,10 @@ type DFAState struct {
predicates []*PredPrediction
}
func NewDFAState(stateNumber int, configs *ATNConfigSet) *DFAState {
func NewDFAState(stateNumber int, configs ATNConfigSet) *DFAState {
if configs == nil {
configs = NewATNConfigSet(false)
configs = NewBaseATNConfigSet(false)
}
this := new(DFAState)
@ -109,8 +109,7 @@ func NewDFAState(stateNumber int, configs *ATNConfigSet) *DFAState {
func (this *DFAState) GetAltSet() *Set {
var alts = NewSet(nil, nil)
if this.configs != nil {
for i := 0; i < len(this.configs.configs); i++ {
var c = this.configs.configs[i]
for _,c := range this.configs.GetItems() {
alts.add(c.GetAlt())
}
}
@ -145,7 +144,7 @@ func (this *DFAState) equals(other interface{}) bool {
return false
}
return this.configs.equals(other.(*DFAState).configs)
return this.configs.Equals(other.(*DFAState).configs)
}
func (this *DFAState) String() string {

View File

@ -38,7 +38,7 @@ func NewDiagnosticErrorListener(exactOnly bool) *DiagnosticErrorListener {
return n
}
func (this *DiagnosticErrorListener) ReportAmbiguity(recognizer *Parser, dfa *DFA, startIndex, stopIndex int, exact bool, ambigAlts *BitSet, configs *ATNConfigSet) {
func (this *DiagnosticErrorListener) ReportAmbiguity(recognizer *BaseParser, dfa *DFA, startIndex, stopIndex int, exact bool, ambigAlts *BitSet, configs ATNConfigSet) {
if this.exactOnly && !exact {
return
}
@ -51,7 +51,7 @@ func (this *DiagnosticErrorListener) ReportAmbiguity(recognizer *Parser, dfa *DF
recognizer.NotifyErrorListeners(msg, nil, nil)
}
func (this *DiagnosticErrorListener) ReportAttemptingFullContext(recognizer *Parser, dfa *DFA, startIndex, stopIndex int, conflictingAlts *BitSet, configs *ATNConfigSet) {
func (this *DiagnosticErrorListener) ReportAttemptingFullContext(recognizer *BaseParser, dfa *DFA, startIndex, stopIndex int, conflictingAlts *BitSet, configs ATNConfigSet) {
var msg = "ReportAttemptingFullContext d=" +
this.getDecisionDescription(recognizer, dfa) +
@ -60,7 +60,7 @@ func (this *DiagnosticErrorListener) ReportAttemptingFullContext(recognizer *Par
recognizer.NotifyErrorListeners(msg, nil, nil)
}
func (this *DiagnosticErrorListener) ReportContextSensitivity(recognizer *Parser, dfa *DFA, startIndex, stopIndex, prediction int, configs *ATNConfigSet) {
func (this *DiagnosticErrorListener) ReportContextSensitivity(recognizer *BaseParser, dfa *DFA, startIndex, stopIndex, prediction int, configs ATNConfigSet) {
var msg = "ReportContextSensitivity d=" +
this.getDecisionDescription(recognizer, dfa) +
", input='" +
@ -68,7 +68,7 @@ func (this *DiagnosticErrorListener) ReportContextSensitivity(recognizer *Parser
recognizer.NotifyErrorListeners(msg, nil, nil)
}
func (this *DiagnosticErrorListener) getDecisionDescription(recognizer *Parser, dfa *DFA) string {
func (this *DiagnosticErrorListener) getDecisionDescription(recognizer *BaseParser, dfa *DFA) string {
var decision = dfa.decision
var ruleIndex = dfa.atnStartState.GetRuleIndex()
@ -94,21 +94,14 @@ func (this *DiagnosticErrorListener) getDecisionDescription(recognizer *Parser,
// @return Returns {@code ReportedAlts} if it is not {@code nil}, otherwise
// returns the set of alternatives represented in {@code configs}.
//
func (this *DiagnosticErrorListener) getConflictingAlts(ReportedAlts *BitSet, set *ATNConfigSet) *BitSet {
func (this *DiagnosticErrorListener) getConflictingAlts(ReportedAlts *BitSet, set ATNConfigSet) *BitSet {
if ReportedAlts != nil {
return ReportedAlts
}
var result = NewBitSet()
for i := 0; i < len(set.configs); i++ {
result.add(set.configs[i].GetAlt())
for _,c := range set.GetItems() {
result.add(c.GetAlt())
}
return result
// valuestrings := make([]string, len(result.values()))
// for i,v := range result.values() {
// valuestrings[i] = strconv.Itoa(v)
// }
//
// return "{" + strings.Join(valuestrings, ", ") + "}"
}

View File

@ -10,10 +10,10 @@ import (
// necessary.
type IErrorListener interface {
SyntaxError(recognizer IRecognizer, offendingSymbol interface{}, line, column int, msg string, e IRecognitionException)
ReportAmbiguity(recognizer IParser, dfa *DFA, startIndex, stopIndex int, exact bool, ambigAlts *BitSet, configs *ATNConfigSet)
ReportAttemptingFullContext(recognizer IParser, dfa *DFA, startIndex, stopIndex int, conflictingAlts *BitSet, configs *ATNConfigSet)
ReportContextSensitivity(recognizer IParser, dfa *DFA, startIndex, stopIndex, prediction int, configs *ATNConfigSet)
SyntaxError(recognizer Recognizer, offendingSymbol interface{}, line, column int, msg string, e IRecognitionException)
ReportAmbiguity(recognizer Parser, dfa *DFA, startIndex, stopIndex int, exact bool, ambigAlts *BitSet, configs ATNConfigSet)
ReportAttemptingFullContext(recognizer Parser, dfa *DFA, startIndex, stopIndex int, conflictingAlts *BitSet, configs ATNConfigSet)
ReportContextSensitivity(recognizer Parser, dfa *DFA, startIndex, stopIndex, prediction int, configs ATNConfigSet)
}
type DefaultErrorListener struct {
@ -23,25 +23,25 @@ func NewDefaultErrorListener() *DefaultErrorListener {
return new(DefaultErrorListener)
}
func (this *DefaultErrorListener) SyntaxError(recognizer IRecognizer, offendingSymbol interface{}, line, column int, msg string, e IRecognitionException) {
func (this *DefaultErrorListener) SyntaxError(recognizer Recognizer, offendingSymbol interface{}, line, column int, msg string, e IRecognitionException) {
if PortDebug {
fmt.Println("SyntaxError!")
}
}
func (this *DefaultErrorListener) ReportAmbiguity(recognizer IParser, dfa *DFA, startIndex, stopIndex int, exact bool, ambigAlts *BitSet, configs *ATNConfigSet) {
func (this *DefaultErrorListener) ReportAmbiguity(recognizer Parser, dfa *DFA, startIndex, stopIndex int, exact bool, ambigAlts *BitSet, configs ATNConfigSet) {
if PortDebug {
fmt.Println("ReportAmbiguity!")
}
}
func (this *DefaultErrorListener) ReportAttemptingFullContext(recognizer IParser, dfa *DFA, startIndex, stopIndex int, conflictingAlts *BitSet, configs *ATNConfigSet) {
func (this *DefaultErrorListener) ReportAttemptingFullContext(recognizer Parser, dfa *DFA, startIndex, stopIndex int, conflictingAlts *BitSet, configs ATNConfigSet) {
if PortDebug {
fmt.Println("ReportAttemptingFullContext!")
}
}
func (this *DefaultErrorListener) ReportContextSensitivity(recognizer IParser, dfa *DFA, startIndex, stopIndex, prediction int, configs *ATNConfigSet) {
func (this *DefaultErrorListener) ReportContextSensitivity(recognizer Parser, dfa *DFA, startIndex, stopIndex, prediction int, configs ATNConfigSet) {
if PortDebug {
fmt.Println("ReportContextSensitivity!")
}
@ -72,7 +72,7 @@ var ConsoleErrorListenerINSTANCE = NewConsoleErrorListener()
// line <em>line</em>:<em>charPositionInLine</em> <em>msg</em>
// </pre>
//
func (this *ConsoleErrorListener) SyntaxError(recognizer IRecognizer, offendingSymbol interface{}, line, column int, msg string, e IRecognitionException) {
func (this *ConsoleErrorListener) SyntaxError(recognizer Recognizer, offendingSymbol interface{}, line, column int, msg string, e IRecognitionException) {
fmt.Println("line " + strconv.Itoa(line) + ":" + strconv.Itoa(column) + " " + msg)
}
@ -90,25 +90,25 @@ func NewProxyErrorListener(delegates []IErrorListener) *ProxyErrorListener {
return l
}
func (this *ProxyErrorListener) SyntaxError(recognizer IRecognizer, offendingSymbol interface{}, line, column int, msg string, e IRecognitionException) {
func (this *ProxyErrorListener) SyntaxError(recognizer Recognizer, offendingSymbol interface{}, line, column int, msg string, e IRecognitionException) {
for _, d := range this.delegates {
d.SyntaxError(recognizer, offendingSymbol, line, column, msg, e)
}
}
func (this *ProxyErrorListener) ReportAmbiguity(recognizer IParser, dfa *DFA, startIndex, stopIndex int, exact bool, ambigAlts *BitSet, configs *ATNConfigSet) {
func (this *ProxyErrorListener) ReportAmbiguity(recognizer Parser, dfa *DFA, startIndex, stopIndex int, exact bool, ambigAlts *BitSet, configs ATNConfigSet) {
for _, d := range this.delegates {
d.ReportAmbiguity(recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs)
}
}
func (this *ProxyErrorListener) ReportAttemptingFullContext(recognizer IParser, dfa *DFA, startIndex, stopIndex int, conflictingAlts *BitSet, configs *ATNConfigSet) {
func (this *ProxyErrorListener) ReportAttemptingFullContext(recognizer Parser, dfa *DFA, startIndex, stopIndex int, conflictingAlts *BitSet, configs ATNConfigSet) {
for _, d := range this.delegates {
d.ReportAttemptingFullContext(recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs)
}
}
func (this *ProxyErrorListener) ReportContextSensitivity(recognizer IParser, dfa *DFA, startIndex, stopIndex, prediction int, configs *ATNConfigSet) {
func (this *ProxyErrorListener) ReportContextSensitivity(recognizer Parser, dfa *DFA, startIndex, stopIndex, prediction int, configs ATNConfigSet) {
for _, d := range this.delegates {
d.ReportContextSensitivity(recognizer, dfa, startIndex, stopIndex, prediction, configs)
}

View File

@ -8,13 +8,13 @@ import (
)
type IErrorStrategy interface {
reset(IParser)
RecoverInline(IParser) IToken
Recover(IParser, IRecognitionException)
Sync(IParser)
inErrorRecoveryMode(IParser) bool
ReportError(IParser, IRecognitionException)
ReportMatch(IParser)
reset(Parser)
RecoverInline(Parser) IToken
Recover(Parser, IRecognitionException)
Sync(Parser)
inErrorRecoveryMode(Parser) bool
ReportError(Parser, IRecognitionException)
ReportMatch(Parser)
}
// This is the default implementation of {@link ANTLRErrorStrategy} used for
@ -52,7 +52,7 @@ func NewDefaultErrorStrategy() *DefaultErrorStrategy {
// <p>The default implementation simply calls {@link //endErrorCondition} to
// ensure that the handler is not in error recovery mode.</p>
func (this *DefaultErrorStrategy) reset(recognizer IParser) {
func (this *DefaultErrorStrategy) reset(recognizer Parser) {
this.endErrorCondition(recognizer)
}
@ -62,11 +62,11 @@ func (this *DefaultErrorStrategy) reset(recognizer IParser) {
//
// @param recognizer the parser instance
//
func (this *DefaultErrorStrategy) beginErrorCondition(recognizer IParser) {
func (this *DefaultErrorStrategy) beginErrorCondition(recognizer Parser) {
this.errorRecoveryMode = true
}
func (this *DefaultErrorStrategy) inErrorRecoveryMode(recognizer IParser) bool {
func (this *DefaultErrorStrategy) inErrorRecoveryMode(recognizer Parser) bool {
return this.errorRecoveryMode
}
@ -76,7 +76,7 @@ func (this *DefaultErrorStrategy) inErrorRecoveryMode(recognizer IParser) bool {
//
// @param recognizer
//
func (this *DefaultErrorStrategy) endErrorCondition(recognizer IParser) {
func (this *DefaultErrorStrategy) endErrorCondition(recognizer Parser) {
this.errorRecoveryMode = false
this.lastErrorStates = nil
this.lastErrorIndex = -1
@ -87,7 +87,7 @@ func (this *DefaultErrorStrategy) endErrorCondition(recognizer IParser) {
//
// <p>The default implementation simply calls {@link //endErrorCondition}.</p>
//
func (this *DefaultErrorStrategy) ReportMatch(recognizer IParser) {
func (this *DefaultErrorStrategy) ReportMatch(recognizer Parser) {
this.endErrorCondition(recognizer)
}
@ -110,7 +110,7 @@ func (this *DefaultErrorStrategy) ReportMatch(recognizer IParser) {
// the exception</li>
// </ul>
//
func (this *DefaultErrorStrategy) ReportError(recognizer IParser, e IRecognitionException) {
func (this *DefaultErrorStrategy) ReportError(recognizer Parser, 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) {
@ -139,7 +139,7 @@ func (this *DefaultErrorStrategy) ReportError(recognizer IParser, e IRecognition
// until we find one in the reSynchronization set--loosely the set of tokens
// that can follow the current rule.</p>
//
func (this *DefaultErrorStrategy) Recover(recognizer IParser, e IRecognitionException) {
func (this *DefaultErrorStrategy) Recover(recognizer Parser, e IRecognitionException) {
if this.lastErrorIndex == recognizer.GetInputStream().Index() &&
this.lastErrorStates != nil && this.lastErrorStates.contains(recognizer.GetState()) {
@ -203,7 +203,7 @@ func (this *DefaultErrorStrategy) Recover(recognizer IParser, e IRecognitionExce
// some reason speed is suffering for you, you can turn off this
// functionality by simply overriding this method as a blank { }.</p>
//
func (this *DefaultErrorStrategy) Sync(recognizer IParser) {
func (this *DefaultErrorStrategy) Sync(recognizer Parser) {
// If already recovering, don't try to Sync
if this.inErrorRecoveryMode(recognizer) {
return
@ -275,7 +275,7 @@ func (this *DefaultErrorStrategy) Sync(recognizer IParser) {
// @param recognizer the parser instance
// @param e the recognition exception
//
func (this *DefaultErrorStrategy) ReportNoViableAlternative(recognizer IParser, e *NoViableAltException) {
func (this *DefaultErrorStrategy) ReportNoViableAlternative(recognizer Parser, e *NoViableAltException) {
var tokens = recognizer.GetTokenStream()
var input string
if tokens != nil {
@ -300,7 +300,7 @@ func (this *DefaultErrorStrategy) ReportNoViableAlternative(recognizer IParser,
// @param recognizer the parser instance
// @param e the recognition exception
//
func (this *DefaultErrorStrategy) ReportInputMisMatch(recognizer IParser, e *InputMisMatchException) {
func (this *DefaultErrorStrategy) ReportInputMisMatch(recognizer Parser, e *InputMisMatchException) {
var msg = "misMatched input " + this.GetTokenErrorDisplay(e.offendingToken) +
" expecting " + e.getExpectedTokens().StringVerbose(recognizer.GetLiteralNames(), recognizer.GetSymbolicNames(), false)
panic(msg)
@ -316,7 +316,7 @@ func (this *DefaultErrorStrategy) ReportInputMisMatch(recognizer IParser, e *Inp
// @param recognizer the parser instance
// @param e the recognition exception
//
func (this *DefaultErrorStrategy) ReportFailedPredicate(recognizer IParser, e *FailedPredicateException) {
func (this *DefaultErrorStrategy) ReportFailedPredicate(recognizer Parser, e *FailedPredicateException) {
var ruleName = recognizer.GetRuleNames()[recognizer.GetParserRuleContext().GetRuleIndex()]
var msg = "rule " + ruleName + " " + e.message
recognizer.NotifyErrorListeners(msg, e.offendingToken, e)
@ -339,7 +339,7 @@ func (this *DefaultErrorStrategy) ReportFailedPredicate(recognizer IParser, e *F
//
// @param recognizer the parser instance
//
func (this *DefaultErrorStrategy) ReportUnwantedToken(recognizer IParser) {
func (this *DefaultErrorStrategy) ReportUnwantedToken(recognizer Parser) {
if this.inErrorRecoveryMode(recognizer) {
return
}
@ -369,7 +369,7 @@ func (this *DefaultErrorStrategy) ReportUnwantedToken(recognizer IParser) {
//
// @param recognizer the parser instance
//
func (this *DefaultErrorStrategy) ReportMissingToken(recognizer IParser) {
func (this *DefaultErrorStrategy) ReportMissingToken(recognizer Parser) {
if this.inErrorRecoveryMode(recognizer) {
return
}
@ -430,7 +430,7 @@ func (this *DefaultErrorStrategy) ReportMissingToken(recognizer IParser) {
// is in the set of tokens that can follow the {@code ')'} token reference
// in rule {@code atom}. It can assume that you forgot the {@code ')'}.
//
func (this *DefaultErrorStrategy) RecoverInline(recognizer IParser) IToken {
func (this *DefaultErrorStrategy) RecoverInline(recognizer Parser) IToken {
// SINGLE TOKEN DELETION
var MatchedSymbol = this.singleTokenDeletion(recognizer)
if MatchedSymbol != nil {
@ -464,7 +464,7 @@ func (this *DefaultErrorStrategy) RecoverInline(recognizer IParser) IToken {
// @return {@code true} if single-token insertion is a viable recovery
// strategy for the current misMatched input, otherwise {@code false}
//
func (this *DefaultErrorStrategy) singleTokenInsertion(recognizer IParser) bool {
func (this *DefaultErrorStrategy) singleTokenInsertion(recognizer Parser) 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
@ -499,7 +499,7 @@ func (this *DefaultErrorStrategy) singleTokenInsertion(recognizer IParser) bool
// deletion successfully recovers from the misMatched input, otherwise
// {@code nil}
//
func (this *DefaultErrorStrategy) singleTokenDeletion(recognizer IParser) IToken {
func (this *DefaultErrorStrategy) singleTokenDeletion(recognizer Parser) IToken {
var nextTokenType = recognizer.GetTokenStream().LA(2)
var expecting = this.getExpectedTokens(recognizer)
if expecting.contains(nextTokenType) {
@ -537,7 +537,7 @@ func (this *DefaultErrorStrategy) singleTokenDeletion(recognizer IParser) IToken
// If you change what tokens must be created by the lexer,
// override this method to create the appropriate tokens.
//
func (this *DefaultErrorStrategy) getMissingSymbol(recognizer IParser) IToken {
func (this *DefaultErrorStrategy) getMissingSymbol(recognizer Parser) IToken {
var currentSymbol = recognizer.getCurrentToken()
var expecting = this.getExpectedTokens(recognizer)
var expectedTokenType = expecting.first()
@ -561,7 +561,7 @@ func (this *DefaultErrorStrategy) getMissingSymbol(recognizer IParser) IToken {
return tf.Create( current.GetSource(), expectedTokenType, tokenText, TokenDefaultChannel, -1, -1, current.GetLine(), current.GetColumn())
}
func (this *DefaultErrorStrategy) getExpectedTokens(recognizer IParser) *IntervalSet {
func (this *DefaultErrorStrategy) getExpectedTokens(recognizer Parser) *IntervalSet {
return recognizer.getExpectedTokens()
}
@ -687,7 +687,7 @@ func (this *DefaultErrorStrategy) escapeWSAndQuote(s string) string {
// Like Grosch I implement context-sensitive FOLLOW sets that are combined
// at run-time upon error to avoid overhead during parsing.
//
func (this *DefaultErrorStrategy) getErrorRecoverySet(recognizer IParser) *IntervalSet {
func (this *DefaultErrorStrategy) getErrorRecoverySet(recognizer Parser) *IntervalSet {
var atn = recognizer.GetInterpreter().atn
var ctx = recognizer.GetParserRuleContext()
var recoverSet = NewIntervalSet()
@ -704,7 +704,7 @@ func (this *DefaultErrorStrategy) getErrorRecoverySet(recognizer IParser) *Inter
}
// Consume tokens until one Matches the given token set.//
func (this *DefaultErrorStrategy) consumeUntil(recognizer IParser, set *IntervalSet) {
func (this *DefaultErrorStrategy) consumeUntil(recognizer Parser, set *IntervalSet) {
var ttype = recognizer.GetTokenStream().LA(1)
for ttype != TokenEOF && !set.contains(ttype) {
recognizer.Consume()
@ -758,7 +758,7 @@ func NewBailErrorStrategy() *BailErrorStrategy {
// rule func catches. Use {@link Exception//getCause()} to get the
// original {@link RecognitionException}.
//
func (this *BailErrorStrategy) Recover(recognizer IParser, e IRecognitionException) {
func (this *BailErrorStrategy) Recover(recognizer Parser, e IRecognitionException) {
var context = recognizer.GetParserRuleContext()
for context != nil {
context.SetException(e)
@ -770,11 +770,11 @@ func (this *BailErrorStrategy) Recover(recognizer IParser, e IRecognitionExcepti
// Make sure we don't attempt to recover inline if the parser
// successfully recovers, it won't panic an exception.
//
func (this *BailErrorStrategy) RecoverInline(recognizer IParser) {
func (this *BailErrorStrategy) RecoverInline(recognizer Parser) {
this.Recover(recognizer, NewInputMisMatchException(recognizer))
}
// Make sure we don't attempt to recover from problems in subrules.//
func (this *BailErrorStrategy) Sync(recognizer IParser) {
func (this *BailErrorStrategy) Sync(recognizer Parser) {
// pass
}

View File

@ -16,14 +16,14 @@ type IRecognitionException interface {
type RecognitionException struct {
message string
recognizer IRecognizer
recognizer Recognizer
offendingToken IToken
offendingState int
ctx IRuleContext
input IntStream
}
func NewRecognitionException(message string, recognizer IRecognizer, input IntStream, ctx IRuleContext) *RecognitionException {
func NewRecognitionException(message string, recognizer Recognizer, input IntStream, ctx IRuleContext) *RecognitionException {
// todo
// Error.call(this)
@ -98,10 +98,10 @@ type LexerNoViableAltException struct {
*RecognitionException
startIndex int
deadEndConfigs *ATNConfigSet
deadEndConfigs ATNConfigSet
}
func NewLexerNoViableAltException(lexer ILexer, input CharStream, startIndex int, deadEndConfigs *ATNConfigSet) *LexerNoViableAltException {
func NewLexerNoViableAltException(lexer ILexer, input CharStream, startIndex int, deadEndConfigs ATNConfigSet) *LexerNoViableAltException {
this := new(LexerNoViableAltException)
@ -127,7 +127,7 @@ type NoViableAltException struct {
startToken IToken
offendingToken IToken
ctx IParserRuleContext
deadEndConfigs *ATNConfigSet
deadEndConfigs ATNConfigSet
}
// Indicates that the parser could not decide which of two or more paths
@ -135,7 +135,7 @@ type NoViableAltException struct {
// of the offending input and also knows where the parser was
// in the various paths when the error. Reported by ReportNoViableAlternative()
//
func NewNoViableAltException(recognizer IParser, input TokenStream, startToken IToken, offendingToken IToken, deadEndConfigs *ATNConfigSet, ctx IParserRuleContext) *NoViableAltException {
func NewNoViableAltException(recognizer Parser, input TokenStream, startToken IToken, offendingToken IToken, deadEndConfigs ATNConfigSet, ctx IParserRuleContext) *NoViableAltException {
if ctx == nil {
ctx = recognizer.GetParserRuleContext()
@ -176,7 +176,7 @@ type InputMisMatchException struct {
// This signifies any kind of misMatched input exceptions such as
// when the current input does not Match the expected token.
//
func NewInputMisMatchException(recognizer IParser) *InputMisMatchException {
func NewInputMisMatchException(recognizer Parser) *InputMisMatchException {
this := new(InputMisMatchException)
this.RecognitionException = NewRecognitionException("", recognizer, recognizer.GetInputStream(), recognizer.GetParserRuleContext())
@ -200,7 +200,7 @@ type FailedPredicateException struct {
predicate string
}
func NewFailedPredicateException(recognizer *Parser, predicate string, message string) *FailedPredicateException {
func NewFailedPredicateException(recognizer *BaseParser, predicate string, message string) *FailedPredicateException {
this := new(FailedPredicateException)

View File

@ -13,7 +13,7 @@ import (
type ILexer interface {
TokenSource
IRecognizer
Recognizer
setChannel(int)
pushMode(int)
@ -23,7 +23,7 @@ type ILexer interface {
}
type Lexer struct {
*Recognizer
*BaseRecognizer
Interpreter *LexerATNSimulator
@ -47,7 +47,7 @@ func NewLexer(input CharStream) *Lexer {
lexer := new(Lexer)
lexer.Recognizer = NewRecognizer()
lexer.BaseRecognizer = NewBaseRecognizer()
lexer._input = input
lexer._factory = CommonTokenFactoryDEFAULT

View File

@ -157,7 +157,7 @@ func (this *LexerATNSimulator) MatchATN(input CharStream) int {
var suppressEdge = s0_closure.hasSemanticContext
s0_closure.hasSemanticContext = false
var next = this.addDFAState(s0_closure.ATNConfigSet)
var next = this.addDFAState(s0_closure.BaseATNConfigSet)
if !suppressEdge {
this.decisionToDFA[this.mode].s0 = next
@ -276,7 +276,7 @@ func (this *LexerATNSimulator) computeTargetState(input CharStream, s *DFAState,
var reach = NewOrderedATNConfigSet()
// if we don't find an existing DFA state
// Fill reach starting from closure, following t transitions
this.getReachableConfigSet(input, s.configs, reach.ATNConfigSet, t)
this.getReachableConfigSet(input, s.configs, reach.BaseATNConfigSet, t)
if len(reach.configs) == 0 { // we got nowhere on t from s
if !reach.hasSemanticContext {
@ -288,10 +288,10 @@ func (this *LexerATNSimulator) computeTargetState(input CharStream, s *DFAState,
return ATNSimulatorERROR
}
// Add an edge from s to target DFA found/created for reach
return this.addDFAEdge(s, t, nil, reach.ATNConfigSet)
return this.addDFAEdge(s, t, nil, reach.BaseATNConfigSet)
}
func (this *LexerATNSimulator) failOrAccept(prevAccept *SimState, input CharStream, reach *ATNConfigSet, t int) int {
func (this *LexerATNSimulator) failOrAccept(prevAccept *SimState, input CharStream, reach ATNConfigSet, t int) int {
if this.prevAccept.dfaState != nil {
var lexerActionExecutor = prevAccept.dfaState.lexerActionExecutor
this.accept(input, lexerActionExecutor, this.startIndex, prevAccept.index, prevAccept.line, prevAccept.column)
@ -312,12 +312,11 @@ func (this *LexerATNSimulator) failOrAccept(prevAccept *SimState, input CharStre
// Given a starting configuration set, figure out all ATN configurations
// we can reach upon input {@code t}. Parameter {@code reach} is a return
// parameter.
func (this *LexerATNSimulator) getReachableConfigSet(input CharStream, closure *ATNConfigSet, reach *ATNConfigSet, t int) {
func (this *LexerATNSimulator) getReachableConfigSet(input CharStream, closure ATNConfigSet, reach ATNConfigSet, t int) {
// this is used to skip processing for configs which have a lower priority
// than a config that already reached an accept state for the same rule
var skipAlt = ATNINVALID_ALT_NUMBER
for i := 0; i < len(closure.configs); i++ {
var cfg = closure.configs[i]
for _, cfg := range closure.GetItems() {
var currentAltReachedAcceptState = (cfg.GetAlt() == skipAlt)
if currentAltReachedAcceptState && cfg.(*LexerATNConfig).passedThroughNonGreedyDecision {
continue
@ -325,8 +324,7 @@ func (this *LexerATNSimulator) getReachableConfigSet(input CharStream, closure *
if LexerATNSimulatorDebug {
fmt.Printf("testing %s at %s\n", this.GetTokenName(t), cfg.String()) // this.recog, true))
}
for j := 0; j < len(cfg.GetState().GetTransitions()); j++ {
var trans = cfg.GetState().GetTransitions()[j] // for each transition
for _, trans := range cfg.GetState().GetTransitions() {
var target = this.getReachableTarget(trans, t)
if target != nil {
var lexerActionExecutor = cfg.(*LexerATNConfig).lexerActionExecutor
@ -377,7 +375,7 @@ func (this *LexerATNSimulator) computeStartState(input CharStream, p IATNState)
for i := 0; i < len(p.GetTransitions()); i++ {
var target = p.GetTransitions()[i].getTarget()
var cfg = NewLexerATNConfig6(target, i+1, PredictionContextEMPTY)
this.closure(input, cfg, configs.ATNConfigSet, false, false, false)
this.closure(input, cfg, configs.BaseATNConfigSet, false, false, false)
}
if PortDebug {
@ -395,7 +393,7 @@ func (this *LexerATNSimulator) computeStartState(input CharStream, p IATNState)
//
// @return {@code true} if an accept state is reached, otherwise
// {@code false}.
func (this *LexerATNSimulator) closure(input CharStream, config *LexerATNConfig, configs *ATNConfigSet,
func (this *LexerATNSimulator) closure(input CharStream, config *LexerATNConfig, configs ATNConfigSet,
currentAltReachedAcceptState, speculative, treatEofAsEpsilon bool) bool {
if LexerATNSimulatorDebug {
@ -415,10 +413,10 @@ func (this *LexerATNSimulator) closure(input CharStream, config *LexerATNConfig,
if config.context == nil || config.context.hasEmptyPath() {
if config.context == nil || config.context.isEmpty() {
configs.add(config, nil)
configs.Add(config, nil)
return true
} else {
configs.add(NewLexerATNConfig2(config, config.state, PredictionContextEMPTY), nil)
configs.Add(NewLexerATNConfig2(config, config.state, PredictionContextEMPTY), nil)
currentAltReachedAcceptState = true
}
}
@ -437,7 +435,7 @@ func (this *LexerATNSimulator) closure(input CharStream, config *LexerATNConfig,
// optimization
if !config.state.GetEpsilonOnlyTransitions() {
if !currentAltReachedAcceptState || !config.passedThroughNonGreedyDecision {
configs.add(config, nil)
configs.Add(config, nil)
}
}
for j := 0; j < len(config.state.GetTransitions()); j++ {
@ -453,7 +451,7 @@ func (this *LexerATNSimulator) closure(input CharStream, config *LexerATNConfig,
// side-effect: can alter configs.hasSemanticContext
func (this *LexerATNSimulator) getEpsilonTarget(input CharStream, config *LexerATNConfig, trans ITransition,
configs *ATNConfigSet, speculative, treatEofAsEpsilon bool) *LexerATNConfig {
configs ATNConfigSet, speculative, treatEofAsEpsilon bool) *LexerATNConfig {
var cfg *LexerATNConfig
@ -489,7 +487,7 @@ func (this *LexerATNSimulator) getEpsilonTarget(input CharStream, config *LexerA
if LexerATNSimulatorDebug {
fmt.Println("EVAL rule " + strconv.Itoa(trans.(*PredicateTransition).ruleIndex) + ":" + strconv.Itoa(pt.predIndex))
}
configs.hasSemanticContext = true
configs.SetHasSemanticContext( true )
if this.evaluatePredicate(input, pt.ruleIndex, pt.predIndex, speculative) {
cfg = NewLexerATNConfig4(config, trans.getTarget())
}
@ -578,7 +576,7 @@ func (this *LexerATNSimulator) captureSimState(settings *SimState, input CharStr
settings.dfaState = dfaState
}
func (this *LexerATNSimulator) addDFAEdge(from_ *DFAState, tk int, to *DFAState, cfgs *ATNConfigSet) *DFAState {
func (this *LexerATNSimulator) addDFAEdge(from_ *DFAState, tk int, to *DFAState, cfgs ATNConfigSet) *DFAState {
if to == nil && cfgs != nil {
// leading to this call, ATNConfigSet.hasSemanticContext is used as a
// marker indicating dynamic predicate evaluation makes this edge
@ -591,8 +589,8 @@ func (this *LexerATNSimulator) addDFAEdge(from_ *DFAState, tk int, to *DFAState,
// If that gets us to a previously created (but dangling) DFA
// state, we can continue in pure DFA mode from there.
// /
var suppressEdge = cfgs.hasSemanticContext
cfgs.hasSemanticContext = false
var suppressEdge = cfgs.HasSemanticContext()
cfgs.SetHasSemanticContext( false )
to = this.addDFAState(cfgs)
@ -621,13 +619,12 @@ func (this *LexerATNSimulator) addDFAEdge(from_ *DFAState, tk int, to *DFAState,
// configurations already. This method also detects the first
// configuration containing an ATN rule stop state. Later, when
// traversing the DFA, we will know which rule to accept.
func (this *LexerATNSimulator) addDFAState(configs *ATNConfigSet) *DFAState {
func (this *LexerATNSimulator) addDFAState(configs ATNConfigSet) *DFAState {
var proposed = NewDFAState(-1, configs)
var firstConfigWithRuleStopState IATNConfig = nil
var firstConfigWithRuleStopState ATNConfig = nil
for i := 0; i < len(configs.configs); i++ {
var cfg = configs.configs[i]
for _, cfg := range configs.GetItems() {
_, ok := cfg.GetState().(*RuleStopState)
@ -649,7 +646,7 @@ func (this *LexerATNSimulator) addDFAState(configs *ATNConfigSet) *DFAState {
}
var newState = proposed
newState.stateNumber = len(dfa.GetStates())
configs.setReadonly(true)
configs.SetReadOnly(true)
newState.configs = configs
dfa.GetStates()[hash] = newState
return newState

View File

@ -1,8 +1,8 @@
package antlr4
import "fmt"
type IParser interface {
IRecognizer
type Parser interface {
Recognizer
GetInterpreter() *ParserATNSimulator
GetErrorHandler() IErrorStrategy
@ -21,8 +21,8 @@ type IParser interface {
getRuleInvocationStack(IParserRuleContext) []string
}
type Parser struct {
*Recognizer
type BaseParser struct {
*BaseRecognizer
Interpreter *ParserATNSimulator
BuildParseTrees bool
@ -39,11 +39,11 @@ type Parser struct {
// p.is all the parsing support code essentially most of it is error
// recovery stuff.//
func NewParser(input TokenStream) *Parser {
func NewBaseParser(input TokenStream) *BaseParser {
p := new(Parser)
p := new(BaseParser)
p.Recognizer = NewRecognizer()
p.BaseRecognizer = NewBaseRecognizer()
// The input stream.
p._input = nil
@ -84,7 +84,7 @@ func NewParser(input TokenStream) *Parser {
var bypassAltsAtnCache = make(map[string]int)
// reset the parser's state//
func (p *Parser) reset() {
func (p *BaseParser) reset() {
if p._input != nil {
p._input.Seek(0)
}
@ -99,11 +99,11 @@ func (p *Parser) reset() {
}
}
func (p *Parser) GetErrorHandler() IErrorStrategy {
func (p *BaseParser) GetErrorHandler() IErrorStrategy {
return p._errHandler
}
func (p *Parser) GetParseListeners() []ParseTreeListener {
func (p *BaseParser) GetParseListeners() []ParseTreeListener {
return p._parseListeners
}
@ -124,7 +124,7 @@ func (p *Parser) GetParseListeners() []ParseTreeListener {
// {@code ttype} and the error strategy could not recover from the
// misMatched symbol
func (p *Parser) Match(ttype int) IToken {
func (p *BaseParser) Match(ttype int) IToken {
if PortDebug {
fmt.Println("get current token")
@ -171,7 +171,7 @@ func (p *Parser) Match(ttype int) IToken {
// a wildcard and the error strategy could not recover from the misMatched
// symbol
func (p *Parser) MatchWildcard() IToken {
func (p *BaseParser) MatchWildcard() IToken {
var t = p.getCurrentToken()
if t.GetTokenType() > 0 {
p._errHandler.ReportMatch(p)
@ -188,11 +188,11 @@ func (p *Parser) MatchWildcard() IToken {
return t
}
func (p *Parser) GetParserRuleContext() IParserRuleContext {
func (p *BaseParser) GetParserRuleContext() IParserRuleContext {
return p._ctx
}
func (p *Parser) getParseListeners() []ParseTreeListener {
func (p *BaseParser) getParseListeners() []ParseTreeListener {
if p._parseListeners == nil {
return make([]ParseTreeListener, 0)
}
@ -227,7 +227,7 @@ func (p *Parser) getParseListeners() []ParseTreeListener {
//
// @panics nilPointerException if {@code} listener is {@code nil}
//
func (p *Parser) addParseListener(listener ParseTreeListener) {
func (p *BaseParser) addParseListener(listener ParseTreeListener) {
if listener == nil {
panic("listener")
}
@ -244,7 +244,7 @@ func (p *Parser) addParseListener(listener ParseTreeListener) {
// listener, p.method does nothing.</p>
// @param listener the listener to remove
//
func (p *Parser) removeParseListener(listener ParseTreeListener) {
func (p *BaseParser) removeParseListener(listener ParseTreeListener) {
if p._parseListeners != nil {
@ -270,12 +270,12 @@ func (p *Parser) removeParseListener(listener ParseTreeListener) {
}
// Remove all parse listeners.
func (p *Parser) removeParseListeners() {
func (p *BaseParser) removeParseListeners() {
p._parseListeners = nil
}
// Notify any parse listeners of an enter rule event.
func (p *Parser) TriggerEnterRuleEvent() {
func (p *BaseParser) TriggerEnterRuleEvent() {
if p._parseListeners != nil {
var ctx = p._ctx
for _, listener := range p._parseListeners {
@ -290,7 +290,7 @@ func (p *Parser) TriggerEnterRuleEvent() {
//
// @see //addParseListener
//
func (p *Parser) TriggerExitRuleEvent() {
func (p *BaseParser) TriggerExitRuleEvent() {
if p._parseListeners != nil {
// reverse order walk of listeners
ctx := p._ctx
@ -304,20 +304,20 @@ func (p *Parser) TriggerExitRuleEvent() {
}
}
func (this *Parser) GetInterpreter() *ParserATNSimulator {
func (this *BaseParser) GetInterpreter() *ParserATNSimulator {
return this.Interpreter
}
func (this *Parser) GetATN() *ATN {
func (this *BaseParser) GetATN() *ATN {
return this.Interpreter.atn
}
func (p *Parser) GetTokenFactory() TokenFactory {
func (p *BaseParser) GetTokenFactory() TokenFactory {
return p._input.GetTokenSource().GetTokenFactory()
}
// Tell our token source and error strategy about a Newway to create tokens.//
func (p *Parser) setTokenFactory(factory TokenFactory) {
func (p *BaseParser) setTokenFactory(factory TokenFactory) {
p._input.GetTokenSource().setTokenFactory(factory)
}
@ -327,7 +327,7 @@ func (p *Parser) setTokenFactory(factory TokenFactory) {
// @panics UnsupportedOperationException if the current parser does not
// implement the {@link //getSerializedATN()} method.
//
func (p *Parser) GetATNWithBypassAlts() {
func (p *BaseParser) GetATNWithBypassAlts() {
// TODO
panic("Not implemented!")
@ -357,7 +357,7 @@ func (p *Parser) GetATNWithBypassAlts() {
// String id = m.Get("ID")
// </pre>
func (p *Parser) compileParseTreePattern(pattern, patternRuleIndex, lexer ILexer) {
func (p *BaseParser) compileParseTreePattern(pattern, patternRuleIndex, lexer ILexer) {
panic("NewParseTreePatternMatcher not implemented!")
//
@ -377,20 +377,20 @@ func (p *Parser) compileParseTreePattern(pattern, patternRuleIndex, lexer ILexer
// return m.compile(pattern, patternRuleIndex)
}
func (p *Parser) GetInputStream() IntStream {
func (p *BaseParser) GetInputStream() IntStream {
return p.GetTokenStream()
}
func (p *Parser) setInputStream(input TokenStream) {
func (p *BaseParser) setInputStream(input TokenStream) {
p.setTokenStream(input)
}
func (p *Parser) GetTokenStream() TokenStream {
func (p *BaseParser) GetTokenStream() TokenStream {
return p._input
}
// Set the token stream and reset the parser.//
func (p *Parser) setTokenStream(input TokenStream) {
func (p *BaseParser) setTokenStream(input TokenStream) {
p._input = nil
p.reset()
p._input = input
@ -399,11 +399,11 @@ func (p *Parser) setTokenStream(input TokenStream) {
// Match needs to return the current input symbol, which gets put
// into the label for the associated token ref e.g., x=ID.
//
func (p *Parser) getCurrentToken() IToken {
func (p *BaseParser) getCurrentToken() IToken {
return p._input.LT(1)
}
func (p *Parser) NotifyErrorListeners(msg string, offendingToken IToken, err IRecognitionException) {
func (p *BaseParser) NotifyErrorListeners(msg string, offendingToken IToken, err IRecognitionException) {
if offendingToken == nil {
offendingToken = p.getCurrentToken()
}
@ -414,7 +414,7 @@ func (p *Parser) NotifyErrorListeners(msg string, offendingToken IToken, err IRe
listener.SyntaxError(p, offendingToken, line, column, msg, err)
}
func (p *Parser) Consume() IToken {
func (p *BaseParser) Consume() IToken {
var o = p.getCurrentToken()
if o.GetTokenType() != TokenEOF {
if PortDebug {
@ -449,14 +449,14 @@ func (p *Parser) Consume() IToken {
return o
}
func (p *Parser) addContextToParseTree() {
func (p *BaseParser) 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))
}
}
func (p *Parser) EnterRule(localctx IParserRuleContext, state, ruleIndex int) {
func (p *BaseParser) EnterRule(localctx IParserRuleContext, state, ruleIndex int) {
p.SetState(state)
p._ctx = localctx
p._ctx.setStart(p._input.LT(1))
@ -468,7 +468,7 @@ func (p *Parser) EnterRule(localctx IParserRuleContext, state, ruleIndex int) {
}
}
func (p *Parser) ExitRule() {
func (p *BaseParser) ExitRule() {
p._ctx.setStop(p._input.LT(-1))
// trigger event on _ctx, before it reverts to parent
if p._parseListeners != nil {
@ -482,7 +482,7 @@ func (p *Parser) ExitRule() {
}
}
func (p *Parser) EnterOuterAlt(localctx IParserRuleContext, altNum int) {
func (p *BaseParser) 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 {
@ -499,7 +499,7 @@ func (p *Parser) EnterOuterAlt(localctx IParserRuleContext, altNum int) {
// @return The precedence level for the top-most precedence rule, or -1 if
// the parser context is not nested within a precedence rule.
func (p *Parser) getPrecedence() int {
func (p *BaseParser) getPrecedence() int {
if len(p._precedenceStack) == 0 {
return -1
} else {
@ -507,7 +507,7 @@ func (p *Parser) getPrecedence() int {
}
}
func (p *Parser) EnterRecursionRule(localctx IParserRuleContext, state, ruleIndex, precedence int) {
func (p *BaseParser) EnterRecursionRule(localctx IParserRuleContext, state, ruleIndex, precedence int) {
p.SetState(state)
p._precedenceStack.Push(precedence)
p._ctx = localctx
@ -521,7 +521,7 @@ func (p *Parser) EnterRecursionRule(localctx IParserRuleContext, state, ruleInde
//
// Like {@link //EnterRule} but for recursive rules.
func (p *Parser) PushNewRecursionContext(localctx IParserRuleContext, state, ruleIndex int) {
func (p *BaseParser) PushNewRecursionContext(localctx IParserRuleContext, state, ruleIndex int) {
var previous = p._ctx
previous.setParent(localctx)
previous.setInvokingState(state)
@ -538,7 +538,7 @@ func (p *Parser) PushNewRecursionContext(localctx IParserRuleContext, state, rul
}
}
func (p *Parser) UnrollRecursionContexts(parentCtx IParserRuleContext) {
func (p *BaseParser) UnrollRecursionContexts(parentCtx IParserRuleContext) {
p._precedenceStack.Pop()
p._ctx.setStop(p._input.LT(-1))
var retCtx = p._ctx // save current ctx (return value)
@ -559,7 +559,7 @@ func (p *Parser) UnrollRecursionContexts(parentCtx IParserRuleContext) {
}
}
func (p *Parser) getInvokingContext(ruleIndex int) IParserRuleContext {
func (p *BaseParser) getInvokingContext(ruleIndex int) IParserRuleContext {
var ctx = p._ctx
for ctx != nil {
if ctx.GetRuleIndex() == ruleIndex {
@ -570,11 +570,11 @@ func (p *Parser) getInvokingContext(ruleIndex int) IParserRuleContext {
return nil
}
func (p *Parser) Precpred(localctx IRuleContext, precedence int) bool {
func (p *BaseParser) Precpred(localctx IRuleContext, precedence int) bool {
return precedence >= p._precedenceStack[len(p._precedenceStack)-1]
}
func (p *Parser) inContext(context IParserRuleContext) bool {
func (p *BaseParser) inContext(context IParserRuleContext) bool {
// TODO: useful in parser?
return false
}
@ -593,7 +593,7 @@ func (p *Parser) inContext(context IParserRuleContext) bool {
// @return {@code true} if {@code symbol} can follow the current state in
// the ATN, otherwise {@code false}.
func (p *Parser) isExpectedToken(symbol int) bool {
func (p *BaseParser) isExpectedToken(symbol int) bool {
var atn *ATN = p.Interpreter.atn
var ctx = p._ctx
var s = atn.states[p.state]
@ -626,18 +626,18 @@ func (p *Parser) isExpectedToken(symbol int) bool {
//
// @see ATN//getExpectedTokens(int, RuleContext)
//
func (p *Parser) getExpectedTokens() *IntervalSet {
func (p *BaseParser) getExpectedTokens() *IntervalSet {
return p.Interpreter.atn.getExpectedTokens(p.state, p._ctx)
}
func (p *Parser) getExpectedTokensWithinCurrentRule() *IntervalSet {
func (p *BaseParser) getExpectedTokensWithinCurrentRule() *IntervalSet {
var atn = p.Interpreter.atn
var s = atn.states[p.state]
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 {
func (p *BaseParser) GetRuleIndex(ruleName string) int {
var ruleIndex, ok = p.getRuleIndexMap()[ruleName]
if ok {
return ruleIndex
@ -653,7 +653,7 @@ func (p *Parser) GetRuleIndex(ruleName string) int {
//
// this very useful for error messages.
func (this *Parser) getRuleInvocationStack(p IParserRuleContext) []string {
func (this *BaseParser) getRuleInvocationStack(p IParserRuleContext) []string {
if p == nil {
p = this._ctx
}
@ -672,13 +672,13 @@ func (this *Parser) getRuleInvocationStack(p IParserRuleContext) []string {
}
// For debugging and other purposes.//
func (p *Parser) getDFAStrings() {
func (p *BaseParser) getDFAStrings() {
panic("dumpDFA Not implemented!")
// return p._interp.decisionToDFA.String()
}
// For debugging and other purposes.//
func (p *Parser) dumpDFA() {
func (p *BaseParser) dumpDFA() {
panic("dumpDFA Not implemented!")
// var seenOne = false
@ -695,14 +695,14 @@ func (p *Parser) dumpDFA() {
// }
}
func (p *Parser) GetSourceName() string {
func (p *BaseParser) GetSourceName() string {
return p.GrammarFileName
}
// During a parse is sometimes useful to listen in on the rule entry and exit
// events as well as token Matches. p.is for quick and dirty debugging.
//
func (p *Parser) setTrace(trace *TraceListener) {
func (p *BaseParser) setTrace(trace *TraceListener) {
if trace == nil {
p.removeParseListener(p._tracer)
p._tracer = nil

View File

@ -9,7 +9,7 @@ import (
type ParserATNSimulator struct {
*ATNSimulator
parser IParser
parser Parser
predictionMode int
_input TokenStream
_startIndex int
@ -19,7 +19,7 @@ type ParserATNSimulator struct {
_outerContext IParserRuleContext
}
func NewParserATNSimulator(parser IParser, atn *ATN, decisionToDFA []*DFA, sharedContextCache *PredictionContextCache) *ParserATNSimulator {
func NewParserATNSimulator(parser Parser, atn *ATN, decisionToDFA []*DFA, sharedContextCache *PredictionContextCache) *ParserATNSimulator {
this := new(ParserATNSimulator)
@ -214,7 +214,7 @@ func (this *ParserATNSimulator) execATN(dfa *DFA, s0 *DFAState, input TokenStrea
}
if D.requiresFullContext && this.predictionMode != PredictionModeSLL {
// IF PREDS, MIGHT RESOLVE TO SINGLE ALT => SLL (or syntax error)
var conflictingAlts *BitSet = D.configs.conflictingAlts
var conflictingAlts = D.configs.GetConflictingAlts()
if D.predicates != nil {
if ParserATNSimulatorDebug {
fmt.Println("DFA state has preds in DFA sim LL failover")
@ -328,17 +328,17 @@ func (this *ParserATNSimulator) computeTargetState(dfa *DFA, previousD *DFAState
if predictedAlt != ATNINVALID_ALT_NUMBER {
// NO CONFLICT, UNIQUELY PREDICTED ALT
D.isAcceptState = true
D.configs.uniqueAlt = predictedAlt
D.configs.SetUniqueAlt( predictedAlt )
D.setPrediction( predictedAlt )
} else if PredictionModehasSLLConflictTerminatingPrediction(this.predictionMode, reach) {
// MORE THAN ONE VIABLE ALTERNATIVE
D.configs.conflictingAlts = this.getConflictingAlts(reach)
D.configs.SetConflictingAlts( 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.setPrediction( D.configs.conflictingAlts.minValue() )
D.setPrediction( D.configs.GetConflictingAlts().minValue() )
}
if D.isAcceptState && D.configs.hasSemanticContext {
if D.isAcceptState && D.configs.HasSemanticContext() {
this.predicateDFAState(D, this.atn.getDecisionState(dfa.decision))
if D.predicates != nil {
D.setPrediction( ATNINVALID_ALT_NUMBER )
@ -369,7 +369,7 @@ func (this *ParserATNSimulator) predicateDFAState(dfaState *DFAState, decisionSt
}
// 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 ParserATNSimulatorDebug || ParserATNSimulatorListATNDecisions {
fmt.Println("execATNWithFullContext " + s0.String())
@ -377,7 +377,7 @@ func (this *ParserATNSimulator) execATNWithFullContext(dfa *DFA, D *DFAState, s0
var fullCtx = true
var foundExactAmbig = false
var reach *ATNConfigSet = nil
var reach ATNConfigSet = nil
var previous = s0
input.Seek(startIndex)
var t = input.LA(1)
@ -410,10 +410,10 @@ func (this *ParserATNSimulator) execATNWithFullContext(dfa *DFA, D *DFAState, s0
strconv.Itoa(PredictionModegetUniqueAlt(altSubSets)) + ", resolvesToJustOneViableAlt=" +
fmt.Sprint(PredictionModeresolvesToJustOneViableAlt(altSubSets)))
}
reach.uniqueAlt = this.getUniqueAlt(reach)
reach.SetUniqueAlt( this.getUniqueAlt(reach) )
// unique prediction?
if reach.uniqueAlt != ATNINVALID_ALT_NUMBER {
predictedAlt = reach.uniqueAlt
if reach.GetUniqueAlt() != ATNINVALID_ALT_NUMBER {
predictedAlt = reach.GetUniqueAlt()
break
} else if this.predictionMode != PredictionModeLL_EXACT_AMBIG_DETECTION {
predictedAlt = PredictionModeresolvesToJustOneViableAlt(altSubSets)
@ -441,7 +441,7 @@ func (this *ParserATNSimulator) execATNWithFullContext(dfa *DFA, D *DFAState, s0
// 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 {
if reach.GetUniqueAlt() != ATNINVALID_ALT_NUMBER {
this.ReportContextSensitivity(dfa, predictedAlt, reach, startIndex, input.Index())
return predictedAlt
}
@ -477,14 +477,14 @@ func (this *ParserATNSimulator) execATNWithFullContext(dfa *DFA, D *DFAState, s0
return predictedAlt
}
func (this *ParserATNSimulator) computeReachSet(closure *ATNConfigSet, t int, fullCtx bool) *ATNConfigSet {
func (this *ParserATNSimulator) computeReachSet(closure ATNConfigSet, t int, fullCtx bool) ATNConfigSet {
if ParserATNSimulatorDebug {
fmt.Println("in computeReachSet, starting closure: " + closure.String())
}
if this.mergeCache == nil {
this.mergeCache = NewDoubleDict()
}
var intermediate = NewATNConfigSet(fullCtx)
var intermediate = NewBaseATNConfigSet(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
@ -496,12 +496,10 @@ func (this *ParserATNSimulator) computeReachSet(closure *ATNConfigSet, t int, fu
// ensure that the alternative Matching the longest overall sequence is
// chosen when multiple such configurations can Match the input.
var skippedStopStates []*ATNConfig = nil
var skippedStopStates []*BaseATNConfig = nil
// First figure out where we can reach on input t
for i := 0; i < len(closure.configs); i++ {
var c = closure.configs[i]
for _,c := range closure.GetItems() {
if ParserATNSimulatorDebug {
fmt.Println("testing " + this.GetTokenName(t) + " at " + c.String())
}
@ -511,9 +509,9 @@ func (this *ParserATNSimulator) computeReachSet(closure *ATNConfigSet, t int, fu
if ok {
if fullCtx || t == TokenEOF {
if skippedStopStates == nil {
skippedStopStates = make([]*ATNConfig, 0)
skippedStopStates = make([]*BaseATNConfig, 0)
}
skippedStopStates = append(skippedStopStates, c.(*ATNConfig))
skippedStopStates = append(skippedStopStates, c.(*BaseATNConfig))
if ParserATNSimulatorDebug {
fmt.Println("added " + c.String() + " to skippedStopStates")
}
@ -526,7 +524,7 @@ func (this *ParserATNSimulator) computeReachSet(closure *ATNConfigSet, t int, fu
var target = this.getReachableTarget(trans, t)
if target != nil {
var cfg = NewATNConfig4(c, target)
intermediate.add(cfg, this.mergeCache)
intermediate.Add(cfg, this.mergeCache)
if ParserATNSimulatorDebug {
fmt.Println("added " + cfg.String() + " to intermediate")
}
@ -534,7 +532,7 @@ func (this *ParserATNSimulator) computeReachSet(closure *ATNConfigSet, t int, fu
}
}
// Now figure out where the reach operation can take us...
var reach *ATNConfigSet = nil
var reach ATNConfigSet = nil
// This block optimizes the reach operation for intermediate sets which
// trivially indicate a termination state for the overall
@ -562,7 +560,7 @@ func (this *ParserATNSimulator) computeReachSet(closure *ATNConfigSet, t int, fu
// operation on the intermediate set to compute its initial value.
//
if reach == nil {
reach = NewATNConfigSet(fullCtx)
reach = NewBaseATNConfigSet(fullCtx)
var closureBusy = NewSet(nil, nil)
var treatEofAsEpsilon = t == TokenEOF
for k := 0; k < len(intermediate.configs); k++ {
@ -599,10 +597,10 @@ func (this *ParserATNSimulator) computeReachSet(closure *ATNConfigSet, t int, fu
//
if skippedStopStates != nil && ((!fullCtx) || (!PredictionModehasConfigInRuleStopState(reach))) {
for l := 0; l < len(skippedStopStates); l++ {
reach.add(skippedStopStates[l], this.mergeCache)
reach.Add(skippedStopStates[l], this.mergeCache)
}
}
if len(reach.configs) == 0 {
if len(reach.GetItems()) == 0 {
return nil
} else {
return reach
@ -629,35 +627,34 @@ func (this *ParserATNSimulator) computeReachSet(closure *ATNConfigSet, t int, fu
// rule stop state, otherwise return a Newconfiguration set containing only
// the configurations from {@code configs} which are in a rule stop state
//
func (this *ParserATNSimulator) removeAllConfigsNotInRuleStopState(configs *ATNConfigSet, lookToEndOfRule bool) *ATNConfigSet {
func (this *ParserATNSimulator) removeAllConfigsNotInRuleStopState(configs ATNConfigSet, lookToEndOfRule bool) ATNConfigSet {
if PredictionModeallConfigsInRuleStopStates(configs) {
return configs
}
var result = NewATNConfigSet(configs.fullCtx)
for i := 0; i < len(configs.configs); i++ {
var config = configs.configs[i]
var result = NewBaseATNConfigSet(configs.FullContext())
for _,config := range configs.GetItems() {
_, ok := config.GetState().(*RuleStopState)
if ok {
result.add(config, this.mergeCache)
result.Add(config, this.mergeCache)
continue
}
if lookToEndOfRule && config.GetState().GetEpsilonOnlyTransitions() {
var nextTokens = this.atn.nextTokens(config.GetState(), nil)
if nextTokens.contains(TokenEpsilon) {
var endOfRuleState = this.atn.ruleToStopState[config.GetState().GetRuleIndex()]
result.add(NewATNConfig4(config, endOfRuleState), this.mergeCache)
result.Add(NewATNConfig4(config, endOfRuleState), this.mergeCache)
}
}
}
return result
}
func (this *ParserATNSimulator) computeStartState(p IATNState, ctx IRuleContext, fullCtx bool) *ATNConfigSet {
func (this *ParserATNSimulator) computeStartState(p IATNState, ctx IRuleContext, fullCtx bool) ATNConfigSet {
// always at least the implicit call to start rule
var initialContext = predictionContextFromRuleContext(this.atn, ctx)
var configs = NewATNConfigSet(fullCtx)
var configs = NewBaseATNConfigSet(fullCtx)
for i := 0; i < len(p.GetTransitions()); i++ {
var target = p.GetTransitions()[i].getTarget()
var c = NewATNConfig6(target, i+1, initialContext)
@ -723,13 +720,12 @@ func (this *ParserATNSimulator) computeStartState(p IATNState, ctx IRuleContext,
// for a precedence DFA at a particular precedence level (determined by
// calling {@link Parser//getPrecedence}).
//
func (this *ParserATNSimulator) applyPrecedenceFilter(configs *ATNConfigSet) *ATNConfigSet {
func (this *ParserATNSimulator) applyPrecedenceFilter(configs ATNConfigSet) ATNConfigSet {
var statesFromAlt1 = make(map[int]IPredictionContext)
var configSet = NewATNConfigSet(configs.fullCtx)
var configSet = NewBaseATNConfigSet(configs.FullContext())
for i := 0; i < len(configs.configs); i++ {
config := configs.configs[i]
for _,config := range configs.GetItems() {
// handle alt 1 first
if config.GetAlt() != 1 {
continue
@ -741,13 +737,12 @@ func (this *ParserATNSimulator) applyPrecedenceFilter(configs *ATNConfigSet) *AT
}
statesFromAlt1[config.GetState().GetStateNumber()] = config.GetContext()
if updatedContext != config.GetSemanticContext() {
configSet.add(NewATNConfig2(config, updatedContext), this.mergeCache)
configSet.Add(NewATNConfig2(config, updatedContext), this.mergeCache)
} else {
configSet.add(config, this.mergeCache)
configSet.Add(config, this.mergeCache)
}
}
for i := 0; i < len(configs.configs); i++ {
config := configs.configs[i]
for _,config := range configs.GetItems() {
if config.GetAlt() == 1 {
// already handled
continue
@ -762,7 +757,7 @@ func (this *ParserATNSimulator) applyPrecedenceFilter(configs *ATNConfigSet) *AT
continue
}
}
configSet.add(config, this.mergeCache)
configSet.Add(config, this.mergeCache)
}
return configSet
}
@ -775,11 +770,10 @@ func (this *ParserATNSimulator) getReachableTarget(trans ITransition, ttype int)
}
}
func (this *ParserATNSimulator) getPredsForAmbigAlts(ambigAlts *BitSet, configs *ATNConfigSet, nalts int) []SemanticContext {
func (this *ParserATNSimulator) getPredsForAmbigAlts(ambigAlts *BitSet, configs ATNConfigSet, nalts int) []SemanticContext {
var altToPred = make([]SemanticContext, nalts+1)
for i := 0; i < len(configs.configs); i++ {
var c = configs.configs[i]
for _, c := range configs.GetItems() {
if ambigAlts.contains(c.GetAlt()) {
altToPred[c.GetAlt()] = SemanticContextorContext(altToPred[c.GetAlt()], c.GetSemanticContext())
}
@ -868,7 +862,7 @@ func (this *ParserATNSimulator) getPredicatePredictions(ambigAlts *BitSet, altTo
// {@link ATN//INVALID_ALT_NUMBER} if a suitable alternative was not
// identified and {@link //AdaptivePredict} should Report an error instead.
//
func (this *ParserATNSimulator) getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(configs *ATNConfigSet, outerContext IParserRuleContext) int {
func (this *ParserATNSimulator) getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(configs ATNConfigSet, outerContext IParserRuleContext) int {
var cfgs = this.splitAccordingToSemanticValidity(configs, outerContext)
var semValidConfigs = cfgs[0]
var semInvalidConfigs = cfgs[1]
@ -877,7 +871,7 @@ func (this *ParserATNSimulator) getSynValidOrSemInvalidAltThatFinishedDecisionEn
return alt
}
// Is there a syntactically valid path with a failed pred?
if len(semInvalidConfigs.configs) > 0 {
if len(semInvalidConfigs.GetItems()) > 0 {
alt = this.GetAltThatFinishedDecisionEntryRule(semInvalidConfigs)
if alt != ATNINVALID_ALT_NUMBER { // syntactically viable path exists
return alt
@ -886,11 +880,10 @@ func (this *ParserATNSimulator) getSynValidOrSemInvalidAltThatFinishedDecisionEn
return ATNINVALID_ALT_NUMBER
}
func (this *ParserATNSimulator) GetAltThatFinishedDecisionEntryRule(configs *ATNConfigSet) int {
func (this *ParserATNSimulator) GetAltThatFinishedDecisionEntryRule(configs ATNConfigSet) int {
var alts = NewIntervalSet()
for i := 0; i < len(configs.configs); i++ {
var c = configs.configs[i]
for _,c := range configs.GetItems() {
_, ok := c.GetState().(*RuleStopState)
if c.GetReachesIntoOuterContext() > 0 || (ok && c.GetContext().hasEmptyPath()) {
@ -914,27 +907,26 @@ func (this *ParserATNSimulator) GetAltThatFinishedDecisionEntryRule(configs *ATN
// prediction, which is where predicates need to evaluate.
type ATNConfigSetPair struct {
item0, item1 *ATNConfigSet
item0, item1 ATNConfigSet
}
func (this *ParserATNSimulator) splitAccordingToSemanticValidity(configs *ATNConfigSet, outerContext IParserRuleContext) []*ATNConfigSet {
var succeeded = NewATNConfigSet(configs.fullCtx)
var failed = NewATNConfigSet(configs.fullCtx)
func (this *ParserATNSimulator) splitAccordingToSemanticValidity(configs ATNConfigSet, outerContext IParserRuleContext) []ATNConfigSet {
var succeeded = NewBaseATNConfigSet(configs.FullContext())
var failed = NewBaseATNConfigSet(configs.FullContext())
for i := 0; i < len(configs.configs); i++ {
var c = configs.configs[i]
for _, c := range configs.GetItems() {
if c.GetSemanticContext() != SemanticContextNONE {
var predicateEvaluationResult = c.GetSemanticContext().evaluate(this.parser, outerContext)
if predicateEvaluationResult {
succeeded.add(c, nil)
succeeded.Add(c, nil)
} else {
failed.add(c, nil)
failed.Add(c, nil)
}
} else {
succeeded.add(c, nil)
succeeded.Add(c, nil)
}
}
return []*ATNConfigSet{succeeded, failed}
return []ATNConfigSet{succeeded, failed}
}
// Look through a list of predicate/alt pairs, returning alts for the
@ -971,13 +963,13 @@ func (this *ParserATNSimulator) evalSemanticContext(predPredictions []*PredPredi
return predictions
}
func (this *ParserATNSimulator) closure(config IATNConfig, configs *ATNConfigSet, closureBusy *Set, collectPredicates, fullCtx, treatEofAsEpsilon bool) {
func (this *ParserATNSimulator) closure(config ATNConfig, configs ATNConfigSet, closureBusy *Set, collectPredicates, fullCtx, treatEofAsEpsilon bool) {
var initialDepth = 0
this.closureCheckingStopState(config, configs, closureBusy, collectPredicates,
fullCtx, initialDepth, treatEofAsEpsilon)
}
func (this *ParserATNSimulator) closureCheckingStopState(config IATNConfig, configs *ATNConfigSet, closureBusy *Set, collectPredicates, fullCtx bool, depth int, treatEofAsEpsilon bool) {
func (this *ParserATNSimulator) closureCheckingStopState(config ATNConfig, configs ATNConfigSet, closureBusy *Set, collectPredicates, fullCtx bool, depth int, treatEofAsEpsilon bool) {
if ParserATNSimulatorDebug {
fmt.Println("closure(" + config.String() + ")")
@ -995,7 +987,7 @@ func (this *ParserATNSimulator) closureCheckingStopState(config IATNConfig, conf
for i := 0; i < config.GetContext().length(); i++ {
if config.GetContext().getReturnState(i) == PredictionContextEMPTY_RETURN_STATE {
if fullCtx {
configs.add(NewATNConfig1(config, config.GetState(), PredictionContextEMPTY), this.mergeCache)
configs.Add(NewATNConfig1(config, config.GetState(), PredictionContextEMPTY), this.mergeCache)
continue
} else {
// we have no context info, just chase follow links (if greedy)
@ -1022,7 +1014,7 @@ func (this *ParserATNSimulator) closureCheckingStopState(config IATNConfig, conf
return
} else if fullCtx {
// reached end of start rule
configs.add(config, this.mergeCache)
configs.Add(config, this.mergeCache)
return
} else {
// else if we have no context info, just chase follow links (if greedy)
@ -1038,14 +1030,14 @@ func (this *ParserATNSimulator) closureCheckingStopState(config IATNConfig, conf
}
// Do the actual work of walking epsilon edges//
func (this *ParserATNSimulator) closure_(config IATNConfig, configs *ATNConfigSet, closureBusy *Set, collectPredicates, fullCtx bool, depth int, treatEofAsEpsilon bool) {
func (this *ParserATNSimulator) closure_(config ATNConfig, configs ATNConfigSet, closureBusy *Set, collectPredicates, fullCtx bool, depth int, treatEofAsEpsilon bool) {
if PortDebug {
fmt.Println("closure_")
}
var p = config.GetState()
// optimization
if !p.GetEpsilonOnlyTransitions() {
configs.add(config, this.mergeCache)
configs.Add(config, this.mergeCache)
// make sure to not return here, because EOF transitions can act as
// both epsilon transitions and non-epsilon transitions.
}
@ -1098,7 +1090,7 @@ func (this *ParserATNSimulator) closure_(config IATNConfig, configs *ATNConfigSe
}
c.SetReachesIntoOuterContext(c.GetReachesIntoOuterContext() + 1)
configs.dipsIntoOuterContext = true // TODO: can remove? only care when we add to set per middle of this method
configs.SetDipsIntoOuterContext( true ) // TODO: can remove? only care when we add to set per middle of this method
newDepth -= 1
if ParserATNSimulatorDebug {
fmt.Println("dips into outer ctx: " + c.String())
@ -1122,7 +1114,7 @@ func (this *ParserATNSimulator) getRuleName(index int) string {
}
}
func (this *ParserATNSimulator) getEpsilonTarget(config IATNConfig, t ITransition, collectPredicates, inContext, fullCtx, treatEofAsEpsilon bool) *ATNConfig {
func (this *ParserATNSimulator) getEpsilonTarget(config ATNConfig, t ITransition, collectPredicates, inContext, fullCtx, treatEofAsEpsilon bool) *BaseATNConfig {
switch t.getSerializationType() {
case TransitionRULE:
@ -1167,15 +1159,15 @@ func (this *ParserATNSimulator) getEpsilonTarget(config IATNConfig, t ITransitio
}
}
func (this *ParserATNSimulator) actionTransition(config IATNConfig, t *ActionTransition) *ATNConfig {
func (this *ParserATNSimulator) actionTransition(config ATNConfig, t *ActionTransition) *BaseATNConfig {
if ParserATNSimulatorDebug {
fmt.Println("ACTION edge " + strconv.Itoa(t.ruleIndex) + ":" + strconv.Itoa(t.actionIndex))
}
return NewATNConfig4(config, t.getTarget())
}
func (this *ParserATNSimulator) precedenceTransition(config IATNConfig,
pt *PrecedencePredicateTransition, collectPredicates, inContext, fullCtx bool) *ATNConfig {
func (this *ParserATNSimulator) precedenceTransition(config ATNConfig,
pt *PrecedencePredicateTransition, collectPredicates, inContext, fullCtx bool) *BaseATNConfig {
if ParserATNSimulatorDebug {
fmt.Println("PRED (collectPredicates=" + fmt.Sprint(collectPredicates) + ") " +
@ -1184,7 +1176,7 @@ func (this *ParserATNSimulator) precedenceTransition(config IATNConfig,
fmt.Println("context surrounding pred is " + fmt.Sprint(this.parser.getRuleInvocationStack(nil)))
}
}
var c *ATNConfig = nil
var c *BaseATNConfig = nil
if collectPredicates && inContext {
if fullCtx {
// In full context mode, we can evaluate predicates on-the-fly
@ -1211,7 +1203,7 @@ func (this *ParserATNSimulator) precedenceTransition(config IATNConfig,
return c
}
func (this *ParserATNSimulator) predTransition(config IATNConfig, pt *PredicateTransition, collectPredicates, inContext, fullCtx bool) *ATNConfig {
func (this *ParserATNSimulator) predTransition(config ATNConfig, pt *PredicateTransition, collectPredicates, inContext, fullCtx bool) *BaseATNConfig {
if ParserATNSimulatorDebug {
fmt.Println("PRED (collectPredicates=" + fmt.Sprint(collectPredicates) + ") " + strconv.Itoa(pt.ruleIndex) +
@ -1220,7 +1212,7 @@ func (this *ParserATNSimulator) predTransition(config IATNConfig, pt *PredicateT
fmt.Println("context surrounding pred is " + fmt.Sprint(this.parser.getRuleInvocationStack(nil)))
}
}
var c *ATNConfig = nil
var c *BaseATNConfig = nil
if collectPredicates && ((pt.isCtxDependent && inContext) || !pt.isCtxDependent) {
if fullCtx {
// In full context mode, we can evaluate predicates on-the-fly
@ -1247,7 +1239,7 @@ func (this *ParserATNSimulator) predTransition(config IATNConfig, pt *PredicateT
return c
}
func (this *ParserATNSimulator) ruleTransition(config IATNConfig, t *RuleTransition) *ATNConfig {
func (this *ParserATNSimulator) ruleTransition(config ATNConfig, t *RuleTransition) *BaseATNConfig {
if ParserATNSimulatorDebug {
fmt.Println("CALL rule " + this.getRuleName(t.getTarget().GetRuleIndex()) + ", ctx=" + config.GetContext().String())
}
@ -1256,7 +1248,7 @@ func (this *ParserATNSimulator) ruleTransition(config IATNConfig, t *RuleTransit
return NewATNConfig1(config, t.getTarget(), newContext)
}
func (this *ParserATNSimulator) getConflictingAlts(configs *ATNConfigSet) *BitSet {
func (this *ParserATNSimulator) getConflictingAlts(configs ATNConfigSet) *BitSet {
var altsets = PredictionModegetConflictingAltSubsets(configs)
return PredictionModeGetAlts(altsets)
}
@ -1297,13 +1289,13 @@ func (this *ParserATNSimulator) getConflictingAlts(configs *ATNConfigSet) *BitSe
// that we still need to pursue.
//
func (this *ParserATNSimulator) getConflictingAltsOrUniqueAlt(configs *ATNConfigSet) *BitSet {
func (this *ParserATNSimulator) getConflictingAltsOrUniqueAlt(configs ATNConfigSet) *BitSet {
var conflictingAlts *BitSet = nil
if configs.uniqueAlt != ATNINVALID_ALT_NUMBER {
if configs.GetUniqueAlt() != ATNINVALID_ALT_NUMBER {
conflictingAlts = NewBitSet()
conflictingAlts.add(configs.uniqueAlt)
conflictingAlts.add(configs.GetUniqueAlt())
} else {
conflictingAlts = configs.conflictingAlts
conflictingAlts = configs.GetConflictingAlts()
}
return conflictingAlts
}
@ -1368,14 +1360,13 @@ func (this *ParserATNSimulator) dumpDeadEndConfigs(nvae *NoViableAltException) {
// }
}
func (this *ParserATNSimulator) noViableAlt(input TokenStream, outerContext IParserRuleContext, configs *ATNConfigSet, startIndex int) *NoViableAltException {
func (this *ParserATNSimulator) noViableAlt(input TokenStream, outerContext IParserRuleContext, configs ATNConfigSet, startIndex int) *NoViableAltException {
return NewNoViableAltException(this.parser, input, input.Get(startIndex), input.LT(1), configs, outerContext)
}
func (this *ParserATNSimulator) getUniqueAlt(configs *ATNConfigSet) int {
func (this *ParserATNSimulator) getUniqueAlt(configs ATNConfigSet) int {
var alt = ATNINVALID_ALT_NUMBER
for i := 0; i < len(configs.configs); i++ {
var c = configs.configs[i]
for _,c := range configs.GetItems() {
if alt == ATNINVALID_ALT_NUMBER {
alt = c.GetAlt() // found first alt
} else if c.GetAlt() != alt {
@ -1457,9 +1448,9 @@ func (this *ParserATNSimulator) addDFAState(dfa *DFA, D *DFAState) *DFAState {
return existing
}
D.stateNumber = len(dfa.GetStates())
if !D.configs.readOnly {
D.configs.optimizeConfigs(this.ATNSimulator)
D.configs.setReadonly(true)
if !D.configs.ReadOnly() {
D.configs.OptimizeConfigs(this.ATNSimulator)
D.configs.SetReadOnly(true)
}
dfa.GetStates()[hash] = D
if ParserATNSimulatorDebug {
@ -1468,7 +1459,7 @@ func (this *ParserATNSimulator) addDFAState(dfa *DFA, D *DFAState) *DFAState {
return D
}
func (this *ParserATNSimulator) ReportAttemptingFullContext(dfa *DFA, conflictingAlts *BitSet, configs *ATNConfigSet, startIndex, stopIndex int) {
func (this *ParserATNSimulator) ReportAttemptingFullContext(dfa *DFA, conflictingAlts *BitSet, configs ATNConfigSet, startIndex, stopIndex int) {
if ParserATNSimulatorDebug || ParserATNSimulatorRetryDebug {
var interval = NewInterval(startIndex, stopIndex+1)
fmt.Println("ReportAttemptingFullContext decision=" + strconv.Itoa(dfa.decision) + ":" + configs.String() +
@ -1479,7 +1470,7 @@ func (this *ParserATNSimulator) ReportAttemptingFullContext(dfa *DFA, conflictin
}
}
func (this *ParserATNSimulator) ReportContextSensitivity(dfa *DFA, prediction int, configs *ATNConfigSet, startIndex, stopIndex int) {
func (this *ParserATNSimulator) ReportContextSensitivity(dfa *DFA, prediction int, configs ATNConfigSet, startIndex, stopIndex int) {
if ParserATNSimulatorDebug || ParserATNSimulatorRetryDebug {
var interval = NewInterval(startIndex, stopIndex+1)
fmt.Println("ReportContextSensitivity decision=" + strconv.Itoa(dfa.decision) + ":" + configs.String() +
@ -1492,7 +1483,7 @@ func (this *ParserATNSimulator) ReportContextSensitivity(dfa *DFA, prediction in
// If context sensitive parsing, we know it's ambiguity not conflict//
func (this *ParserATNSimulator) ReportAmbiguity(dfa *DFA, D *DFAState, startIndex, stopIndex int,
exact bool, ambigAlts *BitSet, configs *ATNConfigSet) {
exact bool, ambigAlts *BitSet, configs ATNConfigSet) {
if ParserATNSimulatorDebug || ParserATNSimulatorRetryDebug {
var interval = NewInterval(startIndex, stopIndex+1)
fmt.Println("ReportAmbiguity " + ambigAlts.String() + ":" + configs.String() +

View File

@ -164,7 +164,7 @@ const (
// the configurations to strip out all of the predicates so that a standard
// {@link ATNConfigSet} will merge everything ignoring predicates.</p>
//
func PredictionModehasSLLConflictTerminatingPrediction(mode int, configs *ATNConfigSet) bool {
func PredictionModehasSLLConflictTerminatingPrediction(mode int, configs ATNConfigSet) bool {
// Configs in rule stop states indicate reaching the end of the decision
// rule (local context) or end of start rule (full context). If all
// configs meet this condition, then none of the configurations is able
@ -178,15 +178,14 @@ func PredictionModehasSLLConflictTerminatingPrediction(mode int, configs *ATNCon
// Don't bother with combining configs from different semantic
// contexts if we can fail over to full LL costs more time
// since we'll often fail over anyway.
if configs.hasSemanticContext {
if configs.HasSemanticContext() {
// dup configs, tossing out semantic predicates
var dup = NewATNConfigSet(false)
for i := 0; i < len(configs.configs); i++ {
var c = configs.configs[i]
var dup = NewBaseATNConfigSet(false)
for _, c := range configs.GetItems() {
// NewATNConfig({semanticContext:}, c)
c = NewATNConfig2(c, SemanticContextNONE)
dup.add(c, nil)
dup.Add(c, nil)
}
configs = dup
}
@ -205,9 +204,8 @@ func PredictionModehasSLLConflictTerminatingPrediction(mode int, configs *ATNCon
// @param configs the configuration set to test
// @return {@code true} if any configuration in {@code configs} is in a
// {@link RuleStopState}, otherwise {@code false}
func PredictionModehasConfigInRuleStopState(configs *ATNConfigSet) bool {
for i := 0; i < len(configs.configs); i++ {
var c = configs.configs[i]
func PredictionModehasConfigInRuleStopState(configs ATNConfigSet) bool {
for _, c := range configs.GetItems() {
if _, ok := c.GetState().(*RuleStopState); ok {
return true
}
@ -223,11 +221,9 @@ func PredictionModehasConfigInRuleStopState(configs *ATNConfigSet) bool {
// @param configs the configuration set to test
// @return {@code true} if all configurations in {@code configs} are in a
// {@link RuleStopState}, otherwise {@code false}
func PredictionModeallConfigsInRuleStopStates(configs *ATNConfigSet) bool {
for i := 0; i < len(configs.configs); i++ {
var c = configs.configs[i]
func PredictionModeallConfigsInRuleStopStates(configs ATNConfigSet) bool {
for _, c := range configs.GetItems() {
if _, ok := c.GetState().(*RuleStopState); !ok {
return false
}
@ -490,11 +486,10 @@ func PredictionModeGetAlts(altsets []*BitSet) *BitSet {
// alt and not pred
// </pre>
//
func PredictionModegetConflictingAltSubsets(configs *ATNConfigSet) []*BitSet {
func PredictionModegetConflictingAltSubsets(configs ATNConfigSet) []*BitSet {
var configToAlts = make(map[string]*BitSet)
for i := 0; i < len(configs.configs); i++ {
var c = configs.configs[i]
for _, c := range configs.GetItems() {
var key = "key_" + strconv.Itoa(c.GetState().GetStateNumber()) + "/" + c.GetContext().String()
var alts = configToAlts[key]
if alts == nil {
@ -523,10 +518,10 @@ func PredictionModegetConflictingAltSubsets(configs *ATNConfigSet) []*BitSet {
// map[c.{@link ATNConfig//state state}] U= c.{@link ATNConfig//alt alt}
// </pre>
//
func PredictionModeGetStateToAltMap(configs *ATNConfigSet) *AltDict {
func PredictionModeGetStateToAltMap(configs ATNConfigSet) *AltDict {
var m = NewAltDict()
for _, c := range configs.configs {
for _, c := range configs.GetItems() {
var alts = m.Get(c.GetState().String())
if alts == nil {
alts = NewBitSet()
@ -537,7 +532,7 @@ func PredictionModeGetStateToAltMap(configs *ATNConfigSet) *AltDict {
return m
}
func PredictionModehasStateAssociatedWithOneAlt(configs *ATNConfigSet) bool {
func PredictionModehasStateAssociatedWithOneAlt(configs ATNConfigSet) bool {
var values = PredictionModeGetStateToAltMap(configs).values()
for i := 0; i < len(values); i++ {
if values[i].(*BitSet).length() == 1 {

View File

@ -7,7 +7,7 @@ import (
"strconv"
)
type IRecognizer interface {
type Recognizer interface {
GetLiteralNames() []string
GetSymbolicNames() []string
@ -23,7 +23,7 @@ type IRecognizer interface {
}
type Recognizer struct {
type BaseRecognizer struct {
_listeners []IErrorListener
state int
@ -33,8 +33,8 @@ type Recognizer struct {
GrammarFileName string
}
func NewRecognizer() *Recognizer {
rec := new(Recognizer)
func NewBaseRecognizer() *BaseRecognizer {
rec := new(BaseRecognizer)
rec._listeners = []IErrorListener{ConsoleErrorListenerINSTANCE}
rec.state = -1
return rec
@ -43,46 +43,46 @@ func NewRecognizer() *Recognizer {
var tokenTypeMapCache = make(map[string]int)
var ruleIndexMapCache = make(map[string]int)
func (this *Recognizer) checkVersion(toolVersion string) {
func (this *BaseRecognizer) checkVersion(toolVersion string) {
var runtimeVersion = "4.5.2"
if runtimeVersion != toolVersion {
fmt.Println("ANTLR runtime and generated code versions disagree: " + runtimeVersion + "!=" + toolVersion)
}
}
func (this *Recognizer) Action(context IRuleContext, ruleIndex, actionIndex int) {
func (this *BaseRecognizer) Action(context IRuleContext, ruleIndex, actionIndex int) {
panic("action not implemented on Recognizer!")
}
func (this *Recognizer) addErrorListener(listener IErrorListener) {
func (this *BaseRecognizer) addErrorListener(listener IErrorListener) {
this._listeners = append(this._listeners, listener)
}
func (this *Recognizer) removeErrorListeners() {
func (this *BaseRecognizer) removeErrorListeners() {
this._listeners = make([]IErrorListener, 0)
}
func (this *Recognizer) GetRuleNames() []string {
func (this *BaseRecognizer) GetRuleNames() []string {
return this.RuleNames
}
func (this *Recognizer) GetTokenNames() []string {
func (this *BaseRecognizer) GetTokenNames() []string {
return this.LiteralNames
}
func (this *Recognizer) GetSymbolicNames() []string {
func (this *BaseRecognizer) GetSymbolicNames() []string {
return this.LiteralNames
}
func (this *Recognizer) GetLiteralNames() []string {
func (this *BaseRecognizer) GetLiteralNames() []string {
return this.LiteralNames
}
func (this *Recognizer) GetState() int {
func (this *BaseRecognizer) GetState() int {
return this.state
}
func (this *Recognizer) SetState(v int) {
func (this *BaseRecognizer) SetState(v int) {
if PortDebug {
fmt.Println("SETTING STATE " + strconv.Itoa(v) + " from " + strconv.Itoa(this.state))
}
@ -108,7 +108,7 @@ func (this *Recognizer) SetState(v int) {
//
// <p>Used for XPath and tree pattern compilation.</p>
//
func (this *Recognizer) getRuleIndexMap() map[string]int {
func (this *BaseRecognizer) getRuleIndexMap() map[string]int {
panic("Method not defined!")
// var ruleNames = this.GetRuleNames()
// if (ruleNames==nil) {
@ -123,7 +123,7 @@ func (this *Recognizer) getRuleIndexMap() map[string]int {
// return result
}
func (this *Recognizer) GetTokenType(tokenName string) int {
func (this *BaseRecognizer) GetTokenType(tokenName string) int {
panic("Method not defined!")
// var ttype = this.GetTokenTypeMap()[tokenName]
// if (ttype !=nil) {
@ -162,7 +162,7 @@ func (this *Recognizer) GetTokenType(tokenName string) int {
//}
// What is the error header, normally line/character position information?//
func (this *Recognizer) getErrorHeader(e IRecognitionException) string {
func (this *BaseRecognizer) getErrorHeader(e IRecognitionException) string {
var line = e.GetOffendingToken().GetLine()
var column = e.GetOffendingToken().GetColumn()
return "line " + strconv.Itoa(line) + ":" + strconv.Itoa(column)
@ -181,7 +181,7 @@ func (this *Recognizer) getErrorHeader(e IRecognitionException) string {
// feature when necessary. For example, see
// {@link DefaultErrorStrategy//GetTokenErrorDisplay}.
//
func (this *Recognizer) GetTokenErrorDisplay(t IToken) string {
func (this *BaseRecognizer) GetTokenErrorDisplay(t IToken) string {
if t == nil {
return "<no token>"
}
@ -200,16 +200,16 @@ func (this *Recognizer) GetTokenErrorDisplay(t IToken) string {
return "'" + s + "'"
}
func (this *Recognizer) getErrorListenerDispatch() IErrorListener {
func (this *BaseRecognizer) getErrorListenerDispatch() IErrorListener {
return NewProxyErrorListener(this._listeners)
}
// subclass needs to override these if there are sempreds or actions
// that the ATN interp needs to execute
func (this *Recognizer) Sempred(localctx IRuleContext, ruleIndex int, actionIndex int) bool {
func (this *BaseRecognizer) Sempred(localctx IRuleContext, ruleIndex int, actionIndex int) bool {
return true
}
func (this *Recognizer) Precpred(localctx IRuleContext, precedence int) bool {
func (this *BaseRecognizer) Precpred(localctx IRuleContext, precedence int) bool {
return true
}

View File

@ -160,7 +160,7 @@ func (this *RuleContext) accept(Visitor ParseTreeVisitor) interface{} {
// (root child1 .. childN). Print just a node if this is a leaf.
//
func (this *RuleContext) StringTree(ruleNames []string, recog IRecognizer) string {
func (this *RuleContext) StringTree(ruleNames []string, recog Recognizer) string {
return TreesStringTree(this, ruleNames, recog)
}

View File

@ -14,8 +14,8 @@ import (
//
type SemanticContext interface {
evaluate(parser IRecognizer, outerContext IRuleContext) bool
evalPrecedence(parser IRecognizer, outerContext IRuleContext) SemanticContext
evaluate(parser Recognizer, outerContext IRuleContext) bool
evalPrecedence(parser Recognizer, outerContext IRuleContext) SemanticContext
equals(interface{}) bool
String() string
}
@ -73,11 +73,11 @@ func NewPredicate(ruleIndex, predIndex int, isCtxDependent bool) *Predicate {
var SemanticContextNONE SemanticContext = NewPredicate(-1, -1, false)
func (this *Predicate) evalPrecedence(parser IRecognizer, outerContext IRuleContext) SemanticContext {
func (this *Predicate) evalPrecedence(parser Recognizer, outerContext IRuleContext) SemanticContext {
return this
}
func (this *Predicate) evaluate(parser IRecognizer, outerContext IRuleContext) bool {
func (this *Predicate) evaluate(parser Recognizer, outerContext IRuleContext) bool {
var localctx IRuleContext = nil
@ -120,11 +120,11 @@ func NewPrecedencePredicate(precedence int) *PrecedencePredicate {
return this
}
func (this *PrecedencePredicate) evaluate(parser IRecognizer, outerContext IRuleContext) bool {
func (this *PrecedencePredicate) evaluate(parser Recognizer, outerContext IRuleContext) bool {
return parser.Precpred(outerContext, this.precedence)
}
func (this *PrecedencePredicate) evalPrecedence(parser IRecognizer, outerContext IRuleContext) SemanticContext {
func (this *PrecedencePredicate) evalPrecedence(parser Recognizer, outerContext IRuleContext) SemanticContext {
if parser.Precpred(outerContext, this.precedence) {
return SemanticContextNONE
} else {
@ -243,7 +243,7 @@ func (this *AND) Hash() string {
// The evaluation of predicates by this context is short-circuiting, but
// unordered.</p>
//
func (this *AND) evaluate(parser IRecognizer, outerContext IRuleContext) bool {
func (this *AND) evaluate(parser Recognizer, outerContext IRuleContext) bool {
for i := 0; i < len(this.opnds); i++ {
if !this.opnds[i].evaluate(parser, outerContext) {
return false
@ -252,7 +252,7 @@ func (this *AND) evaluate(parser IRecognizer, outerContext IRuleContext) bool {
return true
}
func (this *AND) evalPrecedence(parser IRecognizer, outerContext IRuleContext) SemanticContext {
func (this *AND) evalPrecedence(parser Recognizer, outerContext IRuleContext) SemanticContext {
var differs = false
var operands = make([]SemanticContext, 0)
@ -379,7 +379,7 @@ func (this *OR) Hash() string {
// The evaluation of predicates by this context is short-circuiting, but
// unordered.</p>
//
func (this *OR) evaluate(parser IRecognizer, outerContext IRuleContext) bool {
func (this *OR) evaluate(parser Recognizer, outerContext IRuleContext) bool {
for i := 0; i < len(this.opnds); i++ {
if this.opnds[i].evaluate(parser, outerContext) {
return true
@ -388,7 +388,7 @@ func (this *OR) evaluate(parser IRecognizer, outerContext IRuleContext) bool {
return false
}
func (this *OR) evalPrecedence(parser IRecognizer, outerContext IRuleContext) SemanticContext {
func (this *OR) evalPrecedence(parser Recognizer, outerContext IRuleContext) SemanticContext {
var differs = false
var operands = make([]SemanticContext, 0)
for i := 0; i < len(this.opnds); i++ {

View File

@ -3,10 +3,10 @@ package antlr4
import "fmt"
type TraceListener struct {
parser *Parser
parser *BaseParser
}
func NewTraceListener(parser *Parser) *TraceListener {
func NewTraceListener(parser *BaseParser) *TraceListener {
tl := new(TraceListener)
tl.parser = parser
return tl

View File

@ -7,7 +7,7 @@ import "fmt"
// Print out a whole tree in LISP form. {@link //getNodeText} is used on the
// node payloads to get the text for the nodes. Detect
// parse trees and extract data appropriately.
func TreesStringTree(tree Tree, ruleNames []string, recog IRecognizer) string {
func TreesStringTree(tree Tree, ruleNames []string, recog Recognizer) string {
if recog != nil {
ruleNames = recog.GetRuleNames()
@ -33,7 +33,7 @@ func TreesStringTree(tree Tree, ruleNames []string, recog IRecognizer) string {
return res
}
func TreesgetNodeText(t Tree, ruleNames []string, recog *Parser) string {
func TreesgetNodeText(t Tree, ruleNames []string, recog *BaseParser) string {
if recog != nil {
ruleNames = recog.GetRuleNames()

View File

@ -12,32 +12,29 @@ var s = new antlr4.CommonTokenStream(l, 0);
var p = new ArithmeticParser(s);
p.buildParseTrees = true;
//KeyPrinter = function() {
// ArithmeticListener.call(this); // inherit default listener
// return this;
//};
//
//// inherit default listener
//KeyPrinter.prototype = Object.create(ArithmeticListener.prototype);
//KeyPrinter.prototype.constructor = KeyPrinter;
//
//// override default listener behavior
//KeyPrinter.prototype.exitAtom = function(ctx) {
//
// console.log("Oh, a atom!", ctx.start.source[1].strdata[ctx.start.start]);
//};
//
//KeyPrinter.prototype.exitExpression = function(ctx) {
//
// console.log("Oh, an expression!", ctx);
// throw new Error();
//};
KeyPrinter = function() {
ArithmeticListener.call(this); // inherit default listener
return this;
};
// inherit default listener
KeyPrinter.prototype = Object.create(ArithmeticListener.prototype);
KeyPrinter.prototype.constructor = KeyPrinter;
// override default listener behavior
KeyPrinter.prototype.exitAtom = function(ctx) {
console.log("Oh, a atom!");
};
KeyPrinter.prototype.exitExpression = function(ctx) {
console.log("Oh, an expression!");
};
var tree = p.equation();
//var printer = new KeyPrinter();
//antlr4.tree.ParseTreeWalker.DEFAULT.walk(printer, tree);
//console.log( tree.children[0].children[0].children[0].children );
var printer = new KeyPrinter();
antlr4.tree.ParseTreeWalker.DEFAULT.walk(printer, tree);
console.log( tree.children[0].children[0].children[0].children[0].children[0].children[0].children[0].symbol.column );