/
document_tracker.go
412 lines (334 loc) · 12.3 KB
/
document_tracker.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
// Copyright 2017 The Serulian Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package handler
import (
"context"
"fmt"
"log"
"net/url"
"strings"
"time"
"github.com/serulian/compiler/builder"
"github.com/serulian/compiler/compilercommon"
"github.com/serulian/compiler/formatter"
"github.com/serulian/compiler/grok"
"github.com/serulian/compiler/packageloader"
"github.com/serulian/serulian-langserver/protocol"
"path"
"github.com/sourcegraph/jsonrpc2"
cmap "github.com/streamrail/concurrent-map"
)
// MaximumBuildDuration is the maximum duration to build a handle before we timeout.
const MaximumBuildDuration = 5 * time.Second
// DiagnoseDelay is the delay waited before a document is re-parsed.
const DiagnoseDelay = 500 * time.Millisecond
// getPackageLibraries returns the libraries to load, if any, when creating a Groker.
func getPackageLibraries(path string) []packageloader.Library {
return []packageloader.Library{builder.CORE_LIBRARY}
}
// document represents a single document found in the tracker.
type document struct {
// path is the local file system path of the document.
path string
// contents are the current contents of the document.
contents string
// version is the current version of the document.
version int
// groker holds a reference to the Grok for this document.
groker *grok.Groker
// codeContextOrActions holds the map of CodeContextOrActions's for this document, by ID.
codeContextOrActions cmap.ConcurrentMap
}
// documentTracker keeps track of all documents (source files) which are open
// in the client.
type documentTracker struct {
// documents is the map of documents being tracked, keyed by path.
documents cmap.ConcurrentMap
// localPathLoader is an instance of a LocalFilePathLoader to be used as a basis
// for the document tracker's path loading for files that are *not* being tracked.
localPathLoader packageloader.LocalFilePathLoader
// debouncedDiagnose is a debounced-wrapped call over the diagnoseDocument function.
debouncedDiagnose func(data interface{})
// vcsDevelopmentDirectories are the specified VCS development directories to be passed
// to Grok, if any.
vcsDevelopmentDirectories []string
// workspaceRootPath is the root path of the workspace. May be empty if there is no
// workspace being used.
workspaceRootPath string
// workspaceGrok is (if defined) the workspace-wide Grok.
workspaceGrok *grok.Groker
}
func newDocumentTracker(vcsDevelopmentDirectories []string) *documentTracker {
return &documentTracker{
documents: cmap.New(),
localPathLoader: packageloader.LocalFilePathLoader{},
debouncedDiagnose: debounce(diagnoseDocument, DiagnoseDelay),
vcsDevelopmentDirectories: vcsDevelopmentDirectories,
workspaceRootPath: "",
workspaceGrok: nil,
}
}
// initializeWorkspace initializes the document tracker over the given workspace root.
func (dt *documentTracker) initializeWorkspace(ctx context.Context, conn *jsonrpc2.Conn, workspaceRootPath string) {
dt.workspaceRootPath = workspaceRootPath
if workspaceRootPath != "" {
dt.workspaceGrok = grok.NewGrokerWithConfig(grok.Config{
EntrypointPath: workspaceRootPath,
VCSDevelopmentDirectories: dt.vcsDevelopmentDirectories,
Libraries: getPackageLibraries(workspaceRootPath),
PathLoader: dt,
ScopePaths: []compilercommon.InputSource{},
MaximumBuildDuration: MaximumBuildDuration,
})
dt.debouncedDiagnose(diagnoseParams{dt, workspaceRootPath, -1, true, ctx, conn})
}
}
// tracksLanguage returns true if the given language is tracked by the document tracker.
func (dt *documentTracker) tracksLanguage(languageID string) bool {
return languageID == "serulian"
}
// uriToPath converts the given URI into a local file system path. If the URI is not a `file:///`
// URI, returns an error.
func (dt *documentTracker) uriToPath(uri string) (string, error) {
url, err := url.Parse(uri)
if err != nil {
return "", err
}
if url.Scheme != "file" {
return "", fmt.Errorf("Can only work on local files, found: %s", uri)
}
return url.Path, nil
}
// isTracking returns true if and only if the document with the specified URI is already being tracked.
func (dt *documentTracker) isTracking(uri string) bool {
path, err := dt.uriToPath(uri)
if err != nil {
return false
}
return dt.documents.Has(path)
}
// openDocument starts tracking of a document with the given URI, contents and initial version number.
func (dt *documentTracker) openDocument(ctx context.Context, conn *jsonrpc2.Conn, uri string, contents string, version int) {
path, err := dt.uriToPath(uri)
if err != nil {
return
}
documentGroker := grok.NewGrokerWithConfig(grok.Config{
EntrypointPath: path,
VCSDevelopmentDirectories: dt.vcsDevelopmentDirectories,
Libraries: getPackageLibraries(path),
PathLoader: dt,
ScopePaths: []compilercommon.InputSource{compilercommon.InputSource(path)},
MaximumBuildDuration: MaximumBuildDuration,
})
dt.documents.Set(path, document{
path: path,
contents: contents,
version: version,
groker: documentGroker,
codeContextOrActions: cmap.New(),
})
dt.debouncedDiagnose(diagnoseParams{dt, path, version, false, ctx, conn})
}
// updateDocument updates the contents of the document with the given URI. If the document is not being
// tracked, does nothing.
func (dt *documentTracker) updateDocument(ctx context.Context, conn *jsonrpc2.Conn, uri string, contents string, version int) {
path, err := dt.uriToPath(uri)
if err != nil {
return
}
if !dt.documents.Has(path) {
return
}
dt.documents.Upsert(path, nil, func(exists bool, valueInMap interface{}, newValue interface{}) interface{} {
if !exists {
return document{
path: path,
contents: contents,
version: version,
codeContextOrActions: cmap.New(),
}
}
return document{
path: path,
contents: contents,
version: version,
groker: valueInMap.(document).groker,
codeContextOrActions: valueInMap.(document).codeContextOrActions,
}
})
dt.debouncedDiagnose(diagnoseParams{dt, path, version, false, ctx, conn})
}
// closeDocument stops tracking the document with the given URI.
func (dt *documentTracker) closeDocument(uri string) {
path, err := dt.uriToPath(uri)
if err != nil {
return
}
dt.documents.Remove(path)
}
// getDocumentAtVersion returns the document at the specified version, for the specified path, if any.
func (dt *documentTracker) getDocumentAtVersion(path string, version int) (document, bool) {
currentValue, exists := dt.documents.Get(path)
if !exists {
return document{}, false
}
current := currentValue.(document)
return current, current.version == version
}
// getGrokHandle returns the Grok handle using the given URI as the root source path.
func (dt *documentTracker) getGrokHandle(uri string, freshnessOption grok.HandleFreshnessOption) (grok.Handle, error) {
handle, _, err := dt.getGrokHandleAndDocument(uri, freshnessOption)
return handle, err
}
// getGrokHandleAndDocument returns the Grok handle using the given URI as the root source path.
func (dt *documentTracker) getGrokHandleAndDocument(uri string, freshnessOption grok.HandleFreshnessOption) (grok.Handle, document, error) {
path, err := dt.uriToPath(uri)
if err != nil {
return grok.Handle{}, document{}, err
}
current, exists := dt.documents.Get(path)
if !exists {
return grok.Handle{}, document{}, fmt.Errorf("Document is not being tracked: %s", uri)
}
groker := current.(document).groker
if groker == nil {
return grok.Handle{}, current.(document), fmt.Errorf("Document is not being tracked: %s", uri)
}
handle, err := groker.GetHandleWithOption(freshnessOption)
return handle, current.(document), err
}
// sourceToURI returns the given source as a URI.
func (dt *documentTracker) sourceToURI(source compilercommon.InputSource) (protocol.DocumentURI, bool) {
url := url.URL{
Scheme: "file",
Path: string(source),
}
return protocol.DocumentURI(url.String()), true
}
// convertRange returns the given source range as a Document Range.
func (dt *documentTracker) convertRange(sourceRange compilercommon.SourceRange) (protocol.Range, error) {
startLine, startCol, err := sourceRange.Start().LineAndColumn()
if err != nil {
return protocol.Range{}, err
}
endLine, endCol, err := sourceRange.End().LineAndColumn()
if err != nil {
return protocol.Range{}, err
}
return protocol.Range{
Start: protocol.Position{startLine, startCol},
End: protocol.Position{endLine, endCol + 1},
}, nil
}
// convertRanges converts the given SourceRanges's into Document Locations.
func (dt *documentTracker) convertRanges(sourceRanges []compilercommon.SourceRange) []protocol.Location {
locations := make([]protocol.Location, 0, len(sourceRanges))
for _, sourceRange := range sourceRanges {
uri, ok := dt.sourceToURI(sourceRange.Source())
if !ok {
continue
}
documentRange, err := dt.convertRange(sourceRange)
if err != nil {
continue
}
locations = append(locations, protocol.Location{
URI: uri,
Range: documentRange,
})
}
return locations
}
// getLineText returns the text found on the line of the given position before its column position.
func (dt *documentTracker) getLineText(uri string, lineNumber int, colPosition int) (string, error) {
path, err := dt.uriToPath(uri)
if err != nil {
return "", err
}
currentValue, exists := dt.documents.Get(path)
if !exists {
return "", fmt.Errorf("Missing document for path %s", path)
}
lines := strings.Split(currentValue.(document).contents, "\n")
if lineNumber >= len(lines) {
return "", fmt.Errorf("Invalid line %v for path %s", lineNumber, path)
}
lineText := lines[lineNumber]
if colPosition > len(lineText) {
return "", fmt.Errorf("Invalid column %v for path %s", colPosition, path)
}
return lineText[0:colPosition], nil
}
// formatDocument formats the document found at the given URI, return a set of edits.
func (dt *documentTracker) formatDocument(uri string) []protocol.TextEdit {
path, err := dt.uriToPath(uri)
if err != nil {
return []protocol.TextEdit{}
}
currentValue, exists := dt.documents.Get(path)
if !exists {
return []protocol.TextEdit{}
}
current := currentValue.(document)
if len(current.contents) == 0 {
return []protocol.TextEdit{}
}
formatted, err := formatter.FormatSource(current.contents)
if err != nil {
log.Printf("Error when trying to format source for URI %s: %v", uri, err)
return []protocol.TextEdit{}
}
// Skip if nothing has changed.
if formatted == current.contents {
return []protocol.TextEdit{}
}
lines := strings.Split(current.contents, "\n")
lastLine := len(lines) - 1
lastLineLength := len(lines[len(lines)-1])
changeAll := protocol.TextEdit{
NewText: formatted,
Range: protocol.Range{
protocol.Position{0, 0},
protocol.Position{lastLine, lastLineLength + 1},
},
}
return []protocol.TextEdit{changeAll}
}
func (dt *documentTracker) VCSPackageDirectory(entrypoint packageloader.Entrypoint) string {
workspaceRootDirectory := dt.workspaceRootPath
if dt.IsSourceFile(workspaceRootDirectory) {
workspaceRootDirectory = path.Dir(workspaceRootDirectory)
}
workspacePackageDirectory := path.Join(workspaceRootDirectory, packageloader.SerulianPackageDirectory)
return workspacePackageDirectory
}
func (dt *documentTracker) LoadSourceFile(path string) ([]byte, error) {
currentValue, exists := dt.documents.Get(path)
if exists {
return []byte(currentValue.(document).contents), nil
}
return dt.localPathLoader.LoadSourceFile(path)
}
func (dt *documentTracker) GetRevisionID(path string) (int64, error) {
currentValue, exists := dt.documents.Get(path)
if exists {
return int64(currentValue.(document).version), nil
}
return dt.localPathLoader.GetRevisionID(path)
}
func (dt *documentTracker) Exists(path string) (bool, error) {
_, exists := dt.documents.Get(path)
if exists {
return true, nil
}
return dt.localPathLoader.Exists(path)
}
func (dt *documentTracker) IsSourceFile(path string) bool {
_, exists := dt.documents.Get(path)
return exists || dt.localPathLoader.IsSourceFile(path)
}
func (dt *documentTracker) LoadDirectory(path string) ([]packageloader.DirectoryEntry, error) {
return dt.localPathLoader.LoadDirectory(path)
}