Skip to content

Commit

Permalink
go/analysis/passes/unmarshal: allow unmarshalling to a type parameter
Browse files Browse the repository at this point in the history
We can also unmarshal data to a type parameter, in addition to a pointer
and an interface.

This analyzer probably requires more discussion, but this solution
should be sufficient for now.

Updates golang/go#48704

Change-Id: I333f919109295e80a04e59df131713553cdbe612
Reviewed-on: https://go-review.googlesource.com/c/tools/+/353210
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
Trust: Rebecca Stambler <rstambler@golang.org>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Robert Findley <rfindley@google.com>
gopls-CI: kokoro <noreply+kokoro@google.com>
  • Loading branch information
stamblerre committed Oct 4, 2021
1 parent 0ebff1a commit ccaa907
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
22 changes: 22 additions & 0 deletions go/analysis/passes/unmarshal/testdata/src/typeparams/typeparams.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package typeparams

import (
"encoding/json"
"fmt"
)

func unmarshalT[T any](data []byte) T {
var x T
json.Unmarshal(data, x)
return x
}

func unmarshalT2[T any](data []byte, t T) {
json.Unmarshal(data, t)
}

func main() {
x := make(map[string]interface{})
unmarshalT2([]byte(`{"a":1}`), &x)
fmt.Println(x)
}
3 changes: 2 additions & 1 deletion go/analysis/passes/unmarshal/unmarshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/inspector"
"golang.org/x/tools/go/types/typeutil"
"golang.org/x/tools/internal/typeparams"
)

const Doc = `report passing non-pointer or non-interface values to unmarshal
Expand Down Expand Up @@ -85,7 +86,7 @@ func run(pass *analysis.Pass) (interface{}, error) {

t := pass.TypesInfo.Types[call.Args[argidx]].Type
switch t.Underlying().(type) {
case *types.Pointer, *types.Interface:
case *types.Pointer, *types.Interface, *typeparams.TypeParam:
return
}

Expand Down
7 changes: 6 additions & 1 deletion go/analysis/passes/unmarshal/unmarshal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,14 @@ import (

"golang.org/x/tools/go/analysis/analysistest"
"golang.org/x/tools/go/analysis/passes/unmarshal"
"golang.org/x/tools/internal/typeparams"
)

func Test(t *testing.T) {
testdata := analysistest.TestData()
analysistest.Run(t, testdata, unmarshal.Analyzer, "a")
tests := []string{"a"}
if typeparams.Enabled {
tests = append(tests, "typeparams")
}
analysistest.Run(t, testdata, unmarshal.Analyzer, tests...)
}

0 comments on commit ccaa907

Please sign in to comment.