This repository was archived by the owner on Sep 1, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathlsp.go
More file actions
328 lines (276 loc) · 7.95 KB
/
Copy pathlsp.go
File metadata and controls
328 lines (276 loc) · 7.95 KB
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
package lsproto
import (
"bytes"
"context"
"fmt"
"net/url"
"strings"
"github.com/microsoft/typescript-go/internal/bundled"
"github.com/microsoft/typescript-go/internal/json"
"github.com/microsoft/typescript-go/internal/jsonrpc"
"github.com/microsoft/typescript-go/internal/tspath"
)
type DocumentUri string // !!!
func (uri DocumentUri) FileName() string {
if bundled.IsBundled(string(uri)) {
return string(uri)
}
if strings.HasPrefix(string(uri), "file://") {
parsed, err := url.Parse(string(uri))
if err != nil {
panic(fmt.Sprintf("invalid file URI: %s", uri))
}
if parsed.Host != "" {
return "//" + parsed.Host + parsed.Path
}
return fixWindowsURIPath(parsed.Path)
}
// Leave all other URIs escaped so we can round-trip them.
scheme, path, ok := strings.Cut(string(uri), ":")
if !ok {
panic(fmt.Sprintf("invalid URI: %s", uri))
}
authority := "ts-nul-authority"
if rest, ok := strings.CutPrefix(path, "//"); ok {
authority, path, ok = strings.Cut(rest, "/")
if !ok {
panic(fmt.Sprintf("invalid URI: %s", uri))
}
}
return "^/" + scheme + "/" + authority + "/" + path
}
func (uri DocumentUri) Path(useCaseSensitiveFileNames bool) tspath.Path {
fileName := uri.FileName()
return tspath.ToPath(fileName, "", useCaseSensitiveFileNames)
}
func fixWindowsURIPath(path string) string {
if rest, ok := strings.CutPrefix(path, "/"); ok {
if volume, rest, ok := tspath.SplitVolumePath(rest); ok {
return volume + rest
}
}
return path
}
type HasTextDocumentURI interface {
TextDocumentURI() DocumentUri
}
type HasTextDocumentPosition interface {
HasTextDocumentURI
TextDocumentPosition() Position
}
type HasLocations interface {
GetLocations() *[]Location
}
type HasLocation interface {
GetLocation() Location
}
type URI string // !!!
type Method string
func unmarshalPtrTo[T any](data []byte) (*T, error) {
var v T
if err := json.Unmarshal(data, &v); err != nil {
return nil, fmt.Errorf("failed to unmarshal %T: %w", (*T)(nil), err)
}
return &v, nil
}
func unmarshalValue[T any](data []byte) (T, error) {
var v T
if err := json.Unmarshal(data, &v); err != nil {
return *new(T), fmt.Errorf("failed to unmarshal %T: %w", (*T)(nil), err)
}
return v, nil
}
func unmarshalAny(data []byte) (any, error) {
var v any
if err := json.Unmarshal(data, &v); err != nil {
return nil, fmt.Errorf("failed to unmarshal any: %w", err)
}
return v, nil
}
func unmarshalEmpty(data []byte) (any, error) {
if len(data) != 0 {
return nil, fmt.Errorf("expected empty, got: %s", string(data))
}
return nil, nil
}
func boolToInt(b bool) int {
if b {
return 1
}
return 0
}
func errNotObject(k json.Kind) error {
return fmt.Errorf("expected object start, but encountered %v", k)
}
func errNull(field string) error {
return fmt.Errorf("null value is not allowed for field %q", field)
}
func errMissing(props []string) error {
return fmt.Errorf("missing required properties: %s", strings.Join(props, ", "))
}
func errInvalidKind(typeName string, got json.Kind) error {
return fmt.Errorf("invalid %s: got %v", typeName, got)
}
func errInvalidValue(typeName string, data []byte) error {
return fmt.Errorf("invalid %s: %s", typeName, data)
}
func errLiteralMismatch(typeName string, expected string, got []byte) error {
return fmt.Errorf("expected %s value %s, got %s", typeName, expected, got)
}
func assertOnlyOne(message string, count int) {
if count != 1 {
panic(message)
}
}
func assertAtMostOne(message string, count int) {
if count > 1 {
panic(message)
}
}
// jsonKeyCheck compares a raw JSON key token (including quotes) against a Go string.
func jsonKeyCheck(name []byte, key string) bool {
return len(name) == len(key)+2 && name[0] == '"' && string(name[1:len(name)-1]) == key
}
// jsonObjectRawField scans the top-level keys of a JSON object looking for the
// given field name, and returns its raw JSON value (e.g. `"full"` with quotes).
// Returns nil if the field is not found.
func jsonObjectRawField(data []byte, field string) json.Value {
dec := json.NewDecoder(bytes.NewBuffer(data))
if dec.PeekKind() != '{' {
return nil
}
if _, err := dec.ReadToken(); err != nil {
return nil
}
for dec.PeekKind() != '}' {
name, err := dec.ReadValue()
if err != nil {
return nil
}
if jsonKeyCheck(name, field) {
val, err := dec.ReadValue()
if err != nil {
return nil
}
return val
}
if err := dec.SkipValue(); err != nil {
return nil
}
}
return nil
}
// jsonObjectHasKey scans the top-level keys of a JSON object looking for any of the
// given keys. Returns the index of the first key found, or -1 if none match.
// Bails early on first match without decoding any values.
func jsonObjectHasKey(data []byte, keys ...string) int {
dec := json.NewDecoder(bytes.NewBuffer(data))
if dec.PeekKind() != '{' {
return -1
}
if _, err := dec.ReadToken(); err != nil {
return -1
}
for dec.PeekKind() != '}' {
name, err := dec.ReadValue()
if err != nil {
return -1
}
for i, key := range keys {
if jsonKeyCheck(name, key) {
return i
}
}
if err := dec.SkipValue(); err != nil {
return -1
}
}
return -1
}
// Inspired by https://www.youtube.com/watch?v=dab3I-HcTVk
type RequestInfo[Params, Resp any] struct {
_ [0]Params
_ [0]Resp
Method Method
}
func (info RequestInfo[Params, Resp]) UnmarshalResult(result any) (Resp, error) {
if r, ok := result.(Resp); ok {
return r, nil
}
raw, ok := result.(json.Value)
if !ok {
return *new(Resp), fmt.Errorf("expected json.Value, got %T", result)
}
r, err := unmarshalResult(info.Method, raw)
if err != nil {
return *new(Resp), err
}
return r.(Resp), nil
}
func (info RequestInfo[Params, Resp]) NewRequestMessage(id *jsonrpc.ID, params Params) *RequestMessage {
return &RequestMessage{
ID: id,
Method: info.Method,
Params: params,
}
}
type NotificationInfo[Params any] struct {
_ [0]Params
Method Method
}
func (info NotificationInfo[Params]) NewNotificationMessage(params Params) *RequestMessage {
return &RequestMessage{
Method: info.Method,
Params: params,
}
}
type Null struct{}
func (Null) UnmarshalJSONFrom(dec *json.Decoder) error {
data, err := dec.ReadValue()
if err != nil {
return err
}
if string(data) != "null" {
return fmt.Errorf("expected null, got %s", data)
}
return nil
}
func (Null) MarshalJSONTo(enc *json.Encoder) error {
return enc.WriteToken(json.Null)
}
type NoParams struct{}
func (NoParams) IsZero() bool { return true }
type clientCapabilitiesKey struct{}
func WithClientCapabilities(ctx context.Context, caps *ResolvedClientCapabilities) context.Context {
return context.WithValue(ctx, clientCapabilitiesKey{}, caps)
}
func GetClientCapabilities(ctx context.Context) *ResolvedClientCapabilities {
if caps, _ := ctx.Value(clientCapabilitiesKey{}).(*ResolvedClientCapabilities); caps != nil {
return caps
}
return &ResolvedClientCapabilities{}
}
// PreferredMarkupKind returns the first (most preferred) markup kind from the given formats,
// or MarkupKindPlainText if the slice is empty.
func PreferredMarkupKind(formats []MarkupKind) MarkupKind {
if len(formats) > 0 {
return formats[0]
}
return MarkupKindPlainText
}
const (
CodeActionKindSourceRemoveUnusedImports CodeActionKind = "source.removeUnusedImports"
CodeActionKindSourceSortImports CodeActionKind = "source.sortImports"
)
const (
// VSDiagnosticTagHiddenInEditor is a Visual Studio-specific DiagnosticTag
// (see Microsoft.VisualStudio.LanguageServer.Protocol.Extensions.VSDiagnosticTags)
// indicating the diagnostic should not be rendered with a squiggle in the
// editor. When combined with DiagnosticTagUnnecessary, Visual Studio
// renders the affected code as faded-out text (the typical "unused
// variable" appearance). VS extension tags use sentinel values near
// int32.MaxValue to avoid colliding with future standard DiagnosticTag
// additions. Only emit when the client advertises
// _vs_supportsVisualStudioExtensions.
VSDiagnosticTagHiddenInEditor DiagnosticTag = 2147483641 // int32.MaxValue - 6
)