Skip to content

Commit 880a503

Browse files
committed
staticcheck/fakejson: don't complain about maps with generic keys
Updates gh-1256 (cherry picked from commit 311d97b)
1 parent 90804df commit 880a503

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

staticcheck/fakejson/encode.go

+9
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import (
1717
"strings"
1818
"unicode"
1919

20+
"golang.org/x/exp/typeparams"
2021
"honnef.co/go/tools/staticcheck/fakereflect"
2122
)
2223

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

108109
func (enc *encoder) newMapEncoder(t fakereflect.TypeAndCanAddr, stack string) *UnsupportedTypeError {
110+
if typeparams.IsTypeParam(t.Key().Type) {
111+
// We don't know enough about the concrete instantiation to say much about the key. The only time we could make
112+
// a definite "this key is bad" statement is if the type parameter is constrained by type terms, none of which
113+
// are tilde terms, none of which are a basic type. In all other cases, the key might implement TextMarshaler.
114+
// It doesn't seem worth checking for that one single case.
115+
return enc.newTypeEncoder(t.Elem(), stack+"[k]")
116+
}
117+
109118
switch t.Key().Type.Underlying().(type) {
110119
case *types.Basic:
111120
default:
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
//go:build go1.18
2+
3+
package pkg
4+
5+
import "encoding/json"
6+
7+
type LMap[K comparable, V any] struct {
8+
M1 map[K]V
9+
M2 map[K]chan int
10+
}
11+
12+
func (lm *LMap[K, V]) MarshalJSON() {
13+
json.Marshal(lm.M1)
14+
json.Marshal(lm.M2) // want `unsupported type`
15+
}

0 commit comments

Comments
 (0)