-
Notifications
You must be signed in to change notification settings - Fork 12.7k
/
Copy pathshims.ts
1244 lines (1053 loc) · 53.4 KB
/
shims.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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/// <reference path='services.ts' />
/* @internal */
let debugObjectHost: { CollectGarbage(): void } = (function (this: any) { return this; })();
// We need to use 'null' to interface with the managed side.
/* tslint:disable:no-null-keyword */
/* tslint:disable:no-in-operator */
/* @internal */
namespace ts {
export interface ScriptSnapshotShim {
/** Gets a portion of the script snapshot specified by [start, end). */
getText(start: number, end: number): string;
/** Gets the length of this script snapshot. */
getLength(): number;
/**
* Returns a JSON-encoded value of the type:
* { span: { start: number; length: number }; newLength: number }
*
* Or undefined value if there was no change.
*/
getChangeRange(oldSnapshot: ScriptSnapshotShim): string | undefined;
/** Releases all resources held by this script snapshot */
dispose?(): void;
}
export interface Logger {
log(s: string): void;
trace(s: string): void;
error(s: string): void;
}
/** Public interface of the host of a language service shim instance. */
export interface LanguageServiceShimHost extends Logger {
getCompilationSettings(): string;
/** Returns a JSON-encoded value of the type: string[] */
getScriptFileNames(): string;
getScriptKind?(fileName: string): ScriptKind;
getScriptVersion(fileName: string): string;
getScriptSnapshot(fileName: string): ScriptSnapshotShim;
getLocalizedDiagnosticMessages(): string;
getCancellationToken(): HostCancellationToken;
getCurrentDirectory(): string;
getDirectories(path: string): string;
getDefaultLibFileName(options: string): string;
getNewLine?(): string;
getProjectVersion?(): string;
useCaseSensitiveFileNames?(): boolean;
getTypeRootsVersion?(): number;
readDirectory(rootDir: string, extension: string, basePaths?: string, excludeEx?: string, includeFileEx?: string, includeDirEx?: string, depth?: number): string;
readFile(path: string, encoding?: string): string | undefined;
fileExists(path: string): boolean;
getModuleResolutionsForFile?(fileName: string): string;
getTypeReferenceDirectiveResolutionsForFile?(fileName: string): string;
directoryExists(directoryName: string): boolean;
}
/** Public interface of the core-services host instance used in managed side */
export interface CoreServicesShimHost extends Logger {
directoryExists(directoryName: string): boolean;
fileExists(fileName: string): boolean;
getCurrentDirectory(): string;
getDirectories(path: string): string;
/**
* Returns a JSON-encoded value of the type: string[]
*
* @param exclude A JSON encoded string[] containing the paths to exclude
* when enumerating the directory.
*/
readDirectory(rootDir: string, extension: string, basePaths?: string, excludeEx?: string, includeFileEx?: string, includeDirEx?: string, depth?: number): string;
/**
* Read arbitary text files on disk, i.e. when resolution procedure needs the content of 'package.json' to determine location of bundled typings for node modules
*/
readFile(fileName: string): string | undefined;
realpath?(path: string): string;
trace(s: string): void;
useCaseSensitiveFileNames?(): boolean;
}
///
/// Pre-processing
///
// Note: This is being using by the host (VS) and is marshaled back and forth.
// When changing this make sure the changes are reflected in the managed side as well
export interface IFileReference {
path: string;
position: number;
length: number;
}
/** Public interface of a language service instance shim. */
export interface ShimFactory {
registerShim(shim: Shim): void;
unregisterShim(shim: Shim): void;
}
export interface Shim {
dispose(_dummy: {}): void;
}
export interface LanguageServiceShim extends Shim {
languageService: LanguageService;
dispose(_dummy: {}): void;
refresh(throwOnError: boolean): void;
cleanupSemanticCache(): void;
getSyntacticDiagnostics(fileName: string): string;
getSemanticDiagnostics(fileName: string): string;
getCompilerOptionsDiagnostics(): string;
getSyntacticClassifications(fileName: string, start: number, length: number): string;
getSemanticClassifications(fileName: string, start: number, length: number): string;
getEncodedSyntacticClassifications(fileName: string, start: number, length: number): string;
getEncodedSemanticClassifications(fileName: string, start: number, length: number): string;
getCompletionsAtPosition(fileName: string, position: number): string;
getCompletionEntryDetails(fileName: string, position: number, entryName: string): string;
getQuickInfoAtPosition(fileName: string, position: number): string;
getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): string;
getBreakpointStatementAtPosition(fileName: string, position: number): string;
getSignatureHelpItems(fileName: string, position: number): string;
/**
* Returns a JSON-encoded value of the type:
* { canRename: boolean, localizedErrorMessage: string, displayName: string, fullDisplayName: string, kind: string, kindModifiers: string, triggerSpan: { start; length } }
*/
getRenameInfo(fileName: string, position: number): string;
/**
* Returns a JSON-encoded value of the type:
* { fileName: string, textSpan: { start: number, length: number } }[]
*/
findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): string;
/**
* Returns a JSON-encoded value of the type:
* { fileName: string; textSpan: { start: number; length: number}; kind: string; name: string; containerKind: string; containerName: string }
*
* Or undefined value if no definition can be found.
*/
getDefinitionAtPosition(fileName: string, position: number): string;
/**
* Returns a JSON-encoded value of the type:
* { fileName: string; textSpan: { start: number; length: number}; kind: string; name: string; containerKind: string; containerName: string }
*
* Or undefined value if no definition can be found.
*/
getTypeDefinitionAtPosition(fileName: string, position: number): string;
/**
* Returns a JSON-encoded value of the type:
* { fileName: string; textSpan: { start: number; length: number}; }[]
*/
getImplementationAtPosition(fileName: string, position: number): string;
/**
* Returns a JSON-encoded value of the type:
* { fileName: string; textSpan: { start: number; length: number}; isWriteAccess: boolean, isDefinition?: boolean }[]
*/
getReferencesAtPosition(fileName: string, position: number): string;
/**
* Returns a JSON-encoded value of the type:
* { definition: <encoded>; references: <encoded>[] }[]
*/
findReferences(fileName: string, position: number): string;
/**
* @deprecated
* Returns a JSON-encoded value of the type:
* { fileName: string; textSpan: { start: number; length: number}; isWriteAccess: boolean }[]
*/
getOccurrencesAtPosition(fileName: string, position: number): string;
/**
* Returns a JSON-encoded value of the type:
* { fileName: string; highlights: { start: number; length: number, isDefinition: boolean }[] }[]
*
* @param fileToSearch A JSON encoded string[] containing the file names that should be
* considered when searching.
*/
getDocumentHighlights(fileName: string, position: number, filesToSearch: string): string;
/**
* Returns a JSON-encoded value of the type:
* { name: string; kind: string; kindModifiers: string; containerName: string; containerKind: string; matchKind: string; fileName: string; textSpan: { start: number; length: number}; } [] = [];
*/
getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string): string;
/**
* Returns a JSON-encoded value of the type:
* { text: string; kind: string; kindModifiers: string; bolded: boolean; grayed: boolean; indent: number; spans: { start: number; length: number; }[]; childItems: <recursive use of this type>[] } [] = [];
*/
getNavigationBarItems(fileName: string): string;
/** Returns a JSON-encoded value of the type ts.NavigationTree. */
getNavigationTree(fileName: string): string;
/**
* Returns a JSON-encoded value of the type:
* { textSpan: { start: number, length: number }; hintSpan: { start: number, length: number }; bannerText: string; autoCollapse: boolean } [] = [];
*/
getOutliningSpans(fileName: string): string;
getTodoComments(fileName: string, todoCommentDescriptors: string): string;
getBraceMatchingAtPosition(fileName: string, position: number): string;
getIndentationAtPosition(fileName: string, position: number, options: string/*Services.EditorOptions*/): string;
getFormattingEditsForRange(fileName: string, start: number, end: number, options: string/*Services.FormatCodeOptions*/): string;
getFormattingEditsForDocument(fileName: string, options: string/*Services.FormatCodeOptions*/): string;
getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: string/*Services.FormatCodeOptions*/): string;
/**
* Returns JSON-encoded value of the type TextInsertion.
*/
getDocCommentTemplateAtPosition(fileName: string, position: number): string;
/**
* Returns JSON-encoded boolean to indicate whether we should support brace location
* at the current position.
* E.g. we don't want brace completion inside string-literals, comments, etc.
*/
isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): string;
/**
* Returns a JSON-encoded TextSpan | undefined indicating the range of the enclosing comment, if it exists.
*/
getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): string;
getEmitOutput(fileName: string): string;
getEmitOutputObject(fileName: string): EmitOutput;
}
export interface ClassifierShim extends Shim {
getEncodedLexicalClassifications(text: string, lexState: EndOfLineState, syntacticClassifierAbsent?: boolean): string;
getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent?: boolean): string;
}
export interface CoreServicesShim extends Shim {
getAutomaticTypeDirectiveNames(compilerOptionsJson: string): string;
getPreProcessedFileInfo(fileName: string, sourceText: IScriptSnapshot): string;
getTSConfigFileInfo(fileName: string, sourceText: IScriptSnapshot): string;
getDefaultCompilationSettings(): string;
discoverTypings(discoverTypingsJson: string): string;
}
function logInternalError(logger: Logger, err: Error) {
if (logger) {
logger.log("*INTERNAL ERROR* - Exception in typescript services: " + err.message);
}
}
class ScriptSnapshotShimAdapter implements IScriptSnapshot {
constructor(private scriptSnapshotShim: ScriptSnapshotShim) {
}
public getText(start: number, end: number): string {
return this.scriptSnapshotShim.getText(start, end);
}
public getLength(): number {
return this.scriptSnapshotShim.getLength();
}
public getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange {
const oldSnapshotShim = <ScriptSnapshotShimAdapter>oldSnapshot;
const encoded = this.scriptSnapshotShim.getChangeRange(oldSnapshotShim.scriptSnapshotShim);
if (encoded === null) {
return null;
}
const decoded: { span: { start: number; length: number; }; newLength: number; } = JSON.parse(encoded);
return createTextChangeRange(
createTextSpan(decoded.span.start, decoded.span.length), decoded.newLength);
}
public dispose(): void {
// if scriptSnapshotShim is a COM object then property check becomes method call with no arguments
// 'in' does not have this effect
if ("dispose" in this.scriptSnapshotShim) {
this.scriptSnapshotShim.dispose();
}
}
}
export class LanguageServiceShimHostAdapter implements LanguageServiceHost {
private files: string[];
private loggingEnabled = false;
private tracingEnabled = false;
public resolveModuleNames: (moduleName: string[], containingFile: string) => ResolvedModuleFull[];
public resolveTypeReferenceDirectives: (typeDirectiveNames: string[], containingFile: string) => ResolvedTypeReferenceDirective[];
public directoryExists: (directoryName: string) => boolean;
constructor(private shimHost: LanguageServiceShimHost) {
// if shimHost is a COM object then property check will become method call with no arguments.
// 'in' does not have this effect.
if ("getModuleResolutionsForFile" in this.shimHost) {
this.resolveModuleNames = (moduleNames: string[], containingFile: string) => {
const resolutionsInFile = <MapLike<string>>JSON.parse(this.shimHost.getModuleResolutionsForFile(containingFile));
return map(moduleNames, name => {
const result = getProperty(resolutionsInFile, name);
return result ? { resolvedFileName: result, extension: extensionFromPath(result), isExternalLibraryImport: false } : undefined;
});
};
}
if ("directoryExists" in this.shimHost) {
this.directoryExists = directoryName => this.shimHost.directoryExists(directoryName);
}
if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) {
this.resolveTypeReferenceDirectives = (typeDirectiveNames: string[], containingFile: string) => {
const typeDirectivesForFile = <MapLike<ResolvedTypeReferenceDirective>>JSON.parse(this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile));
return map(typeDirectiveNames, name => getProperty(typeDirectivesForFile, name));
};
}
}
public log(s: string): void {
if (this.loggingEnabled) {
this.shimHost.log(s);
}
}
public trace(s: string): void {
if (this.tracingEnabled) {
this.shimHost.trace(s);
}
}
public error(s: string): void {
this.shimHost.error(s);
}
public getProjectVersion(): string {
if (!this.shimHost.getProjectVersion) {
// shimmed host does not support getProjectVersion
return undefined;
}
return this.shimHost.getProjectVersion();
}
public getTypeRootsVersion(): number {
if (!this.shimHost.getTypeRootsVersion) {
return 0;
}
return this.shimHost.getTypeRootsVersion();
}
public useCaseSensitiveFileNames(): boolean {
return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false;
}
public getCompilationSettings(): CompilerOptions {
const settingsJson = this.shimHost.getCompilationSettings();
if (settingsJson === null || settingsJson === "") {
throw Error("LanguageServiceShimHostAdapter.getCompilationSettings: empty compilationSettings");
}
const compilerOptions = <CompilerOptions>JSON.parse(settingsJson);
// permit language service to handle all files (filtering should be performed on the host side)
compilerOptions.allowNonTsExtensions = true;
return compilerOptions;
}
public getScriptFileNames(): string[] {
const encoded = this.shimHost.getScriptFileNames();
return this.files = JSON.parse(encoded);
}
public getScriptSnapshot(fileName: string): IScriptSnapshot {
const scriptSnapshot = this.shimHost.getScriptSnapshot(fileName);
return scriptSnapshot && new ScriptSnapshotShimAdapter(scriptSnapshot);
}
public getScriptKind(fileName: string): ScriptKind {
if ("getScriptKind" in this.shimHost) {
return this.shimHost.getScriptKind(fileName);
}
else {
return ScriptKind.Unknown;
}
}
public getScriptVersion(fileName: string): string {
return this.shimHost.getScriptVersion(fileName);
}
public getLocalizedDiagnosticMessages() {
const diagnosticMessagesJson = this.shimHost.getLocalizedDiagnosticMessages();
if (diagnosticMessagesJson === null || diagnosticMessagesJson === "") {
return null;
}
try {
return JSON.parse(diagnosticMessagesJson);
}
catch (e) {
this.log(e.description || "diagnosticMessages.generated.json has invalid JSON format");
return null;
}
}
public getCancellationToken(): HostCancellationToken {
const hostCancellationToken = this.shimHost.getCancellationToken();
return new ThrottledCancellationToken(hostCancellationToken);
}
public getCurrentDirectory(): string {
return this.shimHost.getCurrentDirectory();
}
public getDirectories(path: string): string[] {
return JSON.parse(this.shimHost.getDirectories(path));
}
public getDefaultLibFileName(options: CompilerOptions): string {
return this.shimHost.getDefaultLibFileName(JSON.stringify(options));
}
public readDirectory(path: string, extensions?: ReadonlyArray<string>, exclude?: string[], include?: string[], depth?: number): string[] {
const pattern = getFileMatcherPatterns(path, exclude, include,
this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory());
return JSON.parse(this.shimHost.readDirectory(
path,
JSON.stringify(extensions),
JSON.stringify(pattern.basePaths),
pattern.excludePattern,
pattern.includeFilePattern,
pattern.includeDirectoryPattern,
depth
));
}
public readFile(path: string, encoding?: string): string | undefined {
return this.shimHost.readFile(path, encoding);
}
public fileExists(path: string): boolean {
return this.shimHost.fileExists(path);
}
}
export class CoreServicesShimHostAdapter implements ParseConfigHost, ModuleResolutionHost, JsTyping.TypingResolutionHost {
public directoryExists: (directoryName: string) => boolean;
public realpath: (path: string) => string;
public useCaseSensitiveFileNames: boolean;
constructor(private shimHost: CoreServicesShimHost) {
this.useCaseSensitiveFileNames = this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false;
if ("directoryExists" in this.shimHost) {
this.directoryExists = directoryName => this.shimHost.directoryExists(directoryName);
}
if ("realpath" in this.shimHost) {
this.realpath = path => this.shimHost.realpath(path);
}
}
public readDirectory(rootDir: string, extensions: ReadonlyArray<string>, exclude: ReadonlyArray<string>, include: ReadonlyArray<string>, depth?: number): string[] {
const pattern = getFileMatcherPatterns(rootDir, exclude, include,
this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory());
return JSON.parse(this.shimHost.readDirectory(
rootDir,
JSON.stringify(extensions),
JSON.stringify(pattern.basePaths),
pattern.excludePattern,
pattern.includeFilePattern,
pattern.includeDirectoryPattern,
depth
));
}
public fileExists(fileName: string): boolean {
return this.shimHost.fileExists(fileName);
}
public readFile(fileName: string): string | undefined {
return this.shimHost.readFile(fileName);
}
public getDirectories(path: string): string[] {
return JSON.parse(this.shimHost.getDirectories(path));
}
}
function simpleForwardCall(logger: Logger, actionDescription: string, action: () => {}, logPerformance: boolean): {} {
let start: number;
if (logPerformance) {
logger.log(actionDescription);
start = timestamp();
}
const result = action();
if (logPerformance) {
const end = timestamp();
logger.log(`${actionDescription} completed in ${end - start} msec`);
if (isString(result)) {
let str = result;
if (str.length > 128) {
str = str.substring(0, 128) + "...";
}
logger.log(` result.length=${str.length}, result='${JSON.stringify(str)}'`);
}
}
return result;
}
function forwardJSONCall(logger: Logger, actionDescription: string, action: () => {}, logPerformance: boolean): string {
return <string>forwardCall(logger, actionDescription, /*returnJson*/ true, action, logPerformance);
}
function forwardCall<T>(logger: Logger, actionDescription: string, returnJson: boolean, action: () => T, logPerformance: boolean): T | string {
try {
const result = simpleForwardCall(logger, actionDescription, action, logPerformance);
return returnJson ? JSON.stringify({ result }) : result as T;
}
catch (err) {
if (err instanceof OperationCanceledException) {
return JSON.stringify({ canceled: true });
}
logInternalError(logger, err);
err.description = actionDescription;
return JSON.stringify({ error: err });
}
}
class ShimBase implements Shim {
constructor(private factory: ShimFactory) {
factory.registerShim(this);
}
public dispose(_dummy: {}): void {
this.factory.unregisterShim(this);
}
}
interface RealizedDiagnostic {
message: string;
start: number;
length: number;
category: string;
code: number;
}
export function realizeDiagnostics(diagnostics: ReadonlyArray<Diagnostic>, newLine: string): RealizedDiagnostic[] {
return diagnostics.map(d => realizeDiagnostic(d, newLine));
}
function realizeDiagnostic(diagnostic: Diagnostic, newLine: string): RealizedDiagnostic {
return {
message: flattenDiagnosticMessageText(diagnostic.messageText, newLine),
start: diagnostic.start,
length: diagnostic.length,
/// TODO: no need for the tolowerCase call
category: DiagnosticCategory[diagnostic.category].toLowerCase(),
code: diagnostic.code
};
}
class LanguageServiceShimObject extends ShimBase implements LanguageServiceShim {
private logger: Logger;
private logPerformance = false;
constructor(factory: ShimFactory,
private host: LanguageServiceShimHost,
public languageService: LanguageService) {
super(factory);
this.logger = this.host;
}
public forwardJSONCall(actionDescription: string, action: () => {}): string {
return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance);
}
/// DISPOSE
/**
* Ensure (almost) deterministic release of internal Javascript resources when
* some external native objects holds onto us (e.g. Com/Interop).
*/
public dispose(dummy: {}): void {
this.logger.log("dispose()");
this.languageService.dispose();
this.languageService = null;
// force a GC
if (debugObjectHost && debugObjectHost.CollectGarbage) {
debugObjectHost.CollectGarbage();
this.logger.log("CollectGarbage()");
}
this.logger = null;
super.dispose(dummy);
}
/// REFRESH
/**
* Update the list of scripts known to the compiler
*/
public refresh(throwOnError: boolean): void {
this.forwardJSONCall(
`refresh(${throwOnError})`,
() => null
);
}
public cleanupSemanticCache(): void {
this.forwardJSONCall(
"cleanupSemanticCache()",
() => {
this.languageService.cleanupSemanticCache();
return null;
});
}
private realizeDiagnostics(diagnostics: ReadonlyArray<Diagnostic>): { message: string; start: number; length: number; category: string; }[] {
const newLine = getNewLineOrDefaultFromHost(this.host);
return ts.realizeDiagnostics(diagnostics, newLine);
}
public getSyntacticClassifications(fileName: string, start: number, length: number): string {
return this.forwardJSONCall(
`getSyntacticClassifications('${fileName}', ${start}, ${length})`,
() => this.languageService.getSyntacticClassifications(fileName, createTextSpan(start, length))
);
}
public getSemanticClassifications(fileName: string, start: number, length: number): string {
return this.forwardJSONCall(
`getSemanticClassifications('${fileName}', ${start}, ${length})`,
() => this.languageService.getSemanticClassifications(fileName, createTextSpan(start, length))
);
}
public getEncodedSyntacticClassifications(fileName: string, start: number, length: number): string {
return this.forwardJSONCall(
`getEncodedSyntacticClassifications('${fileName}', ${start}, ${length})`,
// directly serialize the spans out to a string. This is much faster to decode
// on the managed side versus a full JSON array.
() => convertClassifications(this.languageService.getEncodedSyntacticClassifications(fileName, createTextSpan(start, length)))
);
}
public getEncodedSemanticClassifications(fileName: string, start: number, length: number): string {
return this.forwardJSONCall(
`getEncodedSemanticClassifications('${fileName}', ${start}, ${length})`,
// directly serialize the spans out to a string. This is much faster to decode
// on the managed side versus a full JSON array.
() => convertClassifications(this.languageService.getEncodedSemanticClassifications(fileName, createTextSpan(start, length)))
);
}
public getSyntacticDiagnostics(fileName: string): string {
return this.forwardJSONCall(
`getSyntacticDiagnostics('${fileName}')`,
() => {
const diagnostics = this.languageService.getSyntacticDiagnostics(fileName);
return this.realizeDiagnostics(diagnostics);
});
}
public getSemanticDiagnostics(fileName: string): string {
return this.forwardJSONCall(
`getSemanticDiagnostics('${fileName}')`,
() => {
const diagnostics = this.languageService.getSemanticDiagnostics(fileName);
return this.realizeDiagnostics(diagnostics);
});
}
public getCompilerOptionsDiagnostics(): string {
return this.forwardJSONCall(
"getCompilerOptionsDiagnostics()",
() => {
const diagnostics = this.languageService.getCompilerOptionsDiagnostics();
return this.realizeDiagnostics(diagnostics);
});
}
/// QUICKINFO
/**
* Computes a string representation of the type at the requested position
* in the active file.
*/
public getQuickInfoAtPosition(fileName: string, position: number): string {
return this.forwardJSONCall(
`getQuickInfoAtPosition('${fileName}', ${position})`,
() => this.languageService.getQuickInfoAtPosition(fileName, position)
);
}
/// NAMEORDOTTEDNAMESPAN
/**
* Computes span information of the name or dotted name at the requested position
* in the active file.
*/
public getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): string {
return this.forwardJSONCall(
`getNameOrDottedNameSpan('${fileName}', ${startPos}, ${endPos})`,
() => this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos)
);
}
/**
* STATEMENTSPAN
* Computes span information of statement at the requested position in the active file.
*/
public getBreakpointStatementAtPosition(fileName: string, position: number): string {
return this.forwardJSONCall(
`getBreakpointStatementAtPosition('${fileName}', ${position})`,
() => this.languageService.getBreakpointStatementAtPosition(fileName, position)
);
}
/// SIGNATUREHELP
public getSignatureHelpItems(fileName: string, position: number): string {
return this.forwardJSONCall(
`getSignatureHelpItems('${fileName}', ${position})`,
() => this.languageService.getSignatureHelpItems(fileName, position)
);
}
/// GOTO DEFINITION
/**
* Computes the definition location and file for the symbol
* at the requested position.
*/
public getDefinitionAtPosition(fileName: string, position: number): string {
return this.forwardJSONCall(
`getDefinitionAtPosition('${fileName}', ${position})`,
() => this.languageService.getDefinitionAtPosition(fileName, position)
);
}
/// GOTO Type
/**
* Computes the definition location of the type of the symbol
* at the requested position.
*/
public getTypeDefinitionAtPosition(fileName: string, position: number): string {
return this.forwardJSONCall(
`getTypeDefinitionAtPosition('${fileName}', ${position})`,
() => this.languageService.getTypeDefinitionAtPosition(fileName, position)
);
}
/// GOTO Implementation
/**
* Computes the implementation location of the symbol
* at the requested position.
*/
public getImplementationAtPosition(fileName: string, position: number): string {
return this.forwardJSONCall(
`getImplementationAtPosition('${fileName}', ${position})`,
() => this.languageService.getImplementationAtPosition(fileName, position)
);
}
public getRenameInfo(fileName: string, position: number): string {
return this.forwardJSONCall(
`getRenameInfo('${fileName}', ${position})`,
() => this.languageService.getRenameInfo(fileName, position)
);
}
public findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): string {
return this.forwardJSONCall(
`findRenameLocations('${fileName}', ${position}, ${findInStrings}, ${findInComments})`,
() => this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments)
);
}
/// GET BRACE MATCHING
public getBraceMatchingAtPosition(fileName: string, position: number): string {
return this.forwardJSONCall(
`getBraceMatchingAtPosition('${fileName}', ${position})`,
() => this.languageService.getBraceMatchingAtPosition(fileName, position)
);
}
public isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): string {
return this.forwardJSONCall(
`isValidBraceCompletionAtPosition('${fileName}', ${position}, ${openingBrace})`,
() => this.languageService.isValidBraceCompletionAtPosition(fileName, position, openingBrace)
);
}
public getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): string {
return this.forwardJSONCall(
`getSpanOfEnclosingComment('${fileName}', ${position})`,
() => this.languageService.getSpanOfEnclosingComment(fileName, position, onlyMultiLine)
);
}
/// GET SMART INDENT
public getIndentationAtPosition(fileName: string, position: number, options: string /*Services.EditorOptions*/): string {
return this.forwardJSONCall(
`getIndentationAtPosition('${fileName}', ${position})`,
() => {
const localOptions: EditorOptions = JSON.parse(options);
return this.languageService.getIndentationAtPosition(fileName, position, localOptions);
});
}
/// GET REFERENCES
public getReferencesAtPosition(fileName: string, position: number): string {
return this.forwardJSONCall(
`getReferencesAtPosition('${fileName}', ${position})`,
() => this.languageService.getReferencesAtPosition(fileName, position)
);
}
public findReferences(fileName: string, position: number): string {
return this.forwardJSONCall(
`findReferences('${fileName}', ${position})`,
() => this.languageService.findReferences(fileName, position)
);
}
public getOccurrencesAtPosition(fileName: string, position: number): string {
return this.forwardJSONCall(
`getOccurrencesAtPosition('${fileName}', ${position})`,
() => this.languageService.getOccurrencesAtPosition(fileName, position)
);
}
public getDocumentHighlights(fileName: string, position: number, filesToSearch: string): string {
return this.forwardJSONCall(
`getDocumentHighlights('${fileName}', ${position})`,
() => {
const results = this.languageService.getDocumentHighlights(fileName, position, JSON.parse(filesToSearch));
// workaround for VS document highlighting issue - keep only items from the initial file
const normalizedName = normalizeSlashes(fileName).toLowerCase();
return filter(results, r => normalizeSlashes(r.fileName).toLowerCase() === normalizedName);
});
}
/// COMPLETION LISTS
/**
* Get a string based representation of the completions
* to provide at the given source position and providing a member completion
* list if requested.
*/
public getCompletionsAtPosition(fileName: string, position: number) {
return this.forwardJSONCall(
`getCompletionsAtPosition('${fileName}', ${position})`,
() => this.languageService.getCompletionsAtPosition(fileName, position)
);
}
/** Get a string based representation of a completion list entry details */
public getCompletionEntryDetails(fileName: string, position: number, entryName: string) {
return this.forwardJSONCall(
`getCompletionEntryDetails('${fileName}', ${position}, '${entryName}')`,
() => this.languageService.getCompletionEntryDetails(fileName, position, entryName)
);
}
public getFormattingEditsForRange(fileName: string, start: number, end: number, options: string/*Services.FormatCodeOptions*/): string {
return this.forwardJSONCall(
`getFormattingEditsForRange('${fileName}', ${start}, ${end})`,
() => {
const localOptions: ts.FormatCodeOptions = JSON.parse(options);
return this.languageService.getFormattingEditsForRange(fileName, start, end, localOptions);
});
}
public getFormattingEditsForDocument(fileName: string, options: string/*Services.FormatCodeOptions*/): string {
return this.forwardJSONCall(
`getFormattingEditsForDocument('${fileName}')`,
() => {
const localOptions: ts.FormatCodeOptions = JSON.parse(options);
return this.languageService.getFormattingEditsForDocument(fileName, localOptions);
});
}
public getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: string/*Services.FormatCodeOptions*/): string {
return this.forwardJSONCall(
`getFormattingEditsAfterKeystroke('${fileName}', ${position}, '${key}')`,
() => {
const localOptions: ts.FormatCodeOptions = JSON.parse(options);
return this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions);
});
}
public getDocCommentTemplateAtPosition(fileName: string, position: number): string {
return this.forwardJSONCall(
`getDocCommentTemplateAtPosition('${fileName}', ${position})`,
() => this.languageService.getDocCommentTemplateAtPosition(fileName, position)
);
}
/// NAVIGATE TO
/** Return a list of symbols that are interesting to navigate to */
public getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string): string {
return this.forwardJSONCall(
`getNavigateToItems('${searchValue}', ${maxResultCount}, ${fileName})`,
() => this.languageService.getNavigateToItems(searchValue, maxResultCount, fileName)
);
}
public getNavigationBarItems(fileName: string): string {
return this.forwardJSONCall(
`getNavigationBarItems('${fileName}')`,
() => this.languageService.getNavigationBarItems(fileName)
);
}
public getNavigationTree(fileName: string): string {
return this.forwardJSONCall(
`getNavigationTree('${fileName}')`,
() => this.languageService.getNavigationTree(fileName)
);
}
public getOutliningSpans(fileName: string): string {
return this.forwardJSONCall(
`getOutliningSpans('${fileName}')`,
() => this.languageService.getOutliningSpans(fileName)
);
}
public getTodoComments(fileName: string, descriptors: string): string {
return this.forwardJSONCall(
`getTodoComments('${fileName}')`,
() => this.languageService.getTodoComments(fileName, JSON.parse(descriptors))
);
}
/// Emit
public getEmitOutput(fileName: string): string {
return this.forwardJSONCall(
`getEmitOutput('${fileName}')`,
() => this.languageService.getEmitOutput(fileName)
);
}
public getEmitOutputObject(fileName: string): EmitOutput {
return forwardCall(
this.logger,
`getEmitOutput('${fileName}')`,
/*returnJson*/ false,
() => this.languageService.getEmitOutput(fileName),
this.logPerformance) as EmitOutput;
}
}
function convertClassifications(classifications: Classifications): { spans: string, endOfLineState: EndOfLineState } {
return { spans: classifications.spans.join(","), endOfLineState: classifications.endOfLineState };
}
class ClassifierShimObject extends ShimBase implements ClassifierShim {
public classifier: Classifier;
private logPerformance = false;