From 913131bf627e9df0a87b1dc6699779faaf70ca5d Mon Sep 17 00:00:00 2001 From: Ayke van Laethem Date: Wed, 6 Nov 2019 14:52:35 +0100 Subject: [PATCH] cgo: avoid '"unsafe" imported but not used' error This can happen when not all CGo features are used. --- cgo/cgo.go | 27 +++++++++++++++++++++++++++ cgo/testdata/basic.out.go | 2 ++ cgo/testdata/types.out.go | 2 ++ 3 files changed, 31 insertions(+) diff --git a/cgo/cgo.go b/cgo/cgo.go index 22666499..e11b15ce 100644 --- a/cgo/cgo.go +++ b/cgo/cgo.go @@ -185,6 +185,7 @@ func Process(files []*ast.File, dir string, fset *token.FileSet, cflags []string Name: files[0].Name.Name, }, Decls: []ast.Decl{ + // import "unsafe" &ast.GenDecl{ TokPos: p.generatedPos, Tok: token.IMPORT, @@ -192,6 +193,32 @@ func Process(files []*ast.File, dir string, fset *token.FileSet, cflags []string unsafeImport, }, }, + // var _ unsafe.Pointer + // This avoids type errors when the unsafe package is never used. + &ast.GenDecl{ + Tok: token.VAR, + Specs: []ast.Spec{ + &ast.ValueSpec{ + Names: []*ast.Ident{ + &ast.Ident{ + Name: "_", + Obj: &ast.Object{ + Kind: ast.Var, + Name: "_", + }, + }, + }, + Type: &ast.SelectorExpr{ + X: &ast.Ident{ + Name: "unsafe", + }, + Sel: &ast.Ident{ + Name: "Pointer", + }, + }, + }, + }, + }, }, Imports: []*ast.ImportSpec{unsafeImport}, } diff --git a/cgo/testdata/basic.out.go b/cgo/testdata/basic.out.go index 26126a16..1fb2c4d1 100644 --- a/cgo/testdata/basic.out.go +++ b/cgo/testdata/basic.out.go @@ -2,6 +2,8 @@ package main import "unsafe" +var _ unsafe.Pointer + type C.int16_t = int16 type C.int32_t = int32 type C.int64_t = int64 diff --git a/cgo/testdata/types.out.go b/cgo/testdata/types.out.go index 939c1a5a..bdc2e57f 100644 --- a/cgo/testdata/types.out.go +++ b/cgo/testdata/types.out.go @@ -2,6 +2,8 @@ package main import "unsafe" +var _ unsafe.Pointer + const C.option2A = 20 const C.optionA = 0 const C.optionB = 1