antlr / antlr4

ANTLR (ANother Tool for Language Recognition) is a powerful parser generator for reading, processing, executing, or translating structured text or binary files.
http://antlr.org
BSD 3-Clause "New" or "Revised" License
17.11k stars 3.28k forks source link

Go Target:how Exit when Error occurred #2158

Open wxd237 opened 6 years ago

wxd237 commented 6 years ago

I have search antlr4-discussion google group and stackoverflow ,this is no way to solve this.

  1. I use the example JSON.g4.
  2. execute antlr4 antlr4 -Dlanguage=Go -o parser JSON.g4
  3. the main.go
    
    package main

import ( "github.com/antlr/antlr4/runtime/Go/antlr" "./parser" "fmt" )

type TreeShapeListener struct { *parser.BaseJSONListener }

func NewTreeShapeListener() *TreeShapeListener { return new(TreeShapeListener) }

func (this *TreeShapeListener) EnterEveryRule(ctx antlr.ParserRuleContext) { fmt.Println(ctx.GetText()) }

func main() { str:={"a":1}! input := new(antlr.FileStream) input.InputStream = antlr.NewInputStream(str) lexer := parser.NewJSONLexer(input) stream := antlr.NewCommonTokenStream(lexer,0) p := parser.NewJSONParser(stream) p.AddErrorListener(antlr.NewDiagnosticErrorListener(true)) p.BuildParseTrees = true tree := p.Json() antlr.ParseTreeWalkerDefault.Walk(NewTreeShapeListener(), tree) }

4. 
`go run main.go`
I want the the error message and hope exit when error  occurred  this is the output:

root@iZj6ca7mzaes6eiy2p6fnsZ:~/grammars-v4/json# go run main.go line 1:7 token recognition error at: '!' {"a":1} {"a":1} {"a":1} "a":1 1

dannypsnl commented 6 years ago

Can you provide error message? What did you meet In your code had some problems, I don't know you knew or not.

behdadforghani commented 5 years ago

Here is how I handle errors in my project: First, I define an error listener and count the number of errors. Later on I check i the number of errors is more than one.

type CqlErrorListener struct { errors int }

func (l *CqlErrorListener) SyntaxError(recognizer antlr.Recognizer, offendingSymbol interface{}, line, column int, msg string, e antlr.RecognitionException) { l.errors += 1 }

func (l CqlErrorListener) ReportAmbiguity(recognizer antlr.Parser, dfa antlr.DFA, startIndex, stopIndex int, exact bool, ambigAlts antlr.BitSet, configs antlr.ATNConfigSet) { l.errors += 1 } func (l CqlErrorListener) ReportAttemptingFullContext(recognizer antlr.Parser, dfa antlr.DFA, startIndex, stopIndex int, conflictingAlts antlr.BitSet, configs antlr.ATNConfigSet) { l.errors += 1 } func (l CqlErrorListener) ReportContextSensitivity(recognizer antlr.Parser, dfa antlr.DFA, startIndex, stopIndex, prediction int, configs antlr.ATNConfigSet) { l.errors += 1 }

Later on in main code I have: p.AddErrorListener(errorListener) lexer.AddErrorListener(errorListener) if errorListener.errors > 0 { panic("Found errors in input") }