More work on error

This commit is contained in:
Peter Boyer 2015-12-16 17:57:24 -05:00
parent 2aad0fde60
commit 2cd064a94e
12 changed files with 255 additions and 219 deletions

View File

@ -35,7 +35,7 @@ func (this *TraceListener) exitEveryRule(ctx) {
type Parser struct {
Recognizer
_input *TokenSource
_input *Lexer
_errHandler *error.ErrorStrategy
_precedenceStack IntStack
_ctx RuleContext
@ -125,13 +125,13 @@ func (p *Parser) reset() {
// {@code ttype} and the error strategy could not recover from the
// mismatched symbol
func (p *Parser) match(ttype) {
func (p *Parser) match(ttype int) *Token {
var t = p.getCurrentToken()
if (t.tokenType == ttype) {
p._errHandler.reportMatch(p.
p.consume()
} else {
t = p._errHandler.recoverInline(p.
t = p._errHandler.recoverInline(p)
if (p.buildParseTrees && t.tokenIndex == -1) {
// we must have conjured up a Newtoken during single token
// insertion
@ -211,9 +211,9 @@ func (p *Parser) addParseListener(listener *tree.ParseTreeListener) {
panic("listener")
}
if (p._parseListeners == nil) {
p._parseListeners = []
p._parseListeners = new([]tree.ParseTreeListener)
}
p._parseListeners.push(listener)
p._parseListeners = append(p._parseListeners, listener)
}
//
@ -314,8 +314,8 @@ func (p *Parser) getATNWithBypassAlts() {
//var Lexer = require('./Lexer').Lexer
func (p *Parser) compileParseTreePattern(pattern, patternRuleIndex, lexer) {
lexer = lexer || nil
func (p *Parser) compileParseTreePattern(pattern, patternRuleIndex, lexer *Lexer) {
if (lexer == nil) {
if (p.getTokenStream() != nil) {
var tokenSource = p.getTokenStream().tokenSource
@ -325,9 +325,9 @@ func (p *Parser) compileParseTreePattern(pattern, patternRuleIndex, lexer) {
}
}
if (lexer == nil) {
panic "Parser can't discover a lexer to use"
panic("Parser can't discover a lexer to use")
}
var m = NewParseTreePatternMatcher(lexer, p.
var m = NewParseTreePatternMatcher(lexer, p)
return m.compile(pattern, patternRuleIndex)
}
@ -353,7 +353,7 @@ func (p *Parser) setTokenStream(input) {
// Match needs to return the current input symbol, which gets put
// into the label for the associated token ref e.g., x=ID.
//
func (p *Parser) getCurrentToken() int {
func (p *Parser) getCurrentToken() *Token {
return p._input.LT(1)
}
@ -424,7 +424,7 @@ func (p *Parser) addContextToParseTree() {
// Always called by generated parsers upon entry to a rule. Access field
// {@link //_ctx} get the current context.
func (p *Parser) enterRule(localctx, state, ruleIndex) {
func (p *Parser) enterRule(localctx, state, ruleIndex int) {
p.state = state
p._ctx = localctx
p._ctx.start = p._input.LT(1)
@ -671,7 +671,7 @@ func (p *Parser) getSourceName() {
// During a parse is sometimes useful to listen in on the rule entry and exit
// events as well as token matches. p.is for quick and dirty debugging.
//
func (p *Parser) setTrace(trace) {
func (p *Parser) setTrace(trace bool) {
if (!trace) {
p.removeParseListener(p._tracer)
p._tracer = nil

View File

@ -1,7 +1,5 @@
package antlr4
//var RuleContext = require('./RuleContext').RuleContext
type PredictionContext struct {
cachedHashString string
}
@ -19,7 +17,8 @@ func NewPredictionContext(cachedHashString string) *PredictionContext {
// {@code//+x =//}.
// /
const (
PredictionContext.EMPTY = nil
PredictionContextEMPTY = nil
PredictionContextEMPTY_RETURN_STATE = 0x7FFFFFFF
)
@ -27,7 +26,6 @@ const (
// doesn't mean wildcard: {@code $ + x = [$,x]}. Here,
// {@code $} = {@link //EMPTY_RETURN_STATE}.
// /
PredictionContext.EMPTY_RETURN_STATE = 0x7FFFFFFF
PredictionContext.globalNodeCount = 1
PredictionContext.id = PredictionContext.globalNodeCount
@ -59,11 +57,11 @@ PredictionContext.id = PredictionContext.globalNodeCount
// This means only the {@link //EMPTY} context is in set.
func (this *PredictionContext) isEmpty() {
return this == PredictionContext.EMPTY
return this == PredictionContextEMPTY
}
func (this *PredictionContext) hasEmptyPath() {
return this.getReturnState(this.length - 1) == PredictionContext.EMPTY_RETURN_STATE
return this.getReturnState(this.length - 1) == PredictionContextEMPTY_RETURN_STATE
}
func (this *PredictionContext) hashString() {

View File

@ -2,17 +2,15 @@ package antlr4
import (
"fmt"
"strings"
"antlr4/atn"
"antlr4/tree"
"antlr4/error"
)
//var Token = require('./Token').Token
//var ConsoleErrorListener = require('./error/ErrorListener').ConsoleErrorListener
//var ProxyErrorListener = require('./error/ErrorListener').ProxyErrorListener
type Recognizer struct {
_listeners []tree.ParseTreeListener
_interp *Parser
_interp *atn.ATNSimulator
state int
}
@ -41,20 +39,20 @@ func (this *Recognizer) addErrorListener(listener *tree.ParseTreeListener) {
func (this *Recognizer) removeErrorListeners() {
this._listeners = make([]tree.ParseTreeListener, 1)
}
func (this *Recognizer) getTokenTypeMap() {
var tokenNames = this.getTokenNames()
if (tokenNames==nil) {
panic("The current recognizer does not provide a list of token names.")
}
var result = tokenTypeMapCache[tokenNames]
if(result==nil) {
result = tokenNames.reduce(function(o, k, i) { o[k] = i })
result.EOF = TokenEOF
tokenTypeMapCache[tokenNames] = result
}
return result
}
//
//func (this *Recognizer) getTokenTypeMap() {
// var tokenNames = this.getTokenNames()
// if (tokenNames==nil) {
// panic("The current recognizer does not provide a list of token names.")
// }
// var result = tokenTypeMapCache[tokenNames]
// if(result==nil) {
// result = tokenNames.reduce(function(o, k, i) { o[k] = i })
// result.EOF = TokenEOF
// tokenTypeMapCache[tokenNames] = result
// }
// return result
//}
// Get a map from rule names to rule indexes.
//
@ -72,22 +70,23 @@ func (this *Recognizer) getRuleIndexMap() {
}
return result
}
func (this *Recognizer) getTokenType(tokenName string) int {
var ttype = this.getTokenTypeMap()[tokenName]
if (ttype !=nil) {
return ttype
} else {
return TokenInvalidType
}
}
//
//func (this *Recognizer) getTokenType(tokenName string) int {
// var ttype = this.getTokenTypeMap()[tokenName]
// if (ttype !=nil) {
// return ttype
// } else {
// return TokenInvalidType
// }
//}
// What is the error header, normally line/character position information?//
func (this *Recognizer) getErrorHeader(e) {
var line = e.getOffendingToken().line
var column = e.getOffendingToken().column
return "line " + line + ":" + column
func (this *Recognizer) getErrorHeader(e error) string {
panic("Method not defined!")
// var line = e.getOffendingToken().line
// var column = e.getOffendingToken().column
// return "line " + line + ":" + column
}
@ -108,7 +107,7 @@ func (this *Recognizer) getTokenErrorDisplay(t *Token) string {
if (t==nil) {
return "<no token>"
}
var s = t.text
var s = t.text()
if s==nil {
if (t.tokenType==TokenEOF) {
s = "<EOF>"
@ -116,7 +115,10 @@ func (this *Recognizer) getTokenErrorDisplay(t *Token) string {
s = "<" + t.tokenType + ">"
}
}
s = s.replace("\n","\\n").replace("\r","\\r").replace("\t","\\t")
s = strings.Replace(s,"\t","\\t", -1)
s = strings.Replace(s,"\n","\\n", -1)
s = strings.Replace(s,"\r","\\r", -1)
return "'" + s + "'"
}
@ -130,7 +132,7 @@ func (this *Recognizer) sempred(localctx *RuleContext, ruleIndex int, actionInde
return true
}
func (this *Recognizer) precpred(localctx *RuleContext, precedence) {
func (this *Recognizer) precpred(localctx *RuleContext, precedence int) bool {
return true
}
@ -141,14 +143,4 @@ func (this *Recognizer) precpred(localctx *RuleContext, precedence) {
//invoking rules. Combine this and we have complete ATN
//configuration information.
//Object.defineProperty(Recognizer.prototype, "state", {
// get : function() {
// return this._stateNumber
// },
// set : function(state) {
// this._stateNumber = state
// }
//})

View File

@ -1,5 +1,9 @@
package atn
import (
"antlr4"
)
//
// Specialized {@link Set}{@code <}{@link ATNConfig}{@code >} that can track
// info about the set, with support for combining similar configurations using a
@ -40,7 +44,7 @@ func ATNConfigSet(fullCtx) {
// 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 = NewSet(hashATNConfig, equalATNConfigs)
this.configLookup = antlr4.NewSet(hashATNConfig, equalATNConfigs)
// Indicates that this 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.
@ -115,7 +119,7 @@ func (this *ATNConfigSet) add(config, mergeCache) {
}
func (this *ATNConfigSet) getStates() {
var states = NewSet()
var states = antlr4.NewSet()
for i := 0; i < len(this.configs); i++ {
states.add(this.configs[i].state)
}
@ -222,7 +226,7 @@ func (this *ATNConfigSet) clear() {
}
this.configs = []
this.cachedHashString = "-1"
this.configLookup = NewSet()
this.configLookup = antlr4.NewSet()
}
func (this *ATNConfigSet) setReadonly(readOnly) {
@ -242,7 +246,7 @@ func (this *ATNConfigSet) toString() string {
type OrderedATNConfigSet struct {
ATNConfigSet.call(this)
this.configLookup = NewSet()
this.configLookup = antlr4.NewSet()
return this
}

View File

@ -600,7 +600,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 NewSetTransition(target, sets[arg1])
return antlr4.NewSetTransition(target, sets[arg1])
case Transition.NOT_SET:
return NewNotSetTransition(target, sets[arg1])
case Transition.WILDCARD:

View File

@ -785,7 +785,7 @@ func (this *ParserATNSimulator) computeReachSet(closure, t, fullCtx) {
//
if (reach==nil) {
reach = NewATNConfigSet(fullCtx)
var closureBusy = NewSet()
var closureBusy = antlr4.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 +879,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 = NewSet()
var closureBusy = antlr4.NewSet()
this.closure(c, configs, closureBusy, true, fullCtx, false)
}
return configs
@ -1134,7 +1134,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 Newset so as not to alter the incoming parameter.
// Create a antlr4.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 +1165,7 @@ func (this *ParserATNSimulator) splitAccordingToSemanticValidity( configs, outer
// includes pairs with nil predicates.
//
func (this *ParserATNSimulator) evalSemanticContext(predPredictions, outerContext, complete) {
var predictions = NewBitSet()
var predictions = antlr4.NewBitSet()
for(var i=0i<predPredictions.lengthi++) {
var pair = predPredictions[i]
if (pair.pred == SemanticContext.NONE) {
@ -1478,7 +1478,7 @@ func (this *ParserATNSimulator) getConflictingAlts(configs) {
func (this *ParserATNSimulator) getConflictingAltsOrUniqueAlt(configs) {
var conflictingAlts = nil
if (configs.uniqueAlt!= ATN.INVALID_ALT_NUMBER) {
conflictingAlts = NewBitSet()
conflictingAlts = antlr4.NewBitSet()
conflictingAlts.add(configs.uniqueAlt)
} else {
conflictingAlts = configs.conflictingAlts

View File

@ -477,7 +477,7 @@ PredictionModegetUniqueAlt = function(altsets) {
// @return the set of represented alternatives in {@code altsets}
//
PredictionModegetAlts = function(altsets) {
var all = NewBitSet()
var all = antlr4.NewBitSet()
altsets.map( function(alts) { all.or(alts) })
return all
}
@ -498,7 +498,7 @@ PredictionModegetConflictingAltSubsets = function(configs) {
var key = "key_" + c.state.stateNumber + "/" + c.context
var alts = configToAlts[key] || nil
if (alts == nil) {
alts = NewBitSet()
alts = antlr4.NewBitSet()
configToAlts[key] = alts
}
alts.add(c.alt)
@ -526,7 +526,7 @@ PredictionModegetStateToAltMap = function(configs) {
configs.items.map(function(c) {
var alts = m.get(c.state)
if (alts == nil) {
alts = NewBitSet()
alts = antlr4.NewBitSet()
m.put(c.state, alts)
}
alts.add(c.alt)

View File

@ -1,5 +1,9 @@
package atn
import (
"antlr4"
)
// A tree structure used to record the semantic context in which
// an ATN configuration is valid. It's either a single predicate,
// a conjunction {@code p1&&p2}, or a sum of products {@code p1||p2}.
@ -11,7 +15,11 @@ package atn
//var Set = require('./../Utils').Set
type SemanticContext struct {
return this
}
func NewSemanticContext() *SemanticContext {
return new(SemanticContext)
}
// For context independent predicates, we evaluate them without a local
@ -84,12 +92,20 @@ SemanticContext.orContext = function(a, b) {
}
}
func Predicate(ruleIndex, predIndex, isCtxDependent) {
SemanticContext.call(this)
this.ruleIndex = ruleIndex == nil ? -1 : ruleIndex
this.predIndex = predIndex == nil ? -1 : predIndex
this.isCtxDependent = isCtxDependent == nil ? false : isCtxDependent // e.g., $i ref in pred
return this
type Predicate struct {
SemanticContext
ruleIndex int
predIndex int
isCtxDependent bool
}
func Predicate(ruleIndex, predIndex int, isCtxDependent bool) {
p := &Predicate{SemanticContext{}}
p.ruleIndex = ruleIndex
p.predIndex = predIndex
p.isCtxDependent = isCtxDependent // e.g., $i ref in pred
return p
}
//Predicate.prototype = Object.create(SemanticContext.prototype)
@ -98,7 +114,7 @@ func Predicate(ruleIndex, predIndex, isCtxDependent) {
//The default {@link SemanticContext}, which is semantically equivalent to
//a predicate of the form {@code {true}?}.
//
SemanticContext.NONE = NewPredicate()
var SemanticContextNONE = NewPredicate()
func (this *Predicate) evaluate(parser, outerContext) {
@ -186,7 +202,7 @@ PrecedencePredicate.filterPrecedencePredicates = function(set) {
//
func AND(a, b) {
SemanticContext.call(this)
var operands = NewSet()
var operands = antlr4.antlr4.NewSet()
if _, ok := a.(AND); ok {
a.opnds.map(function(o) {
operands.add(o)
@ -291,7 +307,7 @@ func (this *AND) toString() string {
//
func OR(a, b) {
SemanticContext.call(this)
var operands = NewSet()
var operands = antlr4.NewSet()
if _, ok := a.(OR); ok {
a.opnds.map(function(o) {
operands.add(o)

View File

@ -1,4 +1,9 @@
package error
import (
"antlr4"
"antlr4/atn"
"antlr4/dfa"
)
//
// This implementation of {@link ANTLRErrorListener} can be used to identify
@ -23,19 +28,24 @@ package error
//var ErrorListener = require('./ErrorListener').ErrorListener
//var Interval = require('./../IntervalSet').Interval
func DiagnosticErrorListener(exactOnly) {
ErrorListener.call(this)
exactOnly = exactOnly || true
type DiagnosticErrorListener struct {
ErrorListener
exactOnly bool
}
func DiagnosticErrorListener(exactOnly bool) {
n = new(DiagnosticErrorListener)
// whether all ambiguities or only exact ambiguities are reported.
this.exactOnly = exactOnly
return this
n.exactOnly = exactOnly
return n
}
//DiagnosticErrorListener.prototype = Object.create(ErrorListener.prototype)
//DiagnosticErrorListener.prototype.constructor = DiagnosticErrorListener
func (this *DiagnosticErrorListener) reportAmbiguity(recognizer, dfa,
startIndex, stopIndex, exact, ambigAlts, configs) {
func (this *DiagnosticErrorListener) reportAmbiguity(recognizer *antlr4.Parser, dfa *dfa.DFA, startIndex, stopIndex int, exact bool, ambigAlts *antlr4.BitSet, configs *atn.ATNConfigSet) {
if (this.exactOnly && !exact) {
return
}
@ -48,8 +58,8 @@ func (this *DiagnosticErrorListener) reportAmbiguity(recognizer, dfa,
recognizer.notifyErrorListeners(msg)
}
func (this *DiagnosticErrorListener) reportAttemptingFullContext(
recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs) {
func (this *DiagnosticErrorListener) reportAttemptingFullContext(recognizer *antlr4.Parser, dfa *dfa.DFA, startIndex, stopIndex int, conflictingAlts *antlr4.BitSet, configs *atn.ATNConfigSet) {
var msg = "reportAttemptingFullContext d=" +
this.getDecisionDescription(recognizer, dfa) +
", input='" +
@ -57,8 +67,7 @@ func (this *DiagnosticErrorListener) reportAttemptingFullContext(
recognizer.notifyErrorListeners(msg)
}
func (this *DiagnosticErrorListener) reportContextSensitivity(
recognizer, dfa, startIndex, stopIndex, prediction, configs) {
func (this *DiagnosticErrorListener) reportContextSensitivity(recognizer *antlr4.Parser, dfa *dfa.DFA, startIndex, stopIndex, prediction int, configs *atn.ATNConfigSet) {
var msg = "reportContextSensitivity d=" +
this.getDecisionDescription(recognizer, dfa) +
", input='" +
@ -66,7 +75,7 @@ func (this *DiagnosticErrorListener) reportContextSensitivity(
recognizer.notifyErrorListeners(msg)
}
func (this *DiagnosticErrorListener) getDecisionDescription(recognizer, dfa) {
func (this *DiagnosticErrorListener) getDecisionDescription(recognizer, dfa *dfa.DFA) {
var decision = dfa.decision
var ruleIndex = dfa.atnStartState.ruleIndex
@ -96,10 +105,9 @@ func (this *DiagnosticErrorListener) getConflictingAlts(reportedAlts, configs) {
if (reportedAlts != nil) {
return reportedAlts
}
var result = NewBitSet()
var result = antlr4.NewBitSet()
for i := 0; i < len(configs.items); i++ {
result.add(configs.items[i].alt)
}
return "{" + result.values().join(", ") + "}"
}
}

View File

@ -1,37 +1,48 @@
package error
import (
"antlr4"
"antlr4/atn"
"antlr4/dfa"
"fmt"
)
// Provides an empty default implementation of {@link ANTLRErrorListener}. The
// default implementation of each method does nothing, but can be overridden as
// necessary.
type ErrorListener struct {
return this
}
func (this *ErrorListener) syntaxError(recognizer, offendingSymbol, line, column, msg, e) {
func NewErrorListener() *ErrorListener {
return new(ErrorListener)
}
func (this *ErrorListener) reportAmbiguity(recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs) {
func (this *ErrorListener) syntaxError(recognizer *antlr4.Parser, offendingSymbol interface{}, line, column int, msg string, e *RecognitionException) {
}
func (this *ErrorListener) reportAttemptingFullContext(recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs) {
func (this *ErrorListener) reportAmbiguity(recognizer *antlr4.Parser, dfa *dfa.DFA, startIndex, stopIndex int, exact bool, ambigAlts *antlr4.BitSet, configs *atn.ATNConfigSet) {
}
func (this *ErrorListener) reportContextSensitivity(recognizer, dfa, startIndex, stopIndex, prediction, configs) {
func (this *ErrorListener) reportAttemptingFullContext(recognizer *antlr4.Parser, dfa *dfa.DFA, startIndex, stopIndex int, conflictingAlts *antlr4.BitSet, configs *atn.ATNConfigSet) {
}
func (this *ErrorListener) reportContextSensitivity(recognizer *antlr4.Parser, dfa *dfa.DFA, startIndex, stopIndex, prediction int, configs *atn.ATNConfigSet) {
}
type ConsoleErrorListener struct {
ErrorListener.call(this)
return this
ErrorListener
}
//ConsoleErrorListener.prototype = Object.create(ErrorListener.prototype)
//ConsoleErrorListener.prototype.constructor = ConsoleErrorListener
func NewConsoleErrorListener() *ConsoleErrorListener {
return new(ConsoleErrorListener)
}
//
// Provides a default instance of {@link ConsoleErrorListener}.
//
ConsoleErrorListener.INSTANCE = NewConsoleErrorListener()
var ConsoleErrorListenerINSTANCE = NewConsoleErrorListener()
//
// {@inheritDoc}
@ -45,39 +56,51 @@ ConsoleErrorListener.INSTANCE = NewConsoleErrorListener()
// line <em>line</em>:<em>charPositionInLine</em> <em>msg</em>
// </pre>
//
func (this *ConsoleErrorListener) syntaxError(recognizer, offendingSymbol, line, column, msg, e) {
console.error("line " + line + ":" + column + " " + msg)
func (this *ConsoleErrorListener) syntaxError(recognizer *antlr4.Parser, offendingSymbol interface{}, line, column int, msg string, e *RecognitionException) {
fmt.Errorf("line " + line + ":" + column + " " + msg)
}
func ProxyErrorListener(delegates) {
ErrorListener.call(this)
type ProxyErrorListener struct {
ErrorListener
delegates []ErrorListener
}
func NewProxyErrorListener(delegates []ErrorListener) *ConsoleErrorListener {
if (delegates==nil) {
panic "delegates"
panic("delegates is not provided")
}
this.delegates = delegates
return this
l := new(ProxyErrorListener)
l.delegates = delegates
return l
}
//ProxyErrorListener.prototype = Object.create(ErrorListener.prototype)
//ProxyErrorListener.prototype.constructor = ProxyErrorListener
func (this *ProxyErrorListener) syntaxError(recognizer, offendingSymbol, line, column, msg, e) {
this.delegates.map(function(d) { d.syntaxError(recognizer, offendingSymbol, line, column, msg, e) })
func (this *ProxyErrorListener) syntaxError(recognizer *antlr4.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, dfa, startIndex, stopIndex, exact, ambigAlts, configs) {
this.delegates.map(function(d) { d.reportAmbiguity(recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs) })
func (this *ProxyErrorListener) reportAmbiguity(recognizer *antlr4.Parser, dfa *dfa.DFA, startIndex, stopIndex int, exact bool, ambigAlts *antlr4.BitSet, configs *atn.ATNConfigSet) {
for _,d := range this.delegates {
d.reportAmbiguity(recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs)
}
}
func (this *ProxyErrorListener) reportAttemptingFullContext(recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs) {
this.delegates.map(function(d) { d.reportAttemptingFullContext(recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs) })
func (this *ProxyErrorListener) reportAttemptingFullContext(recognizer *antlr4.Parser, dfa *dfa.DFA, startIndex, stopIndex int, conflictingAlts *antlr4.BitSet, configs *atn.ATNConfigSet) {
for _,d := range this.delegates {
d.reportAttemptingFullContext(recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs)
}
}
func (this *ProxyErrorListener) reportContextSensitivity(recognizer, dfa, startIndex, stopIndex, prediction, configs) {
this.delegates.map(function(d) { d.reportContextSensitivity(recognizer, dfa, startIndex, stopIndex, prediction, configs) })
func (this *ProxyErrorListener) reportContextSensitivity(recognizer *antlr4.Parser, dfa *dfa.DFA, startIndex, stopIndex, prediction int, configs *atn.ATNConfigSet) {
for _,d := range this.delegates {
d.reportContextSensitivity(recognizer, dfa, startIndex, stopIndex, prediction, configs)
}
}

View File

@ -1,40 +1,32 @@
package error
import (
"fmt"
"antlr4"
"antlr4/atn"
"strings"
)
//var Token = require('./../Token').Token
//var Errors = require('./Errors')
//var NoViableAltException = Errors.NoViableAltException
//var InputMismatchException = Errors.InputMismatchException
//var FailedPredicateException = Errors.FailedPredicateException
//var ParseCancellationException = Errors.ParseCancellationException
//var ATNState = require('./../atn/ATNState').ATNState
//var Interval = require('./../IntervalSet').Interval
//var IntervalSet = require('./../IntervalSet').IntervalSet
type ErrorStrategy struct {
}
func (this *ErrorStrategy) reset(recognizer *antlr4.Recognizer){
func (this *ErrorStrategy) reset(recognizer *antlr4.Parser){
}
func (this *ErrorStrategy) recoverInline(recognizer *antlr4.Recognizer){
func (this *ErrorStrategy) recoverInline(recognizer *antlr4.Parser){
}
func (this *ErrorStrategy) recover(recognizer *antlr4.Recognizer, e *Error){
func (this *ErrorStrategy) recover(recognizer *antlr4.Parser, e *Error){
}
func (this *ErrorStrategy) sync(recognizer *antlr4.Recognizer){
func (this *ErrorStrategy) sync(recognizer *antlr4.Parser){
}
func (this *ErrorStrategy) inErrorRecoveryMode(recognizer *antlr4.Recognizer){
func (this *ErrorStrategy) inErrorRecoveryMode(recognizer *antlr4.Parser){
}
func (this *ErrorStrategy) reportError(recognizer *antlr4.Recognizer){
func (this *ErrorStrategy) reportError(recognizer *antlr4.Parser){
}
// This is the default implementation of {@link ANTLRErrorStrategy} used for
@ -77,7 +69,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.Recognizer) {
func (this *DefaultErrorStrategy) reset(recognizer *antlr4.Parser) {
this.endErrorCondition(recognizer)
}
@ -87,11 +79,11 @@ func (this *DefaultErrorStrategy) reset(recognizer *antlr4.Recognizer) {
//
// @param recognizer the parser instance
//
func (this *DefaultErrorStrategy) beginErrorCondition(recognizer *antlr4.Recognizer) {
func (this *DefaultErrorStrategy) beginErrorCondition(recognizer *antlr4.Parser) {
this.errorRecoveryMode = true
}
func (this *DefaultErrorStrategy) inErrorRecoveryMode(recognizer *antlr4.Recognizer) {
func (this *DefaultErrorStrategy) inErrorRecoveryMode(recognizer *antlr4.Parser) {
return this.errorRecoveryMode
}
@ -101,7 +93,7 @@ func (this *DefaultErrorStrategy) inErrorRecoveryMode(recognizer *antlr4.Recogni
//
// @param recognizer
//
func (this *DefaultErrorStrategy) endErrorCondition(recognizer *antlr4.Recognizer) {
func (this *DefaultErrorStrategy) endErrorCondition(recognizer *antlr4.Parser) {
this.errorRecoveryMode = false
this.lastErrorStates = nil
this.lastErrorIndex = -1
@ -112,7 +104,7 @@ func (this *DefaultErrorStrategy) endErrorCondition(recognizer *antlr4.Recognize
//
// <p>The default implementation simply calls {@link //endErrorCondition}.</p>
//
func (this *DefaultErrorStrategy) reportMatch(recognizer *antlr4.Recognizer) {
func (this *DefaultErrorStrategy) reportMatch(recognizer *antlr4.Parser) {
this.endErrorCondition(recognizer)
}
@ -135,23 +127,25 @@ func (this *DefaultErrorStrategy) reportMatch(recognizer *antlr4.Recognizer) {
// the exception</li>
// </ul>
//
func (this *DefaultErrorStrategy) reportError(recognizer, e) {
func (this *DefaultErrorStrategy) reportError(recognizer *antlr4.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)) {
return // don't report spurious errors
}
this.beginErrorCondition(recognizer)
if ( e instanceof NoViableAltException ) {
this.reportNoViableAlternative(recognizer, e)
} else if ( e instanceof InputMismatchException ) {
this.reportInputMismatch(recognizer, e)
} else if ( e instanceof FailedPredicateException ) {
this.reportFailedPredicate(recognizer, e)
} else {
fmt.Println("unknown recognition error type: " + e.constructor.name)
fmt.Println(e.stack)
recognizer.notifyErrorListeners(e.getOffendingToken(), e.getMessage(), e)
switch e.(type) {
default:
fmt.Println("unknown recognition error type: " + e.constructor.name)
fmt.Println(e.stack)
recognizer.notifyErrorListeners(e.getOffendingToken(), e.getMessage(), e)
case NoViableAltException:
this.reportNoViableAlternative(recognizer, e)
case InputMismatchException:
this.reportInputMismatch(recognizer, e)
case FailedPredicateException:
this.reportFailedPredicate(recognizer, e)
}
}
//
@ -161,7 +155,7 @@ func (this *DefaultErrorStrategy) reportError(recognizer, 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, e) {
func (this *DefaultErrorStrategy) recover(recognizer *antlr4.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
@ -224,7 +218,7 @@ func (this *DefaultErrorStrategy) recover(recognizer, e) {
// 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.Recognizer) {
func (this *DefaultErrorStrategy) sync(recognizer *antlr4.Parser) {
// If already recovering, don't try to sync
if (this.inErrorRecoveryMode(recognizer)) {
return
@ -232,35 +226,35 @@ func (this *DefaultErrorStrategy) sync(recognizer *antlr4.Recognizer) {
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==TokenEOF || recognizer.atn.nextTokens(s).contains(la)) {
if (la==antlr4.TokenEOF || recognizer.atn.nextTokens(s).contains(la)) {
return
}
// Return but don't end recovery. only do that upon valid token match
if(recognizer.isExpectedToken(la)) {
return
}
switch (s.stateType) {
case atn.ATNStateBLOCK_START:
case atn.ATNStateSTAR_BLOCK_START:
case atn.ATNStatePLUS_BLOCK_START:
case atn.ATNStateSTAR_LOOP_ENTRY:
// report error and recover if possible
if( this.singleTokenDeletion(recognizer) != nil) {
return
} else {
panic NewInputMismatchException(recognizer)
}
break
case atn.ATNStatePLUS_LOOP_BACK:
case atn.ATNStateSTAR_LOOP_BACK:
this.reportUnwantedToken(recognizer)
var expecting = antlr4.NewIntervalSet()
expecting.addSet(recognizer.getExpectedTokens())
var whatFollowsLoopIterationOrRule = expecting.addSet(this.getErrorRecoverySet(recognizer))
this.consumeUntil(recognizer, whatFollowsLoopIterationOrRule)
break
default:
// do nothing if we can't identify the exact kind of ATN state
switch (s.stateType *RecognitionException) {
case atn.ATNStateBLOCK_START:
case atn.ATNStateSTAR_BLOCK_START:
case atn.ATNStatePLUS_BLOCK_START:
case atn.ATNStateSTAR_LOOP_ENTRY:
// report error and recover if possible
if( this.singleTokenDeletion(recognizer) != nil) {
return
} else {
panic(NewInputMismatchException(recognizer))
}
break
case atn.ATNStatePLUS_LOOP_BACK:
case atn.ATNStateSTAR_LOOP_BACK:
this.reportUnwantedToken(recognizer)
var expecting = antlr4.NewIntervalSet()
expecting.addSet(recognizer.getExpectedTokens())
var whatFollowsLoopIterationOrRule = expecting.addSet(this.getErrorRecoverySet(recognizer))
this.consumeUntil(recognizer, whatFollowsLoopIterationOrRule)
break
default:
// do nothing if we can't identify the exact kind of ATN state
}
}
@ -272,11 +266,11 @@ func (this *DefaultErrorStrategy) sync(recognizer *antlr4.Recognizer) {
// @param recognizer the parser instance
// @param e the recognition exception
//
func (this *DefaultErrorStrategy) reportNoViableAlternative(recognizer, e) {
func (this *DefaultErrorStrategy) reportNoViableAlternative(recognizer *antlr4.Parser, e *RecognitionException) {
var tokens = recognizer.getTokenStream()
var input
if(tokens != nil) {
if (e.startToken.type==TokenEOF) {
if (e.startToken.tokenType==antlr4.TokenEOF) {
input = "<EOF>"
} else {
input = tokens.getText(NewInterval(e.startToken, e.offendingToken))
@ -297,7 +291,7 @@ func (this *DefaultErrorStrategy) reportNoViableAlternative(recognizer, e) {
// @param recognizer the parser instance
// @param e the recognition exception
//
func (this *DefaultErrorStrategy) reportInputMismatch(recognizer, e) {
func (this *DefaultErrorStrategy) reportInputMismatch(recognizer *antlr4.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)
@ -312,7 +306,7 @@ func (this *DefaultErrorStrategy) reportInputMismatch(recognizer, e) {
// @param recognizer the parser instance
// @param e the recognition exception
//
func (this *DefaultErrorStrategy) reportFailedPredicate(recognizer, e) {
func (this *DefaultErrorStrategy) reportFailedPredicate(recognizer *antlr4.Parser, e *RecognitionException) {
var ruleName = recognizer.ruleNames[recognizer._ctx.ruleIndex]
var msg = "rule " + ruleName + " " + e.message
recognizer.notifyErrorListeners(msg, e.offendingToken, e)
@ -335,7 +329,7 @@ func (this *DefaultErrorStrategy) reportFailedPredicate(recognizer, e) {
//
// @param recognizer the parser instance
//
func (this *DefaultErrorStrategy) reportUnwantedToken(recognizer *antlr4.Recognizer) {
func (this *DefaultErrorStrategy) reportUnwantedToken(recognizer *antlr4.Parser) {
if (this.inErrorRecoveryMode(recognizer)) {
return
}
@ -363,7 +357,7 @@ func (this *DefaultErrorStrategy) reportUnwantedToken(recognizer *antlr4.Recogni
//
// @param recognizer the parser instance
//
func (this *DefaultErrorStrategy) reportMissingToken(recognizer *antlr4.Recognizer) {
func (this *DefaultErrorStrategy) reportMissingToken(recognizer *antlr4.Parser) {
if ( this.inErrorRecoveryMode(recognizer)) {
return
}
@ -424,7 +418,7 @@ func (this *DefaultErrorStrategy) reportMissingToken(recognizer *antlr4.Recogniz
// 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.Recognizer) {
func (this *DefaultErrorStrategy) recoverInline(recognizer *antlr4.Parser) {
// SINGLE TOKEN DELETION
var matchedSymbol = this.singleTokenDeletion(recognizer)
if (matchedSymbol != nil) {
@ -438,7 +432,7 @@ func (this *DefaultErrorStrategy) recoverInline(recognizer *antlr4.Recognizer) {
return this.getMissingSymbol(recognizer)
}
// even that didn't work must panic the exception
panic NewInputMismatchException(recognizer)
panic(NewInputMismatchException(recognizer))
}
//
@ -458,7 +452,7 @@ func (this *DefaultErrorStrategy) recoverInline(recognizer *antlr4.Recognizer) {
// @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.Recognizer) {
func (this *DefaultErrorStrategy) singleTokenInsertion(recognizer *antlr4.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
@ -493,7 +487,7 @@ func (this *DefaultErrorStrategy) singleTokenInsertion(recognizer *antlr4.Recogn
// deletion successfully recovers from the mismatched input, otherwise
// {@code nil}
//
func (this *DefaultErrorStrategy) singleTokenDeletion(recognizer *antlr4.Recognizer) {
func (this *DefaultErrorStrategy) singleTokenDeletion(recognizer *antlr4.Parser) {
var nextTokenType = recognizer.getTokenStream().LA(2)
var expecting = this.getExpectedTokens(recognizer)
if (expecting.contains(nextTokenType)) {
@ -531,27 +525,25 @@ func (this *DefaultErrorStrategy) singleTokenDeletion(recognizer *antlr4.Recogni
// 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.Recognizer) {
func (this *DefaultErrorStrategy) getMissingSymbol(recognizer *antlr4.Parser) {
var currentSymbol = recognizer.getCurrentToken()
var expecting = this.getExpectedTokens(recognizer)
var expectedTokenType = expecting.first() // get any element
var tokenText
if (expectedTokenType==TokenEOF) {
if (expectedTokenType==antlr4.TokenEOF) {
tokenText = "<missing EOF>"
} else {
tokenText = "<missing " + recognizer.literalNames[expectedTokenType] + ">"
}
var current = currentSymbol
var lookback = recognizer.getTokenStream().LT(-1)
if (current.type==TokenEOF && lookback != nil) {
if (current.tokenType==antlr4.TokenEOF && lookback != nil) {
current = lookback
}
return recognizer.getTokenFactory().create(current.source,
expectedTokenType, tokenText, TokenDefaultChannel,
-1, -1, current.line, current.column)
return recognizer.getTokenFactory().create(current.source, expectedTokenType, tokenText, TokenDefaultChannel, -1, -1, current.line, current.column)
}
func (this *DefaultErrorStrategy) getExpectedTokens(recognizer *antlr4.Recognizer) {
func (this *DefaultErrorStrategy) getExpectedTokens(recognizer *antlr4.Parser) {
return recognizer.getExpectedTokens()
}
@ -563,25 +555,25 @@ func (this *DefaultErrorStrategy) getExpectedTokens(recognizer *antlr4.Recognize
// 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) {
func (this *DefaultErrorStrategy) getTokenErrorDisplay(t *antlr4.Token) string {
if (t == nil) {
return "<no token>"
}
var s = t.text
if (s == nil) {
if (t.type==TokenEOF) {
if (t.tokenType==antlr4.TokenEOF) {
s = "<EOF>"
} else {
s = "<" + t.type + ">"
s = "<" + t.tokenType + ">"
}
}
return this.escapeWSAndQuote(s)
}
func (this *DefaultErrorStrategy) escapeWSAndQuote(s) {
s = s.replace(/\n/g,"\\n")
s = s.replace(/\r/g,"\\r")
s = s.replace(/\t/g,"\\t")
func (this *DefaultErrorStrategy) escapeWSAndQuote(s string) string {
s = strings.Replace(s,"\t","\\t", -1)
s = strings.Replace(s,"\n","\\n", -1)
s = strings.Replace(s,"\r","\\r", -1)
return "'" + s + "'"
}
@ -677,10 +669,10 @@ func (this *DefaultErrorStrategy) escapeWSAndQuote(s) {
// 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.Recognizer) {
func (this *DefaultErrorStrategy) getErrorRecoverySet(recognizer *antlr4.Parser) *antlr4.IntervalSet {
var atn = recognizer._interp.atn
var ctx = recognizer._ctx
var recoverSet = NewIntervalSet()
var recoverSet = antlr4.NewIntervalSet()
for (ctx != nil && ctx.invokingState>=0) {
// compute what follows who invoked us
var invokingState = atn.states[ctx.invokingState]
@ -694,9 +686,9 @@ func (this *DefaultErrorStrategy) getErrorRecoverySet(recognizer *antlr4.Recogni
}
// Consume tokens until one matches the given token set.//
func (this *DefaultErrorStrategy) consumeUntil(recognizer, set) {
func (this *DefaultErrorStrategy) consumeUntil(recognizer *antlr4.Parser, set) {
var ttype = recognizer.getTokenStream().LA(1)
while( ttype != TokenEOF && !set.contains(ttype)) {
for( ttype != antlr4.antlr4.TokenEOF && !set.contains(ttype)) {
recognizer.consume()
ttype = recognizer.getTokenStream().LA(1)
}
@ -743,24 +735,24 @@ type BailErrorStrategy struct {
// rule func catches. Use {@link Exception//getCause()} to get the
// original {@link RecognitionException}.
//
func (this *BailErrorStrategy) recover(recognizer, e) {
func (this *BailErrorStrategy) recover(recognizer *antlr4.Parser, e *RecognitionException) {
var context = recognizer._ctx
for (context != nil) {
context.exception = e
context = context.parentCtx
}
panic NewParseCancellationException(e)
panic(NewParseCancellationException(e))
}
// 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.Recognizer) {
func (this *BailErrorStrategy) recoverInline(recognizer *antlr4.Parser) {
this.recover(recognizer, NewInputMismatchException(recognizer))
}
// Make sure we don't attempt to recover from problems in subrules.//
func (this *BailErrorStrategy) sync(recognizer *antlr4.Recognizer) {
func (this *BailErrorStrategy) sync(recognizer *antlr4.Parser) {
// pass
}

View File

@ -1,5 +1,8 @@
package error
import "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