From 43923818a821e9aa30ca556829e480ae6a1ae409 Mon Sep 17 00:00:00 2001 From: Robert Findley Date: Sat, 30 Oct 2021 21:23:07 -0400 Subject: [PATCH] go/analysis/passes/unsafeptr: add tests using generics Unlike with some other analyzers, it did not seem worthwhile to consider a type parameter's type set when looking for incorrect conversions to unsafe.Pointer. There's probably no reason to have a type parameter with uintptr structural type. Add some sanity-check tests for the behavior of this analyzer with respect to generic code. Updates golang/go#48704 Change-Id: Ibc3180c6eba9c2c88ea2220b1c84cd27971a6700 Reviewed-on: https://go-review.googlesource.com/c/tools/+/360174 Trust: Robert Findley Run-TryBot: Robert Findley gopls-CI: kokoro TryBot-Result: Go Bot Reviewed-by: Matthew Dempsky --- .../testdata/src/typeparams/typeparams.go | 21 +++++++++++++++++++ .../passes/unsafeptr/unsafeptr_test.go | 7 ++++++- 2 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 go/analysis/passes/unsafeptr/testdata/src/typeparams/typeparams.go diff --git a/go/analysis/passes/unsafeptr/testdata/src/typeparams/typeparams.go b/go/analysis/passes/unsafeptr/testdata/src/typeparams/typeparams.go new file mode 100644 index 00000000000..c1e6c2d54c6 --- /dev/null +++ b/go/analysis/passes/unsafeptr/testdata/src/typeparams/typeparams.go @@ -0,0 +1,21 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package typeparams + +import "unsafe" + +func _[IntPtr ~uintptr, RealPtr *T, AnyPtr uintptr | *T, T any]() { + var ( + i IntPtr + r RealPtr + a AnyPtr + ) + _ = unsafe.Pointer(i) // incorrect, but not detected + _ = unsafe.Pointer(i + i) // incorrect, but not detected + _ = unsafe.Pointer(1 + i) // incorrect, but not detected + _ = unsafe.Pointer(uintptr(i)) // want "possible misuse of unsafe.Pointer" + _ = unsafe.Pointer(r) + _ = unsafe.Pointer(a) // possibly incorrect, but not detected +} diff --git a/go/analysis/passes/unsafeptr/unsafeptr_test.go b/go/analysis/passes/unsafeptr/unsafeptr_test.go index 18e22c6c12a..424de1f04f5 100644 --- a/go/analysis/passes/unsafeptr/unsafeptr_test.go +++ b/go/analysis/passes/unsafeptr/unsafeptr_test.go @@ -9,9 +9,14 @@ import ( "golang.org/x/tools/go/analysis/analysistest" "golang.org/x/tools/go/analysis/passes/unsafeptr" + "golang.org/x/tools/internal/typeparams" ) func Test(t *testing.T) { testdata := analysistest.TestData() - analysistest.Run(t, testdata, unsafeptr.Analyzer, "a") + pkgs := []string{"a"} + if typeparams.Enabled { + pkgs = append(pkgs, "typeparams") + } + analysistest.Run(t, testdata, unsafeptr.Analyzer, pkgs...) }