|
| 1 | +package analyzer |
| 2 | + |
| 3 | +import ( |
| 4 | + "flag" |
| 5 | + "go/ast" |
| 6 | + "go/token" |
| 7 | + |
| 8 | + "golang.org/x/tools/go/analysis" |
| 9 | + "golang.org/x/tools/go/analysis/passes/inspect" |
| 10 | + "golang.org/x/tools/go/ast/inspector" |
| 11 | +) |
| 12 | + |
| 13 | +const InterfaceLenFlag = "interface-len" |
| 14 | + |
| 15 | +const defaultInterfaceLen = 10 |
| 16 | + |
| 17 | +// New returns new interfacebloat analyzer. |
| 18 | +func New() *analysis.Analyzer { |
| 19 | + return &analysis.Analyzer{ |
| 20 | + Name: "interfacebloat", |
| 21 | + Doc: "A linter that checks length of interface.", |
| 22 | + Run: run, |
| 23 | + Flags: flags(), |
| 24 | + Requires: []*analysis.Analyzer{inspect.Analyzer}, |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +func flags() flag.FlagSet { |
| 29 | + flags := flag.NewFlagSet("", flag.ExitOnError) |
| 30 | + flags.Int(InterfaceLenFlag, 10, "length of interface") |
| 31 | + return *flags |
| 32 | +} |
| 33 | + |
| 34 | +func run(pass *analysis.Pass) (interface{}, error) { |
| 35 | + insp := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) |
| 36 | + |
| 37 | + filter := []ast.Node{ |
| 38 | + (*ast.InterfaceType)(nil), |
| 39 | + } |
| 40 | + |
| 41 | + insp.Preorder(filter, func(node ast.Node) { |
| 42 | + i, ok := node.(*ast.InterfaceType) |
| 43 | + if !ok { |
| 44 | + return |
| 45 | + } |
| 46 | + interfaceLen := interfaceLen(pass, InterfaceLenFlag) |
| 47 | + if len(i.Methods.List) > interfaceLen { |
| 48 | + report(pass, node.Pos(), interfaceLen) |
| 49 | + } |
| 50 | + }) |
| 51 | + |
| 52 | + return nil, nil |
| 53 | +} |
| 54 | + |
| 55 | +func interfaceLen(pass *analysis.Pass, name string) (interfaceLen int) { |
| 56 | + interfaceLen, ok := pass.Analyzer.Flags.Lookup(name).Value.(flag.Getter).Get().(int) |
| 57 | + if !ok { |
| 58 | + interfaceLen = defaultInterfaceLen |
| 59 | + } |
| 60 | + return |
| 61 | +} |
| 62 | + |
| 63 | +func report(pass *analysis.Pass, pos token.Pos, interfaceLen int) { |
| 64 | + pass.Reportf(pos, `length of interface greater than %d`, interfaceLen) |
| 65 | +} |
0 commit comments