forked from cugu/gocap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgo.cap.go
70 lines (58 loc) · 1.44 KB
/
go.cap.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
package main
import (
"errors"
"fmt"
"io"
"io/fs"
"os"
"github.com/alecthomas/participle/v2"
"github.com/alecthomas/participle/v2/lexer"
)
type File struct {
Self Line `parser:"@@"`
External []Line `parser:"@@*"`
expected map[string][]string
}
func (f *File) setup() {
expected := map[string][]string{
f.Self.Package: f.Self.Capabilities,
}
for _, ext := range f.External {
expected[ext.Package] = ext.Capabilities
}
f.expected = expected
}
type Line struct {
Package string `parser:"@String"`
Capabilities []string `parser:" '(' ((@String ',' )* @String)? ')'"`
}
var parser = participle.MustBuild(&File{},
participle.Lexer(lexer.MustSimple([]lexer.Rule{
{Name: "Comment", Pattern: `(?:#|//)[^\n]*\n?`},
{Name: "String", Pattern: `[^\s,()]+`},
{Name: "Punct", Pattern: `[,()]`},
{Name: "Whitespace", Pattern: `[ \t\n\r]+`},
})),
participle.Elide("Comment", "Whitespace"),
participle.UseLookahead(2),
)
func parseGoCap(path string) (*File, error) {
r, err := os.Open("go.cap")
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return nil, fmt.Errorf("go.cap file does not exist, consider run `gocap generate %s> go.cap` command", path)
}
return nil, fmt.Errorf("could not open go.cap file: %s", err)
}
defer r.Close()
return parse(r)
}
func parse(r io.Reader) (*File, error) {
ast := &File{}
err := parser.Parse("", r, ast)
if err != nil {
return nil, err
}
ast.setup()
return ast, err
}