Browse Source

all: fix staticcheck warnings

This is a loose collection of small fixes flagged by staticcheck:

  - dead code
  - regexp expressions not using backticks (`foobar` / "foobar")
  - redundant types of slice and map initializers
  - misc other fixes

Not all of these seem very useful to me, but in particular dead code is
nice to fix. I've fixed them all just so that if there are problems,
they aren't hidden in the noise of less useful issues.
pull/2144/head
Ayke van Laethem 3 years ago
committed by Ron Evans
parent
commit
49dd2ce393
  1. 2
      builder/ar.go
  2. 4
      builder/uf2.go
  3. 58
      cgo/cgo.go
  4. 2
      cgo/cgo_test.go
  5. 10
      cgo/libclang.go
  6. 2
      compiler/asserts.go
  7. 4
      compiler/calls.go
  8. 12
      compiler/compiler.go
  9. 12
      compiler/errors.go
  10. 4
      compiler/inlineasm.go
  11. 15
      compiler/llvm.go

2
builder/ar.go

@ -27,7 +27,7 @@ func makeArchive(archivePath string, objs []string) error {
arwriter := ar.NewWriter(arfile) arwriter := ar.NewWriter(arfile)
err = arwriter.WriteGlobalHeader() err = arwriter.WriteGlobalHeader()
if err != nil { if err != nil {
return &os.PathError{"write ar header", archivePath, err} return &os.PathError{Op: "write ar header", Path: archivePath, Err: err}
} }
// Open all object files and read the symbols for the symbol table. // Open all object files and read the symbols for the symbol table.

4
builder/uf2.go

@ -141,11 +141,13 @@ func split(input []byte, limit int) [][]byte {
var block []byte var block []byte
output := make([][]byte, 0, len(input)/limit+1) output := make([][]byte, 0, len(input)/limit+1)
for len(input) >= limit { for len(input) >= limit {
// add all blocks
block, input = input[:limit], input[limit:] block, input = input[:limit], input[limit:]
output = append(output, block) output = append(output, block)
} }
if len(input) > 0 { if len(input) > 0 {
output = append(output, input[:len(input)]) // add remaining block (that isn't full sized)
output = append(output, input)
} }
return output return output
} }

58
cgo/cgo.go

