Skip to content

Commit 5298bab

Browse files
committed
perf: improve IsStandardLibrary
1 parent 6d149e8 commit 5298bab

1 file changed

Lines changed: 14 additions & 14 deletions

File tree

lang/golang/parser/utils.go

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,13 @@ import (
1818
"container/list"
1919
"fmt"
2020
"go/ast"
21-
"go/build"
2221
"go/types"
2322
"os"
2423
"os/exec"
2524
"path"
2625
"path/filepath"
2726
"regexp"
27+
"runtime"
2828
"strings"
2929
"sync"
3030

@@ -112,27 +112,27 @@ func (pc *PackageCache) IsStandardPackage(path string) bool {
112112
return isStd
113113
}
114114

115-
// Optimization: if the first segment of the path contains a dot, it's likely a domain name (e.g. github.com),
116-
// so it's not a standard package. This avoids expensive build.Import calls.
117-
if parts := strings.SplitN(path, "/", 2); len(parts) > 0 && strings.Contains(parts[0], ".") {
118-
pc.set(path, false)
119-
return false
120-
}
115+
isStd := IsStandardLibrary(path)
116+
pc.set(path, isStd)
117+
return isStd
118+
}
121119

122-
pkg, err := build.Import(path, "", build.FindOnly)
123-
if err != nil {
124-
// Cannot find the package, assume it's not a standard package
125-
pc.set(path, false)
120+
func IsStandardLibrary(pkgPath string) bool {
121+
122+
goroot := runtime.GOROOT()
123+
if goroot == "" {
126124
return false
127125
}
128126

129-
isStd := pkg.Goroot
130-
pc.set(path, isStd)
127+
dir := filepath.Join(goroot, "src", pkgPath)
128+
info, err := os.Stat(dir)
129+
isStd := err == nil && info.IsDir()
130+
131131
return isStd
132132
}
133133

134134
// stdlibCache 缓存 importPath 是否是 system package, 10000 个缓存
135-
var stdlibCache = NewPackageCache(10000)
135+
var stdlibCache = NewPackageCache(100000)
136136

137137
func isSysPkg(importPath string) bool {
138138
return stdlibCache.IsStandardPackage(importPath)

0 commit comments

Comments
 (0)