Skip to content

Commit

Permalink
fix: Fix to report on struct (#1)
Browse files Browse the repository at this point in the history
* test: Fix testcase to report on struct

* fix: Fix to report on struct

* test: Add reference in testdata

* perf: Improve code by saving basic types instead of pointers

* chore: Fix typo
  • Loading branch information
raeperd authored Sep 13, 2024
1 parent e778957 commit 0e08ef2
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 11 deletions.
17 changes: 8 additions & 9 deletions analyzer.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,29 +42,28 @@ func run(pass *analysis.Pass) (any, error) {
var st *structType
st, ok = structs[recv.Name]
if !ok {
structs[recv.Name] = &structType{starMethods: []*ast.FuncDecl{}, typeMethods: []*ast.FuncDecl{}}
structs[recv.Name] = &structType{recv: recv.Name}
st = structs[recv.Name]
}

if isStar {
st.starMethods = append(st.starMethods, funcDecl)
st.numStarMethod++
} else {
st.typeMethods = append(st.typeMethods, funcDecl)
st.numTypeMethod++
}
})

for _, st := range structs {
if len(st.starMethods) > 0 && len(st.typeMethods) > 0 {
for _, typeMethod := range st.typeMethods {
pass.Reportf(typeMethod.Pos(), "receiver type should be a pointer")
}
if st.numStarMethod > 0 && st.numTypeMethod > 0 {
pass.Reportf(pass.Pkg.Scope().Lookup(st.recv).Pos(), "the methods of %q use pointer receiver and non-pointer receiver.", st.recv)
}
}

return nil, nil
}

type structType struct {
starMethods []*ast.FuncDecl
typeMethods []*ast.FuncDecl
recv string
numStarMethod int
numTypeMethod int
}
17 changes: 15 additions & 2 deletions testdata/src/test/rpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"time"
)

type RPC struct {
type RPC struct { // want `the methods of "RPC" use pointer receiver and non-pointer receiver.`
result int
done chan struct{}
}
Expand All @@ -15,6 +15,19 @@ func (rpc *RPC) compute() {
close(rpc.done)
}

func (RPC) version() int { // want "receiver type should be a pointer"
func (RPC) version() int {
return 1 // never going to need to change this
}

// Following main function cause data race error
// reference: https://dave.cheney.net/2015/11/18/wednesday-pop-quiz-spot-the-race
// func main() {
// rpc := &RPC{done: make(chan struct{})}
//
// go rpc.compute() // kick off computation in the background
// version := rpc.version() // grab some other information while we're waiting
// <-rpc.done // wait for computation to finish
// result := rpc.result
//
// fmt.Printf("RPC computation complete, result: %d, version: %d\n", result, version)
// }

0 comments on commit 0e08ef2

Please sign in to comment.