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()) {
83 case ioLimit <- struct{}{}:
87 defer func() { <-ioLimit }()
89 fh = readFile(ctx, uri, fi.ModTime())
91 c.fileContent[uri] = fh
96 // ioLimit limits the number of parallel file reads per process.
97 var ioLimit = make(chan struct{}, 128)
99 func readFile(ctx context.Context, uri span.URI, modTime time.Time) *fileHandle {
100 ctx, done := event.Start(ctx, "cache.readFile", tag.File.Of(uri.Filename()))
104 data, err := ioutil.ReadFile(uri.Filename())
115 hash: hashContents(data),
119 func (c *Cache) NewSession(ctx context.Context) *Session {
120 index := atomic.AddInt64(&sessionIndex, 1)
121 options := source.DefaultOptions().Clone()
122 if c.options != nil {
127 id: strconv.FormatInt(index, 10),
129 overlays: make(map[span.URI]*overlay),
130 gocmdRunner: &gocommand.Runner{},
132 event.Log(ctx, "New session", KeyCreateSession.Of(s))
136 func (c *Cache) FileSet() *token.FileSet {
140 func (h *fileHandle) URI() span.URI {
144 func (h *fileHandle) Kind() source.FileKind {
145 return source.DetectLanguage("", h.uri.Filename())
148 func (h *fileHandle) Hash() string {
152 func (h *fileHandle) FileIdentity() source.FileIdentity {
153 return source.FileIdentity{
160 func (h *fileHandle) Read() ([]byte, error) {
161 return h.bytes, h.err
164 func hashContents(contents []byte) string {
165 return fmt.Sprintf("%x", sha256.Sum256(contents))
168 var cacheIndex, sessionIndex, viewIndex int64
170 func (c *Cache) ID() string { return c.id }
171 func (c *Cache) MemStats() map[reflect.Type]int { return c.store.Stats() }
173 type packageStat struct {
175 mode source.ParseMode
183 func (c *Cache) PackageStats(withNames bool) template.HTML {
184 var packageStats []packageStat
185 c.store.DebugOnlyIterate(func(k, v interface{}) {
187 case packageHandleKey:
188 v := v.(*packageData)
192 var typsCost, typInfoCost int64
193 if v.pkg.types != nil {
194 typsCost = typesCost(v.pkg.types.Scope())
196 if v.pkg.typesInfo != nil {
197 typInfoCost = typesInfoCost(v.pkg.typesInfo)
203 typesInfo: typInfoCost,
205 for _, f := range v.pkg.compiledGoFiles {
206 stat.file += int64(len(f.Src))
207 stat.ast += astCost(f.File)
209 stat.total = stat.file + stat.ast + stat.types + stat.typesInfo
210 packageStats = append(packageStats, stat)
214 for _, stat := range packageStats {
215 totalCost += stat.total
217 sort.Slice(packageStats, func(i, j int) bool {
218 return packageStats[i].total > packageStats[j].total
220 html := "<table><thead><td>Name</td><td>total = file + ast + types + types info</td></thead>\n"
221 human := func(n int64) string {
222 return fmt.Sprintf("%.2f", float64(n)/(1024*1024))
224 var printedCost int64
225 for _, stat := range packageStats {
230 html += fmt.Sprintf("<tr><td>%v (%v)</td><td>%v = %v + %v + %v + %v</td></tr>\n", name, stat.mode,
231 human(stat.total), human(stat.file), human(stat.ast), human(stat.types), human(stat.typesInfo))
232 printedCost += stat.total
233 if float64(printedCost) > float64(totalCost)*.9 {
238 return template.HTML(html)
241 func astCost(f *ast.File) int64 {
246 ast.Inspect(f, func(n ast.Node) bool {
247 count += 32 // nodes are pretty small.
253 func typesCost(scope *types.Scope) int64 {
254 cost := 64 + int64(scope.Len())*128 // types.object looks pretty big
255 for i := 0; i < scope.NumChildren(); i++ {
256 cost += typesCost(scope.Child(i))
261 func typesInfoCost(info *types.Info) int64 {
262 // Most of these refer to existing objects, with the exception of InitOrder, Selections, and Types.
263 cost := 24*len(info.Defs) +
264 32*len(info.Implicits) +
265 256*len(info.InitOrder) + // these are big, but there aren't many of them.
266 32*len(info.Scopes) +
267 128*len(info.Selections) + // wild guess
268 128*len(info.Types) + // wild guess