TypeScript/src/services/shims.ts

1359 lines
61 KiB
TypeScript
Raw Normal View History

2014-07-19 01:55:11 +02:00
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
2014-07-19 01:55:11 +02:00
// 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.
//
2014-07-13 01:04:16 +02:00
/* @internal */
let debugObjectHost: { CollectGarbage(): void } = (function (this: any) { // eslint-disable-line prefer-const
return this;
})();
2016-01-08 05:13:41 +01:00
// We need to use 'null' to interface with the managed side.
/* eslint-disable no-in-operator */
2014-07-25 20:21:17 +02:00
/* @internal */
namespace ts {
2017-11-21 01:43:02 +01:00
interface DiscoverTypingsInfo {
fileNames: string[]; // The file names that belong to the same project.
projectRootPath: string; // The path to the project root directory
safeListPath: string; // The path used to retrieve the safe list
packageNameToTypingLocation: ESMap<string, JsTyping.CachedTyping>; // The map of package names to their cached typing locations and installed versions
2017-11-21 01:43:02 +01:00
typeAcquisition: TypeAcquisition; // Used to customize the type acquisition process
compilerOptions: CompilerOptions; // Used as a source for typing inference
unresolvedImports: readonly string[]; // List of unresolved module ids from imports
typesRegistry: ReadonlyESMap<string, MapLike<string>>; // The map of available typings in npm to maps of TS versions to their latest supported versions
2017-11-21 01:43:02 +01:00
}
export interface ScriptSnapshotShim {
2014-09-25 00:27:17 +02:00
/** Gets a portion of the script snapshot specified by [start, end). */
2014-07-13 01:04:16 +02:00
getText(start: number, end: number): string;
2014-09-25 00:27:17 +02:00
/** Gets the length of this script snapshot. */
2014-07-13 01:04:16 +02:00
getLength(): number;
2014-09-24 21:55:27 +02:00
/**
2014-09-25 00:27:17 +02:00
* Returns a JSON-encoded value of the type:
2014-09-24 21:55:27 +02:00
* { span: { start: number; length: number }; newLength: number }
*
2014-09-25 00:27:17 +02:00
* Or undefined value if there was no change.
2014-09-24 21:55:27 +02:00
*/
2017-04-05 20:39:59 +02:00
getChangeRange(oldSnapshot: ScriptSnapshotShim): string | undefined;
/** Releases all resources held by this script snapshot */
dispose?(): void;
2014-07-19 01:55:11 +02:00
}
export interface Logger {
log(s: string): void;
trace(s: string): void;
error(s: string): void;
}
2017-04-03 18:32:39 +02:00
/** Public interface of the host of a language service shim instance. */
2014-07-25 01:01:51 +02:00
export interface LanguageServiceShimHost extends Logger {
2014-07-19 01:55:11 +02:00
getCompilationSettings(): string;
2014-09-25 00:27:17 +02:00
/** Returns a JSON-encoded value of the type: string[] */
2014-07-19 01:55:11 +02:00
getScriptFileNames(): string;
getScriptKind?(fileName: string): ScriptKind;
getScriptVersion(fileName: string): string;
getScriptSnapshot(fileName: string): ScriptSnapshotShim;
2014-07-19 01:55:11 +02:00
getLocalizedDiagnosticMessages(): string;
2015-06-18 21:04:26 +02:00
getCancellationToken(): HostCancellationToken;
getCurrentDirectory(): string;
getDirectories(path: string): string;
getDefaultLibFileName(options: string): string;
getNewLine?(): string;
getProjectVersion?(): string;
useCaseSensitiveFileNames?(): boolean;
2015-12-24 09:21:03 +01:00
2016-09-20 01:47:15 +02:00
getTypeRootsVersion?(): number;
2016-08-04 20:10:00 +02:00
readDirectory(rootDir: string, extension: string, basePaths?: string, excludeEx?: string, includeFileEx?: string, includeDirEx?: string, depth?: number): string;
2017-07-14 23:26:13 +02:00
readFile(path: string, encoding?: string): string | undefined;
fileExists(path: string): boolean;
getModuleResolutionsForFile?(fileName: string): string;
getTypeReferenceDirectiveResolutionsForFile?(fileName: string): string;
directoryExists(directoryName: string): boolean;
2014-07-19 01:55:11 +02:00
}
/** 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;
/**
2018-06-29 04:01:46 +02:00
* Read arbitrary text files on disk, i.e. when resolution procedure needs the content of 'package.json' to determine location of bundled typings for node modules
*/
2017-07-14 23:26:13 +02:00
readFile(fileName: string): string | undefined;
realpath?(path: string): string;
2015-11-20 06:33:33 +01:00
trace(s: string): void;
useCaseSensitiveFileNames?(): boolean;
}
2014-10-28 22:45:32 +01:00
///
/// 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 ShimsFileReference {
2014-10-28 22:45:32 +01:00
path: string;
position: number;
length: number;
}
2014-09-24 21:55:27 +02:00
/** Public interface of a language service instance shim. */
export interface ShimFactory {
registerShim(shim: Shim): void;
unregisterShim(shim: Shim): void;
2014-07-19 01:55:11 +02:00
}
export interface Shim {
dispose(_dummy: {}): void;
2014-07-19 01:55:11 +02:00
}
export interface LanguageServiceShim extends Shim {
2014-07-24 20:57:18 +02:00
languageService: LanguageService;
2014-07-19 01:55:11 +02:00
dispose(_dummy: {}): void;
2014-07-19 01:55:11 +02:00
refresh(throwOnError: boolean): void;
cleanupSemanticCache(): void;
getSyntacticDiagnostics(fileName: string): string;
getSemanticDiagnostics(fileName: string): string;
getSuggestionDiagnostics(fileName: string): string;
2014-07-19 01:55:11 +02:00
getCompilerOptionsDiagnostics(): string;
getSyntacticClassifications(fileName: string, start: number, length: number): string;
getSemanticClassifications(fileName: string, start: number, length: number, format?: SemanticClassificationFormat): string;
2015-05-01 02:39:51 +02:00
getEncodedSyntacticClassifications(fileName: string, start: number, length: number): string;
getEncodedSemanticClassifications(fileName: string, start: number, length: number, format?: SemanticClassificationFormat): string;
2021-11-16 01:39:52 +01:00
getCompletionsAtPosition(fileName: string, position: number, preferences: UserPreferences | undefined, formattingSettings: FormatCodeSettings | undefined): string;
getCompletionEntryDetails(fileName: string, position: number, entryName: string, formatOptions: string/*Services.FormatCodeOptions*/ | undefined, source: string | undefined, preferences: UserPreferences | undefined, data: CompletionEntryData | undefined): string;
2014-07-19 01:55:11 +02:00
2014-09-20 00:32:27 +02:00
getQuickInfoAtPosition(fileName: string, position: number): string;
2014-07-19 01:55:11 +02:00
getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): string;
getBreakpointStatementAtPosition(fileName: string, position: number): string;
getSignatureHelpItems(fileName: string, position: number, options: SignatureHelpItemsOptions | undefined): string;
2014-09-24 21:55:27 +02:00
/**
2014-09-25 00:27:17 +02:00
* Returns a JSON-encoded value of the type:
2014-09-24 21:55:27 +02:00
* { canRename: boolean, localizedErrorMessage: string, displayName: string, fullDisplayName: string, kind: string, kindModifiers: string, triggerSpan: { start; length } }
*/
getRenameInfo(fileName: string, position: number, options?: RenameInfoOptions): string;
2019-04-19 01:23:06 +02:00
getSmartSelectionRange(fileName: string, position: number): string;
2014-07-19 01:55:11 +02:00
/**
* Returns a JSON-encoded value of the type:
* { fileName: string, textSpan: { start: number, length: number } }[]
*/
findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean, providePrefixAndSuffixTextForRename?: boolean): string;
2014-09-24 21:55:27 +02:00
/**
2014-09-25 00:27:17 +02:00
* Returns a JSON-encoded value of the type:
2014-09-24 21:55:27 +02:00
* { fileName: string; textSpan: { start: number; length: number}; kind: string; name: string; containerKind: string; containerName: string }
*
2014-09-25 00:27:17 +02:00
* Or undefined value if no definition can be found.
2014-09-24 21:55:27 +02:00
*/
2014-07-19 01:55:11 +02:00
getDefinitionAtPosition(fileName: string, position: number): string;
getDefinitionAndBoundSpan(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;
2016-08-22 22:57:40 +02:00
/**
* Returns a JSON-encoded value of the type:
2016-09-14 02:33:49 +02:00
* { fileName: string; textSpan: { start: number; length: number}; }[]
2016-08-22 22:57:40 +02:00
*/
getImplementationAtPosition(fileName: string, position: number): string;
2014-09-24 21:55:27 +02:00
/**
2014-09-25 00:27:17 +02:00
* Returns a JSON-encoded value of the type:
* { fileName: string; textSpan: { start: number; length: number}; isWriteAccess: boolean, isDefinition?: boolean }[]
2014-09-24 21:55:27 +02:00
*/
2014-07-19 01:55:11 +02:00
getReferencesAtPosition(fileName: string, position: number): string;
/**
* Returns a JSON-encoded value of the type:
* { definition: <encoded>; references: <encoded>[] }[]
*/
findReferences(fileName: string, position: number): string;
2014-07-19 01:55:11 +02:00
/**
* Returns a JSON-encoded value of the type:
* { fileName: string; textSpan: { start: number; length: number}; isWriteAccess: boolean, isDefinition?: boolean }[]
*/
getFileReferences(fileName: string): string;
2014-09-24 21:55:27 +02:00
/**
* @deprecated
2014-09-25 00:27:17 +02:00
* Returns a JSON-encoded value of the type:
2014-09-24 21:55:27 +02:00
* { fileName: string; textSpan: { start: number; length: number}; isWriteAccess: boolean }[]
*/
2014-07-19 01:55:11 +02:00
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;
2014-09-24 21:55:27 +02:00
/**
2014-09-25 00:27:17 +02:00
* Returns a JSON-encoded value of the type:
2014-09-24 21:55:27 +02:00
* { 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;
2014-07-19 01:55:11 +02:00
2014-09-24 21:55:27 +02:00
/**
2014-09-25 00:27:17 +02:00
* Returns a JSON-encoded value of the type:
2014-09-24 21:55:27 +02:00
* { 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;
2014-07-19 01:55:11 +02:00
/** Returns a JSON-encoded value of the type ts.NavigationTree. */
getNavigationTree(fileName: string): string;
2014-09-24 21:55:27 +02:00
/**
2014-09-25 00:27:17 +02:00
* Returns a JSON-encoded value of the type:
2014-09-24 21:55:27 +02:00
* { textSpan: { start: number, length: number }; hintSpan: { start: number, length: number }; bannerText: string; autoCollapse: boolean } [] = [];
*/
getOutliningSpans(fileName: string): string;
getTodoComments(fileName: string, todoCommentDescriptors: string): string;
2014-07-19 01:55:11 +02:00
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;
2014-07-19 01:55:11 +02:00
getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: string/*Services.FormatCodeOptions*/): string;
2015-07-21 03:31:17 +02:00
/**
* Returns JSON-encoded value of the type TextInsertion.
*/
getDocCommentTemplateAtPosition(fileName: string, position: number, options?: DocCommentTemplateOptions): string;
2015-07-14 03:56:38 +02:00
/**
* 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.
*/
2016-06-24 02:36:59 +02:00
isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): string;
/**
2017-06-10 03:02:42 +02:00
* Returns a JSON-encoded TextSpan | undefined indicating the range of the enclosing comment, if it exists.
*/
2017-06-10 03:02:42 +02:00
getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): string;
prepareCallHierarchy(fileName: string, position: number): string;
provideCallHierarchyIncomingCalls(fileName: string, position: number): string;
provideCallHierarchyOutgoingCalls(fileName: string, position: number): string;
Add inlay hints support (#42089) * Add signature arguments label support * Support rest parameters and destruction * make lint * Fix tuple rest parameters * Adjust name styles * Rename to inline hints * Partition inline hints * Adjust range pred * Add function expression like hints * Support configure inline hints * Display hints in single line * Add test suits and tests * Add range tests * Support more hints * Add more options * Fix logical * Add more cases * Support call chains * Rename options * Match lastest protocol * Update protocol changes * Support context value and hover message * Revert "Support context value and hover message" This reverts commit 37a70896337ddd6dd5360d20e7001ed2338a2595. * Revert "Update protocol changes" This reverts commit e5ca31bc30362144c52c1c2512abc553f0c6b869. * Add hover message * Accept baseline * Update src/services/inlineHints.ts Co-authored-by: Daniel Rosenwasser <DanielRosenwasser@users.noreply.github.com> * Update src/services/inlineHints.ts Co-authored-by: Daniel Rosenwasser <DanielRosenwasser@users.noreply.github.com> * Cache across the program * Fix possible undefined * Update protocol changes * Fix missing property * Make lint happy * Avoid call chain hints * I'm bad * Add whitespace before type * Add more tests * Should care about jsdoc * Support complex rest parameter * Avoid module symbol hints * Care about leading comments * Fix CR issues * Avoid changes * Simplify comments contains * Fix CR issues * Accept baseline * Check parameter name before create regex * Rename option * Avoid makers * Skip parens for argument * Fix CR issues * Fix enums * Accept baseline Co-authored-by: Daniel Rosenwasser <DanielRosenwasser@users.noreply.github.com>
2021-06-25 08:06:34 +02:00
provideInlayHints(fileName: string, span: TextSpan, preference: InlayHintsOptions | undefined): string;
2014-07-19 01:55:11 +02:00
getEmitOutput(fileName: string): string;
getEmitOutputObject(fileName: string): EmitOutput;
2020-03-03 01:30:42 +01:00
toggleLineComment(fileName: string, textChange: TextRange): string;
2020-03-03 02:13:15 +01:00
toggleMultilineComment(fileName: string, textChange: TextRange): string;
2020-03-03 01:30:42 +01:00
commentSelection(fileName: string, textChange: TextRange): string;
uncommentSelection(fileName: string, textChange: TextRange): string;
2014-07-13 01:04:16 +02:00
}
export interface ClassifierShim extends Shim {
2015-05-01 02:39:51 +02:00
getEncodedLexicalClassifications(text: string, lexState: EndOfLineState, syntacticClassifierAbsent?: boolean): string;
getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent?: boolean): string;
2014-07-24 20:57:18 +02:00
}
2014-07-19 01:55:11 +02:00
export interface CoreServicesShim extends Shim {
getAutomaticTypeDirectiveNames(compilerOptionsJson: string): string;
getPreProcessedFileInfo(fileName: string, sourceText: IScriptSnapshot): string;
getTSConfigFileInfo(fileName: string, sourceText: IScriptSnapshot): string;
2014-07-24 20:57:18 +02:00
getDefaultCompilationSettings(): string;
discoverTypings(discoverTypingsJson: string): string;
2014-07-24 20:57:18 +02:00
}
2014-07-25 01:01:51 +02:00
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) {
2014-07-13 01:04:16 +02:00
}
public getText(start: number, end: number): string {
return this.scriptSnapshotShim.getText(start, end);
}
public getLength(): number {
return this.scriptSnapshotShim.getLength();
}
Enable '--strictNullChecks' (#22088) * Enable '--strictNullChecks' * Fix API baselines * Make sys.getEnvironmentVariable non-nullable * make properties optional instead of using `| undefined` in thier type * reportDiagnostics should be required * Declare firstAccessor as non-nullable * Make `some` a type guard * Fix `getEnvironmentVariable` definition in tests * Pretend transformFlags are always defined * Fix one more use of sys.getEnvironmentVariable * `requiredResponse` accepts undefined, remove assertions * Mark optional properties as optional instead of using `| undefined` * Mark optional properties as optional instead of using ` | undefined` * Remove unnecessary null assertions * Put the bang on the declaration instead of every use * Make `createMapFromTemplate` require a parameter * Mark `EmitResult.emittedFiles` and `EmitResult.sourceMaps` as optional * Plumb through undefined in emitLsit and EmitExpressionList * `ElementAccessExpression.argumentExpression` can not be `undefined` * Add overloads for `writeTokenText` * Make `shouldWriteSeparatingLineTerminator` argument non-nullable * Make `synthesizedNodeStartsOnNewLine` argument required * `PropertyAssignment.initializer` cannot be undefined * Use one `!` at declaration site instead of on every use site * Capture host in a constant and avoid null assertions * Remove few more unused assertions * Update baselines * Use parameter defaults * Update baselines * Fix lint * Make Symbol#valueDeclaration and Symbol#declarations non-optional to reduce assertions * Make Node#symbol and Type#symbol non-optional to reduce assertions * Make `flags` non-nullable to reduce assertions * Convert some asserts to type guards * Make `isNonLocalAlias` a type guard * Add overload for `getSymbolOfNode` for `Declaration` * Some more `getSymbolOfNode` changes * Push undefined suppression into `typeToTypeNodeHelper` * `NodeBuilderContext.tracker` is never `undefined` * use `Debug.assertDefined` * Remove unnecessary tag * Mark `LiteralType.freshType` and `LiteralTupe.regularType` as required
2018-05-22 23:46:57 +02:00
public getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange | undefined {
const oldSnapshotShim = oldSnapshot as ScriptSnapshotShimAdapter;
2016-01-07 18:16:14 +01:00
const encoded = this.scriptSnapshotShim.getChangeRange(oldSnapshotShim.scriptSnapshotShim);
2019-07-18 09:50:38 +02:00
/* eslint-disable no-null/no-null */
2017-04-05 00:51:13 +02:00
if (encoded === null) {
Enable '--strictNullChecks' (#22088) * Enable '--strictNullChecks' * Fix API baselines * Make sys.getEnvironmentVariable non-nullable * make properties optional instead of using `| undefined` in thier type * reportDiagnostics should be required * Declare firstAccessor as non-nullable * Make `some` a type guard * Fix `getEnvironmentVariable` definition in tests * Pretend transformFlags are always defined * Fix one more use of sys.getEnvironmentVariable * `requiredResponse` accepts undefined, remove assertions * Mark optional properties as optional instead of using `| undefined` * Mark optional properties as optional instead of using ` | undefined` * Remove unnecessary null assertions * Put the bang on the declaration instead of every use * Make `createMapFromTemplate` require a parameter * Mark `EmitResult.emittedFiles` and `EmitResult.sourceMaps` as optional * Plumb through undefined in emitLsit and EmitExpressionList * `ElementAccessExpression.argumentExpression` can not be `undefined` * Add overloads for `writeTokenText` * Make `shouldWriteSeparatingLineTerminator` argument non-nullable * Make `synthesizedNodeStartsOnNewLine` argument required * `PropertyAssignment.initializer` cannot be undefined * Use one `!` at declaration site instead of on every use site * Capture host in a constant and avoid null assertions * Remove few more unused assertions * Update baselines * Use parameter defaults * Update baselines * Fix lint * Make Symbol#valueDeclaration and Symbol#declarations non-optional to reduce assertions * Make Node#symbol and Type#symbol non-optional to reduce assertions * Make `flags` non-nullable to reduce assertions * Convert some asserts to type guards * Make `isNonLocalAlias` a type guard * Add overload for `getSymbolOfNode` for `Declaration` * Some more `getSymbolOfNode` changes * Push undefined suppression into `typeToTypeNodeHelper` * `NodeBuilderContext.tracker` is never `undefined` * use `Debug.assertDefined` * Remove unnecessary tag * Mark `LiteralType.freshType` and `LiteralTupe.regularType` as required
2018-05-22 23:46:57 +02:00
return null!; // TODO: GH#18217
2014-07-13 01:04:16 +02:00
}
2019-07-18 09:50:38 +02:00
/* eslint-enable no-null/no-null */
2014-07-13 01:04:16 +02:00
Enable '--strictNullChecks' (#22088) * Enable '--strictNullChecks' * Fix API baselines * Make sys.getEnvironmentVariable non-nullable * make properties optional instead of using `| undefined` in thier type * reportDiagnostics should be required * Declare firstAccessor as non-nullable * Make `some` a type guard * Fix `getEnvironmentVariable` definition in tests * Pretend transformFlags are always defined * Fix one more use of sys.getEnvironmentVariable * `requiredResponse` accepts undefined, remove assertions * Mark optional properties as optional instead of using `| undefined` * Mark optional properties as optional instead of using ` | undefined` * Remove unnecessary null assertions * Put the bang on the declaration instead of every use * Make `createMapFromTemplate` require a parameter * Mark `EmitResult.emittedFiles` and `EmitResult.sourceMaps` as optional * Plumb through undefined in emitLsit and EmitExpressionList * `ElementAccessExpression.argumentExpression` can not be `undefined` * Add overloads for `writeTokenText` * Make `shouldWriteSeparatingLineTerminator` argument non-nullable * Make `synthesizedNodeStartsOnNewLine` argument required * `PropertyAssignment.initializer` cannot be undefined * Use one `!` at declaration site instead of on every use site * Capture host in a constant and avoid null assertions * Remove few more unused assertions * Update baselines * Use parameter defaults * Update baselines * Fix lint * Make Symbol#valueDeclaration and Symbol#declarations non-optional to reduce assertions * Make Node#symbol and Type#symbol non-optional to reduce assertions * Make `flags` non-nullable to reduce assertions * Convert some asserts to type guards * Make `isNonLocalAlias` a type guard * Add overload for `getSymbolOfNode` for `Declaration` * Some more `getSymbolOfNode` changes * Push undefined suppression into `typeToTypeNodeHelper` * `NodeBuilderContext.tracker` is never `undefined` * use `Debug.assertDefined` * Remove unnecessary tag * Mark `LiteralType.freshType` and `LiteralTupe.regularType` as required
2018-05-22 23:46:57 +02:00
const decoded: { span: { start: number; length: number; }; newLength: number; } = JSON.parse(encoded!); // TODO: GH#18217
return createTextChangeRange(
2014-12-10 22:45:08 +01:00
createTextSpan(decoded.span.start, decoded.span.length), decoded.newLength);
2014-07-13 01:04:16 +02:00
}
public dispose(): void {
2015-07-09 22:13:49 +02:00
// 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) {
Enable '--strictNullChecks' (#22088) * Enable '--strictNullChecks' * Fix API baselines * Make sys.getEnvironmentVariable non-nullable * make properties optional instead of using `| undefined` in thier type * reportDiagnostics should be required * Declare firstAccessor as non-nullable * Make `some` a type guard * Fix `getEnvironmentVariable` definition in tests * Pretend transformFlags are always defined * Fix one more use of sys.getEnvironmentVariable * `requiredResponse` accepts undefined, remove assertions * Mark optional properties as optional instead of using `| undefined` * Mark optional properties as optional instead of using ` | undefined` * Remove unnecessary null assertions * Put the bang on the declaration instead of every use * Make `createMapFromTemplate` require a parameter * Mark `EmitResult.emittedFiles` and `EmitResult.sourceMaps` as optional * Plumb through undefined in emitLsit and EmitExpressionList * `ElementAccessExpression.argumentExpression` can not be `undefined` * Add overloads for `writeTokenText` * Make `shouldWriteSeparatingLineTerminator` argument non-nullable * Make `synthesizedNodeStartsOnNewLine` argument required * `PropertyAssignment.initializer` cannot be undefined * Use one `!` at declaration site instead of on every use site * Capture host in a constant and avoid null assertions * Remove few more unused assertions * Update baselines * Use parameter defaults * Update baselines * Fix lint * Make Symbol#valueDeclaration and Symbol#declarations non-optional to reduce assertions * Make Node#symbol and Type#symbol non-optional to reduce assertions * Make `flags` non-nullable to reduce assertions * Convert some asserts to type guards * Make `isNonLocalAlias` a type guard * Add overload for `getSymbolOfNode` for `Declaration` * Some more `getSymbolOfNode` changes * Push undefined suppression into `typeToTypeNodeHelper` * `NodeBuilderContext.tracker` is never `undefined` * use `Debug.assertDefined` * Remove unnecessary tag * Mark `LiteralType.freshType` and `LiteralTupe.regularType` as required
2018-05-22 23:46:57 +02:00
this.scriptSnapshotShim.dispose!(); // TODO: GH#18217 Can we just use `if (this.scriptSnapshotShim.dispose)`?
}
}
2014-07-13 01:04:16 +02:00
}
export class LanguageServiceShimHostAdapter implements LanguageServiceHost {
private loggingEnabled = false;
private tracingEnabled = false;
2015-12-24 09:21:03 +01:00
public resolveModuleNames: ((moduleName: string[], containingFile: string) => (ResolvedModuleFull | undefined)[]) | undefined;
public resolveTypeReferenceDirectives: ((typeDirectiveNames: string[], containingFile: string) => (ResolvedTypeReferenceDirective | undefined)[]) | undefined;
public directoryExists: ((directoryName: string) => boolean) | undefined;
2016-01-07 18:24:32 +01:00
constructor(private shimHost: LanguageServiceShimHost) {
// if shimHost is a COM object then property check will become method call with no arguments.
2016-06-03 18:33:17 +02:00
// 'in' does not have this effect.
if ("getModuleResolutionsForFile" in this.shimHost) {
this.resolveModuleNames = (moduleNames, containingFile) => {
const resolutionsInFile = JSON.parse(this.shimHost.getModuleResolutionsForFile!(containingFile)) as MapLike<string>; // TODO: GH#18217
return map(moduleNames, name => {
2016-08-15 21:03:39 +02:00
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, containingFile) => {
const typeDirectivesForFile = JSON.parse(this.shimHost.getTypeReferenceDirectiveResolutionsForFile!(containingFile)) as MapLike<ResolvedTypeReferenceDirective>; // TODO: GH#18217
return map(typeDirectiveNames, name => getProperty(typeDirectivesForFile, name));
};
}
2014-07-19 01:55:11 +02:00
}
2014-07-13 01:04:16 +02:00
public log(s: string): void {
if (this.loggingEnabled) {
this.shimHost.log(s);
}
2014-07-13 01:04:16 +02:00
}
public trace(s: string): void {
if (this.tracingEnabled) {
this.shimHost.trace(s);
}
}
public error(s: string): void {
this.shimHost.error(s);
2015-07-30 03:14:13 +02:00
}
public getProjectVersion(): string {
if (!this.shimHost.getProjectVersion) {
// shimmed host does not support getProjectVersion
Enable '--strictNullChecks' (#22088) * Enable '--strictNullChecks' * Fix API baselines * Make sys.getEnvironmentVariable non-nullable * make properties optional instead of using `| undefined` in thier type * reportDiagnostics should be required * Declare firstAccessor as non-nullable * Make `some` a type guard * Fix `getEnvironmentVariable` definition in tests * Pretend transformFlags are always defined * Fix one more use of sys.getEnvironmentVariable * `requiredResponse` accepts undefined, remove assertions * Mark optional properties as optional instead of using `| undefined` * Mark optional properties as optional instead of using ` | undefined` * Remove unnecessary null assertions * Put the bang on the declaration instead of every use * Make `createMapFromTemplate` require a parameter * Mark `EmitResult.emittedFiles` and `EmitResult.sourceMaps` as optional * Plumb through undefined in emitLsit and EmitExpressionList * `ElementAccessExpression.argumentExpression` can not be `undefined` * Add overloads for `writeTokenText` * Make `shouldWriteSeparatingLineTerminator` argument non-nullable * Make `synthesizedNodeStartsOnNewLine` argument required * `PropertyAssignment.initializer` cannot be undefined * Use one `!` at declaration site instead of on every use site * Capture host in a constant and avoid null assertions * Remove few more unused assertions * Update baselines * Use parameter defaults * Update baselines * Fix lint * Make Symbol#valueDeclaration and Symbol#declarations non-optional to reduce assertions * Make Node#symbol and Type#symbol non-optional to reduce assertions * Make `flags` non-nullable to reduce assertions * Convert some asserts to type guards * Make `isNonLocalAlias` a type guard * Add overload for `getSymbolOfNode` for `Declaration` * Some more `getSymbolOfNode` changes * Push undefined suppression into `typeToTypeNodeHelper` * `NodeBuilderContext.tracker` is never `undefined` * use `Debug.assertDefined` * Remove unnecessary tag * Mark `LiteralType.freshType` and `LiteralTupe.regularType` as required
2018-05-22 23:46:57 +02:00
return undefined!; // TODO: GH#18217
}
return this.shimHost.getProjectVersion();
}
2016-09-20 01:47:15 +02:00
public getTypeRootsVersion(): number {
2016-09-20 02:53:10 +02:00
if (!this.shimHost.getTypeRootsVersion) {
return 0;
}
2016-09-20 01:47:15 +02:00
return this.shimHost.getTypeRootsVersion();
}
public useCaseSensitiveFileNames(): boolean {
2015-06-04 00:22:17 +02:00
return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false;
}
2014-07-25 21:18:12 +02:00
public getCompilationSettings(): CompilerOptions {
2016-01-07 18:16:14 +01:00
const settingsJson = this.shimHost.getCompilationSettings();
2019-07-18 09:50:38 +02:00
// eslint-disable-next-line no-null/no-null
2017-04-05 00:51:13 +02:00
if (settingsJson === null || settingsJson === "") {
2014-07-19 01:55:11 +02:00
throw Error("LanguageServiceShimHostAdapter.getCompilationSettings: empty compilationSettings");
2014-07-13 01:04:16 +02:00
}
const compilerOptions = JSON.parse(settingsJson) as CompilerOptions;
// permit language service to handle all files (filtering should be performed on the host side)
compilerOptions.allowNonTsExtensions = true;
return compilerOptions;
2014-07-13 01:04:16 +02:00
}
public getScriptFileNames(): string[] {
2016-01-07 18:16:14 +01:00
const encoded = this.shimHost.getScriptFileNames();
return JSON.parse(encoded);
2014-07-13 01:04:16 +02:00
}
Enable '--strictNullChecks' (#22088) * Enable '--strictNullChecks' * Fix API baselines * Make sys.getEnvironmentVariable non-nullable * make properties optional instead of using `| undefined` in thier type * reportDiagnostics should be required * Declare firstAccessor as non-nullable * Make `some` a type guard * Fix `getEnvironmentVariable` definition in tests * Pretend transformFlags are always defined * Fix one more use of sys.getEnvironmentVariable * `requiredResponse` accepts undefined, remove assertions * Mark optional properties as optional instead of using `| undefined` * Mark optional properties as optional instead of using ` | undefined` * Remove unnecessary null assertions * Put the bang on the declaration instead of every use * Make `createMapFromTemplate` require a parameter * Mark `EmitResult.emittedFiles` and `EmitResult.sourceMaps` as optional * Plumb through undefined in emitLsit and EmitExpressionList * `ElementAccessExpression.argumentExpression` can not be `undefined` * Add overloads for `writeTokenText` * Make `shouldWriteSeparatingLineTerminator` argument non-nullable * Make `synthesizedNodeStartsOnNewLine` argument required * `PropertyAssignment.initializer` cannot be undefined * Use one `!` at declaration site instead of on every use site * Capture host in a constant and avoid null assertions * Remove few more unused assertions * Update baselines * Use parameter defaults * Update baselines * Fix lint * Make Symbol#valueDeclaration and Symbol#declarations non-optional to reduce assertions * Make Node#symbol and Type#symbol non-optional to reduce assertions * Make `flags` non-nullable to reduce assertions * Convert some asserts to type guards * Make `isNonLocalAlias` a type guard * Add overload for `getSymbolOfNode` for `Declaration` * Some more `getSymbolOfNode` changes * Push undefined suppression into `typeToTypeNodeHelper` * `NodeBuilderContext.tracker` is never `undefined` * use `Debug.assertDefined` * Remove unnecessary tag * Mark `LiteralType.freshType` and `LiteralTupe.regularType` as required
2018-05-22 23:46:57 +02:00
public getScriptSnapshot(fileName: string): IScriptSnapshot | undefined {
2016-01-07 18:16:14 +01:00
const scriptSnapshot = this.shimHost.getScriptSnapshot(fileName);
return scriptSnapshot && new ScriptSnapshotShimAdapter(scriptSnapshot);
2014-07-13 01:04:16 +02:00
}
public getScriptKind(fileName: string): ScriptKind {
if ("getScriptKind" in this.shimHost) {
Enable '--strictNullChecks' (#22088) * Enable '--strictNullChecks' * Fix API baselines * Make sys.getEnvironmentVariable non-nullable * make properties optional instead of using `| undefined` in thier type * reportDiagnostics should be required * Declare firstAccessor as non-nullable * Make `some` a type guard * Fix `getEnvironmentVariable` definition in tests * Pretend transformFlags are always defined * Fix one more use of sys.getEnvironmentVariable * `requiredResponse` accepts undefined, remove assertions * Mark optional properties as optional instead of using `| undefined` * Mark optional properties as optional instead of using ` | undefined` * Remove unnecessary null assertions * Put the bang on the declaration instead of every use * Make `createMapFromTemplate` require a parameter * Mark `EmitResult.emittedFiles` and `EmitResult.sourceMaps` as optional * Plumb through undefined in emitLsit and EmitExpressionList * `ElementAccessExpression.argumentExpression` can not be `undefined` * Add overloads for `writeTokenText` * Make `shouldWriteSeparatingLineTerminator` argument non-nullable * Make `synthesizedNodeStartsOnNewLine` argument required * `PropertyAssignment.initializer` cannot be undefined * Use one `!` at declaration site instead of on every use site * Capture host in a constant and avoid null assertions * Remove few more unused assertions * Update baselines * Use parameter defaults * Update baselines * Fix lint * Make Symbol#valueDeclaration and Symbol#declarations non-optional to reduce assertions * Make Node#symbol and Type#symbol non-optional to reduce assertions * Make `flags` non-nullable to reduce assertions * Convert some asserts to type guards * Make `isNonLocalAlias` a type guard * Add overload for `getSymbolOfNode` for `Declaration` * Some more `getSymbolOfNode` changes * Push undefined suppression into `typeToTypeNodeHelper` * `NodeBuilderContext.tracker` is never `undefined` * use `Debug.assertDefined` * Remove unnecessary tag * Mark `LiteralType.freshType` and `LiteralTupe.regularType` as required
2018-05-22 23:46:57 +02:00
return this.shimHost.getScriptKind!(fileName); // TODO: GH#18217
}
else {
return ScriptKind.Unknown;
}
}
public getScriptVersion(fileName: string): string {
2014-07-13 01:04:16 +02:00
return this.shimHost.getScriptVersion(fileName);
}
public getLocalizedDiagnosticMessages() {
2019-07-18 09:50:38 +02:00
/* eslint-disable no-null/no-null */
2016-01-07 18:16:14 +01:00
const diagnosticMessagesJson = this.shimHost.getLocalizedDiagnosticMessages();
2017-04-05 00:51:13 +02:00
if (diagnosticMessagesJson === null || diagnosticMessagesJson === "") {
2014-07-13 01:04:16 +02:00
return null;
}
2014-07-13 01:04:16 +02:00
try {
return JSON.parse(diagnosticMessagesJson);
}
catch (e) {
this.log(e.description || "diagnosticMessages.generated.json has invalid JSON format");
return null;
}
2019-07-18 09:50:38 +02:00
/* eslint-enable no-null/no-null */
2014-07-13 01:04:16 +02:00
}
2015-06-18 21:04:26 +02:00
public getCancellationToken(): HostCancellationToken {
2016-01-07 18:16:14 +01:00
const hostCancellationToken = this.shimHost.getCancellationToken();
return new ThrottledCancellationToken(hostCancellationToken);
2014-07-19 01:55:11 +02:00
}
public getCurrentDirectory(): string {
return this.shimHost.getCurrentDirectory();
}
2016-05-24 20:10:57 +02:00
public getDirectories(path: string): string[] {
return JSON.parse(this.shimHost.getDirectories(path));
2016-05-24 20:10:57 +02:00
}
public getDefaultLibFileName(options: CompilerOptions): string {
return this.shimHost.getDefaultLibFileName(JSON.stringify(options));
}
public readDirectory(path: string, extensions?: readonly string[], exclude?: string[], include?: string[], depth?: number): string[] {
const pattern = getFileMatcherPatterns(path, exclude, include,
Enable '--strictNullChecks' (#22088) * Enable '--strictNullChecks' * Fix API baselines * Make sys.getEnvironmentVariable non-nullable * make properties optional instead of using `| undefined` in thier type * reportDiagnostics should be required * Declare firstAccessor as non-nullable * Make `some` a type guard * Fix `getEnvironmentVariable` definition in tests * Pretend transformFlags are always defined * Fix one more use of sys.getEnvironmentVariable * `requiredResponse` accepts undefined, remove assertions * Mark optional properties as optional instead of using `| undefined` * Mark optional properties as optional instead of using ` | undefined` * Remove unnecessary null assertions * Put the bang on the declaration instead of every use * Make `createMapFromTemplate` require a parameter * Mark `EmitResult.emittedFiles` and `EmitResult.sourceMaps` as optional * Plumb through undefined in emitLsit and EmitExpressionList * `ElementAccessExpression.argumentExpression` can not be `undefined` * Add overloads for `writeTokenText` * Make `shouldWriteSeparatingLineTerminator` argument non-nullable * Make `synthesizedNodeStartsOnNewLine` argument required * `PropertyAssignment.initializer` cannot be undefined * Use one `!` at declaration site instead of on every use site * Capture host in a constant and avoid null assertions * Remove few more unused assertions * Update baselines * Use parameter defaults * Update baselines * Fix lint * Make Symbol#valueDeclaration and Symbol#declarations non-optional to reduce assertions * Make Node#symbol and Type#symbol non-optional to reduce assertions * Make `flags` non-nullable to reduce assertions * Convert some asserts to type guards * Make `isNonLocalAlias` a type guard * Add overload for `getSymbolOfNode` for `Declaration` * Some more `getSymbolOfNode` changes * Push undefined suppression into `typeToTypeNodeHelper` * `NodeBuilderContext.tracker` is never `undefined` * use `Debug.assertDefined` * Remove unnecessary tag * Mark `LiteralType.freshType` and `LiteralTupe.regularType` as required
2018-05-22 23:46:57 +02:00
this.shimHost.useCaseSensitiveFileNames!(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217
return JSON.parse(this.shimHost.readDirectory(
path,
2016-08-04 20:10:00 +02:00
JSON.stringify(extensions),
JSON.stringify(pattern.basePaths),
pattern.excludePattern,
pattern.includeFilePattern,
pattern.includeDirectoryPattern,
depth
));
}
2017-07-14 23:26:13 +02:00
public readFile(path: string, encoding?: string): string | undefined {
return this.shimHost.readFile(path, encoding);
}
public fileExists(path: string): boolean {
return this.shimHost.fileExists(path);
}
2014-07-19 01:55:11 +02:00
}
export class CoreServicesShimHostAdapter implements ParseConfigHost, ModuleResolutionHost, JsTyping.TypingResolutionHost {
public directoryExists: (directoryName: string) => boolean;
public realpath: (path: string) => string;
2016-05-26 02:07:36 +02:00
public useCaseSensitiveFileNames: boolean;
2016-01-07 18:24:32 +01:00
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);
}
else {
this.directoryExists = undefined!; // TODO: GH#18217
}
if ("realpath" in this.shimHost) {
Enable '--strictNullChecks' (#22088) * Enable '--strictNullChecks' * Fix API baselines * Make sys.getEnvironmentVariable non-nullable * make properties optional instead of using `| undefined` in thier type * reportDiagnostics should be required * Declare firstAccessor as non-nullable * Make `some` a type guard * Fix `getEnvironmentVariable` definition in tests * Pretend transformFlags are always defined * Fix one more use of sys.getEnvironmentVariable * `requiredResponse` accepts undefined, remove assertions * Mark optional properties as optional instead of using `| undefined` * Mark optional properties as optional instead of using ` | undefined` * Remove unnecessary null assertions * Put the bang on the declaration instead of every use * Make `createMapFromTemplate` require a parameter * Mark `EmitResult.emittedFiles` and `EmitResult.sourceMaps` as optional * Plumb through undefined in emitLsit and EmitExpressionList * `ElementAccessExpression.argumentExpression` can not be `undefined` * Add overloads for `writeTokenText` * Make `shouldWriteSeparatingLineTerminator` argument non-nullable * Make `synthesizedNodeStartsOnNewLine` argument required * `PropertyAssignment.initializer` cannot be undefined * Use one `!` at declaration site instead of on every use site * Capture host in a constant and avoid null assertions * Remove few more unused assertions * Update baselines * Use parameter defaults * Update baselines * Fix lint * Make Symbol#valueDeclaration and Symbol#declarations non-optional to reduce assertions * Make Node#symbol and Type#symbol non-optional to reduce assertions * Make `flags` non-nullable to reduce assertions * Convert some asserts to type guards * Make `isNonLocalAlias` a type guard * Add overload for `getSymbolOfNode` for `Declaration` * Some more `getSymbolOfNode` changes * Push undefined suppression into `typeToTypeNodeHelper` * `NodeBuilderContext.tracker` is never `undefined` * use `Debug.assertDefined` * Remove unnecessary tag * Mark `LiteralType.freshType` and `LiteralTupe.regularType` as required
2018-05-22 23:46:57 +02:00
this.realpath = path => this.shimHost.realpath!(path); // TODO: GH#18217
}
else {
this.realpath = undefined!; // TODO: GH#18217
}
}
public readDirectory(rootDir: string, extensions: readonly string[], exclude: readonly string[], include: readonly string[], depth?: number): string[] {
const pattern = getFileMatcherPatterns(rootDir, exclude, include,
Enable '--strictNullChecks' (#22088) * Enable '--strictNullChecks' * Fix API baselines * Make sys.getEnvironmentVariable non-nullable * make properties optional instead of using `| undefined` in thier type * reportDiagnostics should be required * Declare firstAccessor as non-nullable * Make `some` a type guard * Fix `getEnvironmentVariable` definition in tests * Pretend transformFlags are always defined * Fix one more use of sys.getEnvironmentVariable * `requiredResponse` accepts undefined, remove assertions * Mark optional properties as optional instead of using `| undefined` * Mark optional properties as optional instead of using ` | undefined` * Remove unnecessary null assertions * Put the bang on the declaration instead of every use * Make `createMapFromTemplate` require a parameter * Mark `EmitResult.emittedFiles` and `EmitResult.sourceMaps` as optional * Plumb through undefined in emitLsit and EmitExpressionList * `ElementAccessExpression.argumentExpression` can not be `undefined` * Add overloads for `writeTokenText` * Make `shouldWriteSeparatingLineTerminator` argument non-nullable * Make `synthesizedNodeStartsOnNewLine` argument required * `PropertyAssignment.initializer` cannot be undefined * Use one `!` at declaration site instead of on every use site * Capture host in a constant and avoid null assertions * Remove few more unused assertions * Update baselines * Use parameter defaults * Update baselines * Fix lint * Make Symbol#valueDeclaration and Symbol#declarations non-optional to reduce assertions * Make Node#symbol and Type#symbol non-optional to reduce assertions * Make `flags` non-nullable to reduce assertions * Convert some asserts to type guards * Make `isNonLocalAlias` a type guard * Add overload for `getSymbolOfNode` for `Declaration` * Some more `getSymbolOfNode` changes * Push undefined suppression into `typeToTypeNodeHelper` * `NodeBuilderContext.tracker` is never `undefined` * use `Debug.assertDefined` * Remove unnecessary tag * Mark `LiteralType.freshType` and `LiteralTupe.regularType` as required
2018-05-22 23:46:57 +02:00
this.shimHost.useCaseSensitiveFileNames!(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217
return JSON.parse(this.shimHost.readDirectory(
rootDir,
JSON.stringify(extensions),
JSON.stringify(pattern.basePaths),
pattern.excludePattern,
pattern.includeFilePattern,
pattern.includeDirectoryPattern,
depth
));
}
2015-12-24 09:21:03 +01:00
public fileExists(fileName: string): boolean {
return this.shimHost.fileExists(fileName);
}
2015-12-24 09:21:03 +01:00
2017-07-14 23:26:13 +02:00
public readFile(fileName: string): string | undefined {
2015-08-05 06:22:37 +02:00
return this.shimHost.readFile(fileName);
}
public getDirectories(path: string): string[] {
return JSON.parse(this.shimHost.getDirectories(path));
}
}
2014-07-19 01:55:11 +02:00
function simpleForwardCall(logger: Logger, actionDescription: string, action: () => {}, logPerformance: boolean): {} {
Enable '--strictNullChecks' (#22088) * Enable '--strictNullChecks' * Fix API baselines * Make sys.getEnvironmentVariable non-nullable * make properties optional instead of using `| undefined` in thier type * reportDiagnostics should be required * Declare firstAccessor as non-nullable * Make `some` a type guard * Fix `getEnvironmentVariable` definition in tests * Pretend transformFlags are always defined * Fix one more use of sys.getEnvironmentVariable * `requiredResponse` accepts undefined, remove assertions * Mark optional properties as optional instead of using `| undefined` * Mark optional properties as optional instead of using ` | undefined` * Remove unnecessary null assertions * Put the bang on the declaration instead of every use * Make `createMapFromTemplate` require a parameter * Mark `EmitResult.emittedFiles` and `EmitResult.sourceMaps` as optional * Plumb through undefined in emitLsit and EmitExpressionList * `ElementAccessExpression.argumentExpression` can not be `undefined` * Add overloads for `writeTokenText` * Make `shouldWriteSeparatingLineTerminator` argument non-nullable * Make `synthesizedNodeStartsOnNewLine` argument required * `PropertyAssignment.initializer` cannot be undefined * Use one `!` at declaration site instead of on every use site * Capture host in a constant and avoid null assertions * Remove few more unused assertions * Update baselines * Use parameter defaults * Update baselines * Fix lint * Make Symbol#valueDeclaration and Symbol#declarations non-optional to reduce assertions * Make Node#symbol and Type#symbol non-optional to reduce assertions * Make `flags` non-nullable to reduce assertions * Convert some asserts to type guards * Make `isNonLocalAlias` a type guard * Add overload for `getSymbolOfNode` for `Declaration` * Some more `getSymbolOfNode` changes * Push undefined suppression into `typeToTypeNodeHelper` * `NodeBuilderContext.tracker` is never `undefined` * use `Debug.assertDefined` * Remove unnecessary tag * Mark `LiteralType.freshType` and `LiteralTupe.regularType` as required
2018-05-22 23:46:57 +02:00
let start: number | undefined;
if (logPerformance) {
logger.log(actionDescription);
start = timestamp();
}
2016-01-07 18:16:14 +01:00
const result = action();
if (logPerformance) {
const end = timestamp();
2019-06-24 13:55:58 +02:00
logger.log(`${actionDescription} completed in ${end - start!} msec`);
if (isString(result)) {
2015-12-24 09:21:03 +01:00
let str = result;
if (str.length > 128) {
str = str.substring(0, 128) + "...";
}
2015-12-24 09:21:03 +01:00
logger.log(` result.length=${str.length}, result='${JSON.stringify(str)}'`);
2014-07-19 01:55:11 +02:00
}
}
2014-07-19 01:55:11 +02:00
return result;
}
Enable '--strictNullChecks' (#22088) * Enable '--strictNullChecks' * Fix API baselines * Make sys.getEnvironmentVariable non-nullable * make properties optional instead of using `| undefined` in thier type * reportDiagnostics should be required * Declare firstAccessor as non-nullable * Make `some` a type guard * Fix `getEnvironmentVariable` definition in tests * Pretend transformFlags are always defined * Fix one more use of sys.getEnvironmentVariable * `requiredResponse` accepts undefined, remove assertions * Mark optional properties as optional instead of using `| undefined` * Mark optional properties as optional instead of using ` | undefined` * Remove unnecessary null assertions * Put the bang on the declaration instead of every use * Make `createMapFromTemplate` require a parameter * Mark `EmitResult.emittedFiles` and `EmitResult.sourceMaps` as optional * Plumb through undefined in emitLsit and EmitExpressionList * `ElementAccessExpression.argumentExpression` can not be `undefined` * Add overloads for `writeTokenText` * Make `shouldWriteSeparatingLineTerminator` argument non-nullable * Make `synthesizedNodeStartsOnNewLine` argument required * `PropertyAssignment.initializer` cannot be undefined * Use one `!` at declaration site instead of on every use site * Capture host in a constant and avoid null assertions * Remove few more unused assertions * Update baselines * Use parameter defaults * Update baselines * Fix lint * Make Symbol#valueDeclaration and Symbol#declarations non-optional to reduce assertions * Make Node#symbol and Type#symbol non-optional to reduce assertions * Make `flags` non-nullable to reduce assertions * Convert some asserts to type guards * Make `isNonLocalAlias` a type guard * Add overload for `getSymbolOfNode` for `Declaration` * Some more `getSymbolOfNode` changes * Push undefined suppression into `typeToTypeNodeHelper` * `NodeBuilderContext.tracker` is never `undefined` * use `Debug.assertDefined` * Remove unnecessary tag * Mark `LiteralType.freshType` and `LiteralTupe.regularType` as required
2018-05-22 23:46:57 +02:00
function forwardJSONCall(logger: Logger, actionDescription: string, action: () => {} | null | undefined, logPerformance: boolean): string {
return forwardCall(logger, actionDescription, /*returnJson*/ true, action, logPerformance) as string;
}
function forwardCall<T>(logger: Logger, actionDescription: string, returnJson: boolean, action: () => T, logPerformance: boolean): T | string {
2014-07-19 01:55:11 +02:00
try {
2016-01-07 18:16:14 +01:00
const result = simpleForwardCall(logger, actionDescription, action, logPerformance);
return returnJson ? JSON.stringify({ result }) : result as T;
2014-07-19 01:55:11 +02:00
}
catch (err) {
if (err instanceof OperationCanceledException) {
return JSON.stringify({ canceled: true });
}
2014-07-24 20:57:18 +02:00
logInternalError(logger, err);
2014-07-19 01:55:11 +02:00
err.description = actionDescription;
return JSON.stringify({ error: err });
}
}
class ShimBase implements Shim {
constructor(private factory: ShimFactory) {
2014-07-24 20:57:18 +02:00
factory.registerShim(this);
}
public dispose(_dummy: {}): void {
2014-07-24 20:57:18 +02:00
this.factory.unregisterShim(this);
}
}
export interface RealizedDiagnostic {
2017-09-23 01:14:41 +02:00
message: string;
start: number;
length: number;
category: string;
code: number;
reportsUnnecessary?: {};
reportsDeprecated?: {};
2017-09-23 01:14:41 +02:00
}
export function realizeDiagnostics(diagnostics: readonly Diagnostic[], newLine: string): RealizedDiagnostic[] {
return diagnostics.map(d => realizeDiagnostic(d, newLine));
}
2017-09-23 01:14:41 +02:00
function realizeDiagnostic(diagnostic: Diagnostic, newLine: string): RealizedDiagnostic {
return {
message: flattenDiagnosticMessageText(diagnostic.messageText, newLine),
Enable '--strictNullChecks' (#22088) * Enable '--strictNullChecks' * Fix API baselines * Make sys.getEnvironmentVariable non-nullable * make properties optional instead of using `| undefined` in thier type * reportDiagnostics should be required * Declare firstAccessor as non-nullable * Make `some` a type guard * Fix `getEnvironmentVariable` definition in tests * Pretend transformFlags are always defined * Fix one more use of sys.getEnvironmentVariable * `requiredResponse` accepts undefined, remove assertions * Mark optional properties as optional instead of using `| undefined` * Mark optional properties as optional instead of using ` | undefined` * Remove unnecessary null assertions * Put the bang on the declaration instead of every use * Make `createMapFromTemplate` require a parameter * Mark `EmitResult.emittedFiles` and `EmitResult.sourceMaps` as optional * Plumb through undefined in emitLsit and EmitExpressionList * `ElementAccessExpression.argumentExpression` can not be `undefined` * Add overloads for `writeTokenText` * Make `shouldWriteSeparatingLineTerminator` argument non-nullable * Make `synthesizedNodeStartsOnNewLine` argument required * `PropertyAssignment.initializer` cannot be undefined * Use one `!` at declaration site instead of on every use site * Capture host in a constant and avoid null assertions * Remove few more unused assertions * Update baselines * Use parameter defaults * Update baselines * Fix lint * Make Symbol#valueDeclaration and Symbol#declarations non-optional to reduce assertions * Make Node#symbol and Type#symbol non-optional to reduce assertions * Make `flags` non-nullable to reduce assertions * Convert some asserts to type guards * Make `isNonLocalAlias` a type guard * Add overload for `getSymbolOfNode` for `Declaration` * Some more `getSymbolOfNode` changes * Push undefined suppression into `typeToTypeNodeHelper` * `NodeBuilderContext.tracker` is never `undefined` * use `Debug.assertDefined` * Remove unnecessary tag * Mark `LiteralType.freshType` and `LiteralTupe.regularType` as required
2018-05-22 23:46:57 +02:00
start: diagnostic.start!, // TODO: GH#18217
length: diagnostic.length!, // TODO: GH#18217
category: diagnosticCategoryName(diagnostic),
code: diagnostic.code,
reportsUnnecessary: diagnostic.reportsUnnecessary,
reportsDeprecated: diagnostic.reportsDeprecated
};
}
class LanguageServiceShimObject extends ShimBase implements LanguageServiceShim {
2014-07-25 01:01:51 +02:00
private logger: Logger;
private logPerformance = false;
2014-07-19 01:55:11 +02:00
constructor(factory: ShimFactory,
private host: LanguageServiceShimHost,
2014-07-24 20:57:18 +02:00
public languageService: LanguageService) {
2014-07-19 01:55:11 +02:00
super(factory);
this.logger = this.host;
}
Enable '--strictNullChecks' (#22088) * Enable '--strictNullChecks' * Fix API baselines * Make sys.getEnvironmentVariable non-nullable * make properties optional instead of using `| undefined` in thier type * reportDiagnostics should be required * Declare firstAccessor as non-nullable * Make `some` a type guard * Fix `getEnvironmentVariable` definition in tests * Pretend transformFlags are always defined * Fix one more use of sys.getEnvironmentVariable * `requiredResponse` accepts undefined, remove assertions * Mark optional properties as optional instead of using `| undefined` * Mark optional properties as optional instead of using ` | undefined` * Remove unnecessary null assertions * Put the bang on the declaration instead of every use * Make `createMapFromTemplate` require a parameter * Mark `EmitResult.emittedFiles` and `EmitResult.sourceMaps` as optional * Plumb through undefined in emitLsit and EmitExpressionList * `ElementAccessExpression.argumentExpression` can not be `undefined` * Add overloads for `writeTokenText` * Make `shouldWriteSeparatingLineTerminator` argument non-nullable * Make `synthesizedNodeStartsOnNewLine` argument required * `PropertyAssignment.initializer` cannot be undefined * Use one `!` at declaration site instead of on every use site * Capture host in a constant and avoid null assertions * Remove few more unused assertions * Update baselines * Use parameter defaults * Update baselines * Fix lint * Make Symbol#valueDeclaration and Symbol#declarations non-optional to reduce assertions * Make Node#symbol and Type#symbol non-optional to reduce assertions * Make `flags` non-nullable to reduce assertions * Convert some asserts to type guards * Make `isNonLocalAlias` a type guard * Add overload for `getSymbolOfNode` for `Declaration` * Some more `getSymbolOfNode` changes * Push undefined suppression into `typeToTypeNodeHelper` * `NodeBuilderContext.tracker` is never `undefined` * use `Debug.assertDefined` * Remove unnecessary tag * Mark `LiteralType.freshType` and `LiteralTupe.regularType` as required
2018-05-22 23:46:57 +02:00
public forwardJSONCall(actionDescription: string, action: () => {} | null | undefined): string {
return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance);
2014-07-19 01:55:11 +02:00
}
2014-09-24 21:55:27 +02:00
/// 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 {
2014-07-19 01:55:11 +02:00
this.logger.log("dispose()");
this.languageService.dispose();
2019-07-18 09:50:38 +02:00
this.languageService = null!; // eslint-disable-line no-null/no-null
2014-07-19 01:55:11 +02:00
// force a GC
if (debugObjectHost && debugObjectHost.CollectGarbage) {
debugObjectHost.CollectGarbage();
this.logger.log("CollectGarbage()");
}
2019-07-18 09:50:38 +02:00
this.logger = null!; // eslint-disable-line no-null/no-null
2014-07-19 01:55:11 +02:00
super.dispose(dummy);
}
2014-09-24 21:55:27 +02:00
/// REFRESH
/**
* Update the list of scripts known to the compiler
*/
2014-07-19 01:55:11 +02:00
public refresh(throwOnError: boolean): void {
this.forwardJSONCall(
2015-12-24 09:21:03 +01:00
`refresh(${throwOnError})`,
2019-07-18 09:50:38 +02:00
() => null // eslint-disable-line no-null/no-null
2016-01-07 18:24:32 +01:00
);
2014-07-19 01:55:11 +02:00
}
public cleanupSemanticCache(): void {
this.forwardJSONCall(
"cleanupSemanticCache()",
() => {
this.languageService.cleanupSemanticCache();
2019-07-18 09:50:38 +02:00
return null; // eslint-disable-line no-null/no-null
2014-07-19 01:55:11 +02:00
});
}
private realizeDiagnostics(diagnostics: readonly Diagnostic[]): { message: string; start: number; length: number; category: string; }[] {
2016-01-07 18:16:14 +01:00
const newLine = getNewLineOrDefaultFromHost(this.host);
return realizeDiagnostics(diagnostics, newLine);
}
2014-07-19 01:55:11 +02:00
public getSyntacticClassifications(fileName: string, start: number, length: number): string {
return this.forwardJSONCall(
2015-12-24 09:21:03 +01:00
`getSyntacticClassifications('${fileName}', ${start}, ${length})`,
2016-01-07 18:24:32 +01:00
() => this.languageService.getSyntacticClassifications(fileName, createTextSpan(start, length))
);
}
2014-09-13 03:28:54 +02:00
public getSemanticClassifications(fileName: string, start: number, length: number): string {
return this.forwardJSONCall(
2015-12-24 09:21:03 +01:00
`getSemanticClassifications('${fileName}', ${start}, ${length})`,
2016-01-07 18:24:32 +01:00
() => this.languageService.getSemanticClassifications(fileName, createTextSpan(start, length))
);
2014-09-13 03:28:54 +02:00
}
2015-05-01 02:39:51 +02:00
public getEncodedSyntacticClassifications(fileName: string, start: number, length: number): string {
2015-04-23 22:40:34 +02:00
return this.forwardJSONCall(
2015-12-24 09:21:03 +01:00
`getEncodedSyntacticClassifications('${fileName}', ${start}, ${length})`,
2016-01-07 18:24:32 +01:00
// 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)))
);
2015-04-23 22:40:34 +02:00
}
2015-05-01 02:39:51 +02:00
public getEncodedSemanticClassifications(fileName: string, start: number, length: number): string {
2015-04-23 22:40:34 +02:00
return this.forwardJSONCall(
2015-12-24 09:21:03 +01:00
`getEncodedSemanticClassifications('${fileName}', ${start}, ${length})`,
2016-01-07 18:24:32 +01:00
// 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)))
);
2015-04-23 22:40:34 +02:00
}
2014-07-19 01:55:11 +02:00
public getSyntacticDiagnostics(fileName: string): string {
return this.forwardJSONCall(
2015-12-24 09:21:03 +01:00
`getSyntacticDiagnostics('${fileName}')`,
2014-07-19 01:55:11 +02:00
() => {
2016-01-07 18:24:32 +01:00
const diagnostics = this.languageService.getSyntacticDiagnostics(fileName);
return this.realizeDiagnostics(diagnostics);
2014-07-19 01:55:11 +02:00
});
}
public getSemanticDiagnostics(fileName: string): string {
return this.forwardJSONCall(
2015-12-24 09:21:03 +01:00
`getSemanticDiagnostics('${fileName}')`,
2014-07-19 01:55:11 +02:00
() => {
2016-01-07 18:24:32 +01:00
const diagnostics = this.languageService.getSemanticDiagnostics(fileName);
return this.realizeDiagnostics(diagnostics);
2014-07-19 01:55:11 +02:00
});
}
public getSuggestionDiagnostics(fileName: string): string {
return this.forwardJSONCall(`getSuggestionDiagnostics('${fileName}')`, () => this.realizeDiagnostics(this.languageService.getSuggestionDiagnostics(fileName)));
}
2014-07-19 01:55:11 +02:00
public getCompilerOptionsDiagnostics(): string {
return this.forwardJSONCall(
"getCompilerOptionsDiagnostics()",
() => {
2016-01-07 18:24:32 +01:00
const diagnostics = this.languageService.getCompilerOptionsDiagnostics();
return this.realizeDiagnostics(diagnostics);
2014-07-19 01:55:11 +02:00
});
}
/// QUICKINFO
2014-09-24 21:55:27 +02:00
/**
* Computes a string representation of the type at the requested position
* in the active file.
*/
2014-09-20 00:32:27 +02:00
public getQuickInfoAtPosition(fileName: string, position: number): string {
return this.forwardJSONCall(
2015-12-24 09:21:03 +01:00
`getQuickInfoAtPosition('${fileName}', ${position})`,
2016-01-07 18:24:32 +01:00
() => this.languageService.getQuickInfoAtPosition(fileName, position)
);
2014-09-20 00:32:27 +02:00
}
2014-07-19 01:55:11 +02:00
/// NAMEORDOTTEDNAMESPAN
2014-09-24 21:55:27 +02:00
/**
* Computes span information of the name or dotted name at the requested position
* in the active file.
*/
2014-07-19 01:55:11 +02:00
public getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): string {
return this.forwardJSONCall(
2015-12-24 09:21:03 +01:00
`getNameOrDottedNameSpan('${fileName}', ${startPos}, ${endPos})`,
2016-01-07 18:24:32 +01:00
() => this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos)
);
2014-07-19 01:55:11 +02:00
}
2014-09-24 21:55:27 +02:00
/**
* STATEMENTSPAN
* Computes span information of statement at the requested position in the active file.
*/
2014-07-19 01:55:11 +02:00
public getBreakpointStatementAtPosition(fileName: string, position: number): string {
return this.forwardJSONCall(
2015-12-24 09:21:03 +01:00
`getBreakpointStatementAtPosition('${fileName}', ${position})`,
2016-01-07 18:24:32 +01:00
() => this.languageService.getBreakpointStatementAtPosition(fileName, position)
);
2014-07-19 01:55:11 +02:00
}
/// SIGNATUREHELP
public getSignatureHelpItems(fileName: string, position: number, options: SignatureHelpItemsOptions | undefined): string {
2014-07-19 01:55:11 +02:00
return this.forwardJSONCall(
2015-12-24 09:21:03 +01:00
`getSignatureHelpItems('${fileName}', ${position})`,
() => this.languageService.getSignatureHelpItems(fileName, position, options)
2016-01-07 18:24:32 +01:00
);
2014-07-19 01:55:11 +02:00
}
/// GOTO DEFINITION
2014-09-24 21:55:27 +02:00
/**
* Computes the definition location and file for the symbol
* at the requested position.
2014-09-24 21:55:27 +02:00
*/
2014-07-19 01:55:11 +02:00
public getDefinitionAtPosition(fileName: string, position: number): string {
return this.forwardJSONCall(
2015-12-24 09:21:03 +01:00
`getDefinitionAtPosition('${fileName}', ${position})`,
2016-01-07 18:24:32 +01:00
() => this.languageService.getDefinitionAtPosition(fileName, position)
);
}
/**
* Computes the definition location and file for the symbol
* at the requested position.
*/
public getDefinitionAndBoundSpan(fileName: string, position: number): string {
return this.forwardJSONCall(
`getDefinitionAndBoundSpan('${fileName}', ${position})`,
() => this.languageService.getDefinitionAndBoundSpan(fileName, position)
);
2014-07-19 01:55:11 +02:00
}
/// 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(
2015-12-24 09:21:03 +01:00
`getTypeDefinitionAtPosition('${fileName}', ${position})`,
2016-01-07 18:24:32 +01:00
() => this.languageService.getTypeDefinitionAtPosition(fileName, position)
);
}
2016-08-22 22:57:40 +02:00
/// 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, options?: RenameInfoOptions): string {
return this.forwardJSONCall(
2015-12-24 09:21:03 +01:00
`getRenameInfo('${fileName}', ${position})`,
() => this.languageService.getRenameInfo(fileName, position, options)
2016-01-07 18:24:32 +01:00
);
}
2019-04-19 01:23:06 +02:00
public getSmartSelectionRange(fileName: string, position: number): string {
2019-04-12 02:32:40 +02:00
return this.forwardJSONCall(
2019-04-19 01:23:06 +02:00
`getSmartSelectionRange('${fileName}', ${position})`,
() => this.languageService.getSmartSelectionRange(fileName, position)
2019-04-12 02:32:40 +02:00
);
}
public findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean, providePrefixAndSuffixTextForRename?: boolean): string {
return this.forwardJSONCall(
`findRenameLocations('${fileName}', ${position}, ${findInStrings}, ${findInComments}, ${providePrefixAndSuffixTextForRename})`,
() => this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename)
2016-01-07 18:24:32 +01:00
);
}
2014-07-19 01:55:11 +02:00
/// GET BRACE MATCHING
public getBraceMatchingAtPosition(fileName: string, position: number): string {
return this.forwardJSONCall(
2015-12-24 09:21:03 +01:00
`getBraceMatchingAtPosition('${fileName}', ${position})`,
2016-01-07 18:24:32 +01:00
() => this.languageService.getBraceMatchingAtPosition(fileName, position)
);
2014-07-19 01:55:11 +02:00
}
2016-06-24 02:36:59 +02:00
public isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): string {
return this.forwardJSONCall(
2016-06-24 02:36:59 +02:00
`isValidBraceCompletionAtPosition('${fileName}', ${position}, ${openingBrace})`,
() => this.languageService.isValidBraceCompletionAtPosition(fileName, position, openingBrace)
);
}
2017-06-10 03:02:42 +02:00
public getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): string {
return this.forwardJSONCall(
2017-06-10 03:02:42 +02:00
`getSpanOfEnclosingComment('${fileName}', ${position})`,
() => this.languageService.getSpanOfEnclosingComment(fileName, position, onlyMultiLine)
);
}
2014-07-19 01:55:11 +02:00
/// GET SMART INDENT
public getIndentationAtPosition(fileName: string, position: number, options: string /*Services.EditorOptions*/): string {
return this.forwardJSONCall(
2015-12-24 09:21:03 +01:00
`getIndentationAtPosition('${fileName}', ${position})`,
2014-07-19 01:55:11 +02:00
() => {
2016-01-07 18:16:14 +01:00
const localOptions: EditorOptions = JSON.parse(options);
return this.languageService.getIndentationAtPosition(fileName, position, localOptions);
2014-07-19 01:55:11 +02:00
});
}
/// GET REFERENCES
2014-09-24 21:55:27 +02:00
2014-07-19 01:55:11 +02:00
public getReferencesAtPosition(fileName: string, position: number): string {
return this.forwardJSONCall(
2015-12-24 09:21:03 +01:00
`getReferencesAtPosition('${fileName}', ${position})`,
2016-01-07 18:24:32 +01:00
() => this.languageService.getReferencesAtPosition(fileName, position)
);
2014-07-19 01:55:11 +02:00
}
2014-07-13 01:04:16 +02:00
public findReferences(fileName: string, position: number): string {
return this.forwardJSONCall(
2015-12-24 09:21:03 +01:00
`findReferences('${fileName}', ${position})`,
2016-01-07 18:24:32 +01:00
() => this.languageService.findReferences(fileName, position)
);
}
public getFileReferences(fileName: string) {
return this.forwardJSONCall(
`getFileReferences('${fileName})`,
() => this.languageService.getFileReferences(fileName)
);
}
2014-07-19 01:55:11 +02:00
public getOccurrencesAtPosition(fileName: string, position: number): string {
return this.forwardJSONCall(
2015-12-24 09:21:03 +01:00
`getOccurrencesAtPosition('${fileName}', ${position})`,
2016-01-07 18:24:32 +01:00
() => this.languageService.getOccurrencesAtPosition(fileName, position)
);
2014-07-19 01:55:11 +02:00
}
public getDocumentHighlights(fileName: string, position: number, filesToSearch: string): string {
return this.forwardJSONCall(
2015-12-24 09:21:03 +01:00
`getDocumentHighlights('${fileName}', ${position})`,
() => {
2016-01-07 18:16:14 +01:00
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 = toFileNameLowerCase(normalizeSlashes(fileName));
return filter(results, r => toFileNameLowerCase(normalizeSlashes(r.fileName)) === normalizedName);
});
}
2014-07-19 01:55:11 +02:00
/// COMPLETION LISTS
2014-09-24 21:55:27 +02:00
/**
* Get a string based representation of the completions
* to provide at the given source position and providing a member completion
2014-09-24 21:55:27 +02:00
* list if requested.
*/
2021-11-16 01:39:52 +01:00
public getCompletionsAtPosition(fileName: string, position: number, preferences: GetCompletionsAtPositionOptions | undefined, formattingSettings: FormatCodeSettings | undefined) {
2014-07-19 01:55:11 +02:00
return this.forwardJSONCall(
2021-11-16 01:39:52 +01:00
`getCompletionsAtPosition('${fileName}', ${position}, ${preferences}, ${formattingSettings})`,
() => this.languageService.getCompletionsAtPosition(fileName, position, preferences, formattingSettings)
2016-01-07 18:24:32 +01:00
);
2014-07-19 01:55:11 +02:00
}
2014-09-24 21:55:27 +02:00
/** Get a string based representation of a completion list entry details */
public getCompletionEntryDetails(fileName: string, position: number, entryName: string, formatOptions: string/*Services.FormatCodeOptions*/ | undefined, source: string | undefined, preferences: UserPreferences | undefined, data: CompletionEntryData | undefined) {
2014-07-19 01:55:11 +02:00
return this.forwardJSONCall(
2016-01-07 18:00:20 +01:00
`getCompletionEntryDetails('${fileName}', ${position}, '${entryName}')`,
Add exported members of all project files in the global completion list (#19069) * checker.ts: Remove null check on symbols * tsserverProjectSystem.ts: add two tests * client.ts, completions.ts, types.ts: Add codeActions member to CompletionEntryDetails * protocol.ts, session.ts: Add codeActions member to CompletionEntryDetails protocol * protocol.ts, session.ts, types.ts: add hasAction to CompletionEntry * session.ts, services.ts, types.ts: Add formattingOptions parameter to getCompletionEntryDetails * completions.ts: define SymbolOriginInfo type * completions.ts, services.ts: Add allSourceFiles parameter to getCompletionsAtPosition * completions.ts, services.ts: Plumb allSourceFiles into new function getSymbolsFromOtherSourceFileExports inside getCompletionData * completions.ts: add symbolToOriginInfoMap parameter to getCompletionEntriesFromSymbols and to return value of getCompletionData * utilities.ts: Add getOtherModuleSymbols, getUniqueSymbolIdAsString, getUniqueSymbolId * completions.ts: Set CompletionEntry.hasAction when symbol is found in symbolToOriginInfoMap (meaning there's an import action) * completions.ts: Populate list with possible exports (implement getSymbolsFromOtherSourceFileExports) * completions.ts, services.ts: Plumb host and rulesProvider into getCompletionEntryDetails * completions.ts: Add TODO comment * importFixes.ts: Add types ImportDeclarationMap and ImportCodeFixContext * Move getImportDeclarations into getCodeActionForImport, immediately after the implementation * importFixes.ts: Move createChangeTracker into getCodeActionForImport, immediately after getImportDeclarations * importFixes.ts: Add convertToImportCodeFixContext function and reference it from the getCodeActions lambda * importFixes.ts: Add context: ImportCodeFixContext parameter to getCodeActionForImport, update call sites, destructure it, use compilerOptions in getModuleSpecifierForNewImport * importFixes.ts: Remove moduleSymbol parameter from getImportDeclarations and use the ambient one * importFixes.ts: Use cachedImportDeclarations from context in getCodeActionForImport * importFixes.ts: Move createCodeAction out, immediately above convertToImportCodeFixContext * Move the declaration for lastImportDeclaration out of the getCodeActions lambda into getCodeActionForImport * importFixes.ts: Use symbolToken in getCodeActionForImport * importFixes.ts: Remove useCaseSensitiveFileNames altogether from getCodeActions lambda * importFixes.ts: Remove local getUniqueSymbolId function and add checker parameter to calls to it * importFixes.ts: Move getCodeActionForImport out into an export, immediately below convertToImportCodeFixContext * completions.ts: In getCompletionEntryDetails, if there's symbolOriginInfo, call getCodeActionForImport * importFixes.ts: Create and use importFixContext within getCodeActions lambda * importFixes.ts: Use local newLineCharacter instead of context.newLineCharacter in getCodeActionForImport * importFixes.ts: Use local host instead of context.host in getCodeActionForImport * importFixes.ts: Remove dummy getCanonicalFileName line * Filter symbols after gathering exports instead of before * Lint * Test, fix bugs, refactor * Suggestions from code review * Update api baseline * Fix bug if previousToken is not an Identifier * Replace `startsWith` with `stringContainsCharactersInOrder`
2017-10-17 19:20:11 +02:00
() => {
const localOptions: FormatCodeOptions = formatOptions === undefined ? undefined : JSON.parse(formatOptions);
return this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source, preferences, data);
Add exported members of all project files in the global completion list (#19069) * checker.ts: Remove null check on symbols * tsserverProjectSystem.ts: add two tests * client.ts, completions.ts, types.ts: Add codeActions member to CompletionEntryDetails * protocol.ts, session.ts: Add codeActions member to CompletionEntryDetails protocol * protocol.ts, session.ts, types.ts: add hasAction to CompletionEntry * session.ts, services.ts, types.ts: Add formattingOptions parameter to getCompletionEntryDetails * completions.ts: define SymbolOriginInfo type * completions.ts, services.ts: Add allSourceFiles parameter to getCompletionsAtPosition * completions.ts, services.ts: Plumb allSourceFiles into new function getSymbolsFromOtherSourceFileExports inside getCompletionData * completions.ts: add symbolToOriginInfoMap parameter to getCompletionEntriesFromSymbols and to return value of getCompletionData * utilities.ts: Add getOtherModuleSymbols, getUniqueSymbolIdAsString, getUniqueSymbolId * completions.ts: Set CompletionEntry.hasAction when symbol is found in symbolToOriginInfoMap (meaning there's an import action) * completions.ts: Populate list with possible exports (implement getSymbolsFromOtherSourceFileExports) * completions.ts, services.ts: Plumb host and rulesProvider into getCompletionEntryDetails * completions.ts: Add TODO comment * importFixes.ts: Add types ImportDeclarationMap and ImportCodeFixContext * Move getImportDeclarations into getCodeActionForImport, immediately after the implementation * importFixes.ts: Move createChangeTracker into getCodeActionForImport, immediately after getImportDeclarations * importFixes.ts: Add convertToImportCodeFixContext function and reference it from the getCodeActions lambda * importFixes.ts: Add context: ImportCodeFixContext parameter to getCodeActionForImport, update call sites, destructure it, use compilerOptions in getModuleSpecifierForNewImport * importFixes.ts: Remove moduleSymbol parameter from getImportDeclarations and use the ambient one * importFixes.ts: Use cachedImportDeclarations from context in getCodeActionForImport * importFixes.ts: Move createCodeAction out, immediately above convertToImportCodeFixContext * Move the declaration for lastImportDeclaration out of the getCodeActions lambda into getCodeActionForImport * importFixes.ts: Use symbolToken in getCodeActionForImport * importFixes.ts: Remove useCaseSensitiveFileNames altogether from getCodeActions lambda * importFixes.ts: Remove local getUniqueSymbolId function and add checker parameter to calls to it * importFixes.ts: Move getCodeActionForImport out into an export, immediately below convertToImportCodeFixContext * completions.ts: In getCompletionEntryDetails, if there's symbolOriginInfo, call getCodeActionForImport * importFixes.ts: Create and use importFixContext within getCodeActions lambda * importFixes.ts: Use local newLineCharacter instead of context.newLineCharacter in getCodeActionForImport * importFixes.ts: Use local host instead of context.host in getCodeActionForImport * importFixes.ts: Remove dummy getCanonicalFileName line * Filter symbols after gathering exports instead of before * Lint * Test, fix bugs, refactor * Suggestions from code review * Update api baseline * Fix bug if previousToken is not an Identifier * Replace `startsWith` with `stringContainsCharactersInOrder`
2017-10-17 19:20:11 +02:00
}
2016-01-07 18:24:32 +01:00
);
2014-07-19 01:55:11 +02:00
}
public getFormattingEditsForRange(fileName: string, start: number, end: number, options: string/*Services.FormatCodeOptions*/): string {
2014-07-19 01:55:11 +02:00
return this.forwardJSONCall(
2015-12-24 09:21:03 +01:00
`getFormattingEditsForRange('${fileName}', ${start}, ${end})`,
2014-07-19 01:55:11 +02:00
() => {
const localOptions: FormatCodeOptions = JSON.parse(options);
2016-01-07 18:16:14 +01:00
return this.languageService.getFormattingEditsForRange(fileName, start, end, localOptions);
2014-07-19 01:55:11 +02:00
});
}
public getFormattingEditsForDocument(fileName: string, options: string/*Services.FormatCodeOptions*/): string {
2014-07-19 01:55:11 +02:00
return this.forwardJSONCall(
2015-12-24 09:21:03 +01:00
`getFormattingEditsForDocument('${fileName}')`,
2014-07-19 01:55:11 +02:00
() => {
const localOptions: FormatCodeOptions = JSON.parse(options);
2016-01-07 18:16:14 +01:00
return this.languageService.getFormattingEditsForDocument(fileName, localOptions);
2014-07-19 01:55:11 +02:00
});
}
public getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: string/*Services.FormatCodeOptions*/): string {
return this.forwardJSONCall(
2015-12-24 09:21:03 +01:00
`getFormattingEditsAfterKeystroke('${fileName}', ${position}, '${key}')`,
2014-07-19 01:55:11 +02:00
() => {
const localOptions: FormatCodeOptions = JSON.parse(options);
2016-01-07 18:16:14 +01:00
return this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions);
2014-07-19 01:55:11 +02:00
});
}
public getDocCommentTemplateAtPosition(fileName: string, position: number, options?: DocCommentTemplateOptions): string {
2015-07-14 03:56:38 +02:00
return this.forwardJSONCall(
2015-12-24 09:21:03 +01:00
`getDocCommentTemplateAtPosition('${fileName}', ${position})`,
() => this.languageService.getDocCommentTemplateAtPosition(fileName, position, options)
2015-07-21 03:31:17 +02:00
);
2015-07-14 03:56:38 +02:00
}
2014-07-19 01:55:11 +02:00
/// NAVIGATE TO
2014-09-24 21:55:27 +02:00
/** Return a list of symbols that are interesting to navigate to */
public getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string): string {
2014-07-19 01:55:11 +02:00
return this.forwardJSONCall(
`getNavigateToItems('${searchValue}', ${maxResultCount}, ${fileName})`,
() => this.languageService.getNavigateToItems(searchValue, maxResultCount, fileName)
2016-01-07 18:24:32 +01:00
);
2014-07-19 01:55:11 +02:00
}
public getNavigationBarItems(fileName: string): string {
2014-07-19 01:55:11 +02:00
return this.forwardJSONCall(
2015-12-24 09:21:03 +01:00
`getNavigationBarItems('${fileName}')`,
2016-01-07 18:24:32 +01:00
() => this.languageService.getNavigationBarItems(fileName)
);
2014-07-19 01:55:11 +02:00
}
public getNavigationTree(fileName: string): string {
return this.forwardJSONCall(
`getNavigationTree('${fileName}')`,
() => this.languageService.getNavigationTree(fileName)
);
}
public getOutliningSpans(fileName: string): string {
2014-07-19 01:55:11 +02:00
return this.forwardJSONCall(
2015-12-24 09:21:03 +01:00
`getOutliningSpans('${fileName}')`,
2016-01-07 18:24:32 +01:00
() => this.languageService.getOutliningSpans(fileName)
);
}
public getTodoComments(fileName: string, descriptors: string): string {
return this.forwardJSONCall(
2015-12-24 09:21:03 +01:00
`getTodoComments('${fileName}')`,
2016-01-07 18:24:32 +01:00
() => this.languageService.getTodoComments(fileName, JSON.parse(descriptors))
);
2014-07-19 01:55:11 +02:00
}
/// CALL HIERARCHY
public prepareCallHierarchy(fileName: string, position: number): string {
return this.forwardJSONCall(
`prepareCallHierarchy('${fileName}', ${position})`,
() => this.languageService.prepareCallHierarchy(fileName, position)
);
}
public provideCallHierarchyIncomingCalls(fileName: string, position: number): string {
return this.forwardJSONCall(
`provideCallHierarchyIncomingCalls('${fileName}', ${position})`,
() => this.languageService.provideCallHierarchyIncomingCalls(fileName, position)
);
}
public provideCallHierarchyOutgoingCalls(fileName: string, position: number): string {
return this.forwardJSONCall(
`provideCallHierarchyOutgoingCalls('${fileName}', ${position})`,
() => this.languageService.provideCallHierarchyOutgoingCalls(fileName, position)
);
}
Add inlay hints support (#42089) * Add signature arguments label support * Support rest parameters and destruction * make lint * Fix tuple rest parameters * Adjust name styles * Rename to inline hints * Partition inline hints * Adjust range pred * Add function expression like hints * Support configure inline hints * Display hints in single line * Add test suits and tests * Add range tests * Support more hints * Add more options * Fix logical * Add more cases * Support call chains * Rename options * Match lastest protocol * Update protocol changes * Support context value and hover message * Revert "Support context value and hover message" This reverts commit 37a70896337ddd6dd5360d20e7001ed2338a2595. * Revert "Update protocol changes" This reverts commit e5ca31bc30362144c52c1c2512abc553f0c6b869. * Add hover message * Accept baseline * Update src/services/inlineHints.ts Co-authored-by: Daniel Rosenwasser <DanielRosenwasser@users.noreply.github.com> * Update src/services/inlineHints.ts Co-authored-by: Daniel Rosenwasser <DanielRosenwasser@users.noreply.github.com> * Cache across the program * Fix possible undefined * Update protocol changes * Fix missing property * Make lint happy * Avoid call chain hints * I'm bad * Add whitespace before type * Add more tests * Should care about jsdoc * Support complex rest parameter * Avoid module symbol hints * Care about leading comments * Fix CR issues * Avoid changes * Simplify comments contains * Fix CR issues * Accept baseline * Check parameter name before create regex * Rename option * Avoid makers * Skip parens for argument * Fix CR issues * Fix enums * Accept baseline Co-authored-by: Daniel Rosenwasser <DanielRosenwasser@users.noreply.github.com>
2021-06-25 08:06:34 +02:00
public provideInlayHints(fileName: string, span: TextSpan, preference: InlayHintsOptions | undefined): string {
return this.forwardJSONCall(
`provideInlayHints('${fileName}', '${JSON.stringify(span)}', ${JSON.stringify(preference)})`,
() => this.languageService.provideInlayHints(fileName, span, preference)
);
}
2014-07-19 01:55:11 +02:00
/// Emit
public getEmitOutput(fileName: string): string {
return this.forwardJSONCall(
2015-12-24 09:21:03 +01:00
`getEmitOutput('${fileName}')`,
() => {
const { diagnostics, ...rest } = this.languageService.getEmitOutput(fileName);
return { ...rest, diagnostics: this.realizeDiagnostics(diagnostics) };
}
2016-01-07 18:24:32 +01:00
);
2014-07-19 01:55:11 +02:00
}
public getEmitOutputObject(fileName: string): EmitOutput {
return forwardCall(
2016-07-02 05:30:08 +02:00
this.logger,
`getEmitOutput('${fileName}')`,
/*returnJson*/ false,
() => this.languageService.getEmitOutput(fileName),
this.logPerformance) as EmitOutput;
}
2020-03-03 01:30:42 +01:00
public toggleLineComment(fileName: string, textRange: TextRange): string {
return this.forwardJSONCall(
`toggleLineComment('${fileName}', '${JSON.stringify(textRange)}')`,
() => this.languageService.toggleLineComment(fileName, textRange)
);
}
2020-03-03 01:30:42 +01:00
public toggleMultilineComment(fileName: string, textRange: TextRange): string {
return this.forwardJSONCall(
`toggleMultilineComment('${fileName}', '${JSON.stringify(textRange)}')`,
() => this.languageService.toggleMultilineComment(fileName, textRange)
);
}
2020-02-29 03:45:56 +01:00
2020-03-03 01:30:42 +01:00
public commentSelection(fileName: string, textRange: TextRange): string {
2020-02-29 03:45:56 +01:00
return this.forwardJSONCall(
`commentSelection('${fileName}', '${JSON.stringify(textRange)}')`,
() => this.languageService.commentSelection(fileName, textRange)
);
}
2020-03-03 01:30:42 +01:00
public uncommentSelection(fileName: string, textRange: TextRange): string {
2020-02-29 03:45:56 +01:00
return this.forwardJSONCall(
`uncommentSelection('${fileName}', '${JSON.stringify(textRange)}')`,
() => this.languageService.uncommentSelection(fileName, textRange)
);
}
2014-07-19 01:55:11 +02:00
}
function convertClassifications(classifications: Classifications): { spans: string, endOfLineState: EndOfLineState } {
return { spans: classifications.spans.join(","), endOfLineState: classifications.endOfLineState };
}
class ClassifierShimObject extends ShimBase implements ClassifierShim {
2014-07-24 20:57:18 +02:00
public classifier: Classifier;
private logPerformance = false;
2014-07-19 01:55:11 +02:00
constructor(factory: ShimFactory, private logger: Logger) {
2014-07-19 01:55:11 +02:00
super(factory);
this.classifier = createClassifier();
2014-07-19 01:55:11 +02:00
}
Enable '--strictNullChecks' (#22088) * Enable '--strictNullChecks' * Fix API baselines * Make sys.getEnvironmentVariable non-nullable * make properties optional instead of using `| undefined` in thier type * reportDiagnostics should be required * Declare firstAccessor as non-nullable * Make `some` a type guard * Fix `getEnvironmentVariable` definition in tests * Pretend transformFlags are always defined * Fix one more use of sys.getEnvironmentVariable * `requiredResponse` accepts undefined, remove assertions * Mark optional properties as optional instead of using `| undefined` * Mark optional properties as optional instead of using ` | undefined` * Remove unnecessary null assertions * Put the bang on the declaration instead of every use * Make `createMapFromTemplate` require a parameter * Mark `EmitResult.emittedFiles` and `EmitResult.sourceMaps` as optional * Plumb through undefined in emitLsit and EmitExpressionList * `ElementAccessExpression.argumentExpression` can not be `undefined` * Add overloads for `writeTokenText` * Make `shouldWriteSeparatingLineTerminator` argument non-nullable * Make `synthesizedNodeStartsOnNewLine` argument required * `PropertyAssignment.initializer` cannot be undefined * Use one `!` at declaration site instead of on every use site * Capture host in a constant and avoid null assertions * Remove few more unused assertions * Update baselines * Use parameter defaults * Update baselines * Fix lint * Make Symbol#valueDeclaration and Symbol#declarations non-optional to reduce assertions * Make Node#symbol and Type#symbol non-optional to reduce assertions * Make `flags` non-nullable to reduce assertions * Convert some asserts to type guards * Make `isNonLocalAlias` a type guard * Add overload for `getSymbolOfNode` for `Declaration` * Some more `getSymbolOfNode` changes * Push undefined suppression into `typeToTypeNodeHelper` * `NodeBuilderContext.tracker` is never `undefined` * use `Debug.assertDefined` * Remove unnecessary tag * Mark `LiteralType.freshType` and `LiteralTupe.regularType` as required
2018-05-22 23:46:57 +02:00
public getEncodedLexicalClassifications(text: string, lexState: EndOfLineState, syntacticClassifierAbsent = false): string {
2015-05-01 02:39:51 +02:00
return forwardJSONCall(this.logger, "getEncodedLexicalClassifications",
() => convertClassifications(this.classifier.getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent)),
this.logPerformance);
}
2014-07-19 01:55:11 +02:00
/// COLORIZATION
Enable '--strictNullChecks' (#22088) * Enable '--strictNullChecks' * Fix API baselines * Make sys.getEnvironmentVariable non-nullable * make properties optional instead of using `| undefined` in thier type * reportDiagnostics should be required * Declare firstAccessor as non-nullable * Make `some` a type guard * Fix `getEnvironmentVariable` definition in tests * Pretend transformFlags are always defined * Fix one more use of sys.getEnvironmentVariable * `requiredResponse` accepts undefined, remove assertions * Mark optional properties as optional instead of using `| undefined` * Mark optional properties as optional instead of using ` | undefined` * Remove unnecessary null assertions * Put the bang on the declaration instead of every use * Make `createMapFromTemplate` require a parameter * Mark `EmitResult.emittedFiles` and `EmitResult.sourceMaps` as optional * Plumb through undefined in emitLsit and EmitExpressionList * `ElementAccessExpression.argumentExpression` can not be `undefined` * Add overloads for `writeTokenText` * Make `shouldWriteSeparatingLineTerminator` argument non-nullable * Make `synthesizedNodeStartsOnNewLine` argument required * `PropertyAssignment.initializer` cannot be undefined * Use one `!` at declaration site instead of on every use site * Capture host in a constant and avoid null assertions * Remove few more unused assertions * Update baselines * Use parameter defaults * Update baselines * Fix lint * Make Symbol#valueDeclaration and Symbol#declarations non-optional to reduce assertions * Make Node#symbol and Type#symbol non-optional to reduce assertions * Make `flags` non-nullable to reduce assertions * Convert some asserts to type guards * Make `isNonLocalAlias` a type guard * Add overload for `getSymbolOfNode` for `Declaration` * Some more `getSymbolOfNode` changes * Push undefined suppression into `typeToTypeNodeHelper` * `NodeBuilderContext.tracker` is never `undefined` * use `Debug.assertDefined` * Remove unnecessary tag * Mark `LiteralType.freshType` and `LiteralTupe.regularType` as required
2018-05-22 23:46:57 +02:00
public getClassificationsForLine(text: string, lexState: EndOfLineState, classifyKeywordsInGenerics = false): string {
2016-01-07 18:16:14 +01:00
const classification = this.classifier.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics);
2015-12-24 09:21:03 +01:00
let result = "";
2016-01-07 18:16:14 +01:00
for (const item of classification.entries) {
2015-12-24 09:21:03 +01:00
result += item.length + "\n";
result += item.classification + "\n";
2014-07-19 01:55:11 +02:00
}
result += classification.finalLexState;
return result;
}
}
class CoreServicesShimObject extends ShimBase implements CoreServicesShim {
private logPerformance = false;
private safeList: JsTyping.SafeList | undefined;
2017-07-14 23:26:13 +02:00
constructor(factory: ShimFactory, public readonly logger: Logger, private readonly host: CoreServicesShimHostAdapter) {
2014-07-19 01:55:11 +02:00
super(factory);
}
private forwardJSONCall(actionDescription: string, action: () => {}): string {
return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance);
2014-07-19 01:55:11 +02:00
}
2015-12-24 09:21:03 +01:00
public resolveModuleName(fileName: string, moduleName: string, compilerOptionsJson: string): string {
return this.forwardJSONCall(`resolveModuleName('${fileName}')`, () => {
const compilerOptions = JSON.parse(compilerOptionsJson) as CompilerOptions;
const result = resolveModuleName(moduleName, normalizeSlashes(fileName), compilerOptions, this.host);
let resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined;
if (result.resolvedModule && result.resolvedModule.extension !== Extension.Ts && result.resolvedModule.extension !== Extension.Tsx && result.resolvedModule.extension !== Extension.Dts) {
resolvedFileName = undefined;
}
return {
resolvedFileName,
failedLookupLocations: result.failedLookupLocations
};
2015-12-24 09:21:03 +01:00
});
}
2014-07-19 01:55:11 +02:00
public resolveTypeReferenceDirective(fileName: string, typeReferenceDirective: string, compilerOptionsJson: string): string {
return this.forwardJSONCall(`resolveTypeReferenceDirective(${fileName})`, () => {
const compilerOptions = JSON.parse(compilerOptionsJson) as CompilerOptions;
const result = resolveTypeReferenceDirective(typeReferenceDirective, normalizeSlashes(fileName), compilerOptions, this.host);
return {
resolvedFileName: result.resolvedTypeReferenceDirective ? result.resolvedTypeReferenceDirective.resolvedFileName : undefined,
primary: result.resolvedTypeReferenceDirective ? result.resolvedTypeReferenceDirective.primary : true,
failedLookupLocations: result.failedLookupLocations
};
});
}
public getPreProcessedFileInfo(fileName: string, sourceTextSnapshot: IScriptSnapshot): string {
2014-07-19 01:55:11 +02:00
return this.forwardJSONCall(
`getPreProcessedFileInfo('${fileName}')`,
2014-07-19 01:55:11 +02:00
() => {
2016-06-03 18:33:17 +02:00
// for now treat files as JavaScript
const result = preProcessFile(getSnapshotText(sourceTextSnapshot), /* readImportFiles */ true, /* detectJavaScriptImports */ true);
return {
referencedFiles: this.convertFileReferences(result.referencedFiles),
importedFiles: this.convertFileReferences(result.importedFiles),
ambientExternalModules: result.ambientExternalModules,
isLibFile: result.isLibFile,
2018-05-03 20:00:10 +02:00
typeReferenceDirectives: this.convertFileReferences(result.typeReferenceDirectives),
libReferenceDirectives: this.convertFileReferences(result.libReferenceDirectives)
2014-10-28 22:45:32 +01:00
};
});
}
2014-10-28 22:45:32 +01:00
public getAutomaticTypeDirectiveNames(compilerOptionsJson: string): string {
return this.forwardJSONCall(
`getAutomaticTypeDirectiveNames('${compilerOptionsJson}')`,
() => {
const compilerOptions = JSON.parse(compilerOptionsJson) as CompilerOptions;
return getAutomaticTypeDirectiveNames(compilerOptions, this.host);
}
);
}
Enable '--strictNullChecks' (#22088) * Enable '--strictNullChecks' * Fix API baselines * Make sys.getEnvironmentVariable non-nullable * make properties optional instead of using `| undefined` in thier type * reportDiagnostics should be required * Declare firstAccessor as non-nullable * Make `some` a type guard * Fix `getEnvironmentVariable` definition in tests * Pretend transformFlags are always defined * Fix one more use of sys.getEnvironmentVariable * `requiredResponse` accepts undefined, remove assertions * Mark optional properties as optional instead of using `| undefined` * Mark optional properties as optional instead of using ` | undefined` * Remove unnecessary null assertions * Put the bang on the declaration instead of every use * Make `createMapFromTemplate` require a parameter * Mark `EmitResult.emittedFiles` and `EmitResult.sourceMaps` as optional * Plumb through undefined in emitLsit and EmitExpressionList * `ElementAccessExpression.argumentExpression` can not be `undefined` * Add overloads for `writeTokenText` * Make `shouldWriteSeparatingLineTerminator` argument non-nullable * Make `synthesizedNodeStartsOnNewLine` argument required * `PropertyAssignment.initializer` cannot be undefined * Use one `!` at declaration site instead of on every use site * Capture host in a constant and avoid null assertions * Remove few more unused assertions * Update baselines * Use parameter defaults * Update baselines * Fix lint * Make Symbol#valueDeclaration and Symbol#declarations non-optional to reduce assertions * Make Node#symbol and Type#symbol non-optional to reduce assertions * Make `flags` non-nullable to reduce assertions * Convert some asserts to type guards * Make `isNonLocalAlias` a type guard * Add overload for `getSymbolOfNode` for `Declaration` * Some more `getSymbolOfNode` changes * Push undefined suppression into `typeToTypeNodeHelper` * `NodeBuilderContext.tracker` is never `undefined` * use `Debug.assertDefined` * Remove unnecessary tag * Mark `LiteralType.freshType` and `LiteralTupe.regularType` as required
2018-05-22 23:46:57 +02:00
private convertFileReferences(refs: FileReference[]): ShimsFileReference[] | undefined {
if (!refs) {
return undefined;
}
const result: ShimsFileReference[] = [];
for (const ref of refs) {
result.push({
path: normalizeSlashes(ref.fileName),
position: ref.pos,
length: ref.end - ref.pos
2014-07-19 01:55:11 +02:00
});
}
return result;
2014-07-19 01:55:11 +02:00
}
public getTSConfigFileInfo(fileName: string, sourceTextSnapshot: IScriptSnapshot): string {
return this.forwardJSONCall(
2015-12-24 09:21:03 +01:00
`getTSConfigFileInfo('${fileName}')`,
() => {
const result = parseJsonText(fileName, getSnapshotText(sourceTextSnapshot));
2016-01-21 19:43:07 +01:00
const normalizedFileName = normalizeSlashes(fileName);
const configFile = parseJsonSourceFileConfigFileContent(result, this.host, getDirectoryPath(normalizedFileName), /*existingOptions*/ {}, normalizedFileName);
return {
options: configFile.options,
typeAcquisition: configFile.typeAcquisition,
files: configFile.fileNames,
raw: configFile.raw,
errors: realizeDiagnostics([...result.parseDiagnostics, ...configFile.errors], "\r\n")
};
});
}
2014-07-19 01:55:11 +02:00
public getDefaultCompilationSettings(): string {
return this.forwardJSONCall(
"getDefaultCompilationSettings()",
2016-01-07 18:24:32 +01:00
() => getDefaultCompilerOptions()
);
2014-07-19 01:55:11 +02:00
}
public discoverTypings(discoverTypingsJson: string): string {
const getCanonicalFileName = createGetCanonicalFileName(/*useCaseSensitivefileNames:*/ false);
return this.forwardJSONCall("discoverTypings()", () => {
const info = JSON.parse(discoverTypingsJson) as DiscoverTypingsInfo;
if (this.safeList === undefined) {
this.safeList = JsTyping.loadSafeList(this.host, toPath(info.safeListPath, info.safeListPath, getCanonicalFileName));
}
return JsTyping.discoverTypings(
this.host,
msg => this.logger.log(msg),
info.fileNames,
toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName),
this.safeList,
info.packageNameToTypingLocation,
info.typeAcquisition,
info.unresolvedImports,
info.typesRegistry);
});
}
2014-07-13 01:04:16 +02:00
}
export class TypeScriptServicesFactory implements ShimFactory {
private _shims: Shim[] = [];
private documentRegistry: DocumentRegistry | undefined;
/*
* Returns script API version.
*/
public getServicesVersion(): string {
return servicesVersion;
}
public createLanguageServiceShim(host: LanguageServiceShimHost): LanguageServiceShim {
try {
if (this.documentRegistry === undefined) {
this.documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory());
}
2016-01-07 18:16:14 +01:00
const hostAdapter = new LanguageServiceShimHostAdapter(host);
const languageService = createLanguageService(hostAdapter, this.documentRegistry, /*syntaxOnly*/ false);
2014-08-08 08:32:43 +02:00
return new LanguageServiceShimObject(this, host, languageService);
}
catch (err) {
2014-07-24 20:57:18 +02:00
logInternalError(host, err);
throw err;
}
}
2014-08-17 04:03:07 +02:00
public createClassifierShim(logger: Logger): ClassifierShim {
try {
return new ClassifierShimObject(this, logger);
}
catch (err) {
2014-08-17 04:03:07 +02:00
logInternalError(logger, err);
throw err;
}
}
public createCoreServicesShim(host: CoreServicesShimHost): CoreServicesShim {
try {
2016-01-07 18:16:14 +01:00
const adapter = new CoreServicesShimHostAdapter(host);
return new CoreServicesShimObject(this, host as Logger, adapter);
}
catch (err) {
logInternalError(host as Logger, err);
throw err;
}
}
public close(): void {
// Forget all the registered shims
2017-07-18 20:08:44 +02:00
clear(this._shims);
this.documentRegistry = undefined;
}
public registerShim(shim: Shim): void {
this._shims.push(shim);
}
public unregisterShim(shim: Shim): void {
2016-12-19 19:12:35 +01:00
for (let i = 0; i < this._shims.length; i++) {
if (this._shims[i] === shim) {
delete this._shims[i];
return;
}
}
throw new Error("Invalid operation");
}
}
}
/* eslint-enable no-in-operator */