-
Notifications
You must be signed in to change notification settings - Fork 0
/
grammar.go
85 lines (63 loc) · 2.03 KB
/
grammar.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package main
import (
"fmt"
"github.com/antlr4-go/antlr/v4"
"github.com/pkg/errors"
"os"
bindings "github.com/distributed-lab/circom-g4-grammar/parser"
)
type simpleErrorListener struct {
*antlr.DefaultErrorListener
errors []string
}
func (l *simpleErrorListener) SyntaxError(_ antlr.Recognizer, _ interface{},
line, column int, msg string, _ antlr.RecognitionException) {
errorMsg := fmt.Sprintf("line %d:%d %s", line, column, msg)
l.errors = append(l.errors, errorMsg)
}
func (l *simpleErrorListener) hasErrors() bool {
return len(l.errors) > 0
}
func (l *simpleErrorListener) getErrors() []string {
return l.errors
}
func GetParser(input antlr.CharStream) *bindings.CircomParser {
lexer := bindings.NewCircomLexer(input)
stream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)
return bindings.NewCircomParser(stream)
}
// ParseFile parses a single file and returns an error if parsing fails
func ParseFile(filename string) error {
// Open the file for reading
file, err := os.Open(filename)
if err != nil {
fmt.Println("Error opening file:", err)
return errors.Wrap(err, "error opening file")
}
defer func() {
if err := file.Close(); err != nil {
fmt.Println("Error closing file:", err)
}
}()
ioStream := antlr.NewIoStream(file)
parser := GetParser(ioStream)
parser.RemoveErrorListeners()
parser.BuildParseTrees = true
errorListener := &simpleErrorListener{}
parser.AddErrorListener(errorListener)
parser.GetInterpreter().SetPredictionMode(antlr.PredictionModeSLL)
tree := parser.Circuit()
if errorListener.hasErrors() {
fmt.Printf("Failed to parse (with weak stratagy) %s: %v\n", filename, errorListener.getErrors())
parser.GetInterpreter().SetPredictionMode(antlr.PredictionModeLL)
parser.RemoveErrorListeners()
parser.BuildParseTrees = true
errorListener := &simpleErrorListener{}
parser.AddErrorListener(errorListener)
if errorListener.hasErrors() {
return fmt.Errorf("syntax errors encountered in file %s", filename)
}
}
_ = tree // use the parse tree as needed
return nil
}