Skip to content

Commit

Permalink
staticcheck/fakejson: don't complain about maps with generic keys
Browse files Browse the repository at this point in the history
Updates gh-1256

(cherry picked from commit 311d97b)
  • Loading branch information
dominikh committed Apr 24, 2022
1 parent 90804df commit 880a503
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
9 changes: 9 additions & 0 deletions staticcheck/fakejson/encode.go
Expand Up @@ -17,6 +17,7 @@ import (
"strings"
"unicode"

"golang.org/x/exp/typeparams"
"honnef.co/go/tools/staticcheck/fakereflect"
)

Expand Down Expand Up @@ -106,6 +107,14 @@ func (enc *encoder) newTypeEncoder(t fakereflect.TypeAndCanAddr, stack string) *
}

func (enc *encoder) newMapEncoder(t fakereflect.TypeAndCanAddr, stack string) *UnsupportedTypeError {
if typeparams.IsTypeParam(t.Key().Type) {
// We don't know enough about the concrete instantiation to say much about the key. The only time we could make
// a definite "this key is bad" statement is if the type parameter is constrained by type terms, none of which
// are tilde terms, none of which are a basic type. In all other cases, the key might implement TextMarshaler.
// It doesn't seem worth checking for that one single case.
return enc.newTypeEncoder(t.Elem(), stack+"[k]")
}

switch t.Key().Type.Underlying().(type) {
case *types.Basic:
default:
Expand Down
15 changes: 15 additions & 0 deletions staticcheck/testdata/src/CheckUnsupportedMarshal/generics.go
@@ -0,0 +1,15 @@
//go:build go1.18

package pkg

import "encoding/json"

type LMap[K comparable, V any] struct {
M1 map[K]V
M2 map[K]chan int
}

func (lm *LMap[K, V]) MarshalJSON() {
json.Marshal(lm.M1)
json.Marshal(lm.M2) // want `unsupported type`
}

0 comments on commit 880a503

Please sign in to comment.