1 // Copyright 2019 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
24 "golang.org/x/tools/internal/event"
25 "golang.org/x/tools/internal/gocommand"
26 "golang.org/x/tools/internal/lsp/debug/tag"
27 "golang.org/x/tools/internal/lsp/source"
28 "golang.org/x/tools/internal/memoize"
29 "golang.org/x/tools/internal/span"
32 func New(ctx context.Context, options func(*source.Options)) *Cache {
33 index := atomic.AddInt64(&cacheIndex, 1)
35 id: strconv.FormatInt(index, 10),
36 fset: token.NewFileSet(),
38 fileContent: map[span.URI]*fileHandle{},
46 options func(*source.Options)
51 fileContent map[span.URI]*fileHandle
54 type fileHandle struct {
62 func (c *Cache) GetFile(ctx context.Context, uri span.URI) (source.FileHandle, error) {
63 return c.getFile(ctx, uri)
66 func (c *Cache) getFile(ctx context.Context, uri span.URI) (*fileHandle, error) {
67 fi, statErr := os.Stat(uri.Filename())
76 fh, ok := c.fileContent[uri]
78 if ok && fh.modTime.Equal(fi.ModTime()) {
82 fh, err := readFile(ctx, uri, fi.ModTime())
87 c.fileContent[uri] = fh
92 // ioLimit limits the number of parallel file reads per process.
93 var ioLimit = make(chan struct{}, 128)
95 func readFile(ctx context.Context, uri span.URI, modTime time.Time) (*fileHandle, error) {
97 case ioLimit <- struct{}{}:
101 defer func() { <-ioLimit }()
103 ctx, done := event.Start(ctx, "cache.readFile", tag.File.Of(uri.Filename()))
107 data, err := ioutil.ReadFile(uri.Filename())
118 hash: hashContents(data),
122 func (c *Cache) NewSession(ctx context.Context) *Session {
123 index := atomic.AddInt64(&sessionIndex, 1)
124 options := source.DefaultOptions().Clone()
125 if c.options != nil {
130 id: strconv.FormatInt(index, 10),
132 overlays: make(map[span.URI]*overlay),
133 gocmdRunner: &gocommand.Runner{},
135 event.Log(ctx, "New session", KeyCreateSession.Of(s))
139 func (c *Cache) FileSet() *token.FileSet {
143 func (h *fileHandle) URI() span.URI {
147 func (h *fileHandle) Kind() source.FileKind {
148 return source.DetectLanguage("", h.uri.Filename())
151 func (h *fileHandle) Hash() string {
155 func (h *fileHandle) FileIdentity() source.FileIdentity {
156 return source.FileIdentity{
163 func (h *fileHandle) Read() ([]byte, error) {
164 return h.bytes, h.err
167 func hashContents(contents []byte) string {
168 return fmt.Sprintf("%x", sha256.Sum256(contents))
171 var cacheIndex, sessionIndex, viewIndex int64
173 func (c *Cache) ID() string { return c.id }
174 func (c *Cache) MemStats() map[reflect.Type]int { return c.store.Stats() }
176 type packageStat struct {
178 mode source.ParseMode
186 func (c *Cache) PackageStats(withNames bool) template.HTML {
187 var packageStats []packageStat
188 c.store.DebugOnlyIterate(func(k, v interface{}) {
190 case packageHandleKey:
191 v := v.(*packageData)
195 var typsCost, typInfoCost int64
196 if v.pkg.types != nil {
197 typsCost = typesCost(v.pkg.types.Scope())
199 if v.pkg.typesInfo != nil {
200 typInfoCost = typesInfoCost(v.pkg.typesInfo)
206 typesInfo: typInfoCost,
208 for _, f := range v.pkg.compiledGoFiles {
209 stat.file += int64(len(f.Src))
210 stat.ast += astCost(f.File)
212 stat.total = stat.file + stat.ast + stat.types + stat.typesInfo
213 packageStats = append(packageStats, stat)
217 for _, stat := range packageStats {
218 totalCost += stat.total
220 sort.Slice(packageStats, func(i, j int) bool {
221 return packageStats[i].total > packageStats[j].total
223 html := "<table><thead><td>Name</td><td>total = file + ast + types + types info</td></thead>\n"
224 human := func(n int64) string {
225 return fmt.Sprintf("%.2f", float64(n)/(1024*1024))
227 var printedCost int64
228 for _, stat := range packageStats {
233 html += fmt.Sprintf("<tr><td>%v (%v)</td><td>%v = %v + %v + %v + %v</td></tr>\n", name, stat.mode,
234 human(stat.total), human(stat.file), human(stat.ast), human(stat.types), human(stat.typesInfo))
235 printedCost += stat.total
236 if float64(printedCost) > float64(totalCost)*.9 {
241 return template.HTML(html)
244 func astCost(f *ast.File) int64 {
249 ast.Inspect(f, func(n ast.Node) bool {
250 count += 32 // nodes are pretty small.
256 func typesCost(scope *types.Scope) int64 {
257 cost := 64 + int64(scope.Len())*128 // types.object looks pretty big
258 for i := 0; i < scope.NumChildren(); i++ {
259 cost += typesCost(scope.Child(i))
264 func typesInfoCost(info *types.Info) int64 {
265 // Most of these refer to existing objects, with the exception of InitOrder, Selections, and Types.
266 cost := 24*len(info.Defs) +
267 32*len(info.Implicits) +
268 256*len(info.InitOrder) + // these are big, but there aren't many of them.
269 32*len(info.Scopes) +
270 128*len(info.Selections) + // wild guess
271 128*len(info.Types) + // wild guess