Export some additional interface methods, fix issues with ParseTreeWalker, generate base Listener with tool

This commit is contained in:
Peter Boyer 2016-01-03 22:07:43 -05:00
parent 805f706f02
commit fa46c498af
17 changed files with 292 additions and 302 deletions

View File

@ -3,10 +3,23 @@ package main
import (
"antlr4"
"parser"
"fmt"
)
type MyErrorListener struct {
*MyErrorListener
type MyListener struct {
*parser.BaseArithmeticListener
}
func NewMyPrinter() *MyListener {
return new(MyListener)
}
func (k *MyListener) EnterExpression(ctx *parser.ExpressionContext) {
fmt.Println("Oh, an expression!")
}
func (k *MyListener) EnterAtom(ctx *parser.AtomContext) {
fmt.Println(ctx)
}
func main() {
@ -21,6 +34,11 @@ func main() {
p.BuildParseTrees = true
p.Equation()
var tree = p.Equation()
var printer = NewMyPrinter()
antlr4.ParseTreeWalkerDefault.Walk(printer, tree);
fmt.Println( tree.GetChildren()[0].GetChildren()[0].GetChildren()[0].GetChildren()[0].GetChildren()[0].GetChildren()[0].GetChildren()[0] );
}

View File

@ -149,8 +149,8 @@ func (this *ATN) getExpectedTokens(stateNumber int, ctx RuleContext) *IntervalSe
var expected = NewIntervalSet()
expected.addSet(following)
expected.removeOne(TokenEpsilon)
for ctx != nil && ctx.getInvokingState() >= 0 && following.contains(TokenEpsilon) {
var invokingState = this.states[ctx.getInvokingState()]
for ctx != nil && ctx.GetInvokingState() >= 0 && following.contains(TokenEpsilon) {
var invokingState = this.states[ctx.GetInvokingState()]
var rt = invokingState.GetTransitions()[0]
following = this.nextTokens(rt.(*RuleTransition).followState, nil)
expected.addSet(following)

View File

@ -27,7 +27,7 @@ type LoopEndStateIntPair struct {
}
type BlockStartStateIntPair struct {
item0 IBlockStartState
item0 BlockStartState
item1 int
}
@ -165,7 +165,7 @@ func (this *ATNDeserializer) readStates(atn *ATN) {
if stype == ATNStateLoopEnd {
var loopBackStateNumber = this.readInt()
loopBackStateNumbers = append(loopBackStateNumbers, LoopEndStateIntPair{s.(*LoopEndState), loopBackStateNumber})
} else if s2, ok := s.(IBlockStartState); ok {
} else if s2, ok := s.(BlockStartState); ok {
var endStateNumber = this.readInt()
endStateNumbers = append(endStateNumbers, BlockStartStateIntPair{s2, endStateNumber})
}
@ -289,7 +289,7 @@ func (this *ATNDeserializer) readEdges(atn *ATN, sets []*IntervalSet) {
for i := 0; i < len(atn.states); i++ {
state := atn.states[i]
if s2, ok := state.(*BlockStartState); ok {
if s2, ok := state.(*BaseBlockStartState); ok {
// we need to know the end state to set its start state
if s2.endState == nil {
panic("IllegalState")
@ -523,7 +523,7 @@ func (this *ATNDeserializer) verifyATN(atn *ATN) {
this.checkCondition(s2.loopBackState != nil, "")
case *RuleStartState:
this.checkCondition(s2.stopState != nil, "")
case *BlockStartState:
case *BaseBlockStartState:
this.checkCondition(s2.endState != nil, "")
case *BlockEndState:
this.checkCondition(s2.startState != nil, "")

View File

@ -212,7 +212,7 @@ func (s *BaseDecisionState) setNonGreedy(b bool) {
s.nonGreedy = b
}
type IBlockStartState interface {
type BlockStartState interface {
DecisionState
getEndState() *BlockEndState
@ -220,15 +220,15 @@ type IBlockStartState interface {
}
// The start of a regular {@code (...)} block.
type BlockStartState struct {
type BaseBlockStartState struct {
*BaseDecisionState
endState *BlockEndState
}
func NewBlockStartState() *BlockStartState {
func NewBlockStartState() *BaseBlockStartState {
this := new(BlockStartState)
this := new(BaseBlockStartState)
this.BaseDecisionState = NewBaseDecisionState()
this.endState = nil
@ -236,23 +236,23 @@ func NewBlockStartState() *BlockStartState {
return this
}
func (s *BlockStartState) getEndState() *BlockEndState {
func (s *BaseBlockStartState) getEndState() *BlockEndState {
return s.endState
}
func (s *BlockStartState) setEndState(b *BlockEndState) {
func (s *BaseBlockStartState) setEndState(b *BlockEndState) {
s.endState = b
}
type BasicBlockStartState struct {
*BlockStartState
*BaseBlockStartState
}
func NewBasicBlockStartState() *BasicBlockStartState {
this := new(BasicBlockStartState)
this.BlockStartState = NewBlockStartState()
this.BaseBlockStartState = NewBlockStartState()
this.stateType = ATNStateBlockStart
return this
@ -335,7 +335,7 @@ func NewPlusLoopbackState() *PlusLoopbackState {
// real decision-making note for {@code A+}.
//
type PlusBlockStartState struct {
*BlockStartState
*BaseBlockStartState
loopBackState ATNState
}
@ -344,7 +344,7 @@ func NewPlusBlockStartState() *PlusBlockStartState {
this := new(PlusBlockStartState)
this.BlockStartState = NewBlockStartState()
this.BaseBlockStartState = NewBlockStartState()
this.stateType = ATNStatePlusBlockStart
this.loopBackState = nil
@ -354,14 +354,14 @@ func NewPlusBlockStartState() *PlusBlockStartState {
// The block that begins a closure loop.
type StarBlockStartState struct {
*BlockStartState
*BaseBlockStartState
}
func NewStarBlockStartState() *StarBlockStartState {
this := new(StarBlockStartState)
this.BlockStartState = NewBlockStartState()
this.BaseBlockStartState = NewBlockStartState()
this.stateType = ATNStateStarBlockStart

View File

@ -689,9 +689,9 @@ func (this *DefaultErrorStrategy) getErrorRecoverySet(recognizer Parser) *Interv
var atn = recognizer.GetInterpreter().atn
var ctx = recognizer.GetParserRuleContext()
var recoverSet = NewIntervalSet()
for ctx != nil && ctx.getInvokingState() >= 0 {
for ctx != nil && ctx.GetInvokingState() >= 0 {
// compute what follows who invoked us
var invokingState = atn.states[ctx.getInvokingState()]
var invokingState = atn.states[ctx.GetInvokingState()]
var rt = invokingState.GetTransitions()[0]
var follow = atn.nextTokens(rt.(*RuleTransition).followState, nil)
recoverSet.addSet(follow)

View File

@ -145,7 +145,7 @@ func (p *BaseParser) Match(ttype int) Token {
// we must have conjured up a Newtoken during single token
// insertion
// if it's not the current symbol
p._ctx.addErrorNode(t)
p._ctx.AddErrorNode(t)
}
}
@ -183,7 +183,7 @@ func (p *BaseParser) MatchWildcard() Token {
// we must have conjured up a Newtoken during single token
// insertion
// if it's not the current symbol
p._ctx.addErrorNode(t)
p._ctx.AddErrorNode(t)
}
}
return t
@ -429,7 +429,7 @@ func (p *BaseParser) Consume() Token {
var hasListener = p._parseListeners != nil && len(p._parseListeners) > 0
if p.BuildParseTrees || hasListener {
if p._errHandler.inErrorRecoveryMode(p) {
var node = p._ctx.addErrorNode(o)
var node = p._ctx.AddErrorNode(o)
if p._parseListeners != nil {
for _, l := range p._parseListeners {
l.VisitErrorNode(node)
@ -437,7 +437,7 @@ func (p *BaseParser) Consume() Token {
}
} else {
node := p._ctx.addTokenNode(o)
node := p._ctx.AddTokenNode(o)
if p._parseListeners != nil {
for _, l := range p._parseListeners {
l.VisitTerminal(node)
@ -453,14 +453,14 @@ func (p *BaseParser) Consume() Token {
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))
p._ctx.GetParent().(ParserRuleContext).AddChild(p._ctx)
}
}
func (p *BaseParser) EnterRule(localctx ParserRuleContext, state, ruleIndex int) {
p.SetState(state)
p._ctx = localctx
p._ctx.setStart(p._input.LT(1))
p._ctx.SetStart(p._input.LT(1))
if p.BuildParseTrees {
p.addContextToParseTree()
}
@ -470,12 +470,12 @@ func (p *BaseParser) EnterRule(localctx ParserRuleContext, state, ruleIndex int)
}
func (p *BaseParser) ExitRule() {
p._ctx.setStop(p._input.LT(-1))
p._ctx.SetStop(p._input.LT(-1))
// trigger event on _ctx, before it reverts to parent
if p._parseListeners != nil {
p.TriggerExitRuleEvent()
}
p.SetState(p._ctx.getInvokingState())
p.SetState(p._ctx.GetInvokingState())
if p._ctx.GetParent() != nil {
p._ctx = p._ctx.GetParent().(ParserRuleContext)
} else {
@ -488,8 +488,8 @@ func (p *BaseParser) EnterOuterAlt(localctx ParserRuleContext, altNum int) {
// that is previous child of parse tree
if p.BuildParseTrees && p._ctx != localctx {
if p._ctx.GetParent() != nil {
p._ctx.GetParent().(ParserRuleContext).removeLastChild()
p._ctx.GetParent().(ParserRuleContext).addChild(localctx)
p._ctx.GetParent().(ParserRuleContext).RemoveLastChild()
p._ctx.GetParent().(ParserRuleContext).AddChild(localctx)
}
}
p._ctx = localctx
@ -512,7 +512,7 @@ func (p *BaseParser) EnterRecursionRule(localctx ParserRuleContext, state, ruleI
p.SetState(state)
p._precedenceStack.Push(precedence)
p._ctx = localctx
p._ctx.setStart(p._input.LT(1))
p._ctx.SetStart(p._input.LT(1))
if p._parseListeners != nil {
p.TriggerEnterRuleEvent() // simulates rule entry for
// left-recursive rules
@ -524,14 +524,14 @@ func (p *BaseParser) EnterRecursionRule(localctx ParserRuleContext, state, ruleI
func (p *BaseParser) PushNewRecursionContext(localctx ParserRuleContext, state, ruleIndex int) {
var previous = p._ctx
previous.setParent(localctx)
previous.setInvokingState(state)
previous.setStart(p._input.LT(-1))
previous.SetParent(localctx)
previous.SetInvokingState(state)
previous.SetStart(p._input.LT(-1))
p._ctx = localctx
p._ctx.setStart(previous.getStart())
p._ctx.SetStart(previous.GetStart())
if p.BuildParseTrees {
p._ctx.addChild(previous)
p._ctx.AddChild(previous)
}
if p._parseListeners != nil {
p.TriggerEnterRuleEvent() // simulates rule entry for
@ -541,7 +541,7 @@ func (p *BaseParser) PushNewRecursionContext(localctx ParserRuleContext, state,
func (p *BaseParser) UnrollRecursionContexts(parentCtx ParserRuleContext) {
p._precedenceStack.Pop()
p._ctx.setStop(p._input.LT(-1))
p._ctx.SetStop(p._input.LT(-1))
var retCtx = p._ctx // save current ctx (return value)
// unroll so _ctx is as it was before call to recursive method
if p._parseListeners != nil {
@ -553,10 +553,10 @@ func (p *BaseParser) UnrollRecursionContexts(parentCtx ParserRuleContext) {
p._ctx = parentCtx
}
// hook into tree
retCtx.setParent(parentCtx)
retCtx.SetParent(parentCtx)
if p.BuildParseTrees && parentCtx != nil {
// add return ctx into invoking rule's tree
parentCtx.addChild(retCtx)
parentCtx.AddChild(retCtx)
}
}
@ -605,8 +605,8 @@ func (p *BaseParser) isExpectedToken(symbol int) bool {
if !following.contains(TokenEpsilon) {
return false
}
for ctx != nil && ctx.getInvokingState() >= 0 && following.contains(TokenEpsilon) {
var invokingState = atn.states[ctx.getInvokingState()]
for ctx != nil && ctx.GetInvokingState() >= 0 && following.contains(TokenEpsilon) {
var invokingState = atn.states[ctx.GetInvokingState()]
var rt = invokingState.GetTransitions()[0]
following = atn.nextTokens(rt.(*RuleTransition).followState, nil)
if following.contains(symbol) {
@ -639,7 +639,7 @@ func (p *BaseParser) getExpectedTokensWithinCurrentRule() *IntervalSet {
// Get a rule's index (i.e., {@code RULE_ruleName} field) or -1 if not found.//
func (p *BaseParser) GetRuleIndex(ruleName string) int {
var ruleIndex, ok = p.getRuleIndexMap()[ruleName]
var ruleIndex, ok = p.GetRuleIndexMap()[ruleName]
if ok {
return ruleIndex
} else {

View File

@ -99,7 +99,7 @@ func (this *ParserATNSimulator) AdaptivePredict(input TokenStream, decision int,
if s0 == nil {
if outerContext == nil {
outerContext = RuleContextEMPTY
outerContext = RuleContextEmpty
}
if ParserATNSimulatorDebug || ParserATNSimulatorListATNDecisions {
fmt.Println("predictATN decision " + strconv.Itoa(dfa.decision) +
@ -119,7 +119,7 @@ func (this *ParserATNSimulator) AdaptivePredict(input TokenStream, decision int,
}
}
var fullCtx = false
var s0_closure = this.computeStartState(dfa.atnStartState, RuleContextEMPTY, fullCtx)
var s0_closure = this.computeStartState(dfa.atnStartState, RuleContextEmpty, fullCtx)
if dfa.precedenceDfa {
// If this is a precedence DFA, we use applyPrecedenceFilter

View File

@ -2,33 +2,37 @@ package antlr4
import (
"reflect"
"strconv"
"fmt"
)
type ParserRuleContext interface {
RuleContext
SetException(RecognitionException)
addTokenNode(token Token) *TerminalNodeImpl
addErrorNode(badToken Token) *ErrorNodeImpl
AddTokenNode(token Token) *TerminalNodeImpl
AddErrorNode(badToken Token) *ErrorNodeImpl
EnterRule(listener ParseTreeListener)
ExitRule(listener ParseTreeListener)
setStart(Token)
getStart() Token
SetStart(Token)
GetStart() Token
setStop(Token)
getStop() Token
SetStop(Token)
GetStop() Token
addChild(child RuleContext) RuleContext
removeLastChild()
AddChild(child RuleContext) RuleContext
RemoveLastChild()
}
type BaseParserRuleContext struct {
*BaseRuleContext
children []ParseTree
start, stop Token
exception RecognitionException
children []Tree
}
func NewBaseParserRuleContext(parent ParserRuleContext, invokingStateNumber int) *BaseParserRuleContext {
@ -59,19 +63,8 @@ func (prc *BaseParserRuleContext) SetException(e RecognitionException) {
prc.exception = e
}
func (prc *BaseParserRuleContext) GetParent() Tree {
return prc.parentCtx
}
func (prc *BaseParserRuleContext) setParent(ctx Tree) {
prc.parentCtx = ctx.(ParserRuleContext)
}
func (prc *BaseParserRuleContext) setChildren(cs []Tree) {
prc.children = make([]ParseTree, len(cs))
for _, c := range cs {
prc.addChild(c.(RuleContext))
}
func (prc *BaseParserRuleContext) GetChildren() []Tree {
return prc.children
}
func (prc *BaseParserRuleContext) CopyFrom(ctx *BaseParserRuleContext) {
@ -83,25 +76,46 @@ func (prc *BaseParserRuleContext) CopyFrom(ctx *BaseParserRuleContext) {
prc.stop = ctx.stop
}
func (this *BaseParserRuleContext) GetText() string {
if this.GetChildCount() == 0 {
return ""
} else {
var s string
for _, child := range this.children {
s += child.(ParseTree).GetText()
}
return s
}
}
// Double dispatch methods for listeners
func (prc *BaseParserRuleContext) EnterRule(listener ParseTreeListener) {
fmt.Println("Do nothing enter")
}
func (prc *BaseParserRuleContext) ExitRule(listener ParseTreeListener) {
fmt.Println("Do nothing exit")
}
// * Does not set parent link other add methods do that///
func (prc *BaseParserRuleContext) addTerminalNodeChild(child TerminalNode) TerminalNode {
if prc.children == nil {
prc.children = make([]ParseTree, 0)
prc.children = make([]Tree, 0)
}
if child == nil {
panic("Child may not be null")
}
prc.children = append(prc.children, child)
return child
}
func (prc *BaseParserRuleContext) addChild(child RuleContext) RuleContext {
func (prc *BaseParserRuleContext) AddChild(child RuleContext) RuleContext {
if prc.children == nil {
prc.children = make([]ParseTree, 0)
prc.children = make([]Tree, 0)
}
if child == nil {
panic("Child may not be null")
}
prc.children = append(prc.children, child)
return child
@ -111,13 +125,13 @@ func (prc *BaseParserRuleContext) addChild(child RuleContext) RuleContext {
// we entered a rule. If we have // label, we will need to remove
// generic ruleContext object.
// /
func (prc *BaseParserRuleContext) removeLastChild() {
func (prc *BaseParserRuleContext) RemoveLastChild() {
if prc.children != nil && len(prc.children) > 0 {
prc.children = prc.children[0 : len(prc.children)-1]
}
}
func (prc *BaseParserRuleContext) addTokenNode(token Token) *TerminalNodeImpl {
func (prc *BaseParserRuleContext) AddTokenNode(token Token) *TerminalNodeImpl {
var node = NewTerminalNodeImpl(token)
prc.addTerminalNodeChild(node)
@ -126,14 +140,14 @@ func (prc *BaseParserRuleContext) addTokenNode(token Token) *TerminalNodeImpl {
}
func (prc *BaseParserRuleContext) addErrorNode(badToken Token) *ErrorNodeImpl {
func (prc *BaseParserRuleContext) AddErrorNode(badToken Token) *ErrorNodeImpl {
var node = NewErrorNodeImpl(badToken)
prc.addTerminalNodeChild(node)
node.parentCtx = prc
return node
}
func (prc *BaseParserRuleContext) getChild(i int) Tree {
func (prc *BaseParserRuleContext) GetChild(i int) Tree {
if prc.children != nil && len(prc.children) >= i {
return prc.children[i]
} else {
@ -141,9 +155,9 @@ func (prc *BaseParserRuleContext) getChild(i int) Tree {
}
}
func (prc *BaseParserRuleContext) getChildOfType(i int, childType reflect.Type) RuleContext {
func (prc *BaseParserRuleContext) GetChildOfType(i int, childType reflect.Type) RuleContext {
if childType == nil {
return prc.getChild(i).(RuleContext)
return prc.GetChild(i).(RuleContext)
} else {
for j := 0; j < len(prc.children); j++ {
var child = prc.children[j]
@ -159,19 +173,31 @@ func (prc *BaseParserRuleContext) getChildOfType(i int, childType reflect.Type)
}
}
func (prc *BaseParserRuleContext) setStart(t Token) {
func (this *BaseParserRuleContext) StringTree(ruleNames []string, recog Recognizer) string {
return TreesStringTree(this, ruleNames, recog)
}
func (prc *BaseParserRuleContext) GetRuleContext() RuleContext {
return prc
}
func (this *BaseParserRuleContext) Accept(Visitor ParseTreeVisitor) interface{} {
return Visitor.VisitChildren(this)
}
func (prc *BaseParserRuleContext) SetStart(t Token) {
prc.start = t
}
func (prc *BaseParserRuleContext) getStart() Token {
func (prc *BaseParserRuleContext) GetStart() Token {
return prc.start
}
func (prc *BaseParserRuleContext) setStop(t Token) {
func (prc *BaseParserRuleContext) SetStop(t Token) {
prc.stop = t
}
func (prc *BaseParserRuleContext) getStop() Token {
func (prc *BaseParserRuleContext) GetStop() Token {
return prc.stop
}
@ -180,7 +206,7 @@ func (prc *BaseParserRuleContext) GetToken(ttype int, i int) TerminalNode {
for j := 0; j < len(prc.children); j++ {
var child = prc.children[j]
if c2, ok := child.(TerminalNode); ok {
if c2.getSymbol().GetTokenType() == ttype {
if c2.GetSymbol().GetTokenType() == ttype {
if i == 0 {
return c2
} else {
@ -200,7 +226,7 @@ func (prc *BaseParserRuleContext) GetTokens(ttype int) []TerminalNode {
for j := 0; j < len(prc.children); j++ {
var child = prc.children[j]
if tchild, ok := child.(TerminalNode); ok {
if tchild.getSymbol().GetTokenType() == ttype {
if tchild.GetSymbol().GetTokenType() == ttype {
tokens = append(tokens, tchild)
}
}
@ -209,6 +235,10 @@ func (prc *BaseParserRuleContext) GetTokens(ttype int) []TerminalNode {
}
}
func (prc *BaseParserRuleContext) GetPayload() interface{}{
return prc
}
func (prc *BaseParserRuleContext) GetTypedRuleContext(ctxType reflect.Type, i int) interface{} {
panic("GetTypedRuleContexts not implemented")
// return prc.getChild(i, ctxType)
@ -230,7 +260,7 @@ func (prc *BaseParserRuleContext) GetTypedRuleContexts(ctxType reflect.Type) []i
// }
}
func (prc *BaseParserRuleContext) getChildCount() int {
func (prc *BaseParserRuleContext) GetChildCount() int {
if prc.children == nil {
return 0
} else {
@ -246,19 +276,61 @@ func (prc *BaseParserRuleContext) GetSourceInterval() *Interval {
}
}
var RuleContextEMPTY = NewBaseParserRuleContext(nil, -1)
//need to manage circular dependencies, so export now
type IInterpreterRuleContext interface {
// Print out a whole tree, not just a node, in LISP format
// (root child1 .. childN). Print just a node if this is a leaf.
//
func (this *BaseParserRuleContext) String(ruleNames []string, stop RuleContext) string {
var p ParserRuleContext = this
var s = "["
for p != nil && p != stop {
if ruleNames == nil {
if !p.IsEmpty() {
s += strconv.Itoa(p.GetInvokingState())
}
} else {
var ri = p.GetRuleIndex()
var ruleName string
if ri >= 0 && ri < len(ruleNames) {
ruleName = ruleNames[ri]
} else {
ruleName = strconv.Itoa(ri)
}
s += ruleName
}
if p.GetParent() != nil && (ruleNames != nil || !p.GetParent().(ParserRuleContext).IsEmpty()) {
s += " "
}
pi := p.GetParent()
if pi != nil {
p = pi.(ParserRuleContext)
} else {
p = nil
}
}
s += "]"
return s
}
var RuleContextEmpty = NewBaseParserRuleContext(nil, -1)
type InterpreterRuleContext interface {
ParserRuleContext
}
type InterpreterRuleContext struct {
type BaseInterpreterRuleContext struct {
*BaseParserRuleContext
}
func NewInterpreterRuleContext(parent InterpreterRuleContext, invokingStateNumber, ruleIndex int) *InterpreterRuleContext {
func NewBaseInterpreterRuleContext(parent BaseInterpreterRuleContext, invokingStateNumber, ruleIndex int) *BaseInterpreterRuleContext {
prc := new(InterpreterRuleContext)
prc := new(BaseInterpreterRuleContext)
prc.BaseParserRuleContext = NewBaseParserRuleContext(parent, invokingStateNumber)

View File

@ -347,16 +347,16 @@ func (this *ArrayPredictionContext) String() string {
// /
func predictionContextFromRuleContext(a *ATN, outerContext RuleContext) PredictionContext {
if outerContext == nil {
outerContext = RuleContextEMPTY
outerContext = RuleContextEmpty
}
// if we are in RuleContext of start rule, s, then BasePredictionContext
// is EMPTY. Nobody called us. (if we are empty, return empty)
if outerContext.GetParent() == nil || outerContext == RuleContextEMPTY {
if outerContext.GetParent() == nil || outerContext == RuleContextEmpty {
return BasePredictionContextEMPTY
}
// If we have a parent, convert it to a BasePredictionContext graph
var parent = predictionContextFromRuleContext(a, outerContext.GetParent().(RuleContext))
var state = a.states[outerContext.getInvokingState()]
var state = a.states[outerContext.GetInvokingState()]
var transition = state.GetTransitions()[0]
return SingletonBasePredictionContextCreate(parent, transition.(*RuleTransition).followState.GetStateNumber())

View File

@ -106,7 +106,8 @@ func (this *BaseRecognizer) SetState(v int) {
//
// <p>Used for XPath and tree pattern compilation.</p>
//
func (this *BaseRecognizer) getRuleIndexMap() map[string]int {
func (this *BaseRecognizer) GetRuleIndexMap() map[string]int {
panic("Method not defined!")
// var ruleNames = this.GetRuleNames()
// if (ruleNames==nil) {
@ -144,7 +145,7 @@ func (this *BaseRecognizer) GetTokenType(tokenName string) int {
// result.put(literalName, i);
// }
//
// String symbolicName = vocabulary.getSymbolicName(i);
// String symbolicName = vocabulary.GetSymbolicName(i);
// if (symbolicName != null) {
// result.put(symbolicName, i);
// }
@ -160,7 +161,7 @@ func (this *BaseRecognizer) GetTokenType(tokenName string) int {
//}
// What is the error header, normally line/character position information?//
func (this *BaseRecognizer) getErrorHeader(e RecognitionException) string {
func (this *BaseRecognizer) GetErrorHeader(e RecognitionException) string {
var line = e.GetOffendingToken().GetLine()
var column = e.GetOffendingToken().GetColumn()
return "line " + strconv.Itoa(line) + ":" + strconv.Itoa(column)

View File

@ -1,9 +1,5 @@
package antlr4
import (
"strconv"
)
// 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
// naturally the invoking state is not valid. The parent link
@ -28,21 +24,21 @@ import (
type RuleContext interface {
RuleNode
getInvokingState() int
setInvokingState(int)
GetInvokingState() int
SetInvokingState(int)
GetRuleIndex() int
isEmpty() bool
IsEmpty() bool
String([]string, RuleContext) string
}
type BaseRuleContext struct {
parentCtx RuleContext
invokingState int
RuleIndex int
children []Tree
}
func NewBaseRuleContext(parent RuleContext, invokingState int) *BaseRuleContext {
@ -64,19 +60,15 @@ func NewBaseRuleContext(parent RuleContext, invokingState int) *BaseRuleContext
return rn
}
func (this *BaseRuleContext) setChildren(elems []Tree) {
this.children = elems
}
func (this *BaseRuleContext) setParent(v Tree) {
func (this *BaseRuleContext) SetParent(v Tree) {
this.parentCtx = v.(RuleContext)
}
func (this *BaseRuleContext) getInvokingState() int {
func (this *BaseRuleContext) GetInvokingState() int {
return this.invokingState
}
func (this *BaseRuleContext) setInvokingState(t int) {
func (this *BaseRuleContext) SetInvokingState(t int) {
this.invokingState = t
}
@ -84,40 +76,12 @@ func (this *BaseRuleContext) GetRuleIndex() int {
return this.RuleIndex
}
func (this *BaseRuleContext) getChildren() []Tree {
return this.children
}
func (this *BaseRuleContext) depth() int {
var n = 0
var p Tree = this
for p != nil {
p = p.GetParent()
n += 1
}
return n
}
// A context is empty if there is no invoking state meaning nobody call
// current context.
func (this *BaseRuleContext) isEmpty() bool {
func (this *BaseRuleContext) IsEmpty() bool {
return this.invokingState == -1
}
// satisfy the ParseTree / SyntaxTree interface
func (this *BaseRuleContext) GetSourceInterval() *Interval {
return TreeInvalidInterval
}
func (this *BaseRuleContext) getRuleContext() RuleContext {
return this
}
func (this *BaseRuleContext) getPayload() interface{} {
return this
}
// Return the combined text of all child nodes. This method only considers
// tokens which have been added to the parse tree.
// <p>
@ -125,74 +89,7 @@ func (this *BaseRuleContext) getPayload() interface{} {
// added to the parse trees, they will not appear in the output of this
// method.
//
func (this *BaseRuleContext) GetText() string {
if this.getChildCount() == 0 {
return ""
} else {
var s string
for _, child := range this.children {
s += child.(RuleContext).GetText()
}
return s
}
}
func (this *BaseRuleContext) getChild(i int) Tree {
return nil
}
func (this *BaseRuleContext) GetParent() Tree {
return this.parentCtx
}
func (this *BaseRuleContext) getChildCount() int {
return 0
}
func (this *BaseRuleContext) accept(Visitor ParseTreeVisitor) interface{} {
return Visitor.VisitChildren(this)
}
//need to manage circular dependencies, so export now
// Print out a whole tree, not just a node, in LISP format
// (root child1 .. childN). Print just a node if this is a leaf.
//
func (this *BaseRuleContext) StringTree(ruleNames []string, recog Recognizer) string {
return TreesStringTree(this, ruleNames, recog)
}
func (this *BaseRuleContext) String(ruleNames []string, stop RuleContext) string {
var p RuleContext = this
var s = "["
for p != nil && p != stop {
if ruleNames == nil {
if !p.isEmpty() {
s += strconv.Itoa(p.getInvokingState())
}
} else {
var ri = p.GetRuleIndex()
var ruleName string
if ri >= 0 && ri < len(ruleNames) {
ruleName = ruleNames[ri]
} else {
ruleName = strconv.Itoa(ri)
}
s += ruleName
}
if p.GetParent() != nil && (ruleNames != nil || !p.GetParent().(RuleContext).isEmpty()) {
s += " "
}
pi := p.GetParent()
if pi != nil {
p = pi.(RuleContext)
} else {
p = nil
}
}
s += "]"
return s
}

View File

@ -20,7 +20,7 @@ func (this *TraceListener) EnterEveryRule(ctx ParserRuleContext) {
}
func (this *TraceListener) VisitTerminal(node TerminalNode) {
fmt.Println("consume " + fmt.Sprint(node.getSymbol()) + " rule " + this.parser.GetRuleNames()[this.parser._ctx.GetRuleIndex()])
fmt.Println("consume " + fmt.Sprint(node.GetSymbol()) + " rule " + this.parser.GetRuleNames()[this.parser._ctx.GetRuleIndex()])
}
func (this *TraceListener) ExitEveryRule(ctx ParserRuleContext) {

View File

@ -1,5 +1,6 @@
package 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.
///
@ -8,12 +9,11 @@ var TreeInvalidInterval = NewInterval(-1, -2)
type Tree interface {
GetParent() Tree
setParent(Tree)
getPayload() interface{}
getChild(i int) Tree
getChildCount() int
getChildren() []Tree
setChildren([]Tree)
SetParent(Tree)
GetPayload() interface{}
GetChild(i int) Tree
GetChildCount() int
GetChildren() []Tree
// StringTree() string
}
@ -26,8 +26,7 @@ type SyntaxTree interface {
type ParseTree interface {
SyntaxTree
// <T> T accept(ParseTreeVisitor<? extends T> Visitor);
accept(Visitor ParseTreeVisitor) interface{}
Accept(Visitor ParseTreeVisitor) interface{}
GetText() string
// StringTree([]string, IRecognizer) string
}
@ -35,13 +34,13 @@ type ParseTree interface {
type RuleNode interface {
ParseTree
getRuleContext() RuleContext
GetRuleContext() RuleContext
}
type TerminalNode interface {
ParseTree
getSymbol() Token
GetSymbol() Token
}
type ErrorNode interface {
@ -99,19 +98,19 @@ func NewTerminalNodeImpl(symbol Token) *TerminalNodeImpl {
return tn
}
func (this *TerminalNodeImpl) getChild(i int) Tree {
func (this *TerminalNodeImpl) GetChild(i int) Tree {
return nil
}
func (this *TerminalNodeImpl) getChildren() []Tree {
func (this *TerminalNodeImpl) GetChildren() []Tree {
return nil
}
func (this *TerminalNodeImpl) setChildren(t []Tree) {
func (this *TerminalNodeImpl) SetChildren(t []Tree) {
panic("Cannot set children on terminal node")
}
func (this *TerminalNodeImpl) getSymbol() Token {
func (this *TerminalNodeImpl) GetSymbol() Token {
return this.symbol
}
@ -119,11 +118,11 @@ func (this *TerminalNodeImpl) GetParent() Tree {
return this.parentCtx
}
func (this *TerminalNodeImpl) setParent(t Tree) {
func (this *TerminalNodeImpl) SetParent(t Tree) {
this.parentCtx = t.(RuleContext)
}
func (this *TerminalNodeImpl) getPayload() interface{} {
func (this *TerminalNodeImpl) GetPayload() interface{} {
return this.symbol
}
@ -135,11 +134,11 @@ func (this *TerminalNodeImpl) GetSourceInterval() *Interval {
return NewInterval(tokenIndex, tokenIndex)
}
func (this *TerminalNodeImpl) getChildCount() int {
func (this *TerminalNodeImpl) GetChildCount() int {
return 0
}
func (this *TerminalNodeImpl) accept(Visitor ParseTreeVisitor) interface{} {
func (this *TerminalNodeImpl) Accept(Visitor ParseTreeVisitor) interface{} {
return Visitor.VisitTerminal(this)
}
@ -171,11 +170,11 @@ func NewErrorNodeImpl(token Token) *ErrorNodeImpl {
return en
}
func (this *ErrorNodeImpl) isErrorNode() bool {
func (this *ErrorNodeImpl) IsErrorNode() bool {
return true
}
func (this *ErrorNodeImpl) accept(Visitor ParseTreeVisitor) interface{} {
func (this *ErrorNodeImpl) Accept(Visitor ParseTreeVisitor) interface{} {
return Visitor.VisitErrorNode(this)
}
@ -186,7 +185,7 @@ func NewParseTreeWalker() *ParseTreeWalker {
return new(ParseTreeWalker)
}
func (this *ParseTreeWalker) walk(listener ParseTreeListener, t Tree) {
func (this *ParseTreeWalker) Walk(listener ParseTreeListener, t Tree) {
if errorNode, ok := t.(ErrorNode); ok {
listener.VisitErrorNode(errorNode)
@ -194,9 +193,9 @@ func (this *ParseTreeWalker) walk(listener ParseTreeListener, t Tree) {
listener.VisitTerminal(term)
} else {
this.EnterRule(listener, t.(RuleNode))
for i := 0; i < t.getChildCount(); i++ {
var child = t.getChild(i)
this.walk(listener, child)
for i := 0; i < t.GetChildCount(); i++ {
var child = t.GetChild(i)
this.Walk(listener, child)
}
this.ExitRule(listener, t.(RuleNode))
}
@ -209,15 +208,15 @@ 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().(ParserRuleContext)
var ctx = r.GetRuleContext().(ParserRuleContext)
listener.EnterEveryRule(ctx)
ctx.EnterRule(listener)
}
func (this *ParseTreeWalker) ExitRule(listener ParseTreeListener, r RuleNode) {
var ctx = r.getRuleContext().(ParserRuleContext)
var ctx = r.GetRuleContext().(ParserRuleContext)
ctx.ExitRule(listener)
listener.ExitEveryRule(ctx)
}
var ParseTreeWalkerDEFAULT = NewParseTreeWalker()
var ParseTreeWalkerDefault = NewParseTreeWalker()

View File

@ -16,17 +16,17 @@ func TreesStringTree(tree Tree, ruleNames []string, recog Recognizer) string {
var s = TreesgetNodeText(tree, ruleNames, nil)
s = EscapeWhitespace(s, false)
var c = tree.getChildCount()
var c = tree.GetChildCount()
if c == 0 {
return s
}
var res = "(" + s + " "
if c > 0 {
s = TreesStringTree(tree.getChild(0), ruleNames, nil)
s = TreesStringTree(tree.GetChild(0), ruleNames, nil)
res += s
}
for i := 1; i < c; i++ {
s = TreesStringTree(tree.getChild(i), ruleNames, nil)
s = TreesStringTree(tree.GetChild(i), ruleNames, nil)
res += (" " + s)
}
res += ")"
@ -41,30 +41,30 @@ func TreesgetNodeText(t Tree, ruleNames []string, recog *BaseParser) string {
if ruleNames != nil {
if t2, ok := t.(RuleNode); ok {
return ruleNames[t2.getRuleContext().GetRuleIndex()]
return ruleNames[t2.GetRuleContext().GetRuleIndex()]
} else if t2, ok := t.(ErrorNode); ok {
return fmt.Sprint(t2)
} else if t2, ok := t.(TerminalNode); ok {
if t2.getSymbol() != nil {
return t2.getSymbol().GetText()
if t2.GetSymbol() != nil {
return t2.GetSymbol().GetText()
}
}
}
// no recog for rule names
var payload = t.getPayload()
var payload = t.GetPayload()
if p2, ok := payload.(Token); ok {
return p2.GetText()
}
return fmt.Sprint(t.getPayload())
return fmt.Sprint(t.GetPayload())
}
// Return ordered list of all children of this node
func TreesgetChildren(t Tree) []Tree {
func TreesGetChildren(t Tree) []Tree {
var list = make([]Tree, 0)
for i := 0; i < t.getChildCount(); i++ {
list = append(list, t.getChild(i))
for i := 0; i < t.GetChildCount(); i++ {
list = append(list, t.GetChild(i))
}
return list
}
@ -104,7 +104,7 @@ func Trees_findAllNodes(t ParseTree, index int, findTokens bool, nodes []ParseTr
t3, ok2 := t.(ParserRuleContext)
if findTokens && ok {
if t2.getSymbol().GetTokenType() == index {
if t2.GetSymbol().GetTokenType() == index {
nodes = append(nodes, t2)
}
} else if !findTokens && ok2 {
@ -113,15 +113,15 @@ func Trees_findAllNodes(t ParseTree, index int, findTokens bool, nodes []ParseTr
}
}
// check children
for i := 0; i < t.getChildCount(); i++ {
Trees_findAllNodes(t.getChild(i).(ParseTree), index, findTokens, nodes)
for i := 0; i < t.GetChildCount(); i++ {
Trees_findAllNodes(t.GetChild(i).(ParseTree), index, findTokens, nodes)
}
}
func Treesdescendants(t ParseTree) []ParseTree {
var nodes = []ParseTree{t}
for i := 0; i < t.getChildCount(); i++ {
nodes = append(nodes, Treesdescendants(t.getChild(i).(ParseTree))...)
for i := 0; i < t.GetChildCount(); i++ {
nodes = append(nodes, Treesdescendants(t.GetChild(i).(ParseTree))...)
}
return nodes
}

View File

@ -22,11 +22,11 @@ KeyPrinter.prototype = Object.create(ArithmeticListener.prototype);
KeyPrinter.prototype.constructor = KeyPrinter;
// override default listener behavior
KeyPrinter.prototype.exitAtom = function(ctx) {
KeyPrinter.prototype.enterAtom = function(ctx) {
console.log("Oh, a atom!");
};
KeyPrinter.prototype.exitExpression = function(ctx) {
KeyPrinter.prototype.enterExpression = function(ctx) {
console.log("Oh, an expression!");
};

View File

@ -1,10 +1,3 @@
/** ANTLR tool checks output templates are compatible with tool code generation.
* For now, a simple string Match used on x.y of x.y.z scheme.
* Must Match Tool.VERSION during load to templates.
*
* REQUIRED.
*/
fileHeader(grammarFileName, ANTLRVersion) ::= <<
// Generated from <grammarFileName; format="java-escape"> by ANTLR <ANTLRVersion>
>>
@ -26,43 +19,50 @@ import (
>>
ListenerFile(file, header) ::= <<
<fileHeader(file.grammarFileName, file.ANTLRVersion)>
package parser // <file.grammarName>
import "antlr4"
// This class defines a complete listener for a parse tree produced by <file.parserName>
// A complete listener for a parse tree produced by <file.parserName>
type <file.grammarName>Listener struct {
}
func (l *<file.grammarName>Listener) EnterEveryRule(node antlr4.ParserRuleContext) {
\}
func (l *<file.grammarName>Listener) ExitEveryRule(node antlr4.ParserRuleContext) {
\}
func (l *<file.grammarName>Listener) VisitTerminal(ctx antlr4.TerminalNode) {
\}
func (l *<file.grammarName>Listener) VisitErrorNode(ctx antlr4.ErrorNode) {
\}
type <file.grammarName>Listener interface {
antlr4.ParseTreeListener
<file.listenerNames:{lname |
// Enter a parse tree produced by <file.parserName>#<lname>.
func (l *<file.grammarName>Listener) Enter<lname; format="cap">(ctx antlr4.ParserRuleContext) {
\}
// Exit a parse tree produced by <file.parserName>#<lname>.
func (l *<file.grammarName>Listener) Exit<lname; format="cap">(ctx antlr4.ParserRuleContext) {
\}
Enter<lname; format="cap">(*<lname; format="cap">Context)
Exit<lname; format="cap">(*<lname; format="cap">Context)
}; separator="\n">
}
>>
BaseListenerFile(file, header) ::= <<
<fileHeader(file.grammarFileName, file.ANTLRVersion)>
package parser // <file.grammarName>
import "antlr4"
// A complete base listener for a parse tree produced by <file.parserName>
type Base<file.grammarName>Listener struct {
}
func (s *Base<file.grammarName>Listener) VisitTerminal(node antlr4.TerminalNode){}
func (s *Base<file.grammarName>Listener) VisitErrorNode(node antlr4.ErrorNode){}
func (s *Base<file.grammarName>Listener) EnterEveryRule(ctx antlr4.ParserRuleContext){}
func (s *Base<file.grammarName>Listener) ExitEveryRule(ctx antlr4.ParserRuleContext){}
<file.listenerNames:{lname |
func (s *Base<file.grammarName>Listener) Enter<lname; format="cap">(ctx *<lname; format="cap">Context) {\}
func (s *Base<file.grammarName>Listener) Exit<lname; format="cap">(ctx *<lname; format="cap">Context){\}
}; separator="\n">
>>
@ -74,19 +74,16 @@ import "antlr4"
<header>
// This class defines a complete generic Visitor for a parse tree produced by <file.parserName>.
// A complete Visitor for a parse tree produced by <file.parserName>.
type <file.grammarName>Visitor struct {
}
type <file.grammarName>Visitor interface {
antlr4.ParseTreeVisitor
<file.VisitorNames:{lname |
// Visit a parse tree produced by <file.parserName>#<lname>.
func (l <file.grammarName>Visitor) Visit<lname; format="cap">(ctx antlr4.ParserRuleContext) {
\}
// Visit a parse tree produced by <file.parserName>#<lname>.
Visit<lname; format="cap">(ctx antlr4.ParserRuleContext)
}; separator="\n">
}
>>
Parser(parser, funcs, atn, sempredFuncs, superClass) ::= <<
@ -676,6 +673,12 @@ func (s *<struct.name>) CopyFrom(ctx <struct.name>) {
<struct.attrs:{a | s.<a.name> = ctx.<a.name>;}; separator="\n">
}
<endif>
func (s *<struct.name>) GetRuleContext() antlr4.RuleContext {
// Go does not truly support inheritance nor virtual method calls, so we need to implement this directly
return s
}
<dispatchMethods; separator="\n">
<extensionMembers; separator="\n">
@ -692,10 +695,10 @@ func New<struct.name>(parser antlr4.Parser, ctx antlr4.ParserRuleContext) *<stru
var p = new(<struct.name>)
<currentRule.name; format="cap">Context.call(this, parser)
// TODO <currentRule.name; format="cap">Context.call(this, parser)
<attrs:{a | <a>;}; separator="\n">
<currentRule.name; format="cap">Context.prototype.CopyFrom.call(this, ctx)
// TODO <currentRule.name; format="cap">Context.prototype.CopyFrom.call(this, ctx)
return p
}
@ -709,7 +712,7 @@ func New<struct.name>(parser antlr4.Parser, ctx antlr4.ParserRuleContext) *<stru
ListenerDispatchMethod(method) ::= <<
func (s *<struct.name>) <if(method.isEnter)>Enter<else>Exit<endif>Rule(listener antlr4.ParseTreeListener) {
listener.(*<parser.grammarName>Listener).<if(method.isEnter)>Enter<else>Exit<endif><struct.derivedFromName; format="cap">(s)
listener.(<parser.grammarName>Listener).<if(method.isEnter)>Enter<else>Exit<endif><struct.derivedFromName; format="cap">(s)
}
@ -720,7 +723,7 @@ VisitorDispatchMethod(method) ::= <<
func (s *<struct.name>) Accept(Visitor antlr4.ParseTreeVisitor) interface{} {
switch t := listener.(type) {
case *<parser.grammarName>Listener:
case <parser.grammarName>Listener:
return t.Visit<struct.derivedFromName; format="cap">(s)
default:
return t.VisitChildren(s)

View File

@ -96,11 +96,11 @@ public class GoTarget extends Target {
}
public boolean wantsBaseListener() {
return false;
return true;
}
public boolean wantsBaseVisitor() {
return false;
return true;
}
public boolean supportsOverloadedMethods() {