From 9be3087555f4530f81bc7bb97e79e768337c83bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dirk=20B=C3=A4umer?= Date: Wed, 6 Dec 2023 15:22:05 +0100 Subject: [PATCH] Adjust ESLint rules to match the VS Code rules (#1377) * Adjust ESLint rules to match the VS Code rules * Some more --- .eslintrc.base.json | 50 +++++++++- client-node-tests/src/converter.test.ts | 2 +- client-node-tests/src/helpers.test.ts | 48 ++++----- client-node-tests/src/integration.test.ts | 7 +- client/src/common/client.ts | 73 ++++++-------- client/src/common/codeConverter.ts | 26 ++--- client/src/common/colorProvider.ts | 2 +- client/src/common/completion.ts | 2 +- client/src/common/configuration.ts | 40 ++++---- client/src/common/definition.ts | 2 +- client/src/common/diagnostic.ts | 4 +- client/src/common/documentLink.ts | 2 +- client/src/common/documentSymbol.ts | 2 +- client/src/common/executeCommand.ts | 4 +- client/src/common/features.ts | 8 +- client/src/common/fileSystemWatcher.ts | 10 +- client/src/common/foldingRange.ts | 4 +- client/src/common/formatting.ts | 2 +- client/src/common/implementation.ts | 4 +- client/src/common/inlineCompletion.ts | 2 +- client/src/common/linkedEditingRange.ts | 2 +- client/src/common/protocolConverter.ts | 56 +++++------ client/src/common/rename.ts | 6 +- client/src/common/signatureHelp.ts | 2 +- client/src/common/textSynchronization.ts | 22 ++--- client/src/common/typeDefinition.ts | 4 +- client/src/common/utils/async.ts | 4 +- client/src/common/workspaceFolder.ts | 16 +-- client/src/common/workspaceSymbol.ts | 2 +- client/src/node/main.ts | 24 ++--- client/src/node/processes.ts | 6 +- jsonrpc/src/browser/test/test.ts | 1 - jsonrpc/src/common/connection.ts | 3 +- jsonrpc/src/common/messageBuffer.ts | 4 +- jsonrpc/src/common/messageReader.ts | 2 +- jsonrpc/src/common/messageWriter.ts | 2 +- jsonrpc/src/common/test/linkedMap.test.ts | 22 ++--- jsonrpc/src/node/main.ts | 4 +- jsonrpc/src/node/test/connection.test.ts | 10 +- protocol/src/common/protocol.ts | 10 +- protocol/src/node/test/connection.test.ts | 6 +- server/src/common/configuration.ts | 2 +- server/src/common/progress.ts | 6 +- server/src/common/server.ts | 40 ++++---- server/src/common/textDocuments.ts | 8 +- server/src/common/workspaceFolder.ts | 2 +- server/src/node/files.ts | 38 +++---- server/src/node/main.ts | 30 +++--- server/src/node/resolve.ts | 2 +- server/src/node/test/connection.test.ts | 2 +- testbed/client/src/extension.ts | 10 +- testbed/client/src/measure.ts | 2 +- testbed/server/src/fullNotebookServer.ts | 2 +- testbed/server/src/server.ts | 14 +-- testbed/server/src/simpleNotebookServer.ts | 4 +- textDocument/src/main.ts | 30 +++--- textDocument/src/test/edits.test.ts | 8 +- textDocument/src/test/textdocument.test.ts | 12 +-- tools/src/generator-main.ts | 12 +-- tools/src/typescripts.ts | 10 +- tools/src/visitor.ts | 2 +- types/src/main.ts | 110 ++++++++++----------- types/src/test/edits.test.ts | 8 +- types/src/test/textdocument.test.ts | 30 +++--- 64 files changed, 460 insertions(+), 426 deletions(-) diff --git a/.eslintrc.base.json b/.eslintrc.base.json index aa4d4b077..5c32f11a3 100644 --- a/.eslintrc.base.json +++ b/.eslintrc.base.json @@ -24,12 +24,56 @@ }, "multilineDetection": "brackets" }], + "indent": "off", + "@typescript-eslint/indent": ["warn", "tab", { "SwitchCase": 1 } ], + "@typescript-eslint/no-floating-promises": "error", "no-extra-semi": "warn", "curly": "warn", "quotes": ["error", "single", { "allowTemplateLiterals": true } ], "eqeqeq": "error", - "indent": "off", - "@typescript-eslint/indent": ["warn", "tab", { "SwitchCase": 1 } ], - "@typescript-eslint/no-floating-promises": "error" + "constructor-super": "warn", + "prefer-const": [ + "warn", + { + "destructuring": "all" + } + ], + "no-buffer-constructor": "warn", + "no-caller": "warn", + "no-case-declarations": "warn", + "no-debugger": "warn", + "no-duplicate-case": "warn", + "no-duplicate-imports": "warn", + "no-eval": "warn", + "no-async-promise-executor": "warn", + "no-new-wrappers": "warn", + "no-redeclare": "off", + "no-sparse-arrays": "warn", + "no-throw-literal": "warn", + "no-unsafe-finally": "warn", + "no-unused-labels": "warn", + "no-restricted-globals": [ + "warn", + "name", + "length", + "event", + "closed", + "external", + "status", + "origin", + "orientation", + "context" + ], + "no-var": "warn", + "@typescript-eslint/naming-convention": [ + "warn", + { + "selector": "class", + "format": [ + "PascalCase" + ], + "leadingUnderscore": "allow" + } + ] } } \ No newline at end of file diff --git a/client-node-tests/src/converter.test.ts b/client-node-tests/src/converter.test.ts index 27a4bcd96..6c6d78e61 100644 --- a/client-node-tests/src/converter.test.ts +++ b/client-node-tests/src/converter.test.ts @@ -1249,7 +1249,7 @@ suite('Protocol Converter', () => { const result = await p2c.asInlayHints(items); ok(result.every(hint => hint instanceof ProtocolInlayHint)); - for (var i = 0; i < result.length; i++) { + for (let i = 0; i < result.length; i++) { positionEqual(result[i].position, items[i].position); } strictEqual((result[0] as ProtocolInlayHint).data, '1'); diff --git a/client-node-tests/src/helpers.test.ts b/client-node-tests/src/helpers.test.ts index 5ec94f8ad..90dffd73e 100644 --- a/client-node-tests/src/helpers.test.ts +++ b/client-node-tests/src/helpers.test.ts @@ -20,14 +20,14 @@ suite('Protocol Helper Tests', () => { } test('Position', () => { - let position: Position = Position.create(1, 2); + const position: Position = Position.create(1, 2); strictEqual(position.line, 1); strictEqual(position.character, 2); ok(Position.is(position)); }); test('Range - start/end', () => { - let range: Range = Range.create(Position.create(1, 2), Position.create(8,9)); + const range: Range = Range.create(Position.create(1, 2), Position.create(8,9)); strictEqual(range.start.line, 1); strictEqual(range.start.character, 2); strictEqual(range.end.line, 8); @@ -36,7 +36,7 @@ suite('Protocol Helper Tests', () => { }); test('Range - line/character', () => { - let range: Range = Range.create(1,2,8,9); + const range: Range = Range.create(1,2,8,9); strictEqual(range.start.line, 1); strictEqual(range.start.character, 2); strictEqual(range.end.line, 8); @@ -45,15 +45,15 @@ suite('Protocol Helper Tests', () => { }); test('TextDocumentIdentifier', () => { - let uri = 'file:///folder/file.txt'; - let identifier = TextDocumentIdentifier.create(uri); + const uri = 'file:///folder/file.txt'; + const identifier = TextDocumentIdentifier.create(uri); strictEqual(identifier.uri, uri); ok(TextDocumentIdentifier.is(identifier)); }); test('VersionedTextDocumentIdentifier', () => { - let uri = 'file:///folder/file.txt'; - let identifier = VersionedTextDocumentIdentifier.create(uri, 9); + const uri = 'file:///folder/file.txt'; + const identifier = VersionedTextDocumentIdentifier.create(uri, 9); strictEqual(identifier.uri, uri); strictEqual(identifier.version, 9); ok(VersionedTextDocumentIdentifier.is(identifier)); @@ -68,8 +68,8 @@ suite('Protocol Helper Tests', () => { // }); test('TextDocumentItem', () => { - let uri = 'file:///folder/file.txt'; - let item = TextDocumentItem.create(uri, 'pain-text', 9, 'content'); + const uri = 'file:///folder/file.txt'; + const item = TextDocumentItem.create(uri, 'pain-text', 9, 'content'); strictEqual(item.uri, uri); strictEqual(item.languageId, 'pain-text'); strictEqual(item.version, 9); @@ -78,7 +78,7 @@ suite('Protocol Helper Tests', () => { }); test('Diagnostic', () => { - let diagnostic = Diagnostic.create(Range.create(1,2,8,9), 'message', DiagnosticSeverity.Warning, 99, 'source'); + const diagnostic = Diagnostic.create(Range.create(1,2,8,9), 'message', DiagnosticSeverity.Warning, 99, 'source'); ok(Range.is(diagnostic.range)); strictEqual(diagnostic.message, 'message'); strictEqual(diagnostic.severity, DiagnosticSeverity.Warning); @@ -87,15 +87,15 @@ suite('Protocol Helper Tests', () => { }); test('Command', () => { - let command = Command.create('title', 'command', 'arg'); + const command = Command.create('title', 'command', 'arg'); strictEqual(command.title, 'title'); strictEqual(command.command, 'command'); strictEqual(command.arguments![0], 'arg'); }); test('CodeLens', () => { - let codeLens = CodeLens.create(Range.create(1,2,8,9), 'data'); - let range = codeLens.range; + const codeLens = CodeLens.create(Range.create(1,2,8,9), 'data'); + const range = codeLens.range; strictEqual(range.start.line, 1); strictEqual(range.start.character, 2); strictEqual(range.end.line, 8); @@ -104,22 +104,22 @@ suite('Protocol Helper Tests', () => { }); test('CodeActionContext', () => { - let codeActionContext = CodeActionContext.create([Diagnostic.create(Range.create(1, 2, 8, 9), 'message')]); + const codeActionContext = CodeActionContext.create([Diagnostic.create(Range.create(1, 2, 8, 9), 'message')]); strictEqual(codeActionContext.diagnostics.length, 1); ok(Diagnostic.is(codeActionContext.diagnostics[0])); }); test('WorkspaceEdit - documentChanges', () => { - let workspaceChange = new WorkspaceChange(); - let uri = 'file:///abc.txt'; - let change1 = workspaceChange.getTextEditChange({uri: uri, version: 10}); + const workspaceChange = new WorkspaceChange(); + const uri = 'file:///abc.txt'; + const change1 = workspaceChange.getTextEditChange({uri: uri, version: 10}); change1.insert(Position.create(0,1), 'insert'); change1.replace(Range.create(0,1,2,3), 'replace'); change1.delete(Range.create(0,1,2,3)); - let change2 = workspaceChange.getTextEditChange({ uri: 'file:///xyz.txt', version: 20 }); + const change2 = workspaceChange.getTextEditChange({ uri: 'file:///xyz.txt', version: 20 }); change2.insert(Position.create(2,3), 'insert'); - let workspaceEdit = workspaceChange.edit; + const workspaceEdit = workspaceChange.edit; strictEqual(workspaceEdit.changeAnnotations, undefined); strictEqual(workspaceEdit.documentChanges!.length, 2); let edits = (workspaceEdit.documentChanges![0] as TextDocumentEdit).edits; @@ -151,16 +151,16 @@ suite('Protocol Helper Tests', () => { }); test('WorkspaceEdit - changes', () => { - let workspaceChange = new WorkspaceChange(); - let uri = 'file:///abc.txt'; - let change1 = workspaceChange.getTextEditChange(uri); + const workspaceChange = new WorkspaceChange(); + const uri = 'file:///abc.txt'; + const change1 = workspaceChange.getTextEditChange(uri); change1.insert(Position.create(0,1), 'insert'); change1.replace(Range.create(0,1,2,3), 'replace'); change1.delete(Range.create(0,1,2,3)); - let change2 = workspaceChange.getTextEditChange('file:///xyz.txt'); + const change2 = workspaceChange.getTextEditChange('file:///xyz.txt'); change2.insert(Position.create(2,3), 'insert'); - let workspaceEdit = workspaceChange.edit; + const workspaceEdit = workspaceChange.edit; strictEqual(workspaceEdit.changeAnnotations, undefined); strictEqual(Object.keys(workspaceEdit.changes!).length, 2); let edits = workspaceEdit.changes![uri]; diff --git a/client-node-tests/src/integration.test.ts b/client-node-tests/src/integration.test.ts index 6eb289334..dd89f86f7 100644 --- a/client-node-tests/src/integration.test.ts +++ b/client-node-tests/src/integration.test.ts @@ -225,7 +225,7 @@ suite('Client integration', () => { }); test('InitializeResult', () => { - let expected = { + const expected = { capabilities: { textDocumentSync: 1, definitionProvider: true, @@ -955,6 +955,7 @@ suite('Client integration', () => { const feature = client.getFeature(lsclient.WillCreateFilesRequest.method); isDefined(feature); + // eslint-disable-next-line no-async-promise-executor const sendCreateRequest = () => new Promise(async (resolve, reject) => { await feature.send({ files: createFiles, waitUntil: resolve, token: tokenSource.token }); // If feature.send didn't call waitUntil synchronously then something went wrong. @@ -1039,6 +1040,7 @@ suite('Client integration', () => { const feature = client.getFeature(lsclient.WillRenameFilesRequest.method); isDefined(feature); + // eslint-disable-next-line no-async-promise-executor const sendRenameRequest = () => new Promise(async (resolve, reject) => { await feature.send({ files: renameFiles, waitUntil: resolve, token: tokenSource.token }); // If feature.send didn't call waitUntil synchronously then something went wrong. @@ -1087,6 +1089,7 @@ suite('Client integration', () => { // DidRename relies on WillRename firing first and the items existing on disk in their correct locations // so that the type of the items can be checked and stashed before they're actually renamed. await createTestItems(renameFiles.map((f) => f.oldUri)); + // eslint-disable-next-line no-async-promise-executor await new Promise(async (resolve, reject) => { const featureWithWillRename = feature as any as { willRename(e: vscode.FileWillRenameEvent): void }; featureWithWillRename.willRename({ files: renameFiles, waitUntil: resolve, token: tokenSource.token }); @@ -1137,6 +1140,7 @@ suite('Client integration', () => { const feature = client.getFeature(lsclient.WillDeleteFilesRequest.method); isDefined(feature); + // eslint-disable-next-line no-async-promise-executor const sendDeleteRequest = () => new Promise(async (resolve, reject) => { await feature.send({ files: deleteFiles, waitUntil: resolve, token: tokenSource.token }); // If feature.send didn't call waitUntil synchronously then something went wrong. @@ -1185,6 +1189,7 @@ suite('Client integration', () => { // DidDelete relies on WillDelete firing first and the items actually existing on disk // so that the type of the items can be checked and stashed before they're actually deleted. await createTestItems(deleteFiles); + // eslint-disable-next-line no-async-promise-executor await new Promise(async (resolve, reject) => { const featureWithWillDelete = feature as any as { willDelete(e: vscode.FileWillDeleteEvent): void }; featureWithWillDelete.willDelete({ files: deleteFiles, waitUntil: resolve, token: tokenSource.token }); diff --git a/client/src/common/client.ts b/client/src/common/client.ts index 107dfdefa..9da6b9de9 100644 --- a/client/src/common/client.ts +++ b/client/src/common/client.ts @@ -70,44 +70,29 @@ import { DocumentHighlightFeature, DocumentHighlightMiddleware } from './documen import { DocumentSymbolFeature, DocumentSymbolMiddleware } from './documentSymbol'; import { WorkspaceSymbolFeature, WorkspaceSymbolMiddleware } from './workspaceSymbol'; import { ReferencesFeature, ReferencesMiddleware } from './reference'; -import { TypeDefinitionMiddleware } from './typeDefinition'; -import { ImplementationMiddleware } from './implementation'; -import { ColorProviderMiddleware } from './colorProvider'; +import { TypeDefinitionFeature, TypeDefinitionMiddleware } from './typeDefinition'; +import { ImplementationFeature, ImplementationMiddleware } from './implementation'; +import { ColorProviderFeature, ColorProviderMiddleware } from './colorProvider'; import { CodeActionFeature, CodeActionMiddleware } from './codeAction'; import { CodeLensFeature, CodeLensMiddleware, CodeLensProviderShape } from './codeLens'; import { DocumentFormattingFeature, DocumentOnTypeFormattingFeature, DocumentRangeFormattingFeature, FormattingMiddleware } from './formatting'; import { RenameFeature, RenameMiddleware } from './rename'; import { DocumentLinkFeature, DocumentLinkMiddleware } from './documentLink'; import { ExecuteCommandFeature, ExecuteCommandMiddleware } from './executeCommand'; -import { FoldingRangeProviderMiddleware, FoldingRangeProviderShape } from './foldingRange'; -import { DeclarationMiddleware } from './declaration'; -import { SelectionRangeProviderMiddleware } from './selectionRange'; -import { CallHierarchyMiddleware } from './callHierarchy'; -import { SemanticTokensMiddleware, SemanticTokensProviderShape } from './semanticTokens'; -import { LinkedEditingRangeMiddleware } from './linkedEditingRange'; -import { TypeHierarchyMiddleware } from './typeHierarchy'; -import { InlineValueMiddleware, InlineValueProviderShape } from './inlineValue'; -import { InlayHintsMiddleware, InlayHintsProviderShape } from './inlayHint'; -import { WorkspaceFolderMiddleware } from './workspaceFolder'; -import { FileOperationsMiddleware } from './fileOperations'; -import { InlineCompletionMiddleware } from './inlineCompletion'; +import { FoldingRangeFeature, FoldingRangeProviderMiddleware, FoldingRangeProviderShape } from './foldingRange'; +import { DeclarationFeature, DeclarationMiddleware } from './declaration'; +import { SelectionRangeFeature, SelectionRangeProviderMiddleware } from './selectionRange'; +import { CallHierarchyFeature, CallHierarchyMiddleware } from './callHierarchy'; +import { SemanticTokensFeature, SemanticTokensMiddleware, SemanticTokensProviderShape } from './semanticTokens'; +import { LinkedEditingFeature, LinkedEditingRangeMiddleware } from './linkedEditingRange'; +import { TypeHierarchyFeature, TypeHierarchyMiddleware } from './typeHierarchy'; +import { InlineValueFeature, InlineValueMiddleware, InlineValueProviderShape } from './inlineValue'; +import { InlayHintsFeature, InlayHintsMiddleware, InlayHintsProviderShape } from './inlayHint'; +import { WorkspaceFoldersFeature, WorkspaceFolderMiddleware } from './workspaceFolder'; +import { DidCreateFilesFeature, DidDeleteFilesFeature, DidRenameFilesFeature, WillCreateFilesFeature, WillDeleteFilesFeature, WillRenameFilesFeature, FileOperationsMiddleware } from './fileOperations'; +import { InlineCompletionItemFeature, InlineCompletionMiddleware } from './inlineCompletion'; import { FileSystemWatcherFeature } from './fileSystemWatcher'; -import { ColorProviderFeature } from './colorProvider'; -import { ImplementationFeature } from './implementation'; -import { TypeDefinitionFeature } from './typeDefinition'; -import { WorkspaceFoldersFeature } from './workspaceFolder'; -import { FoldingRangeFeature } from './foldingRange'; -import { DeclarationFeature } from './declaration'; -import { SelectionRangeFeature } from './selectionRange'; import { ProgressFeature } from './progress'; -import { CallHierarchyFeature } from './callHierarchy'; -import { SemanticTokensFeature } from './semanticTokens'; -import { DidCreateFilesFeature, DidDeleteFilesFeature, DidRenameFilesFeature, WillCreateFilesFeature, WillDeleteFilesFeature, WillRenameFilesFeature } from './fileOperations'; -import { LinkedEditingFeature } from './linkedEditingRange'; -import { TypeHierarchyFeature } from './typeHierarchy'; -import { InlineValueFeature } from './inlineValue'; -import { InlayHintsFeature } from './inlayHint'; -import { InlineCompletionItemFeature } from './inlineCompletion'; /** * Controls when the output channel is revealed. @@ -448,7 +433,7 @@ class DefaultErrorHandler implements ErrorHandler { if (this.restarts.length <= this.maxRestartCount) { return { action: CloseAction.Restart }; } else { - let diff = this.restarts[this.restarts.length - 1] - this.restarts[0]; + const diff = this.restarts[this.restarts.length - 1] - this.restarts[0]; if (diff <= 3 * 60 * 1000) { return { action: CloseAction.DoNotRestart, message: `The ${this.client.name} server crashed ${this.maxRestartCount+1} times in the last 3 minutes. The server will not be restarted. See the output for more information.` }; } else { @@ -476,7 +461,7 @@ export interface MessageTransports { export namespace MessageTransports { export function is(value: any): value is MessageTransports { - let candidate: MessageTransports = value; + const candidate: MessageTransports = value; return candidate && MessageReader.is(value.reader) && MessageWriter.is(value.writer); } } @@ -684,9 +669,9 @@ export abstract class BaseLanguageClient implements FeatureClient { @@ -1341,11 +1326,11 @@ export abstract class BaseLanguageClient implements FeatureClient { - let errorHandler = (error: Error, message: Message | undefined, count: number | undefined) => { + const errorHandler = (error: Error, message: Message | undefined, count: number | undefined) => { this.handleConnectionError(error, message, count).catch((error) => this.error(`Handling connection error failed`, error)); }; - let closeHandler = () => { + const closeHandler = () => { this.handleConnectionClosed().catch((error) => this.error(`Handling connection close failed`, error)); }; @@ -1679,7 +1664,7 @@ export abstract class BaseLanguageClient implements FeatureClient> = new Map>(); public registerFeatures(features: (StaticFeature | DynamicFeature)[]): void { - for (let feature of features) { + for (const feature of features) { this.registerFeature(feature); } } @@ -1831,7 +1816,7 @@ export abstract class BaseLanguageClient implements FeatureClient): (StaticFeature | DynamicFeature)[] { - let result: (StaticFeature | DynamicFeature)[] = [ + const result: (StaticFeature | DynamicFeature)[] = [ new InlineCompletionItemFeature(_client) ]; return result; diff --git a/client/src/common/codeConverter.ts b/client/src/common/codeConverter.ts index 651aa0ca6..22a8af50b 100644 --- a/client/src/common/codeConverter.ts +++ b/client/src/common/codeConverter.ts @@ -243,7 +243,7 @@ export function createConverter(uriConverter?: URIConverter): Converter { } function asSaveTextDocumentParams(textDocument: code.TextDocument, includeContent: boolean = false): proto.DidSaveTextDocumentParams { - let result: proto.DidSaveTextDocumentParams = { + const result: proto.DidSaveTextDocumentParams = { textDocument: asTextDocumentIdentifier(textDocument) }; if (includeContent) { @@ -478,9 +478,9 @@ export function createConverter(uriConverter?: URIConverter): Converter { if (!tags) { return undefined; } - let result: code.DiagnosticTag[] = []; - for (let tag of tags) { - let converted = asDiagnosticTag(tag); + const result: code.DiagnosticTag[] = []; + for (const tag of tags) { + const converted = asDiagnosticTag(tag); if (converted !== undefined) { result.push(converted); } @@ -584,7 +584,7 @@ export function createConverter(uriConverter?: URIConverter): Converter { return tags; } const result: proto.CompletionItemTag[] = []; - for (let tag of tags) { + for (const tag of tags) { const converted = asCompletionItemTag(tag); if (converted !== undefined) { result.push(converted); @@ -611,11 +611,11 @@ export function createConverter(uriConverter?: URIConverter): Converter { labelDetails = { detail: item.label.detail, description: item.label.description }; } } - let result: proto.CompletionItem = { label: label }; + const result: proto.CompletionItem = { label: label }; if (labelDetails !== undefined) { result.labelDetails = labelDetails; } - let protocolItem = item instanceof ProtocolCompletionItem ? item as ProtocolCompletionItem : undefined; + const protocolItem = item instanceof ProtocolCompletionItem ? item as ProtocolCompletionItem : undefined; if (item.detail) { result.detail = item.detail; } // We only send items back we created. So this can't be something else than // a string right now. @@ -732,7 +732,7 @@ export function createConverter(uriConverter?: URIConverter): Converter { } async function asCodeAction(item: code.CodeAction, token?: code.CancellationToken): Promise { - let result = proto.CodeAction.create(item.title); + const result = proto.CodeAction.create(item.title); if (item instanceof ProtocolCodeAction && item.data !== undefined) { result.data = item.data; } @@ -746,7 +746,7 @@ export function createConverter(uriConverter?: URIConverter): Converter { } function asCodeActionSync(item: code.CodeAction): proto.CodeAction { - let result = proto.CodeAction.create(item.title); + const result = proto.CodeAction.create(item.title); if (item instanceof ProtocolCodeAction && item.data !== undefined) { result.data = item.data; } @@ -834,13 +834,13 @@ export function createConverter(uriConverter?: URIConverter): Converter { } function asCommand(item: code.Command): proto.Command { - let result = proto.Command.create(item.title, item.command); + const result = proto.Command.create(item.title, item.command); if (item.arguments) { result.arguments = item.arguments; } return result; } function asCodeLens(item: code.CodeLens): proto.CodeLens { - let result = proto.CodeLens.create(asRange(item.range)); + const result = proto.CodeLens.create(asRange(item.range)); if (item.command) { result.command = asCommand(item.command); } if (item instanceof ProtocolCodeLens) { if (item.data) { result.data = item.data; } @@ -875,10 +875,10 @@ export function createConverter(uriConverter?: URIConverter): Converter { } function asDocumentLink(item: code.DocumentLink): proto.DocumentLink { - let result = proto.DocumentLink.create(asRange(item.range)); + const result = proto.DocumentLink.create(asRange(item.range)); if (item.target) { result.target = asUri(item.target); } if (item.tooltip !== undefined) { result.tooltip = item.tooltip; } - let protocolItem = item instanceof ProtocolDocumentLink ? item as ProtocolDocumentLink : undefined; + const protocolItem = item instanceof ProtocolDocumentLink ? item as ProtocolDocumentLink : undefined; if (protocolItem && protocolItem.data) { result.data = protocolItem.data; } diff --git a/client/src/common/colorProvider.ts b/client/src/common/colorProvider.ts index c1a829c1c..267145f00 100644 --- a/client/src/common/colorProvider.ts +++ b/client/src/common/colorProvider.ts @@ -36,7 +36,7 @@ export class ColorProviderFeature extends TextDocumentLanguageFeature { - let configuration: ConfigurationRequest.HandlerSignature = (params) => { - let result: any[] = []; - for (let item of params.items) { - let resource = item.scopeUri !== void 0 && item.scopeUri !== null ? this._client.protocol2CodeConverter.asUri(item.scopeUri) : undefined; + const configuration: ConfigurationRequest.HandlerSignature = (params) => { + const result: any[] = []; + for (const item of params.items) { + const resource = item.scopeUri !== void 0 && item.scopeUri !== null ? this._client.protocol2CodeConverter.asUri(item.scopeUri) : undefined; result.push(this.getConfiguration(resource, item.section !== null ? item.section : undefined)); } return result; }; - let middleware = client.middleware.workspace; + const middleware = client.middleware.workspace; return middleware && middleware.configuration ? middleware.configuration(params, token, configuration) : configuration(params, token); @@ -63,19 +63,19 @@ export class ConfigurationFeature implements StaticFeature { private getConfiguration(resource: Uri | undefined, section: string | undefined): any { let result: any = null; if (section) { - let index = section.lastIndexOf('.'); + const index = section.lastIndexOf('.'); if (index === -1) { result = toJSONObject(workspace.getConfiguration(undefined, resource).get(section)); } else { - let config = workspace.getConfiguration(section.substr(0, index), resource); + const config = workspace.getConfiguration(section.substr(0, index), resource); if (config) { result = toJSONObject(config.get(section.substr(index + 1))); } } } else { - let config = workspace.getConfiguration(undefined, resource); + const config = workspace.getConfiguration(undefined, resource); result = {}; - for (let key of Object.keys(config)) { + for (const key of Object.keys(config)) { if (config.has(key)) { result[key] = toJSONObject(config.get(key)); } @@ -171,7 +171,7 @@ export class SyncConfigurationFeature implements DynamicFeature): void { - let disposable = workspace.onDidChangeConfiguration((event) => { + const disposable = workspace.onDidChangeConfiguration((event) => { this.onDidChangeConfiguration(data.registerOptions.section, event); }); this._listeners.set(data.id, disposable); @@ -193,7 +193,7 @@ export class SyncConfigurationFeature implements DynamicFeature event.affectsConfiguration(section)); + const affected = sections.some((section) => event.affectsConfiguration(section)); if (!affected) { return; } @@ -231,7 +231,7 @@ export class SyncConfigurationFeature implements DynamicFeature { this._client.error(`Sending notification ${DidChangeConfigurationNotification.type.method} failed`, error); }); @@ -250,13 +250,13 @@ export class SyncConfigurationFeature implements DynamicFeature= 0) { config = workspace.getConfiguration(key.substr(0, index), resource).get(key.substr(index + 1)); @@ -264,7 +264,7 @@ export class SyncConfigurationFeature implements DynamicFeature { const client = this._client; - let resolveDocumentLink: ResolveDocumentLinkSignature = (link, token) => { + const resolveDocumentLink: ResolveDocumentLinkSignature = (link, token) => { return client.sendRequest(DocumentLinkResolveRequest.type, client.code2ProtocolConverter.asDocumentLink(link), token).then((result) => { if (token.isCancellationRequested) { return link; diff --git a/client/src/common/documentSymbol.ts b/client/src/common/documentSymbol.ts index fd5c9eae1..e39fc5494 100644 --- a/client/src/common/documentSymbol.ts +++ b/client/src/common/documentSymbol.ts @@ -68,7 +68,7 @@ export class DocumentSymbolFeature extends TextDocumentLanguageFeature { - let params: ExecuteCommandParams = { + const params: ExecuteCommandParams = { command, arguments: args }; @@ -86,7 +86,7 @@ export class ExecuteCommandFeature implements DynamicFeature disposable.dispose()); } diff --git a/client/src/common/features.ts b/client/src/common/features.ts index 6f7417b0e..e5cfa850c 100644 --- a/client/src/common/features.ts +++ b/client/src/common/features.ts @@ -507,14 +507,14 @@ export abstract class TextDocumentLanguageFeature 0) { return registration.provider; } @@ -614,7 +614,7 @@ export abstract class WorkspaceFeature implements DynamicFeature protected abstract registerLanguageProvider(options: RO): [Disposable, PR]; public unregister(id: string): void { - let registration = this._registrations.get(id); + const registration = this._registrations.get(id); if (registration !== undefined) { registration.disposable.dispose(); } diff --git a/client/src/common/fileSystemWatcher.ts b/client/src/common/fileSystemWatcher.ts index 0fa08d561..1e333c8bc 100644 --- a/client/src/common/fileSystemWatcher.ts +++ b/client/src/common/fileSystemWatcher.ts @@ -69,8 +69,8 @@ export class FileSystemWatcherFeature implements DynamicFeature { - for (let disposable of disposables) { + for (const disposable of disposables) { disposable.dispose(); } }); diff --git a/client/src/common/foldingRange.ts b/client/src/common/foldingRange.ts index ad8c9dec6..aae2cb8bb 100644 --- a/client/src/common/foldingRange.ts +++ b/client/src/common/foldingRange.ts @@ -34,7 +34,7 @@ export class FoldingRangeFeature extends TextDocumentLanguageFeature { const client = this._client; const provideOnTypeFormattingEdits: ProvideOnTypeFormattingEditsSignature = (document, position, ch, options, token) => { - let params: DocumentOnTypeFormattingParams = { + const params: DocumentOnTypeFormattingParams = { textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document), position: client.code2ProtocolConverter.asPosition(position), ch: ch, diff --git a/client/src/common/implementation.ts b/client/src/common/implementation.ts index aaf3226af..9d5c367ba 100644 --- a/client/src/common/implementation.ts +++ b/client/src/common/implementation.ts @@ -26,13 +26,13 @@ export class ImplementationFeature extends TextDocumentLanguageFeature { - let result = new code.SignatureInformation(item.label); + const result = new code.SignatureInformation(item.label); if (item.documentation !== undefined) { result.documentation = asDocumentation(item.documentation); } if (item.parameters !== undefined) { result.parameters = await asParameterInformations(item.parameters, token); } if (item.activeParameter !== undefined) { result.activeParameter = item.activeParameter ?? -1; } @@ -721,7 +721,7 @@ export function createConverter(uriConverter: URIConverter | undefined, trustMar } function asParameterInformation(item: ls.ParameterInformation): code.ParameterInformation { - let result = new code.ParameterInformation(item.label); + const result = new code.ParameterInformation(item.label); if (item.documentation) { result.documentation = asDocumentation(item.documentation); } return result; } @@ -760,7 +760,7 @@ export function createConverter(uriConverter: URIConverter | undefined, trustMar if (!item) { return undefined; } - let result = { + const result = { targetUri: _uriConverter(item.targetUri), targetRange: asRange(item.targetRange), // See issue: https://github.com/Microsoft/vscode/issues/58649 originSelectionRange: asRange(item.originSelectionRange), @@ -814,7 +814,7 @@ export function createConverter(uriConverter: URIConverter | undefined, trustMar } function asDocumentHighlight(item: ls.DocumentHighlight): code.DocumentHighlight { - let result = new code.DocumentHighlight(asRange(item.range)); + const result = new code.DocumentHighlight(asRange(item.range)); if (Is.number(item.kind)) { result.kind = asDocumentHighlightKind(item.kind); } return result; } @@ -899,7 +899,7 @@ export function createConverter(uriConverter: URIConverter | undefined, trustMar } function asDocumentSymbol(value: ls.DocumentSymbol): code.DocumentSymbol { - let result = new code.DocumentSymbol( + const result = new code.DocumentSymbol( value.name, value.detail || '', asSymbolKind(value.kind), @@ -908,8 +908,8 @@ export function createConverter(uriConverter: URIConverter | undefined, trustMar ); fillTags(result, value); if (value.children !== undefined && value.children.length > 0) { - let children: code.DocumentSymbol[] = []; - for (let child of value.children) { + const children: code.DocumentSymbol[] = []; + for (const child of value.children) { children.push(asDocumentSymbol(child)); } result.children = children; @@ -931,7 +931,7 @@ export function createConverter(uriConverter: URIConverter | undefined, trustMar } function asCommand(item: ls.Command): code.Command { - let result: code.Command = { title: item.title, command: item.command }; + const result: code.Command = { title: item.title, command: item.command }; if (item.arguments) { result.arguments = item.arguments; } return result; } @@ -967,9 +967,9 @@ export function createConverter(uriConverter: URIConverter | undefined, trustMar if (result) { return result; } - let parts = item.split('.'); + const parts = item.split('.'); result = code.CodeActionKind.Empty; - for (let part of parts) { + for (const part of parts) { result = result.append(part); } return result; @@ -992,7 +992,7 @@ export function createConverter(uriConverter: URIConverter | undefined, trustMar if (item === undefined || item === null) { return undefined; } - let result = new ProtocolCodeAction(item.title, item.data); + const result = new ProtocolCodeAction(item.title, item.data); if (item.kind !== undefined) { result.kind = asCodeActionKind(item.kind); } if (item.diagnostics !== undefined) { result.diagnostics = asDiagnosticsSync(item.diagnostics); } if (item.edit !== undefined) { result.edit = await asWorkspaceEdit(item.edit, token); } @@ -1019,7 +1019,7 @@ export function createConverter(uriConverter: URIConverter | undefined, trustMar if (!item) { return undefined; } - let result: ProtocolCodeLens = new ProtocolCodeLens(asRange(item.range)); + const result: ProtocolCodeLens = new ProtocolCodeLens(asRange(item.range)); if (item.command) { result.command = asCommand(item.command); } if (item.data !== undefined && item.data !== null) { result.data = item.data; } return result; @@ -1101,10 +1101,10 @@ export function createConverter(uriConverter: URIConverter | undefined, trustMar } function asDocumentLink(item: ls.DocumentLink): code.DocumentLink { - let range = asRange(item.range); - let target = item.target ? asUri(item.target) : undefined; + const range = asRange(item.range); + const target = item.target ? asUri(item.target) : undefined; // target must be optional in DocumentLink - let link = new ProtocolDocumentLink(range, target); + const link = new ProtocolDocumentLink(range, target); if (item.tooltip !== undefined) { link.tooltip = item.tooltip; } if (item.data !== undefined && item.data !== null) { link.data = item.data; } return link; @@ -1138,7 +1138,7 @@ export function createConverter(uriConverter: URIConverter | undefined, trustMar } function asColorPresentation(cp: ls.ColorPresentation): code.ColorPresentation { - let presentation = new code.ColorPresentation(cp.label); + const presentation = new code.ColorPresentation(cp.label); presentation.additionalTextEdits = asTextEditsSync(cp.additionalTextEdits); if (cp.textEdit) { presentation.textEdit = asTextEdit(cp.textEdit); @@ -1391,7 +1391,7 @@ export function createConverter(uriConverter: URIConverter | undefined, trustMar if (item === null) { return undefined; } - let result = new ProtocolTypeHierarchyItem( + const result = new ProtocolTypeHierarchyItem( asSymbolKind(item.kind), item.name, item.detail || '', diff --git a/client/src/common/rename.ts b/client/src/common/rename.ts index 6186feae1..1a1bca762 100644 --- a/client/src/common/rename.ts +++ b/client/src/common/rename.ts @@ -39,7 +39,7 @@ export class RenameFeature extends TextDocumentLanguageFeature { const client = this._client; const provideRenameEdits: ProvideRenameEditsSignature = (document, position, newName, token) => { - let params: RenameParams = { + const params: RenameParams = { textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document), position: client.code2ProtocolConverter.asPosition(position), newName: newName @@ -86,7 +86,7 @@ export class RenameFeature extends TextDocumentLanguageFeature { const client = this._client; const prepareRename: PrepareRenameSignature = (document, position, token) => { - let params: TextDocumentPositionParams = { + const params: TextDocumentPositionParams = { textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document), position: client.code2ProtocolConverter.asPosition(position), }; diff --git a/client/src/common/signatureHelp.ts b/client/src/common/signatureHelp.ts index dac16a0ea..cf4aa8321 100644 --- a/client/src/common/signatureHelp.ts +++ b/client/src/common/signatureHelp.ts @@ -33,7 +33,7 @@ export class SignatureHelpFeature extends TextDocumentLanguageFeature { if (Languages.match(selector, textDocument) > 0 && !this._selectorFilter!(selectors, textDocument) && !this._client.hasDedicatedTextSynchronizationFeature(textDocument)) { - let middleware = this._client.middleware; - let didClose = (textDocument: TextDocument): Promise => { + const middleware = this._client.middleware; + const didClose = (textDocument: TextDocument): Promise => { return this._client.sendNotification(this._type, this._createParams(textDocument)); }; this._syncedDocuments.delete(textDocument.uri.toString()); @@ -224,7 +224,7 @@ export class DidChangeTextDocumentFeature extends DynamicDocumentFeature => { + const middleware = this._client.middleware; + const willSaveWaitUntil = (event: TextDocumentWillSaveEvent): Thenable => { return this._client.sendRequest(WillSaveTextDocumentWaitUntilRequest.type, this._client.code2ProtocolConverter.asWillSaveTextDocumentParams(event)).then(async (edits) => { - let vEdits = await this._client.protocol2CodeConverter.asTextEdits(edits); + const vEdits = await this._client.protocol2CodeConverter.asTextEdits(edits); return vEdits === undefined ? [] : vEdits; }); }; diff --git a/client/src/common/typeDefinition.ts b/client/src/common/typeDefinition.ts index 05b9aab03..339c594ce 100644 --- a/client/src/common/typeDefinition.ts +++ b/client/src/common/typeDefinition.ts @@ -29,13 +29,13 @@ export class TypeDefinitionFeature extends TextDocumentLanguageFeature { }).then(() => { this.completionPromise = undefined; this.onSuccess = undefined; - var result = this.task!(); + const result = this.task!(); this.task = undefined; return result; }); @@ -57,7 +57,7 @@ export class Delayer { return undefined; } this.cancelTimeout(); - let result: T = this.task!(); + const result: T = this.task!(); this.completionPromise = undefined; this.onSuccess = undefined; this.task = undefined; diff --git a/client/src/common/workspaceFolder.ts b/client/src/common/workspaceFolder.ts index da7cbbe44..c97c2ff02 100644 --- a/client/src/common/workspaceFolder.ts +++ b/client/src/common/workspaceFolder.ts @@ -123,7 +123,7 @@ export class WorkspaceFoldersFeature implements DynamicFeature { } private doSendEvent(addedFolders: ReadonlyArray, removedFolders: ReadonlyArray): Promise { - let params: DidChangeWorkspaceFoldersParams = { + const params: DidChangeWorkspaceFoldersParams = { event: { added: addedFolders.map(folder => this.asProtocol(folder)), removed: removedFolders.map(folder => this.asProtocol(folder)) @@ -133,13 +133,13 @@ export class WorkspaceFoldersFeature implements DynamicFeature { } public register(data: RegistrationData): void { - let id = data.id; - let client = this._client; - let disposable = workspace.onDidChangeWorkspaceFolders((event) => { - let didChangeWorkspaceFolders = (event: VWorkspaceFoldersChangeEvent): Promise => { + const id = data.id; + const client = this._client; + const disposable = workspace.onDidChangeWorkspaceFolders((event) => { + const didChangeWorkspaceFolders = (event: VWorkspaceFoldersChangeEvent): Promise => { return this.doSendEvent(event.added, event.removed); }; - let middleware = client.middleware.workspace; + const middleware = client.middleware.workspace; const promise = middleware && middleware.didChangeWorkspaceFolders ? middleware.didChangeWorkspaceFolders(event, didChangeWorkspaceFolders) : didChangeWorkspaceFolders(event); @@ -152,7 +152,7 @@ export class WorkspaceFoldersFeature implements DynamicFeature { } public unregister(id: string): void { - let disposable = this._listeners.get(id); + const disposable = this._listeners.get(id); if (disposable === void 0) { return; } @@ -161,7 +161,7 @@ export class WorkspaceFoldersFeature implements DynamicFeature { } public clear(): void { - for (let disposable of this._listeners.values()) { + for (const disposable of this._listeners.values()) { disposable.dispose(); } this._listeners.clear(); diff --git a/client/src/common/workspaceSymbol.ts b/client/src/common/workspaceSymbol.ts index 452e9ae29..10988d2cd 100644 --- a/client/src/common/workspaceSymbol.ts +++ b/client/src/common/workspaceSymbol.ts @@ -38,7 +38,7 @@ export class WorkspaceSymbolFeature extends WorkspaceFeature { return debugStartWith.some(value => arg.startsWith(value)) || @@ -305,7 +305,7 @@ export class LanguageClient extends BaseLanguageClient { }); } let json: NodeModule | Executable; - let runDebug = <{ run: any; debug: any }>server; + const runDebug = <{ run: any; debug: any }>server; if (runDebug.run || runDebug.debug) { if (this._forceDebug || startedInDebugMode()) { json = runDebug.debug; @@ -319,8 +319,8 @@ export class LanguageClient extends BaseLanguageClient { } return this._getServerWorkingDir(json.options).then(serverWorkingDir => { if (NodeModule.is(json) && json.module) { - let node = json; - let transport = node.transport || TransportKind.stdio; + const node = json; + const transport = node.transport || TransportKind.stdio; if (node.runtime) { const args: string[] = []; const options: ForkOptions = node.options ?? Object.create(null); @@ -537,11 +537,11 @@ export class LanguageClient extends BaseLanguageClient { } private _mainGetRootPath(): string | undefined { - let folders = Workspace.workspaceFolders; + const folders = Workspace.workspaceFolders; if (!folders || folders.length === 0) { return undefined; } - let folder = folders[0]; + const folder = folders[0]; if (folder.uri.scheme === 'file') { return folder.uri.fsPath; } @@ -587,10 +587,10 @@ export class SettingMonitor { } private onDidChangeConfiguration(): void { - let index = this._setting.indexOf('.'); - let primary = index >= 0 ? this._setting.substr(0, index) : this._setting; - let rest = index >= 0 ? this._setting.substr(index + 1) : undefined; - let enabled = rest ? Workspace.getConfiguration(primary).get(rest, false) : Workspace.getConfiguration(primary); + const index = this._setting.indexOf('.'); + const primary = index >= 0 ? this._setting.substr(0, index) : this._setting; + const rest = index >= 0 ? this._setting.substr(index + 1) : undefined; + const enabled = rest ? Workspace.getConfiguration(primary).get(rest, false) : Workspace.getConfiguration(primary); if (enabled && this._client.needsStart()) { this._client.start().catch((error) => this._client.error('Start failed after configuration change', error, 'force')); } else if (!enabled && this._client.needsStop()) { diff --git a/client/src/node/processes.ts b/client/src/node/processes.ts index 95a935679..4e29bc8b6 100644 --- a/client/src/node/processes.ts +++ b/client/src/node/processes.ts @@ -17,7 +17,7 @@ export function terminate(process: ChildProcess & { pid: number }, cwd?: string) // This we run in Atom execFileSync is available. // Ignore stderr since this is otherwise piped to parent.stderr // which might be already closed. - let options: any = { + const options: any = { stdio: ['pipe', 'pipe', 'ignore'] }; if (cwd) { @@ -30,8 +30,8 @@ export function terminate(process: ChildProcess & { pid: number }, cwd?: string) } } else if (isLinux || isMacintosh) { try { - var cmd = join(__dirname, 'terminateProcess.sh'); - var result = (cp).spawnSync(cmd, [process.pid.toString()]); + const cmd = join(__dirname, 'terminateProcess.sh'); + const result = (cp).spawnSync(cmd, [process.pid.toString()]); return result.error ? false : true; } catch (err) { return false; diff --git a/jsonrpc/src/browser/test/test.ts b/jsonrpc/src/browser/test/test.ts index bf357f347..8235de898 100644 --- a/jsonrpc/src/browser/test/test.ts +++ b/jsonrpc/src/browser/test/test.ts @@ -93,7 +93,6 @@ suite('Browser IPC Reader / Writer', () => { }); test('Cancellation via SharedArrayBuffer', async () => { - debugger; const worker = new Worker('/jsonrpc/dist/cancelWorker.js'); const reader = new BrowserMessageReader(worker); const writer = new BrowserMessageWriter(worker); diff --git a/jsonrpc/src/common/connection.ts b/jsonrpc/src/common/connection.ts index 421e1ddb2..8dc90ac1c 100644 --- a/jsonrpc/src/common/connection.ts +++ b/jsonrpc/src/common/connection.ts @@ -1277,7 +1277,7 @@ export function createMessageConnection(messageReader: MessageReader, messageWri paramStart = 1; parameterStructures = first; } - let paramEnd: number = args.length; + const paramEnd: number = args.length; const numberOfParams = paramEnd - paramStart; switch (numberOfParams) { case 0: @@ -1423,6 +1423,7 @@ export function createMessageConnection(messageReader: MessageReader, messageWri cancellationStrategy.sender.enableCancellation(requestMessage); } + // eslint-disable-next-line no-async-promise-executor return new Promise>(async (resolve, reject) => { const resolveWithCleanup = (r: any) => { resolve(r); diff --git a/jsonrpc/src/common/messageBuffer.ts b/jsonrpc/src/common/messageBuffer.ts index 4a2cd899a..822c42c2b 100644 --- a/jsonrpc/src/common/messageBuffer.ts +++ b/jsonrpc/src/common/messageBuffer.ts @@ -48,7 +48,7 @@ export abstract class AbstractMessageBuffer implements RAL.MessageBuffer { row: while (chunkIndex < this._chunks.length) { const chunk = this._chunks[chunkIndex]; offset = 0; - column: while (offset < chunk.length) { + while (offset < chunk.length) { const value = chunk[offset]; switch (value) { case CR: @@ -150,7 +150,7 @@ export abstract class AbstractMessageBuffer implements RAL.MessageBuffer { const result = this.allocNative(byteCount); let resultOffset = 0; - let chunkIndex = 0; + const chunkIndex = 0; while (byteCount > 0) { const chunk = this._chunks[chunkIndex]; if (chunk.byteLength > byteCount) { diff --git a/jsonrpc/src/common/messageReader.ts b/jsonrpc/src/common/messageReader.ts index 55bf6dc31..47e8e7c4b 100644 --- a/jsonrpc/src/common/messageReader.ts +++ b/jsonrpc/src/common/messageReader.ts @@ -50,7 +50,7 @@ export interface MessageReader { export namespace MessageReader { export function is(value: any): value is MessageReader { - let candidate: MessageReader = value; + const candidate: MessageReader = value; return candidate && Is.func(candidate.listen) && Is.func(candidate.dispose) && Is.func(candidate.onError) && Is.func(candidate.onClose) && Is.func(candidate.onPartialMessage); } diff --git a/jsonrpc/src/common/messageWriter.ts b/jsonrpc/src/common/messageWriter.ts index 5145dcb51..817527c5b 100644 --- a/jsonrpc/src/common/messageWriter.ts +++ b/jsonrpc/src/common/messageWriter.ts @@ -46,7 +46,7 @@ export interface MessageWriter { export namespace MessageWriter { export function is(value: any): value is MessageWriter { - let candidate: MessageWriter = value; + const candidate: MessageWriter = value; return candidate && Is.func(candidate.dispose) && Is.func(candidate.onClose) && Is.func(candidate.onError) && Is.func(candidate.write); } diff --git a/jsonrpc/src/common/test/linkedMap.test.ts b/jsonrpc/src/common/test/linkedMap.test.ts index 45ba70e4d..179ce87c4 100644 --- a/jsonrpc/src/common/test/linkedMap.test.ts +++ b/jsonrpc/src/common/test/linkedMap.test.ts @@ -9,7 +9,7 @@ import { LinkedMap, Touch, LRUCache } from '../linkedMap'; suite('Linked Map', () => { test('Simple', () => { - let map = new LinkedMap(); + const map = new LinkedMap(); map.set('ak', 'av'); map.set('bk', 'bv'); assert.deepStrictEqual([...map.keys()], ['ak', 'bk']); @@ -17,7 +17,7 @@ suite('Linked Map', () => { }); test('Touch First one', () => { - let map = new LinkedMap(); + const map = new LinkedMap(); map.set('ak', 'av'); map.set('ak', 'av', Touch.First); assert.deepStrictEqual([...map.keys()], ['ak']); @@ -25,7 +25,7 @@ suite('Linked Map', () => { }); test('Touch Last one', () => { - let map = new LinkedMap(); + const map = new LinkedMap(); map.set('ak', 'av'); map.set('ak', 'av', Touch.Last); assert.deepStrictEqual([...map.keys()], ['ak']); @@ -33,7 +33,7 @@ suite('Linked Map', () => { }); test('Touch First two', () => { - let map = new LinkedMap(); + const map = new LinkedMap(); map.set('ak', 'av'); map.set('bk', 'bv'); map.set('bk', 'bv', Touch.First); @@ -42,7 +42,7 @@ suite('Linked Map', () => { }); test('Touch Last two', () => { - let map = new LinkedMap(); + const map = new LinkedMap(); map.set('ak', 'av'); map.set('bk', 'bv'); map.set('ak', 'av', Touch.Last); @@ -51,7 +51,7 @@ suite('Linked Map', () => { }); test('Touch Frist from middle', () => { - let map = new LinkedMap(); + const map = new LinkedMap(); map.set('ak', 'av'); map.set('bk', 'bv'); map.set('ck', 'cv'); @@ -61,7 +61,7 @@ suite('Linked Map', () => { }); test('Touch Last from middle', () => { - let map = new LinkedMap(); + const map = new LinkedMap(); map.set('ak', 'av'); map.set('bk', 'bv'); map.set('ck', 'cv'); @@ -136,7 +136,7 @@ suite('Linked Map', () => { cache.set(7, 7); assert.strictEqual(cache.size, 5); assert.deepStrictEqual([...cache.keys()], [3, 4, 5, 6, 7]); - let values: number[] = []; + const values: number[] = []; [3, 4, 5, 6, 7].forEach(key => values.push(cache.get(key)!)); assert.deepStrictEqual(values, [3, 4, 5, 6, 7]); }); @@ -151,7 +151,7 @@ suite('Linked Map', () => { assert.deepStrictEqual([...cache.keys()], [1, 2, 4, 5, 3]); cache.peek(4); assert.deepStrictEqual([...cache.keys()], [1, 2, 4, 5, 3]); - let values: number[] = []; + const values: number[] = []; [1, 2, 3, 4, 5].forEach(key => values.push(cache.get(key)!)); assert.deepStrictEqual(values, [1, 2, 3, 4, 5]); }); @@ -172,7 +172,7 @@ suite('Linked Map', () => { cache.set(i, i); } assert.deepEqual(cache.size, 15); - let values: number[] = []; + const values: number[] = []; for (let i = 6; i <= 20; i++) { values.push(cache.get(i)!); assert.strictEqual(cache.get(i), i); @@ -190,7 +190,7 @@ suite('Linked Map', () => { cache.set(11, 11); assert.strictEqual(cache.size, 5); assert.deepStrictEqual([...cache.keys()], [7, 8, 9, 10, 11]); - let values: number[] = []; + const values: number[] = []; [...cache.keys()].forEach(key => values.push(cache.get(key)!)); assert.deepStrictEqual(values, [7, 8, 9, 10, 11]); assert.deepStrictEqual([...cache.values()], values); diff --git a/jsonrpc/src/node/main.ts b/jsonrpc/src/node/main.ts index 55e8b1527..1edc22984 100644 --- a/jsonrpc/src/node/main.ts +++ b/jsonrpc/src/node/main.ts @@ -30,7 +30,7 @@ export class IPCMessageReader extends AbstractMessageReader { public constructor(process: NodeJS.Process | ChildProcess) { super(); this.process = process; - let eventEmitter: NodeJS.EventEmitter = this.process; + const eventEmitter: NodeJS.EventEmitter = this.process; eventEmitter.on('error', (error: any) => this.fireError(error)); eventEmitter.on('close', () => this.fireClose()); } @@ -203,7 +203,7 @@ export function createClientPipeTransport(pipeName: string, encoding: RAL.Messag connectResolve = resolve; }); return new Promise((resolve, reject) => { - let server: Server = createServer((socket: Socket) => { + const server: Server = createServer((socket: Socket) => { server.close(); connectResolve([ new SocketMessageReader(socket, encoding), diff --git a/jsonrpc/src/node/test/connection.test.ts b/jsonrpc/src/node/test/connection.test.ts index 6080c0d36..33e05f08a 100644 --- a/jsonrpc/src/node/test/connection.test.ts +++ b/jsonrpc/src/node/test/connection.test.ts @@ -655,13 +655,13 @@ suite('Connection', () => { }); test('Uses custom message handler', (done) => { - let type = new RequestType('test/handleSingleRequest'); - let duplexStream1 = new TestDuplex('ds1'); - let duplexStream2 = new TestDuplex('ds2'); + const type = new RequestType('test/handleSingleRequest'); + const duplexStream1 = new TestDuplex('ds1'); + const duplexStream2 = new TestDuplex('ds2'); const asyncLocalStorage = new AsyncLocalStorage(); - let server = hostConnection.createMessageConnection(duplexStream2, duplexStream1, hostConnection.NullLogger, { + const server = hostConnection.createMessageConnection(duplexStream2, duplexStream1, hostConnection.NullLogger, { messageStrategy: { handleMessage(message, next) { asyncLocalStorage.run(1, () => next(message)); @@ -673,7 +673,7 @@ suite('Connection', () => { }); server.listen(); - let client = hostConnection.createMessageConnection(duplexStream1, duplexStream2, hostConnection.NullLogger); + const client = hostConnection.createMessageConnection(duplexStream1, duplexStream2, hostConnection.NullLogger); client.listen(); void client.sendRequest(type, 0).then((res) => { assert.strictEqual(res, 1); diff --git a/protocol/src/common/protocol.ts b/protocol/src/common/protocol.ts index 27b38b8b5..01b0031e5 100644 --- a/protocol/src/common/protocol.ts +++ b/protocol/src/common/protocol.ts @@ -342,7 +342,7 @@ export namespace DocumentSelector { if (!Array.isArray(value)) { return false; } - for (let elem of value) { + for (const elem of value) { if (!Is.string(elem) && !TextDocumentFilter.is(elem) && !NotebookCellTextDocumentFilter.is(elem)) { return false; } @@ -1915,7 +1915,7 @@ export namespace TextDocumentContentChangeEvent { * Checks whether the information describes a delta event. */ export function isIncremental(event: TextDocumentContentChangeEvent): event is { range: Range; rangeLength?: uinteger; text: string } { - let candidate: { range: Range; rangeLength?: uinteger; text: string } = event as any; + const candidate: { range: Range; rangeLength?: uinteger; text: string } = event as any; return candidate !== undefined && candidate !== null && typeof candidate.text === 'string' && candidate.range !== undefined && (candidate.rangeLength === undefined || typeof candidate.rangeLength === 'number'); @@ -1925,7 +1925,7 @@ export namespace TextDocumentContentChangeEvent { * Checks whether the information describes a full replacement event. */ export function isFull(event: TextDocumentContentChangeEvent): event is { text: string } { - let candidate: { range?: Range; rangeLength?: uinteger; text: string } = event as any; + const candidate: { range?: Range; rangeLength?: uinteger; text: string } = event as any; return candidate !== undefined && candidate !== null && typeof candidate.text === 'string' && candidate.range === undefined && candidate.rangeLength === undefined; } @@ -2769,7 +2769,7 @@ export interface ClientSignatureInformationOptions { * @since 3.16.0 */ activeParameterSupport?: boolean; - + /** * The client supports the `activeParameter` property on * `SignatureHelp`/`SignatureInformation` being set to `null` to @@ -2778,7 +2778,7 @@ export interface ClientSignatureInformationOptions { * @since 3.18.0 * @proposed */ - noActiveParameterSupport?: boolean; + noActiveParameterSupport?: boolean; } /** diff --git a/protocol/src/node/test/connection.test.ts b/protocol/src/node/test/connection.test.ts index fa87632a1..02a8f3705 100644 --- a/protocol/src/node/test/connection.test.ts +++ b/protocol/src/node/test/connection.test.ts @@ -50,7 +50,7 @@ suite('Connection Tests', () => { let paramsCorrect: boolean = false; serverConnection.onRequest(InitializeRequest.type, (params) => { paramsCorrect = !Array.isArray(params); - let result: InitializeResult = { + const result: InitializeResult = { capabilities: { } }; @@ -72,7 +72,7 @@ suite('Partial result tests', () => { let serverConnection: ProtocolConnection; let clientConnection: ProtocolConnection; - let progressType: ProgressType = new ProgressType(); + const progressType: ProgressType = new ProgressType(); setup(() => { const up = new TestStream(); @@ -98,7 +98,7 @@ suite('Partial result tests', () => { }); test('Result reported', async () => { - let result: SymbolInformation = { + const result: SymbolInformation = { name: 'abc', kind: SymbolKind.Class, location: { diff --git a/server/src/common/configuration.ts b/server/src/common/configuration.ts index 818012f56..10268dfa7 100644 --- a/server/src/common/configuration.ts +++ b/server/src/common/configuration.ts @@ -32,7 +32,7 @@ export const ConfigurationFeature: Feature<_RemoteWorkspace, Configuration> = (B } private _getConfiguration(arg: ConfigurationItem | ConfigurationItem[]): Promise { - let params: ConfigurationParams = { + const params: ConfigurationParams = { items: Array.isArray(arg) ? arg : [arg] }; return this.connection.sendRequest(ConfigurationRequest.type, params).then((result) => { diff --git a/server/src/common/progress.ts b/server/src/common/progress.ts index 94f8f4649..8f1ab5a7d 100644 --- a/server/src/common/progress.ts +++ b/server/src/common/progress.ts @@ -44,7 +44,7 @@ class WorkDoneProgressReporterImpl implements WorkDoneProgressReporter { } public begin(title: string, percentage?: number, message?: string, cancellable?: boolean): void { - let param: WorkDoneProgressBegin = { + const param: WorkDoneProgressBegin = { kind: 'begin', title, percentage, @@ -55,7 +55,7 @@ class WorkDoneProgressReporterImpl implements WorkDoneProgressReporter { } report(arg0: number | string, arg1?: string): void { - let param: WorkDoneProgressReport = { + const param: WorkDoneProgressReport = { kind: 'report' }; if (typeof arg0 === 'number') { @@ -158,7 +158,7 @@ export const ProgressFeature: Feature<_RemoteWindow, WindowProgress> = (Base) => if (capabilities?.window?.workDoneProgress === true) { this._progressSupported = true; this.connection.onNotification(WorkDoneProgressCancelNotification.type, (params) => { - let progress = WorkDoneProgressReporterImpl.Instances.get(params.token); + const progress = WorkDoneProgressReporterImpl.Instances.get(params.token); if (progress instanceof WorkDoneProgressServerReporterImpl || progress instanceof NullProgressServerReporter) { progress.cancel(); } diff --git a/server/src/common/server.ts b/server/src/common/server.ts index 03a3a755b..4300023e7 100644 --- a/server/src/common/server.ts +++ b/server/src/common/server.ts @@ -303,17 +303,17 @@ class _RemoteWindowImpl implements _RemoteWindow, Remote { } public showErrorMessage(message: string, ...actions: MessageActionItem[]): Promise { - let params: ShowMessageRequestParams = { type: MessageType.Error, message, actions }; + const params: ShowMessageRequestParams = { type: MessageType.Error, message, actions }; return this.connection.sendRequest(ShowMessageRequest.type, params).then(null2Undefined); } public showWarningMessage(message: string, ...actions: MessageActionItem[]): Promise { - let params: ShowMessageRequestParams = { type: MessageType.Warning, message, actions }; + const params: ShowMessageRequestParams = { type: MessageType.Warning, message, actions }; return this.connection.sendRequest(ShowMessageRequest.type, params).then(null2Undefined); } public showInformationMessage(message: string, ...actions: MessageActionItem[]): Promise { - let params: ShowMessageRequestParams = { type: MessageType.Info, message, actions }; + const params: ShowMessageRequestParams = { type: MessageType.Info, message, actions }; return this.connection.sendRequest(ShowMessageRequest.type, params).then(null2Undefined); } } @@ -428,11 +428,11 @@ class BulkUnregistrationImpl implements BulkUnregistration { } public dispose(): any { - let unregistrations: Unregistration[] = []; - for (let unregistration of this._unregistrations.values()) { + const unregistrations: Unregistration[] = []; + for (const unregistration of this._unregistrations.values()) { unregistrations.push(unregistration); } - let params: UnregistrationParams = { + const params: UnregistrationParams = { unregisterations: unregistrations }; this._connection!.sendRequest(UnregistrationRequest.type, params).catch(() => { @@ -448,7 +448,7 @@ class BulkUnregistrationImpl implements BulkUnregistration { return false; } - let params: UnregistrationParams = { + const params: UnregistrationParams = { unregisterations: [unregistration] }; this._connection!.sendRequest(UnregistrationRequest.type, params).then(() => { @@ -574,7 +574,7 @@ class RemoteClientImpl implements RemoteClient, Remote { private registerSingle1(unregistration: BulkUnregistrationImpl, type: string | MethodType, registerOptions: any): Promise { const method = Is.string(type) ? type : type.method; const id = UUID.generateUuid(); - let params: RegistrationParams = { + const params: RegistrationParams = { registrations: [{ id, method, registerOptions: registerOptions || {} }] }; if (!unregistration.isAttached) { @@ -592,7 +592,7 @@ class RemoteClientImpl implements RemoteClient, Remote { private registerSingle2(type: string | MethodType, registerOptions: any): Promise { const method = Is.string(type) ? type : type.method; const id = UUID.generateUuid(); - let params: RegistrationParams = { + const params: RegistrationParams = { registrations: [{ id, method, registerOptions: registerOptions || {} }] }; return this.connection.sendRequest(RegistrationRequest.type, params).then((_result) => { @@ -606,7 +606,7 @@ class RemoteClientImpl implements RemoteClient, Remote { } private unregisterSingle(id: string, method: string): Promise { - let params: UnregistrationParams = { + const params: UnregistrationParams = { unregisterations: [{ id, method }] }; @@ -616,7 +616,7 @@ class RemoteClientImpl implements RemoteClient, Remote { } private registerMany(registrations: BulkRegistrationImpl): Promise { - let params = registrations.asRegistrationParams(); + const params = registrations.asRegistrationParams(); return this.connection.sendRequest(RegistrationRequest.type, params).then(() => { return new BulkUnregistrationImpl(this._connection, params.registrations.map(registration => { return { id: registration.id, method: registration.method }; })); }, (_error) => { @@ -674,7 +674,7 @@ class _RemoteWorkspaceImpl implements _RemoteWorkspace, Remote { return value && !!(value as ApplyWorkspaceEditParams).edit; } - let params: ApplyWorkspaceEditParams = isApplyWorkspaceEditParams(paramOrEdit) ? paramOrEdit : { edit: paramOrEdit }; + const params: ApplyWorkspaceEditParams = isApplyWorkspaceEditParams(paramOrEdit) ? paramOrEdit : { edit: paramOrEdit }; return this.connection.sendRequest(ApplyWorkspaceEditRequest.type, params); } } @@ -1439,7 +1439,7 @@ export function combineFeatures = { + const result: Features = { __brand: 'features', console: combine(one.console, two.console, combineConsoleFeatures), tracer: combine(one.tracer, two.tracer, combineTracerFeatures), @@ -1494,7 +1494,7 @@ export function createConnection | undefined = undefined; let initializeHandler: ServerRequestHandler | undefined = undefined; let exitHandler: NotificationHandler0 | undefined = undefined; - let protocolConnection: _Connection & ConnectionState = { + const protocolConnection: _Connection & ConnectionState = { listen: (): void => connection.listen(), sendRequest: (type: string | MessageSignature, ...params: any[]): Promise => connection.sendRequest(Is.string(type) ? type : type.method, ...params), @@ -1643,7 +1643,7 @@ export function createConnection connection.dispose() }; - for (let remote of allRemotes) { + for (const remote of allRemotes) { remote.attach(protocolConnection); } @@ -1652,11 +1652,11 @@ export function createConnection { if (value instanceof ResponseError) { return value; @@ -1675,14 +1675,14 @@ export function createConnection { } })); disposables.push(connection.onDidCloseTextDocument((event: DidCloseTextDocumentParams) => { - let syncedDocument = this._syncedDocuments.get(event.textDocument.uri); + const syncedDocument = this._syncedDocuments.get(event.textDocument.uri); if (syncedDocument !== undefined) { this._syncedDocuments.delete(event.textDocument.uri); this._onDidClose.fire(Object.freeze({ document: syncedDocument })); } })); disposables.push(connection.onWillSaveTextDocument((event: WillSaveTextDocumentParams) => { - let syncedDocument = this._syncedDocuments.get(event.textDocument.uri); + const syncedDocument = this._syncedDocuments.get(event.textDocument.uri); if (syncedDocument !== undefined) { this._onWillSave.fire(Object.freeze({ document: syncedDocument, reason: event.reason })); } })); disposables.push(connection.onWillSaveTextDocumentWaitUntil((event: WillSaveTextDocumentParams, token: CancellationToken) => { - let syncedDocument = this._syncedDocuments.get(event.textDocument.uri); + const syncedDocument = this._syncedDocuments.get(event.textDocument.uri); if (syncedDocument !== undefined && this._willSaveWaitUntil) { return this._willSaveWaitUntil(Object.freeze({ document: syncedDocument, reason: event.reason }), token); } else { @@ -237,7 +237,7 @@ export class TextDocuments { } })); disposables.push(connection.onDidSaveTextDocument((event: DidSaveTextDocumentParams) => { - let syncedDocument = this._syncedDocuments.get(event.textDocument.uri); + const syncedDocument = this._syncedDocuments.get(event.textDocument.uri); if (syncedDocument !== undefined) { this._onDidSave.fire(Object.freeze({ document: syncedDocument })); } diff --git a/server/src/common/workspaceFolder.ts b/server/src/common/workspaceFolder.ts index 8293de876..0170bc04c 100644 --- a/server/src/common/workspaceFolder.ts +++ b/server/src/common/workspaceFolder.ts @@ -28,7 +28,7 @@ export const WorkspaceFoldersFeature: Feature<_RemoteWorkspace, WorkspaceFolders } public initialize(capabilities: ClientCapabilities): void { super.initialize(capabilities); - let workspaceCapabilities = capabilities.workspace; + const workspaceCapabilities = capabilities.workspace; if (workspaceCapabilities && workspaceCapabilities.workspaceFolders) { this._onDidChangeWorkspaceFolders = new Emitter(); this.connection.onNotification(DidChangeWorkspaceFoldersNotification.type, (params) => { diff --git a/server/src/node/files.ts b/server/src/node/files.ts index 66135afcc..7e69c9fb8 100644 --- a/server/src/node/files.ts +++ b/server/src/node/files.ts @@ -13,17 +13,17 @@ import { spawnSync, fork, ChildProcess, SpawnSyncOptionsWithStringEncoding } fro * complete implementation of handling VS Code URIs. */ export function uriToFilePath(uri: string): string | undefined { - let parsed = url.parse(uri); + const parsed = url.parse(uri); if (parsed.protocol !== 'file:' || !parsed.path) { return undefined; } - let segments = parsed.path.split('/'); - for (var i = 0, len = segments.length; i < len; i++) { + const segments = parsed.path.split('/'); + for (let i = 0, len = segments.length; i < len; i++) { segments[i] = decodeURIComponent(segments[i]); } if (process.platform === 'win32' && segments.length > 1) { - let first = segments[0]; - let second = segments[1]; + const first = segments[0]; + const second = segments[1]; // Do we have a drive letter and we started with a / which is the // case if the first segement is empty (see split above) if (first.length === 0 && second.length > 1 && second[1] === ':') { @@ -67,8 +67,8 @@ export function resolve(moduleName: string, nodePath: string | undefined, cwd: s ].join(''); return new Promise((resolve, reject) => { - let env = process.env; - let newEnv = Object.create(null); + const env = process.env; + const newEnv = Object.create(null); Object.keys(env).forEach(key => newEnv[key] = env[key]); if (nodePath && fs.existsSync(nodePath) /* see issue 545 */) { @@ -83,7 +83,7 @@ export function resolve(moduleName: string, nodePath: string | undefined, cwd: s } newEnv['ELECTRON_RUN_AS_NODE'] = '1'; try { - let cp: ChildProcess = fork('', [], { + const cp: ChildProcess = fork('', [], { cwd: cwd, env: newEnv, execArgv: ['-e', app] @@ -105,7 +105,7 @@ export function resolve(moduleName: string, nodePath: string | undefined, cwd: s } } }); - let message: Message = { + const message: Message = { c: 'rs', a: moduleName }; @@ -137,10 +137,10 @@ export function resolveGlobalNodePath(tracer?: (message: string) => void): strin options.shell = true; } - let handler = () => {}; + const handler = () => {}; try { process.on('SIGPIPE', handler); - let stdout = spawnSync(npmCommand, ['config', 'get', 'prefix'], options).stdout; + const stdout = spawnSync(npmCommand, ['config', 'get', 'prefix'], options).stdout; if (!stdout) { if (tracer) { @@ -148,7 +148,7 @@ export function resolveGlobalNodePath(tracer?: (message: string) => void): strin } return undefined; } - let prefix = stdout.trim(); + const prefix = stdout.trim(); if (tracer) { tracer(`'npm config get prefix' value is: ${prefix}`); } @@ -181,7 +181,7 @@ interface YarnJsonFormat { */ export function resolveGlobalYarnPath(tracer?: (message: string) => void): string | undefined { let yarnCommand = 'yarn'; - let options: SpawnSyncOptionsWithStringEncoding = { + const options: SpawnSyncOptionsWithStringEncoding = { encoding: 'utf8' }; @@ -190,12 +190,12 @@ export function resolveGlobalYarnPath(tracer?: (message: string) => void): strin options.shell = true; } - let handler = () => {}; + const handler = () => {}; try { process.on('SIGPIPE', handler); - let results = spawnSync(yarnCommand, ['global', 'dir', '--json'], options); + const results = spawnSync(yarnCommand, ['global', 'dir', '--json'], options); - let stdout = results.stdout; + const stdout = results.stdout; if (!stdout) { if (tracer) { tracer(`'yarn global dir' didn't return a value.`); @@ -205,10 +205,10 @@ export function resolveGlobalYarnPath(tracer?: (message: string) => void): strin } return undefined; } - let lines = stdout.trim().split(/\r?\n/); - for (let line of lines) { + const lines = stdout.trim().split(/\r?\n/); + for (const line of lines) { try { - let yarn: YarnJsonFormat = JSON.parse(line); + const yarn: YarnJsonFormat = JSON.parse(line); if (yarn.type === 'log') { return path.join(yarn.data, 'node_modules'); } diff --git a/server/src/node/main.ts b/server/src/node/main.ts index 10462f5c2..c98b405c7 100644 --- a/server/src/node/main.ts +++ b/server/src/node/main.ts @@ -19,11 +19,11 @@ export * from 'vscode-languageserver-protocol/node'; export * from '../common/api'; export namespace Files { - export let uriToFilePath = fm.uriToFilePath; - export let resolveGlobalNodePath = fm.resolveGlobalNodePath; - export let resolveGlobalYarnPath = fm.resolveGlobalYarnPath; - export let resolve = fm.resolve; - export let resolveModulePath = fm.resolveModulePath; + export const uriToFilePath = fm.uriToFilePath; + export const resolveGlobalNodePath = fm.resolveGlobalNodePath; + export const resolveGlobalYarnPath = fm.resolveGlobalYarnPath; + export const resolve = fm.resolve; + export const resolveModulePath = fm.resolveModulePath; } let _protocolConnection: ProtocolConnection | undefined; @@ -45,7 +45,7 @@ function setupExitTimer(): void { const argName = '--clientProcessId'; function runTimer(value: string): void { try { - let processId = parseInt(value); + const processId = parseInt(value); if (!isNaN(processId)) { exitTimer = setInterval(() => { try { @@ -63,12 +63,12 @@ function setupExitTimer(): void { } for (let i = 2; i < process.argv.length; i++) { - let arg = process.argv[i]; + const arg = process.argv[i]; if (arg === argName && i + 1 < process.argv.length) { runTimer(process.argv[i + 1]); return; } else { - let args = arg.split('='); + const args = arg.split('='); if (args[0] === argName) { runTimer(args[1]); } @@ -196,9 +196,9 @@ function _createConnection 2) { let port: number | undefined = void 0; let pipeName: string | undefined = void 0; - let argv = process.argv.slice(2); + const argv = process.argv.slice(2); for (let i = 0; i < argv.length; i++) { - let arg = argv[i]; + const arg = argv[i]; if (arg === '--node-ipc') { input = new IPCMessageReader(process); output = new IPCMessageWriter(process); @@ -216,7 +216,7 @@ function _createConnectioninput; + const inputStream = input; inputStream.on('end', () => { endProtocolConnection(); process.exit(_shutdownReceived ? 0 : 1); diff --git a/server/src/node/resolve.ts b/server/src/node/resolve.ts index 2fd40567f..e500b2004 100644 --- a/server/src/node/resolve.ts +++ b/server/src/node/resolve.ts @@ -15,7 +15,7 @@ process.on('message', (message: Message) => { process.exit(0); } else if (message.command === 'resolve') { try { - let result = (require).resolve(message.args); + const result = (require).resolve(message.args); process.send!({ command: 'resolve', success: true, result: result }); } catch (err) { process.send!({ command: 'resolve', success: false }); diff --git a/server/src/node/test/connection.test.ts b/server/src/node/test/connection.test.ts index f14ee1fda..d99f2f5a8 100644 --- a/server/src/node/test/connection.test.ts +++ b/server/src/node/test/connection.test.ts @@ -40,7 +40,7 @@ suite('Connection Tests', () => { let paramsCorrect: boolean = false; serverConnection.onRequest(InitializeRequest.type, (params) => { paramsCorrect = !Array.isArray(params) && params.workDoneToken === 'token'; - let result: InitializeResult = { + const result: InitializeResult = { capabilities: { } }; diff --git a/testbed/client/src/extension.ts b/testbed/client/src/extension.ts index 2c9305432..780147b2d 100644 --- a/testbed/client/src/extension.ts +++ b/testbed/client/src/extension.ts @@ -13,14 +13,14 @@ let client: LanguageClient; export async function activate(context: ExtensionContext) { // We need to go one level up since an extension compile the js code into // the output folder. - let module = path.join(__dirname, '..', '..', 'server', 'out', 'server.js'); - let debugOptions = { execArgv: ['--nolazy', '--inspect=6012'] }; - let serverOptions: ServerOptions = { + const module = path.join(__dirname, '..', '..', 'server', 'out', 'server.js'); + const debugOptions = { execArgv: ['--nolazy', '--inspect=6012'] }; + const serverOptions: ServerOptions = { run: { module, transport: TransportKind.ipc }, debug: { module, /* runtime: 'node.exe', */ transport: TransportKind.ipc, options: debugOptions} }; - let clientOptions: LanguageClientOptions = { + const clientOptions: LanguageClientOptions = { documentSelector: [ { language: 'bat' }, { language: 'bat', notebook: '*' }, @@ -93,7 +93,7 @@ FOR %%f IN (*.jpg *.png *.bmp) DO XCOPY C:\\source\\"%%f" c:\\images /m /y REM This moves any files with a .jpg, .png, REM or .bmp extension from c:\\source to c:\\images;;`; - workspace + void workspace .openTextDocument({ content: testContent, language: 'bat', diff --git a/testbed/client/src/measure.ts b/testbed/client/src/measure.ts index cf6c9af91..e6c04a5b1 100644 --- a/testbed/client/src/measure.ts +++ b/testbed/client/src/measure.ts @@ -15,7 +15,7 @@ export function activate(context: vscode.ExtensionContext) { // The command has been defined in the package.json file // Now provide the implementation of the command with registerCommand // The commandId parameter must match the command field in package.json - let disposable = vscode.commands.registerCommand('testbed.helloWorld', () => { + const disposable = vscode.commands.registerCommand('testbed.helloWorld', () => { const counter = 1000000; diff --git a/testbed/server/src/fullNotebookServer.ts b/testbed/server/src/fullNotebookServer.ts index 8d0e9c496..9cdc6a27b 100644 --- a/testbed/server/src/fullNotebookServer.ts +++ b/testbed/server/src/fullNotebookServer.ts @@ -79,7 +79,7 @@ connection.onDeclaration((params, token) => { connection.onCompletion((params, token): CompletionItem[] => { const result: CompletionItem[] = []; - let item = CompletionItem.create('foo'); + const item = CompletionItem.create('foo'); result.push(item); return result; }); diff --git a/testbed/server/src/server.ts b/testbed/server/src/server.ts index 0d1378ac0..1b90bf635 100644 --- a/testbed/server/src/server.ts +++ b/testbed/server/src/server.ts @@ -109,7 +109,7 @@ connection.onInitialize((params, cancel, progress): Thenable | const workspaceFolders = params.workspaceFolders; if (workspaceFolders !== undefined && workspaceFolders !== null) { - for (let folder of workspaceFolders) { + for (const folder of workspaceFolders) { connection.console.log(`${folder.name} ${folder.uri}`); } if (workspaceFolders.length > 0) { @@ -119,7 +119,7 @@ connection.onInitialize((params, cancel, progress): Thenable | semanticTokensLegend = computeLegend(params.capabilities.textDocument!.semanticTokens!); return new Promise((resolve, reject) => { - let result: InitializeResult = { + const result: InitializeResult = { capabilities: { textDocumentSync: TextDocumentSyncKind.Full, hoverProvider: true, @@ -192,7 +192,7 @@ connection.onInitialized((params) => { connection.console.log('Workspace folder changed received'); }); void connection.workspace.getWorkspaceFolders().then(folders => { - for (let folder of folders) { + for (const folder of folders) { connection.console.log(`Get workspace folders: ${folder.name} ${folder.uri}`); } }); @@ -476,7 +476,7 @@ connection.onReferences((params): Location[] => { }); connection.onDocumentHighlight((textPosition) => { - let position = textPosition.position; + const position = textPosition.position; return [ DocumentHighlight.create({ start: { line: position.line + 1, character: position.character }, @@ -594,13 +594,13 @@ connection.onRequest('addTwenty', (param) => { return { value: param.value + 20 }; }); -let not: ProtocolNotificationType = new ProtocolNotificationType('testbed/notification'); +const not: ProtocolNotificationType = new ProtocolNotificationType('testbed/notification'); connection.onNotification(not, (arr) => { connection.console.log('Is array: ' + Array.isArray(arr)); }); connection.onRequest(SelectionRangeRequest.type, (params) => { - let result: SelectionRange = { + const result: SelectionRange = { range: { start: { line: params.positions[0].line, @@ -637,7 +637,7 @@ connection.languages.callHierarchy.onOutgoingCalls((params) => { return []; }); -let tokenBuilders: Map = new Map(); +const tokenBuilders: Map = new Map(); documents.onDidClose((event) => { tokenBuilders.delete(event.document.uri); }); diff --git a/testbed/server/src/simpleNotebookServer.ts b/testbed/server/src/simpleNotebookServer.ts index c49d6ec40..9f560483b 100644 --- a/testbed/server/src/simpleNotebookServer.ts +++ b/testbed/server/src/simpleNotebookServer.ts @@ -53,7 +53,7 @@ connection.onInitialize((params, cancel, progress): Thenable | }); documents.onDidChangeContent((event) => { - let document = event.document; + const document = event.document; void connection.sendDiagnostics({ uri: document.uri, diagnostics: computeDiagnostics(document.getText()) }); }); @@ -76,7 +76,7 @@ connection.onDeclaration((params, token) => { connection.onCompletion((params, token): CompletionItem[] => { const result: CompletionItem[] = []; - let item = CompletionItem.create('foo'); + const item = CompletionItem.create('foo'); result.push(item); return result; }); diff --git a/textDocument/src/main.ts b/textDocument/src/main.ts index 08a637fee..b6a840839 100644 --- a/textDocument/src/main.ts +++ b/textDocument/src/main.ts @@ -229,7 +229,7 @@ class FullTextDocument implements TextDocument { } public update(changes: TextDocumentContentChangeEvent[], version: number): void { - for (let change of changes) { + for (const change of changes) { if (FullTextDocument.isIncremental(change)) { // makes sure start is before end const range = getWellformedRange(change.range); @@ -281,13 +281,13 @@ class FullTextDocument implements TextDocument { public positionAt(offset: number): Position { offset = Math.max(Math.min(offset, this._content.length), 0); - let lineOffsets = this.getLineOffsets(); + const lineOffsets = this.getLineOffsets(); let low = 0, high = lineOffsets.length; if (high === 0) { return { line: 0, character: offset }; } while (low < high) { - let mid = Math.floor((low + high) / 2); + const mid = Math.floor((low + high) / 2); if (lineOffsets[mid] > offset) { high = mid; } else { @@ -296,19 +296,19 @@ class FullTextDocument implements TextDocument { } // low is the least x for which the line offset is larger than the current offset // or array.length if no line offset is larger than the current offset - let line = low - 1; + const line = low - 1; return { line, character: offset - lineOffsets[line] }; } public offsetAt(position: Position) { - let lineOffsets = this.getLineOffsets(); + const lineOffsets = this.getLineOffsets(); if (position.line >= lineOffsets.length) { return this._content.length; } else if (position.line < 0) { return 0; } - let lineOffset = lineOffsets[position.line]; - let nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length; + const lineOffset = lineOffsets[position.line]; + const nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length; return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset); } @@ -317,14 +317,14 @@ class FullTextDocument implements TextDocument { } private static isIncremental(event: TextDocumentContentChangeEvent): event is { range: Range; rangeLength?: number; text: string } { - let candidate: { range: Range; rangeLength?: number; text: string } = event as any; + const candidate: { range: Range; rangeLength?: number; text: string } = event as any; return candidate !== undefined && candidate !== null && typeof candidate.text === 'string' && candidate.range !== undefined && (candidate.rangeLength === undefined || typeof candidate.rangeLength === 'number'); } private static isFull(event: TextDocumentContentChangeEvent): event is { text: string } { - let candidate: { range?: Range; rangeLength?: number; text: string } = event as any; + const candidate: { range?: Range; rangeLength?: number; text: string } = event as any; return candidate !== undefined && candidate !== null && typeof candidate.text === 'string' && candidate.range === undefined && candidate.rangeLength === undefined; } @@ -362,9 +362,9 @@ export namespace TextDocument { } export function applyEdits(document: TextDocument, edits: TextEdit[]): string { - let text = document.getText(); - let sortedEdits = mergeSort(edits.map(getWellformedEdit), (a, b) => { - let diff = a.range.start.line - b.range.start.line; + const text = document.getText(); + const sortedEdits = mergeSort(edits.map(getWellformedEdit), (a, b) => { + const diff = a.range.start.line - b.range.start.line; if (diff === 0) { return a.range.start.character - b.range.start.character; } @@ -373,7 +373,7 @@ export namespace TextDocument { let lastModifiedOffset = 0; const spans = []; for (const e of sortedEdits) { - let startOffset = document.offsetAt(e.range.start); + const startOffset = document.offsetAt(e.range.start); if (startOffset < lastModifiedOffset) { throw new Error('Overlapping edit'); } else if (startOffset > lastModifiedOffset) { @@ -405,7 +405,7 @@ function mergeSort(data: T[], compare: (a: T, b: T) => number): T[] { let rightIdx = 0; let i = 0; while (leftIdx < left.length && rightIdx < right.length) { - let ret = compare(left[leftIdx], right[rightIdx]); + const ret = compare(left[leftIdx], right[rightIdx]); if (ret <= 0) { // smaller_equal -> take left to preserve order data[i++] = left[leftIdx++]; @@ -437,7 +437,7 @@ const enum CharCode { function computeLineOffsets(text: string, isAtLineStart: boolean, textOffset = 0): number[] { const result: number[] = isAtLineStart ? [textOffset] : []; for (let i = 0; i < text.length; i++) { - let ch = text.charCodeAt(i); + const ch = text.charCodeAt(i); if (ch === CharCode.CarriageReturn || ch === CharCode.LineFeed) { if (ch === CharCode.CarriageReturn && i + 1 < text.length && text.charCodeAt(i + 1) === CharCode.LineFeed) { i++; diff --git a/textDocument/src/test/edits.test.ts b/textDocument/src/test/edits.test.ts index ba760d4a9..c6c07a5b0 100644 --- a/textDocument/src/test/edits.test.ts +++ b/textDocument/src/test/edits.test.ts @@ -13,7 +13,7 @@ const applyEdits = TextDocument.applyEdits; suite('Edits', () => { test('inserts', function (): any { - let input = TextDocument.create('foo://bar/f', 'html', 0, '012345678901234567890123456789'); + const input = TextDocument.create('foo://bar/f', 'html', 0, '012345678901234567890123456789'); assert.equal(applyEdits(input, [TextEdit.insert(Position.create(0, 0), 'Hello')]), 'Hello012345678901234567890123456789'); assert.equal(applyEdits(input, [TextEdit.insert(Position.create(0, 1), 'Hello')]), '0Hello12345678901234567890123456789'); assert.equal(applyEdits(input, [TextEdit.insert(Position.create(0, 1), 'Hello'), TextEdit.insert(Position.create(0, 1), 'World')]), '0HelloWorld12345678901234567890123456789'); @@ -21,7 +21,7 @@ suite('Edits', () => { }); test('replace', function (): any { - let input = TextDocument.create('foo://bar/f', 'html', 0, '012345678901234567890123456789'); + const input = TextDocument.create('foo://bar/f', 'html', 0, '012345678901234567890123456789'); assert.equal(applyEdits(input, [TextEdit.replace(Range.create(0, 3, 0, 6), 'Hello')]), '012Hello678901234567890123456789'); assert.equal(applyEdits(input, [TextEdit.replace(Range.create(0, 3, 0, 6), 'Hello'), TextEdit.replace(Range.create(0, 6, 0, 9), 'World')]), '012HelloWorld901234567890123456789'); assert.equal(applyEdits(input, [TextEdit.replace(Range.create(0, 3, 0, 6), 'Hello'), TextEdit.insert(Position.create(0, 6), 'World')]), '012HelloWorld678901234567890123456789'); @@ -31,13 +31,13 @@ suite('Edits', () => { }); test('overlap', function (): any { - let input = TextDocument.create('foo://bar/f', 'html', 0, '012345678901234567890123456789'); + const input = TextDocument.create('foo://bar/f', 'html', 0, '012345678901234567890123456789'); assert.throws(() => applyEdits(input, [TextEdit.replace(Range.create(0, 3, 0, 6), 'Hello'), TextEdit.insert(Position.create(0, 3), 'World')])); assert.throws(() => applyEdits(input, [TextEdit.replace(Range.create(0, 3, 0, 6), 'Hello'), TextEdit.insert(Position.create(0, 4), 'World')])); }); test('multiline', function (): any { - let input = TextDocument.create('foo://bar/f', 'html', 0, '0\n1\n2\n3\n4'); + const input = TextDocument.create('foo://bar/f', 'html', 0, '0\n1\n2\n3\n4'); assert.equal(applyEdits(input, [TextEdit.replace(Range.create(2, 0, 3, 0), 'Hello'), TextEdit.insert(Position.create(1, 1), 'World')]), '0\n1World\nHello3\n4'); }); }); \ No newline at end of file diff --git a/textDocument/src/test/textdocument.test.ts b/textDocument/src/test/textdocument.test.ts index 85f6b1228..d30685723 100644 --- a/textDocument/src/test/textdocument.test.ts +++ b/textDocument/src/test/textdocument.test.ts @@ -304,7 +304,7 @@ suite('Text Document Incremental Updates', () => { }); test('Basic append', () => { - let document = newDocument('foooo\nbar\nbaz'); + const document = newDocument('foooo\nbar\nbaz'); assert.equal(document.offsetAt(Positions.create(2, 0)), 10); @@ -316,7 +316,7 @@ suite('Text Document Incremental Updates', () => { }); test('Multi-line append', () => { - let document = newDocument('foooo\nbar\nbaz'); + const document = newDocument('foooo\nbar\nbaz'); assert.equal(document.offsetAt(Positions.create(2, 0)), 10); @@ -329,7 +329,7 @@ suite('Text Document Incremental Updates', () => { }); test('Basic delete', () => { - let document = newDocument('foooo\nbar\nbaz'); + const document = newDocument('foooo\nbar\nbaz'); assert.equal(document.offsetAt(Positions.create(2, 0)), 10); @@ -341,7 +341,7 @@ suite('Text Document Incremental Updates', () => { }); test('Multi-line delete', () => { - let lm = newDocument('foooo\nbar\nbaz'); + const lm = newDocument('foooo\nbar\nbaz'); assert.equal(lm.offsetAt(Positions.create(2, 0)), 10); @@ -353,7 +353,7 @@ suite('Text Document Incremental Updates', () => { }); test('Single character replace', () => { - let document = newDocument('foooo\nbar\nbaz'); + const document = newDocument('foooo\nbar\nbaz'); assert.equal(document.offsetAt(Positions.create(2, 0)), 10); @@ -365,7 +365,7 @@ suite('Text Document Incremental Updates', () => { }); test('Multi-character replace', () => { - let lm = newDocument('foo\nbar'); + const lm = newDocument('foo\nbar'); assert.equal(lm.offsetAt(Positions.create(1, 0)), 4); diff --git a/tools/src/generator-main.ts b/tools/src/generator-main.ts index f0e80aa30..5b4edfdee 100644 --- a/tools/src/generator-main.ts +++ b/tools/src/generator-main.ts @@ -11,17 +11,17 @@ import * as tss from './typescripts'; import Visitor from './visitor'; function loadConfigFile(file: string): ts.ParsedCommandLine { - let absolute = path.resolve(file); + const absolute = path.resolve(file); - let readResult = ts.readConfigFile(absolute, ts.sys.readFile); + const readResult = ts.readConfigFile(absolute, ts.sys.readFile); if (readResult.error) { throw new Error(ts.formatDiagnostics([readResult.error], ts.createCompilerHost({}))); } - let config = readResult.config; + const config = readResult.config; if (config.compilerOptions !== undefined) { config.compilerOptions = Object.assign(config.compilerOptions, tss.CompileOptions.getDefaultOptions(file)); } - let result = ts.parseJsonConfigFileContent(config, ts.sys, path.dirname(absolute)); + const result = ts.parseJsonConfigFileContent(config, ts.sys, path.dirname(absolute)); if (result.errors.length > 0) { throw new Error(ts.formatDiagnostics(result.errors, ts.createCompilerHost({}))); } @@ -31,7 +31,7 @@ function loadConfigFile(file: string): ts.ParsedCommandLine { async function main(): Promise { let config: ts.ParsedCommandLine = ts.parseCommandLine(ts.sys.args); - let configFilePath: string | undefined = tss.CompileOptions.getConfigFilePath(config.options); + const configFilePath: string | undefined = tss.CompileOptions.getConfigFilePath(config.options); if (configFilePath && config.options.project) { config = loadConfigFile(configFilePath); } @@ -92,7 +92,7 @@ async function main(): Promise { }); const languageService = ts.createLanguageService(host); - let program = languageService.getProgram(); + const program = languageService.getProgram(); if (program === undefined) { console.error('Couldn\'t create language service with underlying program.'); process.exitCode = -1; diff --git a/tools/src/typescripts.ts b/tools/src/typescripts.ts index 15c2dcbf2..ecf7c1c05 100644 --- a/tools/src/typescripts.ts +++ b/tools/src/typescripts.ts @@ -153,7 +153,7 @@ export class Symbols { if (result !== undefined) { return result; } - let declarations = symbol.getDeclarations(); + const declarations = symbol.getDeclarations(); if (declarations === undefined) { if (this.typeChecker.isUnknownSymbol(symbol)) { return Symbols.Unknown; @@ -163,8 +163,8 @@ export class Symbols { return Symbols.None; } } - let fragments: { f: string; s: number; e: number; k: number }[] = []; - for (let declaration of declarations) { + const fragments: { f: string; s: number; e: number; k: number }[] = []; + for (const declaration of declarations) { fragments.push({ f: declaration.getSourceFile().fileName, s: declaration.getStart(), @@ -235,8 +235,8 @@ export class Symbols { } const baseTypes = tsType.getBaseTypes(); if (baseTypes !== undefined) { - for (let base of baseTypes) { - let symbol = base.getSymbol(); + for (const base of baseTypes) { + const symbol = base.getSymbol(); if (symbol) { result.push(symbol); } diff --git a/tools/src/visitor.ts b/tools/src/visitor.ts index f3cbd6c2b..d2628ceb6 100644 --- a/tools/src/visitor.ts +++ b/tools/src/visitor.ts @@ -76,6 +76,7 @@ namespace TypeInfo { const baseSet = new Set(['null', 'void', 'string', 'boolean', 'URI', 'DocumentUri', 'integer', 'uinteger', 'decimal']); export function asJsonType(info: TypeInfo): JsonType { + const literal: StructureLiteral = { properties: [] }; switch (info.kind) { case 'base': if (baseSet.has(info.name)) { @@ -98,7 +99,6 @@ namespace TypeInfo { case 'tuple': return { kind: 'tuple', items: info.items.map(info => asJsonType(info)) }; case 'literal': - const literal: StructureLiteral = { properties: [] }; for (const entry of info.items) { const property: Property = { name: entry[0], type: asJsonType(entry[1].type) }; const value = entry[1]; diff --git a/types/src/main.ts b/types/src/main.ts index 32fee0e7b..63c7b7fb6 100644 --- a/types/src/main.ts +++ b/types/src/main.ts @@ -160,7 +160,7 @@ export namespace Position { * Checks whether the given literal conforms to the {@link Position} interface. */ export function is(value: any): value is Position { - let candidate = value as Position; + const candidate = value as Position; return Is.objectLiteral(candidate) && Is.uinteger(candidate.line) && Is.uinteger(candidate.character); } } @@ -222,7 +222,7 @@ export namespace Range { * Checks whether the given literal conforms to the {@link Range} interface. */ export function is(value: any): value is Range { - let candidate = value as Range; + const candidate = value as Range; return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end); } } @@ -253,7 +253,7 @@ export namespace Location { * Checks whether the given literal conforms to the {@link Location} interface. */ export function is(value: any): value is Location { - let candidate = value as Location; + const candidate = value as Location; return Is.objectLiteral(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri)); } } @@ -311,7 +311,7 @@ export namespace LocationLink { * Checks whether the given literal conforms to the {@link LocationLink} interface. */ export function is(value: any): value is LocationLink { - let candidate = value as LocationLink; + const candidate = value as LocationLink; return Is.objectLiteral(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri) && Range.is(candidate.targetSelectionRange) && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange)); @@ -609,7 +609,7 @@ export namespace DiagnosticRelatedInformation { * Checks whether the given literal conforms to the {@link DiagnosticRelatedInformation} interface. */ export function is(value: any): value is DiagnosticRelatedInformation { - let candidate: DiagnosticRelatedInformation = value as DiagnosticRelatedInformation; + const candidate: DiagnosticRelatedInformation = value as DiagnosticRelatedInformation; return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message); } } @@ -759,7 +759,7 @@ export namespace Diagnostic { * Creates a new Diagnostic literal. */ export function create(range: Range, message: string, severity?: DiagnosticSeverity, code?: integer | string, source?: string, relatedInformation?: DiagnosticRelatedInformation[]): Diagnostic { - let result: Diagnostic = { range, message }; + const result: Diagnostic = { range, message }; if (Is.defined(severity)) { result.severity = severity; } @@ -779,7 +779,7 @@ export namespace Diagnostic { * Checks whether the given literal conforms to the {@link Diagnostic} interface. */ export function is(value: any): value is Diagnostic { - let candidate = value as Diagnostic; + const candidate = value as Diagnostic; return Is.defined(candidate) && Range.is(candidate.range) && Is.string(candidate.message) @@ -824,7 +824,7 @@ export namespace Command { * Creates a new Command literal. */ export function create(title: string, command: string, ...args: any[]): Command { - let result: Command = { title, command }; + const result: Command = { title, command }; if (Is.defined(args) && args.length > 0) { result.arguments = args; } @@ -834,7 +834,7 @@ export namespace Command { * Checks whether the given literal conforms to the {@link Command} interface. */ export function is(value: any): value is Command { - let candidate = value as Command; + const candidate = value as Command; return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command); } } @@ -1034,7 +1034,7 @@ export namespace TextDocumentEdit { } export function is(value: any): value is TextDocumentEdit { - let candidate = value as TextDocumentEdit; + const candidate = value as TextDocumentEdit; return Is.defined(candidate) && OptionalVersionedTextDocumentIdentifier.is(candidate.textDocument) && Array.isArray(candidate.edits); @@ -1095,7 +1095,7 @@ export interface CreateFile extends ResourceOperation { export namespace CreateFile { export function create(uri: DocumentUri, options?: CreateFileOptions, annotation?: ChangeAnnotationIdentifier): CreateFile { - let result: CreateFile = { + const result: CreateFile = { kind: 'create', uri }; @@ -1109,7 +1109,7 @@ export namespace CreateFile { } export function is(value: any): value is CreateFile { - let candidate: CreateFile = value; + const candidate: CreateFile = value; return candidate && candidate.kind === 'create' && Is.string(candidate.uri) && ( candidate.options === undefined || ((candidate.options.overwrite === undefined || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === undefined || Is.boolean(candidate.options.ignoreIfExists))) @@ -1161,7 +1161,7 @@ export interface RenameFile extends ResourceOperation { export namespace RenameFile { export function create(oldUri: DocumentUri, newUri: DocumentUri, options?: RenameFileOptions, annotation?: ChangeAnnotationIdentifier): RenameFile { - let result: RenameFile = { + const result: RenameFile = { kind: 'rename', oldUri, newUri @@ -1176,7 +1176,7 @@ export namespace RenameFile { } export function is(value: any): value is RenameFile { - let candidate: RenameFile = value; + const candidate: RenameFile = value; return candidate && candidate.kind === 'rename' && Is.string(candidate.oldUri) && Is.string(candidate.newUri) && ( candidate.options === undefined || ((candidate.options.overwrite === undefined || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === undefined || Is.boolean(candidate.options.ignoreIfExists))) @@ -1223,7 +1223,7 @@ export interface DeleteFile extends ResourceOperation { export namespace DeleteFile { export function create(uri: DocumentUri, options?: DeleteFileOptions, annotation?: ChangeAnnotationIdentifier): DeleteFile { - let result: DeleteFile = { + const result: DeleteFile = { kind: 'delete', uri }; @@ -1237,7 +1237,7 @@ export namespace DeleteFile { } export function is(value: any): value is DeleteFile { - let candidate: DeleteFile = value; + const candidate: DeleteFile = value; return candidate && candidate.kind === 'delete' && Is.string(candidate.uri) && ( candidate.options === undefined || ((candidate.options.recursive === undefined || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === undefined || Is.boolean(candidate.options.ignoreIfNotExists))) @@ -1297,7 +1297,7 @@ export interface WorkspaceEdit { export namespace WorkspaceEdit { export function is(value: any): value is WorkspaceEdit { - let candidate: WorkspaceEdit = value; + const candidate: WorkspaceEdit = value; return candidate && (candidate.changes !== undefined || candidate.documentChanges !== undefined) && (candidate.documentChanges === undefined || candidate.documentChanges.every((change) => { @@ -1592,7 +1592,7 @@ export class WorkspaceChange { } let result: TextEditChange = this._textEditChanges[key]; if (!result) { - let edits: (TextEdit | AnnotatedTextEdit)[] = []; + const edits: (TextEdit | AnnotatedTextEdit)[] = []; this._workspaceEdit.changes[key] = edits; result = new TextEditChangeImpl(edits); this._textEditChanges[key] = result; @@ -1726,7 +1726,7 @@ export namespace TextDocumentIdentifier { * Checks whether the given literal conforms to the {@link TextDocumentIdentifier} interface. */ export function is(value: any): value is TextDocumentIdentifier { - let candidate = value as TextDocumentIdentifier; + const candidate = value as TextDocumentIdentifier; return Is.defined(candidate) && Is.string(candidate.uri); } } @@ -1759,7 +1759,7 @@ export namespace VersionedTextDocumentIdentifier { * Checks whether the given literal conforms to the {@link VersionedTextDocumentIdentifier} interface. */ export function is(value: any): value is VersionedTextDocumentIdentifier { - let candidate = value as VersionedTextDocumentIdentifier; + const candidate = value as VersionedTextDocumentIdentifier; return Is.defined(candidate) && Is.string(candidate.uri) && Is.integer(candidate.version); } } @@ -1796,7 +1796,7 @@ export namespace OptionalVersionedTextDocumentIdentifier { * Checks whether the given literal conforms to the {@link OptionalVersionedTextDocumentIdentifier} interface. */ export function is(value: any): value is OptionalVersionedTextDocumentIdentifier { - let candidate = value as OptionalVersionedTextDocumentIdentifier; + const candidate = value as OptionalVersionedTextDocumentIdentifier; return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.integer(candidate.version)); } } @@ -1848,7 +1848,7 @@ export namespace TextDocumentItem { * Checks whether the given literal conforms to the {@link TextDocumentItem} interface. */ export function is(value: any): value is TextDocumentItem { - let candidate = value as TextDocumentItem; + const candidate = value as TextDocumentItem; return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.integer(candidate.version) && Is.string(candidate.text); } } @@ -2480,7 +2480,7 @@ export namespace Hover { * Checks whether the given value conforms to the {@link Hover} interface. */ export function is(value: any): value is Hover { - let candidate = value as Hover; + const candidate = value as Hover; return !!candidate && Is.objectLiteral(candidate) && ( MarkupContent.is(candidate.contents) || MarkedString.is(candidate.contents) || @@ -2577,7 +2577,7 @@ export interface SignatureInformation { */ export namespace SignatureInformation { export function create(label: string, documentation?: string, ...parameters: ParameterInformation[]): SignatureInformation { - let result: SignatureInformation = { label }; + const result: SignatureInformation = { label }; if (Is.defined(documentation)) { result.documentation = documentation; } @@ -2730,7 +2730,7 @@ export namespace DocumentHighlight { * @param kind The highlight kind */ export function create(range: Range, kind?: DocumentHighlightKind): DocumentHighlight { - let result: DocumentHighlight = { range }; + const result: DocumentHighlight = { range }; if (Is.number(kind)) { result.kind = kind; } @@ -2855,7 +2855,7 @@ export namespace SymbolInformation { * @param containerName The name of the symbol containing the symbol. */ export function create(name: string, kind: SymbolKind, range: Range, uri: DocumentUri, containerName?: string): SymbolInformation { - let result: SymbolInformation = { + const result: SymbolInformation = { name, kind, location: { uri, range } @@ -2986,7 +2986,7 @@ export namespace DocumentSymbol { * @param children Children of the symbol. */ export function create(name: string, detail: string | undefined, kind: SymbolKind, range: Range, selectionRange: Range, children?: DocumentSymbol[]): DocumentSymbol { - let result: DocumentSymbol = { + const result: DocumentSymbol = { name, detail, kind, @@ -3002,7 +3002,7 @@ export namespace DocumentSymbol { * Checks whether the given literal conforms to the {@link DocumentSymbol} interface. */ export function is(value: any): value is DocumentSymbol { - let candidate: DocumentSymbol = value; + const candidate: DocumentSymbol = value; return candidate && Is.string(candidate.name) && Is.number(candidate.kind) && Range.is(candidate.range) && Range.is(candidate.selectionRange) && @@ -3182,7 +3182,7 @@ export namespace CodeActionContext { * Creates a new CodeActionContext literal. */ export function create(diagnostics: Diagnostic[], only?: CodeActionKind[], triggerKind?: CodeActionTriggerKind): CodeActionContext { - let result: CodeActionContext = { diagnostics }; + const result: CodeActionContext = { diagnostics }; if (only !== undefined && only !== null) { result.only = only; } @@ -3195,7 +3195,7 @@ export namespace CodeActionContext { * Checks whether the given literal conforms to the {@link CodeActionContext} interface. */ export function is(value: any): value is CodeActionContext { - let candidate = value as CodeActionContext; + const candidate = value as CodeActionContext; return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === undefined || Is.typedArray(candidate.only, Is.string)) && (candidate.triggerKind === undefined || candidate.triggerKind === CodeActionTriggerKind.Invoked || candidate.triggerKind === CodeActionTriggerKind.Automatic); @@ -3323,7 +3323,7 @@ export namespace CodeAction { export function create(title: string, edit: WorkspaceEdit, kind?: CodeActionKind): CodeAction; export function create(title: string, kindOrCommandOrEdit?: CodeActionKind | Command | WorkspaceEdit, kind?: CodeActionKind): CodeAction { - let result: CodeAction = { title }; + const result: CodeAction = { title }; let checkKind: boolean = true; if (typeof kindOrCommandOrEdit === 'string') { checkKind = false; @@ -3339,7 +3339,7 @@ export namespace CodeAction { return result; } export function is(value: any): value is CodeAction { - let candidate: CodeAction = value; + const candidate: CodeAction = value; return candidate && Is.string(candidate.title) && (candidate.diagnostics === undefined || Is.typedArray(candidate.diagnostics, Diagnostic.is)) && (candidate.kind === undefined || Is.string(candidate.kind)) && @@ -3384,7 +3384,7 @@ export namespace CodeLens { * Creates a new CodeLens literal. */ export function create(range: Range, data?: LSPAny): CodeLens { - let result: CodeLens = { range }; + const result: CodeLens = { range }; if (Is.defined(data)) { result.data = data; } return result; } @@ -3392,7 +3392,7 @@ export namespace CodeLens { * Checks whether the given literal conforms to the {@link CodeLens} interface. */ export function is(value: any): value is CodeLens { - let candidate = value as CodeLens; + const candidate = value as CodeLens; return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command)); } } @@ -3453,7 +3453,7 @@ export namespace FormattingOptions { * Checks whether the given literal conforms to the {@link FormattingOptions} interface. */ export function is(value: any): value is FormattingOptions { - let candidate = value as FormattingOptions; + const candidate = value as FormattingOptions; return Is.defined(candidate) && Is.uinteger(candidate.tabSize) && Is.boolean(candidate.insertSpaces); } } @@ -3508,7 +3508,7 @@ export namespace DocumentLink { * Checks whether the given literal conforms to the {@link DocumentLink} interface. */ export function is(value: any): value is DocumentLink { - let candidate = value as DocumentLink; + const candidate = value as DocumentLink; return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target)); } } @@ -3546,7 +3546,7 @@ export namespace SelectionRange { } export function is(value: any): value is SelectionRange { - let candidate = value as SelectionRange; + const candidate = value as SelectionRange; return Is.objectLiteral(candidate) && Range.is(candidate.range) && (candidate.parent === undefined || SelectionRange.is(candidate.parent)); } } @@ -4435,15 +4435,15 @@ export namespace TextDocument { * Checks whether the given literal conforms to the {@link ITextDocument} interface. */ export function is(value: any): value is TextDocument { - let candidate = value as TextDocument; + const candidate = value as TextDocument; return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.uinteger(candidate.lineCount) && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false; } export function applyEdits(document: TextDocument, edits: TextEdit[]): string { let text = document.getText(); - let sortedEdits = mergeSort(edits, (a, b) => { - let diff = a.range.start.line - b.range.start.line; + const sortedEdits = mergeSort(edits, (a, b) => { + const diff = a.range.start.line - b.range.start.line; if (diff === 0) { return a.range.start.character - b.range.start.character; } @@ -4451,9 +4451,9 @@ export namespace TextDocument { }); let lastModifiedOffset = text.length; for (let i = sortedEdits.length - 1; i >= 0; i--) { - let e = sortedEdits[i]; - let startOffset = document.offsetAt(e.range.start); - let endOffset = document.offsetAt(e.range.end); + const e = sortedEdits[i]; + const startOffset = document.offsetAt(e.range.start); + const endOffset = document.offsetAt(e.range.end); if (endOffset <= lastModifiedOffset) { text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length); } else { @@ -4480,7 +4480,7 @@ export namespace TextDocument { let rightIdx = 0; let i = 0; while (leftIdx < left.length && rightIdx < right.length) { - let ret = compare(left[leftIdx], right[rightIdx]); + const ret = compare(left[leftIdx], right[rightIdx]); if (ret <= 0) { // smaller_equal -> take left to preserve order data[i++] = left[leftIdx++]; @@ -4562,8 +4562,8 @@ class FullTextDocument implements TextDocument { public getText(range?: Range): string { if (range) { - let start = this.offsetAt(range.start); - let end = this.offsetAt(range.end); + const start = this.offsetAt(range.start); + const end = this.offsetAt(range.end); return this._content.substring(start, end); } return this._content; @@ -4577,15 +4577,15 @@ class FullTextDocument implements TextDocument { private getLineOffsets(): uinteger[] { if (this._lineOffsets === undefined) { - let lineOffsets: uinteger[] = []; - let text = this._content; + const lineOffsets: uinteger[] = []; + const text = this._content; let isLineStart = true; for (let i = 0; i < text.length; i++) { if (isLineStart) { lineOffsets.push(i); isLineStart = false; } - let ch = text.charAt(i); + const ch = text.charAt(i); isLineStart = (ch === '\r' || ch === '\n'); if (ch === '\r' && i + 1 < text.length && text.charAt(i + 1) === '\n') { i++; @@ -4602,13 +4602,13 @@ class FullTextDocument implements TextDocument { public positionAt(offset: uinteger) { offset = Math.max(Math.min(offset, this._content.length), 0); - let lineOffsets = this.getLineOffsets(); + const lineOffsets = this.getLineOffsets(); let low = 0, high = lineOffsets.length; if (high === 0) { return Position.create(0, offset); } while (low < high) { - let mid = Math.floor((low + high) / 2); + const mid = Math.floor((low + high) / 2); if (lineOffsets[mid] > offset) { high = mid; } else { @@ -4617,19 +4617,19 @@ class FullTextDocument implements TextDocument { } // low is the least x for which the line offset is larger than the current offset // or array.length if no line offset is larger than the current offset - let line = low - 1; + const line = low - 1; return Position.create(line, offset - lineOffsets[line]); } public offsetAt(position: Position) { - let lineOffsets = this.getLineOffsets(); + const lineOffsets = this.getLineOffsets(); if (position.line >= lineOffsets.length) { return this._content.length; } else if (position.line < 0) { return 0; } - let lineOffset = lineOffsets[position.line]; - let nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length; + const lineOffset = lineOffsets[position.line]; + const nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length; return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset); } diff --git a/types/src/test/edits.test.ts b/types/src/test/edits.test.ts index af8ec6394..08d056fa1 100644 --- a/types/src/test/edits.test.ts +++ b/types/src/test/edits.test.ts @@ -12,7 +12,7 @@ const applyEdits = TextDocument.applyEdits; suite('Edits', () => { test('inserts', function (): any { - let input = TextDocument.create('foo://bar/f', 'html', 0, '012345678901234567890123456789'); + const input = TextDocument.create('foo://bar/f', 'html', 0, '012345678901234567890123456789'); assert.equal(applyEdits(input, [TextEdit.insert(Position.create(0, 0), 'Hello')]), 'Hello012345678901234567890123456789'); assert.equal(applyEdits(input, [TextEdit.insert(Position.create(0, 1), 'Hello')]), '0Hello12345678901234567890123456789'); assert.equal(applyEdits(input, [TextEdit.insert(Position.create(0, 1), 'Hello'), TextEdit.insert(Position.create(0, 1), 'World')]), '0HelloWorld12345678901234567890123456789'); @@ -20,7 +20,7 @@ suite('Edits', () => { }); test('replace', function (): any { - let input = TextDocument.create('foo://bar/f', 'html', 0, '012345678901234567890123456789'); + const input = TextDocument.create('foo://bar/f', 'html', 0, '012345678901234567890123456789'); assert.equal(applyEdits(input, [TextEdit.replace(Range.create(Position.create(0, 3), Position.create(0, 6)), 'Hello')]), '012Hello678901234567890123456789'); assert.equal(applyEdits(input, [TextEdit.replace(Range.create(Position.create(0, 3), Position.create(0, 6)), 'Hello'), TextEdit.replace(Range.create(Position.create(0, 6), Position.create(0, 9)), 'World')]), '012HelloWorld901234567890123456789'); assert.equal(applyEdits(input, [TextEdit.replace(Range.create(Position.create(0, 3), Position.create(0, 6)), 'Hello'), TextEdit.insert(Position.create(0, 6), 'World')]), '012HelloWorld678901234567890123456789'); @@ -30,13 +30,13 @@ suite('Edits', () => { }); test('overlap', function (): any { - let input = TextDocument.create('foo://bar/f', 'html', 0, '012345678901234567890123456789'); + const input = TextDocument.create('foo://bar/f', 'html', 0, '012345678901234567890123456789'); assert.throws(() => applyEdits(input, [TextEdit.replace(Range.create(Position.create(0, 3), Position.create(0, 6)), 'Hello'), TextEdit.insert(Position.create(0, 3), 'World')])); assert.throws(() => applyEdits(input, [TextEdit.replace(Range.create(Position.create(0, 3), Position.create(0, 6)), 'Hello'), TextEdit.insert(Position.create(0, 4), 'World')])); }); test('multiline', function (): any { - let input = TextDocument.create('foo://bar/f', 'html', 0, '0\n1\n2\n3\n4'); + const input = TextDocument.create('foo://bar/f', 'html', 0, '0\n1\n2\n3\n4'); assert.equal(applyEdits(input, [TextEdit.replace(Range.create(Position.create(2, 0), Position.create(3, 0)), 'Hello'), TextEdit.insert(Position.create(1, 1), 'World')]), '0\n1World\nHello3\n4'); }); diff --git a/types/src/test/textdocument.test.ts b/types/src/test/textdocument.test.ts index cf612cac7..c10c24734 100644 --- a/types/src/test/textdocument.test.ts +++ b/types/src/test/textdocument.test.ts @@ -13,24 +13,24 @@ suite('Text Document Lines Model Validator', () => { } test('Single line', () => { - var str = 'Hello World'; - var lm = newDocument(str); + const str = 'Hello World'; + const lm = newDocument(str); assert.equal(lm.lineCount, 1); - for (var i = 0; i < str.length; i++) { + for (let i = 0; i < str.length; i++) { assert.equal(lm.offsetAt(Position.create(0, i)), i); assert.deepEqual(lm.positionAt(i), Position.create(0, i)); } }); test('Multiple lines', () => { - var str = 'ABCDE\nFGHIJ\nKLMNO\n'; - var lm = newDocument(str); + const str = 'ABCDE\nFGHIJ\nKLMNO\n'; + const lm = newDocument(str); assert.equal(lm.lineCount, 4); - for (var i = 0; i < str.length; i++) { - var line = Math.floor(i / 6); - var column = i % 6; + for (let i = 0; i < str.length; i++) { + const line = Math.floor(i / 6); + const column = i % 6; assert.equal(lm.offsetAt(Position.create(line, column)), i); assert.deepEqual(lm.positionAt(i), Position.create(line, column)); @@ -43,13 +43,13 @@ suite('Text Document Lines Model Validator', () => { }); test('New line characters', () => { - var str = 'ABCDE\rFGHIJ'; + let str = 'ABCDE\rFGHIJ'; assert.equal(newDocument(str).lineCount, 2); - var str = 'ABCDE\nFGHIJ'; + str = 'ABCDE\nFGHIJ'; assert.equal(newDocument(str).lineCount, 2); - var str = 'ABCDE\r\nFGHIJ'; + str = 'ABCDE\r\nFGHIJ'; assert.equal(newDocument(str).lineCount, 2); str = 'ABCDE\n\nFGHIJ'; @@ -63,8 +63,8 @@ suite('Text Document Lines Model Validator', () => { }); test('getText(Range)', () => { - var str = '12345\n12345\n12345'; - var lm = newDocument(str); + const str = '12345\n12345\n12345'; + const lm = newDocument(str); assert.equal(lm.getText(), str); assert.equal(lm.getText(Range.create(0, 0, 0, 5)), '12345'); assert.equal(lm.getText(Range.create(0, 4, 1, 1)), '5\n1'); @@ -74,8 +74,8 @@ suite('Text Document Lines Model Validator', () => { }); test('Invalid inputs', () => { - var str = 'Hello World'; - var lm = newDocument(str); + const str = 'Hello World'; + const lm = newDocument(str); // invalid position assert.equal(lm.offsetAt(Position.create(0, str.length)), str.length);