@ -124,17 +124,17 @@ var cgoAliases = map[string]string{
// builtinAliases are handled specially because they only exist on the Go side // builtinAliases are handled specially because they only exist on the Go side
// of CGo, not on the CGo side (they're prefixed with "_Cgo_" there). // of CGo, not on the CGo side (they're prefixed with "_Cgo_" there).
var builtinAliases = map[string]struct{}{ var builtinAliases = map[string]struct{}{
"char": struct{}{}, "char": {},
"schar": struct{}{}, "schar": {},
"uchar": struct{}{}, "uchar": {},
"short": struct{}{}, "short": {},
"ushort": struct{}{}, "ushort": {},
"int": struct{}{}, "int": {},
"uint": struct{}{}, "uint": {},
"long": struct{}{}, "long": {},
"ulong": struct{}{}, "ulong": {},
"longlong": struct{}{}, "longlong": {},
"ulonglong": struct{}{}, "ulonglong": {},
} }
// cgoTypes lists some C types with ambiguous sizes that must be retrieved // cgoTypes lists some C types with ambiguous sizes that must be retrieved
@ -224,7 +224,7 @@ func Process(files []*ast.File, dir string, fset *token.FileSet, cflags []string
Specs: []ast.Spec{ Specs: []ast.Spec{
&ast.ValueSpec{ &ast.ValueSpec{
Names: []*ast.Ident{ Names: []*ast.Ident{
&ast.Ident{ {
Name: "_", Name: "_",
Obj: &ast.Object{ Obj: &ast.Object{
Kind: ast.Var, Kind: ast.Var,
@ -494,7 +494,7 @@ func (p *cgoPackage) addFuncDecls() {
if fn.variadic { if fn.variadic {
decl.Doc = &ast.CommentGroup{ decl.Doc = &ast.CommentGroup{
List: []*ast.Comment{ List: []*ast.Comment{
&ast.Comment{ {
Slash: fn.pos, Slash: fn.pos,
Text: "//go:variadic", Text: "//go:variadic",
}, },
@ -505,7 +505,7 @@ func (p *cgoPackage) addFuncDecls() {
for i, arg := range fn.args { for i, arg := range fn.args {
args[i] = &ast.Field{ args[i] = &ast.Field{
Names: []*ast.Ident{ Names: []*ast.Ident{
&ast.Ident{ {
NamePos: fn.pos, NamePos: fn.pos,
Name: arg.name, Name: arg.name,
Obj: &ast.Object{ Obj: &ast.Object{
@ -553,7 +553,7 @@ func (p *cgoPackage) addFuncPtrDecls() {
Name: "C." + name + "$funcaddr", Name: "C." + name + "$funcaddr",
} }
valueSpec := &ast.ValueSpec{ valueSpec := &ast.ValueSpec{
Names: []*ast.Ident{&ast.Ident{ Names: []*ast.Ident{{
NamePos: fn.pos, NamePos: fn.pos,
Name: "C." + name + "$funcaddr", Name: "C." + name + "$funcaddr",
Obj: obj, Obj: obj,
@ -603,7 +603,7 @@ func (p *cgoPackage) addConstDecls() {
Name: "C." + name, Name: "C." + name,
} }
valueSpec := &ast.ValueSpec{ valueSpec := &ast.ValueSpec{
Names: []*ast.Ident{&ast.Ident{ Names: []*ast.Ident{{
NamePos: constVal.pos, NamePos: constVal.pos,
Name: "C." + name, Name: "C." + name,
Obj: obj, Obj: obj,
@ -644,7 +644,7 @@ func (p *cgoPackage) addVarDecls() {
Name: "C." + name, Name: "C." + name,
} }
valueSpec := &ast.ValueSpec{ valueSpec := &ast.ValueSpec{
Names: []*ast.Ident{&ast.Ident{ Names: []*ast.Ident{{
NamePos: global.pos, NamePos: global.pos,
Name: "C." + name, Name: "C." + name,
Obj: obj, Obj: obj,
@ -845,9 +845,9 @@ func (p *cgoPackage) makeUnionField(typ *elaboratedTypeInfo) *ast.StructType {
Struct: typ.typeExpr.Struct, Struct: typ.typeExpr.Struct,
Fields: &ast.FieldList{ Fields: &ast.FieldList{
Opening: typ.typeExpr.Fields.Opening, Opening: typ.typeExpr.Fields.Opening,
List: []*ast.Field{&ast.Field{ List: []*ast.Field{{
Names: []*ast.Ident{ Names: []*ast.Ident{
&ast.Ident{ {
NamePos: typ.typeExpr.Fields.Opening, NamePos: typ.typeExpr.Fields.Opening,
Name: "$union", Name: "$union",
}, },
@ -928,9 +928,9 @@ func (p *cgoPackage) createUnionAccessor(field *ast.Field, typeName string) {
Recv: &ast.FieldList{ Recv: &ast.FieldList{
Opening: pos, Opening: pos,
List: []*ast.Field{ List: []*ast.Field{
&ast.Field{ {
Names: []*ast.Ident{ Names: []*ast.Ident{
&ast.Ident{ {
NamePos: pos, NamePos: pos,
Name: "union", Name: "union",
}, },
@ -959,7 +959,7 @@ func (p *cgoPackage) createUnionAccessor(field *ast.Field, typeName string) {
}, },
Results: &ast.FieldList{ Results: &ast.FieldList{
List: []*ast.Field{ List: []*ast.Field{
&ast.Field{ {
Type: &ast.StarExpr{ Type: &ast.StarExpr{
Star: pos, Star: pos,
X: field.Type, X: field.Type,
@ -1038,9 +1038,9 @@ func (p *cgoPackage) createBitfieldGetter(bitfield bitfieldInfo, typeName string
Recv: &ast.FieldList{ Recv: &ast.FieldList{
Opening: bitfield.pos, Opening: bitfield.pos,
List: []*ast.Field{ List: []*ast.Field{
&ast.Field{ {
Names: []*ast.Ident{ Names: []*ast.Ident{
&ast.Ident{ {
NamePos: bitfield.pos, NamePos: bitfield.pos,
Name: "s", Name: "s",
Obj: &ast.Object{ Obj: &ast.Object{
@ -1074,7 +1074,7 @@ func (p *cgoPackage) createBitfieldGetter(bitfield bitfieldInfo, typeName string
}, },
Results: &ast.FieldList{ Results: &ast.FieldList{
List: []*ast.Field{ List: []*ast.Field{
&ast.Field{ {
Type: bitfield.field.Type, Type: bitfield.field.Type,
}, },
}, },
@ -1191,9 +1191,9 @@ func (p *cgoPackage) createBitfieldSetter(bitfield bitfieldInfo, typeName string
Recv: &ast.FieldList{ Recv: &ast.FieldList{
Opening: bitfield.pos, Opening: bitfield.pos,
List: []*ast.Field{ List: []*ast.Field{
&ast.Field{ {
Names: []*ast.Ident{ Names: []*ast.Ident{
&ast.Ident{ {
NamePos: bitfield.pos, NamePos: bitfield.pos,
Name: "s", Name: "s",
Obj: &ast.Object{ Obj: &ast.Object{
@ -1224,9 +1224,9 @@ func (p *cgoPackage) createBitfieldSetter(bitfield bitfieldInfo, typeName string
Params: &ast.FieldList{ Params: &ast.FieldList{
Opening: bitfield.pos, Opening: bitfield.pos,
List: []*ast.Field{ List: []*ast.Field{
&ast.Field{ {
Names: []*ast.Ident{ Names: []*ast.Ident{
&ast.Ident{ {
NamePos: bitfield.pos, NamePos: bitfield.pos,
Name: "value", Name: "value",
Obj: nil, Obj: nil,

2
cgo/cgo_test.go

@ -96,7 +96,7 @@ func TestCGo(t *testing.T) {
if err != nil { if err != nil {
t.Errorf("could not write out CGo AST: %v", err) t.Errorf("could not write out CGo AST: %v", err)
} }
actual := normalizeResult(string(buf.Bytes())) actual := normalizeResult(buf.String())
// Read the file with the expected output, to compare against. // Read the file with the expected output, to compare against.
outfile := filepath.Join("testdata", name+".out.go") outfile := filepath.Join("testdata", name+".out.go")

10
cgo/libclang.go

@ -203,7 +203,7 @@ func tinygo_clang_globals_visitor(c, parent C.GoCXCursor, client_data C.CXClient
if resultType.kind != C.CXType_Void { if resultType.kind != C.CXType_Void {
fn.results = &ast.FieldList{ fn.results = &ast.FieldList{
List: []*ast.Field{ List: []*ast.Field{
&ast.Field{ {
Type: p.makeASTType(resultType, pos), Type: p.makeASTType(resultType, pos),
}, },
}, },
@ -775,7 +775,7 @@ func tinygo_clang_struct_visitor(c, parent C.GoCXCursor, client_data C.CXClientD
} }
*inBitfield = false *inBitfield = false
field.Names = []*ast.Ident{ field.Names = []*ast.Ident{
&ast.Ident{ {
NamePos: pos, NamePos: pos,
Name: name, Name: name,
Obj: &ast.Object{ Obj: &ast.Object{
@ -796,7 +796,11 @@ func tinygo_clang_enum_visitor(c, parent C.GoCXCursor, client_data C.CXClientDat
pos := p.getCursorPosition(c) pos := p.getCursorPosition(c)
value := C.tinygo_clang_getEnumConstantDeclValue(c) value := C.tinygo_clang_getEnumConstantDeclValue(c)
p.constants[name] = constantInfo{ p.constants[name] = constantInfo{
expr: &ast.BasicLit{pos, token.INT, strconv.FormatInt(int64(value), 10)}, expr: &ast.BasicLit{
ValuePos: pos,
Kind: token.INT,
Value: strconv.FormatInt(int64(value), 10),
},
pos: pos, pos: pos,
} }
return C.CXChildVisit_Continue return C.CXChildVisit_Continue

2
compiler/asserts.go

@ -164,11 +164,9 @@ func (b *builder) createChanBoundsCheck(elementSize uint64, bufSize llvm.Value,
if bufSize.Type().IntTypeWidth() < b.uintptrType.IntTypeWidth() { if bufSize.Type().IntTypeWidth() < b.uintptrType.IntTypeWidth() {
if bufSizeType.Info()&types.IsUnsigned != 0 { if bufSizeType.Info()&types.IsUnsigned != 0 {
// Unsigned, so zero-extend to uint type. // Unsigned, so zero-extend to uint type.
bufSizeType = types.Typ[types.Uint]
bufSize = b.CreateZExt(bufSize, b.intType, "") bufSize = b.CreateZExt(bufSize, b.intType, "")
} else { } else {
// Signed, so sign-extend to int type. // Signed, so sign-extend to int type.
bufSizeType = types.Typ[types.Int]
bufSize = b.CreateSExt(bufSize, b.intType, "") bufSize = b.CreateSExt(bufSize, b.intType, "")
} }
} }

4
compiler/calls.go

@ -63,10 +63,10 @@ func (c *compilerContext) expandFormalParamType(t llvm.Type, name string, goType
case llvm.StructTypeKind: case llvm.StructTypeKind:
fieldInfos := c.flattenAggregateType(t, name, goType) fieldInfos := c.flattenAggregateType(t, name, goType)
if len(fieldInfos) <= maxFieldsPerParam { if len(fieldInfos) <= maxFieldsPerParam {
// managed to expand this parameter
return fieldInfos return fieldInfos
} else {
// failed to lower
} }
// failed to expand this parameter: too many fields
} }
// TODO: split small arrays // TODO: split small arrays
return []paramInfo{ return []paramInfo{

12
compiler/compiler.go

@ -33,9 +33,6 @@ func init() {
llvm.InitializeAllAsmPrinters() llvm.InitializeAllAsmPrinters()
} }
// The TinyGo import path.
const tinygoPath = "github.com/tinygo-org/tinygo"
// Config is the configuration for the compiler. Most settings should be copied // Config is the configuration for the compiler. Most settings should be copied
// directly from compileopts.Config, it recreated here to decouple the compiler // directly from compileopts.Config, it recreated here to decouple the compiler
// package a bit and because it makes caching easier. // package a bit and because it makes caching easier.
@ -141,7 +138,6 @@ type builder struct {
blockExits map[*ssa.BasicBlock]llvm.BasicBlock // these are the exit blocks blockExits map[*ssa.BasicBlock]llvm.BasicBlock // these are the exit blocks
currentBlock *ssa.BasicBlock currentBlock *ssa.BasicBlock
phis []phiNode phis []phiNode
taskHandle llvm.Value
deferPtr llvm.Value deferPtr llvm.Value
difunc llvm.Metadata difunc llvm.Metadata
dilocals map[*types.Var]llvm.Metadata dilocals map[*types.Var]llvm.Metadata
@ -233,10 +229,6 @@ func Sizes(machine llvm.TargetMachine) types.Sizes {
targetData := machine.CreateTargetData() targetData := machine.CreateTargetData()
defer targetData.Dispose() defer targetData.Dispose()
intPtrType := targetData.IntPtrType()
if intPtrType.IntTypeWidth()/8 <= 32 {
}
var intWidth int var intWidth int
if targetData.PointerSize() <= 4 { if targetData.PointerSize() <= 4 {
// 8, 16, 32 bits targets // 8, 16, 32 bits targets
@ -251,7 +243,7 @@ func Sizes(machine llvm.TargetMachine) types.Sizes {
return &stdSizes{ return &stdSizes{
IntSize: int64(intWidth / 8), IntSize: int64(intWidth / 8),
PtrSize: int64(targetData.PointerSize()), PtrSize: int64(targetData.PointerSize()),
MaxAlign: int64(targetData.PrefTypeAlignment(intPtrType)), MaxAlign: int64(targetData.PrefTypeAlignment(targetData.IntPtrType())),
} }
} }
@ -452,7 +444,7 @@ func (c *compilerContext) createDIType(typ types.Type) llvm.Metadata {
AlignInBits: uint32(c.targetData.ABITypeAlignment(llvmType)) * 8, AlignInBits: uint32(c.targetData.ABITypeAlignment(llvmType)) * 8,
ElementType: c.getDIType(typ.Elem()), ElementType: c.getDIType(typ.Elem()),
Subscripts: []llvm.DISubrange{ Subscripts: []llvm.DISubrange{
llvm.DISubrange{ {
Lo: 0, Lo: 0,
Count: typ.Len(), Count: typ.Len(),
}, },

12
compiler/errors.go

@ -3,7 +3,6 @@ package compiler
// This file contains some utility functions related to error handling. // This file contains some utility functions related to error handling.
import ( import (
"go/scanner"
"go/token" "go/token"
"go/types" "go/types"
"path/filepath" "path/filepath"
@ -20,20 +19,11 @@ func (c *compilerContext) makeError(pos token.Pos, msg string) types.Error {
} }
} }
// addError adds a new compiler diagnostic with the given location and message.
func (c *compilerContext) addError(pos token.Pos, msg string) { func (c *compilerContext) addError(pos token.Pos, msg string) {
c.diagnostics = append(c.diagnostics, c.makeError(pos, msg)) c.diagnostics = append(c.diagnostics, c.makeError(pos, msg))
} }
// errorAt returns an error value at the location of the instruction.
// The location information may not be complete as it depends on debug
// information in the IR.
func errorAt(inst llvm.Value, msg string) scanner.Error {
return scanner.Error{
Pos: getPosition(inst),
Msg: msg,
}
}
// getPosition returns the position information for the given value, as far as // getPosition returns the position information for the given value, as far as
// it is available. // it is available.
func getPosition(val llvm.Value) token.Position { func getPosition(val llvm.Value) token.Position {

4
compiler/inlineasm.go

@ -72,7 +72,7 @@ func (b *builder) createInlineAsmFull(instr *ssa.CallCommon) (llvm.Value, error)
args := []llvm.Value{} args := []llvm.Value{}
constraints := []string{} constraints := []string{}
hasOutput := false hasOutput := false
asmString = regexp.MustCompile("\\{\\}").ReplaceAllStringFunc(asmString, func(s string) string { asmString = regexp.MustCompile(`\{\}`).ReplaceAllStringFunc(asmString, func(s string) string {
hasOutput = true hasOutput = true
return "$0" return "$0"
}) })
@ -80,7 +80,7 @@ func (b *builder) createInlineAsmFull(instr *ssa.CallCommon) (llvm.Value, error)
constraints = append(constraints, "=&r") constraints = append(constraints, "=&r")
registerNumbers[""] = 0 registerNumbers[""] = 0
} }
asmString = regexp.MustCompile("\\{[a-zA-Z]+\\}").ReplaceAllStringFunc(asmString, func(s string) string { asmString = regexp.MustCompile(`\{[a-zA-Z]+\}`).ReplaceAllStringFunc(asmString, func(s string) string {
// TODO: skip strings like {r4} etc. that look like ARM push/pop // TODO: skip strings like {r4} etc. that look like ARM push/pop
// instructions. // instructions.
name := s[1 : len(s)-1] name := s[1 : len(s)-1]

15
compiler/llvm.go

@ -8,21 +8,6 @@ import (
// This file contains helper functions for LLVM that are not exposed in the Go // This file contains helper functions for LLVM that are not exposed in the Go
// bindings. // bindings.
// Return a list of values (actually, instructions) where this value is used as
// an operand.
func getUses(value llvm.Value) []llvm.Value {
if value.IsNil() {
return nil
}
var uses []llvm.Value
use := value.FirstUse()
for !use.IsNil() {
uses = append(uses, use.User())
use = use.NextUse()
}
return uses
}
// createTemporaryAlloca creates a new alloca in the entry block and adds // createTemporaryAlloca creates a new alloca in the entry block and adds
// lifetime start information in the IR signalling that the alloca won't be used // lifetime start information in the IR signalling that the alloca won't be used
// before this point. // before this point.

Loading…
Cancel
Save