Skip to content

Commit

Permalink
Calculate correct position with comments before the package keyword
Browse files Browse the repository at this point in the history
Detect the file beginning by using `pass.Fset.File(f.Pos())` instead of
assuming that `f.Pos()` is always the beginning of the file.

`f.Pos()` is not the beginning of the file when there is for instance a
comment before the package, which can lead to wrong reportings of the
actual error position.

Signed-off-by: Roman Mohr <[email protected]>
  • Loading branch information
rmohr committed Jul 8, 2022
1 parent 98d3f84 commit 875db03
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 2 deletions.
3 changes: 1 addition & 2 deletions errcheck/analyzer.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package errcheck
import (
"fmt"
"go/ast"
"go/token"
"reflect"
"regexp"

Expand Down Expand Up @@ -66,7 +65,7 @@ func runAnalyzer(pass *analysis.Pass) (interface{}, error) {

for _, err := range v.errors {
pass.Report(analysis.Diagnostic{
Pos: token.Pos(int(f.Pos()) + err.Pos.Offset),
Pos: pass.Fset.File(f.Pos()).Pos(err.Pos.Offset),
Message: "unchecked error",
})
}
Expand Down
12 changes: 12 additions & 0 deletions errcheck/analyzer_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package errcheck

import (
"golang.org/x/tools/go/analysis/analysistest"
"path/filepath"
"testing"
)

func TestAnalyzer(t *testing.T) {
packageDir := filepath.Join(analysistest.TestData(), "src/a/")
_ = analysistest.Run(t, packageDir, Analyzer)
}
2 changes: 2 additions & 0 deletions errcheck/testdata/src/a/main.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// ensure that the package keyword is not equal to file beginning
// to test correct position calculations.
package a

import (
Expand Down

0 comments on commit 875db03

Please sign in to comment.