Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Fix gocognit output when a function has generic receiver type
recvString func in gocognit returns BADRECV when the function's receiver is a generic type. Implement recvString in two variants in order to keep the code compatible with go versions less than 1.18
- Loading branch information
Showing
3 changed files
with
50 additions
and
12 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
//go:build go1.18 | ||
// +build go1.18 | ||
|
||
package gocognit | ||
|
||
import ( | ||
"go/ast" | ||
"strings" | ||
) | ||
|
||
// recvString returns a string representation of recv of the | ||
// form "T", "*T", Type[T], Type[T, V], or "BADRECV" (if not a proper receiver type). | ||
func recvString(recv ast.Expr) string { | ||
switch t := recv.(type) { | ||
case *ast.Ident: | ||
return t.Name | ||
case *ast.StarExpr: | ||
return "*" + recvString(t.X) | ||
case *ast.IndexExpr: | ||
return recvString(t.X) + "[" + recvString(t.Index) + "]" | ||
case *ast.IndexListExpr: | ||
targs := make([]string, len(t.Indices)) | ||
for i, exp := range t.Indices { | ||
targs[i] = recvString(exp) | ||
} | ||
|
||
return recvString(t.X) + "[" + strings.Join(targs, ", ") + "]" | ||
} | ||
return "BADRECV" | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
//go:build !go1.18 | ||
// +build !go1.18 | ||
|
||
package gocognit | ||
|
||
import ( | ||
"go/ast" | ||
) | ||
|
||
// recvString returns a string representation of recv of the | ||
// form "T", "*T", or "BADRECV" (if not a proper receiver type). | ||
func recvString(recv ast.Expr) string { | ||
switch t := recv.(type) { | ||
case *ast.Ident: | ||
return t.Name | ||
case *ast.StarExpr: | ||
return "*" + recvString(t.X) | ||
} | ||
return "BADRECV" | ||
} |