More work on ATN code

This commit is contained in:
Peter Boyer 2015-12-18 09:20:41 -05:00
parent 5d0b4dfa09
commit 40890f2122
34 changed files with 535 additions and 494 deletions

View File

@ -1,22 +1,19 @@
package atn
//var LL1Analyzer = require('./../LL1Analyzer').LL1Analyzer
//var IntervalSet = require('./../IntervalSet').IntervalSet
package antlr4
type ATN struct {
grammarType
maxTokenType
states
decisionToState
ruleToStartState
ruleToStopState
modeNameToStartState
ruleToTokenType
lexerActions
modeToStartState
grammarType *ATNType
maxTokenType int
states []*ATNState
decisionToState []DecisionState
ruleToStartState []RuleStartState
ruleToStopState []RuleStopState
modeNameToStartState map[string]TokensStartState
ruleToTokenType []int
lexerActions []LexerAction
modeToStartState []TokensStartState
}
func NewATN(grammarType , maxTokenType) *ATN {
func NewATN(grammarType *ATNType, maxTokenType int) *ATN {
atn := new(ATN)
@ -25,16 +22,16 @@ func NewATN(grammarType , maxTokenType) *ATN {
atn.grammarType = grammarType
// The maximum value for any symbol recognized by a transition in the ATN.
atn.maxTokenType = maxTokenType
atn.states = []
atn.states = make([]*ATNState)
// Each subrule/rule is a decision point and we must track them so we
// can go back later and build DFA predictors for them. This includes
// all the rules, subrules, optional blocks, ()+, ()* etc...
atn.decisionToState = []
atn.decisionToState = make([]*DecisionState)
// Maps from rule index to starting state number.
atn.ruleToStartState = []
atn.ruleToStartState = []RuleStartState
// Maps from rule index to stop state number.
atn.ruleToStopState = nil
atn.modeNameToStartState = {}
atn.modeNameToStartState = make( map[string]TokensStartState )
// For lexer ATNs, atn.maps the rule index to the resulting token type.
// For parser ATNs, atn.maps the rule index to the generated bypass token
// type if the
@ -44,7 +41,7 @@ func NewATN(grammarType , maxTokenType) *ATN {
// For lexer ATNs, atn.is an array of {@link LexerAction} objects which may
// be referenced by action transitions in the ATN.
atn.lexerActions = nil
atn.modeToStartState = []
atn.modeToStartState = make([]TokensStartState)
return atn
@ -54,7 +51,7 @@ func NewATN(grammarType , maxTokenType) *ATN {
// If {@code ctx} is nil, the set of tokens will not include what can follow
// the rule surrounding {@code s}. In other words, the set will be
// restricted to tokens reachable staying within {@code s}'s rule.
func (this *ATN) nextTokensInContext(s, ctx) {
func (this *ATN) nextTokensInContext(s *ATNState, ctx *RuleContext) *IntervalSet {
var anal = NewLL1Analyzer(this)
return anal.LOOK(s, nil, ctx)
}
@ -62,7 +59,7 @@ func (this *ATN) nextTokensInContext(s, ctx) {
// Compute the set of valid tokens that can occur starting in {@code s} and
// staying in same rule. {@link Token//EPSILON} is in set if we reach end of
// rule.
func (this *ATN) nextTokensNoContext(s) {
func (this *ATN) nextTokensNoContext(s *ATNState) *IntervalSet {
if (s.nextTokenWithinRule != nil ) {
return s.nextTokenWithinRule
}
@ -71,7 +68,7 @@ func (this *ATN) nextTokensNoContext(s) {
return s.nextTokenWithinRule
}
func (this *ATN) nextTokens(s, ctx) {
func (this *ATN) nextTokens(s *ATNState, ctx *RuleContext) *IntervalSet {
if ( ctx==nil ) {
return this.nextTokensNoContext(s)
} else {
@ -79,26 +76,26 @@ func (this *ATN) nextTokens(s, ctx) {
}
}
func (this *ATN) addState( state) {
func (this *ATN) addState( state *ATNState ) {
if ( state != nil ) {
state.atn = this
state.stateNumber = this.states.length
state.stateNumber = len(this.states)
}
this.states.push(state)
this.states = append(this.states, state)
}
func (this *ATN) removeState( state ) {
func (this *ATN) removeState( state *ATNState ) {
this.states[state.stateNumber] = nil // just free mem, don't shift states in list
}
func (this *ATN) defineDecisionState( s) {
this.decisionToState.push(s)
s.decision = this.decisionToState.length-1
func (this *ATN) defineDecisionState( s DecisionState) DecisionState {
append( this.decisionToState, s)
s.decision = len(this.decisionToState)-1
return s.decision
}
func (this *ATN) getDecisionState( decision) {
if (this.decisionToState.length==0) {
func (this *ATN) getDecisionState( decision int) DecisionState {
if (len(this.decisionToState)==0) {
return nil
} else {
return this.decisionToState[decision]
@ -125,12 +122,12 @@ func (this *ATN) getDecisionState( decision) {
//var Token = require('./../Token').Token
func (this *ATN) getExpectedTokens( stateNumber, ctx ) {
if ( stateNumber < 0 || stateNumber >= this.states.length ) {
func (this *ATN) getExpectedTokens( stateNumber int, ctx *RuleContext ) *IntervalSet {
if ( stateNumber < 0 || stateNumber >= len(this.states) ) {
panic("Invalid state number.")
}
var s = this.states[stateNumber]
var following = this.nextTokens(s)
var following = this.nextTokens(s, nil)
if (!following.contains(TokenEpsilon)) {
return following
}
@ -140,7 +137,7 @@ func (this *ATN) getExpectedTokens( stateNumber, ctx ) {
for (ctx != nil && ctx.invokingState >= 0 && following.contains(TokenEpsilon)) {
var invokingState = this.states[ctx.invokingState]
var rt = invokingState.transitions[0]
following = this.nextTokens(rt.followState)
following = this.nextTokens(rt.(RuleTransition).followState, nil)
expected.addSet(following)
expected.removeOne(TokenEpsilon)
ctx = ctx.parentCtx

View File

@ -1,7 +1,8 @@
package atn
package antlr4
import (
"antlr4"
"reflect"
"fmt"
)
// A tuple: (ATN state, predicted alt, syntactic, semantic context).
@ -16,8 +17,8 @@ type ATNConfig struct {
precedenceFilterSuppressed int
state *ATNState
alt int
context *antlr4.PredictionContext
semanticContext int
context *PredictionContext
semanticContext *SemanticContext
reachesIntoOuterContext int
}
@ -31,11 +32,11 @@ func NewATNConfig7(old *ATNConfig) *ATNConfig { // dup
return a
}
func NewATNConfig6(state *ATNState, alt int, context *antlr4.PredictionContext) *ATNConfig {
func NewATNConfig6(state *ATNState, alt int, context *PredictionContext) *ATNConfig {
return NewATNConfig(state, alt, context, SemanticContextNONE);
}
func NewATNConfig5(state *ATNState, alt int, context *antlr4.PredictionContext, semanticContext *SemanticContext) *ATNConfig {
func NewATNConfig5(state *ATNState, alt int, context *PredictionContext, semanticContext *SemanticContext) *ATNConfig {
a := new(ATNConfig)
a.state = state;
a.alt = alt;
@ -56,18 +57,25 @@ func NewATNConfig2(c *ATNConfig, semanticContext *SemanticContext) *ATNConfig {
return NewATNConfig(c, c.state, c.context, semanticContext);
}
func NewATNConfig1(c *ATNConfig, state *ATNState, context *antlr4.PredictionContext) *ATNConfig {
func NewATNConfig1(c *ATNConfig, state *ATNState, context *PredictionContext) *ATNConfig {
return NewATNConfig(c, state, context, c.semanticContext);
}
func NewATNConfig(c *ATNConfig, state *ATNState, context *antlr4.PredictionContext, semanticContext *SemanticContext) *ATNConfig {
func NewATNConfig(c *ATNConfig, state *ATNState, context *PredictionContext, semanticContext *SemanticContext) *ATNConfig {
a := new(ATNConfig)
a.initATNConfig2(c, state, context, semanticContext)
return a
}
func (a *ATNConfig) initATNConfig2(c *ATNConfig, state *ATNState, context *PredictionContext, semanticContext *SemanticContext) {
a.state = state;
a.alt = c.alt;
a.context = context;
a.semanticContext = semanticContext;
a.reachesIntoOuterContext = c.reachesIntoOuterContext;
return a
}
//
@ -156,47 +164,72 @@ func (this *ATNConfig) shortHashString() {
}
func (this *ATNConfig) hashString() {
return "" + this.state.stateNumber + "/" + this.alt + "/" +
(this.context==nil ? "" : this.context.hashString()) +
"/" + this.semanticContext.hashString()
var c string
if (this.context == nil){
c = ""
} else {
c = this.context.hashString()
}
return "" + this.state.stateNumber + "/" + this.alt + "/" + c + "/" + fmt.Sprint(this.semanticContext)
}
func (this *ATNConfig) toString() string {
return "(" + this.state + "," + this.alt +
(this.context!=nil ? ",[" + this.context.toString() + "]" : "") +
(this.semanticContext != SemanticContext.NONE ?
("," + this.semanticContext.toString())
: "") +
(this.reachesIntoOuterContext>0 ?
(",up=" + this.reachesIntoOuterContext)
: "") + ")"
var a string
if (this.context != nil){
a = ",[" + fmt.Sprint(this.context) + "]"
}
var b string
if (this.semanticContext != SemanticContextNONE){
b = ("," + fmt.Sprint(this.semanticContext))
}
var c string
if (this.reachesIntoOuterContext > 0){
c = ",up=" + this.reachesIntoOuterContext
}
return "(" + this.state + "," + this.alt + a + b + c + ")"
}
type LexerATNConfig struct {
ATNConfig
lexerActionExecutor *LexerActionExecutor
passedThroughNonGreedyDecision bool
}
func LexerATNConfig(params, config) {
ATNConfig.call(this, params, config)
// This is the backing field for {@link //getLexerActionExecutor}.
var lexerActionExecutor = params.lexerActionExecutor || nil
this.lexerActionExecutor = lexerActionExecutor || (config!=nil ? config.lexerActionExecutor : nil)
this.passedThroughNonGreedyDecision = config!=nil ? this.checkNonGreedyDecision(config, this.state) : false
func NewLexerATNConfig( state *ATNState, alt int, context *PredictionContext) *LexerATNConfig {
this := new(LexerATNConfig)
this.initATNConfig(state, alt, context, SemanticContextNONE)
this.lexerActionExecutor = nil
this.passedThroughNonGreedyDecision = false
return this
}
func (this *LexerATNConfig) hashString() {
var f string
if this.passedThroughNonGreedyDecision {
f = "1"
} else {
f = "0"
}
return "" + this.state.stateNumber + this.alt + this.context +
this.semanticContext + (this.passedThroughNonGreedyDecision ? 1 : 0) +
this.lexerActionExecutor
this.semanticContext + f + this.lexerActionExecutor
}
func (this *LexerATNConfig) equals(other) {
func (this *LexerATNConfig) equals(other *ATNConfig) bool {
if (this == other) {
return true
} else if (!_, ok := other.(LexerATNConfig); ok) {
} else if _, ok := other.(*LexerATNConfig); !ok {
return false
} else if (this.passedThroughNonGreedyDecision != other.passedThroughNonGreedyDecision) {
return false
@ -209,9 +242,9 @@ func (this *LexerATNConfig) equals(other) {
}
}
func (this *LexerATNConfig) checkNonGreedyDecision(source, target) {
return source.passedThroughNonGreedyDecision ||
_, ok := target.(DecisionState); ok && target.nonGreedy
}
//func (this *LexerATNConfig) checkNonGreedyDecision(source, target) {
// return source.passedThroughNonGreedyDecision ||
// _, ok := target.(DecisionState); ok && target.nonGreedy
//}

View File

@ -1,78 +1,90 @@
package atn
package antlr4
import (
"antlr4"
"math"
"fmt"
)
//
// 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.
///
//var ATN = require('./ATN').ATN
//var Utils = require('./../Utils')
//var Set = Utils.Set
//var SemanticContext = require('./SemanticContext').SemanticContext
//var merge = require('./../PredictionContext').merge
func hashATNConfig(c) {
func hashATNConfig(c *ATNConfig) string {
return c.shortHashString()
}
func equalATNConfigs(a, b) {
func equalATNConfigs(a, b *ATNConfig) bool {
if ( a==b ) {
return true
}
if ( a==nil || b==nil ) {
return false
}
return a.state.stateNumber==b.state.stateNumber &&
a.alt==b.alt && a.semanticContext.equals(b.semanticContext)
return a.state.stateNumber==b.state.stateNumber && a.alt==b.alt && a.semanticContext.equals(b.semanticContext)
}
type ATNConfigSet struct {
readOnly bool
fullCtx bool
configLookup Set
conflictingAlts BitSet
cachedHashString string
hasSemanticContext bool
dipsIntoOuterContext bool
configs []*ATNConfig
uniqueAlt int
}
func ATNConfigSet(fullCtx) {
//
// The reason that we need this is because we don't want the hash map to use
func NewATNConfigSet(fullCtx bool) *ATNConfigSet {
this := new(ATNConfigSet)
this.initATNConfigSet(fullCtx)
return this
}
func (a *ATNConfigSet) initATNConfigSet(fullCtx bool) {
// 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
// same
// {@code (s,i,_,semctx)} to be equal. Unfortunately, this key effectively
// {@code (s,i,_,semctx)} to be equal. Unfortunately, a.key effectively
// doubles
// the number of objects associated with ATNConfigs. The other solution is
// to
// use a hash table that lets us specify the equals/hashcode operation.
// All configs but hashed by (s, i, _, pi) not including context. Wiped out
// when we go readonly as this set becomes a DFA state.
this.configLookup = antlr4.NewSet(hashATNConfig, equalATNConfigs)
// Indicates that this configuration set is part of a full context
// when we go readonly as a.set becomes a DFA state.
a.configLookup = NewSet(hashATNConfig, equalATNConfigs)
// Indicates that a.configuration set is part of a full context
// LL prediction. It will be used to determine how to merge $. With SLL
// it's a wildcard whereas it is not for LL context merge.
this.fullCtx = fullCtx == nil ? true : fullCtx
a.fullCtx = fullCtx
// Indicates that the set of configurations is read-only. Do not
// allow any code to manipulate the set DFA states will point at
// the sets and they must not change. This does not protect the other
// the sets and they must not change. a.does not protect the other
// fields in particular, conflictingAlts is set after
// we've made this readonly.
this.readOnly = false
// we've made a.readonly.
a.readOnly = false
// Track the elements as they are added to the set supports get(i)///
this.configs = []
a.configs = make([]*ATNConfig)
// TODO: these fields make me pretty uncomfortable but nice to pack up info
// together, saves recomputation
// TODO: can we track conflicts as they are added to save scanning configs
// later?
this.uniqueAlt = 0
this.conflictingAlts = nil
a.uniqueAlt = 0
a.conflictingAlts = nil
// Used in parser and lexer. In lexer, it indicates we hit a pred
// while computing a closure operation. Don't make a DFA state from this.
this.hasSemanticContext = false
this.dipsIntoOuterContext = false
// while computing a closure operation. Don't make a DFA state from a.
a.hasSemanticContext = false
a.dipsIntoOuterContext = false
this.cachedHashString = "-1"
return this
a.cachedHashString = "-1"
}
// Adding a Newconfig means merging contexts with existing configs for
@ -84,23 +96,21 @@ func ATNConfigSet(fullCtx) {
// <p>This method updates {@link //dipsIntoOuterContext} and
// {@link //hasSemanticContext} when necessary.</p>
// /
func (this *ATNConfigSet) add(config, mergeCache) {
if (mergeCache == nil) {
mergeCache = nil
}
func (this *ATNConfigSet) add(config *ATNConfig, mergeCache DoubleDict) bool {
if (this.readOnly) {
panic "This set is readonly"
panic("This set is readonly")
}
if (config.semanticContext != SemanticContext.NONE) {
if (config.semanticContext != SemanticContextNONE) {
this.hasSemanticContext = true
}
if (config.reachesIntoOuterContext > 0) {
this.dipsIntoOuterContext = true
}
var existing = this.configLookup.add(config)
var existing *ATNConfig = this.configLookup.add(config).(*ATNConfig)
if (existing == config) {
this.cachedHashString = "-1"
this.configs.push(config) // track order here
this.configs = append(this.configs, config )// track order here
return true
}
// a previous (s,i,pi,_), merge with it and save result
@ -109,7 +119,7 @@ func (this *ATNConfigSet) add(config, mergeCache) {
// no need to check for existing.context, config.context in cache
// since only way to create Newgraphs is "call rule" and here. We
// cache at both places.
existing.reachesIntoOuterContext = Math.max( existing.reachesIntoOuterContext, config.reachesIntoOuterContext)
existing.reachesIntoOuterContext = math.Max( existing.reachesIntoOuterContext, config.reachesIntoOuterContext)
// make sure to preserve the precedence filter suppression during the merge
if (config.precedenceFilterSuppressed) {
existing.precedenceFilterSuppressed = true
@ -119,33 +129,31 @@ func (this *ATNConfigSet) add(config, mergeCache) {
}
func (this *ATNConfigSet) getStates() {
var states = antlr4.NewSet()
var states = NewSet()
for i := 0; i < len(this.configs); i++ {
states.add(this.configs[i].state)
}
return states
}
func (this *ATNConfigSet) getPredicates() {
var preds = []
func (this *ATNConfigSet) getPredicates() []SemanticContext {
var preds = make([]SemanticContext)
for i := 0; i < len(this.configs); i++ {
var c = this.configs[i].semanticContext
if (c != SemanticContext.NONE) {
preds.push(c.semanticContext)
if (c != SemanticContextNONE) {
preds = append(preds, c.semanticContext)
}
}
return preds
}
Object.defineProperty(ATNConfigSet.prototype, "items", {
get : function() {
return this.configs
}
})
func (this *ATNConfigSet) getItems() []*ATNConfig {
return this.configs
}
func (this *ATNConfigSet) optimizeConfigs(interpreter) {
func (this *ATNConfigSet) optimizeConfigs(interpreter *ATNSimulator) {
if (this.readOnly) {
panic "This set is readonly"
panic("This set is readonly")
}
if (this.configLookup.length == 0) {
return
@ -156,28 +164,31 @@ func (this *ATNConfigSet) optimizeConfigs(interpreter) {
}
}
func (this *ATNConfigSet) addAll(coll) {
func (this *ATNConfigSet) addAll(coll []*ATNConfig) bool{
for i := 0; i < len(coll); i++ {
this.add(coll[i])
}
return false
}
func (this *ATNConfigSet) equals(other) {
func (this *ATNConfigSet) equals(other interface{}) bool {
if (this == other) {
return true
} else if (!_, ok := other.(ATNConfigSet); ok) {
} else if _, ok := other.(*ATNConfigSet); !ok {
return false
}
return this.configs != nil && this.configs.equals(other.configs) &&
this.fullCtx == other.fullCtx &&
this.uniqueAlt == other.uniqueAlt &&
this.conflictingAlts == other.conflictingAlts &&
this.hasSemanticContext == other.hasSemanticContext &&
this.dipsIntoOuterContext == other.dipsIntoOuterContext
other2 := other.(*ATNConfigSet)
return this.configs != nil &&
this.configs.equals(other2.configs) &&
this.fullCtx == other2.fullCtx &&
this.uniqueAlt == other2.uniqueAlt &&
this.conflictingAlts == other2.conflictingAlts &&
this.hasSemanticContext == other2.hasSemanticContext &&
this.dipsIntoOuterContext == other2.dipsIntoOuterContext
}
func (this *ATNConfigSet) hashString() {
func (this *ATNConfigSet) hashString() string {
if (this.readOnly) {
if (this.cachedHashString == "-1") {
this.cachedHashString = this.hashConfigs()
@ -190,46 +201,44 @@ func (this *ATNConfigSet) hashString() {
func (this *ATNConfigSet) hashConfigs() {
var s = ""
this.configs.map(function(c) {
s += c.toString()
})
for _, c := range this.configs {
s += fmt.Sprint(c)
}
return s
}
Object.defineProperty(ATNConfigSet.prototype, "length", {
get : function() {
return this.configs.length
}
})
func (this *ATNConfigSet) length() int {
return this.configs.length
}
func (this *ATNConfigSet) isEmpty() {
func (this *ATNConfigSet) isEmpty() bool {
return this.configs.length == 0
}
func (this *ATNConfigSet) contains(item) {
func (this *ATNConfigSet) contains(item *ATNConfig ) bool {
if (this.configLookup == nil) {
panic "This method is not implemented for readonly sets."
panic("This method is not implemented for readonly sets.")
}
return this.configLookup.contains(item)
}
func (this *ATNConfigSet) containsFast(item) {
func (this *ATNConfigSet) containsFast(item *ATNConfig ) bool {
if (this.configLookup == nil) {
panic "This method is not implemented for readonly sets."
panic("This method is not implemented for readonly sets.")
}
return this.configLookup.containsFast(item)
}
func (this *ATNConfigSet) clear() {
if (this.readOnly) {
panic "This set is readonly"
panic("This set is readonly")
}
this.configs = []
this.configs = make([]*ATNConfig)
this.cachedHashString = "-1"
this.configLookup = antlr4.NewSet()
this.configLookup = NewSet(hashATNConfig, equalATNConfigs)
}
func (this *ATNConfigSet) setReadonly(readOnly) {
func (this *ATNConfigSet) setReadonly(readOnly bool) {
this.readOnly = readOnly
if (readOnly) {
this.configLookup = nil // can't mod, no need for lookup cache
@ -237,21 +246,29 @@ func (this *ATNConfigSet) setReadonly(readOnly) {
}
func (this *ATNConfigSet) toString() string {
return Utils.arrayToString(this.configs) +
(this.hasSemanticContext ? ",hasSemanticContext=" + this.hasSemanticContext : "") +
(this.uniqueAlt != ATN.INVALID_ALT_NUMBER ? ",uniqueAlt=" + this.uniqueAlt : "") +
(this.conflictingAlts != nil ? ",conflictingAlts=" + this.conflictingAlts : "") +
(this.dipsIntoOuterContext ? ",dipsIntoOuterContext" : "")
panic("not implemented")
return ""
// return Utils.arrayToString(this.configs) +
// (this.hasSemanticContext ? ",hasSemanticContext=" + this.hasSemanticContext : "") +
// (this.uniqueAlt != ATN.INVALID_ALT_NUMBER ? ",uniqueAlt=" + this.uniqueAlt : "") +
// (this.conflictingAlts != nil ? ",conflictingAlts=" + this.conflictingAlts : "") +
// (this.dipsIntoOuterContext ? ",dipsIntoOuterContext" : "")
}
type OrderedATNConfigSet struct {
ATNConfigSet.call(this)
this.configLookup = antlr4.NewSet()
ATNConfigSet
}
func NewOrderedATNConfigSet() *OrderedATNConfigSet {
this := new(OrderedATNConfigSet)
this.initATNConfigSet(false)
this.configLookup = NewSet(nil, nil)
return this
}
//OrderedATNConfigSet.prototype = Object.create(ATNConfigSet.prototype)
//OrderedATNConfigSet.prototype.constructor = OrderedATNConfigSet

View File

@ -1,18 +1,24 @@
package atn
package antlr4
func ATNDeserializationOptions(copyFrom) {
if(copyFrom==nil) {
copyFrom = nil
}
this.readOnly = false
this.verifyATN = copyFrom==nil ? true : copyFrom.verifyATN
this.generateRuleBypassTransitions = copyFrom==nil ? false : copyFrom.generateRuleBypassTransitions
return this
type ATNDeserializationOptions struct {
readOnly bool
verifyATN bool
generateRuleBypassTransitions bool
}
ATNDeserializationOptions.defaultOptions = NewATNDeserializationOptions()
ATNDeserializationOptions.defaultOptions.readOnly = true
func NewATNDeserializationOptions(copyFrom *ATNDeserializationOptions) *ATNDeserializationOptions {
o := new(ATNDeserializationOptions)
if (copyFrom != nil){
o.readOnly = copyFrom.readOnly
o.verifyATN = copyFrom.verifyATN
o.generateRuleBypassTransitions = copyFrom.generateRuleBypassTransitions
}
return o
}
var ATNDeserializationOptionsdefaultOptions = &ATNDeserializationOptions{true}
// func __setattr__(self, key, value):
// if key!="readOnly" and self.readOnly:

View File

@ -1,4 +1,4 @@
package atn
package antlr4
// This is the earliest supported serialized UUID.
// stick to serialized version for now, we don't need a UUID instance
@ -522,7 +522,7 @@ var byteToHex = createByteToHex()
func (this *ATNDeserializer) readUUID() {
var bb = []
for(var i=7i>=0i--) {
for i:=7;i>=0;i-- {
var int = this.readInt()
/* jshint bitwise: false */
bb[(2*i)+1] = int & 0xFF
@ -556,7 +556,7 @@ ATNDeserializer.prototype.edgeFactory = function(atn, type, src, trg, arg1, arg2
case Transition.ACTION:
return NewActionTransition(target, arg1, arg2, arg3 != 0)
case Transition.SET:
return antlr4.NewSetTransition(target, sets[arg1])
return NewSetTransition(target, sets[arg1])
case Transition.NOT_SET:
return NewNotSetTransition(target, sets[arg1])
case Transition.WILDCARD:

View File

@ -1,16 +1,14 @@
package atn
package antlr4
import (
"antlr4"
"antlr4/dfa"
)
)
type ATNSimulator struct {
atn *ATN
sharedContextCache *antlr4.PredictionContextCache
sharedContextCache *PredictionContextCache
}
func ATNSimulator(atn *ATN, sharedContextCache *antlr4.PredictionContextCache) *ATNSimulator {
func ATNSimulator(atn *ATN, sharedContextCache *PredictionContextCache) *ATNSimulator {
// The context cache maps all PredictionContext objects that are ==
// to a single cached copy. This cache is shared across all contexts
@ -41,13 +39,13 @@ func ATNSimulator(atn *ATN, sharedContextCache *antlr4.PredictionContextCache) *
}
// Must distinguish between missing edge and edge we know leads nowhere///
var ATNSimulatorERROR = dfa.NewDFAState(0x7FFFFFFF, NewATNConfigSet())
var ATNSimulatorERROR = NewDFAState(0x7FFFFFFF, NewATNConfigSet())
func (this *ATNSimulator) getCachedContext(context *antlr4.PredictionContext) *antlr4.PredictionContext {
func (this *ATNSimulator) getCachedContext(context *PredictionContext) *PredictionContext {
if (this.sharedContextCache == nil) {
return context
}
var visited = make(map[*antlr4.PredictionContext]*antlr4.PredictionContext)
var visited = make(map[*PredictionContext]*PredictionContext)
return getCachedPredictionContext(context, this.sharedContextCache, visited)
}

View File

@ -1,5 +1,4 @@
package atn
import "antlr4"
package antlr4
// The following images show the relation of states and
// {@link ATNState//transitions} for various grammar constructs.
@ -73,7 +72,7 @@ type ATNState struct {
// Track the transitions emanating from this ATN state.
transitions []*Transition
// Used to cache lookahead during parsing, not used during construction
nextTokenWithinRule *antlr4.Token
nextTokenWithinRule *Token
}
func NewATNState() *ATNState {

View File

@ -1,4 +1,4 @@
package atn
package antlr4
// Represents the type of recognizer an ATN applies to.

View File

@ -1,24 +1,35 @@
package dfa
//var DFAState = require('./DFAState').DFAState
//var ATNConfigSet = require('./../atn/ATNConfigSet').ATNConfigSet
//var DFASerializer = require('./DFASerializer').DFASerializer
//var LexerDFASerializer = require('./DFASerializer').LexerDFASerializer
package antlr4
type DFAStatesSet struct {
return this
states map[string]DFAState
}
Object.defineProperty(DFAStatesSet.prototype, "length", {
get : function() {
return Object.keys(this).length
}
})
func NewDFAStatesSet() *DFAStatesSet {
n := new(DFAStatesSet)
n.states = make(map[string]DFAState)
return n
}
func (this *DFAStatesSet) length() int {
return len(this.states)
}
type DFA struct {
atnStartState *DecisionState
decision int
_states *DFAStatesSet
s0 DFAState
precedenceDfa bool
}
func NewDFA(atnStartState *DecisionState, decision int) *DFA {
func DFA(atnStartState, decision) {
if (decision == nil) {
decision = 0
}
this := new(DFA)
// From which ATN state did we create this DFA?
this.atnStartState = atnStartState
this.decision = decision
@ -30,6 +41,7 @@ func DFA(atnStartState, decision) {
// {@code false}. This is the backing field for {@link //isPrecedenceDfa},
// {@link //setPrecedenceDfa}.
this.precedenceDfa = false
return this
}
@ -42,15 +54,15 @@ func DFA(atnStartState, decision) {
// @panics IllegalStateException if this is not a precedence DFA.
// @see //isPrecedenceDfa()
func (this *DFA) getPrecedenceStartState(precedence) {
func (this *DFA) getPrecedenceStartState(precedence int) *DFAState {
if (!(this.precedenceDfa)) {
panic ("Only precedence DFAs may contain a precedence start state.")
panic("Only precedence DFAs may contain a precedence start state.")
}
// s0.edges is never nil for a precedence DFA
if (precedence < 0 || precedence >= this.s0.edges.length) {
return nil
}
return this.s0.edges[precedence] || nil
return this.s0.edges[precedence]
}
// Set the start state for a specific precedence value.
@ -62,7 +74,7 @@ func (this *DFA) getPrecedenceStartState(precedence) {
// @panics IllegalStateException if this is not a precedence DFA.
// @see //isPrecedenceDfa()
//
func (this *DFA) setPrecedenceStartState(precedence, startState) {
func (this *DFA) setPrecedenceStartState(precedence int, startState *DFAState) {
if (!(this.precedenceDfa)) {
panic ("Only precedence DFAs may contain a precedence start state.")
}
@ -93,11 +105,11 @@ func (this *DFA) setPrecedenceStartState(precedence, startState) {
// @param precedenceDfa {@code true} if this is a precedence DFA otherwise,
// {@code false}
func (this *DFA) setPrecedenceDfa(precedenceDfa) {
func (this *DFA) setPrecedenceDfa(precedenceDfa bool) {
if (this.precedenceDfa!=precedenceDfa) {
this._states = NewDFAStatesSet()
if (precedenceDfa) {
var precedenceState = NewDFAState(NewATNConfigSet())
var precedenceState = NewDFAState(NewATNConfigSet(false))
precedenceState.edges = []
precedenceState.isAcceptState = false
precedenceState.requiresFullContext = false
@ -109,28 +121,28 @@ func (this *DFA) setPrecedenceDfa(precedenceDfa) {
}
}
Object.defineProperty(DFA.prototype, "states", {
get : function() {
return this._states
}
})
// Return a list of all states in this DFA, ordered by state number.
func (this *DFA) sortedStates() {
// states_ is a map of state/state, where key=value
var keys = Object.keys(this._states)
var list = []
for(var i=0i<keys.lengthi++) {
list.push(this._states[keys[i]])
}
return list.sort(function(a, b) {
return a.stateNumber - b.stateNumber
})
func (this *DFA) states(precedenceDfa bool) *DFAStatesSet {
return this._states
}
func (this *DFA) toString(literalNames, symbolicNames) {
literalNames = literalNames || nil
symbolicNames = symbolicNames || nil
// Return a list of all states in this DFA, ordered by state number.
func (this *DFA) sortedStates() []*DFAState {
panic("Not implemented")
return nil
// states_ is a map of state/state, where key=value
// var keys = Object.keys(this._states)
// var list = []
// for i:=0; i<keys.length; i++ {
// list.push(this._states[keys[i]])
// }
// return list.sort(function(a, b) {
// return a.stateNumber - b.stateNumber
// })
}
func (this *DFA) toString(literalNames []string, symbolicNames []string) string {
if (this.s0 == nil) {
return ""
}

View File

@ -1,4 +1,4 @@
package dfa
package antlr4
// A DFA walker that knows how to dump them to serialized strings.#/
@ -8,6 +8,8 @@ type DFASerializer struct {
}
func DFASerializer(dfa, literalNames, symbolicNames) {
this.dfa = dfa
this.literalNames = literalNames || []
this.symbolicNames = symbolicNames || []

View File

@ -1,17 +1,27 @@
package dfa
package antlr4
//var ATNConfigSet = require('./../atn/ATNConfigSet').ATNConfigSet
import (
"fmt"
)
// Map a predicate to a predicted alternative.///
func PredPrediction(pred, alt) {
type PredPrediction struct {
alt int
pred int
}
func NewPredPrediction(pred, alt int) *PredPrediction {
this := new(PredPrediction)
this.alt = alt
this.pred = pred
return this
}
func (this *PredPrediction) toString() string {
return "(" + this.pred + ", " + this.alt + ")"
return "(" + fmt.Sprint(this.pred) + ", " + fmt.Sprint(this.alt) + ")"
}
// A DFA state represents a set of possible ATN configurations.
@ -39,13 +49,25 @@ func (this *PredPrediction) toString() string {
// meaning that state was reached via a different set of rule invocations.</p>
// /
func DFAState(stateNumber, configs) {
if (stateNumber == nil) {
stateNumber = -1
}
type DFAState struct {
stateNumber int
configs *ATNConfigSet
edges []*DFAState
isAcceptState bool
prediction int
lexerActionExecutor *LexerActionExecutor
requiresFullContext bool
predicates []PredPrediction
}
func NewDFAState(stateNumber int, configs *NewATNConfigSet) *DFAState {
if (configs == nil) {
configs = NewATNConfigSet()
configs = NewATNConfigSet(false)
}
this := new(DFAState)
this.stateNumber = stateNumber
this.configs = configs
// {@code edges[symbol]} points to target of symbol. Shift up by 1 so (-1)
@ -84,7 +106,7 @@ func DFAState(stateNumber, configs) {
// Get the set of all alts mentioned by all ATN configurations in this
// DFA state.
func (this *DFAState) getAltSet() {
var alts = NewSet()
var alts = NewSet(nil,nil)
if (this.configs != nil) {
for i := 0; i < len(this.configs); i++ {
var c = this.configs[i]
@ -109,28 +131,35 @@ func (this *DFAState) getAltSet() {
// {@link ParserATNSimulator//addDFAState} we need to know if any other state
// exists that has this exact set of ATN configurations. The
// {@link //stateNumber} is irrelevant.</p>
func (this *DFAState) equals(other) {
// compare set of ATN configurations in this set with other
func (this *DFAState) equals(other interface{}) bool {
if (this == other) {
return true
} else if (!_, ok := other.(DFAState); ok) {
} else if _, ok := other.(*DFAState); !ok {
return false
} else {
return this.configs.equals(other.configs)
}
return this.configs.equals(other.configs)
}
func (this *DFAState) toString() string {
return "" + this.stateNumber + ":" + this.hashString()
}
func (this *DFAState) hashString() {
return "" + this.configs +
(this.isAcceptState ?
"=>" + (this.predicates != nil ?
this.predicates :
this.prediction) :
"")
func (this *DFAState) hashString() string {
panic("Not implementd")
// var s string
// if (this.acceptState){
//
// }
//
// return "" + this.configs +
// (this.isAcceptState ?
// "=>" + (this.predicates != nil ?
// this.predicates :
// this.prediction) :
// "")
}

View File

@ -1,9 +1,4 @@
package error
import (
"antlr4"
"antlr4/atn"
"antlr4/dfa"
)
package antlr4
//
// This implementation of {@link ANTLRErrorListener} can be used to identify
@ -45,7 +40,7 @@ func DiagnosticErrorListener(exactOnly bool) {
//DiagnosticErrorListener.prototype = Object.create(ErrorListener.prototype)
//DiagnosticErrorListener.prototype.constructor = DiagnosticErrorListener
func (this *DiagnosticErrorListener) reportAmbiguity(recognizer *antlr4.Parser, dfa *dfa.DFA, startIndex, stopIndex int, exact bool, ambigAlts *antlr4.BitSet, configs *atn.ATNConfigSet) {
func (this *DiagnosticErrorListener) reportAmbiguity(recognizer *Parser, dfa *DFA, startIndex, stopIndex int, exact bool, ambigAlts *BitSet, configs *ATNConfigSet) {
if (this.exactOnly && !exact) {
return
}
@ -58,7 +53,7 @@ func (this *DiagnosticErrorListener) reportAmbiguity(recognizer *antlr4.Parser,
recognizer.notifyErrorListeners(msg)
}
func (this *DiagnosticErrorListener) reportAttemptingFullContext(recognizer *antlr4.Parser, dfa *dfa.DFA, startIndex, stopIndex int, conflictingAlts *antlr4.BitSet, configs *atn.ATNConfigSet) {
func (this *DiagnosticErrorListener) reportAttemptingFullContext(recognizer *Parser, dfa *DFA, startIndex, stopIndex int, conflictingAlts *BitSet, configs *ATNConfigSet) {
var msg = "reportAttemptingFullContext d=" +
this.getDecisionDescription(recognizer, dfa) +
@ -67,7 +62,7 @@ func (this *DiagnosticErrorListener) reportAttemptingFullContext(recognizer *ant
recognizer.notifyErrorListeners(msg)
}
func (this *DiagnosticErrorListener) reportContextSensitivity(recognizer *antlr4.Parser, dfa *dfa.DFA, startIndex, stopIndex, prediction int, configs *atn.ATNConfigSet) {
func (this *DiagnosticErrorListener) reportContextSensitivity(recognizer *Parser, dfa *DFA, startIndex, stopIndex, prediction int, configs *ATNConfigSet) {
var msg = "reportContextSensitivity d=" +
this.getDecisionDescription(recognizer, dfa) +
", input='" +
@ -75,7 +70,7 @@ func (this *DiagnosticErrorListener) reportContextSensitivity(recognizer *antlr4
recognizer.notifyErrorListeners(msg)
}
func (this *DiagnosticErrorListener) getDecisionDescription(recognizer *antlr4.Parser, dfa *dfa.DFA) {
func (this *DiagnosticErrorListener) getDecisionDescription(recognizer *Parser, dfa *DFA) {
var decision = dfa.decision
var ruleIndex = dfa.atnStartState.ruleIndex
@ -105,7 +100,7 @@ func (this *DiagnosticErrorListener) getConflictingAlts(reportedAlts, configs) {
if (reportedAlts != nil) {
return reportedAlts
}
var result = antlr4.NewBitSet()
var result = NewBitSet()
for i := 0; i < len(configs.items); i++ {
result.add(configs.items[i].alt)
}

View File

@ -1,10 +1,7 @@
package error
package antlr4
import (
"antlr4"
"antlr4/atn"
"antlr4/dfa"
"fmt"
"fmt"
)
// Provides an empty default implementation of {@link ANTLRErrorListener}. The
@ -19,16 +16,16 @@ func NewErrorListener() *ErrorListener {
return new(ErrorListener)
}
func (this *ErrorListener) syntaxError(recognizer *antlr4.Parser, offendingSymbol interface{}, line, column int, msg string, e *RecognitionException) {
func (this *ErrorListener) syntaxError(recognizer *Parser, offendingSymbol interface{}, line, column int, msg string, e *RecognitionException) {
}
func (this *ErrorListener) reportAmbiguity(recognizer *antlr4.Parser, dfa *dfa.DFA, startIndex, stopIndex int, exact bool, ambigAlts *antlr4.BitSet, configs *atn.ATNConfigSet) {
func (this *ErrorListener) reportAmbiguity(recognizer *Parser, dfa *DFA, startIndex, stopIndex int, exact bool, ambigAlts *BitSet, configs *ATNConfigSet) {
}
func (this *ErrorListener) reportAttemptingFullContext(recognizer *antlr4.Parser, dfa *dfa.DFA, startIndex, stopIndex int, conflictingAlts *antlr4.BitSet, configs *atn.ATNConfigSet) {
func (this *ErrorListener) reportAttemptingFullContext(recognizer *Parser, dfa *DFA, startIndex, stopIndex int, conflictingAlts *BitSet, configs *ATNConfigSet) {
}
func (this *ErrorListener) reportContextSensitivity(recognizer *antlr4.Parser, dfa *dfa.DFA, startIndex, stopIndex, prediction int, configs *atn.ATNConfigSet) {
func (this *ErrorListener) reportContextSensitivity(recognizer *Parser, dfa *DFA, startIndex, stopIndex, prediction int, configs *ATNConfigSet) {
}
type ConsoleErrorListener struct {
@ -56,7 +53,7 @@ var ConsoleErrorListenerINSTANCE = NewConsoleErrorListener()
// line <em>line</em>:<em>charPositionInLine</em> <em>msg</em>
// </pre>
//
func (this *ConsoleErrorListener) syntaxError(recognizer *antlr4.Parser, offendingSymbol interface{}, line, column int, msg string, e *RecognitionException) {
func (this *ConsoleErrorListener) syntaxError(recognizer *Parser, offendingSymbol interface{}, line, column int, msg string, e *RecognitionException) {
fmt.Errorf("line " + line + ":" + column + " " + msg)
}
@ -74,25 +71,25 @@ func NewProxyErrorListener(delegates []ErrorListener) *ConsoleErrorListener {
return l
}
func (this *ProxyErrorListener) syntaxError(recognizer *antlr4.Parser, offendingSymbol interface{}, line, column int, msg string, e *RecognitionException) {
func (this *ProxyErrorListener) syntaxError(recognizer *Parser, offendingSymbol interface{}, line, column int, msg string, e *RecognitionException) {
for _,d := range this.delegates {
d.syntaxError(recognizer, offendingSymbol, line, column, msg, e)
}
}
func (this *ProxyErrorListener) reportAmbiguity(recognizer *antlr4.Parser, dfa *dfa.DFA, startIndex, stopIndex int, exact bool, ambigAlts *antlr4.BitSet, configs *atn.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 *antlr4.Parser, dfa *dfa.DFA, startIndex, stopIndex int, conflictingAlts *antlr4.BitSet, configs *atn.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 *antlr4.Parser, dfa *dfa.DFA, startIndex, stopIndex, prediction int, configs *atn.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

@ -1,9 +1,7 @@
package error
package antlr4
import (
"fmt"
"antlr4"
"antlr4/atn"
"strings"
)
@ -11,22 +9,22 @@ type ErrorStrategy struct {
}
func (this *ErrorStrategy) reset(recognizer *antlr4.Parser){
func (this *ErrorStrategy) reset(recognizer *Parser){
}
func (this *ErrorStrategy) recoverInline(recognizer *antlr4.Parser){
func (this *ErrorStrategy) recoverInline(recognizer *Parser){
}
func (this *ErrorStrategy) recover(recognizer *antlr4.Parser, e *Error){
func (this *ErrorStrategy) recover(recognizer *Parser, e *Error){
}
func (this *ErrorStrategy) sync(recognizer *antlr4.Parser){
func (this *ErrorStrategy) sync(recognizer *Parser){
}
func (this *ErrorStrategy) inErrorRecoveryMode(recognizer *antlr4.Parser){
func (this *ErrorStrategy) inErrorRecoveryMode(recognizer *Parser){
}
func (this *ErrorStrategy) reportError(recognizer *antlr4.Parser){
func (this *ErrorStrategy) reportError(recognizer *Parser){
}
// This is the default implementation of {@link ANTLRErrorStrategy} used for
@ -69,7 +67,7 @@ func DefaultErrorStrategy() *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 *antlr4.Parser) {
func (this *DefaultErrorStrategy) reset(recognizer *Parser) {
this.endErrorCondition(recognizer)
}
@ -79,11 +77,11 @@ func (this *DefaultErrorStrategy) reset(recognizer *antlr4.Parser) {
//
// @param recognizer the parser instance
//
func (this *DefaultErrorStrategy) beginErrorCondition(recognizer *antlr4.Parser) {
func (this *DefaultErrorStrategy) beginErrorCondition(recognizer *Parser) {
this.errorRecoveryMode = true
}
func (this *DefaultErrorStrategy) inErrorRecoveryMode(recognizer *antlr4.Parser) {
func (this *DefaultErrorStrategy) inErrorRecoveryMode(recognizer *Parser) {
return this.errorRecoveryMode
}
@ -93,7 +91,7 @@ func (this *DefaultErrorStrategy) inErrorRecoveryMode(recognizer *antlr4.Parser)
//
// @param recognizer
//
func (this *DefaultErrorStrategy) endErrorCondition(recognizer *antlr4.Parser) {
func (this *DefaultErrorStrategy) endErrorCondition(recognizer *Parser) {
this.errorRecoveryMode = false
this.lastErrorStates = nil
this.lastErrorIndex = -1
@ -104,7 +102,7 @@ func (this *DefaultErrorStrategy) endErrorCondition(recognizer *antlr4.Parser) {
//
// <p>The default implementation simply calls {@link //endErrorCondition}.</p>
//
func (this *DefaultErrorStrategy) reportMatch(recognizer *antlr4.Parser) {
func (this *DefaultErrorStrategy) reportMatch(recognizer *Parser) {
this.endErrorCondition(recognizer)
}
@ -127,7 +125,7 @@ func (this *DefaultErrorStrategy) reportMatch(recognizer *antlr4.Parser) {
// the exception</li>
// </ul>
//
func (this *DefaultErrorStrategy) reportError(recognizer *antlr4.Parser, e *) {
func (this *DefaultErrorStrategy) reportError(recognizer *Parser, e *) {
// if we've already reported an error and have not matched a token
// yet successfully, don't report any errors.
if(this.inErrorRecoveryMode(recognizer)) {
@ -155,7 +153,7 @@ func (this *DefaultErrorStrategy) reportError(recognizer *antlr4.Parser, e *) {
// 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 *antlr4.Parser, e *RecognitionException) {
func (this *DefaultErrorStrategy) recover(recognizer *Parser, e *RecognitionException) {
if (this.lastErrorIndex==recognizer.getInputStream().index &&
this.lastErrorStates != nil && this.lastErrorStates.indexOf(recognizer.state)>=0) {
// uh oh, another error at same token index and previously-visited
@ -218,7 +216,7 @@ func (this *DefaultErrorStrategy) recover(recognizer *antlr4.Parser, e *Recognit
// 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 *antlr4.Parser) {
func (this *DefaultErrorStrategy) sync(recognizer *Parser) {
// If already recovering, don't try to sync
if (this.inErrorRecoveryMode(recognizer)) {
return
@ -226,7 +224,7 @@ func (this *DefaultErrorStrategy) sync(recognizer *antlr4.Parser) {
var s = recognizer._interp.atn.states[recognizer.state]
var la = recognizer.getTokenStream().LA(1)
// try cheaper subset first might get lucky. seems to shave a wee bit off
if (la==antlr4.TokenEOF || recognizer.atn.nextTokens(s).contains(la)) {
if (la==TokenEOF || recognizer.atn.nextTokens(s).contains(la)) {
return
}
// Return but don't end recovery. only do that upon valid token match
@ -234,10 +232,10 @@ func (this *DefaultErrorStrategy) sync(recognizer *antlr4.Parser) {
return
}
switch (s.stateType *RecognitionException) {
case atn.ATNStateBLOCK_START:
case atn.ATNStateSTAR_BLOCK_START:
case atn.ATNStatePLUS_BLOCK_START:
case atn.ATNStateSTAR_LOOP_ENTRY:
case ATNStateBLOCK_START:
case ATNStateSTAR_BLOCK_START:
case ATNStatePLUS_BLOCK_START:
case ATNStateSTAR_LOOP_ENTRY:
// report error and recover if possible
if( this.singleTokenDeletion(recognizer) != nil) {
return
@ -245,10 +243,10 @@ func (this *DefaultErrorStrategy) sync(recognizer *antlr4.Parser) {
panic(NewInputMismatchException(recognizer))
}
break
case atn.ATNStatePLUS_LOOP_BACK:
case atn.ATNStateSTAR_LOOP_BACK:
case ATNStatePLUS_LOOP_BACK:
case ATNStateSTAR_LOOP_BACK:
this.reportUnwantedToken(recognizer)
var expecting = antlr4.NewIntervalSet()
var expecting = NewIntervalSet()
expecting.addSet(recognizer.getExpectedTokens())
var whatFollowsLoopIterationOrRule = expecting.addSet(this.getErrorRecoverySet(recognizer))
this.consumeUntil(recognizer, whatFollowsLoopIterationOrRule)
@ -266,11 +264,11 @@ func (this *DefaultErrorStrategy) sync(recognizer *antlr4.Parser) {
// @param recognizer the parser instance
// @param e the recognition exception
//
func (this *DefaultErrorStrategy) reportNoViableAlternative(recognizer *antlr4.Parser, e *RecognitionException) {
func (this *DefaultErrorStrategy) reportNoViableAlternative(recognizer *Parser, e *RecognitionException) {
var tokens = recognizer.getTokenStream()
var input
if(tokens != nil) {
if (e.startToken.tokenType==antlr4.TokenEOF) {
if (e.startToken.tokenType==TokenEOF) {
input = "<EOF>"
} else {
input = tokens.getText(NewInterval(e.startToken, e.offendingToken))
@ -291,7 +289,7 @@ func (this *DefaultErrorStrategy) reportNoViableAlternative(recognizer *antlr4.P
// @param recognizer the parser instance
// @param e the recognition exception
//
func (this *DefaultErrorStrategy) reportInputMismatch(recognizer *antlr4.Parser, e *RecognitionException) {
func (this *DefaultErrorStrategy) reportInputMismatch(recognizer *Parser, e *RecognitionException) {
var msg = "mismatched input " + this.getTokenErrorDisplay(e.offendingToken) +
" expecting " + e.getExpectedTokens().toString(recognizer.literalNames, recognizer.symbolicNames)
recognizer.notifyErrorListeners(msg, e.offendingToken, e)
@ -306,7 +304,7 @@ func (this *DefaultErrorStrategy) reportInputMismatch(recognizer *antlr4.Parser,
// @param recognizer the parser instance
// @param e the recognition exception
//
func (this *DefaultErrorStrategy) reportFailedPredicate(recognizer *antlr4.Parser, e *RecognitionException) {
func (this *DefaultErrorStrategy) reportFailedPredicate(recognizer *Parser, e *RecognitionException) {
var ruleName = recognizer.ruleNames[recognizer._ctx.ruleIndex]
var msg = "rule " + ruleName + " " + e.message
recognizer.notifyErrorListeners(msg, e.offendingToken, e)
@ -329,7 +327,7 @@ func (this *DefaultErrorStrategy) reportFailedPredicate(recognizer *antlr4.Parse
//
// @param recognizer the parser instance
//
func (this *DefaultErrorStrategy) reportUnwantedToken(recognizer *antlr4.Parser) {
func (this *DefaultErrorStrategy) reportUnwantedToken(recognizer *Parser) {
if (this.inErrorRecoveryMode(recognizer)) {
return
}
@ -357,7 +355,7 @@ func (this *DefaultErrorStrategy) reportUnwantedToken(recognizer *antlr4.Parser)
//
// @param recognizer the parser instance
//
func (this *DefaultErrorStrategy) reportMissingToken(recognizer *antlr4.Parser) {
func (this *DefaultErrorStrategy) reportMissingToken(recognizer *Parser) {
if ( this.inErrorRecoveryMode(recognizer)) {
return
}
@ -418,7 +416,7 @@ func (this *DefaultErrorStrategy) reportMissingToken(recognizer *antlr4.Parser)
// 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 *antlr4.Parser) {
func (this *DefaultErrorStrategy) recoverInline(recognizer *Parser) {
// SINGLE TOKEN DELETION
var matchedSymbol = this.singleTokenDeletion(recognizer)
if (matchedSymbol != nil) {
@ -452,7 +450,7 @@ func (this *DefaultErrorStrategy) recoverInline(recognizer *antlr4.Parser) {
// @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 *antlr4.Parser) {
func (this *DefaultErrorStrategy) singleTokenInsertion(recognizer *Parser) {
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
@ -487,7 +485,7 @@ func (this *DefaultErrorStrategy) singleTokenInsertion(recognizer *antlr4.Parser
// deletion successfully recovers from the mismatched input, otherwise
// {@code nil}
//
func (this *DefaultErrorStrategy) singleTokenDeletion(recognizer *antlr4.Parser) {
func (this *DefaultErrorStrategy) singleTokenDeletion(recognizer *Parser) {
var nextTokenType = recognizer.getTokenStream().LA(2)
var expecting = this.getExpectedTokens(recognizer)
if (expecting.contains(nextTokenType)) {
@ -525,25 +523,25 @@ func (this *DefaultErrorStrategy) singleTokenDeletion(recognizer *antlr4.Parser)
// If you change what tokens must be created by the lexer,
// override this method to create the appropriate tokens.
//
func (this *DefaultErrorStrategy) getMissingSymbol(recognizer *antlr4.Parser) {
func (this *DefaultErrorStrategy) getMissingSymbol(recognizer *Parser) {
var currentSymbol = recognizer.getCurrentToken()
var expecting = this.getExpectedTokens(recognizer)
var expectedTokenType = expecting.first() // get any element
var tokenText
if (expectedTokenType==antlr4.TokenEOF) {
if (expectedTokenType==TokenEOF) {
tokenText = "<missing EOF>"
} else {
tokenText = "<missing " + recognizer.literalNames[expectedTokenType] + ">"
}
var current = currentSymbol
var lookback = recognizer.getTokenStream().LT(-1)
if (current.tokenType==antlr4.TokenEOF && lookback != nil) {
if (current.tokenType==TokenEOF && lookback != nil) {
current = lookback
}
return recognizer.getTokenFactory().create(current.source, expectedTokenType, tokenText, TokenDefaultChannel, -1, -1, current.line, current.column)
}
func (this *DefaultErrorStrategy) getExpectedTokens(recognizer *antlr4.Parser) {
func (this *DefaultErrorStrategy) getExpectedTokens(recognizer *Parser) {
return recognizer.getExpectedTokens()
}
@ -555,13 +553,13 @@ func (this *DefaultErrorStrategy) getExpectedTokens(recognizer *antlr4.Parser) {
// your token objects because you don't have to go modify your lexer
// so that it creates a NewJava type.
//
func (this *DefaultErrorStrategy) getTokenErrorDisplay(t *antlr4.Token) string {
func (this *DefaultErrorStrategy) getTokenErrorDisplay(t *Token) string {
if (t == nil) {
return "<no token>"
}
var s = t.text
if (s == nil) {
if (t.tokenType==antlr4.TokenEOF) {
if (t.tokenType==TokenEOF) {
s = "<EOF>"
} else {
s = "<" + t.tokenType + ">"
@ -669,10 +667,10 @@ 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 *antlr4.Parser) *antlr4.IntervalSet {
func (this *DefaultErrorStrategy) getErrorRecoverySet(recognizer *Parser) *IntervalSet {
var atn = recognizer._interp.atn
var ctx = recognizer._ctx
var recoverSet = antlr4.NewIntervalSet()
var recoverSet = NewIntervalSet()
for (ctx != nil && ctx.invokingState>=0) {
// compute what follows who invoked us
var invokingState = atn.states[ctx.invokingState]
@ -686,9 +684,9 @@ func (this *DefaultErrorStrategy) getErrorRecoverySet(recognizer *antlr4.Parser)
}
// Consume tokens until one matches the given token set.//
func (this *DefaultErrorStrategy) consumeUntil(recognizer *antlr4.Parser, set) {
func (this *DefaultErrorStrategy) consumeUntil(recognizer *Parser, set) {
var ttype = recognizer.getTokenStream().LA(1)
for( ttype != antlr4.antlr4.TokenEOF && !set.contains(ttype)) {
for( ttype != TokenEOF && !set.contains(ttype)) {
recognizer.consume()
ttype = recognizer.getTokenStream().LA(1)
}
@ -735,7 +733,7 @@ type BailErrorStrategy struct {
// rule func catches. Use {@link Exception//getCause()} to get the
// original {@link RecognitionException}.
//
func (this *BailErrorStrategy) recover(recognizer *antlr4.Parser, e *RecognitionException) {
func (this *BailErrorStrategy) recover(recognizer *Parser, e *RecognitionException) {
var context = recognizer._ctx
for (context != nil) {
context.exception = e
@ -747,12 +745,12 @@ func (this *BailErrorStrategy) recover(recognizer *antlr4.Parser, e *Recognition
// 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 *antlr4.Parser) {
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 *antlr4.Parser) {
func (this *BailErrorStrategy) sync(recognizer *Parser) {
// pass
}

View File

@ -1,8 +1,7 @@
package error
package antlr4
import (
"antlr4"
)
)
// The root of the ANTLR exception hierarchy. In general, ANTLR tracks just
// 3 kinds of errors: prediction errors, failed predicate errors, and
@ -15,7 +14,7 @@ import (
type RecognitionException struct {
message string
recognizer antlr4.Recognizer
recognizer Recognizer
}

View File

@ -1,14 +1,13 @@
package antlr4
import (
"antlr4/atn"
)
)
type LL1Analyzer struct {
atn *atn.ATN
atn *ATN
}
func NewLL1Analyzer (atn *atn.ATN) *LL1Analyzer {
func NewLL1Analyzer (atn *ATN) *LL1Analyzer {
la := new(LL1Analyzer)
la.atn = atn
return la
@ -30,7 +29,7 @@ const (
//
// @param s the ATN state
// @return the expected symbols for each outgoing transition of {@code s}.
func (la *LL1Analyzer) getDecisionLookahead(s *atn.ATNState) []*IntervalSet {
func (la *LL1Analyzer) getDecisionLookahead(s *ATNState) []*IntervalSet {
if (s == nil) {
return nil
}
@ -110,9 +109,9 @@ func (la *LL1Analyzer) LOOK(s, stopState int, ctx *RuleContext) *IntervalSet {
// is {@code nil}.
func (la *LL1Analyzer) _LOOK(s, stopState *atn.ATNState, ctx *PredictionContext, look *IntervalSet, lookBusy *Set, calledRuleStack *BitSet, seeThruPreds, addEOF bool) {
func (la *LL1Analyzer) _LOOK(s, stopState *ATNState, ctx *PredictionContext, look *IntervalSet, lookBusy *Set, calledRuleStack *BitSet, seeThruPreds, addEOF bool) {
c := atn.NewATNConfig6(s, 0, ctx)
c := NewATNConfig6(s, 0, ctx)
if !lookBusy.add(c) {
return
@ -128,7 +127,7 @@ func (la *LL1Analyzer) _LOOK(s, stopState *atn.ATNState, ctx *PredictionContext,
}
}
_,ok := s.(atn.RuleStopState)
_,ok := s.(RuleStopState)
if ok {
if ( ctx==nil ) {
@ -168,7 +167,7 @@ func (la *LL1Analyzer) _LOOK(s, stopState *atn.ATNState, ctx *PredictionContext,
for i:=0; i<n; i++ {
t := s.transitions[i]
if t1, ok := t.(*atn.RuleTransition); ok {
if t1, ok := t.(*RuleTransition); ok {
if (calledRuleStack.get(t1.target.ruleIndex)) {
continue
@ -182,7 +181,7 @@ func (la *LL1Analyzer) _LOOK(s, stopState *atn.ATNState, ctx *PredictionContext,
calledRuleStack.set(t1.target.ruleIndex)
la._LOOK(t.target, stopState, newContext, look, lookBusy, calledRuleStack, seeThruPreds, addEOF)
} else if t2, ok := t.(*atn.AbstractPredicateTransition); ok {
} else if t2, ok := t.(*AbstractPredicateTransition); ok {
if ( seeThruPreds ) {
la._LOOK(t2.target, stopState, ctx, look, lookBusy, calledRuleStack, seeThruPreds, addEOF)
} else {
@ -190,12 +189,12 @@ func (la *LL1Analyzer) _LOOK(s, stopState *atn.ATNState, ctx *PredictionContext,
}
} else if ( t.isEpsilon() ) {
la._LOOK(t.target, stopState, ctx, look, lookBusy, calledRuleStack, seeThruPreds, addEOF)
} else if _, ok := t.(*atn.WildcardTransition); ok {
} else if _, ok := t.(*WildcardTransition); ok {
look.addRange( TokenMinUserTokenType, la.atn.maxTokenType );
} else {
set := t.label()
if (set != nil) {
if _, ok := t.(*atn.NotSetTransition); ok {
if _, ok := t.(*NotSetTransition); ok {
set = set.complement(TokenMinUserTokenType, la.atn.maxTokenType);
}
look.addAll(set)

View File

@ -3,7 +3,6 @@ package antlr4
import (
"strings"
"fmt"
"antlr4/atn"
)
// A lexer is recognizer that draws input symbols from a character stream.
@ -33,7 +32,7 @@ type Lexer struct {
_input *InputStream
_factory *TokenFactory
_tokenFactorySourcePair *TokenFactorySourcePair
_interp *atn.LexerATNSimulator
_interp *LexerATNSimulator
_token int
_tokenStartCharIndex int
_tokenStartLine int
@ -365,7 +364,7 @@ func (l *Lexer) getCharErrorDisplay(c) string {
// /
func (l *Lexer) recover(re error) {
if (l._input.LA(1) != TokenEOF) {
if _, ok := re.(error.LexerNoViableAltException); ok {
if _, ok := re.(LexerNoViableAltException); ok {
// skip a char and try again
l._interp.consume(l._input)
} else {

View File

@ -1,7 +1,6 @@
package atn
package antlr4
import (
"antlr4/dfa"
"fmt"
"fmt"
)
// When we hit an accept state in either the DFA or the ATN, we
@ -31,7 +30,7 @@ type SimState struct {
index int
line int
column int
dfaState *dfa.DFAState
dfaState *DFAState
}
func NewSimState() *SimState {

View File

@ -1,4 +1,4 @@
package atn
package antlr4
type LexerActionType struct {
}

View File

@ -1,4 +1,4 @@
package atn
package antlr4
// Represents an executor for a sequence of lexer actions which traversed during
// the matching operation of a lexer rule (token).

View File

@ -2,18 +2,15 @@ package antlr4
import (
"fmt"
"antlr4/atn"
"antlr4/tree"
"antlr4/error"
)
)
type TraceListener struct {
tree.ParseTreeListener
ParseTreeListener
parser *Parser
}
func NewTraceListener(parser *Parser) *TraceListener {
tl := &TraceListener{tree.ParseTreeListener{}}
tl := &TraceListener{ParseTreeListener{}}
tl.parser = parser
return tl
}
@ -22,7 +19,7 @@ func (this *TraceListener) enterEveryRule(ctx *ParserRuleContext) {
fmt.Println("enter " + this.parser.getRuleNames()[ctx.ruleIndex] + ", LT(1)=" + this.parser._input.LT(1).text())
}
func (this *TraceListener) visitTerminal( node *tree.TerminalNode ) {
func (this *TraceListener) visitTerminal( node *TerminalNode ) {
fmt.Println("consume " + node.symbol + " rule " + this.parser.getRuleNames()[this.parser._ctx.ruleIndex])
}
@ -34,12 +31,12 @@ func (this *TraceListener) exitEveryRule(ctx *ParserRuleContext) {
type Parser struct {
Recognizer
_input *TokenStream
_errHandler *error.ErrorStrategy
_errHandler *ErrorStrategy
_precedenceStack IntStack
_ctx *ParserRuleContext
buildParseTrees bool
_tracer bool
_parseListeners []*tree.ParseTreeListener
_parseListeners []*ParseTreeListener
_syntaxErrors int
}
@ -55,7 +52,7 @@ func NewParser(input *TokenStream) *Parser {
p._input = nil
// The error handling strategy for the parser. The default value is a new
// instance of {@link DefaultErrorStrategy}.
p._errHandler = error.NewDefaultErrorStrategy()
p._errHandler = NewDefaultErrorStrategy()
p._precedenceStack = make([]int, 0)
p._precedenceStack.Push(0)
// The {@link ParserRuleContext} object for the currently executing rule.
@ -171,9 +168,9 @@ func (p *Parser) matchWildcard() *Token {
return t
}
func (p *Parser) getParseListeners() []*tree.ParseTreeListener {
func (p *Parser) getParseListeners() []*ParseTreeListener {
if (p._parseListeners == nil){
return make([]*tree.ParseTreeListener)
return make([]*ParseTreeListener)
}
return p._parseListeners
}
@ -206,12 +203,12 @@ func (p *Parser) getParseListeners() []*tree.ParseTreeListener {
//
// @panics nilPointerException if {@code} listener is {@code nil}
//
func (p *Parser) addParseListener(listener *tree.ParseTreeListener) {
func (p *Parser) addParseListener(listener *ParseTreeListener) {
if (listener == nil) {
panic("listener")
}
if (p._parseListeners == nil) {
p._parseListeners = new([]tree.ParseTreeListener)
p._parseListeners = new([]ParseTreeListener)
}
p._parseListeners = append(p._parseListeners, listener)
}
@ -223,7 +220,7 @@ func (p *Parser) addParseListener(listener *tree.ParseTreeListener) {
// listener, p.method does nothing.</p>
// @param listener the listener to remove
//
func (p *Parser) removeParseListener(listener *tree.ParseTreeListener) {
func (p *Parser) removeParseListener(listener *ParseTreeListener) {
if (p._parseListeners != nil) {
var idx = p._parseListeners.indexOf(listener)
if (idx >= 0) {
@ -292,9 +289,9 @@ func (p *Parser) getATNWithBypassAlts() {
}
var result = p.bypassAltsAtnCache[serializedAtn]
if (result == nil) {
var deserializationOptions = atn.NewATNDeserializationOptions()
var deserializationOptions = NewATNDeserializationOptions()
deserializationOptions.generateRuleBypassTransitions = true
result = atn.NewATNDeserializer(deserializationOptions).deserialize(serializedAtn)
result = NewATNDeserializer(deserializationOptions).deserialize(serializedAtn)
p.bypassAltsAtnCache[serializedAtn] = result
}
return result
@ -356,7 +353,7 @@ func (p *Parser) getCurrentToken() *Token {
return p._input.LT(1)
}
func (p *Parser) notifyErrorListeners(msg string, offendingToken *Token, err *error.RecognitionException) {
func (p *Parser) notifyErrorListeners(msg string, offendingToken *Token, err *RecognitionException) {
offendingToken = offendingToken || nil
err = err || nil
if (offendingToken == nil) {
@ -397,7 +394,7 @@ func (p *Parser) consume() {
}
var hasListener = p._parseListeners != nil && len(p._parseListeners) > 0
if (p.buildParseTrees || hasListener) {
var node *tree.ErrorNodeImpl
var node *ErrorNodeImpl
if (p._errHandler.inErrorRecoveryMode(p)) {
node = p._ctx.addErrorNode(o)
} else {
@ -557,7 +554,7 @@ func (p *Parser) inContext(context *ParserRuleContext) bool {
// the ATN, otherwise {@code false}.
func (p *Parser) isExpectedToken(symbol *Token) bool {
var atn *atn.ATN = p._interp.atn
var atn *ATN = p._interp.atn
var ctx = p._ctx
var s = atn.states[p.state]
var following = atn.nextTokens(s)

View File

@ -1,8 +1,7 @@
package atn
package antlr4
import (
"antlr4"
"fmt"
"fmt"
)
//
@ -785,7 +784,7 @@ func (this *ParserATNSimulator) computeReachSet(closure, t, fullCtx) {
//
if (reach==nil) {
reach = NewATNConfigSet(fullCtx)
var closureBusy = antlr4.NewSet()
var closureBusy = NewSet()
var treatEofAsEpsilon = t == TokenEOF
for (var k=0 k<intermediate.items.lengthk++) {
this.closure(intermediate.items[k], reach, closureBusy, false, fullCtx, treatEofAsEpsilon)
@ -879,7 +878,7 @@ func (this *ParserATNSimulator) computeStartState(p, ctx, fullCtx) {
for(var i=0i<p.transitions.lengthi++) {
var target = p.transitions[i].target
var c = NewATNConfig({ state:target, alt:i+1, context:initialContext }, nil)
var closureBusy = antlr4.NewSet()
var closureBusy = NewSet()
this.closure(c, configs, closureBusy, true, fullCtx, false)
}
return configs
@ -1134,7 +1133,7 @@ func (this *ParserATNSimulator) getAltThatFinishedDecisionEntryRule(configs) {
// those that have preds evaluating to true/false. If no pred, assume
// true pred and include in succeeded set. Returns Pair of sets.
//
// Create a antlr4.NewSet so as not to alter the incoming parameter.
// Create a NewSet so as not to alter the incoming parameter.
//
// Assumption: the input stream has been restored to the starting point
// prediction, which is where predicates need to evaluate.
@ -1165,7 +1164,7 @@ func (this *ParserATNSimulator) splitAccordingToSemanticValidity( configs, outer
// includes pairs with nil predicates.
//
func (this *ParserATNSimulator) evalSemanticContext(predPredictions, outerContext, complete) {
var predictions = antlr4.NewBitSet()
var predictions = NewBitSet()
for(var i=0i<predPredictions.lengthi++) {
var pair = predPredictions[i]
if (pair.pred == SemanticContext.NONE) {
@ -1478,7 +1477,7 @@ func (this *ParserATNSimulator) getConflictingAlts(configs) {
func (this *ParserATNSimulator) getConflictingAltsOrUniqueAlt(configs) {
var conflictingAlts = nil
if (configs.uniqueAlt!= ATN.INVALID_ALT_NUMBER) {
conflictingAlts = antlr4.NewBitSet()
conflictingAlts = NewBitSet()
conflictingAlts.add(configs.uniqueAlt)
} else {
conflictingAlts = configs.conflictingAlts

View File

@ -1,9 +1,7 @@
package antlr4
import (
"antlr4/error"
"antlr4/tree"
"reflect"
"reflect"
)
//* A rule invocation record for parsing.
@ -36,7 +34,7 @@ type ParserRuleContext struct {
ruleIndex int
children []RuleContext
start, stop *Token
exception *error.RecognitionException
exception *RecognitionException
}
func NewParserRuleContext(parent *ParserRuleContext, invokingStateNumber int) *ParserRuleContext {
@ -82,10 +80,10 @@ func (prc *ParserRuleContext) copyFrom(ctx *ParserRuleContext) {
}
// Double dispatch methods for listeners
func (prc *ParserRuleContext) enterRule(listener *tree.ParseTreeListener) {
func (prc *ParserRuleContext) enterRule(listener *ParseTreeListener) {
}
func (prc *ParserRuleContext) exitRule(listener *tree.ParseTreeListener) {
func (prc *ParserRuleContext) exitRule(listener *ParseTreeListener) {
}
// * Does not set parent link other add methods do that///
@ -107,15 +105,15 @@ func (prc *ParserRuleContext) removeLastChild() {
}
}
func (prc *ParserRuleContext) addTokenNode(token *Token) *tree.TerminalNodeImpl {
var node = tree.NewTerminalNodeImpl(token)
func (prc *ParserRuleContext) addTokenNode(token *Token) *TerminalNodeImpl {
var node = NewTerminalNodeImpl(token)
prc.addChild(node)
node.parentCtx = prc
return node
}
func (prc *ParserRuleContext) addErrorNode(badToken *Token) *tree.ErrorNodeImpl {
var node = tree.NewErrorNodeImpl(badToken)
func (prc *ParserRuleContext) addErrorNode(badToken *Token) *ErrorNodeImpl {
var node = NewErrorNodeImpl(badToken)
prc.addChild(node)
node.parentCtx = prc
return node
@ -144,11 +142,11 @@ func (prc *ParserRuleContext) getChild(i int, childType reflect.Type) {
}
func (prc *ParserRuleContext) getToken(ttype int, i int) *tree.TerminalNode {
func (prc *ParserRuleContext) getToken(ttype int, i int) *TerminalNode {
for j :=0; j<len(prc.children); j++ {
var child = prc.children[j]
if _, ok := child.(*tree.TerminalNode); ok {
if _, ok := child.(*TerminalNode); ok {
if (child.symbol.tokenType == ttype) {
if(i==0) {
return child
@ -161,14 +159,14 @@ func (prc *ParserRuleContext) getToken(ttype int, i int) *tree.TerminalNode {
return nil
}
func (prc *ParserRuleContext) getTokens(ttype int) []*tree.TerminalNode {
func (prc *ParserRuleContext) getTokens(ttype int) []*TerminalNode {
if (prc.children== nil) {
return make([]*tree.TerminalNode)
return make([]*TerminalNode)
} else {
var tokens = make([]*tree.TerminalNode)
var tokens = make([]*TerminalNode)
for j:=0; j<len(prc.children); j++ {
var child = prc.children[j]
if tchild, ok := child.(*tree.TerminalNode); ok {
if tchild, ok := child.(*TerminalNode); ok {
if (tchild.symbol.tokenType == ttype) {
tokens = append(tokens, tchild)
}
@ -209,7 +207,7 @@ func (prc *ParserRuleContext) getChildCount() {
func (prc *ParserRuleContext) getSourceInterval() {
if( prc.start == nil || prc.stop == nil) {
return tree.TreeINVALID_INTERVAL
return TreeINVALID_INTERVAL
} else {
return NewInterval(prc.start.tokenIndex, prc.stop.tokenIndex)
}

View File

@ -1,7 +1,6 @@
package antlr4
import (
"antlr4/atn"
"fmt"
)
@ -339,7 +338,7 @@ func (this *ArrayPredictionContext) toString() string {
// Convert a {@link RuleContext} tree to a {@link PredictionContext} graph.
// Return {@link //EMPTY} if {@code outerContext} is empty or nil.
// /
func predictionContextFromRuleContext(a *atn.ATN, outerContext *RuleContext) *PredictionContext {
func predictionContextFromRuleContext(a *ATN, outerContext *RuleContext) *PredictionContext {
if (outerContext == nil) {
outerContext = RuleContextEMPTY
}

View File

@ -1,7 +1,6 @@
package atn
package antlr4
import (
"antlr4"
"strings"
"strings"
)
//
@ -377,7 +376,7 @@ func PredictionModeallConfigsInRuleStopStates(configs *ATNConfigSet) bool {
// we need exact ambiguity detection when the sets look like
// {@code A={{1,2}}} or {@code {{1,2},{1,2}}}, etc...</p>
//
func PredictionModeresolvesToJustOneViableAlt(altsets []*antlr4.BitSet) bool {
func PredictionModeresolvesToJustOneViableAlt(altsets []*BitSet) bool {
return PredictionModegetSingleViableAlt(altsets)
}
@ -389,7 +388,7 @@ func PredictionModeresolvesToJustOneViableAlt(altsets []*antlr4.BitSet) bool {
// @return {@code true} if every {@link BitSet} in {@code altsets} has
// {@link BitSet//cardinality cardinality} &gt 1, otherwise {@code false}
//
func PredictionModeallSubsetsConflict(altsets []*antlr4.BitSet) bool {
func PredictionModeallSubsetsConflict(altsets []*BitSet) bool {
return !PredictionModehasNonConflictingAltSet(altsets)
}
//
@ -400,7 +399,7 @@ func PredictionModeallSubsetsConflict(altsets []*antlr4.BitSet) bool {
// @return {@code true} if {@code altsets} contains a {@link BitSet} with
// {@link BitSet//cardinality cardinality} 1, otherwise {@code false}
//
func PredictionModehasNonConflictingAltSet(altsets []*antlr4.BitSet) bool {
func PredictionModehasNonConflictingAltSet(altsets []*BitSet) bool {
for i:=0; i<len(altsets); i++{
var alts = altsets[i]
if (len(alts)==1) {
@ -418,7 +417,7 @@ func PredictionModehasNonConflictingAltSet(altsets []*antlr4.BitSet) bool {
// @return {@code true} if {@code altsets} contains a {@link BitSet} with
// {@link BitSet//cardinality cardinality} &gt 1, otherwise {@code false}
//
func PredictionModehasConflictingAltSet(altsets []*antlr4.BitSet) bool {
func PredictionModehasConflictingAltSet(altsets []*BitSet) bool {
for i:=0; i<len(altsets); i++{
var alts = altsets[i]
if (len(alts)>1) {
@ -435,7 +434,7 @@ func PredictionModehasConflictingAltSet(altsets []*antlr4.BitSet) bool {
// @return {@code true} if every member of {@code altsets} is equal to the
// others, otherwise {@code false}
//
func PredictionModeallSubsetsEqual(altsets []*antlr4.BitSet) bool {
func PredictionModeallSubsetsEqual(altsets []*BitSet) bool {
var first = nil
for i:=0; i<len(altsets); i++{
var alts = altsets[i]
@ -455,7 +454,7 @@ func PredictionModeallSubsetsEqual(altsets []*antlr4.BitSet) bool {
//
// @param altsets a collection of alternative subsets
//
func PredictionModegetUniqueAlt(altsets []*antlr4.BitSet) int {
func PredictionModegetUniqueAlt(altsets []*BitSet) int {
var all = PredictionModegetAlts(altsets)
if (len(all)==1) {
return all.minValue()
@ -471,8 +470,8 @@ func PredictionModegetUniqueAlt(altsets []*antlr4.BitSet) int {
// @param altsets a collection of alternative subsets
// @return the set of represented alternatives in {@code altsets}
//
func PredictionModegetAlts(altsets []*antlr4.BitSet) *antlr4.BitSet {
var all = antlr4.NewBitSet()
func PredictionModegetAlts(altsets []*BitSet) *BitSet {
var all = NewBitSet()
for _, alts := range altsets {
all.or(alts)
}
@ -495,7 +494,7 @@ func PredictionModegetConflictingAltSubsets(configs *ATNConfigSet) {
var key = "key_" + c.state.stateNumber + "/" + c.context
var alts = configToAlts[key] || nil
if (alts == nil) {
alts = antlr4.NewBitSet()
alts = NewBitSet()
configToAlts[key] = alts
}
alts.add(c.alt)
@ -521,12 +520,12 @@ func PredictionModegetConflictingAltSubsets(configs *ATNConfigSet) {
// </pre>
//
func PredictionModegetStateToAltMap(configs *ATNConfigSet) {
var m = antlr4.NewAltDict()
var m = NewAltDict()
for _, c := range configs.items {
var alts = m.get(c.state)
if (alts == nil) {
alts = antlr4.NewBitSet()
alts = NewBitSet()
m.put(c.state, alts)
}
alts.add(c.alt)
@ -544,7 +543,7 @@ func PredictionModehasStateAssociatedWithOneAlt (configs *ATNConfigSet) bool {
return false
}
func PredictionModegetSingleViableAlt (altsets []*antlr4.BitSet) int {
func PredictionModegetSingleViableAlt (altsets []*BitSet) int {
var result = ATNINVALID_ALT_NUMBER
for i:=0; i<len(altsets); i++{
var alts = altsets[i]

View File

@ -3,14 +3,11 @@ package antlr4
import (
"fmt"
"strings"
"antlr4/atn"
"antlr4/tree"
"antlr4/error"
)
)
type Recognizer struct {
_listeners []tree.ParseTreeListener
_interp *atn.ATNSimulator
_listeners []ParseTreeListener
_interp *ATNSimulator
state int
}
@ -21,7 +18,7 @@ func NewRecognizer() *Recognizer {
}
func (rec *Recognizer) initRecognizer() {
rec._listeners = []tree.ParseTreeListener{ error.ConsoleErrorListenerINSTANCE }
rec._listeners = []ParseTreeListener{ ConsoleErrorListenerINSTANCE }
rec._interp = nil
rec.state = -1
}
@ -36,12 +33,12 @@ func (this *Recognizer) checkVersion(toolVersion string) {
}
}
func (this *Recognizer) addErrorListener(listener *tree.ParseTreeListener) {
func (this *Recognizer) addErrorListener(listener *ParseTreeListener) {
append(this._listeners, listener)
}
func (this *Recognizer) removeErrorListeners() {
this._listeners = make([]tree.ParseTreeListener, 0)
this._listeners = make([]ParseTreeListener, 0)
}
func (this *Recognizer) getRuleNames() []string {
@ -164,8 +161,8 @@ func (this *Recognizer) getTokenErrorDisplay(t *Token) string {
return "'" + s + "'"
}
func (this *Recognizer) getErrorListenerDispatch() *error.ErrorListener {
return error.NewProxyErrorListener(this._listeners)
func (this *Recognizer) getErrorListenerDispatch() *ErrorListener {
return NewProxyErrorListener(this._listeners)
}
// subclass needs to override these if there are sempreds or actions

View File

@ -1,8 +1,7 @@
package antlr4
import (
"antlr4/tree"
)
)
// A rule context is a record of a single rule invocation. It knows
// which context invoked it, if any. If there is no parent context, then
@ -26,7 +25,7 @@ import (
//
type RuleContext struct {
tree.RuleNode
RuleNode
parentCtx *RuleContext
invokingState int
ruleIndex int
@ -35,7 +34,7 @@ type RuleContext struct {
func NewRuleContext(parent *RuleContext, invokingState int) *RuleContext {
rn := &RuleContext{tree.RuleNode{}}
rn := &RuleContext{RuleNode{}}
rn.initRuleContext(parent, invokingState)
return rn
@ -75,7 +74,7 @@ func (this *RuleContext) isEmpty() bool {
// satisfy the ParseTree / SyntaxTree interface
func (this *RuleContext) getSourceInterval() *Interval {
return tree.TreeINVALID_INTERVAL
return TreeINVALID_INTERVAL
}
func (this *RuleContext) getRuleContext() *RuleContext {
@ -114,7 +113,7 @@ func (this *RuleContext) getChildCount() {
return 0
}
func (this *RuleContext) accept(visitor *tree.ParseTreeVisitor) {
func (this *RuleContext) accept(visitor *ParseTreeVisitor) {
visitor.visitChildren(this)
}
@ -125,7 +124,7 @@ func (this *RuleContext) accept(visitor *tree.ParseTreeVisitor) {
//
func (this *RuleContext) toStringTree(ruleNames []string, recog *Recognizer) string {
return tree.Trees.toStringTree(this, ruleNames, recog)
return Trees.toStringTree(this, ruleNames, recog)
}
func (this *RuleContext) toString(ruleNames []string, stop *RuleContext) string {

View File

@ -1,8 +1,7 @@
package atn
package antlr4
import (
"antlr4"
)
)
// A tree structure used to record the semantic context in which
// an ATN configuration is valid. It's either a single predicate,
@ -202,7 +201,7 @@ PrecedencePredicate.filterPrecedencePredicates = function(set) {
//
func AND(a, b) {
SemanticContext.call(this)
var operands = antlr4.antlr4.NewSet()
var operands = NewSet()
if _, ok := a.(AND); ok {
a.opnds.map(function(o) {
operands.add(o)
@ -307,7 +306,7 @@ func (this *AND) toString() string {
//
func OR(a, b) {
SemanticContext.call(this)
var operands = antlr4.NewSet()
var operands = NewSet()
if _, ok := a.(OR); ok {
a.opnds.map(function(o) {
operands.add(o)

View File

@ -23,17 +23,7 @@ type Token struct {
line int // line=1..n of the 1st character
column int // beginning of the line at which it occurs, 0..n-1
_text string // text of the token.
// String getText();
// int getType();
// int getLine();
// int getCharPositionInLine();
// int getChannel();
// int getTokenIndex();
// int getStartIndex();
// int getStopIndex();
// TokenSource getTokenSource();
// CharStream getInputStream();
readOnly bool
}
const (

View File

@ -1,7 +1,6 @@
package atn
package antlr4
import (
"antlr4"
"fmt"
"fmt"
)
// atom, set, epsilon, action, predicate, rule transitions.
@ -18,7 +17,7 @@ import (
type Transition struct {
target *ATNState
isEpsilon bool
label *antlr4.IntervalSet
label *IntervalSet
}
func Transition (target *ATNState) *Transition {
@ -97,7 +96,7 @@ var TransitionserializationNames = []string{
type AtomTransition struct {
Transition
label_ int
label *antlr4.IntervalSet
label *IntervalSet
serializationType int
}
@ -113,8 +112,8 @@ func NewAtomTransition ( target *ATNState, label int ) *AtomTransition {
return t
}
func (t *AtomTransition) makeLabel() *antlr4.IntervalSet {
var s = antlr4.NewIntervalSet()
func (t *AtomTransition) makeLabel() *IntervalSet {
var s = NewIntervalSet()
s.addOne(t.label_)
return s
}
@ -198,8 +197,8 @@ func NewRangeTransition ( target *ATNState, start, stop int ) *RangeTransition {
}
func (t *RangeTransition) makeLabel() *antlr4.IntervalSet {
var s = antlr4.NewIntervalSet()
func (t *RangeTransition) makeLabel() *IntervalSet {
var s = NewIntervalSet()
s.addRange(t.start, t.stop)
return s
}
@ -295,7 +294,7 @@ type SetTransition struct {
serializationType int
}
func NewSetTransition ( target *ATNState, set *antlr4.IntervalSet ) *SetTransition {
func NewSetTransition ( target *ATNState, set *IntervalSet ) *SetTransition {
t := new(SetTransition)
t.initTransition( target )
@ -304,14 +303,14 @@ func NewSetTransition ( target *ATNState, set *antlr4.IntervalSet ) *SetTransiti
return t
}
func (t *SetTransition) initSetTransition( set *antlr4.IntervalSet ) {
func (t *SetTransition) initSetTransition( set *IntervalSet ) {
t.serializationType = TransitionSET
if (set !=nil && set !=nil) {
t.label = set
} else {
t.label = antlr4.NewIntervalSet()
t.label.addOne(antlr4.TokenInvalidType)
t.label = NewIntervalSet()
t.label.addOne(TokenInvalidType)
}
}
@ -331,7 +330,7 @@ type NotSetTransition struct {
SetTransition
}
func NotSetTransition ( target *ATNState, set *antlr4.IntervalSet) *NotSetTransition {
func NotSetTransition ( target *ATNState, set *IntervalSet) *NotSetTransition {
t := new(NotSetTransition)
t.initTransition( target )

View File

@ -1,14 +1,11 @@
package tree
package antlr4
import (
"antlr4"
)
// The basic notion of a tree has a parent, a payload, and a list of children.
// It is the most abstract interface for all the trees used by ANTLR.
///
var TreeINVALID_INTERVAL = antlr4.NewInterval(-1, -2)
var TreeINVALID_INTERVAL = NewInterval(-1, -2)
type Tree interface {
getParent() *Tree
@ -20,7 +17,7 @@ type Tree interface {
type SyntaxTree interface {
Tree
getSourceInterval() *antlr4.Interval
getSourceInterval() *Interval
}
type ParseTree interface {
@ -28,17 +25,17 @@ type ParseTree interface {
// <T> T accept(ParseTreeVisitor<? extends T> visitor);
accept(visitor *ParseTreeVisitor)
getText() string
toStringTree(parser *antlr4.Parser) string
toStringTree(parser *Parser) string
}
type RuleNode interface {
ParseTree
getRuleContext() *antlr4.RuleContext
getRuleContext() *RuleContext
}
type TerminalNode interface {
ParseTree
getSymbol() *antlr4.Token
getSymbol() *Token
}
type ErrorNode interface {
@ -76,18 +73,16 @@ type ParseTreeVisitor interface {
type ParseTreeListener interface {
visitTerminal(node *TerminalNode)
visitErrorNode(node *ErrorNode)
enterEveryRule(ctx *antlr4.ParserRuleContext)
exitEveryRule(ctx *antlr4.ParserRuleContext)
enterEveryRule(ctx *ParserRuleContext)
exitEveryRule(ctx *ParserRuleContext)
}
type TerminalNodeImpl struct {
parentCtx *antlr4.RuleContext
symbol *antlr4.Token
parentCtx *RuleContext
symbol *Token
}
func NewTerminalNodeImpl(symbol *antlr4.Token) *TerminalNodeImpl {
func NewTerminalNodeImpl(symbol *Token) *TerminalNodeImpl {
tn := &TerminalNodeImpl{TerminalNode{}}
tn.initTerminalNodeImpl(symbol)
@ -95,7 +90,7 @@ func NewTerminalNodeImpl(symbol *antlr4.Token) *TerminalNodeImpl {
return tn
}
func (this *TerminalNodeImpl) initTerminalNodeImpl(symbol *antlr4.Token) {
func (this *TerminalNodeImpl) initTerminalNodeImpl(symbol *Token) {
this.parentCtx = nil
this.symbol = symbol
}
@ -104,7 +99,7 @@ func (this *TerminalNodeImpl) getChild(i int) *Tree {
return nil
}
func (this *TerminalNodeImpl) getSymbol() *antlr4.Token {
func (this *TerminalNodeImpl) getSymbol() *Token {
return this.symbol
}
@ -112,16 +107,16 @@ func (this *TerminalNodeImpl) getParent() *Tree {
return this.parentCtx
}
func (this *TerminalNodeImpl) getPayload() *antlr4.Token {
func (this *TerminalNodeImpl) getPayload() *Token {
return this.symbol
}
func (this *TerminalNodeImpl) getSourceInterval() *antlr4.Interval {
func (this *TerminalNodeImpl) getSourceInterval() *Interval {
if (this.symbol == nil) {
return TreeINVALID_INTERVAL
}
var tokenIndex = this.symbol.tokenIndex
return antlr4.NewInterval(tokenIndex, tokenIndex)
return NewInterval(tokenIndex, tokenIndex)
}
func (this *TerminalNodeImpl) getChildCount() {
@ -157,7 +152,7 @@ type ErrorNodeImpl struct {
TerminalNodeImpl
}
func NewErrorNodeImpl(token *antlr4.Token) *ErrorNodeImpl {
func NewErrorNodeImpl(token *Token) *ErrorNodeImpl {
en := new(ErrorNodeImpl)
en.initTerminalNodeImpl(token)
return en
@ -203,13 +198,13 @@ func (this *ParseTreeWalker) walk(listener *ParseTreeListener, t *Tree) {
// the rule specific. We to them in reverse order upon finishing the node.
//
func (this *ParseTreeWalker) enterRule(listener *ParseTreeListener, r *RuleNode) {
var ctx = r.getRuleContext().(*antlr4.ParserRuleContext)
var ctx = r.getRuleContext().(*ParserRuleContext)
listener.enterEveryRule(ctx)
ctx.enterRule(listener)
}
func (this *ParseTreeWalker) exitRule(listene *ParseTreeListener, r *RuleNode) {
var ctx = r.getRuleContext().(*antlr4.ParserRuleContext)
var ctx = r.getRuleContext().(*ParserRuleContext)
ctx.exitRule(listener)
listener.exitEveryRule(ctx)
}

View File

@ -1,4 +1,4 @@
package tree
package antlr4
//var Utils = require('./../Utils')
//var Token = require('./../Token').Token

View File

@ -85,7 +85,7 @@ func (this *Set) length() int {
return len(this.data)
}
func (this *Set) add(value interface{}) {
func (this *Set) add(value interface{}) interface{} {
var hash = this.hashFunction(value)
var key = "hash_" + hashCode(hash)

View File

@ -17,9 +17,6 @@ package parser // <file.grammarName>
import(
"antlr4"
"antlr4/atn"
"antlr4/dfa"
"antlr4/tree"
"strings"
)
@ -38,7 +35,6 @@ package parser // <file.grammarName>
import(
"antlr4"
"antlr4/tree"
)
// This class defines a complete listener for a parse tree produced by <file.parserName>.
@ -67,9 +63,6 @@ package parser // <file.grammarName>
import(
"antlr4"
"antlr4/atn"
"antlr4/dfa"
"antlr4/tree"
)
<header>
@ -796,8 +789,6 @@ package parser
import (
"antlr4"
"antlr4/atn"
"antlr4/dfa"
"strings"
)