1// Copyright 2018 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.
4
5package cache
6
7import (
8	"context"
9	"go/token"
10	"path/filepath"
11	"strings"
12	"sync"
13
14	"golang.org/x/tools/internal/lsp/source"
15	"golang.org/x/tools/internal/span"
16)
17
18// viewFile extends source.File with helper methods for the view package.
19type viewFile interface {
20	source.File
21
22	filename() string
23	addURI(uri span.URI) int
24}
25
26// fileBase holds the common functionality for all files.
27// It is intended to be embedded in the file implementations
28type fileBase struct {
29	uris  []span.URI
30	fname string
31	kind  source.FileKind
32
33	view *view
34
35	handleMu sync.Mutex
36	handle   source.FileHandle
37
38	token *token.File
39}
40
41func basename(filename string) string {
42	return strings.ToLower(filepath.Base(filename))
43}
44
45func (f *fileBase) URI() span.URI {
46	return f.uris[0]
47}
48
49func (f *fileBase) filename() string {
50	return f.fname
51}
52
53// View returns the view associated with the file.
54func (f *fileBase) View() source.View {
55	return f.view
56}
57
58// Content returns a handle for the contents of the file.
59func (f *fileBase) Handle(ctx context.Context) source.FileHandle {
60	f.handleMu.Lock()
61	defer f.handleMu.Unlock()
62	if f.handle == nil {
63		f.handle = f.view.Session().GetFile(f.URI())
64	}
65	return f.handle
66}
67
68func (f *fileBase) FileSet() *token.FileSet {
69	return f.view.Session().Cache().FileSet()
70}
71