From 49dd2ce3933e9460c3dc04797b5f30134f48dd39 Mon Sep 17 00:00:00 2001 From: Ayke van Laethem Date: Wed, 22 Sep 2021 21:51:19 +0200 Subject: [PATCH] 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. --- builder/ar.go | 2 +- builder/uf2.go | 4 ++- cgo/cgo.go | 58 +++++++++++++++++++++---------------------- cgo/cgo_test.go | 2 +- cgo/libclang.go | 12 ++++++--- compiler/asserts.go | 2 -- compiler/calls.go | 4 +-- compiler/compiler.go | 12 ++------- compiler/errors.go | 12 +-------- compiler/inlineasm.go | 4 +-- compiler/llvm.go | 15 ----------- 11 files changed, 49 insertions(+), 78 deletions(-) diff --git a/builder/ar.go b/builder/ar.go index 98d574fc..37b94af2 100644 --- a/builder/ar.go +++ b/builder/ar.go @@ -27,7 +27,7 @@ func makeArchive(archivePath string, objs []string) error { arwriter := ar.NewWriter(arfile) err = arwriter.WriteGlobalHeader() 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. diff --git a/builder/uf2.go b/builder/uf2.go index 24417a02..0d8696f8 100644 --- a/builder/uf2.go +++ b/builder/uf2.go @@ -141,11 +141,13 @@ func split(input []byte, limit int) [][]byte { var block []byte output := make([][]byte, 0, len(input)/limit+1) for len(input) >= limit { + // add all blocks block, input = input[:limit], input[limit:] output = append(output, block) } if len(input) > 0 { - output = append(output, input[:len(input)]) + // add remaining block (that isn't full sized) + output = append(output, input) } return output } diff --git a/cgo/cgo.go b/cgo/cgo.go index 8581807f..2718062d 100644 --- a/cgo/cgo.go +++ b/cgo/cgo.go @@ -124,17 +124,17 @@ var cgoAliases = map[string]string{ // 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). var builtinAliases = map[string]struct{}{ - "char": struct{}{}, - "schar": struct{}{}, - "uchar": struct{}{}, - "short": struct{}{}, - "ushort": struct{}{}, - "int": struct{}{}, - "uint": struct{}{}, - "long": struct{}{}, - "ulong": struct{}{}, - "longlong": struct{}{}, - "ulonglong": struct{}{}, + "char": {}, + "schar": {}, + "uchar": {}, + "short": {}, + "ushort": {}, + "int": {}, + "uint": {}, + "long": {}, + "ulong": {}, + "longlong": {}, + "ulonglong": {}, } // 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{ &ast.ValueSpec{ Names: []*ast.Ident{ - &ast.Ident{ + { Name: "_", Obj: &ast.Object{ Kind: ast.Var, @@ -494,7 +494,7 @@ func (p *cgoPackage) addFuncDecls() { if fn.variadic { decl.Doc = &ast.CommentGroup{ List: []*ast.Comment{ - &ast.Comment{ + { Slash: fn.pos, Text: "//go:variadic", }, @@ -505,7 +505,7 @@ func (p *cgoPackage) addFuncDecls() { for i, arg := range fn.args { args[i] = &ast.Field{ Names: []*ast.Ident{ - &ast.Ident{ + { NamePos: fn.pos, Name: arg.name, Obj: &ast.Object{ @@ -553,7 +553,7 @@ func (p *cgoPackage) addFuncPtrDecls() { Name: "C." + name + "$funcaddr", } valueSpec := &ast.ValueSpec{ - Names: []*ast.Ident{&ast.Ident{ + Names: []*ast.Ident{{ NamePos: fn.pos, Name: "C." + name + "$funcaddr", Obj: obj, @@ -603,7 +603,7 @@ func (p *cgoPackage) addConstDecls() { Name: "C." + name, } valueSpec := &ast.ValueSpec{ - Names: []*ast.Ident{&ast.Ident{ + Names: []*ast.Ident{{ NamePos: constVal.pos, Name: "C." + name, Obj: obj, @@ -644,7 +644,7 @@ func (p *cgoPackage) addVarDecls() { Name: "C." + name, } valueSpec := &ast.ValueSpec{ - Names: []*ast.Ident{&ast.Ident{ + Names: []*ast.Ident{{ NamePos: global.pos, Name: "C." + name, Obj: obj, @@ -845,9 +845,9 @@ func (p *cgoPackage) makeUnionField(typ *elaboratedTypeInfo) *ast.StructType { Struct: typ.typeExpr.Struct, Fields: &ast.FieldList{ Opening: typ.typeExpr.Fields.Opening, - List: []*ast.Field{&ast.Field{ + List: []*ast.Field{{ Names: []*ast.Ident{ - &ast.Ident{ + { NamePos: typ.typeExpr.Fields.Opening, Name: "$union", }, @@ -928,9 +928,9 @@ func (p *cgoPackage) createUnionAccessor(field *ast.Field, typeName string) { Recv: &ast.FieldList{ Opening: pos, List: []*ast.Field{ - &ast.Field{ + { Names: []*ast.Ident{ - &ast.Ident{ + { NamePos: pos, Name: "union", }, @@ -959,7 +959,7 @@ func (p *cgoPackage) createUnionAccessor(field *ast.Field, typeName string) { }, Results: &ast.FieldList{ List: []*ast.Field{ - &ast.Field{ + { Type: &ast.StarExpr{ Star: pos, X: field.Type, @@ -1038,9 +1038,9 @@ func (p *cgoPackage) createBitfieldGetter(bitfield bitfieldInfo, typeName string Recv: &ast.FieldList{ Opening: bitfield.pos, List: []*ast.Field{ - &ast.Field{ + { Names: []*ast.Ident{ - &ast.Ident{ + { NamePos: bitfield.pos, Name: "s", Obj: &ast.Object{ @@ -1074,7 +1074,7 @@ func (p *cgoPackage) createBitfieldGetter(bitfield bitfieldInfo, typeName string }, Results: &ast.FieldList{ List: []*ast.Field{ - &ast.Field{ + { Type: bitfield.field.Type, }, }, @@ -1191,9 +1191,9 @@ func (p *cgoPackage) createBitfieldSetter(bitfield bitfieldInfo, typeName string Recv: &ast.FieldList{ Opening: bitfield.pos, List: []*ast.Field{ - &ast.Field{ + { Names: []*ast.Ident{ - &ast.Ident{ + { NamePos: bitfield.pos, Name: "s", Obj: &ast.Object{ @@ -1224,9 +1224,9 @@ func (p *cgoPackage) createBitfieldSetter(bitfield bitfieldInfo, typeName string Params: &ast.FieldList{ Opening: bitfield.pos, List: []*ast.Field{ - &ast.Field{ + { Names: []*ast.Ident{ - &ast.Ident{ + { NamePos: bitfield.pos, Name: "value", Obj: nil, diff --git a/cgo/cgo_test.go b/cgo/cgo_test.go index b1865060..6d5d5504 100644 --- a/cgo/cgo_test.go +++ b/cgo/cgo_test.go @@ -96,7 +96,7 @@ func TestCGo(t *testing.T) { if err != nil { 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. outfile := filepath.Join("testdata", name+".out.go") diff --git a/cgo/libclang.go b/cgo/libclang.go index 8e9af8a0..22ce68cd 100644 --- a/cgo/libclang.go +++ b/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 { fn.results = &ast.FieldList{ List: []*ast.Field{ - &ast.Field{ + { Type: p.makeASTType(resultType, pos), }, }, @@ -775,7 +775,7 @@ func tinygo_clang_struct_visitor(c, parent C.GoCXCursor, client_data C.CXClientD } *inBitfield = false field.Names = []*ast.Ident{ - &ast.Ident{ + { NamePos: pos, Name: name, Obj: &ast.Object{ @@ -796,8 +796,12 @@ func tinygo_clang_enum_visitor(c, parent C.GoCXCursor, client_data C.CXClientDat pos := p.getCursorPosition(c) value := C.tinygo_clang_getEnumConstantDeclValue(c) p.constants[name] = constantInfo{ - expr: &ast.BasicLit{pos, token.INT, strconv.FormatInt(int64(value), 10)}, - pos: pos, + expr: &ast.BasicLit{ + ValuePos: pos, + Kind: token.INT, + Value: strconv.FormatInt(int64(value), 10), + }, + pos: pos, } return C.CXChildVisit_Continue } diff --git a/compiler/asserts.go b/compiler/asserts.go index 381900bb..bcfafb99 100644 --- a/compiler/asserts.go +++ b/compiler/asserts.go @@ -164,11 +164,9 @@ func (b *builder) createChanBoundsCheck(elementSize uint64, bufSize llvm.Value, if bufSize.Type().IntTypeWidth() < b.uintptrType.IntTypeWidth() { if bufSizeType.Info()&types.IsUnsigned != 0 { // Unsigned, so zero-extend to uint type. - bufSizeType = types.Typ[types.Uint] bufSize = b.CreateZExt(bufSize, b.intType, "") } else { // Signed, so sign-extend to int type. - bufSizeType = types.Typ[types.Int] bufSize = b.CreateSExt(bufSize, b.intType, "") } } diff --git a/compiler/calls.go b/compiler/calls.go index 81842dc6..4c5b1fb4 100644 --- a/compiler/calls.go +++ b/compiler/calls.go @@ -63,10 +63,10 @@ func (c *compilerContext) expandFormalParamType(t llvm.Type, name string, goType case llvm.StructTypeKind: fieldInfos := c.flattenAggregateType(t, name, goType) if len(fieldInfos) <= maxFieldsPerParam { + // managed to expand this parameter return fieldInfos - } else { - // failed to lower } + // failed to expand this parameter: too many fields } // TODO: split small arrays return []paramInfo{ diff --git a/compiler/compiler.go b/compiler/compiler.go index 1ca798d1..2b1ab019 100644 --- a/compiler/compiler.go +++ b/compiler/compiler.go @@ -33,9 +33,6 @@ func init() { 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 // directly from compileopts.Config, it recreated here to decouple the compiler // 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 currentBlock *ssa.BasicBlock phis []phiNode - taskHandle llvm.Value deferPtr llvm.Value difunc llvm.Metadata dilocals map[*types.Var]llvm.Metadata @@ -233,10 +229,6 @@ func Sizes(machine llvm.TargetMachine) types.Sizes { targetData := machine.CreateTargetData() defer targetData.Dispose() - intPtrType := targetData.IntPtrType() - if intPtrType.IntTypeWidth()/8 <= 32 { - } - var intWidth int if targetData.PointerSize() <= 4 { // 8, 16, 32 bits targets @@ -251,7 +243,7 @@ func Sizes(machine llvm.TargetMachine) types.Sizes { return &stdSizes{ IntSize: int64(intWidth / 8), 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, ElementType: c.getDIType(typ.Elem()), Subscripts: []llvm.DISubrange{ - llvm.DISubrange{ + { Lo: 0, Count: typ.Len(), }, diff --git a/compiler/errors.go b/compiler/errors.go index 11813229..5f15a149 100644 --- a/compiler/errors.go +++ b/compiler/errors.go @@ -3,7 +3,6 @@ package compiler // This file contains some utility functions related to error handling. import ( - "go/scanner" "go/token" "go/types" "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) { 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 // it is available. func getPosition(val llvm.Value) token.Position { diff --git a/compiler/inlineasm.go b/compiler/inlineasm.go index 31312a92..e32a4f39 100644 --- a/compiler/inlineasm.go +++ b/compiler/inlineasm.go @@ -72,7 +72,7 @@ func (b *builder) createInlineAsmFull(instr *ssa.CallCommon) (llvm.Value, error) args := []llvm.Value{} constraints := []string{} hasOutput := false - asmString = regexp.MustCompile("\\{\\}").ReplaceAllStringFunc(asmString, func(s string) string { + asmString = regexp.MustCompile(`\{\}`).ReplaceAllStringFunc(asmString, func(s string) string { hasOutput = true return "$0" }) @@ -80,7 +80,7 @@ func (b *builder) createInlineAsmFull(instr *ssa.CallCommon) (llvm.Value, error) constraints = append(constraints, "=&r") 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 // instructions. name := s[1 : len(s)-1] diff --git a/compiler/llvm.go b/compiler/llvm.go index b8e0808a..da4013e6 100644 --- a/compiler/llvm.go +++ b/compiler/llvm.go @@ -8,21 +8,6 @@ import ( // This file contains helper functions for LLVM that are not exposed in the Go // 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 // lifetime start information in the IR signalling that the alloca won't be used // before this point.