-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
249 lines (218 loc) · 6.9 KB
/
handler.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
package lsp
import (
contextpkg "context"
"fmt"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/ngld/fso-table-parser/pkg/parser"
"github.com/ngld/fso-table-parser/pkg/structs"
"github.com/rotisserie/eris"
"github.com/tliron/glsp"
protocol "github.com/tliron/glsp/protocol_3_16"
)
var (
version = "0.0.1"
lspCode = "fso-lsp-error"
)
type docCacheEntry struct {
uri string
content string
ctx contextpkg.Context
ctxCancel contextpkg.CancelFunc
scopes []parser.ScopeInfo
sync.Mutex
version int32
pendingVersion int32
}
func processLexerErrors(errors []error, severity protocol.DiagnosticSeverity, content string) []protocol.Diagnostic {
msgs := make([]protocol.Diagnostic, len(errors))
for idx, err := range errors {
var loc [4]int
if errInfo, ok := eris.Cause(err).(parser.ParserError); ok {
loc = errInfo.Location()
} else {
loc = [4]int{0, 0, 0, 0}
}
msgs[idx] = protocol.Diagnostic{
Range: protocol.Range{
Start: protocol.Position{
Line: uint32(loc[0] - 1),
Character: uint32(loc[1]),
},
End: protocol.Position{
Line: uint32(loc[2] - 1),
Character: uint32(loc[3]),
},
},
Severity: &severity,
Code: &protocol.IntegerOrString{
Value: "fso-lsp-error",
},
Message: err.Error(),
}
}
return msgs
}
func analyseDoc(context *glsp.Context, doc *docCacheEntry, fields []parser.ContainerItem) {
defer func() {
p := recover()
if p != nil {
err := eris.New(fmt.Sprint(p))
protocol.Trace(context, protocol.MessageTypeError, eris.ToString(err, true))
}
}()
doc.ctx, doc.ctxCancel = contextpkg.WithDeadline(contextpkg.Background(), time.Now().Add(1000*time.Millisecond))
protocol.Trace(context, protocol.MessageTypeInfo, fmt.Sprintf("Parsing %s", doc.uri))
start := time.Now()
lexer := parser.NewLexer(doc.ctx, strings.NewReader(doc.content))
for _, container := range fields {
if doc.ctx.Err() != nil {
break
}
_, err := container.Parse(lexer)
if err != nil {
lexer.Report(err)
}
}
if doc.ctx.Err() != nil {
protocol.Trace(context, protocol.MessageTypeInfo, fmt.Sprintf("Canceled %s (%v)", doc.uri, doc.ctx.Err()))
return
}
msgs := processLexerErrors(lexer.Errors(), protocol.DiagnosticSeverityError, doc.content)
msgs = append(msgs, processLexerErrors(lexer.Warnings(), protocol.DiagnosticSeverityInformation, doc.content)...)
end := time.Now()
version := uint32(doc.version)
context.Notify(protocol.ServerTextDocumentPublishDiagnostics, &protocol.PublishDiagnosticsParams{
URI: doc.uri,
Version: &version,
Diagnostics: msgs,
})
doc.scopes = lexer.ScopeInfos()
duration := end.Sub(start).Milliseconds()
protocol.Trace(context, protocol.MessageTypeInfo, fmt.Sprintf("Processed %s in %dms", doc.uri, duration))
doc.ctxCancel()
}
func GetHandler() *protocol.Handler {
var handler *protocol.Handler
docCache := make(map[string]*docCacheEntry)
fields := structs.NewTestTable()
handler = &protocol.Handler{
CancelRequest: func(context *glsp.Context, params *protocol.CancelParams) error {
return nil
},
Progress: func(context *glsp.Context, params *protocol.ProgressParams) error {
return nil
},
Initialize: func(context *glsp.Context, params *protocol.InitializeParams) (interface{}, error) {
/*if params.Trace != nil {
protocol.SetTraceValue(*params.Trace)
}*/
protocol.SetTraceValue(protocol.TraceValueVerbose)
protocol.Trace(context, protocol.MessageTypeInfo, fmt.Sprintf("Trace: %v", *params.Trace))
caps := handler.CreateServerCapabilities()
caps.TextDocumentSync = protocol.TextDocumentSyncKindIncremental
protocol.Trace(context, protocol.MessageTypeInfo, "Hello World!")
return protocol.InitializeResult{
Capabilities: caps,
ServerInfo: &protocol.InitializeResultServerInfo{
Name: "FSO Tables LSP",
Version: &version,
},
}, nil
},
Initialized: func(context *glsp.Context, params *protocol.InitializedParams) error {
return nil
},
Shutdown: func(context *glsp.Context) error {
return nil
},
Exit: func(context *glsp.Context) error {
return nil
},
LogTrace: func(context *glsp.Context, params *protocol.LogTraceParams) error {
return nil
},
SetTrace: func(context *glsp.Context, params *protocol.SetTraceParams) error {
protocol.SetTraceValue(params.Value)
return nil
},
TextDocumentDidOpen: func(context *glsp.Context, params *protocol.DidOpenTextDocumentParams) error {
doc := params.TextDocument
docCache[doc.URI] = &docCacheEntry{
uri: doc.URI,
version: doc.Version,
content: doc.Text,
}
go analyseDoc(context, docCache[doc.URI], fields)
return nil
},
TextDocumentDidChange: func(context *glsp.Context, params *protocol.DidChangeTextDocumentParams) error {
defer func() {
p := recover()
if p != nil {
err := eris.New(fmt.Sprint(p))
protocol.Trace(context, protocol.MessageTypeError, eris.ToString(err, true))
}
}()
item := docCache[params.TextDocument.URI]
atomic.StoreInt32(&item.pendingVersion, params.TextDocument.Version)
item.ctxCancel()
go func() {
// Run the text updates in a goroutine to avoid blocking the server on the lock
item.Lock()
item.version = params.TextDocument.Version
for _, change := range params.ContentChanges {
if ev, ok := change.(protocol.TextDocumentContentChangeEvent); ok {
start, end := ev.Range.IndexesIn(item.content)
item.content = item.content[:start] + ev.Text + item.content[end:]
} else if ev, ok := change.(protocol.TextDocumentContentChangeEventWhole); ok {
item.content = ev.Text
}
}
if item.pendingVersion == params.TextDocument.Version {
// Only trigger the analysis for the latest version
analyseDoc(context, item, fields)
}
item.Unlock()
}()
return nil
},
TextDocumentDidClose: func(context *glsp.Context, params *protocol.DidCloseTextDocumentParams) error {
delete(docCache, params.TextDocument.URI)
return nil
},
TextDocumentHover: func(context *glsp.Context, params *protocol.HoverParams) (*protocol.Hover, error) {
doc, found := docCache[params.TextDocument.URI]
if !found {
return nil, eris.Errorf("Document %s not found", params.TextDocument.URI)
}
line := int(params.Position.Line) + 1
col := int(params.Position.Character)
for _, info := range doc.scopes {
if info.Start[0] <= line && info.Start[1] <= col &&
info.End[0] >= line && info.End[1] >= col {
return &protocol.Hover{
Range: &protocol.Range{
Start: protocol.Position{
Line: uint32(info.Start[0]) - 1,
Character: uint32(info.Start[1]),
},
End: protocol.Position{
Line: uint32(info.End[0]) - 1,
Character: uint32(info.End[1]),
},
},
Contents: protocol.MarkupContent{
Kind: protocol.MarkupKindPlainText,
Value: info.HoverText,
},
}, nil
}
}
return nil, nil
},
}
return handler
}