Skip to content
Merged
Show file tree
Hide file tree
Changes from 21 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 3 additions & 6 deletions builder/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"fmt"
"go/types"
"hash/crc32"
"maps"
"math/bits"
"os"
"os/exec"
Expand Down Expand Up @@ -137,9 +138,7 @@ func Build(pkgName, outpath, tmpdir string, config *compileopts.Config) (BuildRe
if _, ok := globalValues[pkgPath]; !ok {
globalValues[pkgPath] = map[string]string{}
}
for k, v := range vals {
globalValues[pkgPath][k] = v
}
maps.Copy(globalValues[pkgPath], vals)
}

// Check for a libc dependency.
Expand Down Expand Up @@ -278,7 +277,6 @@ func Build(pkgName, outpath, tmpdir string, config *compileopts.Config) (BuildRe

var embedFileObjects []*compileJob
for _, pkg := range lprogram.Sorted() {
pkg := pkg // necessary to avoid a race condition

var undefinedGlobals []string
for name := range globalValues[pkg.Pkg.Path()] {
Expand Down Expand Up @@ -775,7 +773,6 @@ func Build(pkgName, outpath, tmpdir string, config *compileopts.Config) (BuildRe
// TODO: do this as part of building the package to be able to link the
// bitcode files together.
for _, pkg := range lprogram.Sorted() {
pkg := pkg
for _, filename := range pkg.CFiles {
abspath := filepath.Join(pkg.OriginalDir(), filename)
job := &compileJob{
Expand Down Expand Up @@ -914,7 +911,7 @@ func Build(pkgName, outpath, tmpdir string, config *compileopts.Config) (BuildRe
}

// Run wasm-opt for wasm binaries
if arch := strings.Split(config.Triple(), "-")[0]; arch == "wasm32" {
if arch, _, _ := strings.Cut(config.Triple(), "-"); arch == "wasm32" {
optLevel, _, _ := config.OptLevel()
opt := "-" + optLevel

Expand Down
1 change: 0 additions & 1 deletion builder/builder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ func TestClangAttributes(t *testing.T) {
targetNames = append(targetNames, "esp32", "esp8266")
}
for _, targetName := range targetNames {
targetName := targetName
t.Run(targetName, func(t *testing.T) {
testClangAttributes(t, &compileopts.Options{Target: targetName})
})
Expand Down
2 changes: 1 addition & 1 deletion builder/cc.go
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,7 @@ func parseDepFile(s string) ([]string, error) {
s = strings.ReplaceAll(s, "\\\n", " ")

// Only use the first line, which is expected to begin with "deps:".
line := strings.SplitN(s, "\n", 2)[0]
line, _, _ := strings.Cut(s, "\n")
if !strings.HasPrefix(line, "deps:") {
return nil, errors.New("readDepFile: expected 'deps:' prefix")
}
Expand Down
2 changes: 1 addition & 1 deletion builder/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import (
var commands = map[string][]string{}

func init() {
llvmMajor := strings.Split(llvm.Version, ".")[0]
llvmMajor, _, _ := strings.Cut(llvm.Version, ".")
commands["clang"] = []string{"clang-" + llvmMajor}
commands["ld.lld"] = []string{"ld.lld-" + llvmMajor, "ld.lld"}
commands["wasm-ld"] = []string{"wasm-ld-" + llvmMajor, "wasm-ld"}
Expand Down
2 changes: 1 addition & 1 deletion builder/darwin-libsystem.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ func makeDarwinLibSystemJob(config *compileopts.Config, tmpdir string) *compileJ
return &compileJob{
description: "compile Darwin libSystem.dylib",
run: func(job *compileJob) (err error) {
arch := strings.Split(config.Triple(), "-")[0]
arch, _, _ := strings.Cut(config.Triple(), "-")
job.result = filepath.Join(tmpdir, "libSystem.dylib")
objpath := filepath.Join(tmpdir, "libSystem.o")
inpath := filepath.Join(goenv.Get("TINYGOROOT"), "lib/macos-minimal-sdk/src", arch, "libSystem.s")
Expand Down
4 changes: 2 additions & 2 deletions builder/jobs.go
Original file line number Diff line number Diff line change
Expand Up @@ -195,11 +195,11 @@ type intHeap struct {
sort.IntSlice
}

func (h *intHeap) Push(x interface{}) {
func (h *intHeap) Push(x any) {
h.IntSlice = append(h.IntSlice, x.(int))
}

func (h *intHeap) Pop() interface{} {
func (h *intHeap) Pop() any {
x := h.IntSlice[len(h.IntSlice)-1]
h.IntSlice = h.IntSlice[:len(h.IntSlice)-1]
return x
Expand Down
1 change: 0 additions & 1 deletion builder/library.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,6 @@ func (l *Library) load(config *compileopts.Config, tmpdir string) (job *compileJ
}
for _, path := range paths {
// Strip leading "../" parts off the path.
path := path
cleanpath := path
for strings.HasPrefix(cleanpath, "../") {
cleanpath = cleanpath[3:]
Expand Down
4 changes: 2 additions & 2 deletions builder/musl.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ func buildMuslAllTypes(arch, muslDir, outputBitsDir string) error {
if err != nil {
return err
}
lines := strings.Split(string(data), "\n")
for _, line := range lines {
lines := strings.SplitSeq(string(data), "\n")
for line := range lines {
if strings.HasPrefix(line, "TYPEDEF ") {
matches := regexp.MustCompile(`TYPEDEF (.*) ([^ ]*);`).FindStringSubmatch(line)
value := matches[1]
Expand Down
2 changes: 0 additions & 2 deletions builder/sizes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ func TestBinarySize(t *testing.T) {
// output varies by binaryen version.
}
for _, tc := range tests {
tc := tc
t.Run(tc.target+"/"+tc.path, func(t *testing.T) {
t.Parallel()

Expand Down Expand Up @@ -85,7 +84,6 @@ func TestSizeFull(t *testing.T) {
pkgMatch := regexp.MustCompile(`^[a-z/]+$`) // example: "internal/task"

for _, target := range tests {
target := target
t.Run(target, func(t *testing.T) {
t.Parallel()

Expand Down
2 changes: 1 addition & 1 deletion builder/tools.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ func parseLLDErrors(text string) error {
// This can happen in some cases like with CGo and //go:linkname tricker.
if matches := regexp.MustCompile(`^ld.lld(-[0-9]+)?: error: undefined symbol: (.*)\n`).FindStringSubmatch(message); matches != nil {
symbolName := matches[2]
for _, line := range strings.Split(message, "\n") {
for line := range strings.SplitSeq(message, "\n") {
matches := regexp.MustCompile(`referenced by .* \(((.*):([0-9]+))\)`).FindStringSubmatch(line)
if matches != nil {
parsedError = true
Expand Down
2 changes: 1 addition & 1 deletion builder/uf2.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ func convertBinToUF2(input []byte, targetAddr uint32, uf2FamilyID string) ([]byt
}
bl.SetNumBlocks(len(blocks))

for i := 0; i < len(blocks); i++ {
for i := range blocks {
bl.SetBlockNo(i)
bl.SetData(blocks[i])

Expand Down
18 changes: 10 additions & 8 deletions cgo/cgo.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ type cgoPackage struct {
tokenFiles map[string]*token.File
definedGlobally map[string]ast.Node
noescapingFuncs map[string]*noescapingFunc // #cgo noescape lines
anonDecls map[interface{}]string
anonDecls map[any]string
cflags []string // CFlags from #cgo lines
ldflags []string // LDFlags from #cgo lines
visitedFiles map[string][]byte
Expand Down Expand Up @@ -263,7 +263,7 @@ func Process(files []*ast.File, dir, importPath string, fset *token.FileSet, cfl
tokenFiles: map[string]*token.File{},
definedGlobally: map[string]ast.Node{},
noescapingFuncs: map[string]*noescapingFunc{},
anonDecls: map[interface{}]string{},
anonDecls: map[any]string{},
visitedFiles: map[string][]byte{},
}

Expand Down Expand Up @@ -306,7 +306,7 @@ func Process(files []*ast.File, dir, importPath string, fset *token.FileSet, cfl
// Find `import "C"` C fragments in the file.
p.cgoHeaders = make([]string, len(files)) // combined CGo header fragment for each file
for i, f := range files {
var cgoHeader string
var cgoHeader strings.Builder
for i := 0; i < len(f.Decls); i++ {
decl := f.Decls[i]
genDecl, ok := decl.(*ast.GenDecl)
Expand Down Expand Up @@ -341,7 +341,8 @@ func Process(files []*ast.File, dir, importPath string, fset *token.FileSet, cfl
// Iterate through all parts of the CGo header. Note that every //
// line is a new comment.
position := fset.Position(genDecl.Doc.Pos())
fragment := fmt.Sprintf("# %d %#v\n", position.Line, position.Filename)
var fragment strings.Builder
fragment.WriteString(fmt.Sprintf("# %d %#v\n", position.Line, position.Filename))
for _, comment := range genDecl.Doc.List {
// Find all #cgo lines, extract and use their contents, and
// replace the lines with spaces (to preserve locations).
Expand All @@ -358,12 +359,13 @@ func Process(files []*ast.File, dir, importPath string, fset *token.FileSet, cfl
} else { // comment
c = " " + c[2:len(c)-2]
}
fragment += c + "\n"
fragment.WriteString(c)
fragment.WriteByte('\n')
}
cgoHeader += fragment
cgoHeader.WriteString(fragment.String())
}

p.cgoHeaders[i] = cgoHeader
p.cgoHeaders[i] = cgoHeader.String()
}

// Define CFlags that will be used while parsing the package.
Expand Down Expand Up @@ -1221,7 +1223,7 @@ func getPos(node ast.Node) token.Pos {
// getUnnamedDeclName creates a name (with the given prefix) for the given C
// declaration. This is used for structs, unions, and enums that are often
// defined without a name and used in a typedef.
func (p *cgoPackage) getUnnamedDeclName(prefix string, itf interface{}) string {
func (p *cgoPackage) getUnnamedDeclName(prefix string, itf any) string {
if name, ok := p.anonDecls[itf]; ok {
return name
}
Expand Down
1 change: 0 additions & 1 deletion cgo/cgo_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ func TestCGo(t *testing.T) {
"flags",
"const",
} {
name := name // avoid a race condition
t.Run(name, func(t *testing.T) {
// Read the AST in memory.
path := filepath.Join("testdata", name+".go")
Expand Down
6 changes: 3 additions & 3 deletions cgo/libclang.go
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ func (f *cgoFile) readNames(fragment string, cflags []string, filename string, c
pos := f.getClangLocationPosition(location, unit)
f.addError(pos, severity+": "+spelling)
}
for i := 0; i < numDiagnostics; i++ {
for i := range numDiagnostics {
diagnostic := C.clang_getDiagnostic(unit, C.uint(i))
addDiagnostic(diagnostic)

Expand Down Expand Up @@ -278,7 +278,7 @@ func (f *cgoFile) createASTNode(name string, c clangCursor) (ast.Node, any) {
Text: strings.Join(doc, "\n"),
})
}
for i := 0; i < numArgs; i++ {
for i := range numArgs {
arg := C.tinygo_clang_Cursor_getArgument(c, C.uint(i))
argName := getString(C.tinygo_clang_getCursorSpelling(arg))
argType := C.clang_getArgType(cursorType, C.uint(i))
Expand Down Expand Up @@ -534,7 +534,7 @@ func tinygo_clang_globals_visitor(c, parent C.GoCXCursor, client_data C.CXClient

// Get the precise location in the source code. Used for uniquely identifying
// source locations.
func (f *cgoFile) getUniqueLocationID(pos token.Pos, cursor C.GoCXCursor) interface{} {
func (f *cgoFile) getUniqueLocationID(pos token.Pos, cursor C.GoCXCursor) any {
clangLocation := C.tinygo_clang_getCursorLocation(cursor)
var file C.CXFile
var line C.unsigned
Expand Down
8 changes: 4 additions & 4 deletions cgo/sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,17 @@ import "C"
// C. It is useful if an API uses function pointers and you cannot pass a Go
// pointer but only a C pointer.
type refMap struct {
refs map[unsafe.Pointer]interface{}
refs map[unsafe.Pointer]any
lock sync.Mutex
}

// Put stores a value in the map. It can later be retrieved using Get. It must
// be removed using Remove to avoid memory leaks.
func (m *refMap) Put(v interface{}) unsafe.Pointer {
func (m *refMap) Put(v any) unsafe.Pointer {
m.lock.Lock()
defer m.lock.Unlock()
if m.refs == nil {
m.refs = make(map[unsafe.Pointer]interface{}, 1)
m.refs = make(map[unsafe.Pointer]any, 1)
}
ref := C.malloc(1)
m.refs[ref] = v
Expand All @@ -31,7 +31,7 @@ func (m *refMap) Put(v interface{}) unsafe.Pointer {

// Get returns a stored value previously inserted with Put. Use the same
// reference as you got from Put.
func (m *refMap) Get(ref unsafe.Pointer) interface{} {
func (m *refMap) Get(ref unsafe.Pointer) any {
m.lock.Lock()
defer m.lock.Unlock()
return m.refs[ref]
Expand Down
11 changes: 3 additions & 8 deletions compileopts/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"os"
"path/filepath"
"regexp"
"slices"
"strconv"
"strings"

Expand Down Expand Up @@ -140,13 +141,7 @@ func (c *Config) GC() string {
func (c *Config) NeedsStackObjects() bool {
switch c.GC() {
case "conservative", "custom", "precise", "boehm":
for _, tag := range c.BuildTags() {
if tag == "tinygo.wasm" {
return true
}
}

return false
return slices.Contains(c.BuildTags(), "tinygo.wasm")
default:
return false
}
Expand Down Expand Up @@ -245,7 +240,7 @@ func (c *Config) RP2040BootPatch() bool {
// Return a canonicalized architecture name, so we don't have to deal with arm*
// vs thumb* vs arm64.
func CanonicalArchName(triple string) string {
arch := strings.Split(triple, "-")[0]
arch, _, _ := strings.Cut(triple, "-")
if arch == "arm64" {
return "aarch64"
}
Expand Down
8 changes: 2 additions & 6 deletions compileopts/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package compileopts
import (
"fmt"
"regexp"
"slices"
"strings"
"time"
)
Expand Down Expand Up @@ -129,10 +130,5 @@ func (o *Options) Verify() error {
}

func isInArray(arr []string, item string) bool {
for _, i := range arr {
if i == item {
return true
}
}
return false
return slices.Contains(arr, item)
}
Comment thread
jakebailey marked this conversation as resolved.
Outdated
13 changes: 5 additions & 8 deletions compiler/compiler.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ type builder struct {
dilocals map[*types.Var]llvm.Metadata
initInlinedAt llvm.Metadata // fake inlinedAt position
initPseudoFuncs map[string]llvm.Metadata // fake "inlined" functions for proper init debug locations
allDeferFuncs []interface{}
allDeferFuncs []any
deferFuncs map[*ssa.Function]int
deferInvokeFuncs map[string]int
deferClosureFuncs map[*ssa.Function]int
Expand Down Expand Up @@ -2154,13 +2154,10 @@ func (c *compilerContext) maxSliceSize(elementType llvm.Type) uint64 {
if elementSize == 0 {
elementSize = 1
}
maxSize := maxPointerValue / elementSize

// len(slice) is an int. Make sure the length remains small enough to fit in
// an int.
if maxSize > maxIntegerValue {
maxSize = maxIntegerValue
}
maxSize := min(
// len(slice) is an int. Make sure the length remains small enough to fit in
// an int.
maxPointerValue/elementSize, maxIntegerValue)

return maxSize
}
Expand Down
6 changes: 3 additions & 3 deletions compiler/compiler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -188,9 +188,9 @@ func TestCompilerErrors(t *testing.T) {
t.Error(err)
}
errorsFileString := strings.ReplaceAll(string(errorsFile), "\r\n", "\n")
for _, line := range strings.Split(errorsFileString, "\n") {
if strings.HasPrefix(line, "// ERROR: ") {
expectedErrors = append(expectedErrors, strings.TrimPrefix(line, "// ERROR: "))
for line := range strings.SplitSeq(errorsFileString, "\n") {
if after, ok := strings.CutPrefix(line, "// ERROR: "); ok {
expectedErrors = append(expectedErrors, after)
}
}

Expand Down
8 changes: 4 additions & 4 deletions compiler/defer.go
Original file line number Diff line number Diff line change
Expand Up @@ -669,8 +669,8 @@ func (b *builder) createRunDefers() {
fn := callback.Fn.(*ssa.Function)
valueTypes := []llvm.Type{b.uintptrType, b.dataPtrType}
params := fn.Signature.Params()
for i := 0; i < params.Len(); i++ {
valueTypes = append(valueTypes, b.getLLVMType(params.At(i).Type()))
for v := range params.Variables() {
valueTypes = append(valueTypes, b.getLLVMType(v.Type()))
}
valueTypes = append(valueTypes, b.dataPtrType) // closure
deferredCallType := b.ctx.StructType(valueTypes, false)
Expand All @@ -695,8 +695,8 @@ func (b *builder) createRunDefers() {

//Get signature from call results
params := callback.Type().Underlying().(*types.Signature).Params()
for i := 0; i < params.Len(); i++ {
valueTypes = append(valueTypes, b.getLLVMType(params.At(i).Type()))
for v := range params.Variables() {
valueTypes = append(valueTypes, b.getLLVMType(v.Type()))
}

deferredCallType := b.ctx.StructType(valueTypes, false)
Expand Down
4 changes: 2 additions & 2 deletions compiler/func.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,8 @@ func (c *compilerContext) getLLVMFunctionType(typ *types.Signature) llvm.Type {
paramTypes = append(paramTypes, info.llvmType)
}
}
for i := 0; i < typ.Params().Len(); i++ {
subType := c.getLLVMType(typ.Params().At(i).Type())
for v := range typ.Params().Variables() {
subType := c.getLLVMType(v.Type())
for _, info := range c.expandFormalParamType(subType, "", nil) {
paramTypes = append(paramTypes, info.llvmType)
}
Expand Down
Loading
Loading