-
-
Notifications
You must be signed in to change notification settings - Fork 599
/
Copy pathjavascript.ts
507 lines (473 loc) · 16.7 KB
/
javascript.ts
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
import { LanguageModelCache, getLanguageModelCache } from '../languageModelCache';
import {
SymbolInformation,
SymbolKind,
CompletionItem,
Location,
SignatureHelp,
SignatureInformation,
ParameterInformation,
Definition,
TextEdit,
TextDocument,
Diagnostic,
DiagnosticSeverity,
Range,
CompletionItemKind,
Hover,
MarkedString,
DocumentHighlight,
DocumentHighlightKind,
CompletionList,
Position,
FormattingOptions
} from 'vscode-languageserver-types';
import { LanguageMode } from '../languageModes';
import { VueDocumentRegions, LanguageRange } from '../embeddedSupport';
import { getServiceHost } from './serviceHost';
import { findComponents, ComponentInfo } from './findComponents';
import { prettierify, prettierEslintify } from '../../utils/prettier';
import { getFileFsPath, getFilePath } from '../../utils/paths';
import Uri from 'vscode-uri';
import * as ts from 'typescript';
import * as _ from 'lodash';
import { nullMode, NULL_SIGNATURE, NULL_COMPLETION } from '../nullMode';
export interface ScriptMode extends LanguageMode {
findComponents(document: TextDocument): ComponentInfo[];
}
export function getJavascriptMode(
documentRegions: LanguageModelCache<VueDocumentRegions>,
workspacePath: string | null | undefined
): ScriptMode {
if (!workspacePath) {
return { ...nullMode, findComponents: () => [] };
}
const jsDocuments = getLanguageModelCache(10, 60, document => {
const vueDocument = documentRegions.get(document);
return vueDocument.getEmbeddedDocumentByType('script');
});
const regionStart = getLanguageModelCache(10, 60, document => {
const vueDocument = documentRegions.get(document);
return vueDocument.getLanguageRangeByType('script');
});
const serviceHost = getServiceHost(workspacePath, jsDocuments);
const { updateCurrentTextDocument, getScriptDocByFsPath } = serviceHost;
let config: any = {};
return {
getId() {
return 'javascript';
},
configure(c) {
config = c;
},
doValidation(doc: TextDocument): Diagnostic[] {
const { scriptDoc, service } = updateCurrentTextDocument(doc);
if (!languageServiceIncludesFile(service, doc.uri)) {
return [];
}
const fileFsPath = getFileFsPath(doc.uri);
const diagnostics = [
...service.getSyntacticDiagnostics(fileFsPath),
...service.getSemanticDiagnostics(fileFsPath)
];
return diagnostics.map(diag => {
// syntactic/semantic diagnostic always has start and length
// so we can safely cast diag to TextSpan
return {
range: convertRange(scriptDoc, diag as ts.TextSpan),
severity: DiagnosticSeverity.Error,
message: ts.flattenDiagnosticMessageText(diag.messageText, '\n')
};
});
},
doComplete(doc: TextDocument, position: Position): CompletionList {
const { scriptDoc, service } = updateCurrentTextDocument(doc);
if (!languageServiceIncludesFile(service, doc.uri)) {
return { isIncomplete: false, items: [] };
}
const fileFsPath = getFileFsPath(doc.uri);
const offset = scriptDoc.offsetAt(position);
const completions = service.getCompletionsAtPosition(
fileFsPath,
offset,
{
includeExternalModuleExports: _.get(config, ['vetur', 'completion', 'autoImport']),
includeInsertTextCompletions: false
}
);
if (!completions) {
return { isIncomplete: false, items: [] };
}
const entries = completions.entries.filter(entry => entry.name !== '__vueEditorBridge');
return {
isIncomplete: false,
items: entries.map((entry, index) => {
const range = entry.replacementSpan && convertRange(scriptDoc, entry.replacementSpan);
return {
uri: doc.uri,
position,
label: entry.name,
sortText: entry.sortText + index,
kind: convertKind(entry.kind),
textEdit: range && TextEdit.replace(range, entry.name),
data: {
// data used for resolving item details (see 'doResolve')
languageId: scriptDoc.languageId,
uri: doc.uri,
offset,
source: entry.source
}
};
})
};
},
doResolve(doc: TextDocument, item: CompletionItem): CompletionItem {
const { service } = updateCurrentTextDocument(doc);
if (!languageServiceIncludesFile(service, doc.uri)) {
return NULL_COMPLETION;
}
const fileFsPath = getFileFsPath(doc.uri);
const details = service.getCompletionEntryDetails(
fileFsPath,
item.data.offset,
item.label,
/*formattingOption*/ {},
item.data.source
);
if (details) {
item.detail = ts.displayPartsToString(details.displayParts);
item.documentation = ts.displayPartsToString(details.documentation);
if (details.codeActions && config.vetur.completion.autoImport) {
const textEdits = convertCodeAction(doc, details.codeActions, regionStart);
item.additionalTextEdits = textEdits;
}
delete item.data;
}
return item;
},
doHover(doc: TextDocument, position: Position): Hover {
const { scriptDoc, service } = updateCurrentTextDocument(doc);
if (!languageServiceIncludesFile(service, doc.uri)) {
return { contents: [] };
}
const fileFsPath = getFileFsPath(doc.uri);
const info = service.getQuickInfoAtPosition(fileFsPath, scriptDoc.offsetAt(position));
if (info) {
const display = ts.displayPartsToString(info.displayParts);
const doc = ts.displayPartsToString(info.documentation);
const markedContents: MarkedString[] = [{ language: 'ts', value: display }];
if (doc) {
markedContents.unshift(doc, '\n');
}
return {
range: convertRange(scriptDoc, info.textSpan),
contents: markedContents
};
}
return { contents: [] };
},
doSignatureHelp(doc: TextDocument, position: Position): SignatureHelp {
const { scriptDoc, service } = updateCurrentTextDocument(doc);
if (!languageServiceIncludesFile(service, doc.uri)) {
return NULL_SIGNATURE;
}
const fileFsPath = getFileFsPath(doc.uri);
const signHelp = service.getSignatureHelpItems(fileFsPath, scriptDoc.offsetAt(position));
if (!signHelp) {
return NULL_SIGNATURE;
}
const ret: SignatureHelp = {
activeSignature: signHelp.selectedItemIndex,
activeParameter: signHelp.argumentIndex,
signatures: []
};
signHelp.items.forEach(item => {
const signature: SignatureInformation = {
label: '',
documentation: undefined,
parameters: []
};
signature.label += ts.displayPartsToString(item.prefixDisplayParts);
item.parameters.forEach((p, i, a) => {
const label = ts.displayPartsToString(p.displayParts);
const parameter: ParameterInformation = {
label,
documentation: ts.displayPartsToString(p.documentation)
};
signature.label += label;
signature.parameters!.push(parameter);
if (i < a.length - 1) {
signature.label += ts.displayPartsToString(item.separatorDisplayParts);
}
});
signature.label += ts.displayPartsToString(item.suffixDisplayParts);
ret.signatures.push(signature);
});
return ret;
},
findDocumentHighlight(doc: TextDocument, position: Position): DocumentHighlight[] {
const { scriptDoc, service } = updateCurrentTextDocument(doc);
if (!languageServiceIncludesFile(service, doc.uri)) {
return [];
}
const fileFsPath = getFileFsPath(doc.uri);
const occurrences = service.getOccurrencesAtPosition(fileFsPath, scriptDoc.offsetAt(position));
if (occurrences) {
return occurrences.map(entry => {
return {
range: convertRange(scriptDoc, entry.textSpan),
kind: entry.isWriteAccess
? DocumentHighlightKind.Write
: DocumentHighlightKind.Text
};
});
}
return [];
},
findDocumentSymbols(doc: TextDocument): SymbolInformation[] {
const { scriptDoc, service } = updateCurrentTextDocument(doc);
if (!languageServiceIncludesFile(service, doc.uri)) {
return [];
}
const fileFsPath = getFileFsPath(doc.uri);
const items = service.getNavigationBarItems(fileFsPath);
if (!items) {
return [];
}
const result: SymbolInformation[] = [];
const existing: { [k: string]: boolean } = {};
const collectSymbols = (item: ts.NavigationBarItem, containerLabel?: string) => {
const sig = item.text + item.kind + item.spans[0].start;
if (item.kind !== 'script' && !existing[sig]) {
const symbol: SymbolInformation = {
name: item.text,
kind: convertSymbolKind(item.kind),
location: {
uri: doc.uri,
range: convertRange(scriptDoc, item.spans[0])
},
containerName: containerLabel
};
existing[sig] = true;
result.push(symbol);
containerLabel = item.text;
}
if (item.childItems && item.childItems.length > 0) {
for (const child of item.childItems) {
collectSymbols(child, containerLabel);
}
}
};
items.forEach(item => collectSymbols(item));
return result;
},
findDefinition(doc: TextDocument, position: Position): Definition {
const { scriptDoc, service } = updateCurrentTextDocument(doc);
if (!languageServiceIncludesFile(service, doc.uri)) {
return [];
}
const fileFsPath = getFileFsPath(doc.uri);
const definitions = service.getDefinitionAtPosition(fileFsPath, scriptDoc.offsetAt(position));
if (!definitions) {
return [];
}
const definitionResults: Definition = [];
const program = service.getProgram();
definitions.forEach(d => {
const sourceFile = program.getSourceFile(d.fileName);
const definitionTargetDoc = TextDocument.create(d.fileName, 'vue', 0, sourceFile!.getText());
definitionResults.push({
uri: Uri.file(d.fileName).toString(),
range: convertRange(definitionTargetDoc, d.textSpan)
});
});
return definitionResults;
},
findReferences(doc: TextDocument, position: Position): Location[] {
const { scriptDoc, service } = updateCurrentTextDocument(doc);
if (!languageServiceIncludesFile(service, doc.uri)) {
return [];
}
const fileFsPath = getFileFsPath(doc.uri);
const references = service.getReferencesAtPosition(fileFsPath, scriptDoc.offsetAt(position));
if (!references) {
return [];
}
const referenceResults: Location[] = [];
references.forEach(r => {
const referenceTargetDoc = getScriptDocByFsPath(fileFsPath);
if (referenceTargetDoc) {
referenceResults.push({
uri: Uri.file(r.fileName).toString(),
range: convertRange(referenceTargetDoc, r.textSpan)
});
}
});
return referenceResults;
},
format(doc: TextDocument, range: Range, formatParams: FormattingOptions): TextEdit[] {
const { scriptDoc, service } = updateCurrentTextDocument(doc);
const defaultFormatter =
scriptDoc.languageId === 'javascript'
? config.vetur.format.defaultFormatter.js
: config.vetur.format.defaultFormatter.ts;
if (defaultFormatter === 'none') {
return [];
}
const needIndent = config.vetur.format.scriptInitialIndent;
const parser = scriptDoc.languageId === 'javascript' ? 'babylon' : 'typescript';
if (defaultFormatter === 'prettier') {
const code = scriptDoc.getText();
const filePath = getFileFsPath(scriptDoc.uri);
if (config.prettier.eslintIntegration) {
return prettierEslintify(code, filePath, range, needIndent, formatParams, config.prettier, parser);
} else {
return prettierify(code, filePath, range, needIndent, formatParams, config.prettier, parser);
}
} else {
const initialIndentLevel = needIndent ? 1 : 0;
const formatSettings: ts.FormatCodeSettings =
scriptDoc.languageId === 'javascript' ? config.javascript.format : config.typescript.format;
const convertedFormatSettings = convertOptions(formatSettings, formatParams, initialIndentLevel);
const fileFsPath = getFileFsPath(doc.uri);
const start = scriptDoc.offsetAt(range.start);
const end = scriptDoc.offsetAt(range.end);
const edits = service.getFormattingEditsForRange(fileFsPath, start, end, convertedFormatSettings);
if (!edits) {
return [];
}
const result = [];
for (const edit of edits) {
if (edit.span.start >= start && edit.span.start + edit.span.length <= end) {
result.push({
range: convertRange(scriptDoc, edit.span),
newText: edit.newText
});
}
}
return result;
}
},
findComponents(doc: TextDocument) {
const { service } = updateCurrentTextDocument(doc);
const fileFsPath = getFileFsPath(doc.uri);
return findComponents(service, fileFsPath);
},
onDocumentRemoved(document: TextDocument) {
jsDocuments.onDocumentRemoved(document);
},
dispose() {
serviceHost.getService().dispose();
jsDocuments.dispose();
}
};
}
function languageServiceIncludesFile(ls: ts.LanguageService, documentUri: string): boolean {
const filePaths = ls.getProgram().getRootFileNames();
const filePath = getFilePath(documentUri);
return filePaths.includes(filePath);
}
function convertRange(document: TextDocument, span: ts.TextSpan): Range {
const startPosition = document.positionAt(span.start);
const endPosition = document.positionAt(span.start + span.length);
return Range.create(startPosition, endPosition);
}
function convertKind(kind: ts.ScriptElementKind): CompletionItemKind {
switch (kind) {
case 'primitive type':
case 'keyword':
return CompletionItemKind.Keyword;
case 'var':
case 'local var':
return CompletionItemKind.Variable;
case 'property':
case 'getter':
case 'setter':
return CompletionItemKind.Field;
case 'function':
case 'method':
case 'construct':
case 'call':
case 'index':
return CompletionItemKind.Function;
case 'enum':
return CompletionItemKind.Enum;
case 'module':
return CompletionItemKind.Module;
case 'class':
return CompletionItemKind.Class;
case 'interface':
return CompletionItemKind.Interface;
case 'warning':
return CompletionItemKind.File;
}
return CompletionItemKind.Property;
}
function convertSymbolKind(kind: ts.ScriptElementKind): SymbolKind {
switch (kind) {
case 'var':
case 'local var':
case 'const':
return SymbolKind.Variable;
case 'function':
case 'local function':
return SymbolKind.Function;
case 'enum':
return SymbolKind.Enum;
case 'module':
return SymbolKind.Module;
case 'class':
return SymbolKind.Class;
case 'interface':
return SymbolKind.Interface;
case 'method':
return SymbolKind.Method;
case 'property':
case 'getter':
case 'setter':
return SymbolKind.Property;
}
return SymbolKind.Variable;
}
function convertOptions(
formatSettings: ts.FormatCodeSettings,
options: FormattingOptions,
initialIndentLevel: number
): ts.FormatCodeSettings {
return _.assign(formatSettings, {
convertTabsToSpaces: options.insertSpaces,
tabSize: options.tabSize,
indentSize: options.tabSize,
baseIndentSize: options.tabSize * initialIndentLevel
});
}
function convertCodeAction(
doc: TextDocument,
codeActions: ts.CodeAction[],
regionStart: LanguageModelCache<LanguageRange | undefined>) {
const textEdits: TextEdit[] = [];
for (const action of codeActions) {
for (const change of action.changes) {
textEdits.push(...change.textChanges.map(tc => {
// currently, only import codeAction is available
// change start of doc to start of script region
if (tc.span.start === 0 && tc.span.length === 0) {
const region = regionStart.get(doc);
if (region) {
const line = region.start.line;
return {
range: Range.create(line + 1, 0, line + 1, 0),
newText: tc.newText
};
}
}
return {
range: convertRange(doc, tc.span),
newText: tc.newText
};
}
));
}
}
return textEdits;
}