Skip to content

Commit

Permalink
improve error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
lmbsog0 committed Jun 30, 2023
1 parent 2b61f43 commit f9cd7b4
Showing 1 changed file with 23 additions and 23 deletions.
46 changes: 23 additions & 23 deletions cmd/a2l/a2l.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,36 +9,41 @@ import (
"github.com/sauci/a2l-grpc/pkg/a2l/parser"
"google.golang.org/grpc"
"google.golang.org/protobuf/encoding/protojson"
"io"
"net"
"os"
"strings"
"sync"
)

type CustomSyntaxError struct {
type A2LSyntaxError struct {
line, column int
msg string
}

type CustomErrorListener struct {
func (e A2LSyntaxError) String() string {
return fmt.Sprintf("%v:%v %v", e.line, e.column, e.msg)
}

type A2LErrorListener struct {
*antlr.DefaultErrorListener // Embed default which ensures we fit the interface
Errors []CustomSyntaxError
Errors []A2LSyntaxError
}

func (c *CustomErrorListener) SyntaxError(recognizer antlr.Recognizer, offendingSymbol interface{}, line, column int, msg string, e antlr.RecognitionException) {
c.Errors = append(c.Errors, CustomSyntaxError{
line: line,
column: column,
msg: msg,
})
func (l *A2LErrorListener) GetErrors() (result []string) {
result = make([]string, 0)

for _, e := range l.Errors {
result = append(result, e.String())
}

return result
}

func getTreeFromString(a2lString string) (result *a2l.RootNodeType, err error) {
stdErr := os.Stderr
r, w, _ := os.Pipe()
os.Stderr = w
func (l *A2LErrorListener) SyntaxError(_ antlr.Recognizer, _ interface{}, line, column int, msg string, _ antlr.RecognitionException) {
l.Errors = append(l.Errors, A2LSyntaxError{line: line, column: column, msg: msg})
}

errorListener := CustomErrorListener{Errors: make([]CustomSyntaxError, 0)}
func getTreeFromString(a2lString string) (result *a2l.RootNodeType, err error) {
errorListener := A2LErrorListener{Errors: make([]A2LSyntaxError, 0)}
lexer := parser.NewA2LLexer(antlr.NewInputStream(a2lString))
lexer.RemoveErrorListeners()
lexer.AddErrorListener(&errorListener)
Expand All @@ -52,13 +57,8 @@ func getTreeFromString(a2lString string) (result *a2l.RootNodeType, err error) {

antlr.ParseTreeWalkerDefault.Walk(listener, p.A2lFile())

_ = w.Close()
out, _ := io.ReadAll(r)

os.Stderr = stdErr

if len(out) != 0 {
err = fmt.Errorf("%s", string(out))
if len(errorListener.Errors) != 0 {
err = fmt.Errorf(strings.Join(errorListener.GetErrors(), "\n"))
}

return listener.Tree(), err
Expand Down

0 comments on commit f9cd7b4

Please sign in to comment.