forked from go-critic/go-critic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
embedded_rules.go
103 lines (90 loc) · 2.65 KB
/
embedded_rules.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package checkers
import (
"fmt"
"go/ast"
"go/build"
"go/token"
"os"
"github.com/go-critic/go-critic/checkers/rulesdata"
"github.com/go-critic/go-critic/framework/linter"
"github.com/quasilyte/go-ruleguard/ruleguard"
)
//go:generate go run ./rules/precompile.go -rules ./rules/rules.go -o ./rulesdata/rulesdata.go
func init() {
filename := "rules/rules.go"
fset := token.NewFileSet()
var groups []ruleguard.GoRuleGroup
var buildContext *build.Context
ruleguardDebug := os.Getenv("GOCRITIC_RULEGUARD_DEBUG") != ""
// First we create an Engine to parse all rules.
// We need it to get the structured info about our rules
// that will be used to generate checkers.
// We introduce an extra scope in hope that rootEngine
// will be garbage-collected after we don't need it.
// LoadedGroups() returns a slice copy and that's all what we need.
{
rootEngine := ruleguard.NewEngine()
rootEngine.InferBuildContext()
buildContext = rootEngine.BuildContext
loadContext := &ruleguard.LoadContext{
Fset: fset,
DebugImports: ruleguardDebug,
DebugPrint: func(s string) {
fmt.Println("debug:", s)
},
}
if err := rootEngine.LoadFromIR(loadContext, filename, rulesdata.PrecompiledRules); err != nil {
panic(fmt.Sprintf("load embedded ruleguard rules: %v", err))
}
groups = rootEngine.LoadedGroups()
}
// For every rules group we create a new checker and a separate engine.
// That dedicated ruleguard engine will contain rules only from one group.
for i := range groups {
g := groups[i]
info := &linter.CheckerInfo{
Name: g.Name,
Summary: g.DocSummary,
Before: g.DocBefore,
After: g.DocAfter,
Note: g.DocNote,
Tags: g.DocTags,
EmbeddedRuleguard: true,
}
collection.AddChecker(info, func(ctx *linter.CheckerContext) (linter.FileWalker, error) {
parseContext := &ruleguard.LoadContext{
Fset: fset,
GroupFilter: func(name string) bool {
return name == g.Name
},
DebugImports: ruleguardDebug,
DebugPrint: func(s string) {
fmt.Println("debug:", s)
},
}
engine := ruleguard.NewEngine()
engine.BuildContext = buildContext
err := engine.LoadFromIR(parseContext, filename, rulesdata.PrecompiledRules)
if err != nil {
return nil, err
}
c := &embeddedRuleguardChecker{
ctx: ctx,
engine: engine,
}
return c, nil
})
}
}
type embeddedRuleguardChecker struct {
ctx *linter.CheckerContext
engine *ruleguard.Engine
}
func (c *embeddedRuleguardChecker) WalkFile(f *ast.File) {
runRuleguardEngine(c.ctx, f, c.engine, &ruleguard.RunContext{
Pkg: c.ctx.Pkg,
Types: c.ctx.TypesInfo,
Sizes: c.ctx.SizesInfo,
Fset: c.ctx.FileSet,
})
}