Skip to content

Commit

Permalink
Avoid exporting a pointer to a loop variable in linker (#1389)
Browse files Browse the repository at this point in the history
The Bazel nogo (Go lint config) errored when I tried to compile esbuild:

    compilepkg: nogo: errors found by nogo during build-time code analysis:
    external/com_github_evanw_esbuild/internal/bundler/linker.go:3309:27:
     exporting a pointer for the loop variable stmt (export_loop_ref)

The simplified code nogo complains about is:

    for _, stmt := range partStmts {
      stmt.Data = &js_ast.SImport{
        StarNameLoc: &stmt.Loc,
      }
    }

The problem is `&stmt.Loc` points to the mutated loop variable `stmt`.  After
the loop iteration ends, all stored pointers will point to the last value of
`partStmts[-1].Loc`.

An alternative solution is to shadow `stmt` at the beginning of the loop, but
this felt cleaner:

    stmt := stmt

The lint rule is defined by https://github.com/kyoh86/exportloopref.
  • Loading branch information
jschaf authored Jun 24, 2021
1 parent f96b797 commit 35a1099
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion internal/bundler/linker.go
Original file line number Diff line number Diff line change
Expand Up @@ -3306,7 +3306,7 @@ func (c *linkerContext) convertStmtsForChunk(sourceIndex uint32, stmtList *stmtL
// Turn this statement into "import * as ns from 'path'"
stmt.Data = &js_ast.SImport{
NamespaceRef: s.NamespaceRef,
StarNameLoc: &stmt.Loc,
StarNameLoc: &logger.Loc{Start: stmt.Loc.Start},
ImportRecordIndex: s.ImportRecordIndex,
}

Expand Down

0 comments on commit 35a1099

Please sign in to comment.