Skip to content

Commit

Permalink
add one naive lint
Browse files Browse the repository at this point in the history
  • Loading branch information
alingse committed Jul 4, 2022
1 parent bcff8ec commit c30f63c
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 11 deletions.
52 changes: 41 additions & 11 deletions asasalint.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package asasalint
import (
"fmt"
"go/ast"
"go/token"
"go/types"

"golang.org/x/tools/go/analysis"
Expand Down Expand Up @@ -40,22 +41,51 @@ func (s *Searcher) CheckAndReport(n ast.Node, push bool, stack []ast.Node) bool
if !ok {
return true
}
if caller.Ellipsis != token.NoPos {
return true
}

fn := s.Pass.TypesInfo.TypeOf(caller.Fun)
fnSign := fn.(*types.Signature)
if !fnSign.Variadic() {
fnType := s.Pass.TypesInfo.TypeOf(caller.Fun)
if !isSliceAnyVariadicFuncType(fnType) {
return true
}

params := fnSign.Params()
param := params.At(params.Len() - 1)
varParamType := param.Type().(*types.Slice)
paramType, ok := varParamType.Elem().(*types.Interface)
if !ok || paramType.NumMethods() != 0 {
lastArg := caller.Args[len(caller.Args)-1]
argType := s.Pass.TypesInfo.TypeOf(lastArg)
if !isSliceAnyType(argType) {
return true
}
// assert the last param is []any
fmt.Printf("paramType %#v\n", paramType)
fmt.Println("param", param)
node := lastArg
// report a diagnostic
d := analysis.Diagnostic{
Pos: node.Pos(),
End: node.End(),
Message: fmt.Sprintf("pass []any as any to %s", fnType.String()),
Category: "asasalint",
}
s.Pass.Report(d)
return false
}

func isSliceAnyVariadicFuncType(typ types.Type) (r bool) {
fnSign, ok := typ.(*types.Signature)
if !ok || !fnSign.Variadic() {
return false
}

params := fnSign.Params()
lastParam := params.At(params.Len() - 1)
return isSliceAnyType(lastParam.Type())
}

func isSliceAnyType(typ types.Type) (r bool) {
sliceType, ok := typ.(*types.Slice)
if !ok {
return
}
elemType, ok := sliceType.Elem().(*types.Interface)
if !ok {
return
}
return elemType.NumMethods() == 0
}
3 changes: 3 additions & 0 deletions testdata/src/simple/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,7 @@ func main() {
var a = []any{1, 2, 3}
getArgsLength(a)
getArgsLength(a...)
getArgsLength(1, 2, 3)
getArgsLength([]any{1, 2, 3})
getArgsLength(append([]any{1, 2, 3}, 4, 5, 6))
}

0 comments on commit c30f63c

Please sign in to comment.