diff --git a/.prettierrc b/.prettierrc index 9d1ee8539..a639031ac 100644 --- a/.prettierrc +++ b/.prettierrc @@ -1,6 +1,15 @@ { - "singleQuote": true, - "tabWidth": 4, - "useTabs": false, - "printWidth": 120 + "singleQuote": true, + "tabWidth": 4, + "useTabs": false, + "printWidth": 120, + "endOfLine": "auto", + "overrides": [ + { + "files": ["*.yml", "*.yaml"], + "options": { + "tabWidth": 2 + } + } + ] } diff --git a/client/src/cancellationUtils.ts b/client/src/cancellationUtils.ts index 5492f2e9d..bc3b80f04 100644 --- a/client/src/cancellationUtils.ts +++ b/client/src/cancellationUtils.ts @@ -15,7 +15,7 @@ import { CancellationReceiverStrategy, CancellationSenderStrategy, CancellationStrategy, - Disposable + Disposable, } from 'vscode-languageserver'; function getCancellationFolderPath(folderName: string) { diff --git a/client/src/extension.ts b/client/src/extension.ts index b695fb4e2..6967a05c0 100644 --- a/client/src/extension.ts +++ b/client/src/extension.ts @@ -37,8 +37,8 @@ export function activate(context: ExtensionContext) { module: fs.existsSync(nonBundlePath) ? nonBundlePath : bundlePath, transport: TransportKind.ipc, args: cancellationStrategy.getCommandLineArguments(), - options: debugOptions - } + options: debugOptions, + }, }; // Options to control the language client @@ -47,14 +47,14 @@ export function activate(context: ExtensionContext) { documentSelector: [ { scheme: 'file', - language: 'python' - } + language: 'python', + }, ], synchronize: { // Synchronize the setting section to the server. - configurationSection: ['python', 'pyright'] + configurationSection: ['python', 'pyright'], }, - connectionOptions: { cancellationStrategy: cancellationStrategy } + connectionOptions: { cancellationStrategy: cancellationStrategy }, }; // Create the language client and start the client. @@ -71,22 +71,22 @@ export function activate(context: ExtensionContext) { // Register our custom commands. const textEditorCommands = [Commands.orderImports, Commands.addMissingOptionalToParam]; - textEditorCommands.forEach(commandName => { + textEditorCommands.forEach((commandName) => { context.subscriptions.push( commands.registerTextEditorCommand( commandName, (editor: TextEditor, edit: TextEditorEdit, ...args: any[]) => { const cmd = { command: commandName, - arguments: [editor.document.uri.toString(), ...args] + arguments: [editor.document.uri.toString(), ...args], }; languageClient .sendRequest('workspace/executeCommand', cmd) .then((edits: TextEdit[] | undefined) => { if (edits && edits.length > 0) { - editor.edit(editBuilder => { - edits.forEach(edit => { + editor.edit((editBuilder) => { + edits.forEach((edit) => { const startPos = new Position( edit.range.start.line, edit.range.start.character @@ -107,7 +107,7 @@ export function activate(context: ExtensionContext) { }); const genericCommands = [Commands.createTypeStub, Commands.restartServer]; - genericCommands.forEach(command => { + genericCommands.forEach((command) => { context.subscriptions.push( commands.registerCommand(command, (...args: any[]) => { languageClient.sendRequest('workspace/executeCommand', { command, arguments: args }); diff --git a/client/src/progress.ts b/client/src/progress.ts index ca37f9911..7f06ec54c 100644 --- a/client/src/progress.ts +++ b/client/src/progress.ts @@ -21,16 +21,16 @@ export class ProgressReporting implements Disposable { constructor(languageClient: LanguageClient) { languageClient.onReady().then(() => { languageClient.onNotification('pyright/beginProgress', async () => { - const progressPromise = new Promise(resolve => { + const progressPromise = new Promise((resolve) => { this._resolveProgress = resolve; }); window.withProgress( { location: ProgressLocation.Window, - title: '' + title: '', }, - progress => { + (progress) => { this._progress = progress; return progressPromise; } diff --git a/package-lock.json b/package-lock.json index 33d2a429e..79b95c6e6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1313,9 +1313,9 @@ "dev": true }, "prettier": { - "version": "1.19.1", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.19.1.tgz", - "integrity": "sha512-s7PoyDv/II1ObgQunCbB9PdLmUcBZcnWOcxDh7O0N/UwDEsHyqkW+Qh28jW+mVuCdx7gLB0BotYI1Y6uI9iyew==", + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.0.4.tgz", + "integrity": "sha512-SVJIQ51spzFDvh4fIbCLvciiDMCrRhlN3mbZvv/+ycjvmF5E73bKdGfU8QDLNmjYJf+lsGnDBC4UUnvTe5OO0w==", "dev": true }, "progress": { diff --git a/package.json b/package.json index 663f1231f..817118175 100644 --- a/package.json +++ b/package.json @@ -31,7 +31,7 @@ "eslint": "^6.8.0", "eslint-config-prettier": "^6.10.1", "eslint-plugin-simple-import-sort": "^5.0.2", - "prettier": "1.19.1", + "prettier": "2.0.4", "typescript": "^3.8.3" }, "main": "index.js", diff --git a/server/.prettierrc b/server/.prettierrc index 9d1ee8539..a639031ac 100644 --- a/server/.prettierrc +++ b/server/.prettierrc @@ -1,6 +1,15 @@ { - "singleQuote": true, - "tabWidth": 4, - "useTabs": false, - "printWidth": 120 + "singleQuote": true, + "tabWidth": 4, + "useTabs": false, + "printWidth": 120, + "endOfLine": "auto", + "overrides": [ + { + "files": ["*.yml", "*.yaml"], + "options": { + "tabWidth": 2 + } + } + ] } diff --git a/server/jest.config.js b/server/jest.config.js index 3d2622ecf..3d6f3a9ad 100644 --- a/server/jest.config.js +++ b/server/jest.config.js @@ -7,7 +7,7 @@ module.exports = { roots: ['/src/tests'], transform: { - '^.+\\.tsx?$': 'ts-jest' + '^.+\\.tsx?$': 'ts-jest', }, testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$', moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'], @@ -18,8 +18,8 @@ module.exports = { // Needed because jest calls tsc in a way that doesn't // inline const enums. - preserveConstEnums: true - } - } - } + preserveConstEnums: true, + }, + }, + }, }; diff --git a/server/package-lock.json b/server/package-lock.json index e672fca5b..f5a7bc836 100644 --- a/server/package-lock.json +++ b/server/package-lock.json @@ -7264,9 +7264,9 @@ "dev": true }, "prettier": { - "version": "1.19.1", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.19.1.tgz", - "integrity": "sha512-s7PoyDv/II1ObgQunCbB9PdLmUcBZcnWOcxDh7O0N/UwDEsHyqkW+Qh28jW+mVuCdx7gLB0BotYI1Y6uI9iyew==", + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.0.4.tgz", + "integrity": "sha512-SVJIQ51spzFDvh4fIbCLvciiDMCrRhlN3mbZvv/+ycjvmF5E73bKdGfU8QDLNmjYJf+lsGnDBC4UUnvTe5OO0w==", "dev": true }, "pretty-format": { diff --git a/server/package.json b/server/package.json index 0f19ffcf1..de51e78ad 100644 --- a/server/package.json +++ b/server/package.json @@ -43,7 +43,7 @@ "jest": "^25.2.4", "jest-junit": "^10.0.0", "node-loader": "^0.6.0", - "prettier": "1.19.1", + "prettier": "2.0.4", "ts-jest": "^25.2.1", "ts-loader": "^6.2.2", "typescript": "^3.8.3", diff --git a/server/src/analyzer/analyzerNodeInfo.ts b/server/src/analyzer/analyzerNodeInfo.ts index 04bf43669..83f5526b3 100644 --- a/server/src/analyzer/analyzerNodeInfo.ts +++ b/server/src/analyzer/analyzerNodeInfo.ts @@ -17,7 +17,7 @@ import { LambdaNode, ListComprehensionNode, ModuleNode, - ParseNode + ParseNode, } from '../parser/parseNodes'; import { AnalyzerFileInfo } from './analyzerFileInfo'; import { FlowFlags, FlowNode } from './codeFlow'; diff --git a/server/src/analyzer/binder.ts b/server/src/analyzer/binder.ts index 47064164b..b9cdb6707 100644 --- a/server/src/analyzer/binder.ts +++ b/server/src/analyzer/binder.ts @@ -67,7 +67,7 @@ import { WhileNode, WithNode, YieldFromNode, - YieldNode + YieldNode, } from '../parser/parseNodes'; import * as StringTokenUtils from '../parser/stringTokenUtils'; import { KeywordType, OperatorType } from '../parser/tokenizerTypes'; @@ -86,7 +86,7 @@ import { FlowPreFinallyGate, FlowWildcardImport, getUniqueFlowNodeId, - isCodeFlowSupportedForReference + isCodeFlowSupportedForReference, } from './codeFlow'; import { AliasDeclaration, @@ -96,7 +96,7 @@ import { IntrinsicType, ModuleLoaderActions, ParameterDeclaration, - VariableDeclaration + VariableDeclaration, } from './declaration'; import { ImplicitImport, ImportResult, ImportType } from './importResult'; import * as ParseTreeUtils from './parseTreeUtils'; @@ -111,7 +111,7 @@ export const enum NameBindingType { Nonlocal, // With "global" keyword - Global + Global, } interface MemberAccessInfo { @@ -189,7 +189,7 @@ export class Binder extends ParseTreeWalker { // Flow node that is used for unreachable code. private static _unreachableFlowNode: FlowNode = { flags: FlowFlags.Unreachable, - id: getUniqueFlowNodeId() + id: getUniqueFlowNodeId(), }; constructor(fileInfo: AnalyzerFileInfo) { @@ -234,7 +234,7 @@ export class Binder extends ParseTreeWalker { this._bindDeferred(); return { - moduleDocString: ParseTreeUtils.getDocString(node.statements) + moduleDocString: ParseTreeUtils.getDocString(node.statements), }; } @@ -274,7 +274,7 @@ export class Binder extends ParseTreeWalker { // Add a diagnostic action for resolving this diagnostic. const createTypeStubAction: CreateTypeStubFileAction = { action: Commands.createTypeStub, - moduleName: importResult.importName + moduleName: importResult.importName, }; diagnostic.addAction(createTypeStubAction); } @@ -292,7 +292,7 @@ export class Binder extends ParseTreeWalker { type: DeclarationType.Class, node, path: this._fileInfo.filePath, - range: convertOffsetsToRange(node.name.start, TextRange.getEnd(node.name), this._fileInfo.lines) + range: convertOffsetsToRange(node.name.start, TextRange.getEnd(node.name), this._fileInfo.lines), }; const symbol = this._bindNameToScope(this._currentScope, node.name.value); @@ -337,7 +337,7 @@ export class Binder extends ParseTreeWalker { isMethod: !!containingClassNode, isGenerator: false, path: this._fileInfo.filePath, - range: convertOffsetsToRange(node.name.start, TextRange.getEnd(node.name), this._fileInfo.lines) + range: convertOffsetsToRange(node.name.start, TextRange.getEnd(node.name), this._fileInfo.lines), }; if (symbol) { @@ -348,7 +348,7 @@ export class Binder extends ParseTreeWalker { AnalyzerNodeInfo.setDeclaration(node, functionDeclaration); this.walkMultiple(node.decorators); - node.parameters.forEach(param => { + node.parameters.forEach((param) => { if (param.defaultValue) { this.walk(param.defaultValue); } @@ -411,7 +411,7 @@ export class Binder extends ParseTreeWalker { // Create a start node for the function. this._currentFlowNode = this._createStartFlowNode(); - node.parameters.forEach(paramNode => { + node.parameters.forEach((paramNode) => { if (paramNode.name) { const symbol = this._bindNameToScope(this._currentScope, paramNode.name.value); if (symbol) { @@ -423,7 +423,7 @@ export class Binder extends ParseTreeWalker { paramNode.start, TextRange.getEnd(paramNode), this._fileInfo.lines - ) + ), }; symbol.addDeclaration(paramDeclaration); @@ -464,7 +464,7 @@ export class Binder extends ParseTreeWalker { visitLambda(node: LambdaNode): boolean { // Analyze the parameter defaults in the context of the parent's scope // before we add any names from the function's scope. - node.parameters.forEach(param => { + node.parameters.forEach((param) => { if (param.defaultValue) { this.walk(param.defaultValue); } @@ -477,7 +477,7 @@ export class Binder extends ParseTreeWalker { // Create a start node for the lambda. this._currentFlowNode = this._createStartFlowNode(); - node.parameters.forEach(paramNode => { + node.parameters.forEach((paramNode) => { if (paramNode.name) { const symbol = this._bindNameToScope(this._currentScope, paramNode.name.value); if (symbol) { @@ -489,7 +489,7 @@ export class Binder extends ParseTreeWalker { paramNode.start, TextRange.getEnd(paramNode), this._fileInfo.lines - ) + ), }; symbol.addDeclaration(paramDeclaration); @@ -592,7 +592,7 @@ export class Binder extends ParseTreeWalker { } visitDel(node: DelNode) { - node.expressions.forEach(expr => { + node.expressions.forEach((expr) => { this._bindPossibleTupleNamedTarget(expr); this.walk(expr); this._createAssignmentTargetFlowNodes(expr, false, true); @@ -807,7 +807,7 @@ export class Binder extends ParseTreeWalker { node: node.name, isConstant: isConstantName(node.name.value), path: this._fileInfo.filePath, - range: convertOffsetsToRange(node.name.start, TextRange.getEnd(node.name), this._fileInfo.lines) + range: convertOffsetsToRange(node.name.start, TextRange.getEnd(node.name), this._fileInfo.lines), }; symbol.addDeclaration(declaration); } @@ -897,7 +897,7 @@ export class Binder extends ParseTreeWalker { flags: FlowFlags.PreFinallyGate, id: getUniqueFlowNodeId(), antecedent: preFinallyReturnOrRaiseLabel, - isGateClosed: false + isGateClosed: false, }; if (node.finallySuite) { this._addAntecedent(preFinallyLabel, preFinallyGate); @@ -906,7 +906,7 @@ export class Binder extends ParseTreeWalker { // An exception may be generated before the first flow node // added by the try block, so all of the exception targets // must have the pre-try flow node as an antecedent. - curExceptTargets.forEach(exceptLabel => { + curExceptTargets.forEach((exceptLabel) => { this._addAntecedent(exceptLabel, this._currentFlowNode); }); @@ -958,7 +958,7 @@ export class Binder extends ParseTreeWalker { flags: FlowFlags.PostFinally, id: getUniqueFlowNodeId(), antecedent: this._currentFlowNode, - preFinallyGate + preFinallyGate, }; this._currentFlowNode = isAfterElseAndExceptsReachable ? postFinallyNode : Binder._unreachableFlowNode; } @@ -1021,7 +1021,7 @@ export class Binder extends ParseTreeWalker { visitGlobal(node: GlobalNode): boolean { const globalScope = this._currentScope.getGlobalScope(); - node.nameList.forEach(name => { + node.nameList.forEach((name) => { const nameValue = name.value; // Is the binding inconsistent? @@ -1053,7 +1053,7 @@ export class Binder extends ParseTreeWalker { if (this._currentScope === globalScope) { this._addError('Nonlocal declaration not allowed at module level', node); } else { - node.nameList.forEach(name => { + node.nameList.forEach((name) => { const nameValue = name.value; // Is the binding inconsistent? @@ -1112,14 +1112,14 @@ export class Binder extends ParseTreeWalker { // python module loader. const existingDecl = symbol .getDeclarations() - .find(decl => decl.type === DeclarationType.Alias && decl.firstNamePart === firstNamePartValue); + .find((decl) => decl.type === DeclarationType.Alias && decl.firstNamePart === firstNamePartValue); const newDecl: AliasDeclaration = (existingDecl as AliasDeclaration) || { type: DeclarationType.Alias, node, path: '', range: getEmptyRange(), - firstNamePart: firstNamePartValue + firstNamePart: firstNamePartValue, }; // Add the implicit imports for this module if it's the last @@ -1146,7 +1146,7 @@ export class Binder extends ParseTreeWalker { // Allocate a new loader action. loaderActions = { path: '', - implicitImports: new Map() + implicitImports: new Map(), }; if (!curLoaderActions.implicitImports) { curLoaderActions.implicitImports = new Map(); @@ -1195,7 +1195,7 @@ export class Binder extends ParseTreeWalker { const lookupInfo = this._fileInfo.importLookup(resolvedPath); if (lookupInfo) { const wildcardNames = this._getWildcardImportNames(lookupInfo); - wildcardNames.forEach(name => { + wildcardNames.forEach((name) => { const symbol = lookupInfo.symbolTable.get(name)!; // Don't include the ignored names in the symbol table. @@ -1207,7 +1207,7 @@ export class Binder extends ParseTreeWalker { node, path: resolvedPath, range: getEmptyRange(), - symbolName: name + symbolName: name, }; symbol.addDeclaration(aliasDecl); names.push(name); @@ -1218,16 +1218,16 @@ export class Binder extends ParseTreeWalker { // Also add all of the implicitly-imported modules for // the import module. - importInfo.implicitImports.forEach(implicitImport => { + importInfo.implicitImports.forEach((implicitImport) => { // Don't overwrite a symbol that was imported from the module. - if (!names.some(name => name === implicitImport.name)) { + if (!names.some((name) => name === implicitImport.name)) { const symbol = this._bindNameToScope(this._currentScope, implicitImport.name); if (symbol) { const submoduleFallback: AliasDeclaration = { type: DeclarationType.Alias, node, path: implicitImport.path, - range: getEmptyRange() + range: getEmptyRange(), }; const aliasDecl: AliasDeclaration = { @@ -1236,7 +1236,7 @@ export class Binder extends ParseTreeWalker { path: resolvedPath, symbolName: implicitImport.name, submoduleFallback, - range: getEmptyRange() + range: getEmptyRange(), }; symbol.addDeclaration(aliasDecl); @@ -1248,7 +1248,7 @@ export class Binder extends ParseTreeWalker { this._createFlowWildcardImport(node, names); } } else { - node.imports.forEach(importSymbolNode => { + node.imports.forEach((importSymbolNode) => { const importedName = importSymbolNode.name.value; const nameNode = importSymbolNode.alias || importSymbolNode.name; const symbol = this._bindNameToScope(this._currentScope, nameNode.value); @@ -1264,7 +1264,7 @@ export class Binder extends ParseTreeWalker { // Is the import referring to an implicitly-imported module? let implicitImport: ImplicitImport | undefined; if (importInfo && importInfo.implicitImports) { - implicitImport = importInfo.implicitImports.find(imp => imp.name === importedName); + implicitImport = importInfo.implicitImports.find((imp) => imp.name === importedName); } let submoduleFallback: AliasDeclaration | undefined; @@ -1273,7 +1273,7 @@ export class Binder extends ParseTreeWalker { type: DeclarationType.Alias, node: importSymbolNode, path: implicitImport.path, - range: getEmptyRange() + range: getEmptyRange(), }; // Handle the case of "from . import X". In this case, @@ -1290,7 +1290,7 @@ export class Binder extends ParseTreeWalker { path: resolvedPath, symbolName: importedName, submoduleFallback, - range: getEmptyRange() + range: getEmptyRange(), }; symbol.addDeclaration(aliasDecl); @@ -1303,7 +1303,7 @@ export class Binder extends ParseTreeWalker { } visitWith(node: WithNode): boolean { - node.withItems.forEach(item => { + node.withItems.forEach((item) => { this.walk(item.expression); if (item.target) { this._bindPossibleTupleNamedTarget(item.target); @@ -1476,7 +1476,7 @@ export class Binder extends ParseTreeWalker { if (firstDecl.node.parent && firstDecl.node.parent.nodeType === ParseNodeType.Assignment) { const expr = firstDecl.node.parent.rightExpression; if (expr.nodeType === ParseNodeType.List) { - expr.entries.forEach(listEntryNode => { + expr.entries.forEach((listEntryNode) => { if ( listEntryNode.nodeType === ParseNodeType.StringList && listEntryNode.strings.length === 1 && @@ -1544,7 +1544,7 @@ export class Binder extends ParseTreeWalker { private _createStartFlowNode() { const flowNode: FlowNode = { flags: FlowFlags.Start, - id: getUniqueFlowNodeId() + id: getUniqueFlowNodeId(), }; return flowNode; } @@ -1553,7 +1553,7 @@ export class Binder extends ParseTreeWalker { const flowNode: FlowLabel = { flags: FlowFlags.BranchLabel, id: getUniqueFlowNodeId(), - antecedents: [] + antecedents: [], }; return flowNode; } @@ -1562,7 +1562,7 @@ export class Binder extends ParseTreeWalker { const flowNode: FlowLabel = { flags: FlowFlags.LoopLabel, id: getUniqueFlowNodeId(), - antecedents: [] + antecedents: [], }; return flowNode; } @@ -1625,7 +1625,7 @@ export class Binder extends ParseTreeWalker { return antecedent; } - expressionList.forEach(expr => { + expressionList.forEach((expr) => { const referenceKey = createKeyForReference(expr); this._currentExecutionScopeReferenceMap.set(referenceKey, referenceKey); }); @@ -1634,7 +1634,7 @@ export class Binder extends ParseTreeWalker { flags, id: getUniqueFlowNodeId(), expression, - antecedent + antecedent, }; this._addExceptTargets(conditionalFlowNode); @@ -1759,7 +1759,7 @@ export class Binder extends ParseTreeWalker { } case ParseNodeType.Tuple: { - target.expressions.forEach(expr => { + target.expressions.forEach((expr) => { this._createAssignmentTargetFlowNodes(expr, walkTargets, unbound); }); break; @@ -1782,7 +1782,7 @@ export class Binder extends ParseTreeWalker { } case ParseNodeType.List: { - target.entries.forEach(entry => { + target.entries.forEach((entry) => { this._createAssignmentTargetFlowNodes(entry, walkTargets, unbound); }); break; @@ -1802,7 +1802,7 @@ export class Binder extends ParseTreeWalker { flags: FlowFlags.Call, id: getUniqueFlowNodeId(), node, - antecedent: this._currentFlowNode + antecedent: this._currentFlowNode, }; this._currentFlowNode = flowNode; @@ -1816,7 +1816,7 @@ export class Binder extends ParseTreeWalker { id: getUniqueFlowNodeId(), antecedent: this._currentFlowNode, targetSymbolId, - aliasSymbolId + aliasSymbolId, }; this._currentFlowNode = flowNode; @@ -1838,7 +1838,7 @@ export class Binder extends ParseTreeWalker { id: getUniqueFlowNodeId(), node, antecedent: this._currentFlowNode, - targetSymbolId + targetSymbolId, }; const referenceKey = createKeyForReference(node); @@ -1865,7 +1865,7 @@ export class Binder extends ParseTreeWalker { id: getUniqueFlowNodeId(), node, names, - antecedent: this._currentFlowNode + antecedent: this._currentFlowNode, }; this._addExceptTargets(flowNode); @@ -1883,7 +1883,7 @@ export class Binder extends ParseTreeWalker { // If there are any except targets, then we're in a try block, and we // have to assume that an exception can be raised after every assignment. if (this._currentExceptTargets) { - this._currentExceptTargets.forEach(label => { + this._currentExceptTargets.forEach((label) => { this._addAntecedent(label, flowNode); }); } @@ -1904,7 +1904,7 @@ export class Binder extends ParseTreeWalker { private _addAntecedent(label: FlowLabel, antecedent: FlowNode) { if (!(this._currentFlowNode.flags & FlowFlags.Unreachable)) { // Don't add the same antecedent twice. - if (!label.antecedents.some(existing => existing.id === antecedent.id)) { + if (!label.antecedents.some((existing) => existing.id === antecedent.id)) { label.antecedents.push(antecedent); } } @@ -1950,14 +1950,14 @@ export class Binder extends ParseTreeWalker { } case ParseNodeType.Tuple: { - target.expressions.forEach(expr => { + target.expressions.forEach((expr) => { this._bindPossibleTupleNamedTarget(expr, addedSymbols); }); break; } case ParseNodeType.List: { - target.entries.forEach(expr => { + target.entries.forEach((expr) => { this._bindPossibleTupleNamedTarget(expr, addedSymbols); }); break; @@ -1987,7 +1987,7 @@ export class Binder extends ParseTreeWalker { node, intrinsicType: type, path: this._fileInfo.filePath, - range: getEmptyRange() + range: getEmptyRange(), }); symbol.setIsIgnoredForProtocolMatch(); } @@ -2055,7 +2055,7 @@ export class Binder extends ParseTreeWalker { isConstant: isConstantName(target.value), inferredTypeSource: source, path: this._fileInfo.filePath, - range: convertOffsetsToRange(name.start, TextRange.getEnd(name), this._fileInfo.lines) + range: convertOffsetsToRange(name.start, TextRange.getEnd(name), this._fileInfo.lines), }; symbolWithScope.symbol.addDeclaration(declaration); } @@ -2092,7 +2092,7 @@ export class Binder extends ParseTreeWalker { target.memberName.start, target.memberName.start + target.memberName.length, this._fileInfo.lines - ) + ), }; symbol.addDeclaration(declaration); } @@ -2100,7 +2100,7 @@ export class Binder extends ParseTreeWalker { } case ParseNodeType.Tuple: { - target.expressions.forEach(expr => { + target.expressions.forEach((expr) => { this._addInferredTypeAssignmentForVariable(expr, source); }); break; @@ -2117,7 +2117,7 @@ export class Binder extends ParseTreeWalker { } case ParseNodeType.List: { - target.entries.forEach(entry => { + target.entries.forEach((entry) => { this._addInferredTypeAssignmentForVariable(entry, source); }); break; @@ -2141,7 +2141,7 @@ export class Binder extends ParseTreeWalker { isFinal: finalInfo.isFinal, path: this._fileInfo.filePath, typeAnnotationNode: finalInfo.isFinal ? finalInfo.finalTypeNode : typeAnnotation, - range: convertOffsetsToRange(name.start, TextRange.getEnd(name), this._fileInfo.lines) + range: convertOffsetsToRange(name.start, TextRange.getEnd(name), this._fileInfo.lines), }; symbolWithScope.symbol.addDeclaration(declaration); } @@ -2190,7 +2190,7 @@ export class Binder extends ParseTreeWalker { target.memberName.start, target.memberName.start + target.memberName.length, this._fileInfo.lines - ) + ), }; symbol.addDeclaration(declaration); @@ -2319,12 +2319,12 @@ export class Binder extends ParseTreeWalker { classNode, methodNode, classScope, - isInstanceMember + isInstanceMember, }; } private _addImplicitImportsToLoaderActions(importResult: ImportResult, loaderActions: ModuleLoaderActions) { - importResult.implicitImports.forEach(implicitImport => { + importResult.implicitImports.forEach((implicitImport) => { const existingLoaderAction = loaderActions.implicitImports ? loaderActions.implicitImports.get(implicitImport.name) : undefined; @@ -2336,7 +2336,7 @@ export class Binder extends ParseTreeWalker { } loaderActions.implicitImports.set(implicitImport.name, { path: implicitImport.path, - implicitImports: new Map() + implicitImports: new Map(), }); } }); @@ -2375,7 +2375,7 @@ export class Binder extends ParseTreeWalker { ClassVar: true, Final: true, Literal: true, - TypedDict: true + TypedDict: true, }; const assignedName = assignedNameNode.value; @@ -2394,7 +2394,7 @@ export class Binder extends ParseTreeWalker { annotationNode.start, TextRange.getEnd(annotationNode), this._fileInfo.lines - ) + ), }); } return true; @@ -2405,7 +2405,7 @@ export class Binder extends ParseTreeWalker { scope: this._currentScope, nonLocalBindingsMap: this._notLocalBindings, codeFlowExpressionMap: this._currentExecutionScopeReferenceMap, - callback + callback, }); } diff --git a/server/src/analyzer/checker.ts b/server/src/analyzer/checker.ts index 3382354e3..360c9af4b 100644 --- a/server/src/analyzer/checker.ts +++ b/server/src/analyzer/checker.ts @@ -57,7 +57,7 @@ import { WhileNode, WithNode, YieldFromNode, - YieldNode + YieldNode, } from '../parser/parseNodes'; import { AnalyzerFileInfo } from './analyzerFileInfo'; import * as AnalyzerNodeInfo from './analyzerNodeInfo'; @@ -82,7 +82,7 @@ import { ObjectType, Type, TypeCategory, - UnknownType + UnknownType, } from './types'; import { ClassMemberLookupFlags, @@ -95,7 +95,7 @@ import { isProperty, lookUpClassMember, specializeType, - transformTypeObjectToClass + transformTypeObjectToClass, } from './typeUtils'; export class Checker extends ParseTreeWalker { @@ -189,7 +189,7 @@ export class Checker extends ParseTreeWalker { } } - node.parameters.forEach(param => { + node.parameters.forEach((param) => { if (param.defaultValue) { this.walk(param.defaultValue); } @@ -205,7 +205,7 @@ export class Checker extends ParseTreeWalker { this.walkMultiple(node.decorators); - node.parameters.forEach(param => { + node.parameters.forEach((param) => { if (param.name) { this.walk(param.name); } @@ -229,7 +229,7 @@ export class Checker extends ParseTreeWalker { // Walk the children. this.walkMultiple([...node.parameters, node.expression]); - node.parameters.forEach(param => { + node.parameters.forEach((param) => { if (param.name) { const paramType = this._evaluator.getType(param.name); if (paramType) { @@ -315,7 +315,7 @@ export class Checker extends ParseTreeWalker { } visitWith(node: WithNode): boolean { - node.withItems.forEach(item => { + node.withItems.forEach((item) => { this._evaluator.evaluateTypesForStatement(item); }); @@ -421,7 +421,7 @@ export class Checker extends ParseTreeWalker { if (exceptionType && baseExceptionType && baseExceptionType.category === TypeCategory.Class) { const diagAddendum = new DiagnosticAddendum(); - doForSubtypes(exceptionType, subtype => { + doForSubtypes(exceptionType, (subtype) => { if (!isAnyOrUnknown(subtype)) { if (subtype.category === TypeCategory.Class) { if (!derivesFromClassRecursive(subtype, baseExceptionType)) { @@ -463,7 +463,7 @@ export class Checker extends ParseTreeWalker { if (exceptionType && baseExceptionType && baseExceptionType.category === TypeCategory.Class) { const diagAddendum = new DiagnosticAddendum(); - doForSubtypes(exceptionType, subtype => { + doForSubtypes(exceptionType, (subtype) => { if (!isAnyOrUnknown(subtype) && !isNoneOrNever(subtype)) { if (subtype.category === TypeCategory.Object) { if (!derivesFromClassRecursive(subtype.classType, baseExceptionType)) { @@ -602,7 +602,7 @@ export class Checker extends ParseTreeWalker { } visitFormatString(node: FormatStringNode): boolean { - node.expressions.forEach(formatExpr => { + node.expressions.forEach((formatExpr) => { this._evaluator.getType(formatExpr); }); @@ -616,7 +616,7 @@ export class Checker extends ParseTreeWalker { } visitDel(node: DelNode) { - node.expressions.forEach(expr => { + node.expressions.forEach((expr) => { this._evaluator.verifyDeleteExpression(expr); }); @@ -640,7 +640,7 @@ export class Checker extends ParseTreeWalker { visitImportFrom(node: ImportFromNode): boolean { if (!node.isWildcardImport) { - node.imports.forEach(importAs => { + node.imports.forEach((importAs) => { this._evaluator.evaluateTypesForStatement(importAs); }); } @@ -689,7 +689,7 @@ export class Checker extends ParseTreeWalker { } else if (exceptionType.category === TypeCategory.Object) { const iterableType = this._evaluator.getTypeFromIterable(exceptionType, false, errorNode, false); - resultingExceptionType = doForSubtypes(iterableType, subtype => { + resultingExceptionType = doForSubtypes(iterableType, (subtype) => { if (isAnyOrUnknown(subtype)) { return subtype; } @@ -750,7 +750,7 @@ export class Checker extends ParseTreeWalker { let sawFinal = false; let sawAssignment = false; - decls.forEach(decl => { + decls.forEach((decl) => { if (isFinalVariableDeclaration(decl)) { if (sawFinal) { this._evaluator.addError(`"${name}" was previously declared as Final`, decl.node); @@ -768,7 +768,7 @@ export class Checker extends ParseTreeWalker { // If it's not a stub file, an assignment must be provided. if (!sawAssignment && !this._fileInfo.isStubFile) { - const firstDecl = decls.find(decl => decl.type === DeclarationType.Variable && decl.isFinal); + const firstDecl = decls.find((decl) => decl.type === DeclarationType.Variable && decl.isFinal); if (firstDecl) { this._evaluator.addError(`"${name}" is declared Final, but value is not assigned`, firstDecl.node); } @@ -786,12 +786,12 @@ export class Checker extends ParseTreeWalker { return; } - let otherDecls = symbol.getDeclarations().filter(decl => decl !== primaryDecl); + let otherDecls = symbol.getDeclarations().filter((decl) => decl !== primaryDecl); // If it's a function, we can skip any other declarations // that are overloads. if (primaryDecl.type === DeclarationType.Function) { - otherDecls = otherDecls.filter(decl => decl.type !== DeclarationType.Function); + otherDecls = otherDecls.filter((decl) => decl.type !== DeclarationType.Function); } // If there are no other declarations to consider, we're done. @@ -916,7 +916,7 @@ export class Checker extends ParseTreeWalker { } const decls = symbol.getDeclarations(); - decls.forEach(decl => { + decls.forEach((decl) => { this._conditionallyReportUnusedDeclaration(decl, this._isSymbolPrivate(name, scopeType)); }); } @@ -938,7 +938,7 @@ export class Checker extends ParseTreeWalker { // Handle multi-part names specially. const nameParts = decl.node.module.nameParts; if (nameParts.length > 0) { - const multipartName = nameParts.map(np => np.value).join('.'); + const multipartName = nameParts.map((np) => np.value).join('.'); const textRange: TextRange = { start: nameParts[0].start, length: nameParts[0].length }; TextRange.extend(textRange, nameParts[nameParts.length - 1]); this._fileInfo.diagnosticSink.addUnusedCodeWithTextRange( @@ -1045,7 +1045,7 @@ export class Checker extends ParseTreeWalker { if (!arg0Type) { return; } - arg0Type = doForSubtypes(arg0Type, subtype => { + arg0Type = doForSubtypes(arg0Type, (subtype) => { return transformTypeObjectToClass(subtype); }); @@ -1066,7 +1066,7 @@ export class Checker extends ParseTreeWalker { // parameter is a tuple of classes. const objClass = arg1Type.classType; if (ClassType.isBuiltIn(objClass, 'Tuple') && objClass.typeArguments) { - objClass.typeArguments.forEach(typeArg => { + objClass.typeArguments.forEach((typeArg) => { if (typeArg.category === TypeCategory.Class) { classTypeList.push(typeArg); } else { @@ -1080,7 +1080,7 @@ export class Checker extends ParseTreeWalker { // According to PEP 544, protocol classes cannot be used as the right-hand // argument to isinstance or issubclass. - if (classTypeList.some(type => ClassType.isProtocolClass(type))) { + if (classTypeList.some((type) => ClassType.isProtocolClass(type))) { this._evaluator.addError( `Protocol class cannot be used in ${callName} call`, node.arguments[1].valueExpression @@ -1125,7 +1125,7 @@ export class Checker extends ParseTreeWalker { } // Make all class types into object types before returning them. - return filteredTypes.map(t => (t.category === TypeCategory.Class ? ObjectType.create(t) : t)); + return filteredTypes.map((t) => (t.category === TypeCategory.Class ? ObjectType.create(t) : t)); }; let filteredType: Type; @@ -1139,7 +1139,7 @@ export class Checker extends ParseTreeWalker { let remainingTypes: Type[] = []; let foundAnyType = false; - arg0Type.subtypes.forEach(t => { + arg0Type.subtypes.forEach((t) => { if (isAnyOrUnknown(t)) { foundAnyType = true; } @@ -1162,7 +1162,7 @@ export class Checker extends ParseTreeWalker { } const getTestType = () => { - const objTypeList = classTypeList.map(t => ObjectType.create(t)); + const objTypeList = classTypeList.map((t) => ObjectType.create(t)); return combineTypes(objTypeList); }; @@ -1319,7 +1319,7 @@ export class Checker extends ParseTreeWalker { this._evaluator.addError(`TypedDict classes can contain only type annotations`, node); }; - suiteNode.statements.forEach(statement => { + suiteNode.statements.forEach((statement) => { if (!AnalyzerNodeInfo.isCodeUnreachable(statement)) { if (statement.nodeType === ParseNodeType.StatementList) { for (const substatement of statement.statements) { @@ -1674,11 +1674,11 @@ export class Checker extends ParseTreeWalker { const importModuleMap = new Map(); - importStatements.orderedImports.forEach(importStatement => { + importStatements.orderedImports.forEach((importStatement) => { if (importStatement.node.nodeType === ParseNodeType.ImportFrom) { const symbolMap = new Map(); - importStatement.node.imports.forEach(importFromAs => { + importStatement.node.imports.forEach((importFromAs) => { // Ignore duplicates if they're aliased. if (!importFromAs.alias) { const prevImport = symbolMap.get(importFromAs.name.value); diff --git a/server/src/analyzer/codeFlow.ts b/server/src/analyzer/codeFlow.ts index 02226353e..7b7bd9593 100644 --- a/server/src/analyzer/codeFlow.ts +++ b/server/src/analyzer/codeFlow.ts @@ -20,7 +20,7 @@ import { ImportFromNode, MemberAccessNode, NameNode, - ParseNodeType + ParseNodeType, } from '../parser/parseNodes'; export enum FlowFlags { @@ -36,7 +36,7 @@ export enum FlowFlags { Call = 1 << 10, // Call node PreFinallyGate = 1 << 11, // Injected edge that links pre-finally label and pre-try flow PostFinally = 1 << 12, // Injected edge that links post-finally flow with the rest of the graph - AssignmentAlias = 1 << 13 // Assigned symbol is aliased to another symbol with the same name + AssignmentAlias = 1 << 13, // Assigned symbol is aliased to another symbol with the same name } let _nextFlowNodeId = 1; diff --git a/server/src/analyzer/commentUtils.ts b/server/src/analyzer/commentUtils.ts index ab5b68f57..adf475e0f 100644 --- a/server/src/analyzer/commentUtils.ts +++ b/server/src/analyzer/commentUtils.ts @@ -14,7 +14,7 @@ import { DiagnosticSettings, getBooleanDiagnosticSettings, getDiagLevelSettings, - getStrictDiagnosticSettings + getStrictDiagnosticSettings, } from '../common/configOptions'; import { TextRangeCollection } from '../common/textRangeCollection'; import { Token } from '../parser/tokenizerTypes'; @@ -69,14 +69,14 @@ function _applyStrictSettings(settings: DiagnosticSettings) { function _parsePyrightComment(commentValue: string, settings: DiagnosticSettings) { // Is this a pyright or mspython-specific comment? const validPrefixes = ['pyright:', 'mspython:']; - const prefix = validPrefixes.find(p => commentValue.startsWith(p)); + const prefix = validPrefixes.find((p) => commentValue.startsWith(p)); if (prefix) { const operands = commentValue.substr(prefix.length).trim(); - const operandList = operands.split(',').map(s => s.trim()); + const operandList = operands.split(',').map((s) => s.trim()); // If it contains a "strict" operand, replace the existing // diagnostic settings with their strict counterparts. - if (operandList.some(s => s === 'strict')) { + if (operandList.some((s) => s === 'strict')) { _applyStrictSettings(settings); } @@ -89,7 +89,7 @@ function _parsePyrightComment(commentValue: string, settings: DiagnosticSettings } function _parsePyrightOperand(operand: string, settings: DiagnosticSettings) { - const operandSplit = operand.split('=').map(s => s.trim()); + const operandSplit = operand.split('=').map((s) => s.trim()); if (operandSplit.length !== 2) { return settings; } @@ -98,12 +98,12 @@ function _parsePyrightOperand(operand: string, settings: DiagnosticSettings) { const boolSettings = getBooleanDiagnosticSettings(); const diagLevelSettings = getDiagLevelSettings(); - if (diagLevelSettings.find(s => s === settingName)) { + if (diagLevelSettings.find((s) => s === settingName)) { const diagLevelValue = _parseDiagLevel(operandSplit[1]); if (diagLevelValue !== undefined) { (settings as any)[settingName] = diagLevelValue; } - } else if (boolSettings.find(s => s === settingName)) { + } else if (boolSettings.find((s) => s === settingName)) { const boolValue = _parseBoolSetting(operandSplit[1]); if (boolValue !== undefined) { (settings as any)[settingName] = boolValue; diff --git a/server/src/analyzer/declaration.ts b/server/src/analyzer/declaration.ts index 8dd50884c..d16229c7e 100644 --- a/server/src/analyzer/declaration.ts +++ b/server/src/analyzer/declaration.ts @@ -25,7 +25,7 @@ import { StringListNode, TypeAnnotationNode, YieldFromNode, - YieldNode + YieldNode, } from '../parser/parseNodes'; export const enum DeclarationType { @@ -35,7 +35,7 @@ export const enum DeclarationType { Function, Class, SpecialBuiltInClass, - Alias + Alias, } export type IntrinsicType = 'Any' | 'str' | 'Iterable[str]' | 'class' | 'Dict[str, Any]'; diff --git a/server/src/analyzer/docStringToMarkdown.ts b/server/src/analyzer/docStringToMarkdown.ts index fe3aa5701..c1cb09ff2 100644 --- a/server/src/analyzer/docStringToMarkdown.ts +++ b/server/src/analyzer/docStringToMarkdown.ts @@ -41,7 +41,7 @@ const PotentialHeaders: RegexReplacement[] = [ { exp: /^\s*=+(\s+=+)+$/, replacement: '=' }, { exp: /^\s*-+(\s+-+)+$/, replacement: '-' }, { exp: /^\s*~+(\s+-+)+$/, replacement: '~' }, - { exp: /^\s*\++(\s+\++)+$/, replacement: '+' } + { exp: /^\s*\++(\s+\++)+$/, replacement: '+' }, ]; // Regexes for replace all @@ -59,7 +59,7 @@ const LiteralBlockReplacements: RegexReplacement[] = [ { exp: /(\S)\s*::$/g, replacement: '$1:' }, // http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#interpreted-text { exp: /:[\w_\-+:.]+:`/g, replacement: '`' }, - { exp: /`:[\w_\-+:.]+:/g, replacement: '`' } + { exp: /`:[\w_\-+:.]+:/g, replacement: '`' }, ]; // Converter is a state machine, where the current state is a function which @@ -133,7 +133,9 @@ class DocStringConverter { } private _nextBlockIndent(): number { - return _countLeadingSpaces(this._lines.slice(this._lineNum + 1).find(v => !_isUndefinedOrWhitespace(v)) || ''); + return _countLeadingSpaces( + this._lines.slice(this._lineNum + 1).find((v) => !_isUndefinedOrWhitespace(v)) || '' + ); } private _currentLineIsOutsideBlock(): boolean { @@ -284,7 +286,7 @@ class DocStringConverter { return ''; } - LiteralBlockReplacements.forEach(item => (line = line.replace(item.exp, item.replacement))); + LiteralBlockReplacements.forEach((item) => (line = line.replace(item.exp, item.replacement))); line = line.replace(DoubleTickRegEx, '`'); return line; @@ -503,7 +505,7 @@ function _splitDocString(docstring: string): string[] { // As done by inspect.cleandoc. docstring = docstring.replace(TabRegEx, ' '.repeat(8)); - let lines = docstring.split(CrLfRegEx).map(v => v.trimRight()); + let lines = docstring.split(CrLfRegEx).map((v) => v.trimRight()); if (lines.length > 0) { let first: string | undefined = lines[0].trimLeft(); if (first === '') { @@ -524,11 +526,11 @@ function _splitDocString(docstring: string): string[] { function _stripLeadingWhitespace(lines: string[], trim?: number): string[] { const amount = trim === undefined ? _largestTrim(lines) : trim; - return lines.map(line => (amount > line.length ? '' : line.substr(amount))); + return lines.map((line) => (amount > line.length ? '' : line.substr(amount))); } function _largestTrim(lines: string[]): number { - const nonEmptyLines = lines.filter(s => !_isUndefinedOrWhitespace(s)); + const nonEmptyLines = lines.filter((s) => !_isUndefinedOrWhitespace(s)); const counts = nonEmptyLines.map(_countLeadingSpaces); const largest = counts.length > 0 ? Math.min(...counts) : 0; return largest; diff --git a/server/src/analyzer/importResolver.ts b/server/src/analyzer/importResolver.ts index 033286dd8..2b46dbc3e 100644 --- a/server/src/analyzer/importResolver.ts +++ b/server/src/analyzer/importResolver.ts @@ -20,7 +20,7 @@ import { isDirectory, isFile, stripFileExtension, - stripTrailingDirectorySeparator + stripTrailingDirectorySeparator, } from '../common/pathUtils'; import { versionToString } from '../common/pythonVersion'; import * as StringUtils from '../common/stringUtils'; @@ -243,7 +243,7 @@ export class ImportResolver { importType: ImportType.Local, isStubFile: false, isPydFile: false, - implicitImports: [] + implicitImports: [], }; return this._addResultsToCache(execEnv, importName, notFoundResult, undefined); @@ -837,7 +837,7 @@ export class ImportResolver { searchPath: rootPath, isStubFile, isPydFile, - implicitImports + implicitImports, }; } @@ -853,7 +853,7 @@ export class ImportResolver { // Copy the nameParts into a new directory and add an extra empty // part if there is a trailing dot. - const nameParts = moduleDescriptor.nameParts.map(name => name); + const nameParts = moduleDescriptor.nameParts.map((name) => name); if (moduleDescriptor.hasTrailingDot) { nameParts.push(''); } @@ -881,7 +881,7 @@ export class ImportResolver { private _addFilteredSuggestions(dirPath: string, filter: string, suggestions: string[], similarityLimit: number) { const entries = getFileSystemEntries(this.fileSystem, dirPath); - entries.files.forEach(file => { + entries.files.forEach((file) => { const fileWithoutExtension = stripFileExtension(file); const fileExtension = getFileExtension(file); @@ -897,7 +897,7 @@ export class ImportResolver { } }); - entries.directories.forEach(dir => { + entries.directories.forEach((dir) => { if (!filter || dir.startsWith(filter)) { this._addUniqueSuggestion(dir, suggestions); } @@ -905,7 +905,7 @@ export class ImportResolver { } private _addUniqueSuggestion(suggestionToAdd: string, suggestions: string[]) { - if (suggestions.some(s => s === suggestionToAdd)) { + if (suggestions.some((s) => s === suggestionToAdd)) { return; } @@ -939,8 +939,8 @@ export class ImportResolver { return importResult; } - const filteredImplicitImports = importResult.implicitImports.filter(implicitImport => { - return importedSymbols.some(sym => sym === implicitImport.name); + const filteredImplicitImports = importResult.implicitImports.filter((implicitImport) => { + return importedSymbols.some((sym) => sym === implicitImport.name); }); if (filteredImplicitImports.length === importResult.implicitImports.length) { @@ -963,12 +963,12 @@ export class ImportResolver { if (fileName.endsWith('.py') || fileName.endsWith('.pyi')) { const filePath = combinePaths(dirPath, fileName); - if (!exclusions.find(exclusion => exclusion === filePath)) { + if (!exclusions.find((exclusion) => exclusion === filePath)) { const strippedFileName = stripFileExtension(fileName); const implicitImport: ImplicitImport = { isStubFile: fileName.endsWith('.pyi'), name: strippedFileName, - path: filePath + path: filePath, }; // Always prefer stub files over non-stub files. @@ -995,11 +995,11 @@ export class ImportResolver { } if (path) { - if (!exclusions.find(exclusion => exclusion === path)) { + if (!exclusions.find((exclusion) => exclusion === path)) { const implicitImport: ImplicitImport = { isStubFile, name: dirName, - path + path, }; implicitImportMap.set(implicitImport.name, implicitImport); @@ -1016,7 +1016,7 @@ export class ImportResolver { name += '.'; } - return name + moduleDescriptor.nameParts.map(part => part).join('.'); + return name + moduleDescriptor.nameParts.map((part) => part).join('.'); } } diff --git a/server/src/analyzer/importResult.ts b/server/src/analyzer/importResult.ts index 75d1cf1f4..d3876245c 100644 --- a/server/src/analyzer/importResult.ts +++ b/server/src/analyzer/importResult.ts @@ -10,7 +10,7 @@ export const enum ImportType { BuiltIn, ThirdParty, - Local + Local, } export interface ImplicitImport { diff --git a/server/src/analyzer/importStatementUtils.ts b/server/src/analyzer/importStatementUtils.ts index e4dbad59d..93bedb96e 100644 --- a/server/src/analyzer/importStatementUtils.ts +++ b/server/src/analyzer/importStatementUtils.ts @@ -19,7 +19,7 @@ import { ImportNode, ModuleNameNode, ModuleNode, - ParseNodeType + ParseNodeType, } from '../parser/parseNodes'; import { ParseResults } from '../parser/parser'; import * as AnalyzerNodeInfo from './analyzerNodeInfo'; @@ -45,15 +45,15 @@ export interface ImportStatements { export function getTopLevelImports(parseTree: ModuleNode): ImportStatements { const localImports: ImportStatements = { orderedImports: [], - mapByFilePath: new Map() + mapByFilePath: new Map(), }; let followsNonImportStatement = false; let foundFirstImportStatement = false; - parseTree.statements.forEach(statement => { + parseTree.statements.forEach((statement) => { if (statement.nodeType === ParseNodeType.StatementList) { - statement.statements.forEach(subStatement => { + statement.statements.forEach((subStatement) => { if (subStatement.nodeType === ParseNodeType.Import) { foundFirstImportStatement = true; _processImportNode(subStatement, localImports, followsNonImportStatement); @@ -88,7 +88,7 @@ export function getTextEditsForAutoImportSymbolAddition( if (importStatement.node && importStatement.node.nodeType === ParseNodeType.ImportFrom) { // Make sure we're not attempting to auto-import a symbol that // already exists in the import list. - if (!importStatement.node.imports.some(importAs => importAs.name.value === symbolName)) { + if (!importStatement.node.imports.some((importAs) => importAs.name.value === symbolName)) { for (const curImport of importStatement.node.imports) { if (curImport.name.value > symbolName) { break; @@ -106,7 +106,7 @@ export function getTextEditsForAutoImportSymbolAddition( textEditList.push({ range: { start: insertionPosition, end: insertionPosition }, - replacementText: priorImport ? ', ' + symbolName : symbolName + ', ' + replacementText: priorImport ? ', ' + symbolName : symbolName + ', ', }); } } @@ -247,14 +247,14 @@ export function getTextEditsForAutoImportInsertion( textEditList.push({ range: { start: insertionPosition, end: insertionPosition }, - replacementText: newImportStatement + replacementText: newImportStatement, }); return textEditList; } function _processImportNode(node: ImportNode, localImports: ImportStatements, followsNonImportStatement: boolean) { - node.list.forEach(importAsNode => { + node.list.forEach((importAsNode) => { const importResult = AnalyzerNodeInfo.getImportInfo(importAsNode.module); let resolvedPath: string | undefined; @@ -268,7 +268,7 @@ function _processImportNode(node: ImportNode, localImports: ImportStatements, fo importResult, resolvedPath, moduleName: _formatModuleName(importAsNode.module), - followsNonImportStatement + followsNonImportStatement, }; localImports.orderedImports.push(localImport); @@ -302,7 +302,7 @@ function _processImportFromNode( importResult, resolvedPath, moduleName: _formatModuleName(node.module), - followsNonImportStatement + followsNonImportStatement, }; localImports.orderedImports.push(localImport); @@ -329,7 +329,7 @@ function _formatModuleName(node: ModuleNameNode): string { moduleName = moduleName + '.'; } - moduleName += node.nameParts.map(part => part.value).join('.'); + moduleName += node.nameParts.map((part) => part.value).join('.'); return moduleName; } diff --git a/server/src/analyzer/parseTreeUtils.ts b/server/src/analyzer/parseTreeUtils.ts index 2c010f5c7..258651e61 100644 --- a/server/src/analyzer/parseTreeUtils.ts +++ b/server/src/analyzer/parseTreeUtils.ts @@ -27,7 +27,7 @@ import { ParseNode, ParseNodeType, StatementNode, - SuiteNode + SuiteNode, } from '../parser/parseNodes'; import { KeywordType, OperatorType, StringTokenFlags } from '../parser/tokenizerTypes'; import { decodeDocString } from './docStringUtils'; @@ -37,7 +37,7 @@ export const enum PrintExpressionFlags { None = 0, // Don't use string literals for forward declarations. - ForwardDeclarations = 1 << 0 + ForwardDeclarations = 1 << 0, } export function getNodeDepth(node: ParseNode): number { @@ -104,7 +104,7 @@ export function printExpression(node: ExpressionNode, flags = PrintExpressionFla printExpression(node.leftExpression, flags) + '(' + node.arguments - .map(arg => { + .map((arg) => { let argStr = ''; if (arg.argumentCategory === ArgumentCategory.UnpackedList) { argStr = '*'; @@ -126,7 +126,7 @@ export function printExpression(node: ExpressionNode, flags = PrintExpressionFla return ( printExpression(node.baseExpression, flags) + '[' + - node.items.items.map(item => printExpression(item, flags)).join(', ') + + node.items.items.map((item) => printExpression(item, flags)).join(', ') + ']' ); } @@ -158,7 +158,7 @@ export function printExpression(node: ExpressionNode, flags = PrintExpressionFla return printExpression(node.typeAnnotation, flags); } else { return node.strings - .map(str => { + .map((str) => { return printExpression(str, flags); }) .join(' '); @@ -237,7 +237,7 @@ export function printExpression(node: ExpressionNode, flags = PrintExpressionFla } case ParseNodeType.List: { - const expressions = node.entries.map(expr => { + const expressions = node.entries.map((expr) => { return printExpression(expr, flags); }); return `[${expressions.join(', ')}]`; @@ -248,7 +248,7 @@ export function printExpression(node: ExpressionNode, flags = PrintExpressionFla } case ParseNodeType.Tuple: { - const expressions = node.expressions.map(expr => { + const expressions = node.expressions.map((expr) => { return printExpression(expr, flags); }); if (expressions.length === 1) { @@ -288,7 +288,7 @@ export function printExpression(node: ExpressionNode, flags = PrintExpressionFla listStr + ' ' + node.comprehensions - .map(expr => { + .map((expr) => { if (expr.nodeType === ParseNodeType.ListComprehensionFor) { return ( `${expr.isAsync ? 'async ' : ''}for ` + @@ -321,7 +321,7 @@ export function printExpression(node: ExpressionNode, flags = PrintExpressionFla return ( 'lambda ' + node.parameters - .map(param => { + .map((param) => { let paramStr = ''; if (param.category === ParameterCategory.VarArgList) { @@ -359,7 +359,7 @@ export function printExpression(node: ExpressionNode, flags = PrintExpressionFla } case ParseNodeType.Dictionary: { - return `{ ${node.entries.map(entry => { + return `{ ${node.entries.map((entry) => { if (entry.nodeType === ParseNodeType.DictionaryKeyEntry) { return ( `${printExpression(entry.keyExpression, flags)}: ` + @@ -376,7 +376,7 @@ export function printExpression(node: ExpressionNode, flags = PrintExpressionFla } case ParseNodeType.Set: { - return node.entries.map(entry => printExpression(entry, flags)).join(', '); + return node.entries.map((entry) => printExpression(entry, flags)).join(', '); } } @@ -425,7 +425,7 @@ export function printOperator(operator: OperatorType): string { [OperatorType.Is]: 'is', [OperatorType.IsNot]: 'is not', [OperatorType.In]: 'in', - [OperatorType.NotIn]: 'not in' + [OperatorType.NotIn]: 'not in', }; if (operatorMap[operator]) { @@ -554,7 +554,7 @@ export function getEvaluationScopeNode(node: ParseNode): EvaluationScopeNode { // the enclosing scope instead. switch (curNode.nodeType) { case ParseNodeType.Function: { - if (curNode.parameters.some(param => param === prevNode)) { + if (curNode.parameters.some((param) => param === prevNode)) { if (isParamNameNode) { return curNode; } @@ -737,7 +737,7 @@ export function isAssignmentToDefaultsFollowingNamedTuple(callNode: ParseNode): } const moduleOrSuite = statementList.parent; - let statementIndex = moduleOrSuite.statements.findIndex(s => s === statementList); + let statementIndex = moduleOrSuite.statements.findIndex((s) => s === statementList); if (statementIndex < 0) { return false; diff --git a/server/src/analyzer/parseTreeWalker.ts b/server/src/analyzer/parseTreeWalker.ts index cbf32af6d..720fa26f7 100644 --- a/server/src/analyzer/parseTreeWalker.ts +++ b/server/src/analyzer/parseTreeWalker.ts @@ -74,7 +74,7 @@ import { WithItemNode, WithNode, YieldFromNode, - YieldNode + YieldNode, } from '../parser/parseNodes'; // To use this class, create a subclass and override the @@ -88,7 +88,7 @@ export class ParseTreeWalker { } walkMultiple(nodes: ParseNodeArray) { - nodes.forEach(node => { + nodes.forEach((node) => { if (node) { this.walk(node); } diff --git a/server/src/analyzer/program.ts b/server/src/analyzer/program.ts index 0d711781d..b585d5fa5 100644 --- a/server/src/analyzer/program.ts +++ b/server/src/analyzer/program.ts @@ -13,7 +13,7 @@ import { CompletionItem, CompletionList, DocumentSymbol, - SymbolInformation + SymbolInformation, } from 'vscode-languageserver'; import { throwIfCancellationRequested } from '../common/cancellationUtils'; @@ -30,7 +30,7 @@ import { getRelativePath, makeDirectories, normalizePath, - stripFileExtension + stripFileExtension, } from '../common/pathUtils'; import { DocumentRange, doRangesOverlap, Position, Range } from '../common/textRange'; import { Duration, timingStats } from '../common/timing'; @@ -119,13 +119,13 @@ export class Program { if (this._sourceFileList.length > 0) { // We need to determine which files to remove from the existing file list. const newFileMap = new Map(); - filePaths.forEach(path => { + filePaths.forEach((path) => { newFileMap.set(path, path); }); // Files that are not in the tracked file list are // marked as no longer tracked. - this._sourceFileList.forEach(oldFile => { + this._sourceFileList.forEach((oldFile) => { const filePath = oldFile.sourceFile.getFilePath(); if (!newFileMap.has(filePath)) { oldFile.isTracked = false; @@ -155,7 +155,7 @@ export class Program { getFilesToAnalyzeCount() { let sourceFileCount = 0; - this._sourceFileList.forEach(fileInfo => { + this._sourceFileList.forEach((fileInfo) => { if ( fileInfo.sourceFile.isParseRequired() || fileInfo.sourceFile.isBindingRequired() || @@ -175,7 +175,7 @@ export class Program { } addTrackedFiles(filePaths: string[]) { - filePaths.forEach(filePath => { + filePaths.forEach((filePath) => { this.addTrackedFile(filePath); }); } @@ -196,7 +196,7 @@ export class Program { isThirdPartyImport: false, diagnosticsVersion: sourceFile.getDiagnosticVersion(), imports: [], - importedBy: [] + importedBy: [], }; this._addToSourceFileListAndMap(sourceFileInfo); return sourceFile; @@ -214,7 +214,7 @@ export class Program { isThirdPartyImport: false, diagnosticsVersion: sourceFile.getDiagnosticVersion(), imports: [], - importedBy: [] + importedBy: [], }; this._addToSourceFileListAndMap(sourceFileInfo); } else { @@ -251,7 +251,7 @@ export class Program { markAllFilesDirty(evenIfContentsAreSame: boolean) { const markDirtyMap = new Map(); - this._sourceFileList.forEach(sourceFileInfo => { + this._sourceFileList.forEach((sourceFileInfo) => { if (evenIfContentsAreSame) { sourceFileInfo.sourceFile.markDirty(); } else if (sourceFileInfo.sourceFile.didContentsChangeOnDisk()) { @@ -270,7 +270,7 @@ export class Program { markFilesDirty(filePaths: string[]) { const markDirtyMap = new Map(); - filePaths.forEach(filePath => { + filePaths.forEach((filePath) => { const sourceFileInfo = this._sourceFileMap.get(filePath); if (sourceFileInfo) { sourceFileInfo.sourceFile.markDirty(); @@ -309,7 +309,7 @@ export class Program { const elapsedTime = new Duration(); const openFiles = this._sourceFileList.filter( - sf => sf.isOpenByClient && sf.sourceFile.isCheckingRequired() + (sf) => sf.isOpenByClient && sf.sourceFile.isCheckingRequired() ); if (openFiles.length > 0) { @@ -359,14 +359,14 @@ export class Program { // the program, skipping any typeshed files. printDependencies(projectRootDir: string, verbose: boolean) { const sortedFiles = this._sourceFileList - .filter(s => !s.isTypeshedFile) + .filter((s) => !s.isTypeshedFile) .sort((a, b) => { return a.sourceFile.getFilePath() < b.sourceFile.getFilePath() ? 1 : -1; }); const zeroImportFiles: SourceFile[] = []; - sortedFiles.forEach(sfInfo => { + sortedFiles.forEach((sfInfo) => { this._console.log(''); let filePath = sfInfo.sourceFile.getFilePath(); const relPath = getRelativePath(filePath, projectRootDir); @@ -380,7 +380,7 @@ export class Program { ` Imports ${sfInfo.imports.length} ` + `file${sfInfo.imports.length === 1 ? '' : 's'}` ); if (verbose) { - sfInfo.imports.forEach(importInfo => { + sfInfo.imports.forEach((importInfo) => { this._console.log(` ${importInfo.sourceFile.getFilePath()}`); }); } @@ -389,7 +389,7 @@ export class Program { ` Imported by ${sfInfo.importedBy.length} ` + `file${sfInfo.importedBy.length === 1 ? '' : 's'}` ); if (verbose) { - sfInfo.importedBy.forEach(importInfo => { + sfInfo.importedBy.forEach((importInfo) => { this._console.log(` ${importInfo.sourceFile.getFilePath()}`); }); } @@ -404,7 +404,7 @@ export class Program { this._console.log( `${zeroImportFiles.length} file${zeroImportFiles.length === 1 ? '' : 's'}` + ` not explicitly imported` ); - zeroImportFiles.forEach(importFile => { + zeroImportFiles.forEach((importFile) => { this._console.log(` ${importFile.getFilePath()}`); }); } @@ -533,7 +533,7 @@ export class Program { return { symbolTable, - docString + docString, }; }; @@ -542,7 +542,7 @@ export class Program { private _buildModuleSymbolsMap(sourceFileToExclude?: SourceFileInfo): ModuleSymbolMap { const moduleSymbolMap = new Map(); - this._sourceFileList.forEach(fileInfo => { + this._sourceFileList.forEach((fileInfo) => { if (fileInfo !== sourceFileToExclude) { const symbolTable = fileInfo.sourceFile.getModuleSymbolTable(); if (symbolTable) { @@ -601,7 +601,7 @@ export class Program { const closureMap = new Map(); this._getImportsRecursive(fileToCheck, closureMap, 0); - closureMap.forEach(file => { + closureMap.forEach((file) => { timingStats.cycleDetectionTime.timeOperation(() => { this._detectAndReportImportCycles(file); }); @@ -689,7 +689,7 @@ export class Program { private _logImportCycle(dependencyChain: SourceFileInfo[]) { const circDep = new CircularDependency(); - dependencyChain.forEach(sourceFileInfo => { + dependencyChain.forEach((sourceFileInfo) => { circDep.appendPath(sourceFileInfo.sourceFile.getFilePath()); }); @@ -708,7 +708,7 @@ export class Program { sourceFileInfo.sourceFile.markReanalysisRequired(); markMap.set(filePath, true); - sourceFileInfo.importedBy.forEach(dep => { + sourceFileInfo.importedBy.forEach((dep) => { this._markFileDirtyRecursive(dep, markMap); }); } @@ -717,7 +717,7 @@ export class Program { getDiagnostics(options: ConfigOptions): FileDiagnostics[] { const fileDiagnostics: FileDiagnostics[] = this._removeUnneededFiles(); - this._sourceFileList.forEach(sourceFileInfo => { + this._sourceFileList.forEach((sourceFileInfo) => { if (sourceFileInfo.isOpenByClient || (!options.checkOnlyOpenFiles && !sourceFileInfo.isThirdPartyImport)) { const diagnostics = sourceFileInfo.sourceFile.getDiagnostics( options, @@ -726,7 +726,7 @@ export class Program { if (diagnostics !== undefined) { fileDiagnostics.push({ filePath: sourceFileInfo.sourceFile.getFilePath(), - diagnostics + diagnostics, }); // Update the cached diagnosticsVersion so we can determine @@ -750,7 +750,7 @@ export class Program { return []; } - return unfilteredDiagnostics.filter(diag => { + return unfilteredDiagnostics.filter((diag) => { return doRangesOverlap(diag.range, range); }); } @@ -977,11 +977,11 @@ export class Program { const editActions: FileEditAction[] = []; - referencesResult.locations.forEach(loc => { + referencesResult.locations.forEach((loc) => { editActions.push({ filePath: loc.path, range: loc.range, - replacementText: newName + replacementText: newName, }); }); @@ -1037,7 +1037,7 @@ export class Program { if (!this._isFileNeeded(fileInfo)) { fileDiagnostics.push({ filePath: fileInfo.sourceFile.getFilePath(), - diagnostics: [] + diagnostics: [], }); fileInfo.sourceFile.prepareForClose(); @@ -1046,8 +1046,8 @@ export class Program { // Unlink any imports and remove them from the list if // they are no longer referenced. - fileInfo.imports.forEach(importedFile => { - const indexToRemove = importedFile.importedBy.findIndex(fi => fi === fileInfo); + fileInfo.imports.forEach((importedFile) => { + const indexToRemove = importedFile.importedBy.findIndex((fi) => fi === fileInfo); assert(indexToRemove >= 0); importedFile.importedBy.splice(indexToRemove, 1); @@ -1055,11 +1055,11 @@ export class Program { // is no longer needed. If its index is >= i, it will be // removed when we get to it. if (!this._isFileNeeded(importedFile)) { - const indexToRemove = this._sourceFileList.findIndex(fi => fi === importedFile); + const indexToRemove = this._sourceFileList.findIndex((fi) => fi === importedFile); if (indexToRemove >= 0 && indexToRemove < i) { fileDiagnostics.push({ filePath: importedFile.sourceFile.getFilePath(), - diagnostics: [] + diagnostics: [], }); importedFile.sourceFile.prepareForClose(); @@ -1079,7 +1079,7 @@ export class Program { ) { fileDiagnostics.push({ filePath: fileInfo.sourceFile.getFilePath(), - diagnostics: [] + diagnostics: [], }); fileInfo.diagnosticsVersion = fileInfo.sourceFile.getDiagnosticVersion(); @@ -1188,7 +1188,7 @@ export class Program { // Create a map of unique imports, since imports can appear more than once. const newImportPathMap = new Map(); - imports.forEach(importResult => { + imports.forEach((importResult) => { if (importResult.isImportFound) { if (this._isImportAllowed(sourceFileInfo, importResult, importResult.isStubFile)) { if (importResult.resolvedPaths.length > 0) { @@ -1198,19 +1198,19 @@ export class Program { isTypeshedFile: !!importResult.isTypeshedFile, isThirdPartyImport: importResult.importType === ImportType.ThirdParty || - (sourceFileInfo.isThirdPartyImport && importResult.importType === ImportType.Local) + (sourceFileInfo.isThirdPartyImport && importResult.importType === ImportType.Local), }); } } } - importResult.implicitImports.forEach(implicitImport => { + importResult.implicitImports.forEach((implicitImport) => { if (this._isImportAllowed(sourceFileInfo, importResult, implicitImport.isStubFile)) { newImportPathMap.set(implicitImport.path, { isTypeshedFile: !!importResult.isTypeshedFile, isThirdPartyImport: importResult.importType === ImportType.ThirdParty || - (sourceFileInfo.isThirdPartyImport && importResult.importType === ImportType.Local) + (sourceFileInfo.isThirdPartyImport && importResult.importType === ImportType.Local), }); } }); @@ -1221,7 +1221,7 @@ export class Program { `in file '${sourceFileInfo.sourceFile.getFilePath()}'` ); if (importResult.importFailureInfo) { - importResult.importFailureInfo.forEach(diag => { + importResult.importFailureInfo.forEach((diag) => { this._console.log(` ${diag}`); }); } @@ -1230,13 +1230,13 @@ export class Program { }); const updatedImportMap = new Map(); - sourceFileInfo.imports.forEach(importInfo => { + sourceFileInfo.imports.forEach((importInfo) => { const oldFilePath = importInfo.sourceFile.getFilePath(); // A previous import was removed. if (!newImportPathMap.has(oldFilePath)) { importInfo.importedBy = importInfo.importedBy.filter( - fi => fi.sourceFile.getFilePath() !== sourceFileInfo.sourceFile.getFilePath() + (fi) => fi.sourceFile.getFilePath() !== sourceFileInfo.sourceFile.getFilePath() ); } else { updatedImportMap.set(oldFilePath, importInfo); @@ -1267,7 +1267,7 @@ export class Program { isThirdPartyImport: importInfo.isThirdPartyImport, diagnosticsVersion: sourceFile.getDiagnosticVersion(), imports: [], - importedBy: [] + importedBy: [], }; this._addToSourceFileListAndMap(importedFileInfo); diff --git a/server/src/analyzer/pythonPathUtils.ts b/server/src/analyzer/pythonPathUtils.ts index a2c87a50c..80eb2203c 100644 --- a/server/src/analyzer/pythonPathUtils.ts +++ b/server/src/analyzer/pythonPathUtils.ts @@ -19,7 +19,7 @@ import { getDirectoryPath, getFileSystemEntries, isDirectory, - normalizePath + normalizePath, } from '../common/pathUtils'; const cachedSearchPaths = new Map(); @@ -120,7 +120,7 @@ export function findPythonSearchPaths( const pathResult = getPythonPathFromPythonInterpreter(fs, configOptions.pythonPath, importFailureInfo); if (includeWatchPathsOnly && workspaceRoot) { const paths = pathResult.paths.filter( - p => !containsPath(workspaceRoot, p, true) || containsPath(pathResult.prefix, p, true) + (p) => !containsPath(workspaceRoot, p, true) || containsPath(pathResult.prefix, p, true) ); return paths; @@ -149,7 +149,7 @@ export function getPythonPathFromPythonInterpreter( const result: PythonPathResult = { paths: [], - prefix: '' + prefix: '', }; try { @@ -163,7 +163,7 @@ export function getPythonPathFromPythonInterpreter( const commandLineArgs: string[] = [ '-c', - 'import sys, json; json.dump(dict(path=sys.path, prefix=sys.prefix), sys.stdout)' + 'import sys, json; json.dump(dict(path=sys.path, prefix=sys.prefix), sys.stdout)', ]; let execOutput: string; @@ -208,7 +208,7 @@ export function getPythonPathFromPythonInterpreter( cachedSearchPaths.set(searchKey, result); importFailureInfo.push(`Received ${result.paths.length} paths from interpreter`); - result.paths.forEach(path => { + result.paths.forEach((path) => { importFailureInfo.push(` ${path}`); }); return result; diff --git a/server/src/analyzer/scope.ts b/server/src/analyzer/scope.ts index 53adc5acb..e8a2dbc90 100644 --- a/server/src/analyzer/scope.ts +++ b/server/src/analyzer/scope.ts @@ -27,7 +27,7 @@ export const enum ScopeType { // Built-in scopes are used for all ambient symbols provided // by the Python environment. - Builtin + Builtin, } // Provides information for recursive scope lookups. @@ -121,7 +121,7 @@ export class Scope { symbol, isOutsideCallerModule, isBeyondExecutionScope, - scope: this + scope: this, }; } diff --git a/server/src/analyzer/service.ts b/server/src/analyzer/service.ts index bb6a24006..062383324 100644 --- a/server/src/analyzer/service.ts +++ b/server/src/analyzer/service.ts @@ -13,7 +13,7 @@ import { CompletionItem, CompletionList, DocumentSymbol, - SymbolInformation + SymbolInformation, } from 'vscode-languageserver'; import { getGlobalCancellationToken, OperationCanceledException } from '../common/cancellationUtils'; @@ -36,7 +36,7 @@ import { getFileSystemEntries, isDirectory, normalizePath, - stripFileExtension + stripFileExtension, } from '../common/pathUtils'; import { DocumentRange, Position, Range } from '../common/textRange'; import { Duration, timingStats } from '../common/timing'; @@ -340,7 +340,7 @@ export class AnalyzerService { const defaultExcludes = ['**/node_modules', '**/__pycache__', '.git']; if (commandLineOptions.fileSpecs.length > 0) { - commandLineOptions.fileSpecs.forEach(fileSpec => { + commandLineOptions.fileSpecs.forEach((fileSpec) => { configOptions.include.push(getFileSpec(projectRoot, fileSpec)); }); } else if (!configFilePath) { @@ -351,7 +351,7 @@ export class AnalyzerService { configOptions.include.push(getFileSpec(commandLineOptions.executionRoot, '.')); // Add a few common excludes to avoid long scan times. - defaultExcludes.forEach(exclude => { + defaultExcludes.forEach((exclude) => { configOptions.exclude.push(getFileSpec(commandLineOptions.executionRoot, exclude)); }); } @@ -377,7 +377,7 @@ export class AnalyzerService { // If there was no explicit set of excludes, add a few common ones to avoid long scan times. if (configOptions.exclude.length === 0) { - defaultExcludes.forEach(exclude => { + defaultExcludes.forEach((exclude) => { this._console.log(`Auto-excluding ${exclude}`); configOptions.exclude.push(getFileSpec(configFileDir, exclude)); }); @@ -477,7 +477,7 @@ export class AnalyzerService { ); if (configOptions.verboseOutput) { - importFailureInfo.forEach(diag => { + importFailureInfo.forEach((diag) => { this._console.log(` ${diag}`); }); } @@ -498,7 +498,7 @@ export class AnalyzerService { } else { if (configOptions.verboseOutput) { this._console.log(`Search paths found for configured python interpreter:`); - pythonPaths.forEach(path => { + pythonPaths.forEach((path) => { this._console.log(` ${path}`); }); } @@ -507,7 +507,7 @@ export class AnalyzerService { if (configOptions.verboseOutput) { if (importFailureInfo.length > 0) { this._console.log(`When attempting to get search paths from python interpreter:`); - importFailureInfo.forEach(diag => { + importFailureInfo.forEach((diag) => { this._console.log(` ${diag}`); }); } @@ -515,7 +515,7 @@ export class AnalyzerService { } // Is there a reference to a venv? If so, there needs to be a valid venvPath. - if (configOptions.defaultVenv || configOptions.executionEnvironments.find(e => !!e.venv)) { + if (configOptions.defaultVenv || configOptions.executionEnvironments.find((e) => !!e.venv)) { if (!configOptions.venvPath) { this._console.log(`venvPath not specified, so venv settings will be ignored.`); } @@ -619,7 +619,7 @@ export class AnalyzerService { } private _findConfigFileHereOrUp(searchPath: string): string | undefined { - return forEachAncestorDirectory(searchPath, ancestor => this._findConfigFile(ancestor)); + return forEachAncestorDirectory(searchPath, (ancestor) => this._findConfigFile(ancestor)); } private _findConfigFile(searchPath: string): string | undefined { @@ -700,7 +700,7 @@ export class AnalyzerService { const moduleDescriptor: ImportedModuleDescriptor = { leadingDots: 0, nameParts: this._typeStubTargetImportName.split('.'), - importedSymbols: [] + importedSymbols: [], }; const importResult = this._importResolver.resolveImport('', execEnv, moduleDescriptor); @@ -740,7 +740,7 @@ export class AnalyzerService { } // Add the implicit import paths. - importResult.implicitImports.forEach(implicitImport => { + importResult.implicitImports.forEach((implicitImport) => { filesToImport.push(implicitImport.path); }); @@ -769,7 +769,7 @@ export class AnalyzerService { } private _isInExcludePath(path: string, excludePaths: FileSpec[]) { - return !!excludePaths.find(excl => excl.regExp.test(path)); + return !!excludePaths.find((excl) => excl.regExp.test(path)); } private _matchFiles(include: FileSpec[], exclude: FileSpec[]): string[] { @@ -779,7 +779,7 @@ export class AnalyzerService { const visitDirectory = (absolutePath: string, includeRegExp: RegExp) => { if (this._configOptions.autoExcludeVenv) { - if (envMarkers.some(f => this._fs.existsSync(combinePaths(absolutePath, ...f)))) { + if (envMarkers.some((f) => this._fs.existsSync(combinePaths(absolutePath, ...f)))) { this._console.log(`Auto-excluding ${absolutePath}`); return; } @@ -807,7 +807,7 @@ export class AnalyzerService { } }; - include.forEach(includeSpec => { + include.forEach((includeSpec) => { let foundFileSpec = false; if (!this._isInExcludePath(includeSpec.wildcardRoot, exclude)) { @@ -855,7 +855,7 @@ export class AnalyzerService { } if (this._configOptions.include.length > 0) { - const fileList = this._configOptions.include.map(spec => { + const fileList = this._configOptions.include.map((spec) => { return combinePaths(this._executionRootPath, spec.wildcardRoot); }); @@ -967,7 +967,7 @@ export class AnalyzerService { this._removeConfigFileWatcher(); if (this._configFilePath) { - this._configFileWatcher = this._fs.createFileSystemWatcher([this._configFilePath], event => { + this._configFileWatcher = this._fs.createFileSystemWatcher([this._configFilePath], (event) => { if (this._verboseOutput) { this._console.log(`Received fs event '${event}' for config file`); } @@ -1105,7 +1105,7 @@ export class AnalyzerService { checkingOnlyOpenFiles: this._program.isCheckingOnlyOpenFiles(), fatalErrorOccurred: false, configParseErrorOccurred: false, - elapsedTime: duration.getDurationInSeconds() + elapsedTime: duration.getDurationInSeconds(), }; const diagnosticFileCount = results.diagnostics.length; @@ -1135,7 +1135,7 @@ export class AnalyzerService { checkingOnlyOpenFiles: true, fatalErrorOccurred: true, configParseErrorOccurred: false, - elapsedTime: 0 + elapsedTime: 0, }); } } @@ -1153,7 +1153,7 @@ export class AnalyzerService { checkingOnlyOpenFiles: this._program.isCheckingOnlyOpenFiles(), fatalErrorOccurred: false, configParseErrorOccurred: false, - elapsedTime: 0 + elapsedTime: 0, }); } } @@ -1168,7 +1168,7 @@ export class AnalyzerService { checkingOnlyOpenFiles: true, fatalErrorOccurred: false, configParseErrorOccurred: true, - elapsedTime: 0 + elapsedTime: 0, }); } } diff --git a/server/src/analyzer/sourceFile.ts b/server/src/analyzer/sourceFile.ts index 6bb668b9d..5200b4485 100644 --- a/server/src/analyzer/sourceFile.ts +++ b/server/src/analyzer/sourceFile.ts @@ -12,7 +12,7 @@ import { CompletionItem, CompletionList, DocumentSymbol, - SymbolInformation + SymbolInformation, } from 'vscode-languageserver'; import { OperationCanceledException } from '../common/cancellationUtils'; @@ -213,7 +213,7 @@ export class SourceFile { if (options.diagnosticSettings.enableTypeIgnoreComments) { const typeIgnoreLines = this._parseResults ? this._parseResults.tokenizerOutput.typeIgnoreLines : {}; if (Object.keys(typeIgnoreLines).length > 0) { - diagList = diagList.filter(d => { + diagList = diagList.filter((d) => { for (let line = d.range.start.line; line <= d.range.end.line; line++) { if (typeIgnoreLines[line]) { return false; @@ -231,14 +231,14 @@ export class SourceFile { ? DiagnosticCategory.Warning : DiagnosticCategory.Error; - this._circularDependencies.forEach(cirDep => { + this._circularDependencies.forEach((cirDep) => { diagList.push( new Diagnostic( category, 'Cycle detected in import chain\n' + cirDep .getPaths() - .map(path => ' ' + path) + .map((path) => ' ' + path) .join('\n'), getEmptyRange() ) @@ -261,7 +261,7 @@ export class SourceFile { includeWarningsAndErrors = false; } else if (options.diagnosticSettings.reportTypeshedErrors === 'warning') { // Convert all the errors to warnings. - diagList = diagList.map(diag => { + diagList = diagList.map((diag) => { if (diag.category === DiagnosticCategory.Error) { return new Diagnostic(DiagnosticCategory.Warning, diag.message, diag.range); } @@ -271,7 +271,7 @@ export class SourceFile { } // If the file is in the ignore list, clear the diagnostic list. - if (options.ignore.find(ignoreFileSpec => ignoreFileSpec.regExp.test(this._filePath))) { + if (options.ignore.find((ignoreFileSpec) => ignoreFileSpec.regExp.test(this._filePath))) { diagList = []; } @@ -287,7 +287,7 @@ export class SourceFile { // the errors and warnings, leaving only the unreachable code // diagnostics. if (!includeWarningsAndErrors) { - diagList = diagList.filter(diag => diag.category === DiagnosticCategory.UnusedCode); + diagList = diagList.filter((diag) => diag.category === DiagnosticCategory.UnusedCode); } return diagList; @@ -428,7 +428,7 @@ export class SourceFile { // Some topologies can result in a massive number of cycles. We'll cut it off. if (this._circularDependencies.length < _maxImportCyclesPerFile) { - if (!this._circularDependencies.some(dep => dep.isEqual(circDependency))) { + if (!this._circularDependencies.some((dep) => dep.isEqual(circDependency))) { this._circularDependencies.push(circDependency); updatedDependencyList = true; } @@ -497,14 +497,14 @@ export class SourceFile { this._imports, this._builtinsImport, this._typingModulePath, - this._collectionsModulePath + this._collectionsModulePath, ] = this._resolveImports(importResolver, parseResults.importedModules, execEnvironment); this._parseDiagnostics = diagSink.fetchAndClear(); }); // Is this file in a "strict" path? const useStrict = - configOptions.strict.find(strictFileSpec => strictFileSpec.regExp.test(this._filePath)) !== undefined; + configOptions.strict.find((strictFileSpec) => strictFileSpec.regExp.test(this._filePath)) !== undefined; this._diagnosticSettings = CommentUtils.getFileLevelDirectives( this._parseResults.tokenizerOutput.tokens, @@ -531,9 +531,9 @@ export class SourceFile { typeIgnoreLines: {}, predominantEndOfLineSequence: '\n', predominantTabSequence: ' ', - predominantSingleQuoteCharacter: "'" + predominantSingleQuoteCharacter: "'", }, - containsWildcardImport: false + containsWildcardImport: false, }; this._imports = undefined; this._builtinsImport = undefined; @@ -886,7 +886,7 @@ export class SourceFile { isStubFile: this._isStubFile, isTypingStubFile: this._isTypingStubFile, isBuiltInStubFile: this._isBuiltInStubFile, - accessedSymbolMap: new Map() + accessedSymbolMap: new Map(), }; return fileInfo; } @@ -912,7 +912,7 @@ export class SourceFile { let builtinsImportResult: ImportResult | undefined = importResolver.resolveImport(this._filePath, execEnv, { leadingDots: 0, nameParts: ['builtins'], - importedSymbols: undefined + importedSymbols: undefined, }); // Avoid importing builtins from the builtins.pyi file itself. @@ -929,7 +929,7 @@ export class SourceFile { const typingImportResult: ImportResult | undefined = importResolver.resolveImport(this._filePath, execEnv, { leadingDots: 0, nameParts: ['typing'], - importedSymbols: undefined + importedSymbols: undefined, }); // Avoid importing typing from the typing.pyi file itself. @@ -948,7 +948,7 @@ export class SourceFile { const importResult = importResolver.resolveImport(this._filePath, execEnv, { leadingDots: moduleImport.leadingDots, nameParts: moduleImport.nameParts, - importedSymbols: moduleImport.importedSymbols + importedSymbols: moduleImport.importedSymbols, }); // If the file imports the stdlib 'collections' module, stash diff --git a/server/src/analyzer/staticExpressions.ts b/server/src/analyzer/staticExpressions.ts index c84feb26e..d830d6c95 100644 --- a/server/src/analyzer/staticExpressions.ts +++ b/server/src/analyzer/staticExpressions.ts @@ -63,7 +63,7 @@ export function evaluateStaticBoolExpression(node: ExpressionNode, execEnv: Exec node.rightExpression.nodeType === ParseNodeType.StringList ) { // Handle the special case of "sys.platform != 'X'" - const comparisonPlatform = node.rightExpression.strings.map(s => s.value).join(''); + const comparisonPlatform = node.rightExpression.strings.map((s) => s.value).join(''); const expectedPlatformName = _getExpectedPlatformNameFromPlatform(execEnv); return _evaluateStringBinaryOperation(node.operator, expectedPlatformName || '', comparisonPlatform); } else if ( @@ -71,7 +71,7 @@ export function evaluateStaticBoolExpression(node: ExpressionNode, execEnv: Exec node.rightExpression.nodeType === ParseNodeType.StringList ) { // Handle the special case of "os.name == 'X'" - const comparisonOsName = node.rightExpression.strings.map(s => s.value).join(''); + const comparisonOsName = node.rightExpression.strings.map((s) => s.value).join(''); const expectedOsName = _getExpectedOsNameFromPlatform(execEnv); if (expectedOsName !== undefined) { return _evaluateStringBinaryOperation(node.operator, expectedOsName, comparisonOsName); diff --git a/server/src/analyzer/symbol.ts b/server/src/analyzer/symbol.ts index 215916e1f..daac5c6c5 100644 --- a/server/src/analyzer/symbol.ts +++ b/server/src/analyzer/symbol.ts @@ -40,7 +40,7 @@ export const enum SymbolFlags { // Indicates that the symbol is not considered for protocol // matching. This applies to some built-in symbols like __class__. - IgnoredForProtocolMatch = 1 << 5 + IgnoredForProtocolMatch = 1 << 5, } let nextSymbolId = 1; @@ -129,7 +129,7 @@ export class Symbol { // See if this node was already identified as a declaration. If so, // replace it. Otherwise, add it as a new declaration to the end of // the list. - const declIndex = this._declarations.findIndex(decl => areDeclarationsSame(decl, declaration)); + const declIndex = this._declarations.findIndex((decl) => areDeclarationsSame(decl, declaration)); if (declIndex < 0) { this._declarations.push(declaration); } else { @@ -177,11 +177,11 @@ export class Symbol { return true; } - return this.getDeclarations().some(decl => hasTypeForDeclaration(decl)); + return this.getDeclarations().some((decl) => hasTypeForDeclaration(decl)); } getTypedDeclarations() { - return this.getDeclarations().filter(decl => hasTypeForDeclaration(decl)); + return this.getDeclarations().filter((decl) => hasTypeForDeclaration(decl)); } getSynthesizedType() { diff --git a/server/src/analyzer/symbolUtils.ts b/server/src/analyzer/symbolUtils.ts index 11eb268d5..973a664a7 100644 --- a/server/src/analyzer/symbolUtils.ts +++ b/server/src/analyzer/symbolUtils.ts @@ -37,5 +37,5 @@ export function isTypedDictMemberAccessedThroughIndex(symbol: Symbol): boolean { } export function isFinalVariable(symbol: Symbol): boolean { - return symbol.getDeclarations().some(decl => isFinalVariableDeclaration(decl)); + return symbol.getDeclarations().some((decl) => isFinalVariableDeclaration(decl)); } diff --git a/server/src/analyzer/testWalker.ts b/server/src/analyzer/testWalker.ts index d4068d3af..01903492e 100644 --- a/server/src/analyzer/testWalker.ts +++ b/server/src/analyzer/testWalker.ts @@ -24,7 +24,7 @@ export class TestWalker extends ParseTreeWalker { // Make sure that all of the children point to their parent. private _verifyParentChildLinks(node: ParseNode, children: ParseNodeArray) { - children.forEach(child => { + children.forEach((child) => { if (child) { if (child.parent !== node) { fail( @@ -42,7 +42,7 @@ export class TestWalker extends ParseTreeWalker { private _verifyChildRanges(node: ParseNode, children: ParseNodeArray) { let prevNode: ParseNode | undefined; - children.forEach(child => { + children.forEach((child) => { if (child) { let skipCheck = false; diff --git a/server/src/analyzer/typeCache.ts b/server/src/analyzer/typeCache.ts index f108d8695..14b0ee186 100644 --- a/server/src/analyzer/typeCache.ts +++ b/server/src/analyzer/typeCache.ts @@ -58,7 +58,7 @@ export class SpeculativeTypeTracker { // Delete all of the speculative type cache entries // that were tracked in this context. - context!.entriesToUndo.forEach(entry => { + context!.entriesToUndo.forEach((entry) => { entry.cache.delete(entry.id); }); } @@ -83,7 +83,7 @@ export class SpeculativeTypeTracker { if (stackSize > 0) { this._speculativeContextStack[stackSize - 1].entriesToUndo.push({ cache, - id + id, }); } } diff --git a/server/src/analyzer/typeEvaluator.ts b/server/src/analyzer/typeEvaluator.ts index d69ae5499..e5e47f1ec 100644 --- a/server/src/analyzer/typeEvaluator.ts +++ b/server/src/analyzer/typeEvaluator.ts @@ -65,7 +65,7 @@ import { UnaryOperationNode, WithItemNode, YieldFromNode, - YieldNode + YieldNode, } from '../parser/parseNodes'; import { ParseOptions, Parser } from '../parser/parser'; import { KeywordType, OperatorType, StringTokenFlags, Token, TokenType } from '../parser/tokenizerTypes'; @@ -83,7 +83,7 @@ import { FlowPostFinally, FlowPreFinallyGate, FlowWildcardImport, - isCodeFlowSupportedForReference + isCodeFlowSupportedForReference, } from './codeFlow'; import { AliasDeclaration, @@ -91,7 +91,7 @@ import { DeclarationType, FunctionDeclaration, ModuleLoaderActions, - VariableDeclaration + VariableDeclaration, } from './declaration'; import * as ParseTreeUtils from './parseTreeUtils'; import { ScopeType } from './scope'; @@ -131,7 +131,7 @@ import { TypeSourceId, TypeVarType, UnboundType, - UnknownType + UnknownType, } from './types'; import { addDefaultFunctionParameters, @@ -174,7 +174,7 @@ import { stripLiteralTypeArgsValue, stripLiteralValue, transformTypeObjectToClass, - TypedDictEntry + TypedDictEntry, } from './typeUtils'; import { TypeVarMap } from './typeVarMap'; @@ -242,7 +242,7 @@ export const enum EvaluatorFlags { EvaluateStringLiteralAsType = 16, // 'Final' is not allowed in this context - FinalDisallowed = 32 + FinalDisallowed = 32, } interface EvaluatorUsage { @@ -285,7 +285,7 @@ export const enum MemberAccessFlags { SkipGetCheck = 1 << 4, // This set of flags is appropriate for looking up methods. - SkipForMethodLookup = SkipInstanceMembers | SkipGetAttributeCheck | SkipGetCheck + SkipForMethodLookup = SkipInstanceMembers | SkipGetAttributeCheck | SkipGetCheck, } interface ParamAssignmentInfo { @@ -303,7 +303,7 @@ const arithmeticOperatorMap: { [operator: number]: [string, string] } = { [OperatorType.Divide]: ['__truediv__', '__rtruediv__'], [OperatorType.Mod]: ['__mod__', '__rmod__'], [OperatorType.Power]: ['__pow__', '__rpow__'], - [OperatorType.MatrixMultiply]: ['__matmul__', ''] + [OperatorType.MatrixMultiply]: ['__matmul__', ''], }; const bitwiseOperatorMap: { [operator: number]: [string, string] } = { @@ -311,7 +311,7 @@ const bitwiseOperatorMap: { [operator: number]: [string, string] } = { [OperatorType.BitwiseOr]: ['__or__', '__ror__'], [OperatorType.BitwiseXor]: ['__xor__', '__rxor__'], [OperatorType.LeftShift]: ['__lshift__', '__rlshift__'], - [OperatorType.RightShift]: ['__rshift__', '__rrshift__'] + [OperatorType.RightShift]: ['__rshift__', '__rrshift__'], }; const comparisonOperatorMap: { [operator: number]: [string, string] } = { @@ -320,7 +320,7 @@ const comparisonOperatorMap: { [operator: number]: [string, string] } = { [OperatorType.LessThan]: ['__lt__', '__gt__'], [OperatorType.LessThanOrEqual]: ['__le__', '__ge__'], [OperatorType.GreaterThan]: ['__gt__', '__lt__'], - [OperatorType.GreaterThanOrEqual]: ['__ge__', '__le__'] + [OperatorType.GreaterThanOrEqual]: ['__ge__', '__le__'], }; const booleanOperatorMap: { [operator: number]: boolean } = { @@ -329,7 +329,7 @@ const booleanOperatorMap: { [operator: number]: boolean } = { [OperatorType.Is]: true, [OperatorType.IsNot]: true, [OperatorType.In]: true, - [OperatorType.NotIn]: true + [OperatorType.NotIn]: true, }; export interface ClassTypeResult { @@ -573,7 +573,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { function getIndexOfSymbolResolution(symbol: Symbol, declaration: Declaration) { return symbolResolutionStack.findIndex( - entry => entry.symbolId === symbol.id && entry.declaration === declaration + (entry) => entry.symbolId === symbol.id && entry.declaration === declaration ); } @@ -590,7 +590,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { symbolResolutionStack.push({ symbolId: symbol.id, declaration, - isResultValid: true + isResultValid: true, }); return true; } @@ -719,9 +719,9 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { } } else { // Evaluate the format string expressions in this context. - node.strings.forEach(str => { + node.strings.forEach((str) => { if (str.nodeType === ParseNodeType.FormatString) { - str.expressions.forEach(expr => { + str.expressions.forEach((expr) => { getTypeOfExpression(expr); }); } @@ -730,10 +730,10 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { const isBytes = (node.strings[0].token.flags & StringTokenFlags.Bytes) !== 0; // Don't create a literal type if it's an f-string. - if (node.strings.some(str => str.nodeType === ParseNodeType.FormatString)) { + if (node.strings.some((str) => str.nodeType === ParseNodeType.FormatString)) { typeResult = { node, - type: getBuiltInObject(node, isBytes ? 'bytes' : 'str') + type: getBuiltInObject(node, isBytes ? 'bytes' : 'str'), }; } else { typeResult = { @@ -741,8 +741,8 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { type: cloneBuiltinTypeWithLiteral( node, isBytes ? 'bytes' : 'str', - node.strings.map(s => s.value).join('') - ) + node.strings.map((s) => s.value).join('') + ), }; } } @@ -801,7 +801,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { typeResult = getTypeOfExpression(node.expression, undefined, flags); typeResult = { type: getTypeFromAwaitable(typeResult.type, node.expression), - node + node, }; break; } @@ -929,11 +929,11 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // If the decorator has arguments, evaluate that call first. if (node.arguments) { - const argList = node.arguments.map(arg => { + const argList = node.arguments.map((arg) => { const functionArg: FunctionArgument = { valueExpression: arg.valueExpression, argumentCategory: arg.argumentCategory, - name: arg.name + name: arg.name, }; return functionArg; }); @@ -953,8 +953,8 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { const argList = [ { argumentCategory: ArgumentCategory.Simple, - type: functionOrClassType - } + type: functionOrClassType, + }, ]; return getTypeFromCallWithBaseType( @@ -1123,11 +1123,11 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { argList.push({ argumentCategory: previousCategory, type: UnknownType.create(), - active: true + active: true, }); } - callNode.arguments.forEach(arg => { + callNode.arguments.forEach((arg) => { let active = false; if (!addedActive) { @@ -1175,7 +1175,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { valueExpression: arg.valueExpression, argumentCategory: arg.argumentCategory, name: arg.name, - active: active + active: active, }); }); @@ -1194,7 +1194,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { signatures.push({ type, - activeParam: callResult?.activeParam + activeParam: callResult?.activeParam, }); } @@ -1206,7 +1206,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { } } - doForSubtypes(callType, subtype => { + doForSubtypes(callType, (subtype) => { switch (subtype.category) { case TypeCategory.Function: case TypeCategory.OverloadedFunction: { @@ -1252,7 +1252,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { return { callNode, - signatures + signatures, }; } @@ -1353,7 +1353,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // returns a generator object) // If errorNode is undefined, no errors are reported. function getTypeFromAwaitable(type: Type, errorNode?: ParseNode): Type { - return doForSubtypes(type, subtype => { + return doForSubtypes(type, (subtype) => { if (isAnyOrUnknown(subtype)) { return subtype; } @@ -1413,7 +1413,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { type = specializeType(type, undefined); } - if (type.category === TypeCategory.Union && type.subtypes.some(t => isNoneOrNever(t))) { + if (type.category === TypeCategory.Union && type.subtypes.some((t) => isNoneOrNever(t))) { if (errorNode) { addDiagnostic( getFileInfo(errorNode).diagnosticSettings.reportOptionalIterable, @@ -1473,7 +1473,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { return undefined; }; - return doForSubtypes(type, subtype => { + return doForSubtypes(type, (subtype) => { if (isAnyOrUnknown(subtype)) { return subtype; } @@ -1519,7 +1519,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { FunctionType.addParameter(newType, { category: ParameterCategory.Simple, name: 'cls', - type: classType + type: classType, }); addDefaultFunctionParameters(newType); newType.details.declaredReturnType = ObjectType.create(classType); @@ -1527,7 +1527,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { FunctionType.addParameter(initType, { category: ParameterCategory.Simple, name: 'self', - type: ObjectType.create(classType) + type: ObjectType.create(classType), }); initType.details.declaredReturnType = NoneType.create(); @@ -1542,9 +1542,9 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { type TypeEvaluator = () => Type; const localEntryTypeEvaluator: { entry: DataClassEntry; evaluator: TypeEvaluator }[] = []; - node.suite.statements.forEach(statementList => { + node.suite.statements.forEach((statementList) => { if (statementList.nodeType === ParseNodeType.StatementList) { - statementList.statements.forEach(statement => { + statementList.statements.forEach((statement) => { let variableNameNode: NameNode | undefined; let variableTypeEvaluator: TypeEvaluator | undefined; let hasDefaultValue = false; @@ -1580,12 +1580,12 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { const dataClassEntry: DataClassEntry = { name: variableName, hasDefault: hasDefaultValue, - type: UnknownType.create() + type: UnknownType.create(), }; localEntryTypeEvaluator.push({ entry: dataClassEntry, evaluator: variableTypeEvaluator }); // Add the new entry to the local entry list. - let insertIndex = localDataClassEntries.findIndex(e => e.name === variableName); + let insertIndex = localDataClassEntries.findIndex((e) => e.name === variableName); if (insertIndex >= 0) { localDataClassEntries[insertIndex] = dataClassEntry; } else { @@ -1593,7 +1593,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { } // Add the new entry to the full entry list. - insertIndex = fullDataClassEntries.findIndex(p => p.name === variableName); + insertIndex = fullDataClassEntries.findIndex((p) => p.name === variableName); if (insertIndex >= 0) { fullDataClassEntries[insertIndex] = dataClassEntry; } else { @@ -1603,7 +1603,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // If we've already seen a entry with a default value defined, // all subsequent entries must also have default values. - const firstDefaultValueIndex = fullDataClassEntries.findIndex(p => p.hasDefault); + const firstDefaultValueIndex = fullDataClassEntries.findIndex((p) => p.hasDefault); if (!hasDefaultValue && firstDefaultValueIndex >= 0 && firstDefaultValueIndex < insertIndex) { addError( `Data fields without default value cannot appear after data fields with default values`, @@ -1622,18 +1622,18 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // evaluations. This could involve circular type dependencies, so it's // required that the list be complete (even if types are not yet accurate) // before we perform the type evaluations. - localEntryTypeEvaluator.forEach(entryEvaluator => { + localEntryTypeEvaluator.forEach((entryEvaluator) => { entryEvaluator.entry.type = entryEvaluator.evaluator(); }); if (!skipSynthesizeInit) { - fullDataClassEntries.forEach(entry => { + fullDataClassEntries.forEach((entry) => { const functionParam: FunctionParameter = { category: ParameterCategory.Simple, name: entry.name, hasDefault: entry.hasDefault, hasDeclaredType: true, - type: entry.type + type: entry.type, }; FunctionType.addParameter(initType, functionParam); @@ -1653,7 +1653,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { FunctionType.addParameter(newType, { category: ParameterCategory.Simple, name: 'cls', - type: classType + type: classType, }); addDefaultFunctionParameters(newType); newType.details.declaredReturnType = ObjectType.create(classType); @@ -1663,14 +1663,14 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { FunctionType.addParameter(initType, { category: ParameterCategory.Simple, name: 'self', - type: ObjectType.create(classType) + type: ObjectType.create(classType), }); initType.details.declaredReturnType = NoneType.create(); // All parameters must be named, so insert an empty "*". FunctionType.addParameter(initType, { category: ParameterCategory.VarArgList, - type: AnyType.create() + type: AnyType.create(), }); const entries = getTypedDictMembersForClass(classType); @@ -1679,7 +1679,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { category: ParameterCategory.Simple, name, hasDefault: !entry.isRequired, - type: entry.valueType + type: entry.valueType, }); }); @@ -1699,20 +1699,20 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { FunctionType.addParameter(getOverload, { category: ParameterCategory.Simple, name: 'self', - type: ObjectType.create(classType) + type: ObjectType.create(classType), }); FunctionType.addParameter(getOverload, { category: ParameterCategory.Simple, name: 'k', hasDeclaredType: true, - type: ObjectType.cloneWithLiteral(ObjectType.create(strClass), name) + type: ObjectType.cloneWithLiteral(ObjectType.create(strClass), name), }); FunctionType.addParameter(getOverload, { category: ParameterCategory.Simple, name: 'default', hasDeclaredType: true, type: entry.valueType, - hasDefault: true + hasDefault: true, }); getOverload.details.declaredReturnType = entry.valueType; getOverloads.push(getOverload); @@ -1908,7 +1908,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { } } - const varDecl: Declaration | undefined = declarations.find(decl => decl.type === DeclarationType.Variable); + const varDecl: Declaration | undefined = declarations.find((decl) => decl.type === DeclarationType.Variable); if (varDecl && varDecl.type === DeclarationType.Variable && srcExpression) { if (varDecl.isConstant) { @@ -2103,7 +2103,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { targetTypes[i] = []; } - doForSubtypes(type, subtype => { + doForSubtypes(type, (subtype) => { // Is this subtype a tuple? const tupleType = getSpecializedTupleType(subtype); if (tupleType && tupleType.typeArguments) { @@ -2194,7 +2194,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // We will mark the symbols referenced by these strings as accessed. if (srcExpr.nodeType === ParseNodeType.List) { const fileInfo = getFileInfo(target); - srcExpr.entries.forEach(entryExpr => { + srcExpr.entries.forEach((entryExpr) => { if ( entryExpr.nodeType === ParseNodeType.StringList || entryExpr.nodeType === ParseNodeType.String @@ -2202,7 +2202,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { const symbolName = entryExpr.nodeType === ParseNodeType.String ? entryExpr.value - : entryExpr.strings.map(s => s.value).join(''); + : entryExpr.strings.map((s) => s.value).join(''); const symbolInScope = scope.lookUpSymbolRecursive(symbolName); if (symbolInScope) { setSymbolAccessed(fileInfo, symbolInScope.symbol, target); @@ -2284,7 +2284,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // The assigned expression had better be some iterable type. const iteratedType = getTypeFromIterable(type, false, srcExpr, false); - target.entries.forEach(entry => { + target.entries.forEach((entry) => { assignTypeToExpression(entry, iteratedType, srcExpr); }); break; @@ -2388,8 +2388,8 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // Add the entries to the end of the list, replacing same-named // entries if found. - dataClassEntries.forEach(entry => { - const existingIndex = entries.findIndex(e => e.name === entry.name); + dataClassEntries.forEach((entry) => { + const existingIndex = entries.findIndex((e) => e.name === entry.name); if (existingIndex >= 0) { entries[existingIndex] = entry; } else { @@ -2624,7 +2624,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { node, { type: specializeType(baseType, undefined), - node + node, }, usage, EvaluatorFlags.None @@ -2685,7 +2685,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { } case TypeCategory.Union: { - type = doForSubtypes(baseType, subtype => { + type = doForSubtypes(baseType, (subtype) => { if (isNoneOrNever(subtype)) { addDiagnostic( getFileInfo(node).diagnosticSettings.reportOptionalMemberAccess, @@ -2703,7 +2703,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { node, { type: subtype, - node + node, }, usage, EvaluatorFlags.None @@ -2892,19 +2892,19 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { const argList: FunctionArgument[] = [ { argumentCategory: ArgumentCategory.Simple, - type: ObjectType.create(memberClassType) + type: ObjectType.create(memberClassType), }, { argumentCategory: ArgumentCategory.Simple, type: flags & MemberAccessFlags.SkipInstanceMembers ? NoneType.create() - : ObjectType.create(classType) + : ObjectType.create(classType), }, { argumentCategory: ArgumentCategory.Simple, - type: AnyType.create() - } + type: AnyType.create(), + }, ]; const overload = findOverloadedFunctionType(errorNode, argList, accessMethodType); @@ -2943,7 +2943,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { return { type, - isClassMember: !memberInfo.isInstanceMember + isClassMember: !memberInfo.isInstanceMember, }; } } @@ -2960,7 +2960,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // if this assignment isn't within the enclosing class. If // it is within the enclosing class, the assignment is used // to infer the type of the member. - if (!memberInfo.symbol.getDeclarations().some(decl => decl.node === errorNode)) { + if (!memberInfo.symbol.getDeclarations().some((decl) => decl.node === errorNode)) { enforceTargetType = true; } } @@ -2996,7 +2996,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { return { type, - isClassMember: !memberInfo.isInstanceMember + isClassMember: !memberInfo.isInstanceMember, }; } @@ -3016,7 +3016,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { if (getAttribType && getAttribType.category === TypeCategory.Function) { return { type: getFunctionEffectiveReturnType(getAttribType), - isClassMember: false + isClassMember: false, }; } @@ -3031,7 +3031,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { if (getAttrType && getAttrType.category === TypeCategory.Function) { return { type: getFunctionEffectiveReturnType(getAttrType), - isClassMember: false + isClassMember: false, }; } } else if (usage.method === 'set') { @@ -3048,7 +3048,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // to return a defined type. return { type: AnyType.create(), - isClassMember: false + isClassMember: false, }; } } else { @@ -3066,7 +3066,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // to return a defined type. return { type: AnyType.create(), - isClassMember: false + isClassMember: false, }; } } @@ -3098,7 +3098,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { const typeParameters: TypeVarType[] = []; let isUnionOfClasses = true; - doForSubtypes(baseType, subtype => { + doForSubtypes(baseType, (subtype) => { if ( subtype.category === TypeCategory.Class || subtype.category === TypeCategory.TypeVar || @@ -3113,14 +3113,14 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { }); if (isUnionOfClasses && typeParameters.length > 0) { - const typeArgs = getTypeArgs(node.items, flags).map(t => convertClassToObject(t.type)); + const typeArgs = getTypeArgs(node.items, flags).map((t) => convertClassToObject(t.type)); const typeVarMap = buildTypeVarMap(typeParameters, typeArgs); const type = specializeType(baseType, typeVarMap); return { type, node }; } } - const type = doForSubtypes(baseType, subtype => { + const type = doForSubtypes(baseType, (subtype) => { if (subtype.category === TypeCategory.TypeVar) { subtype = specializeType(subtype, undefined); } @@ -3200,7 +3200,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // In case we didn't walk the list items above, do so now. // If we have, this information will be cached. - node.items.items.forEach(item => { + node.items.items.forEach((item) => { getTypeOfExpression(item); }); @@ -3219,7 +3219,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { const indexType = getTypeOfExpression(node.items.items[0]).type; const diag = new DiagnosticAddendum(); - const resultingType = doForSubtypes(indexType, subtype => { + const resultingType = doForSubtypes(indexType, (subtype) => { if (isAnyOrUnknown(subtype)) { return subtype; } @@ -3308,7 +3308,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { return UnknownType.create(); } - const indexTypeList = node.items.items.map(item => getTypeOfExpression(item).type); + const indexTypeList = node.items.items.map((item) => getTypeOfExpression(item).type); let indexType: Type; if (indexTypeList.length === 1) { @@ -3354,14 +3354,14 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { const argList: FunctionArgument[] = [ { argumentCategory: ArgumentCategory.Simple, - type: indexType - } + type: indexType, + }, ]; if (usage.method === 'set') { argList.push({ argumentCategory: ArgumentCategory.Simple, - type: usage.setType || AnyType.create() + type: usage.setType || AnyType.create(), }); } @@ -3373,7 +3373,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { function getTypeArgs(node: IndexItemsNode, flags: EvaluatorFlags): TypeResult[] { const typeArgs: TypeResult[] = []; - node.items.forEach(expr => { + node.items.forEach((expr) => { typeArgs.push(getTypeArg(expr, flags)); }); @@ -3386,8 +3386,8 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { if (node.nodeType === ParseNodeType.List) { typeResult = { type: UnknownType.create(), - typeList: node.entries.map(entry => getTypeOfExpression(entry, undefined, flags)), - node + typeList: node.entries.map((entry) => getTypeOfExpression(entry, undefined, flags)), + node, }; } else { typeResult = getTypeOfExpression( @@ -3418,7 +3418,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { expectedTypes.push(tupleClass.typeArguments[0]); } } else { - tupleClass.typeArguments.forEach(typeArg => { + tupleClass.typeArguments.forEach((typeArg) => { expectedTypes.push(typeArg); }); } @@ -3448,7 +3448,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // If the Tuple wasn't specialized or has a "..." type parameter, we can't // make any determination about its contents. - if (!typeArgs || typeArgs.some(t => t.category === TypeCategory.Any && t.isEllipsis)) { + if (!typeArgs || typeArgs.some((t) => t.category === TypeCategory.Any && t.isEllipsis)) { tupleTypes = [AnyType.create(false), AnyType.create(true)]; break; } @@ -3478,7 +3478,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { if (node.leftExpression.nodeType === ParseNodeType.Name && node.leftExpression.value === 'super') { return { type: getTypeFromSuperCall(node), - node + node, }; } @@ -3497,11 +3497,11 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { return { type: AnyType.create(), node }; } - const argList = node.arguments.map(arg => { + const argList = node.arguments.map((arg) => { const functionArg: FunctionArgument = { valueExpression: arg.valueExpression, argumentCategory: arg.argumentCategory, - name: arg.name + name: arg.name, }; return functionArg; }); @@ -3689,7 +3689,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { getAbstractMethodsRecursive(callType, symbolTable); const diagAddendum = new DiagnosticAddendum(); - const symbolTableKeys = [...symbolTable.keys()].filter(key => symbolTable.get(key)!.isAbstract); + const symbolTableKeys = [...symbolTable.keys()].filter((key) => symbolTable.get(key)!.isAbstract); const errorsToDisplay = 2; symbolTableKeys.forEach((symbolName, index) => { @@ -3802,7 +3802,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { } else { const exprString = ParseTreeUtils.printExpression(errorNode); const diagAddendum = new DiagnosticAddendum(); - const argTypes = argList.map(t => printType(getTypeForArgument(t))); + const argTypes = argList.map((t) => printType(getTypeForArgument(t))); diagAddendum.addMessage(`Argument types: (${argTypes.join(', ')})`); const fileInfo = getFileInfo(errorNode); addDiagnostic( @@ -3858,7 +3858,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { case TypeCategory.Union: { const returnTypes: Type[] = []; - callType.subtypes.forEach(typeEntry => { + callType.subtypes.forEach((typeEntry) => { if (isNoneOrNever(typeEntry)) { addDiagnostic( getFileInfo(errorNode).diagnosticSettings.reportOptionalCall, @@ -3872,7 +3872,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { argList, { type: typeEntry, - node: baseTypeResult.node + node: baseTypeResult.node, }, expectedType, flags @@ -3892,7 +3892,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { case TypeCategory.Any: case TypeCategory.Unknown: { // Mark the arguments accessed. - argList.forEach(arg => getTypeForArgument(arg)); + argList.forEach((arg) => getTypeForArgument(arg)); type = callType; break; } @@ -4132,7 +4132,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { case TypeCategory.Unknown: case TypeCategory.Any: { // Touch all of the args so they're marked accessed. - argList.forEach(arg => getTypeForArgument(arg)); + argList.forEach((arg) => getTypeForArgument(arg)); callResult.returnType = callType; break; } @@ -4163,7 +4163,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { } else { const exprString = ParseTreeUtils.printExpression(errorNode); const diagAddendum = new DiagnosticAddendum(); - const argTypes = argList.map(t => printType(getTypeForArgument(t))); + const argTypes = argList.map((t) => printType(getTypeForArgument(t))); diagAddendum.addMessage(`Argument types: (${argTypes.join(', ')})`); const fileInfo = getFileInfo(errorNode); addDiagnostic( @@ -4267,16 +4267,16 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { const typeParams = type.details.parameters; // The last parameter might be a var arg dictionary. If so, strip it off. - const varArgDictParam = typeParams.find(param => param.category === ParameterCategory.VarArgDictionary); + const varArgDictParam = typeParams.find((param) => param.category === ParameterCategory.VarArgDictionary); let reportedArgError = false; // Build a map of parameters by name. const paramMap = new Map(); - typeParams.forEach(param => { + typeParams.forEach((param) => { if (param.name) { paramMap.set(param.name, { argsNeeded: param.category === ParameterCategory.Simple && !param.hasDefault ? 1 : 0, - argsReceived: 0 + argsReceived: 0, }); } }); @@ -4284,19 +4284,19 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // Is there a bare (nameless) "*" parameter? If so, it signifies the end // of the positional parameter list. let positionalParamCount = typeParams.findIndex( - param => param.category === ParameterCategory.VarArgList && !param.name + (param) => param.category === ParameterCategory.VarArgList && !param.name ); // Is there a positional-only "/" parameter? If so, it separates the // positional-only from positional or keyword parameters. const positionalOnlyIndex = typeParams.findIndex( - param => param.category === ParameterCategory.Simple && !param.name + (param) => param.category === ParameterCategory.Simple && !param.name ); // Is there a var-arg (named "*") parameter? If so, it is the last of // the positional parameters. if (positionalParamCount < 0) { - positionalParamCount = typeParams.findIndex(param => param.category === ParameterCategory.VarArgList); + positionalParamCount = typeParams.findIndex((param) => param.category === ParameterCategory.VarArgList); if (positionalParamCount >= 0) { positionalParamCount++; } @@ -4305,7 +4305,9 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // Is there a keyword var-arg ("**") parameter? If so, it's not included // in the list of positional parameters. if (positionalParamCount < 0) { - positionalParamCount = typeParams.findIndex(param => param.category === ParameterCategory.VarArgDictionary); + positionalParamCount = typeParams.findIndex( + (param) => param.category === ParameterCategory.VarArgDictionary + ); } // If we didn't see any special cases, then all parameters are positional. @@ -4316,7 +4318,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // Determine how many positional args are being passed before // we see a named arg. let positionalArgCount = argList.findIndex( - arg => arg.argumentCategory === ArgumentCategory.UnpackedDictionary || arg.name !== undefined + (arg) => arg.argumentCategory === ArgumentCategory.UnpackedDictionary || arg.name !== undefined ); if (positionalArgCount < 0) { positionalArgCount = argList.length; @@ -4383,14 +4385,14 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { ); const funcArg: FunctionArgument = { argumentCategory: ArgumentCategory.Simple, - type: listElementType + type: listElementType, }; validateArgTypeParams.push({ paramType, requiresTypeVarMatching: requiresSpecialization(paramType), argument: funcArg, - errorNode: argList[argIndex].valueExpression || errorNode + errorNode: argList[argIndex].valueExpression || errorNode, }); trySetActive(argList[argIndex], typeParams[paramIndex]); } @@ -4401,7 +4403,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { requiresTypeVarMatching: requiresSpecialization(paramType), argument: argList[argIndex], errorNode: argList[argIndex].valueExpression || errorNode, - paramName: typeParams[paramIndex].name + paramName: typeParams[paramIndex].name, }); trySetActive(argList[argIndex], typeParams[paramIndex]); @@ -4412,7 +4414,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { requiresTypeVarMatching: requiresSpecialization(paramType), argument: argList[argIndex], errorNode: argList[argIndex].valueExpression || errorNode, - paramName: typeParams[paramIndex].name + paramName: typeParams[paramIndex].name, }); trySetActive(argList[argIndex], typeParams[paramIndex]); @@ -4430,7 +4432,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { if (!reportedArgError) { let foundUnpackedDictionaryArg = false; const foundUnpackedListArg = - argList.find(arg => arg.argumentCategory === ArgumentCategory.UnpackedList) !== undefined; + argList.find((arg) => arg.argumentCategory === ArgumentCategory.UnpackedList) !== undefined; // Now consume any named parameters. while (argIndex < argList.length) { @@ -4453,7 +4455,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { } else { paramMap.get(paramName.value)!.argsReceived++; - const paramInfoIndex = typeParams.findIndex(param => param.name === paramNameValue); + const paramInfoIndex = typeParams.findIndex((param) => param.name === paramNameValue); assert(paramInfoIndex >= 0); const paramType = FunctionType.getEffectiveParameterType(type, paramInfoIndex); @@ -4462,7 +4464,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { requiresTypeVarMatching: requiresSpecialization(paramType), argument: argList[argIndex], errorNode: argList[argIndex].valueExpression || errorNode, - paramName: paramNameValue + paramName: paramNameValue, }); trySetActive(argList[argIndex], typeParams[paramInfoIndex]); } @@ -4472,7 +4474,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { requiresTypeVarMatching: requiresSpecialization(varArgDictParam.type), argument: argList[argIndex], errorNode: argList[argIndex].valueExpression || errorNode, - paramName: paramNameValue + paramName: paramNameValue, }); trySetActive(argList[argIndex], varArgDictParam); } else { @@ -4494,7 +4496,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { !foundUnpackedListArg && !FunctionType.isDefaultParameterCheckDisabled(type) ) { - const unassignedParams = [...paramMap.keys()].filter(name => { + const unassignedParams = [...paramMap.keys()].filter((name) => { const entry = paramMap.get(name)!; return entry.argsReceived < entry.argsNeeded; }); @@ -4502,7 +4504,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { if (unassignedParams.length > 0) { addError( `Argument missing for parameter${unassignedParams.length === 1 ? '' : 's'} ` + - unassignedParams.map(p => `"${p}"`).join(', '), + unassignedParams.map((p) => `"${p}"`).join(', '), errorNode ); reportedArgError = true; @@ -4513,7 +4515,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // def foo(v1: _T = 'default') // and _T is a TypeVar, we need to match the TypeVar to the default // value's type if it's not provided by the caller. - typeParams.forEach(param => { + typeParams.forEach((param) => { if (param.category === ParameterCategory.Simple && param.name) { const entry = paramMap.get(param.name)!; if (entry.argsNeeded === 0 && entry.argsReceived === 0) { @@ -4523,10 +4525,10 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { requiresTypeVarMatching: true, argument: { argumentCategory: ArgumentCategory.Simple, - type: param.defaultType + type: param.defaultType, }, errorNode: errorNode, - paramName: param.name + paramName: param.name, }); } } @@ -4537,7 +4539,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // Special-case a few built-in calls that are often used for // casting or checking for unknown types. - if (['cast', 'isinstance', 'issubclass'].some(name => name === type.details.builtInName)) { + if (['cast', 'isinstance', 'issubclass'].some((name) => name === type.details.builtInName)) { skipUnknownArgCheck = true; } @@ -4545,7 +4547,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // We'll do two passes. The first one will match any type arguments. The second // will perform the actual validation. We can skip the first pass if there // are no type vars to match. - const typeVarMatchingCount = validateArgTypeParams.filter(arg => arg.requiresTypeVarMatching).length; + const typeVarMatchingCount = validateArgTypeParams.filter((arg) => arg.requiresTypeVarMatching).length; if (typeVarMatchingCount > 0) { // In theory, we may need to do up to n passes where n is the number of // arguments that need type var matching. That's because later matches @@ -4558,7 +4560,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { const passCount = Math.min(typeVarMatchingCount, 2); for (let i = 0; i < passCount; i++) { useSpeculativeMode(errorNode, () => { - validateArgTypeParams.forEach(argParam => { + validateArgTypeParams.forEach((argParam) => { if (argParam.requiresTypeVarMatching) { validateArgType(argParam, typeVarMap, skipUnknownArgCheck); } @@ -4571,7 +4573,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { typeVarMap.lock(); } - validateArgTypeParams.forEach(argParam => { + validateArgTypeParams.forEach((argParam) => { if (!validateArgType(argParam, typeVarMap, skipUnknownArgCheck)) { reportedArgError = true; } @@ -4581,9 +4583,9 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // to ensure that we haven't missed any (due to arg/param mismatches). This will // ensure that referenced symbols are not reported as unaccessed. if (!isSpeculativeMode(undefined)) { - argList.forEach(arg => { + argList.forEach((arg) => { if (arg.valueExpression) { - if (!validateArgTypeParams.some(validatedArg => validatedArg.argument === arg)) { + if (!validateArgTypeParams.some((validatedArg) => validatedArg.argument === arg)) { getTypeOfExpression(arg.valueExpression); } } @@ -4685,7 +4687,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { const firstArg = argList[0]; if (firstArg.valueExpression && firstArg.valueExpression.nodeType === ParseNodeType.StringList) { - typeVarName = firstArg.valueExpression.strings.map(s => s.value).join(''); + typeVarName = firstArg.valueExpression.strings.map((s) => s.value).join(''); } else { addError('Expected name of TypeVar as first parameter', firstArg.valueExpression || errorNode); } @@ -4788,7 +4790,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { if (nameArg.argumentCategory !== ArgumentCategory.Simple) { addError('Expected enum class name as first parameter', argList[0].valueExpression || errorNode); } else if (nameArg.valueExpression && nameArg.valueExpression.nodeType === ParseNodeType.StringList) { - className = nameArg.valueExpression.strings.map(s => s.value).join(''); + className = nameArg.valueExpression.strings.map((s) => s.value).join(''); } } @@ -4814,10 +4816,10 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { addError('Expected enum item string as second parameter', errorNode); } else { const entries = entriesArg.valueExpression.strings - .map(s => s.value) + .map((s) => s.value) .join('') .split(' '); - entries.forEach(entryName => { + entries.forEach((entryName) => { entryName = entryName.trim(); if (entryName) { const entryType = UnknownType.create(); @@ -4837,7 +4839,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { stringNode.start, TextRange.getEnd(stringNode), getFileInfo(errorNode).lines - ) + ), }; newSymbol.addDeclaration(declaration); classFields.set(entryName, newSymbol); @@ -4858,7 +4860,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { const nameArg = argList[0]; if (nameArg.argumentCategory === ArgumentCategory.Simple) { if (nameArg.valueExpression && nameArg.valueExpression.nodeType === ParseNodeType.StringList) { - className = nameArg.valueExpression.strings.map(s => s.value).join(''); + className = nameArg.valueExpression.strings.map((s) => s.value).join(''); } } } @@ -4899,7 +4901,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { } const classType = ClassType.create(className, ClassTypeFlags.None, errorNode.id); - arg1Type.classType.typeArguments.forEach(baseClass => { + arg1Type.classType.typeArguments.forEach((baseClass) => { if (baseClass.category === TypeCategory.Class || isAnyOrUnknown(baseClass)) { classType.details.baseClasses.push(baseClass); } else { @@ -4936,7 +4938,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { ) { addError('Expected TypedDict class name as first parameter', argList[0].valueExpression || errorNode); } else { - className = nameArg.valueExpression.strings.map(s => s.value).join(''); + className = nameArg.valueExpression.strings.map((s) => s.value).join(''); } } @@ -4988,7 +4990,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { const entryDict = entriesArg.valueExpression; const entryMap = new Map(); - entryDict.entries.forEach(entry => { + entryDict.entries.forEach((entry) => { if (entry.nodeType !== ParseNodeType.DictionaryKeyEntry) { addError('Expected simple dictionary entry', entry); return; @@ -4999,7 +5001,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { return; } - const entryName = entry.keyExpression.strings.map(s => s.value).join(''); + const entryName = entry.keyExpression.strings.map((s) => s.value).join(''); if (!entryName) { addError('Names within a TypedDict cannot be empty', entry.keyExpression); return; @@ -5026,7 +5028,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { entry.keyExpression.start, TextRange.getEnd(entry.keyExpression), getFileInfo(errorNode).lines - ) + ), }; newSymbol.addDeclaration(declaration); @@ -5055,7 +5057,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { if (nameArg.argumentCategory !== ArgumentCategory.Simple) { addError('Expected named tuple class name as first parameter', argList[0].valueExpression || errorNode); } else if (nameArg.valueExpression && nameArg.valueExpression.nodeType === ParseNodeType.StringList) { - className = nameArg.valueExpression.strings.map(s => s.value).join(''); + className = nameArg.valueExpression.strings.map((s) => s.value).join(''); } } @@ -5082,13 +5084,13 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { FunctionType.addParameter(constructorType, { category: ParameterCategory.Simple, name: 'cls', - type: classType + type: classType, }); const selfParameter: FunctionParameter = { category: ParameterCategory.Simple, name: 'self', - type: ObjectType.create(classType) + type: ObjectType.create(classType), }; let addGenericGetAttribute = false; @@ -5107,10 +5109,10 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { entriesArg.valueExpression.nodeType === ParseNodeType.StringList ) { const entries = entriesArg.valueExpression.strings - .map(s => s.value) + .map((s) => s.value) .join('') .split(/[,\s]+/); - entries.forEach(entryName => { + entries.forEach((entryName) => { entryName = entryName.trim(); if (entryName) { const entryType = UnknownType.create(); @@ -5118,7 +5120,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { category: ParameterCategory.Simple, name: entryName, hasDeclaredType: includesTypes, - type: entryType + type: entryType, }; FunctionType.addParameter(constructorType, paramInfo); @@ -5137,7 +5139,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { stringNode.start, TextRange.getEnd(stringNode), getFileInfo(errorNode).lines - ) + ), }; newSymbol.addDeclaration(declaration); classFields.set(entryName, newSymbol); @@ -5178,7 +5180,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { } if (entryNameNode && entryNameNode.nodeType === ParseNodeType.StringList) { - entryName = entryNameNode.strings.map(s => s.value).join(''); + entryName = entryNameNode.strings.map((s) => s.value).join(''); if (!entryName) { addError('Names within a named tuple cannot be empty', entryNameNode); } @@ -5205,7 +5207,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { category: ParameterCategory.Simple, name: entryName, hasDeclaredType: includesTypes, - type: entryType + type: entryType, }; FunctionType.addParameter(constructorType, paramInfo); @@ -5221,7 +5223,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { entryNameNode.start, TextRange.getEnd(entryNameNode), getFileInfo(errorNode).lines - ) + ), }; newSymbol.addDeclaration(declaration); } @@ -5255,7 +5257,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { const keysItemType = FunctionType.create(FunctionTypeFlags.SynthesizedMethod); keysItemType.details.declaredReturnType = getBuiltInObject(errorNode, 'list', [ - getBuiltInObject(errorNode, 'str') + getBuiltInObject(errorNode, 'str'), ]); classFields.set('keys', Symbol.createWithType(SymbolFlags.InstanceMember, keysItemType)); classFields.set('items', Symbol.createWithType(SymbolFlags.InstanceMember, keysItemType)); @@ -5272,7 +5274,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { FunctionType.addParameter(getAttribType, { category: ParameterCategory.Simple, name: 'name', - type: getBuiltInObject(errorNode, 'str') + type: getBuiltInObject(errorNode, 'str'), }); classFields.set('__getattribute__', Symbol.createWithType(SymbolFlags.ClassMember, getAttribType)); } @@ -5322,7 +5324,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { const unaryOperatorMap: { [operator: number]: string } = { [OperatorType.Add]: '__pos__', [OperatorType.Subtract]: '__neg__', - [OperatorType.BitwiseInvert]: '__invert__' + [OperatorType.BitwiseInvert]: '__invert__', }; let type: Type | undefined; @@ -5418,7 +5420,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { return { type: validateBinaryOperation(node.operator, leftType, rightType, node), - node + node, }; } @@ -5436,7 +5438,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { [OperatorType.BitwiseOrEqual]: ['__ior__', OperatorType.BitwiseOr], [OperatorType.BitwiseXorEqual]: ['__ixor__', OperatorType.BitwiseXor], [OperatorType.LeftShiftEqual]: ['__ilshift__', OperatorType.LeftShift], - [OperatorType.RightShiftEqual]: ['__irshift__', OperatorType.RightShift] + [OperatorType.RightShiftEqual]: ['__irshift__', OperatorType.RightShift], }; let type: Type | undefined; @@ -5451,8 +5453,8 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { rightType = specializeType(rightType, undefined); } - type = doForSubtypes(leftType!, leftSubtype => { - return doForSubtypes(rightType, rightSubtype => { + type = doForSubtypes(leftType!, (leftSubtype) => { + return doForSubtypes(rightType, (rightSubtype) => { if (isAnyOrUnknown(leftSubtype) || isAnyOrUnknown(rightSubtype)) { // If either type is "Unknown" (versus Any), propagate the Unknown. if ( @@ -5489,8 +5491,8 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { let type: Type | undefined; if (arithmeticOperatorMap[operator]) { - type = doForSubtypes(leftType, leftSubtype => { - return doForSubtypes(rightType, rightSubtype => { + type = doForSubtypes(leftType, (leftSubtype) => { + return doForSubtypes(rightType, (rightSubtype) => { if (isAnyOrUnknown(leftSubtype) || isAnyOrUnknown(rightSubtype)) { // If either type is "Unknown" (versus Any), propagate the Unknown. if ( @@ -5519,8 +5521,8 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { }); }); } else if (bitwiseOperatorMap[operator]) { - type = doForSubtypes(leftType, leftSubtype => { - return doForSubtypes(rightType, rightSubtype => { + type = doForSubtypes(leftType, (leftSubtype) => { + return doForSubtypes(rightType, (rightSubtype) => { if (isAnyOrUnknown(leftSubtype) || isAnyOrUnknown(rightSubtype)) { // If either type is "Unknown" (versus Any), propagate the Unknown. if ( @@ -5539,8 +5541,8 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { }); }); } else if (comparisonOperatorMap[operator]) { - type = doForSubtypes(leftType, leftSubtype => { - return doForSubtypes(rightType, rightSubtype => { + type = doForSubtypes(leftType, (leftSubtype) => { + return doForSubtypes(rightType, (rightSubtype) => { if (isAnyOrUnknown(leftSubtype) || isAnyOrUnknown(rightSubtype)) { // If either type is "Unknown" (versus Any), propagate the Unknown. if ( @@ -5577,8 +5579,8 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { leftType = removeFalsinessFromType(leftType); } - type = doForSubtypes(leftType, leftSubtype => { - return doForSubtypes(rightType, rightSubtype => { + type = doForSubtypes(leftType, (leftSubtype) => { + return doForSubtypes(rightType, (rightSubtype) => { // If the operator is an AND or OR, we need to combine the two types. if (operator === OperatorType.And || operator === OperatorType.Or) { return combineTypes([leftSubtype, rightSubtype]); @@ -5626,10 +5628,10 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { ); if (magicMethodType) { - const functionArgs = args.map(arg => { + const functionArgs = args.map((arg) => { return { argumentCategory: ArgumentCategory.Simple, - type: arg + type: arg, }; }); @@ -5656,7 +5658,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { return undefined; }; - const returnType = doForSubtypes(objType, subtype => { + const returnType = doForSubtypes(objType, (subtype) => { if (isAnyOrUnknown(subtype)) { return subtype; } @@ -5690,7 +5692,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { } function getTypeFromSet(node: SetNode, expectedType?: Type): TypeResult { - const entryTypes = node.entries.map(entryNode => { + const entryTypes = node.entries.map((entryNode) => { if (entryNode.nodeType === ParseNodeType.ListComprehension) { return getElementTypeFromListComprehension(entryNode); } @@ -5699,7 +5701,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // If there is an expected type, see if we can match it. if (expectedType && entryTypes.length > 0) { - const narrowedExpectedType = doForSubtypes(expectedType, subtype => { + const narrowedExpectedType = doForSubtypes(expectedType, (subtype) => { if (subtype.category === TypeCategory.Object) { const classAlias = subtype.classType.details.aliasClass || subtype.classType; if (ClassType.isBuiltIn(classAlias, 'set') && subtype.classType.typeArguments) { @@ -5725,7 +5727,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { } const inferredEntryType = - entryTypes.length > 0 ? combineTypes(entryTypes.map(t => stripLiteralValue(t))) : AnyType.create(); + entryTypes.length > 0 ? combineTypes(entryTypes.map((t) => stripLiteralValue(t))) : AnyType.create(); const type = getBuiltInObject(node, 'set', [inferredEntryType]); @@ -5756,7 +5758,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { } // Infer the key and value types if possible. - node.entries.forEach(entryNode => { + node.entries.forEach((entryNode) => { let addUnknown = true; if (entryNode.nodeType === ParseNodeType.DictionaryKeyEntry) { @@ -5825,7 +5827,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // If there is an expected type, see if we can match any parts of it. if (expectedType) { - const narrowedExpectedType = doForSubtypes(expectedType, subtype => { + const narrowedExpectedType = doForSubtypes(expectedType, (subtype) => { if (subtype.category !== TypeCategory.Object) { return undefined; } @@ -5867,8 +5869,8 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { } // Strip any literal values. - keyTypes = keyTypes.map(t => stripLiteralValue(t)); - valueTypes = valueTypes.map(t => stripLiteralValue(t)); + keyTypes = keyTypes.map((t) => stripLiteralValue(t)); + valueTypes = valueTypes.map((t) => stripLiteralValue(t)); keyType = keyTypes.length > 0 ? combineTypes(keyTypes) : AnyType.create(); @@ -5910,7 +5912,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { const expectedEntryType = expectedType ? getListTypeArg(expectedType) : undefined; - let entryTypes = node.entries.map(entry => { + let entryTypes = node.entries.map((entry) => { if (entry.nodeType === ParseNodeType.ListComprehension) { return getElementTypeFromListComprehension(entry); } @@ -5919,7 +5921,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // If there is an expected type, see if we can match it. if (expectedType && entryTypes.length > 0) { - const narrowedExpectedType = doForSubtypes(expectedType, subtype => { + const narrowedExpectedType = doForSubtypes(expectedType, (subtype) => { const listElementType = getListTypeArg(subtype); if (listElementType) { const typeVarMap = new TypeVarMap(); @@ -5941,7 +5943,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { } } - entryTypes = entryTypes.map(t => stripLiteralValue(t)); + entryTypes = entryTypes.map((t) => stripLiteralValue(t)); let inferredEntryType: Type = AnyType.create(); if (entryTypes.length > 0) { @@ -6028,7 +6030,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // It's not clear what we should do with a union type. For now, // simply use the first function in the union. expectedFunctionType = expectedType.subtypes.find( - t => t.category === TypeCategory.Function + (t) => t.category === TypeCategory.Function ) as FunctionType; } } @@ -6048,7 +6050,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { category: param.category, name: param.name ? param.name.value : undefined, hasDefault: !!param.defaultValue, - type: paramType + type: paramType, }; FunctionType.addParameter(functionType, functionParam); }); @@ -6207,7 +6209,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { category: ParameterCategory.Simple, name: `p${index.toString()}`, isNameSynthesized: true, - type: convertClassToObject(entry.type) + type: convertClassToObject(entry.type), }); }); } else if (isEllipsisType(typeArgs[0].type)) { @@ -6279,7 +6281,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { if (item.nodeType === ParseNodeType.StringList) { const isBytes = (item.strings[0].token.flags & StringTokenFlags.Bytes) !== 0; - const value = item.strings.map(s => s.value).join(''); + const value = item.strings.map((s) => s.value).join(''); if (isBytes) { type = cloneBuiltinTypeWithLiteral(node, 'bytes', value); } else { @@ -6390,7 +6392,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { } } - let typeArgTypes = typeArgs ? typeArgs.map(t => convertClassToObject(t.type)) : []; + let typeArgTypes = typeArgs ? typeArgs.map((t) => convertClassToObject(t.type)) : []; // Make sure the argument list count is correct. if (paramLimit !== undefined) { @@ -6456,7 +6458,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // Make sure that all of the type args are typeVars and are unique. const uniqueTypeVars: TypeVarType[] = []; if (typeArgs) { - typeArgs.forEach(typeArg => { + typeArgs.forEach((typeArg) => { if (!(typeArg.type.category === TypeCategory.TypeVar)) { addError(`Type argument for "Generic" must be a type variable`, typeArg.node); } else { @@ -6488,7 +6490,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // want to interpret their class variables as enumerations. const className = enumClassInfo.classType.details.name; const builtInEnumClasses = ['Enum', 'IntEnum', 'Flag', 'IntFlag']; - if (builtInEnumClasses.find(c => c === className)) { + if (builtInEnumClasses.find((c) => c === className)) { return typeOfExpr; } } @@ -6572,7 +6574,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { ClassVar: { alias: '', module: 'builtins' }, Final: { alias: '', module: 'builtins' }, Literal: { alias: '', module: 'builtins' }, - TypedDict: { alias: '_TypedDict', module: 'self' } + TypedDict: { alias: '_TypedDict', module: 'self' }, }; const aliasMapEntry = specialTypes[assignedName]; @@ -6611,7 +6613,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { Set: { alias: 'set', module: 'builtins' }, FrozenSet: { alias: 'frozenset', module: 'builtins' }, Deque: { alias: 'deque', module: 'collections' }, - ChainMap: { alias: 'ChainMap', module: 'collections' } + ChainMap: { alias: 'ChainMap', module: 'collections' }, }; const aliasMapEntry = specialTypes[assignedName]; @@ -6754,7 +6756,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { let sawMetaclass = false; let nonMetaclassBaseClassCount = 0; - node.arguments.forEach(arg => { + node.arguments.forEach((arg) => { // Ignore keyword parameters other than metaclass or total. if (!arg.name || arg.name.value === 'metaclass') { let argType = getTypeOfExpression(arg.valueExpression).type; @@ -6830,7 +6832,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { if ( argType.category === TypeCategory.Unknown || (argType.category === TypeCategory.Union && - argType.subtypes.some(t => t.category === TypeCategory.Unknown)) + argType.subtypes.some((t) => t.category === TypeCategory.Unknown)) ) { addDiagnostic( fileInfo.diagnosticSettings.reportUntypedBaseClass, @@ -6950,7 +6952,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { if (initDecls.length === 1 && initDecls[0].type === DeclarationType.Function) { const initDeclNode = initDecls[0].node; const initParams = initDeclNode.parameters; - if (initParams.length > 1 && !initParams.some(param => param.typeAnnotation)) { + if (initParams.length > 1 && !initParams.some((param) => param.typeAnnotation)) { const genericParams = initParams.filter( (param, index) => index > 0 && param.name && param.category === ParameterCategory.Simple ); @@ -6960,7 +6962,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // Create a type parameter for each simple, named parameter // in the __init__ method. - classType.details.typeParameters = genericParams.map(param => + classType.details.typeParameters = genericParams.map((param) => TypeVarType.create(`__type_of_${param.name!.value}`, true) ); } @@ -7040,7 +7042,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { let skipSynthesizeInit = false; if (decoratorNode.arguments) { - decoratorNode.arguments.forEach(arg => { + decoratorNode.arguments.forEach((arg) => { if (arg.name && arg.name.value === 'init') { if (arg.valueExpression) { const fileInfo = getFileInfo(decoratorNode); @@ -7207,7 +7209,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { if (isNoneWithoutOptional && param.typeAnnotation) { const addOptionalAction: AddMissingOptionalToParamAction = { action: Commands.addMissingOptionalToParam, - offsetOfTypeNode: param.typeAnnotation.start + 1 + offsetOfTypeNode: param.typeAnnotation.start + 1, }; if (diag) { diag.addAction(addOptionalAction); @@ -7225,7 +7227,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { hasDefault: !!param.defaultValue, defaultType: defaultValueType, hasDeclaredType: !!param.typeAnnotation, - type: paramType || UnknownType.create() + type: paramType || UnknownType.create(), }; FunctionType.addParameter(functionType, functionParam); @@ -7486,12 +7488,12 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { getFunction.details.parameters.push({ category: ParameterCategory.Simple, name: 'self', - type: fget.details.parameters.length > 0 ? fget.details.parameters[0].type : AnyType.create() + type: fget.details.parameters.length > 0 ? fget.details.parameters[0].type : AnyType.create(), }); getFunction.details.parameters.push({ category: ParameterCategory.Simple, name: 'obj', - type: propertyObject + type: propertyObject, }); getFunction.details.declaredReturnType = fget.details.declaredReturnType; getFunction.details.declaration = fget.details.declaration; @@ -7503,12 +7505,12 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { accessorFunction.details.parameters.push({ category: ParameterCategory.Simple, name: 'self', - type: propertyObject + type: propertyObject, }); accessorFunction.details.parameters.push({ category: ParameterCategory.Simple, name: 'accessor', - type: AnyType.create() + type: AnyType.create(), }); accessorFunction.details.declaredReturnType = propertyObject; const accessorSymbol = Symbol.createWithType(SymbolFlags.ClassMember, accessorFunction); @@ -7551,12 +7553,12 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { setFunction.details.parameters.push({ category: ParameterCategory.Simple, name: 'self', - type: fset.details.parameters.length > 0 ? fset.details.parameters[0].type : AnyType.create() + type: fset.details.parameters.length > 0 ? fset.details.parameters[0].type : AnyType.create(), }); setFunction.details.parameters.push({ category: ParameterCategory.Simple, name: 'obj', - type: propertyObject + type: propertyObject, }); setFunction.details.declaredReturnType = NoneType.create(); let setParamType: Type = UnknownType.create(); @@ -7570,7 +7572,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { setFunction.details.parameters.push({ category: ParameterCategory.Simple, name: 'value', - type: setParamType + type: setParamType, }); const setSymbol = Symbol.createWithType(SymbolFlags.ClassMember, setFunction); fields.set('__set__', setSymbol); @@ -7610,12 +7612,12 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { delFunction.details.parameters.push({ category: ParameterCategory.Simple, name: 'self', - type: fdel.details.parameters.length > 0 ? fdel.details.parameters[0].type : AnyType.create() + type: fdel.details.parameters.length > 0 ? fdel.details.parameters[0].type : AnyType.create(), }); delFunction.details.parameters.push({ category: ParameterCategory.Simple, name: 'obj', - type: propertyObject + type: propertyObject, }); delFunction.details.declaredReturnType = NoneType.create(); const delSymbol = Symbol.createWithType(SymbolFlags.ClassMember, delFunction); @@ -7635,7 +7637,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { const decls = symbolWithScope.symbol.getDeclarations(); // Find this function's declaration. - let declIndex = decls.findIndex(decl => decl === functionDecl); + let declIndex = decls.findIndex((decl) => decl === functionDecl); if (declIndex > 0) { const overloadedTypes: FunctionType[] = [type]; while (declIndex > 0) { @@ -7727,7 +7729,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { ); } } else if ( - ['AsyncGenerator', 'AsyncIterator', 'AsyncIterable'].some(name => name === classType.details.name) + ['AsyncGenerator', 'AsyncIterator', 'AsyncIterable'].some((name) => name === classType.details.name) ) { // If it's already an AsyncGenerator, AsyncIterator or AsyncIterable, // leave it as is. @@ -7766,7 +7768,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // Is it a generator? if (functionDecl.yieldExpressions) { const inferredYieldTypes: Type[] = []; - functionDecl.yieldExpressions.forEach(yieldNode => { + functionDecl.yieldExpressions.forEach((yieldNode) => { if (isNodeReachable(yieldNode)) { if (yieldNode.expression) { const cachedType = getTypeOfExpression(yieldNode.expression).type; @@ -7819,7 +7821,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { } else { const inferredReturnTypes: Type[] = []; if (functionDecl.returnExpressions) { - functionDecl.returnExpressions.forEach(returnNode => { + functionDecl.returnExpressions.forEach((returnNode) => { if (isNodeReachable(returnNode)) { if (returnNode.returnExpression) { const returnType = getTypeOfExpression(returnNode.returnExpression).type; @@ -7885,7 +7887,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { if (exceptionType.category === TypeCategory.Object) { const iterableType = getTypeFromIterable(exceptionType, false, errorNode, false); - return doForSubtypes(iterableType, subtype => { + return doForSubtypes(iterableType, (subtype) => { if (isAnyOrUnknown(subtype)) { return subtype; } @@ -7902,12 +7904,12 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { return UnknownType.create(); } - const targetType = doForSubtypes(exceptionTypes, subType => { + const targetType = doForSubtypes(exceptionTypes, (subType) => { // If more than one type was specified for the exception, we'll receive // a specialized tuple object here. const tupleType = getSpecializedTupleType(subType); if (tupleType && tupleType.typeArguments) { - const entryTypes = tupleType.typeArguments.map(t => { + const entryTypes = tupleType.typeArguments.map((t) => { return getExceptionType(t, node.typeExpression!); }); return combineTypes(entryTypes); @@ -7943,7 +7945,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { } const enterMethodName = isAsync ? '__aenter__' : '__enter__'; - const scopedType = doForSubtypes(exprType, subtype => { + const scopedType = doForSubtypes(exprType, (subtype) => { if (subtype.category === TypeCategory.TypeVar) { subtype = specializeType(subtype, undefined); } @@ -8106,7 +8108,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { return undefined; } - const aliasDecl = symbolWithScope.symbol.getDeclarations().find(decl => decl.type === DeclarationType.Alias); + const aliasDecl = symbolWithScope.symbol.getDeclarations().find((decl) => decl.type === DeclarationType.Alias); if (!aliasDecl) { return undefined; } @@ -8251,7 +8253,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { return; } - const paramIndex = functionNode.parameters.findIndex(param => param === node); + const paramIndex = functionNode.parameters.findIndex((param) => param === node); // We may be able to infer the type of the first parameter. if (paramIndex === 0) { @@ -8366,7 +8368,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { const symbolWithScope = lookUpSymbolRecursive(flowNode.node, name); assert(symbolWithScope !== undefined); const decls = symbolWithScope!.symbol.getDeclarations(); - const wildcardDecl = decls.find(decl => decl.node === flowNode.node); + const wildcardDecl = decls.find((decl) => decl.node === flowNode.node); if (!wildcardDecl) { return UnknownType.create(); @@ -8570,7 +8572,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { const entry: CachedType | undefined = isIncomplete ? { isIncompleteType: true, - type + type, } : type; @@ -8579,7 +8581,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { return { type, - isIncomplete + isIncomplete, }; } @@ -8596,13 +8598,13 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { if (!isIncompleteType(cachedEntry)) { return { type: cachedEntry, - isIncomplete: false + isIncomplete: false, }; } return { type: cachedEntry.type, - isIncomplete: true + isIncomplete: true, }; } @@ -8824,7 +8826,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { const wildcardImportFlowNode = curFlowNode as FlowWildcardImport; if (reference.nodeType === ParseNodeType.Name) { const nameValue = reference.value; - if (wildcardImportFlowNode.names.some(name => name === nameValue)) { + if (wildcardImportFlowNode.names.some((name) => name === nameValue)) { const type = getTypeFromWildcardImport(wildcardImportFlowNode, nameValue); return setCacheEntry(curFlowNode, type, false); } @@ -8847,7 +8849,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // referenced types). return { type: initialType, - isIncomplete: false + isIncomplete: false, }; } @@ -8855,7 +8857,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { } return { - getTypeFromCodeFlow + getTypeFromCodeFlow, }; } @@ -9008,7 +9010,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // Narrow the type by filtering on "None". return (type: Type) => { if (type.category === TypeCategory.Union) { - const remainingTypes = type.subtypes.filter(t => { + const remainingTypes = type.subtypes.filter((t) => { if (isAnyOrUnknown(t)) { // We need to assume that "Any" is always both None and not None, // so it matches regardless of whether the test is positive or negative. @@ -9049,7 +9051,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { if (classType.category === TypeCategory.Class) { return (type: Type) => { // Narrow the type based on whether the type matches the specified type. - return doForSubtypes(type, subtype => { + return doForSubtypes(type, (subtype) => { if (subtype.category === TypeCategory.Object) { const matches = ClassType.isSameGenericClass(subtype.classType, classType); if (adjIsPositiveTest) { @@ -9111,7 +9113,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { if (ParseTreeUtils.isMatchingExpression(reference, testExpression)) { return (type: Type) => { // Narrow the type based on whether the subtype can be true or false. - return doForSubtypes(type, subtype => { + return doForSubtypes(type, (subtype) => { if (isPositiveTest) { if (canBeTruthy(subtype)) { return subtype; @@ -9143,7 +9145,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { if (ClassType.isBuiltIn(objClass, 'Tuple') && objClass.typeArguments) { let foundNonClassType = false; const classTypeList: ClassType[] = []; - objClass.typeArguments.forEach(typeArg => { + objClass.typeArguments.forEach((typeArg) => { if (typeArg.category === TypeCategory.Class) { classTypeList.push(typeArg); } else { @@ -9171,7 +9173,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { isInstanceCheck: boolean, isPositiveTest: boolean ): Type { - const effectiveType = doForSubtypes(type, subtype => { + const effectiveType = doForSubtypes(type, (subtype) => { return transformTypeObjectToClass(subtype); }); @@ -9230,7 +9232,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { return filteredTypes; } - return filteredTypes.map(t => ObjectType.create(t)); + return filteredTypes.map((t) => ObjectType.create(t)); }; if (isInstanceCheck && effectiveType.category === TypeCategory.Object) { @@ -9242,7 +9244,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { } else if (effectiveType.category === TypeCategory.Union) { let remainingTypes: Type[] = []; - effectiveType.subtypes.forEach(t => { + effectiveType.subtypes.forEach((t) => { if (isAnyOrUnknown(t)) { // Any types always remain for both positive and negative // checks because we can't say anything about them. @@ -9271,7 +9273,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // Union[Callable[..., Any], Type[int], int], it would remove the "int" because // it's not callable. function narrowTypeForCallable(type: Type, isPositiveTest: boolean, errorNode: ExpressionNode): Type { - return doForSubtypes(type, subtype => { + return doForSubtypes(type, (subtype) => { switch (subtype.category) { case TypeCategory.Function: case TypeCategory.OverloadedFunction: @@ -9406,7 +9408,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { } if (typeArgs) { - typeArgs.forEach(typeArg => { + typeArgs.forEach((typeArg) => { // Verify that we didn't receive any inappropriate ellipses or modules. if (isEllipsisType(typeArg.type)) { addError(`"..." not allowed in this context`, typeArg.node); @@ -9417,7 +9419,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { } // Fill in any missing type arguments with Any. - const typeArgTypes = typeArgs ? typeArgs.map(t => convertClassToObject(t.type)) : []; + const typeArgTypes = typeArgs ? typeArgs.map((t) => convertClassToObject(t.type)) : []; const typeParams = ClassType.getTypeParameters(classType); for (let i = typeArgTypes.length; i < typeParams.length; i++) { typeArgTypes.push(getConcreteTypeFromTypeVar(typeParams[i])); @@ -9538,7 +9540,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { const functionScope = AnalyzerNodeInfo.getScope(functionNode)!; const paramSymbol = functionScope.lookUpSymbol(paramName)!; if (paramSymbol) { - return paramSymbol.getDeclarations().find(decl => decl.type === DeclarationType.Parameter); + return paramSymbol.getDeclarations().find((decl) => decl.type === DeclarationType.Parameter); } } } @@ -9570,7 +9572,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { const baseType = getType(node.parent.leftExpression); if (baseType) { const memberName = node.parent.memberName.value; - doForSubtypes(baseType, subtype => { + doForSubtypes(baseType, (subtype) => { let symbol: Symbol | undefined; if (subtype.category === TypeCategory.Class) { @@ -9613,7 +9615,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { }); } } else if (node.parent && node.parent.nodeType === ParseNodeType.ModuleName) { - const namePartIndex = node.parent.nameParts.findIndex(part => part === node); + const namePartIndex = node.parent.nameParts.findIndex((part) => part === node); const importInfo = AnalyzerNodeInfo.getImportInfo(node.parent); if (namePartIndex >= 0 && importInfo && namePartIndex < importInfo.resolvedPaths.length) { if (importInfo.resolvedPaths[namePartIndex]) { @@ -9624,7 +9626,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { node: undefined!, path: importInfo.resolvedPaths[namePartIndex], range: getEmptyRange(), - implicitImports: new Map() + implicitImports: new Map(), }; declarations.push(aliasDeclaration); } @@ -9917,7 +9919,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { curDeclaration = declarations[declarations.length - 1]; // Make sure we don't follow a circular list indefinitely. - if (alreadyVisited.find(decl => decl === curDeclaration)) { + if (alreadyVisited.find((decl) => decl === curDeclaration)) { return declaration; } alreadyVisited.push(curDeclaration); @@ -9937,7 +9939,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { const decls = symbol.getDeclarations(); const isFinalVar = isFinalVariable(symbol); - decls.forEach(decl => { + decls.forEach((decl) => { if (pushSymbolResolution(symbol, decl)) { let type = getInferredTypeOfDeclaration(decl); @@ -10102,14 +10104,14 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // If an arg hasn't been matched to a specific named parameter, // it's an unpacked value that corresponds to multiple parameters. // That's an edge case that we don't handle here. - if (args.some(arg => !arg.paramName)) { + if (args.some((arg) => !arg.paramName)) { return undefined; } // Detect recurrence. If a function invokes itself either directly // or indirectly, we won't attempt to infer contextual return // types any further. - if (returnTypeInferenceContextStack.some(context => context.functionNode === functionNode)) { + if (returnTypeInferenceContextStack.some((context) => context.functionNode === functionNode)) { return undefined; } @@ -10131,7 +10133,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { const prevTypeCache = returnTypeInferenceTypeCache; returnTypeInferenceContextStack.push({ functionNode, - codeFlowAnalyzer: createCodeFlowAnalyzer() + codeFlowAnalyzer: createCodeFlowAnalyzer(), }); returnTypeInferenceTypeCache = new Map(); @@ -10139,7 +10141,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { functionNode.parameters.forEach((param, index) => { if (param.name) { let paramType: Type | undefined; - const arg = args.find(arg => param.name!.value === arg.paramName); + const arg = args.find((arg) => param.name!.value === arg.paramName); if (arg && arg.argument.valueExpression) { paramType = getTypeOfExpression(arg.argument.valueExpression).type; allArgTypesAreUnknown = false; @@ -10275,7 +10277,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { }); // Now handle base classes of the dest protocol. - destType.details.baseClasses.forEach(baseClass => { + destType.details.baseClasses.forEach((baseClass) => { if ( baseClass.category === TypeCategory.Class && !ClassType.isBuiltIn(baseClass, 'object') && @@ -10657,7 +10659,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // Handle the constrained case. if (destType.constraints.length > 0) { // Find the first constrained type that is compatible. - const constrainedType = destType.constraints.find(constraintType => { + const constrainedType = destType.constraints.find((constraintType) => { return canAssignType(constraintType, srcType, new DiagnosticAddendum()); }); @@ -10886,7 +10888,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { let isIncompatible = false; // For union sources, all of the types need to be assignable to the dest. - srcType.subtypes.forEach(t => { + srcType.subtypes.forEach((t) => { if (!canAssignType(destType, t, diag.createAddendum(), typeVarMap, flags, recursionCount + 1)) { diag.addMessage(`Type "${printType(t)}" cannot be assigned to type "${printType(destType)}"`); isIncompatible = true; @@ -10908,7 +10910,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // Run through all subtypes in the union. Don't stop at the first // match we find because we may need to match TypeVars in other // subtypes. - destType.subtypes.forEach(subtype => { + destType.subtypes.forEach((subtype) => { if (canAssignType(subtype, srcType, diagAddendum, typeVarMap, flags, recursionCount + 1)) { foundMatch = true; } @@ -11099,7 +11101,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // We don't want to pollute the current typeVarMap, so we'll // make a copy of the existing one if it's specified. const overloads = srcType.overloads; - const overloadIndex = overloads.findIndex(overload => { + const overloadIndex = overloads.findIndex((overload) => { const typeVarMapClone = typeVarMap ? typeVarMap.clone() : undefined; return canAssignType( destType, @@ -11216,8 +11218,8 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // Count the number of parameters that have names. We'll exclude // pseudo-parameters (* and /) that designate name-only and position-only // separators. - const srcParamCount = srcType.details.parameters.filter(param => param.name).length; - const destParamCount = destType.details.parameters.filter(param => param.name).length; + const srcParamCount = srcType.details.parameters.filter((param) => param.name).length; + const destParamCount = destType.details.parameters.filter((param) => param.name).length; const minParamCount = Math.min(srcParamCount, destParamCount); // Match as many input parameters as we can. @@ -11271,16 +11273,16 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { const destParams = destType.details.parameters; const srcHasVarArgs = - srcParams.find(param => param.name && param.category !== ParameterCategory.Simple) !== undefined; + srcParams.find((param) => param.name && param.category !== ParameterCategory.Simple) !== undefined; const destHasVarArgs = - destParams.find(param => param.name && param.category !== ParameterCategory.Simple) !== undefined; + destParams.find((param) => param.name && param.category !== ParameterCategory.Simple) !== undefined; if (checkNamedParams) { // Handle matching of named (keyword) parameters. // Build a dictionary of named parameters in the dest. const destParamMap = new Map(); let destHasNamedParam = false; - destParams.forEach(param => { + destParams.forEach((param) => { if (destHasNamedParam) { if (param.name && param.category === ParameterCategory.Simple) { destParamMap.set(param.name, param); @@ -11291,7 +11293,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { }); let srcHasNamedParam = false; - srcParams.forEach(param => { + srcParams.forEach((param) => { if (srcHasNamedParam) { if (param.name && param.category === ParameterCategory.Simple) { const destParam = destParamMap.get(param.name); @@ -11344,7 +11346,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // with values. Plus, the number of source params must be enough to // accept all of the dest arguments. if (!srcHasVarArgs && !destHasVarArgs) { - const nonDefaultSrcParamCount = srcParams.filter(param => !!param.name && !param.hasDefault).length; + const nonDefaultSrcParamCount = srcParams.filter((param) => !!param.name && !param.hasDefault).length; if (destParamCount < nonDefaultSrcParamCount) { diag.addMessage( @@ -11394,9 +11396,9 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { const diagAddendum = new DiagnosticAddendum(); if (declaredType.category === TypeCategory.Union) { - return doForSubtypes(declaredType, subtype => { + return doForSubtypes(declaredType, (subtype) => { if (assignedType.category === TypeCategory.Union) { - if (!assignedType.subtypes.some(t => canAssignType(subtype, t, diagAddendum))) { + if (!assignedType.subtypes.some((t) => canAssignType(subtype, t, diagAddendum))) { return undefined; } else { return subtype; @@ -11449,8 +11451,9 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { if (baseParam.name !== overrideParam.name) { diag.addMessage( - `Parameter ${i + 1} name mismatch: base parameter is named "${baseParam.name || - '*'}", override parameter is named "${overrideParam.name || '*'}"` + `Parameter ${i + 1} name mismatch: base parameter is named "${ + baseParam.name || '*' + }", override parameter is named "${overrideParam.name || '*'}"` ); canOverride = false; } else { @@ -11539,7 +11542,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { return true; } else if (effectiveSrcType.category === TypeCategory.Union) { // Does it match at least one of the constraints? - if (effectiveSrcType.subtypes.find(t => isSameWithoutLiteralValue(constraint, t))) { + if (effectiveSrcType.subtypes.find((t) => isSameWithoutLiteralValue(constraint, t))) { return true; } } else if (isSameWithoutLiteralValue(constraint, effectiveSrcType)) { @@ -11561,7 +11564,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { getAbstractMethodsRecursive(classType, symbolMap); let abstractMethodCount = 0; - symbolMap.forEach(entry => { + symbolMap.forEach((entry) => { if (entry.isAbstract) { abstractMethodCount++; } @@ -11581,7 +11584,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { } const baseClasses: ClassType[] = []; - classType.details.baseClasses.forEach(baseClass => { + classType.details.baseClasses.forEach((baseClass) => { if (baseClass.category === TypeCategory.Class) { baseClasses.push(baseClass); } @@ -11603,7 +11606,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { symbolTable.set(symbolName, { symbol, isAbstract, - classType + classType, }); } } @@ -11612,7 +11615,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { // Recursively get abstract methods for subclasses. This is expensive, // so we'll check it only if one or more of the base classes is known // to have abstract methods. - if (baseClasses.some(baseClass => ClassType.hasAbstractMethods(baseClass))) { + if (baseClasses.some((baseClass) => ClassType.hasAbstractMethods(baseClass))) { for (const baseClass of baseClasses) { getAbstractMethodsRecursive(baseClass, symbolTable, recursiveCount + 1); } @@ -11660,7 +11663,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { } // See if any required keys are missing. - symbolMap.forEach(entry => { + symbolMap.forEach((entry) => { if (entry.isRequired && !entry.isProvided) { isMatch = false; } @@ -11685,7 +11688,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { return; } - classType.details.baseClasses.forEach(baseClassType => { + classType.details.baseClasses.forEach((baseClassType) => { if (baseClassType.category === TypeCategory.Class && ClassType.isTypedDictClass(baseClassType)) { getTypedDictMembersForClassRecursive(baseClassType, keyMap, recursionCount + 1); } @@ -11700,7 +11703,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { keyMap.set(name, { valueType: getDeclaredTypeOfSymbol(symbol) || UnknownType.create(), isRequired: !ClassType.isCanOmitDictValues(classType), - isProvided: false + isProvided: false, }); } } @@ -11735,7 +11738,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { } } else if (memberType.category === TypeCategory.OverloadedFunction) { const newOverloadType = OverloadedFunctionType.create(); - memberType.overloads.forEach(overload => { + memberType.overloads.forEach((overload) => { OverloadedFunctionType.addOverload( newOverloadType, bindFunctionToClassOrObject(baseType, overload, treatAsClassMember) as FunctionType @@ -11782,7 +11785,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { objName += '[' + type.typeArguments - .map(typeArg => { + .map((typeArg) => { return printType(typeArg, recursionCount + 1); }) .join(', ') + @@ -11799,7 +11802,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { objName += '[' + typeParams - .map(typeArg => { + .map((typeArg) => { return printType(typeArg, recursionCount + 1); }) .join(', ') + @@ -11813,7 +11816,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { function printFunctionParts(type: FunctionType, recursionCount = 0): [string[], string] { // Avoid printing type types if none of the parameters have known types. - const printInputTypes = type.details.parameters.some(param => param.hasDeclaredType); + const printInputTypes = type.details.parameters.some((param) => param.hasDeclaredType); const paramTypeStrings = type.details.parameters.map((param, index) => { let paramString = ''; if (param.category === ParameterCategory.VarArgList) { @@ -11905,7 +11908,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { case TypeCategory.OverloadedFunction: { const overloadedType = type; - const overloads = overloadedType.overloads.map(overload => printType(overload, recursionCount + 1)); + const overloads = overloadedType.overloads.map((overload) => printType(overload, recursionCount + 1)); return `Overload[${overloads.join(', ')}]`; } @@ -11913,7 +11916,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { const unionType = type; let subtypes: Type[] = unionType.subtypes; - if (subtypes.find(t => t.category === TypeCategory.None) !== undefined) { + if (subtypes.find((t) => t.category === TypeCategory.None) !== undefined) { const optionalType = printType(removeNoneFromUnion(unionType), recursionCount + 1); return 'Optional[' + optionalType + ']'; } @@ -11931,14 +11934,14 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { if (isLiteral(subtype)) { // Combine all literal values. Rather than printing Union[Literal[1], // Literal[2]], print Literal[1, 2]. - const literals = subtypes.filter(t => isLiteral(t)); + const literals = subtypes.filter((t) => isLiteral(t)); literals.unshift(subtype); - const literalValues = literals.map(t => printLiteralValue(t as ObjectType)); + const literalValues = literals.map((t) => printLiteralValue(t as ObjectType)); subtypeStrings.push(`Literal[${literalValues.join(', ')}]`); // Remove the items we've handled. if (literals.length > 1) { - subtypes = subtypes.filter(t => !isLiteral(t)); + subtypes = subtypes.filter((t) => !isLiteral(t)); } } else { subtypeStrings.push(printType(subtype, recursionCount + 1)); @@ -12020,7 +12023,7 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { ); if (parseResults.parseTree) { - parseResults.diagnostics.forEach(diag => { + parseResults.diagnostics.forEach((diag) => { addError(diag.message, node); }); @@ -12062,6 +12065,6 @@ export function createTypeEvaluator(importLookup: ImportLookup): TypeEvaluator { addDiagnosticForTextRange, printType, printFunctionParts, - hasGrownTooLarge + hasGrownTooLarge, }; } diff --git a/server/src/analyzer/typeStubWriter.ts b/server/src/analyzer/typeStubWriter.ts index 03091485e..11d66cebe 100644 --- a/server/src/analyzer/typeStubWriter.ts +++ b/server/src/analyzer/typeStubWriter.ts @@ -32,7 +32,7 @@ import { TryNode, TypeAnnotationNode, WhileNode, - WithNode + WithNode, } from '../parser/parseNodes'; import * as AnalyzerNodeInfo from './analyzerNodeInfo'; import * as ParseTreeUtils from './parseTreeUtils'; @@ -72,12 +72,12 @@ class TrackedImportFrom extends TrackedImport { } addSymbol(symbol: Symbol | undefined, name: string, alias: string | undefined, isAccessed = false) { - if (!this.symbols.find(s => s.name === name)) { + if (!this.symbols.find((s) => s.name === name)) { this.symbols.push({ symbol, name, alias, - isAccessed + isAccessed, }); } } @@ -163,7 +163,7 @@ export class TypeStubWriter extends ParseTreeWalker { let line = `class ${className}`; if (node.arguments.length > 0) { line += `(${node.arguments - .map(arg => { + .map((arg) => { let argString = ''; if (arg.name) { argString = arg.name.value + '='; @@ -198,7 +198,7 @@ export class TypeStubWriter extends ParseTreeWalker { this._emitDecorators(node.decorators); let line = node.isAsync ? 'async ' : ''; line += `def ${functionName}`; - line += `(${node.parameters.map(param => this._printParameter(param)).join(', ')})`; + line += `(${node.parameters.map((param) => this._printParameter(param)).join(', ')})`; if (node.returnTypeAnnotation) { line += ' -> ' + this._printExpression(node.returnTypeAnnotation, true); @@ -367,7 +367,7 @@ export class TypeStubWriter extends ParseTreeWalker { const currentScope = getScopeForNode(node); if (currentScope) { // Record the input for later. - node.list.forEach(imp => { + node.list.forEach((imp) => { const moduleName = this._printModuleName(imp.module); if (!this._trackedImportAs.has(moduleName)) { const symbolName = imp.alias @@ -406,7 +406,7 @@ export class TypeStubWriter extends ParseTreeWalker { this._trackedImportFrom.set(moduleName, trackedImportFrom); } - node.imports.forEach(imp => { + node.imports.forEach((imp) => { const symbolName = imp.alias ? imp.alias.value : imp.name.value; const symbolInfo = currentScope.lookUpSymbolRecursive(symbolName); if (symbolInfo) { @@ -461,10 +461,10 @@ export class TypeStubWriter extends ParseTreeWalker { } private _emitDecorators(decorators: DecoratorNode[]) { - decorators.forEach(decorator => { + decorators.forEach((decorator) => { let line = '@' + this._printExpression(decorator.leftExpression); if (decorator.arguments) { - line += `(${decorator.arguments.map(arg => this._printArgument(arg)).join(', ')})`; + line += `(${decorator.arguments.map((arg) => this._printArgument(arg)).join(', ')})`; } this._emitLine(line); }); @@ -499,7 +499,7 @@ export class TypeStubWriter extends ParseTreeWalker { for (let i = 0; i < node.leadingDots; i++) { line += '.'; } - line += node.nameParts.map(part => part.value).join('.'); + line += node.nameParts.map((part) => part.value).join('.'); return line; } @@ -510,7 +510,7 @@ export class TypeStubWriter extends ParseTreeWalker { this._trackedImportFrom.set(importName, trackedImportFrom); } - symbols.forEach(symbol => { + symbols.forEach((symbol) => { trackedImportFrom!.addSymbol(undefined, symbol, undefined, true); }); } @@ -593,7 +593,7 @@ export class TypeStubWriter extends ParseTreeWalker { let lineEmitted = false; // Emit the "import" statements. - this._trackedImportAs.forEach(imp => { + this._trackedImportAs.forEach((imp) => { if (this._accessedImportedSymbols.get(imp.alias || imp.importName)) { imp.isAccessed = true; } @@ -609,8 +609,8 @@ export class TypeStubWriter extends ParseTreeWalker { }); // Emit the "import from" statements. - this._trackedImportFrom.forEach(imp => { - imp.symbols.forEach(s => { + this._trackedImportFrom.forEach((imp) => { + imp.symbols.forEach((s) => { if (this._accessedImportedSymbols.get(s.alias || s.name)) { s.isAccessed = true; } @@ -622,7 +622,7 @@ export class TypeStubWriter extends ParseTreeWalker { } const sortedSymbols = imp.symbols - .filter(s => s.isAccessed || this._includeAllImports) + .filter((s) => s.isAccessed || this._includeAllImports) .sort((a, b) => { if (a.name < b.name) { return -1; @@ -636,7 +636,7 @@ export class TypeStubWriter extends ParseTreeWalker { importStr += `from ${imp.importName} import `; importStr += sortedSymbols - .map(symbol => { + .map((symbol) => { let symStr = symbol.name; if (symbol.alias) { symStr += ' as ' + symbol.alias; diff --git a/server/src/analyzer/typeUtils.ts b/server/src/analyzer/typeUtils.ts index ed9b54085..ff0a380dc 100644 --- a/server/src/analyzer/typeUtils.ts +++ b/server/src/analyzer/typeUtils.ts @@ -28,7 +28,7 @@ import { Type, TypeCategory, TypeVarType, - UnknownType + UnknownType, } from './types'; import { TypeVarMap } from './typeVarMap'; @@ -66,7 +66,7 @@ export const enum ClassMemberLookupFlags { // By default, the first symbol is returned even if it has only // an inferred type associated with it. If this flag is set, // the search looks only for symbols with declared types. - DeclaredTypesOnly = 1 << 4 + DeclaredTypesOnly = 1 << 4, } export const enum CanAssignFlags { @@ -79,7 +79,7 @@ export const enum CanAssignFlags { // The caller has swapped the source and dest types because // the types are contravariant. Perform type var matching // on dest type vars rather than source type var. - ReverseTypeVarMatching = 1 << 1 + ReverseTypeVarMatching = 1 << 1, } export interface TypedDictEntry { @@ -90,7 +90,7 @@ export interface TypedDictEntry { export function isOptionalType(type: Type): boolean { if (type.category === TypeCategory.Union) { - return type.subtypes.some(t => isNoneOrNever(t)); + return type.subtypes.some((t) => isNoneOrNever(t)); } return false; @@ -102,7 +102,7 @@ export function doForSubtypes(type: Type, callback: (type: Type) => Type | undef if (type.category === TypeCategory.Union) { const newTypes: Type[] = []; - type.subtypes.forEach(typeEntry => { + type.subtypes.forEach((typeEntry) => { const transformedType = callback(typeEntry); if (transformedType) { newTypes.push(transformedType); @@ -140,7 +140,7 @@ export function stripLiteralValue(type: Type): Type { } if (type.category === TypeCategory.Union) { - return doForSubtypes(type, subtype => { + return doForSubtypes(type, (subtype) => { return stripLiteralValue(subtype); }); } @@ -155,7 +155,7 @@ export function stripLiteralTypeArgsValue(type: Type, recursionCount = 0): Type if (type.category === TypeCategory.Class) { if (type.typeArguments) { - const strippedTypeArgs = type.typeArguments.map(t => + const strippedTypeArgs = type.typeArguments.map((t) => stripLiteralTypeArgsValue(stripLiteralValue(t), recursionCount + 1) ); return ClassType.cloneForSpecialization(type, strippedTypeArgs, type.skipAbstractClassTest); @@ -171,7 +171,7 @@ export function stripLiteralTypeArgsValue(type: Type, recursionCount = 0): Type } if (type.category === TypeCategory.Union) { - return doForSubtypes(type, subtype => { + return doForSubtypes(type, (subtype) => { return stripLiteralTypeArgsValue(subtype, recursionCount + 1); }); } @@ -179,12 +179,12 @@ export function stripLiteralTypeArgsValue(type: Type, recursionCount = 0): Type if (type.category === TypeCategory.Function) { if (type.specializedTypes) { const strippedSpecializedTypes: SpecializedFunctionTypes = { - parameterTypes: type.specializedTypes.parameterTypes.map(t => + parameterTypes: type.specializedTypes.parameterTypes.map((t) => stripLiteralTypeArgsValue(stripLiteralValue(t), recursionCount + 1) ), returnType: type.specializedTypes.returnType ? stripLiteralTypeArgsValue(stripLiteralValue(type.specializedTypes.returnType), recursionCount + 1) - : undefined + : undefined, }; type = FunctionType.cloneForSpecialization(type, strippedSpecializedTypes); } @@ -195,7 +195,7 @@ export function stripLiteralTypeArgsValue(type: Type, recursionCount = 0): Type if (type.category === TypeCategory.OverloadedFunction) { const strippedOverload = OverloadedFunctionType.create(); strippedOverload.overloads = type.overloads.map( - t => stripLiteralTypeArgsValue(t, recursionCount + 1) as FunctionType + (t) => stripLiteralTypeArgsValue(t, recursionCount + 1) as FunctionType ); return strippedOverload; } @@ -388,7 +388,7 @@ export function specializeType( if (type.category === TypeCategory.Union) { const subtypes: Type[] = []; - type.subtypes.forEach(typeEntry => { + type.subtypes.forEach((typeEntry) => { subtypes.push(specializeType(typeEntry, typeVarMap, makeConcrete, recursionLevel + 1)); }); @@ -503,7 +503,7 @@ export function lookUpClassMember( return { symbol, isInstanceMember: true, - classType: specializedMroClass + classType: specializedMroClass, }; } } @@ -533,7 +533,7 @@ export function lookUpClassMember( return { symbol, isInstanceMember, - classType: specializedMroClass + classType: specializedMroClass, }; } } @@ -550,7 +550,7 @@ export function lookUpClassMember( return { symbol: Symbol.createWithType(SymbolFlags.None, UnknownType.create()), isInstanceMember: false, - classType: UnknownType.create() + classType: UnknownType.create(), }; } } else if (isAnyOrUnknown(classType)) { @@ -559,7 +559,7 @@ export function lookUpClassMember( return { symbol: Symbol.createWithType(SymbolFlags.None, UnknownType.create()), isInstanceMember: false, - classType: UnknownType.create() + classType: UnknownType.create(), }; } @@ -570,12 +570,12 @@ export function addDefaultFunctionParameters(functionType: FunctionType) { FunctionType.addParameter(functionType, { category: ParameterCategory.VarArgList, name: 'args', - type: AnyType.create() + type: AnyType.create(), }); FunctionType.addParameter(functionType, { category: ParameterCategory.VarArgDictionary, name: 'kwargs', - type: AnyType.create() + type: AnyType.create(), }); } @@ -608,7 +608,7 @@ export function getMetaclass(type: ClassType, recursionCount = 0): ClassType | U // but removing any duplicates. export function addTypeVarsToListIfUnique(list1: TypeVarType[], list2: TypeVarType[]) { for (const type2 of list2) { - if (!list1.find(type1 => type1 === type2)) { + if (!list1.find((type1) => type1 === type2)) { list1.push(type2); } } @@ -623,7 +623,7 @@ export function getTypeVarArgumentsRecursive(type: Type): TypeVarType[] { const getTypeVarsFromClass = (classType: ClassType) => { const combinedList: TypeVarType[] = []; if (classType.typeArguments) { - classType.typeArguments.forEach(typeArg => { + classType.typeArguments.forEach((typeArg) => { addTypeVarsToListIfUnique(combinedList, getTypeVarArgumentsRecursive(typeArg)); }); } @@ -646,7 +646,7 @@ export function getTypeVarArgumentsRecursive(type: Type): TypeVarType[] { } else if (type.category === TypeCategory.Function) { const combinedList: TypeVarType[] = []; - type.details.parameters.forEach(param => { + type.details.parameters.forEach((param) => { addTypeVarsToListIfUnique(combinedList, getTypeVarArgumentsRecursive(param.type)); }); @@ -689,14 +689,14 @@ export function setTypeArgumentsRecursive(destType: Type, srcType: Type, typeVar switch (destType.category) { case TypeCategory.Union: - destType.subtypes.forEach(subtype => { + destType.subtypes.forEach((subtype) => { setTypeArgumentsRecursive(subtype, srcType, typeVarMap, recursionCount + 1); }); break; case TypeCategory.Class: if (destType.typeArguments) { - destType.typeArguments.forEach(typeArg => { + destType.typeArguments.forEach((typeArg) => { setTypeArgumentsRecursive(typeArg, srcType, typeVarMap, recursionCount + 1); }); } @@ -708,7 +708,7 @@ export function setTypeArgumentsRecursive(destType: Type, srcType: Type, typeVar case TypeCategory.Function: if (destType.specializedTypes) { - destType.specializedTypes.parameterTypes.forEach(paramType => { + destType.specializedTypes.parameterTypes.forEach((paramType) => { setTypeArgumentsRecursive(paramType, srcType, typeVarMap, recursionCount + 1); }); if (destType.specializedTypes.returnType) { @@ -720,7 +720,7 @@ export function setTypeArgumentsRecursive(destType: Type, srcType: Type, typeVar ); } } else { - destType.details.parameters.forEach(param => { + destType.details.parameters.forEach((param) => { setTypeArgumentsRecursive(param.type, srcType, typeVarMap, recursionCount + 1); }); if (destType.details.declaredReturnType) { @@ -735,7 +735,7 @@ export function setTypeArgumentsRecursive(destType: Type, srcType: Type, typeVar break; case TypeCategory.OverloadedFunction: - destType.overloads.forEach(subtype => { + destType.overloads.forEach((subtype) => { setTypeArgumentsRecursive(subtype, srcType, typeVarMap, recursionCount + 1); }); break; @@ -821,7 +821,7 @@ export function derivesFromClassRecursive(classType: ClassType, baseClassToFind: // and an "int", this method would strip off the "None" // and return only the "int". export function removeFalsinessFromType(type: Type): Type { - return doForSubtypes(type, subtype => { + return doForSubtypes(type, (subtype) => { if (subtype.category === TypeCategory.Object) { if (subtype.literalValue !== undefined) { // If the object is already definitely truthy, it's fine to @@ -851,7 +851,7 @@ export function removeFalsinessFromType(type: Type): Type { // method, this method would strip off the "Foo" // and return only the "None". export function removeTruthinessFromType(type: Type): Type { - return doForSubtypes(type, subtype => { + return doForSubtypes(type, (subtype) => { if (subtype.category === TypeCategory.Object) { if (subtype.literalValue !== undefined) { // If the object is already definitely falsy, it's fine to @@ -931,7 +931,7 @@ export function getDeclaredGeneratorReturnType(functionType: FunctionType): Type } export function convertClassToObject(type: Type): Type { - return doForSubtypes(type, subtype => { + return doForSubtypes(type, (subtype) => { if (subtype.category === TypeCategory.Class) { return ObjectType.create(subtype); } @@ -1014,7 +1014,7 @@ export function containsUnknown(type: Type, allowUnknownTypeArgsForClasses = fal // See if a function has an unknown type. if (type.category === TypeCategory.OverloadedFunction) { - return type.overloads.some(overload => { + return type.overloads.some((overload) => { return containsUnknown(overload, false, recursionCount + 1); }); } @@ -1052,7 +1052,7 @@ function _specializeClassType( // If type args were previously provided, specialize them. if (classType.typeArguments) { - newTypeArgs = classType.typeArguments.map(oldTypeArgType => { + newTypeArgs = classType.typeArguments.map((oldTypeArgType) => { const newTypeArgType = specializeType(oldTypeArgType, typeVarMap, makeConcrete, recursionLevel + 1); if (newTypeArgType !== oldTypeArgType) { specializationNeeded = true; @@ -1060,7 +1060,7 @@ function _specializeClassType( return newTypeArgType; }); } else { - ClassType.getTypeParameters(classType).forEach(typeParam => { + ClassType.getTypeParameters(classType).forEach((typeParam) => { let typeArgType: Type; if (typeVarMap && typeVarMap.get(typeParam.name)) { @@ -1111,13 +1111,13 @@ function _specializeOverloadedFunctionType( recursionLevel: number ): OverloadedFunctionType { // Specialize each of the functions in the overload. - const overloads = type.overloads.map(entry => + const overloads = type.overloads.map((entry) => _specializeFunctionType(entry, typeVarMap, makeConcrete, recursionLevel) ); // Construct a new overload with the specialized function types. const newOverloadType = OverloadedFunctionType.create(); - overloads.forEach(overload => { + overloads.forEach((overload) => { OverloadedFunctionType.addOverload(newOverloadType, overload); }); @@ -1141,7 +1141,7 @@ function _specializeFunctionType( const specializedParameters: SpecializedFunctionTypes = { parameterTypes: [], - returnType: specializedReturnType + returnType: specializedReturnType, }; for (let i = 0; i < functionType.details.parameters.length; i++) { @@ -1190,7 +1190,7 @@ export function requiresSpecialization(type: Type, recursionCount = 0): boolean } return ( - type.typeArguments.find(typeArg => requiresSpecialization(typeArg, recursionCount + 1)) !== + type.typeArguments.find((typeArg) => requiresSpecialization(typeArg, recursionCount + 1)) !== undefined ); } @@ -1233,11 +1233,13 @@ export function requiresSpecialization(type: Type, recursionCount = 0): boolean } case TypeCategory.OverloadedFunction: { - return type.overloads.find(overload => requiresSpecialization(overload, recursionCount + 1)) !== undefined; + return ( + type.overloads.find((overload) => requiresSpecialization(overload, recursionCount + 1)) !== undefined + ); } case TypeCategory.Union: { - return type.subtypes.find(type => requiresSpecialization(type, recursionCount + 1)) !== undefined; + return type.subtypes.find((type) => requiresSpecialization(type, recursionCount + 1)) !== undefined; } case TypeCategory.TypeVar: { @@ -1258,11 +1260,11 @@ export function computeMroLinearization(classType: ClassType): boolean { // Construct the list of class lists that need to be merged. const classListsToMerge: Type[][] = []; - classType.details.baseClasses.forEach(baseClass => { + classType.details.baseClasses.forEach((baseClass) => { if (baseClass.category === TypeCategory.Class) { const typeVarMap = buildTypeVarMapFromSpecializedClass(baseClass, false); classListsToMerge.push( - baseClass.details.mro.map(mroClass => { + baseClass.details.mro.map((mroClass) => { return specializeType(mroClass, typeVarMap); }) ); @@ -1272,7 +1274,7 @@ export function computeMroLinearization(classType: ClassType): boolean { }); classListsToMerge.push( - classType.details.baseClasses.map(baseClass => { + classType.details.baseClasses.map((baseClass) => { const typeVarMap = buildTypeVarMapFromSpecializedClass(classType, false); return specializeType(baseClass, typeVarMap); }) @@ -1286,10 +1288,10 @@ export function computeMroLinearization(classType: ClassType): boolean { // is found in the "tail" (i.e. in elements 1 through n) of any // of the class lists. const isInTail = (searchClass: ClassType, classLists: Type[][]) => { - return classLists.some(classList => { + return classLists.some((classList) => { return ( classList.findIndex( - value => + (value) => value.category === TypeCategory.Class && ClassType.isSameGenericClass(value, searchClass, false) ) > 0 ); @@ -1299,7 +1301,7 @@ export function computeMroLinearization(classType: ClassType): boolean { const filterClass = (classToFilter: ClassType, classLists: Type[][]) => { for (let i = 0; i < classLists.length; i++) { classLists[i] = classLists[i].filter( - value => + (value) => value.category !== TypeCategory.Class || !ClassType.isSameGenericClass(value, classToFilter, false) ); } diff --git a/server/src/analyzer/types.ts b/server/src/analyzer/types.ts index 8e38cbb76..aae082b3b 100644 --- a/server/src/analyzer/types.ts +++ b/server/src/analyzer/types.ts @@ -53,7 +53,7 @@ export const enum TypeCategory { Union, // Type variable (defined with TypeVar) - TypeVar + TypeVar, } export type Type = @@ -87,7 +87,7 @@ export interface UnboundType extends TypeBase { export namespace UnboundType { const _instance: UnboundType = { - category: TypeCategory.Unbound + category: TypeCategory.Unbound, }; export function create() { @@ -102,7 +102,7 @@ export interface UnknownType extends TypeBase { export namespace UnknownType { const _instance: UnknownType = { - category: TypeCategory.Unknown + category: TypeCategory.Unknown, }; export function create() { @@ -127,7 +127,7 @@ export namespace ModuleType { const newModuleType: ModuleType = { category: TypeCategory.Module, fields: symbolTable || new Map(), - loaderFields: new Map() + loaderFields: new Map(), }; return newModuleType; } @@ -208,7 +208,7 @@ export const enum ClassTypeFlags { // A class whose constructor (__init__ method) does not have // annotated types and is treated as though each parameter // is a generic type for purposes of type inference. - PseudoGenericClass = 1 << 12 + PseudoGenericClass = 1 << 12, } interface ClassDetails { @@ -251,9 +251,9 @@ export namespace ClassType { mro: [], fields: new Map(), typeParameters: [], - docString + docString, }, - skipAbstractClassTest: false + skipAbstractClassTest: false, }; return newClass; @@ -530,7 +530,7 @@ export namespace ObjectType { export function create(classType: ClassType) { const newObjectType: ObjectType = { category: TypeCategory.Object, - classType + classType, }; return newObjectType; } @@ -601,7 +601,7 @@ export const enum FunctionTypeFlags { Final = 1 << 12, // Function has one or more parameters that are missing type annotations - UnannotatedParams = 1 << 13 + UnannotatedParams = 1 << 13, } interface FunctionDetails { @@ -642,8 +642,8 @@ export namespace FunctionType { details: { flags, parameters: [], - docString - } + docString, + }, }; return newFunctionType; } @@ -660,7 +660,7 @@ export namespace FunctionType { declaredReturnType: type.details.declaredReturnType, declaration: type.details.declaration, builtInName: type.details.builtInName, - docString: type.details.docString + docString: type.details.docString, }; // If we strip off the first parameter, this is no longer an @@ -674,7 +674,7 @@ export namespace FunctionType { if (type.specializedTypes) { newFunction.specializedTypes = { parameterTypes: type.specializedTypes.parameterTypes.slice(startParam), - returnType: type.specializedTypes.returnType + returnType: type.specializedTypes.returnType, }; } @@ -794,7 +794,7 @@ export namespace OverloadedFunctionType { export function create() { const newType: OverloadedFunctionType = { category: TypeCategory.OverloadedFunction, - overloads: [] + overloads: [], }; return newType; } @@ -810,7 +810,7 @@ export interface NoneType extends TypeBase { export namespace NoneType { const _noneInstance: NoneType = { - category: TypeCategory.None + category: TypeCategory.None, }; export function create() { @@ -824,7 +824,7 @@ export interface NeverType extends TypeBase { export namespace NeverType { const _neverInstance: NeverType = { - category: TypeCategory.Never + category: TypeCategory.Never, }; export function create() { @@ -840,11 +840,11 @@ export interface AnyType extends TypeBase { export namespace AnyType { const _anyInstance: AnyType = { category: TypeCategory.Any, - isEllipsis: false + isEllipsis: false, }; const _ellipsisInstance: AnyType = { category: TypeCategory.Any, - isEllipsis: true + isEllipsis: true, }; export function create(isEllipsis = false) { @@ -861,7 +861,7 @@ export namespace UnionType { export function create() { const newUnionType: UnionType = { category: TypeCategory.Union, - subtypes: [] + subtypes: [], }; return newUnionType; @@ -876,7 +876,7 @@ export namespace UnionType { } export function containsType(unionType: UnionType, subtype: Type, recursionCount = 0): boolean { - return unionType.subtypes.find(t => isTypeSame(t, subtype, recursionCount + 1)) !== undefined; + return unionType.subtypes.find((t) => isTypeSame(t, subtype, recursionCount + 1)) !== undefined; } } @@ -901,7 +901,7 @@ export namespace TypeVarType { constraints: [], isCovariant: false, isContravariant: false, - isSynthesized + isSynthesized, }; return newTypeVarType; } @@ -921,7 +921,7 @@ export function isAnyOrUnknown(type: Type): boolean { } if (type.category === TypeCategory.Union) { - return type.subtypes.find(t => !isAnyOrUnknown(t)) === undefined; + return type.subtypes.find((t) => !isAnyOrUnknown(t)) === undefined; } return false; @@ -937,7 +937,7 @@ export function isPossiblyUnbound(type: Type): boolean { } if (type.category === TypeCategory.Union) { - return type.subtypes.find(t => isPossiblyUnbound(t)) !== undefined; + return type.subtypes.find((t) => isPossiblyUnbound(t)) !== undefined; } return false; @@ -1070,7 +1070,7 @@ export function isTypeSame(type1: Type, type2: Type, recursionCount = 0): boolea // The types do not have a particular order, so we need to // do the comparison in an order-independent manner. - return subtypes1.find(t => !UnionType.containsType(unionType2, t, recursionCount + 1)) === undefined; + return subtypes1.find((t) => !UnionType.containsType(unionType2, t, recursionCount + 1)) === undefined; } case TypeCategory.TypeVar: { @@ -1163,7 +1163,7 @@ export function removeNoneFromUnion(type: Type): Type { export function removeFromUnion(type: Type, removeFilter: (type: Type) => boolean) { if (type.category === TypeCategory.Union) { - const remainingTypes = type.subtypes.filter(t => !removeFilter(t)); + const remainingTypes = type.subtypes.filter((t) => !removeFilter(t)); if (remainingTypes.length < type.subtypes.length) { return combineTypes(remainingTypes); } @@ -1178,7 +1178,7 @@ export function removeFromUnion(type: Type, removeFilter: (type: Type) => boolea // If no types remain in the end, a NeverType is returned. export function combineTypes(types: Type[]): Type { // Filter out any "Never" types. - types = types.filter(type => type.category !== TypeCategory.Never); + types = types.filter((type) => type.category !== TypeCategory.Never); if (types.length === 0) { return NeverType.create(); } diff --git a/server/src/commands/commands.ts b/server/src/commands/commands.ts index faf6670b4..c7505fa40 100644 --- a/server/src/commands/commands.ts +++ b/server/src/commands/commands.ts @@ -11,5 +11,5 @@ export const enum Commands { createTypeStub = 'pyright.createtypestub', restartServer = 'pyright.restartserver', orderImports = 'pyright.organizeimports', - addMissingOptionalToParam = 'pyright.addoptionalforparam' + addMissingOptionalToParam = 'pyright.addoptionalforparam', } diff --git a/server/src/commands/createTypeStub.ts b/server/src/commands/createTypeStub.ts index b1d248d94..5f1a4b122 100644 --- a/server/src/commands/createTypeStub.ts +++ b/server/src/commands/createTypeStub.ts @@ -30,10 +30,10 @@ export class CreateTypeStubCommand implements ServerCommand { rootPath: workspaceRoot, rootUri: convertPathToUri(workspaceRoot), serviceInstance: service, - disableLanguageServices: true + disableLanguageServices: true, }; - service.setCompletionCallback(results => { + service.setCompletionCallback((results) => { if (results.filesRequiringAnalysis === 0) { try { service.writeTypeStub(token); @@ -72,7 +72,7 @@ export class CreateTypeStubCommand implements ServerCommand { service.setMaxAnalysisDuration({ openFilesTimeInMs: 500, - noOpenFilesTimeInMs: 500 + noOpenFilesTimeInMs: 500, }); return service; diff --git a/server/src/commands/quickActionCommand.ts b/server/src/commands/quickActionCommand.ts index 8794162bd..eca66eb86 100644 --- a/server/src/commands/quickActionCommand.ts +++ b/server/src/commands/quickActionCommand.ts @@ -30,10 +30,10 @@ export class QuickActionCommand implements ServerCommand { } const edits: TextEdit[] = []; - editActions.forEach(editAction => { + editActions.forEach((editAction) => { edits.push({ range: editAction.range, - newText: editAction.replacementText + newText: editAction.replacementText, }); }); diff --git a/server/src/common/cancellationUtils.ts b/server/src/common/cancellationUtils.ts index 249188d9b..26b7f1be2 100644 --- a/server/src/common/cancellationUtils.ts +++ b/server/src/common/cancellationUtils.ts @@ -19,7 +19,7 @@ import { Emitter, ErrorCodes, Event, - ResponseError + ResponseError, } from 'vscode-languageserver'; class CancellationThrottle { diff --git a/server/src/common/collectionUtils.ts b/server/src/common/collectionUtils.ts index d8b4be963..540f50e46 100644 --- a/server/src/common/collectionUtils.ts +++ b/server/src/common/collectionUtils.ts @@ -166,7 +166,7 @@ function indicesOf(array: readonly unknown[]): number[] { export function stableSort(array: readonly T[], comparer: Comparer): SortedReadonlyArray { const indices = indicesOf(array); stableSortIndices(array, indices, comparer); - return (indices.map(i => array[i]) as SortedArray) as SortedReadonlyArray; + return (indices.map((i) => array[i]) as SortedArray) as SortedReadonlyArray; } function stableSortIndices(array: readonly T[], indices: number[], comparer: Comparer) { diff --git a/server/src/common/configOptions.ts b/server/src/common/configOptions.ts index 402e13677..731d474d2 100644 --- a/server/src/common/configOptions.ts +++ b/server/src/common/configOptions.ts @@ -176,7 +176,7 @@ export function getBooleanDiagnosticSettings() { return [ DiagnosticRule.strictListInference, DiagnosticRule.strictDictionaryInference, - DiagnosticRule.strictParameterNoneValue + DiagnosticRule.strictParameterNoneValue, // Do not include this this one because we don't // want to override it in strict mode or support @@ -221,7 +221,7 @@ export function getDiagLevelSettings() { DiagnosticRule.reportUnnecessaryCast, DiagnosticRule.reportAssertAlwaysTrue, DiagnosticRule.reportSelfClsParameterName, - DiagnosticRule.reportImplicitStringConcatenation + DiagnosticRule.reportImplicitStringConcatenation, ]; } @@ -265,7 +265,7 @@ export function getStrictDiagnosticSettings(): DiagnosticSettings { reportUnnecessaryCast: 'error', reportAssertAlwaysTrue: 'error', reportSelfClsParameterName: 'error', - reportImplicitStringConcatenation: 'none' + reportImplicitStringConcatenation: 'none', }; return diagSettings; @@ -311,7 +311,7 @@ export function getDefaultDiagnosticSettings(): DiagnosticSettings { reportUnnecessaryCast: 'none', reportAssertAlwaysTrue: 'warning', reportSelfClsParameterName: 'warning', - reportImplicitStringConcatenation: 'none' + reportImplicitStringConcatenation: 'none', }; return diagSettings; @@ -411,7 +411,7 @@ export class ConfigOptions { // If no matching execution environment can be found, a default // execution environment is used. findExecEnvironment(filePath: string): ExecutionEnvironment { - let execEnv = this.executionEnvironments.find(env => { + let execEnv = this.executionEnvironments.find((env) => { const envRoot = ensureTrailingDirectorySeparator(normalizePath(combinePaths(this.projectRoot, env.root))); return filePath.startsWith(envRoot); }); @@ -792,7 +792,7 @@ export class ConfigOptions { configObj.reportImplicitStringConcatenation, DiagnosticRule.reportImplicitStringConcatenation, defaultSettings.reportImplicitStringConcatenation - ) + ), }; // Read the "venvPath". diff --git a/server/src/common/core.ts b/server/src/common/core.ts index de1bd9091..1e1f25067 100644 --- a/server/src/common/core.ts +++ b/server/src/common/core.ts @@ -11,7 +11,7 @@ export const enum Comparison { LessThan = -1, EqualTo = 0, - GreaterThan = 1 + GreaterThan = 1, } /** diff --git a/server/src/common/diagnostic.ts b/server/src/common/diagnostic.ts index 0615ba33d..98c8c47e6 100644 --- a/server/src/common/diagnostic.ts +++ b/server/src/common/diagnostic.ts @@ -13,7 +13,7 @@ import { Range } from './textRange'; export const enum DiagnosticCategory { Error, Warning, - UnusedCode + UnusedCode, } export interface DiagnosticAction { @@ -127,6 +127,6 @@ export class DiagnosticAddendum { // Prepend indentation for readability. Skip if there are no // messages at this level. const extraSpace = this._messages.length > 0 ? ' ' : ''; - return this._messages.concat(childLines).map(line => extraSpace + line); + return this._messages.concat(childLines).map((line) => extraSpace + line); } } diff --git a/server/src/common/diagnosticRules.ts b/server/src/common/diagnosticRules.ts index a03e23e06..a16d75913 100644 --- a/server/src/common/diagnosticRules.ts +++ b/server/src/common/diagnosticRules.ts @@ -48,5 +48,5 @@ export const enum DiagnosticRule { reportUnnecessaryCast = 'reportUnnecessaryCast', reportAssertAlwaysTrue = 'reportAssertAlwaysTrue', reportSelfClsParameterName = 'reportSelfClsParameterName', - reportImplicitStringConcatenation = 'reportImplicitStringConcatenation' + reportImplicitStringConcatenation = 'reportImplicitStringConcatenation', } diff --git a/server/src/common/diagnosticSink.ts b/server/src/common/diagnosticSink.ts index 20784c6c7..e65c2e799 100644 --- a/server/src/common/diagnosticSink.ts +++ b/server/src/common/diagnosticSink.ts @@ -65,11 +65,11 @@ export class DiagnosticSink { } getErrors() { - return this._diagnosticList.filter(diag => diag.category === DiagnosticCategory.Error); + return this._diagnosticList.filter((diag) => diag.category === DiagnosticCategory.Error); } getWarnings() { - return this._diagnosticList.filter(diag => diag.category === DiagnosticCategory.Warning); + return this._diagnosticList.filter((diag) => diag.category === DiagnosticCategory.Warning); } } diff --git a/server/src/common/extensions.ts b/server/src/common/extensions.ts index 8812e71cf..59a9103d1 100644 --- a/server/src/common/extensions.ts +++ b/server/src/common/extensions.ts @@ -10,6 +10,6 @@ /* eslint-disable @typescript-eslint/no-empty-function */ // Explicitly tells that promise should be run asynchronously. -Promise.prototype.ignoreErrors = function(this: Promise) { +Promise.prototype.ignoreErrors = function (this: Promise) { this.catch(() => {}); }; diff --git a/server/src/common/fileSystem.ts b/server/src/common/fileSystem.ts index 7afaa1ec3..88d05c6c6 100644 --- a/server/src/common/fileSystem.ts +++ b/server/src/common/fileSystem.ts @@ -70,7 +70,7 @@ class LowLevelWatcher implements FileWatcher { constructor(private paths: string[]) {} close(): void { - this.paths.forEach(p => fs.unwatchFile(p)); + this.paths.forEach((p) => fs.unwatchFile(p)); } } @@ -126,7 +126,7 @@ class RealFileSystem implements FileSystem { recursive?: boolean, listener?: (event: string, filename: string) => void ): FileWatcher { - paths.forEach(p => { + paths.forEach((p) => { fs.watch(p, { recursive: recursive }, listener); }); @@ -146,7 +146,7 @@ class RealFileSystem implements FileSystem { followSymlinks: true, // this is the default of chokidar and supports file events through symlinks interval: 1000, // while not used in normal cases, if any error causes chokidar to fallback to polling, increase its intervals binaryInterval: 1000, - disableGlobbing: true // fix https://github.com/Microsoft/vscode/issues/4586 + disableGlobbing: true, // fix https://github.com/Microsoft/vscode/issues/4586 }; if (_isMacintosh) { @@ -157,7 +157,7 @@ class RealFileSystem implements FileSystem { const excludes: string[] = []; if (_isMacintosh || _isLinux) { - if (paths.some(path => path === '' || path === '/')) { + if (paths.some((path) => path === '' || path === '/')) { excludes.push('/dev/**'); if (_isLinux) { excludes.push('/proc/**', '/sys/**'); @@ -167,7 +167,7 @@ class RealFileSystem implements FileSystem { watcherOptions.ignored = excludes; const watcher = chokidar.watch(paths, watcherOptions); - watcher.on('error', _ => { + watcher.on('error', (_) => { this._console.log('Error returned from file system watcher.'); }); diff --git a/server/src/common/pathUtils.ts b/server/src/common/pathUtils.ts index 051d963f6..4029b6445 100644 --- a/server/src/common/pathUtils.ts +++ b/server/src/common/pathUtils.ts @@ -20,7 +20,7 @@ import { compareStringsCaseSensitive, equateStringsCaseInsensitive, equateStringsCaseSensitive, - getStringComparer + getStringComparer, } from './stringUtils'; export interface FileSpec { @@ -601,7 +601,7 @@ export function getWildcardRegexPattern(rootPath: string, fileSpec: string): str component = escapedSeparator + component; } - regExPattern += component.replace(reservedCharacterPattern, match => { + regExPattern += component.replace(reservedCharacterPattern, (match) => { if (match === '*') { return `[^${escapedSeparator}]*`; } else if (match === '?') { @@ -666,7 +666,7 @@ export function getFileSpec(rootPath: string, fileSpec: string): FileSpec { return { wildcardRoot, - regExp + regExp, }; } @@ -807,7 +807,7 @@ function getPathComponentsRelativeTo( const enum FileSystemEntryKind { File, - Directory + Directory, } function fileSystemEntryExists(fs: FileSystem, path: string, entryKind: FileSystemEntryKind): boolean { diff --git a/server/src/common/positionUtils.ts b/server/src/common/positionUtils.ts index 44e94f40f..91b931a8a 100644 --- a/server/src/common/positionUtils.ts +++ b/server/src/common/positionUtils.ts @@ -18,7 +18,7 @@ export function convertOffsetToPosition(offset: number, lines: TextRangeCollecti if (lines.end === 0) { return { line: 0, - character: 0 + character: 0, }; } @@ -33,7 +33,7 @@ export function convertOffsetToPosition(offset: number, lines: TextRangeCollecti assert(lineRange !== undefined); return { line: itemIndex, - character: offset - lineRange.start + character: offset - lineRange.start, }; } diff --git a/server/src/common/pythonVersion.ts b/server/src/common/pythonVersion.ts index d8d5342c0..3e087682c 100644 --- a/server/src/common/pythonVersion.ts +++ b/server/src/common/pythonVersion.ts @@ -24,7 +24,7 @@ export enum PythonVersion { V35 = 0x0305, V36 = 0x0306, V37 = 0x0307, - V38 = 0x0308 + V38 = 0x0308, } export const latestStablePythonVersion = PythonVersion.V38; diff --git a/server/src/common/textRange.ts b/server/src/common/textRange.ts index cc4d0fefe..3a02f858f 100644 --- a/server/src/common/textRange.ts +++ b/server/src/common/textRange.ts @@ -44,7 +44,7 @@ export namespace TextRange { export function extend(range: TextRange, extension: TextRange | TextRange[] | undefined) { if (extension) { if (Array.isArray(extension)) { - extension.forEach(r => { + extension.forEach((r) => { extend(range, r); }); } else { @@ -94,7 +94,7 @@ export function comparePositions(a: Position, b: Position) { export function getEmptyPosition(): Position { return { line: 0, - character: 0 + character: 0, }; } @@ -118,6 +118,6 @@ export function rangesAreEqual(a: Range, b: Range) { export function getEmptyRange(): Range { return { start: getEmptyPosition(), - end: getEmptyPosition() + end: getEmptyPosition(), }; } diff --git a/server/src/languageServerBase.ts b/server/src/languageServerBase.ts index aef13306a..1153b935c 100644 --- a/server/src/languageServerBase.ts +++ b/server/src/languageServerBase.ts @@ -34,7 +34,7 @@ import { SymbolInformation, TextDocumentSyncKind, TextEdit, - WorkspaceEdit + WorkspaceEdit, } from 'vscode-languageserver'; import { ImportResolver } from './analyzer/importResolver'; @@ -137,7 +137,7 @@ export abstract class LanguageServerBase implements LanguageServerInterface { const scopeUri = workspace.rootUri ? workspace.rootUri : undefined; const item: ConfigurationItem = { scopeUri, - section + section, }; return this._connection.workspace.getConfiguration(item); } @@ -184,10 +184,10 @@ export abstract class LanguageServerBase implements LanguageServerInterface { // reporting results. This will keep it responsive. service.setMaxAnalysisDuration({ openFilesTimeInMs: 50, - noOpenFilesTimeInMs: 200 + noOpenFilesTimeInMs: 200, }); - service.setCompletionCallback(results => this.onAnalysisCompletedHandler(results)); + service.setCompletionCallback((results) => this.onAnalysisCompletedHandler(results)); return service; } @@ -197,13 +197,13 @@ export abstract class LanguageServerBase implements LanguageServerInterface { } reanalyze() { - this._workspaceMap.forEach(workspace => { + this._workspaceMap.forEach((workspace) => { workspace.serviceInstance.invalidateAndForceReanalysis(); }); } restart() { - this._workspaceMap.forEach(workspace => { + this._workspaceMap.forEach((workspace) => { workspace.serviceInstance.restart(); }); } @@ -221,14 +221,14 @@ export abstract class LanguageServerBase implements LanguageServerInterface { // Create a service instance for each of the workspace folders. if (params.workspaceFolders) { - params.workspaceFolders.forEach(folder => { + params.workspaceFolders.forEach((folder) => { const path = convertUriToPath(folder.uri); this._workspaceMap.set(path, { workspaceName: folder.name, rootPath: path, rootUri: folder.uri, serviceInstance: this.createAnalyzerService(folder.name), - disableLanguageServices: false + disableLanguageServices: false, }); }); } else if (params.rootPath) { @@ -237,7 +237,7 @@ export abstract class LanguageServerBase implements LanguageServerInterface { rootPath: params.rootPath, rootUri: '', serviceInstance: this.createAnalyzerService(params.rootPath), - disableLanguageServices: false + disableLanguageServices: false, }); } @@ -254,20 +254,20 @@ export abstract class LanguageServerBase implements LanguageServerInterface { renameProvider: true, completionProvider: { triggerCharacters: ['.', '['], - resolveProvider: true + resolveProvider: true, }, signatureHelpProvider: { - triggerCharacters: ['(', ',', ')'] + triggerCharacters: ['(', ',', ')'], }, codeActionProvider: { - codeActionKinds: [CodeActionKind.QuickFix, CodeActionKind.SourceOrganizeImports] - } - } + codeActionKinds: [CodeActionKind.QuickFix, CodeActionKind.SourceOrganizeImports], + }, + }, }; } ); - this._connection.onDidChangeConfiguration(params => { + this._connection.onDidChangeConfiguration((params) => { this._connection.console.log(`Received updated settings`); if (params?.settings) { this._defaultClientConfig = params?.settings; @@ -284,7 +284,7 @@ export abstract class LanguageServerBase implements LanguageServerInterface { const position: Position = { line: params.position.line, - character: params.position.character + character: params.position.character, }; const workspace = this._workspaceMap.getWorkspaceForFile(filePath); @@ -295,7 +295,7 @@ export abstract class LanguageServerBase implements LanguageServerInterface { if (!locations) { return undefined; } - return locations.map(loc => Location.create(convertPathToUri(loc.path), loc.range)); + return locations.map((loc) => Location.create(convertPathToUri(loc.path), loc.range)); }); this._connection.onReferences((params, token) => { @@ -303,7 +303,7 @@ export abstract class LanguageServerBase implements LanguageServerInterface { const position: Position = { line: params.position.line, - character: params.position.character + character: params.position.character, }; const workspace = this._workspaceMap.getWorkspaceForFile(filePath); @@ -319,7 +319,7 @@ export abstract class LanguageServerBase implements LanguageServerInterface { if (!locations) { return undefined; } - return locations.map(loc => Location.create(convertPathToUri(loc.path), loc.range)); + return locations.map((loc) => Location.create(convertPathToUri(loc.path), loc.range)); }); this._connection.onDocumentSymbol((params, token) => { @@ -340,7 +340,7 @@ export abstract class LanguageServerBase implements LanguageServerInterface { this._connection.onWorkspaceSymbol((params, token) => { const symbolList: SymbolInformation[] = []; - this._workspaceMap.forEach(workspace => { + this._workspaceMap.forEach((workspace) => { if (!workspace.disableLanguageServices) { workspace.serviceInstance.addSymbolsForWorkspace(symbolList, params.query, token); } @@ -354,7 +354,7 @@ export abstract class LanguageServerBase implements LanguageServerInterface { const position: Position = { line: params.position.line, - character: params.position.character + character: params.position.character, }; const workspace = this._workspaceMap.getWorkspaceForFile(filePath); @@ -367,7 +367,7 @@ export abstract class LanguageServerBase implements LanguageServerInterface { const position: Position = { line: params.position.line, - character: params.position.character + character: params.position.character, }; const workspace = this._workspaceMap.getWorkspaceForFile(filePath); @@ -384,10 +384,10 @@ export abstract class LanguageServerBase implements LanguageServerInterface { } return { - signatures: signatureHelpResults.signatures.map(sig => { + signatures: signatureHelpResults.signatures.map((sig) => { let paramInfo: ParameterInformation[] = []; if (sig.parameters) { - paramInfo = sig.parameters.map(param => { + paramInfo = sig.parameters.map((param) => { return ParameterInformation.create( [param.startOffset, param.endOffset], param.documentation @@ -399,7 +399,7 @@ export abstract class LanguageServerBase implements LanguageServerInterface { activeSignature: signatureHelpResults.activeSignature !== undefined ? signatureHelpResults.activeSignature : null, activeParameter: - signatureHelpResults.activeParameter !== undefined ? signatureHelpResults.activeParameter : null + signatureHelpResults.activeParameter !== undefined ? signatureHelpResults.activeParameter : null, }; }); @@ -408,7 +408,7 @@ export abstract class LanguageServerBase implements LanguageServerInterface { const position: Position = { line: params.position.line, - character: params.position.character + character: params.position.character, }; const workspace = this._workspaceMap.getWorkspaceForFile(filePath); @@ -450,7 +450,7 @@ export abstract class LanguageServerBase implements LanguageServerInterface { const position: Position = { line: params.position.line, - character: params.position.character + character: params.position.character, }; const workspace = this._workspaceMap.getWorkspaceForFile(filePath); @@ -469,9 +469,9 @@ export abstract class LanguageServerBase implements LanguageServerInterface { } const edits: WorkspaceEdit = { - changes: {} + changes: {}, }; - editActions.forEach(editAction => { + editActions.forEach((editAction) => { const uri = convertPathToUri(editAction.filePath); if (edits.changes![uri] === undefined) { edits.changes![uri] = []; @@ -479,7 +479,7 @@ export abstract class LanguageServerBase implements LanguageServerInterface { const textEdit: TextEdit = { range: editAction.range, - newText: editAction.replacementText + newText: editAction.replacementText, }; edits.changes![uri].push(textEdit); }); @@ -487,13 +487,13 @@ export abstract class LanguageServerBase implements LanguageServerInterface { return edits; }); - this._connection.onDidOpenTextDocument(params => { + this._connection.onDidOpenTextDocument((params) => { const filePath = convertUriToPath(params.textDocument.uri); const service = this._workspaceMap.getWorkspaceForFile(filePath).serviceInstance; service.setFileOpened(filePath, params.textDocument.version, params.textDocument.text); }); - this._connection.onDidChangeTextDocument(params => { + this._connection.onDidChangeTextDocument((params) => { this.recordUserInteractionTime(); const filePath = convertUriToPath(params.textDocument.uri); @@ -501,27 +501,27 @@ export abstract class LanguageServerBase implements LanguageServerInterface { service.updateOpenFileContents(filePath, params.textDocument.version, params.contentChanges[0].text); }); - this._connection.onDidCloseTextDocument(params => { + this._connection.onDidCloseTextDocument((params) => { const filePath = convertUriToPath(params.textDocument.uri); const service = this._workspaceMap.getWorkspaceForFile(filePath).serviceInstance; service.setFileClosed(filePath); }); this._connection.onInitialized(() => { - this._connection.workspace.onDidChangeWorkspaceFolders(event => { - event.removed.forEach(workspace => { + this._connection.workspace.onDidChangeWorkspaceFolders((event) => { + event.removed.forEach((workspace) => { const rootPath = convertUriToPath(workspace.uri); this._workspaceMap.delete(rootPath); }); - event.added.forEach(async workspace => { + event.added.forEach(async (workspace) => { const rootPath = convertUriToPath(workspace.uri); const newWorkspace: WorkspaceServiceInstance = { workspaceName: workspace.name, rootPath, rootUri: workspace.uri, serviceInstance: this.createAnalyzerService(workspace.name), - disableLanguageServices: false + disableLanguageServices: false, }; this._workspaceMap.set(rootPath, newWorkspace); await this.updateSettingsForWorkspace(newWorkspace); @@ -533,19 +533,19 @@ export abstract class LanguageServerBase implements LanguageServerInterface { } updateSettingsForAllWorkspaces(): void { - this._workspaceMap.forEach(workspace => { + this._workspaceMap.forEach((workspace) => { this.updateSettingsForWorkspace(workspace).ignoreErrors(); }); } protected onAnalysisCompletedHandler(results: AnalysisResults): void { - results.diagnostics.forEach(fileDiag => { + results.diagnostics.forEach((fileDiag) => { const diagnostics = this._convertDiagnostics(fileDiag.diagnostics); // Send the computed diagnostics to the client. this._connection.sendDiagnostics({ uri: convertPathToUri(fileDiag.filePath), - diagnostics + diagnostics, }); if (results.filesRequiringAnalysis > 0) { @@ -590,7 +590,7 @@ export abstract class LanguageServerBase implements LanguageServerInterface { } private _convertDiagnostics(diags: AnalyzerDiagnostic[]): Diagnostic[] { - return diags.map(diag => { + return diags.map((diag) => { const severity = diag.category === DiagnosticCategory.Error ? DiagnosticSeverity.Error : DiagnosticSeverity.Warning; @@ -609,7 +609,7 @@ export abstract class LanguageServerBase implements LanguageServerInterface { const relatedInfo = diag.getRelatedInfo(); if (relatedInfo.length > 0) { - vsDiag.relatedInformation = relatedInfo.map(info => { + vsDiag.relatedInformation = relatedInfo.map((info) => { return DiagnosticRelatedInformation.create( Location.create(convertPathToUri(info.filePath), info.range), info.message @@ -625,7 +625,7 @@ export abstract class LanguageServerBase implements LanguageServerInterface { // Tell all of the services that the user is actively // interacting with one or more editors, so they should // back off from performing any work. - this._workspaceMap.forEach(workspace => { + this._workspaceMap.forEach((workspace) => { workspace.serviceInstance.recordUserInteractionTime(); }); } diff --git a/server/src/languageService/codeActionProvider.ts b/server/src/languageService/codeActionProvider.ts index 7e95a5be3..93200bc9c 100644 --- a/server/src/languageService/codeActionProvider.ts +++ b/server/src/languageService/codeActionProvider.ts @@ -30,15 +30,15 @@ export class CodeActionProvider { if (!workspace.disableLanguageServices) { const diags = workspace.serviceInstance.getDiagnosticsForRange(filePath, range); - const typeStubDiag = diags.find(d => { + const typeStubDiag = diags.find((d) => { const actions = d.getActions(); - return actions && actions.find(a => a.action === Commands.createTypeStub); + return actions && actions.find((a) => a.action === Commands.createTypeStub); }); if (typeStubDiag) { const action = typeStubDiag .getActions()! - .find(a => a.action === Commands.createTypeStub) as CreateTypeStubFileAction; + .find((a) => a.action === Commands.createTypeStub) as CreateTypeStubFileAction; if (action) { const createTypeStubAction = CodeAction.create( `Create Type Stub For "${action.moduleName}"`, @@ -55,15 +55,15 @@ export class CodeActionProvider { } } - const addOptionalDiag = diags.find(d => { + const addOptionalDiag = diags.find((d) => { const actions = d.getActions(); - return actions && actions.find(a => a.action === Commands.addMissingOptionalToParam); + return actions && actions.find((a) => a.action === Commands.addMissingOptionalToParam); }); if (addOptionalDiag) { const action = addOptionalDiag .getActions()! - .find(a => a.action === Commands.addMissingOptionalToParam) as AddMissingOptionalToParamAction; + .find((a) => a.action === Commands.addMissingOptionalToParam) as AddMissingOptionalToParamAction; if (action) { const addMissingOptionalAction = CodeAction.create( `Add "Optional" to type annotation`, diff --git a/server/src/languageService/completionProvider.ts b/server/src/languageService/completionProvider.ts index e8b61caf1..c1af44dcf 100644 --- a/server/src/languageService/completionProvider.ts +++ b/server/src/languageService/completionProvider.ts @@ -15,7 +15,7 @@ import { CompletionList, MarkupKind, Range, - TextEdit + TextEdit, } from 'vscode-languageserver'; import { ImportLookup } from '../analyzer/analyzerFileInfo'; @@ -52,7 +52,7 @@ import { ParameterCategory, ParseNode, ParseNodeType, - StringNode + StringNode, } from '../parser/parseNodes'; import { ParseResults } from '../parser/parser'; @@ -93,7 +93,7 @@ const _keywords: string[] = [ 'return', 'try', 'while', - 'yield' + 'yield', ]; enum SortCategory { @@ -135,7 +135,7 @@ enum SortCategory { DunderSymbol, // An auto-import symbol. - AutoImport + AutoImport, } // Completion items can have arbitrary data hanging off them. @@ -330,7 +330,7 @@ export class CompletionProvider { } const curIndex = CompletionProvider._mostRecentCompletions.findIndex( - item => item.label === label && item.autoImportText === autoImportText + (item) => item.label === label && item.autoImportText === autoImportText ); if (curIndex > 0) { @@ -459,7 +459,7 @@ export class CompletionProvider { if (isSimilar) { const range: Range = { start: { line: this._position.line, character: this._position.character - partialName.length }, - end: { line: this._position.line, character: this._position.character } + end: { line: this._position.line, character: this._position.character }, }; const methodSignature = this._printMethodSignature(decl.node) + ':'; @@ -474,7 +474,7 @@ export class CompletionProvider { private _printMethodSignature(node: FunctionNode): string { const paramList = node.parameters - .map(param => { + .map((param) => { let paramString = ''; if (param.category === ParameterCategory.VarArgList) { paramString += '*'; @@ -508,7 +508,7 @@ export class CompletionProvider { const symbolTable = new Map(); if (leftType) { - doForSubtypes(leftType, subtype => { + doForSubtypes(leftType, (subtype) => { if (subtype.category === TypeCategory.Object) { getMembersForClass(subtype.classType, symbolTable, true); } else if (subtype.category === TypeCategory.Class) { @@ -522,7 +522,7 @@ export class CompletionProvider { } const completionList = CompletionList.create(); - this._addSymbolsForSymbolTable(symbolTable, _ => true, priorWord, completionList); + this._addSymbolsForSymbolTable(symbolTable, (_) => true, priorWord, completionList); return completionList; } @@ -558,7 +558,7 @@ export class CompletionProvider { this._addSymbols(parseNode, priorWord, completionList); // Add keywords. - this._findMatchingKeywords(_keywords, priorWord).map(keyword => { + this._findMatchingKeywords(_keywords, priorWord).map((keyword) => { const completionItem = CompletionItem.create(keyword); completionItem.kind = CompletionItemKind.Keyword; completionList.items.push(completionItem); @@ -628,7 +628,7 @@ export class CompletionProvider { postText: string, completionList: CompletionList ) { - signatureInfo.signatures.forEach(signature => { + signatureInfo.signatures.forEach((signature) => { if (!signature.activeParam) { return undefined; } @@ -653,7 +653,7 @@ export class CompletionProvider { completionList: CompletionList ) { const quoteValue = this._getQuoteValueFromPriorText(priorText); - doForSubtypes(type, subtype => { + doForSubtypes(type, (subtype) => { if (subtype.category === TypeCategory.Object) { if (ClassType.isBuiltIn(subtype.classType, 'str')) { if (subtype.literalValue !== undefined) { @@ -817,7 +817,7 @@ export class CompletionProvider { const range: Range = { start: { line: this._position.line, character: rangeStartCol }, - end: { line: this._position.line, character: rangeEndCol } + end: { line: this._position.line, character: rangeEndCol }, }; completionItem.textEdit = TextEdit.replace(range, valueWithQuotes); @@ -850,7 +850,7 @@ export class CompletionProvider { // this name, don't add an auto-import suggestion with // the same name. const localDuplicate = completionList.items.find( - item => item.label === name && !item.data.autoImport + (item) => item.label === name && !item.data.autoImport ); const declarations = symbol.getDeclarations(); if (declarations && declarations.length > 0 && localDuplicate === undefined) { @@ -904,7 +904,7 @@ export class CompletionProvider { if (moduleNameAndType.moduleName) { const autoImportText = `Auto-import from ${moduleNameAndType.moduleName}`; - const isDuplicateEntry = completionList.items.find(item => { + const isDuplicateEntry = completionList.items.find((item) => { if (item.label === name) { // Don't add if there's already a local completion suggestion. if (!item.data.autoImport) { @@ -1002,9 +1002,9 @@ export class CompletionProvider { if (lookupResults) { this._addSymbolsForSymbolTable( lookupResults.symbolTable, - name => { + (name) => { // Don't suggest symbols that have already been imported. - return !importFromNode.imports.find(imp => imp.name.value === name); + return !importFromNode.imports.find((imp) => imp.name.value === name); }, priorWord, completionList @@ -1012,8 +1012,8 @@ export class CompletionProvider { } // Add the implicit imports. - importInfo.implicitImports.forEach(implImport => { - if (!importFromNode.imports.find(imp => imp.name.value === implImport.name)) { + importInfo.implicitImports.forEach((implImport) => { + if (!importFromNode.imports.find((imp) => imp.name.value === implImport.name)) { this._addNameToCompletionList(implImport.name, CompletionItemKind.Module, priorWord, completionList); } }); @@ -1022,7 +1022,7 @@ export class CompletionProvider { } private _findMatchingKeywords(keywordList: string[], partialMatch: string): string[] { - return keywordList.filter(keyword => { + return keywordList.filter((keyword) => { if (partialMatch) { return StringUtils.computeCompletionSimilarity(partialMatch, keyword) > similarityLimit; } else { @@ -1034,19 +1034,19 @@ export class CompletionProvider { private _addNamedParameters(signatureInfo: CallSignatureInfo, priorWord: string, completionList: CompletionList) { const argNameMap = new Map(); - signatureInfo.signatures.forEach(signature => { + signatureInfo.signatures.forEach((signature) => { this._addNamedParametersToMap(signature.type, argNameMap); }); // Remove any named parameters that are already provided. - signatureInfo.callNode.arguments!.forEach(arg => { + signatureInfo.callNode.arguments!.forEach((arg) => { if (arg.name) { argNameMap.delete(arg.name.value); } }); // Add the remaining unique parameter names to the completion list. - argNameMap.forEach(argName => { + argNameMap.forEach((argName) => { const similarity = StringUtils.computeCompletionSimilarity(priorWord, argName); if (similarity > similarityLimit) { @@ -1056,7 +1056,7 @@ export class CompletionProvider { const completionItemData: CompletionItemData = { workspacePath: this._workspacePath, filePath: this._filePath, - position: this._position + position: this._position, }; completionItem.data = completionItemData; completionItem.sortText = this._makeSortText(SortCategory.NamedParameter, argName); @@ -1067,7 +1067,7 @@ export class CompletionProvider { } private _addNamedParametersToMap(type: FunctionType, paramMap: Map) { - type.details.parameters.forEach(param => { + type.details.parameters.forEach((param) => { if (param.name && !param.isNameSynthesized) { // Don't add private or protected names. These are assumed // not to be named parameters. @@ -1160,7 +1160,7 @@ export class CompletionProvider { case DeclarationType.Function: if (type.category === TypeCategory.OverloadedFunction) { typeDetail = type.overloads - .map(overload => name + this._evaluator.printType(overload)) + .map((overload) => name + this._evaluator.printType(overload)) .join('\n'); } else { typeDetail = name + ': ' + this._evaluator.printType(type); @@ -1208,7 +1208,7 @@ export class CompletionProvider { if (markdownString) { this._itemToResolve.documentation = { kind: MarkupKind.Markdown, - value: markdownString + value: markdownString, }; } } @@ -1275,7 +1275,7 @@ export class CompletionProvider { const completionItemData: CompletionItemData = { workspacePath: this._workspacePath, filePath: this._filePath, - position: this._position + position: this._position, }; completionItem.data = completionItemData; @@ -1319,7 +1319,7 @@ export class CompletionProvider { if (markdownString) { completionItem.documentation = { kind: MarkupKind.Markdown, - value: markdownString + value: markdownString, }; } @@ -1328,13 +1328,13 @@ export class CompletionProvider { } if (additionalTextEdits) { - completionItem.additionalTextEdits = additionalTextEdits.map(te => { + completionItem.additionalTextEdits = additionalTextEdits.map((te) => { const textEdit: TextEdit = { range: { start: { line: te.range.start.line, character: te.range.start.character }, - end: { line: te.range.end.line, character: te.range.end.character } + end: { line: te.range.end.line, character: te.range.end.character }, }, - newText: te.replacementText + newText: te.replacementText, }; return textEdit; }); @@ -1346,7 +1346,7 @@ export class CompletionProvider { private _getRecentListIndex(name: string, autoImportText: string) { return CompletionProvider._mostRecentCompletions.findIndex( - item => item.label === name && item.autoImportText === autoImportText + (item) => item.label === name && item.autoImportText === autoImportText ); } @@ -1429,8 +1429,8 @@ export class CompletionProvider { const moduleDescriptor: ImportedModuleDescriptor = { leadingDots: node.leadingDots, hasTrailingDot: node.hasTrailingDot, - nameParts: node.nameParts.map(part => part.value), - importedSymbols: [] + nameParts: node.nameParts.map((part) => part.value), + importedSymbols: [], }; const completions = this._importResolver.getCompletionSuggestions( @@ -1457,7 +1457,7 @@ export class CompletionProvider { completionItem.sortText = this._makeSortText(SortCategory.Keyword, keyword); } - completions.forEach(completionName => { + completions.forEach((completionName) => { const completionItem = CompletionItem.create(completionName); completionItem.kind = CompletionItemKind.Module; completionList.items.push(completionItem); diff --git a/server/src/languageService/definitionProvider.ts b/server/src/languageService/definitionProvider.ts index dcc1e9456..9e99b9d1d 100644 --- a/server/src/languageService/definitionProvider.ts +++ b/server/src/languageService/definitionProvider.ts @@ -44,12 +44,12 @@ export class DefinitionProvider { if (node.nodeType === ParseNodeType.Name) { const declarations = evaluator.getDeclarationsForNameNode(node); if (declarations) { - declarations.forEach(decl => { + declarations.forEach((decl) => { const resolvedDecl = evaluator.resolveAliasDeclaration(decl); if (resolvedDecl && resolvedDecl.path) { this._addIfUnique(definitions, { path: resolvedDecl.path, - range: resolvedDecl.range + range: resolvedDecl.range, }); } }); diff --git a/server/src/languageService/documentSymbolProvider.ts b/server/src/languageService/documentSymbolProvider.ts index 557155059..64a9c1388 100644 --- a/server/src/languageService/documentSymbolProvider.ts +++ b/server/src/languageService/documentSymbolProvider.ts @@ -129,7 +129,7 @@ class FindSymbolTreeWalker extends ParseTreeWalker { const location: Location = { uri: URI.file(this._filePath).toString(), - range: declaration.range + range: declaration.range, }; const symbolKind = getSymbolKind(name, declaration, this._evaluator); @@ -140,7 +140,7 @@ class FindSymbolTreeWalker extends ParseTreeWalker { const symbolInfo: SymbolInformation = { name, kind: symbolKind, - location + location, }; if (containerName) { @@ -267,7 +267,7 @@ function getDocumentSymbolRecursive( kind: symbolKind, range, selectionRange, - children + children, }; docSymbolResults.push(symbolInfo); diff --git a/server/src/languageService/hoverProvider.ts b/server/src/languageService/hoverProvider.ts index 2ba0ce2b7..b8c75b194 100644 --- a/server/src/languageService/hoverProvider.ts +++ b/server/src/languageService/hoverProvider.ts @@ -57,8 +57,8 @@ export class HoverProvider { parts: [], range: { start: convertOffsetToPosition(node.start, parseResults.tokenizerOutput.lines), - end: convertOffsetToPosition(TextRange.getEnd(node), parseResults.tokenizerOutput.lines) - } + end: convertOffsetToPosition(TextRange.getEnd(node), parseResults.tokenizerOutput.lines), + }, }; if (node.nodeType === ParseNodeType.Name) { @@ -212,7 +212,7 @@ export class HoverProvider { } else if (type.category === TypeCategory.Function) { this._addDocumentationResultsPart(parts, type.details.docString); } else if (type.category === TypeCategory.OverloadedFunction) { - type.overloads.forEach(overload => { + type.overloads.forEach((overload) => { this._addDocumentationResultsPart(parts, overload.details.docString); }); } @@ -227,7 +227,7 @@ export class HoverProvider { private static _addResultsPart(parts: HoverTextPart[], text: string, python = false) { parts.push({ python, - text + text, }); } } @@ -238,7 +238,7 @@ export function convertHoverResults(hoverResults: HoverResults | undefined): Hov } const markupString = hoverResults.parts - .map(part => { + .map((part) => { if (part.python) { return '```python\n' + part.text + '\n```\n'; } @@ -249,8 +249,8 @@ export function convertHoverResults(hoverResults: HoverResults | undefined): Hov return { contents: { kind: MarkupKind.Markdown, - value: markupString + value: markupString, }, - range: hoverResults.range + range: hoverResults.range, }; } diff --git a/server/src/languageService/importSorter.ts b/server/src/languageService/importSorter.ts index cda2cd8b6..10039e5de 100644 --- a/server/src/languageService/importSorter.ts +++ b/server/src/languageService/importSorter.ts @@ -28,7 +28,7 @@ export const enum ImportGroup { BuiltIn = 0, ThirdParty = 1, Local = 2, - LocalRelative = 3 + LocalRelative = 3, } export class ImportSorter { @@ -41,7 +41,7 @@ export class ImportSorter { const importStatements = ImportStatementUtils.getTopLevelImports(this._parseResults.parseTree); const sortedStatements = importStatements.orderedImports - .map(s => s) + .map((s) => s) .sort((a, b) => { return this._compareImportStatements(a, b); }); @@ -55,7 +55,7 @@ export class ImportSorter { actions.push({ range: primaryRange, - replacementText: this._generateSortedImportText(sortedStatements) + replacementText: this._generateSortedImportText(sortedStatements), }); this._addSecondaryReplacementRanges(importStatements.orderedImports, actions); @@ -101,7 +101,7 @@ export class ImportSorter { // If there are other blocks of import statements separated by other statements, // we'll ignore these other blocks for now. private _getPrimaryReplacementRange(statements: ImportStatementUtils.ImportStatement[]): Range { - let statementLimit = statements.findIndex(s => s.followsNonImportStatement); + let statementLimit = statements.findIndex((s) => s.followsNonImportStatement); if (statementLimit < 0) { statementLimit = statements.length; } @@ -109,7 +109,7 @@ export class ImportSorter { const lastStatement = statements[statementLimit - 1].node; return { start: convertOffsetToPosition(statements[0].node.start, this._parseResults.tokenizerOutput.lines), - end: convertOffsetToPosition(TextRange.getEnd(lastStatement), this._parseResults.tokenizerOutput.lines) + end: convertOffsetToPosition(TextRange.getEnd(lastStatement), this._parseResults.tokenizerOutput.lines), }; } @@ -119,7 +119,7 @@ export class ImportSorter { statements: ImportStatementUtils.ImportStatement[], actions: TextEditAction[] ) { - let secondaryBlockStart = statements.findIndex(s => s.followsNonImportStatement); + let secondaryBlockStart = statements.findIndex((s) => s.followsNonImportStatement); if (secondaryBlockStart < 0) { return; } @@ -141,9 +141,9 @@ export class ImportSorter { end: convertOffsetToPosition( TextRange.getEnd(statements[secondaryBlockLimit - 1].node), this._parseResults.tokenizerOutput.lines - ) + ), }, - replacementText: '' + replacementText: '', }); secondaryBlockStart = secondaryBlockLimit; @@ -195,7 +195,7 @@ export class ImportSorter { private _formatImportFromNode(node: ImportFromNode, moduleName: string): string { const symbols = node.imports .sort((a, b) => this._compareSymbols(a, b)) - .map(symbol => { + .map((symbol) => { let symbolText = symbol.name.value; if (symbol.alias) { symbolText += ` as ${symbol.alias.value}`; diff --git a/server/src/languageService/quickActions.ts b/server/src/languageService/quickActions.ts index 733e54d20..4994f0fef 100644 --- a/server/src/languageService/quickActions.ts +++ b/server/src/languageService/quickActions.ts @@ -64,16 +64,16 @@ function _addMissingOptionalToParam( editActions.push({ range: { start: startPos, end: startPos }, - replacementText: 'Optional[' + replacementText: 'Optional[', }); editActions.push({ range: { start: endPos, end: endPos }, - replacementText: ']' + replacementText: ']', }); // Add the import statement if necessary. const importStatements = ImportStatementUtils.getTopLevelImports(parseResults.parseTree); - const importStatement = importStatements.orderedImports.find(imp => imp.moduleName === 'typing'); + const importStatement = importStatements.orderedImports.find((imp) => imp.moduleName === 'typing'); // If there's an existing import statement, insert into it. if (importStatement && importStatement.node.nodeType === ParseNodeType.ImportFrom) { diff --git a/server/src/languageService/referencesProvider.ts b/server/src/languageService/referencesProvider.ts index 470abea18..9a809db47 100644 --- a/server/src/languageService/referencesProvider.ts +++ b/server/src/languageService/referencesProvider.ts @@ -72,7 +72,7 @@ class FindReferencesTreeWalker extends ParseTreeWalker { if (declarations && declarations.length > 0) { // Does this name share a declaration with the symbol of interest? - if (declarations.some(decl => this._resultsContainsDeclaration(decl))) { + if (declarations.some((decl) => this._resultsContainsDeclaration(decl))) { // Is it the same symbol? if (this._includeDeclaration || node !== this._referencesResult.nodeAtOffset) { this._referencesResult.locations.push({ @@ -82,8 +82,8 @@ class FindReferencesTreeWalker extends ParseTreeWalker { end: convertOffsetToPosition( TextRange.getEnd(node), this._parseResults.tokenizerOutput.lines - ) - } + ), + }, }); } } @@ -100,7 +100,7 @@ class FindReferencesTreeWalker extends ParseTreeWalker { // The reference results declarations are already resolved, so we don't // need to call resolveAliasDeclaration on them. - return this._referencesResult.declarations.some(decl => + return this._referencesResult.declarations.some((decl) => DeclarationUtils.areDeclarationsSame(decl, resolvedDecl) ); } @@ -137,7 +137,7 @@ export class ReferencesProvider { } const resolvedDeclarations: Declaration[] = []; - declarations.forEach(decl => { + declarations.forEach((decl) => { const resolvedDecl = evaluator.resolveAliasDeclaration(decl); if (resolvedDecl) { resolvedDeclarations.push(resolvedDecl); @@ -151,7 +151,7 @@ export class ReferencesProvider { // Does this symbol require search beyond the current file? Determine whether // the symbol is declared within an evaluation scope that is within the current // file and cannot be imported directly from other modules. - const requiresGlobalSearch = resolvedDeclarations.some(decl => { + const requiresGlobalSearch = resolvedDeclarations.some((decl) => { // If the declaration is outside of this file, a global search is needed. if (decl.path !== filePath) { return true; @@ -172,7 +172,7 @@ export class ReferencesProvider { requiresGlobalSearch, nodeAtOffset: node, declarations: resolvedDeclarations, - locations: [] + locations: [], }; const refTreeWalker = new FindReferencesTreeWalker( diff --git a/server/src/languageService/signatureHelpProvider.ts b/server/src/languageService/signatureHelpProvider.ts index 9fa211c97..926f35b75 100644 --- a/server/src/languageService/signatureHelpProvider.ts +++ b/server/src/languageService/signatureHelpProvider.ts @@ -104,7 +104,7 @@ export class SignatureHelpProvider { return { signatures, activeSignature, - activeParameter + activeParameter, }; } @@ -119,7 +119,7 @@ export class SignatureHelpProvider { parameters.push({ startOffset: label.length, endOffset: label.length + paramString.length, - documentation: extractParameterDocumentation(functionDocString || '', paramName) + documentation: extractParameterDocumentation(functionDocString || '', paramName), }); label += paramString; @@ -133,7 +133,7 @@ export class SignatureHelpProvider { const sigInfo: SignatureInfo = { label, parameters, - documentation: functionDocString + documentation: functionDocString, }; return sigInfo; diff --git a/server/src/parser/characters.ts b/server/src/parser/characters.ts index 131cfe78e..2c242ed48 100644 --- a/server/src/parser/characters.ts +++ b/server/src/parser/characters.ts @@ -22,7 +22,7 @@ enum CharCategory { StartIdentifierChar = 1, // Character can appear only within identifier, not at beginning - IdentifierChar = 2 + IdentifierChar = 2, } // Table of first 256 character codes (the most common cases). @@ -100,7 +100,7 @@ const _specialStartIdentifierChars: unicode.UnicodeRangeTable = [ 0x2118, 0x212e, 0x309b, - 0x309c + 0x309c, ]; const _startIdentifierCharRanges = [ @@ -110,7 +110,7 @@ const _startIdentifierCharRanges = [ unicode.unicodeLt, unicode.unicodeLo, unicode.unicodeLm, - unicode.unicodeNl + unicode.unicodeNl, ]; // Characters with the Other_ID_Start property. @@ -126,7 +126,7 @@ const _specialIdentifierChars: unicode.UnicodeRangeTable = [ 0x136f, 0x1370, 0x1371, - 0x19da + 0x19da, ]; const _identifierCharRanges = [ @@ -134,7 +134,7 @@ const _identifierCharRanges = [ unicode.unicodeMn, unicode.unicodeMc, unicode.unicodeNd, - unicode.unicodePc + unicode.unicodePc, ]; function _buildIdentifierLookupTableFromUnicodeRangeTable( @@ -172,11 +172,11 @@ function _buildIdentifierLookupTableFromUnicodeRangeTable( function _buildIdentifierLookupTable(fastTableOnly: boolean) { _identifierCharFastTable.fill(CharCategory.NotIdentifierChar); - _identifierCharRanges.forEach(table => { + _identifierCharRanges.forEach((table) => { _buildIdentifierLookupTableFromUnicodeRangeTable(table, CharCategory.IdentifierChar, fastTableOnly); }); - _startIdentifierCharRanges.forEach(table => { + _startIdentifierCharRanges.forEach((table) => { _buildIdentifierLookupTableFromUnicodeRangeTable(table, CharCategory.StartIdentifierChar, fastTableOnly); }); } diff --git a/server/src/parser/parseNodes.ts b/server/src/parser/parseNodes.ts index 8fcc217fc..f3bd8d843 100644 --- a/server/src/parser/parseNodes.ts +++ b/server/src/parser/parseNodes.ts @@ -17,7 +17,7 @@ import { OperatorType, StringToken, Token, - TokenType + TokenType, } from './tokenizerTypes'; export const enum ParseNodeType { @@ -90,7 +90,7 @@ export const enum ParseNodeType { WithItem, // 60 Yield, - YieldFrom + YieldFrom, } export const enum ErrorExpressionCategory { @@ -104,7 +104,7 @@ export const enum ErrorExpressionCategory { MissingMemberAccessName, MissingTupleCloseParen, MissingListCloseBracket, - MissingFunctionParameterList + MissingFunctionParameterList, } export interface ParseNodeBase extends TextRange { @@ -146,7 +146,7 @@ export namespace ModuleNode { length: range.length, nodeType: ParseNodeType.Module, id: _nextNodeId++, - statements: [] + statements: [], }; return node; @@ -165,7 +165,7 @@ export namespace SuiteNode { length: range.length, nodeType: ParseNodeType.Suite, id: _nextNodeId++, - statements: [] + statements: [], }; return node; @@ -193,7 +193,7 @@ export namespace IfNode { id: _nextNodeId++, testExpression, ifSuite, - elseSuite + elseSuite, }; testExpression.parent = node; @@ -225,7 +225,7 @@ export namespace WhileNode { nodeType: ParseNodeType.While, id: _nextNodeId++, testExpression, - whileSuite + whileSuite, }; testExpression.parent = node; @@ -260,7 +260,7 @@ export namespace ForNode { id: _nextNodeId++, targetExpression, iterableExpression, - forSuite + forSuite, }; targetExpression.parent = node; @@ -290,7 +290,7 @@ export namespace ListComprehensionForNode { nodeType: ParseNodeType.ListComprehensionFor, id: _nextNodeId++, targetExpression, - iterableExpression + iterableExpression, }; targetExpression.parent = node; @@ -315,7 +315,7 @@ export namespace ListComprehensionIfNode { length: ifToken.length, nodeType: ParseNodeType.ListComprehensionIf, id: _nextNodeId++, - testExpression + testExpression, }; testExpression.parent = node; @@ -342,7 +342,7 @@ export namespace TryNode { nodeType: ParseNodeType.Try, id: _nextNodeId++, trySuite, - exceptClauses: [] + exceptClauses: [], }; trySuite.parent = node; @@ -367,7 +367,7 @@ export namespace ExceptNode { length: exceptToken.length, nodeType: ParseNodeType.Except, id: _nextNodeId++, - exceptSuite + exceptSuite, }; exceptSuite.parent = node; @@ -398,7 +398,7 @@ export namespace FunctionNode { decorators: [], name, parameters: [], - suite + suite, }; name.parent = node; @@ -413,7 +413,7 @@ export namespace FunctionNode { export const enum ParameterCategory { Simple, VarArgList, - VarArgDictionary + VarArgDictionary, } export interface ParameterNode extends ParseNodeBase { @@ -431,7 +431,7 @@ export namespace ParameterNode { length: startToken.length, nodeType: ParseNodeType.Parameter, id: _nextNodeId++, - category: paramCategory + category: paramCategory, }; return node; @@ -456,7 +456,7 @@ export namespace ClassNode { decorators: [], name, arguments: [], - suite + suite, }; name.parent = node; @@ -487,9 +487,9 @@ export namespace ClassNode { start: 0, length: 0, comments: [], - value: '' + value: '', }, - value: '' + value: '', }, arguments: [], suite: { @@ -497,11 +497,11 @@ export namespace ClassNode { length: 0, id: 0, nodeType: ParseNodeType.Suite, - statements: [] - } + statements: [], + }, }; - decorators.forEach(decorator => { + decorators.forEach((decorator) => { decorator.parent = node; extendRange(node, decorator); }); @@ -525,7 +525,7 @@ export namespace WithNode { nodeType: ParseNodeType.With, id: _nextNodeId++, withItems: [], - suite + suite, }; suite.parent = node; @@ -549,7 +549,7 @@ export namespace WithItemNode { length: expression.length, nodeType: ParseNodeType.WithItem, id: _nextNodeId++, - expression + expression, }; expression.parent = node; @@ -572,7 +572,7 @@ export namespace DecoratorNode { nodeType: ParseNodeType.Decorator, id: _nextNodeId++, leftExpression, - arguments: undefined + arguments: undefined, }; leftExpression.parent = node; @@ -595,7 +595,7 @@ export namespace StatementListNode { length: atToken.length, nodeType: ParseNodeType.StatementList, id: _nextNodeId++, - statements: [] + statements: [], }; return node; @@ -705,7 +705,7 @@ export namespace ErrorNode { nodeType: ParseNodeType.Error, id: _nextNodeId++, category, - child + child, }; if (child) { @@ -731,7 +731,7 @@ export namespace UnaryOperationNode { nodeType: ParseNodeType.UnaryOperation, id: _nextNodeId++, operator, - expression + expression, }; expression.parent = node; @@ -758,7 +758,7 @@ export namespace BinaryOperationNode { id: _nextNodeId++, leftExpression, operator, - rightExpression + rightExpression, }; leftExpression.parent = node; @@ -784,7 +784,7 @@ export namespace AssignmentExpressionNode { nodeType: ParseNodeType.AssignmentExpression, id: _nextNodeId++, name, - rightExpression + rightExpression, }; name.parent = node; @@ -811,7 +811,7 @@ export namespace AssignmentNode { nodeType: ParseNodeType.Assignment, id: _nextNodeId++, leftExpression, - rightExpression + rightExpression, }; leftExpression.parent = node; @@ -837,7 +837,7 @@ export namespace TypeAnnotationNode { nodeType: ParseNodeType.TypeAnnotation, id: _nextNodeId++, valueExpression, - typeAnnotation + typeAnnotation, }; valueExpression.parent = node; @@ -876,7 +876,7 @@ export namespace AugmentedAssignmentNode { leftExpression, operator, rightExpression, - destExpression + destExpression, }; leftExpression.parent = node; @@ -901,7 +901,7 @@ export namespace AwaitNode { length: awaitToken.length, nodeType: ParseNodeType.Await, id: _nextNodeId++, - expression + expression, }; expression.parent = node; @@ -932,7 +932,7 @@ export namespace TernaryNode { id: _nextNodeId++, ifExpression, testExpression, - elseExpression + elseExpression, }; ifExpression.parent = node; @@ -957,7 +957,7 @@ export namespace UnpackNode { length: starToken.length, nodeType: ParseNodeType.Unpack, id: _nextNodeId++, - expression + expression, }; expression.parent = node; @@ -980,7 +980,7 @@ export namespace TupleNode { length: range.length, nodeType: ParseNodeType.Tuple, id: _nextNodeId++, - expressions: [] + expressions: [], }; return node; @@ -1001,7 +1001,7 @@ export namespace CallNode { nodeType: ParseNodeType.Call, id: _nextNodeId++, leftExpression, - arguments: [] + arguments: [], }; leftExpression.parent = node; @@ -1024,7 +1024,7 @@ export namespace ListComprehensionNode { nodeType: ParseNodeType.ListComprehension, id: _nextNodeId++, expression, - comprehensions: [] + comprehensions: [], }; expression.parent = node; @@ -1045,10 +1045,10 @@ export namespace IndexItemsNode { length: openBracketToken.length, nodeType: ParseNodeType.IndexItems, id: _nextNodeId++, - items + items, }; - items.forEach(item => { + items.forEach((item) => { item.parent = node; }); @@ -1072,7 +1072,7 @@ export namespace IndexNode { nodeType: ParseNodeType.Index, id: _nextNodeId++, baseExpression, - items + items, }; baseExpression.parent = node; @@ -1097,7 +1097,7 @@ export namespace SliceNode { start: range.start, length: range.length, nodeType: ParseNodeType.Slice, - id: _nextNodeId++ + id: _nextNodeId++, }; return node; @@ -1116,7 +1116,7 @@ export namespace YieldNode { length: yieldToken.length, nodeType: ParseNodeType.Yield, id: _nextNodeId++, - expression + expression, }; if (expression) { @@ -1140,7 +1140,7 @@ export namespace YieldFromNode { length: yieldToken.length, nodeType: ParseNodeType.YieldFrom, id: _nextNodeId++, - expression + expression, }; expression.parent = node; @@ -1165,7 +1165,7 @@ export namespace MemberAccessNode { nodeType: ParseNodeType.MemberAccess, id: _nextNodeId++, leftExpression, - memberName + memberName, }; leftExpression.parent = node; @@ -1191,7 +1191,7 @@ export namespace LambdaNode { nodeType: ParseNodeType.Lambda, id: _nextNodeId++, parameters: [], - expression + expression, }; expression.parent = node; @@ -1216,7 +1216,7 @@ export namespace NameNode { nodeType: ParseNodeType.Name, id: _nextNodeId++, token: nameToken, - value: nameToken.value + value: nameToken.value, }; return node; @@ -1235,7 +1235,7 @@ export namespace ConstantNode { length: token.length, nodeType: ParseNodeType.Constant, id: _nextNodeId++, - constType: token.keywordType + constType: token.keywordType, }; return node; @@ -1252,7 +1252,7 @@ export namespace EllipsisNode { start: range.start, length: range.length, nodeType: ParseNodeType.Ellipsis, - id: _nextNodeId++ + id: _nextNodeId++, }; return node; @@ -1275,7 +1275,7 @@ export namespace NumberNode { id: _nextNodeId++, value: token.value, isInteger: token.isInteger, - isImaginary: token.isImaginary + isImaginary: token.isImaginary, }; return node; @@ -1298,7 +1298,7 @@ export namespace StringNode { id: _nextNodeId++, token, value: unescapedValue, - hasUnescapeErrors + hasUnescapeErrors, }; return node; @@ -1328,10 +1328,10 @@ export namespace FormatStringNode { token, value: unescapedValue, hasUnescapeErrors, - expressions + expressions, }; - expressions.forEach(expr => { + expressions.forEach((expr) => { expr.parent = node; }); @@ -1356,11 +1356,11 @@ export namespace StringListNode { length: strings[0].length, nodeType: ParseNodeType.StringList, id: _nextNodeId++, - strings + strings, }; if (strings.length > 0) { - strings.forEach(str => { + strings.forEach((str) => { str.parent = node; }); extendRange(node, strings[strings.length - 1]); @@ -1382,7 +1382,7 @@ export namespace DictionaryNode { length: range.length, nodeType: ParseNodeType.Dictionary, id: _nextNodeId++, - entries: [] + entries: [], }; return node; @@ -1403,7 +1403,7 @@ export namespace DictionaryKeyEntryNode { nodeType: ParseNodeType.DictionaryKeyEntry, id: _nextNodeId++, keyExpression, - valueExpression + valueExpression, }; keyExpression.parent = node; @@ -1427,7 +1427,7 @@ export namespace DictionaryExpandEntryNode { length: expandExpression.length, nodeType: ParseNodeType.DictionaryExpandEntry, id: _nextNodeId++, - expandExpression + expandExpression, }; expandExpression.parent = node; @@ -1450,7 +1450,7 @@ export namespace SetNode { length: range.length, nodeType: ParseNodeType.Set, id: _nextNodeId++, - entries: [] + entries: [], }; return node; @@ -1469,7 +1469,7 @@ export namespace ListNode { length: range.length, nodeType: ParseNodeType.List, id: _nextNodeId++, - entries: [] + entries: [], }; return node; @@ -1479,7 +1479,7 @@ export namespace ListNode { export const enum ArgumentCategory { Simple, UnpackedList, - UnpackedDictionary + UnpackedDictionary, } export interface ArgumentNode extends ParseNodeBase { @@ -1497,7 +1497,7 @@ export namespace ArgumentNode { nodeType: ParseNodeType.Argument, id: _nextNodeId++, valueExpression, - argumentCategory: argCategory + argumentCategory: argCategory, }; valueExpression.parent = node; @@ -1520,7 +1520,7 @@ export namespace DelNode { length: delToken.length, nodeType: ParseNodeType.Del, id: _nextNodeId++, - expressions: [] + expressions: [], }; return node; @@ -1537,7 +1537,7 @@ export namespace PassNode { start: passToken.start, length: passToken.length, nodeType: ParseNodeType.Pass, - id: _nextNodeId++ + id: _nextNodeId++, }; return node; @@ -1556,7 +1556,7 @@ export namespace ImportNode { length: passToken.length, nodeType: ParseNodeType.Import, id: _nextNodeId++, - list: [] + list: [], }; return node; @@ -1580,7 +1580,7 @@ export namespace ModuleNameNode { nodeType: ParseNodeType.ModuleName, id: _nextNodeId++, leadingDots: 0, - nameParts: [] + nameParts: [], }; return node; @@ -1600,7 +1600,7 @@ export namespace ImportAsNode { length: module.length, nodeType: ParseNodeType.ImportAs, id: _nextNodeId++, - module + module, }; module.parent = node; @@ -1628,7 +1628,7 @@ export namespace ImportFromNode { module, imports: [], isWildcardImport: false, - usesParens: false + usesParens: false, }; module.parent = node; @@ -1652,7 +1652,7 @@ export namespace ImportFromAsNode { length: name.length, nodeType: ParseNodeType.ImportFromAs, id: _nextNodeId++, - name + name, }; name.parent = node; @@ -1673,7 +1673,7 @@ export namespace GlobalNode { length: range.length, nodeType: ParseNodeType.Global, id: _nextNodeId++, - nameList: [] + nameList: [], }; return node; @@ -1692,7 +1692,7 @@ export namespace NonlocalNode { length: range.length, nodeType: ParseNodeType.Nonlocal, id: _nextNodeId++, - nameList: [] + nameList: [], }; return node; @@ -1712,7 +1712,7 @@ export namespace AssertNode { length: assertToken.length, nodeType: ParseNodeType.Assert, id: _nextNodeId++, - testExpression + testExpression, }; testExpression.parent = node; @@ -1733,7 +1733,7 @@ export namespace BreakNode { start: range.start, length: range.length, nodeType: ParseNodeType.Break, - id: _nextNodeId++ + id: _nextNodeId++, }; return node; @@ -1750,7 +1750,7 @@ export namespace ContinueNode { start: range.start, length: range.length, nodeType: ParseNodeType.Continue, - id: _nextNodeId++ + id: _nextNodeId++, }; return node; @@ -1768,7 +1768,7 @@ export namespace ReturnNode { start: range.start, length: range.length, nodeType: ParseNodeType.Return, - id: _nextNodeId++ + id: _nextNodeId++, }; return node; @@ -1788,7 +1788,7 @@ export namespace RaiseNode { start: range.start, length: range.length, nodeType: ParseNodeType.Raise, - id: _nextNodeId++ + id: _nextNodeId++, }; return node; diff --git a/server/src/parser/parser.ts b/server/src/parser/parser.ts index 7c82f78ba..2d6d050fa 100644 --- a/server/src/parser/parser.ts +++ b/server/src/parser/parser.ts @@ -93,7 +93,7 @@ import { WithItemNode, WithNode, YieldFromNode, - YieldNode + YieldNode, } from './parseNodes'; import * as StringTokenUtils from './stringTokenUtils'; import { Tokenizer, TokenizerOutput } from './tokenizer'; @@ -109,7 +109,7 @@ import { StringToken, StringTokenFlags, Token, - TokenType + TokenType, } from './tokenizerTypes'; interface ExpressionListResult { @@ -210,7 +210,7 @@ export class Parser { importedModules: this._importedModules, futureImports: this._futureImportMap, tokenizerOutput: this._tokenizerOutput!, - containsWildcardImport: this._containsWildcardImport + containsWildcardImport: this._containsWildcardImport, }; } @@ -244,7 +244,7 @@ export class Parser { return { parseTree, lines: this._tokenizerOutput!.lines, - diagnostics: diagSink.fetchAndClear() + diagnostics: diagSink.fetchAndClear(), }; } @@ -496,7 +496,7 @@ export class Parser { listCompNode.comprehensions = compList; if (compList.length > 0) { - compList.forEach(comp => { + compList.forEach((comp) => { comp.parent = listCompNode; }); extendRange(listCompNode, compList[compList.length - 1]); @@ -704,13 +704,13 @@ export class Parser { } functionNode.parameters = paramList; - paramList.forEach(param => { + paramList.forEach((param) => { param.parent = functionNode; }); if (decorators) { functionNode.decorators = decorators; - decorators.forEach(decorator => { + decorators.forEach((decorator) => { decorator.parent = functionNode; }); @@ -922,7 +922,7 @@ export class Parser { } withNode.withItems = withItemList; - withItemList.forEach(withItem => { + withItemList.forEach((withItem) => { withItem.parent = withNode; }); @@ -1022,7 +1022,7 @@ export class Parser { if (this._consumeTokenIfType(TokenType.OpenParenthesis)) { decoratorNode.arguments = this._parseArgList(); - decoratorNode.arguments.forEach(arg => { + decoratorNode.arguments.forEach((arg) => { arg.parent = decoratorNode; extendRange(decoratorNode, arg); }); @@ -1066,14 +1066,14 @@ export class Parser { const classNode = ClassNode.create(classToken, NameNode.create(nameToken), suite); classNode.arguments = argList; - argList.forEach(arg => { + argList.forEach((arg) => { arg.parent = classNode; }); if (decorators) { classNode.decorators = decorators; if (decorators.length > 0) { - decorators.forEach(decorator => { + decorators.forEach((decorator) => { decorator.parent = classNode; }); extendRange(classNode, decorators[0]); @@ -1216,8 +1216,8 @@ export class Parser { this._importedModules.push({ nameNode: importFromNode.module, leadingDots: importFromNode.module.leadingDots, - nameParts: importFromNode.module.nameParts.map(p => p.value), - importedSymbols: importFromNode.imports.map(imp => imp.name.value) + nameParts: importFromNode.module.nameParts.map((p) => p.value), + importedSymbols: importFromNode.imports.map((imp) => imp.name.value), }); return importFromNode; @@ -1252,8 +1252,8 @@ export class Parser { this._importedModules.push({ nameNode: importAsNode.module, leadingDots: importAsNode.module.leadingDots, - nameParts: importAsNode.module.nameParts.map(p => p.value), - importedSymbols: undefined + nameParts: importAsNode.module.nameParts.map((p) => p.value), + importedSymbols: undefined, }); if (!this._consumeTokenIfType(TokenType.Comma)) { @@ -1316,7 +1316,7 @@ export class Parser { const globalNode = GlobalNode.create(globalToken); globalNode.nameList = this._parseNameList(); if (globalNode.nameList.length > 0) { - globalNode.nameList.forEach(name => { + globalNode.nameList.forEach((name) => { name.parent = globalNode; }); extendRange(globalNode, globalNode.nameList[globalNode.nameList.length - 1]); @@ -1330,7 +1330,7 @@ export class Parser { const nonlocalNode = NonlocalNode.create(nonlocalToken); nonlocalNode.nameList = this._parseNameList(); if (nonlocalNode.nameList.length > 0) { - nonlocalNode.nameList.forEach(name => { + nonlocalNode.nameList.forEach((name) => { name.parent = nonlocalNode; }); extendRange(nonlocalNode, nonlocalNode.nameList[nonlocalNode.nameList.length - 1]); @@ -1420,7 +1420,7 @@ export class Parser { const delNode = DelNode.create(delToken); delNode.expressions = exprListResult.list; if (delNode.expressions.length > 0) { - delNode.expressions.forEach(expr => { + delNode.expressions.forEach((expr) => { expr.parent = delNode; }); extendRange(delNode, delNode.expressions[delNode.expressions.length - 1]); @@ -1570,7 +1570,7 @@ export class Parser { const tupleNode = TupleNode.create(tupleStartRange); tupleNode.expressions = exprListResult.list; if (exprListResult.list.length > 0) { - exprListResult.list.forEach(expr => { + exprListResult.list.forEach((expr) => { expr.parent = tupleNode; }); extendRange(tupleNode, exprListResult.list[exprListResult.list.length - 1]); @@ -1975,7 +1975,7 @@ export class Parser { const callNode = CallNode.create(atomExpression); callNode.arguments = argList; if (argList.length > 0) { - argList.forEach(arg => { + argList.forEach((arg) => { arg.parent = callNode; }); extendRange(callNode, argList[argList.length - 1]); @@ -2089,7 +2089,7 @@ export class Parser { this._handleExpressionParseError( ErrorExpressionCategory.MissingIndexOrSlice, 'Expected index or slice expression' - ) + ), ]; } @@ -2361,7 +2361,7 @@ export class Parser { const lambdaNode = LambdaNode.create(lambdaToken, testExpr); lambdaNode.parameters = argList; - argList.forEach(arg => { + argList.forEach((arg) => { arg.parent = lambdaNode; }); return lambdaNode; @@ -2419,7 +2419,7 @@ export class Parser { const listAtom = ListNode.create(startBracket); extendRange(listAtom, closeBracket); if (exprListResult.list.length > 0) { - exprListResult.list.forEach(expr => { + exprListResult.list.forEach((expr) => { expr.parent = listAtom; }); extendRange(listAtom, exprListResult.list[exprListResult.list.length - 1]); @@ -2555,7 +2555,7 @@ export class Parser { if (setEntries.length > 0) { extendRange(setAtom, setEntries[setEntries.length - 1]); } - setEntries.forEach(entry => { + setEntries.forEach((entry) => { entry.parent = setAtom; }); setAtom.entries = setEntries; @@ -2567,7 +2567,7 @@ export class Parser { extendRange(dictionaryAtom, closeCurlyBrace); } if (dictionaryEntries.length > 0) { - dictionaryEntries.forEach(entry => { + dictionaryEntries.forEach((entry) => { entry.parent = dictionaryAtom; }); extendRange(dictionaryAtom, dictionaryEntries[dictionaryEntries.length - 1]); @@ -2802,7 +2802,7 @@ export class Parser { true ); - parseResults.diagnostics.forEach(diag => { + parseResults.diagnostics.forEach((diag) => { this._addError(diag.message, stringListNode); }); @@ -2835,7 +2835,7 @@ export class Parser { false ); - parseResults.diagnostics.forEach(diag => { + parseResults.diagnostics.forEach((diag) => { const textRangeStart = (diag.range ? convertPositionToOffset(diag.range.start, parseResults.lines) @@ -2992,7 +2992,7 @@ export class Parser { true ); - parseResults.diagnostics.forEach(diag => { + parseResults.diagnostics.forEach((diag) => { this._addError(diag.message, stringNode); }); @@ -3152,7 +3152,7 @@ export class Parser { // to an identifier token. if (nextToken.type === TokenType.Keyword) { const keywordType = this._peekKeywordType(); - if (!disallowedKeywords.find(type => type === keywordType)) { + if (!disallowedKeywords.find((type) => type === keywordType)) { const keywordText = this._fileContents!.substr(nextToken.start, nextToken.length); this._getNextToken(); return IdentifierToken.create(nextToken.start, nextToken.length, keywordText, nextToken.comments); diff --git a/server/src/parser/stringTokenUtils.ts b/server/src/parser/stringTokenUtils.ts index e2be1cc71..f38944bfa 100644 --- a/server/src/parser/stringTokenUtils.ts +++ b/server/src/parser/stringTokenUtils.ts @@ -33,7 +33,7 @@ export const enum UnescapeErrorType { InvalidEscapeSequence, EscapeWithinFormatExpression, SingleCloseBraceWithinFormatLiteral, - UnterminatedFormatExpression + UnterminatedFormatExpression, } export interface UnescapeError { @@ -65,14 +65,14 @@ export function getUnescapedString(stringToken: StringToken): UnescapedString { offset: 0, length: 0, value: '', - isExpression: false + isExpression: false, }; let strOffset = 0; const output: UnescapedString = { value: '', unescapeErrors: [], nonAsciiInBytes: false, - formatStringSegments: [] + formatStringSegments: [], }; const addInvalidEscapeOffset = () => { @@ -81,7 +81,7 @@ export function getUnescapedString(stringToken: StringToken): UnescapedString { output.unescapeErrors.push({ offset: strOffset - 1, length: 2, - errorType: UnescapeErrorType.InvalidEscapeSequence + errorType: UnescapeErrorType.InvalidEscapeSequence, }); } }; @@ -135,7 +135,7 @@ export function getUnescapedString(stringToken: StringToken): UnescapedString { output.unescapeErrors.push({ offset: formatSegment.offset, length: strOffset - formatSegment.offset, - errorType: UnescapeErrorType.UnterminatedFormatExpression + errorType: UnescapeErrorType.UnterminatedFormatExpression, }); } @@ -154,7 +154,7 @@ export function getUnescapedString(stringToken: StringToken): UnescapedString { output.unescapeErrors.push({ offset: strOffset, length: 1, - errorType: UnescapeErrorType.EscapeWithinFormatExpression + errorType: UnescapeErrorType.EscapeWithinFormatExpression, }); } @@ -326,7 +326,7 @@ export function getUnescapedString(stringToken: StringToken): UnescapedString { offset: strOffset, length: 0, value: '', - isExpression: true + isExpression: true, }; formatExpressionNestCount++; } @@ -338,7 +338,7 @@ export function getUnescapedString(stringToken: StringToken): UnescapedString { output.unescapeErrors.push({ offset: strOffset, length: 1, - errorType: UnescapeErrorType.SingleCloseBraceWithinFormatLiteral + errorType: UnescapeErrorType.SingleCloseBraceWithinFormatLiteral, }); strOffset++; } else { @@ -355,7 +355,7 @@ export function getUnescapedString(stringToken: StringToken): UnescapedString { offset: strOffset, length: 0, value: '', - isExpression: false + isExpression: false, }; } } else if (formatSegment.isExpression && (curChar === Char.SingleQuote || curChar === Char.DoubleQuote)) { diff --git a/server/src/parser/tokenizer.ts b/server/src/parser/tokenizer.ts index c1e277831..f8615f1e5 100644 --- a/server/src/parser/tokenizer.ts +++ b/server/src/parser/tokenizer.ts @@ -32,7 +32,7 @@ import { StringToken, StringTokenFlags, Token, - TokenType + TokenType, } from './tokenizerTypes'; const _keywords: { [key: string]: KeywordType } = { @@ -71,7 +71,7 @@ const _keywords: { [key: string]: KeywordType } = { yield: KeywordType.Yield, False: KeywordType.False, None: KeywordType.None, - True: KeywordType.True + True: KeywordType.True, }; const _operatorInfo: { [key: number]: OperatorFlags } = { @@ -116,7 +116,7 @@ const _operatorInfo: { [key: number]: OperatorFlags } = { [OperatorType.Is]: OperatorFlags.Binary, [OperatorType.IsNot]: OperatorFlags.Binary, [OperatorType.In]: OperatorFlags.Binary, - [OperatorType.NotIn]: OperatorFlags.Binary + [OperatorType.NotIn]: OperatorFlags.Binary, }; const _byteOrderMarker = 0xfeff; @@ -270,7 +270,7 @@ export class Tokenizer { typeIgnoreAll: this._typeIgnoreAll, predominantEndOfLineSequence, predominantTabSequence, - predominantSingleQuoteCharacter: this._singleQuoteCount >= this._doubleQuoteCount ? "'" : '"' + predominantSingleQuoteCharacter: this._singleQuoteCount >= this._doubleQuoteCount ? "'" : '"', }; } @@ -563,7 +563,7 @@ export class Tokenizer { tab1Spaces, tab8Spaces, isSpacePresent, - isTabPresent + isTabPresent, }); this._tokens.push(IndentToken.create(this._cs.position, 0, tab8Spaces, false, this._getComments())); } @@ -588,7 +588,7 @@ export class Tokenizer { tab1Spaces, tab8Spaces, isSpacePresent, - isTabPresent + isTabPresent, }); this._tokens.push( @@ -924,7 +924,7 @@ export class Tokenizer { const comment = Comment.create(start, length, value); if (value.match(/^\s*type:\s*ignore(\s|$)/)) { - if (this._tokens.findIndex(t => t.type !== TokenType.NewLine && t && t.type !== TokenType.Indent) < 0) { + if (this._tokens.findIndex((t) => t.type !== TokenType.NewLine && t && t.type !== TokenType.Indent) < 0) { this._typeIgnoreAll = true; } else { this._typeIgnoreLines[this._lineRanges.length] = true; @@ -962,10 +962,7 @@ export class Tokenizer { } if (this._cs.lookAhead(2) === Char.SingleQuote || this._cs.lookAhead(2) === Char.DoubleQuote) { - const prefix = this._cs - .getText() - .substr(this._cs.position, 2) - .toLowerCase(); + const prefix = this._cs.getText().substr(this._cs.position, 2).toLowerCase(); switch (prefix) { case 'rf': case 'fr': diff --git a/server/src/parser/tokenizerTypes.ts b/server/src/parser/tokenizerTypes.ts index 080fdce5b..d68052f78 100644 --- a/server/src/parser/tokenizerTypes.ts +++ b/server/src/parser/tokenizerTypes.ts @@ -36,14 +36,14 @@ export const enum TokenType { Ellipsis, Dot, Arrow, - Backtick + Backtick, } export const enum NewLineType { CarriageReturn, LineFeed, CarriageReturnLineFeed, - Implied + Implied, } export const enum OperatorType { @@ -93,14 +93,14 @@ export const enum OperatorType { Is, IsNot, In, - NotIn + NotIn, } export const enum OperatorFlags { Unary = 1 << 0, Binary = 1 << 1, Assignment = 1 << 2, - Comparison = 1 << 3 + Comparison = 1 << 3, } export const enum KeywordType { @@ -139,7 +139,7 @@ export const enum KeywordType { Try, While, With, - Yield + Yield, } export const enum StringTokenFlags { @@ -157,7 +157,7 @@ export const enum StringTokenFlags { Format = 1 << 6, // Error conditions - Unterminated = 1 << 16 + Unterminated = 1 << 16, } export interface Comment extends TextRange { @@ -171,7 +171,7 @@ export namespace Comment { const comment: Comment = { start, length, - value + value, }; return comment; @@ -193,7 +193,7 @@ export namespace Token { start, length, type, - comments + comments, }; return token; @@ -220,7 +220,7 @@ export namespace IndentToken { type: TokenType.Indent, isIndentAmbiguous, comments, - indentAmount + indentAmount, }; return token; @@ -247,7 +247,7 @@ export namespace DedentToken { type: TokenType.Dedent, comments, indentAmount, - matchesIndent + matchesIndent, }; return token; @@ -266,7 +266,7 @@ export namespace NewLineToken { length, type: TokenType.NewLine, comments, - newLineType + newLineType, }; return token; @@ -285,7 +285,7 @@ export namespace KeywordToken { length, type: TokenType.Keyword, comments, - keywordType + keywordType, }; return token; @@ -325,7 +325,7 @@ export namespace StringToken { escapedValue, prefixLength, quoteMarkLength: flags & StringTokenFlags.Triplicate ? 3 : 1, - comments + comments, }; return token; @@ -355,7 +355,7 @@ export namespace NumberToken { isInteger, isImaginary, value, - comments + comments, }; return token; @@ -374,7 +374,7 @@ export namespace OperatorToken { length, type: TokenType.Operator, operatorType, - comments + comments, }; return token; @@ -393,7 +393,7 @@ export namespace IdentifierToken { length, type: TokenType.Identifier, value, - comments + comments, }; return token; diff --git a/server/src/parser/unicode.ts b/server/src/parser/unicode.ts index f05a25131..64fdf4abd 100644 --- a/server/src/parser/unicode.ts +++ b/server/src/parser/unicode.ts @@ -639,7 +639,7 @@ export const unicodeLu: UnicodeRangeTable = [ [120662, 120686], [120720, 120744], 120778, - [125184, 125217] + [125184, 125217], ]; export const unicodeLl: UnicodeRangeTable = [ @@ -1275,7 +1275,7 @@ export const unicodeLl: UnicodeRangeTable = [ [120746, 120770], [120772, 120777], 120779, - [125218, 125251] + [125218, 125251], ]; export const unicodeLt: UnicodeRangeTable = [ @@ -1288,7 +1288,7 @@ export const unicodeLt: UnicodeRangeTable = [ [8104, 8111], 8124, 8140, - 8188 + 8188, ]; export const unicodeLo: UnicodeRangeTable = [ @@ -1750,7 +1750,7 @@ export const unicodeLo: UnicodeRangeTable = [ [177984, 178205], [178208, 183969], [183984, 191456], - [194560, 195101] + [194560, 195101], ]; export const unicodeLm: UnicodeRangeTable = [ @@ -1810,7 +1810,7 @@ export const unicodeLm: UnicodeRangeTable = [ [65438, 65439], [92992, 92995], [94099, 94111], - [94176, 94177] + [94176, 94177], ]; export const unicodeNl: UnicodeRangeTable = [ @@ -1825,7 +1825,7 @@ export const unicodeNl: UnicodeRangeTable = [ 66369, 66378, [66513, 66517], - [74752, 74862] + [74752, 74862], ]; export const unicodeMn: UnicodeRangeTable = [ @@ -2129,7 +2129,7 @@ export const unicodeMn: UnicodeRangeTable = [ [122918, 122922], [125136, 125142], [125252, 125258], - [917760, 917999] + [917760, 917999], ]; export const unicodeMc: UnicodeRangeTable = [ @@ -2292,7 +2292,7 @@ export const unicodeMc: UnicodeRangeTable = [ 72884, [94033, 94078], [119141, 119142], - [119149, 119154] + [119149, 119154], ]; export const unicodeNd: UnicodeRangeTable = [ @@ -2350,7 +2350,7 @@ export const unicodeNd: UnicodeRangeTable = [ [92768, 92777], [93008, 93017], [120782, 120831], - [125264, 125273] + [125264, 125273], ]; export const unicodePc: UnicodeRangeTable = [95, [8255, 8256], 8276, [65075, 65076], [65101, 65103], 65343]; diff --git a/server/src/pyright.ts b/server/src/pyright.ts index 1426d8f1b..7d9ec2eac 100644 --- a/server/src/pyright.ts +++ b/server/src/pyright.ts @@ -33,7 +33,7 @@ enum ExitStatus { NoErrors = 0, ErrorsReported = 1, FatalError = 2, - ConfigFileParseError = 3 + ConfigFileParseError = 3, } interface PyrightJsonResults { @@ -65,13 +65,13 @@ interface DiagnosticResult { const cancellationNone = Object.freeze({ isCancellationRequested: false, - onCancellationRequested: function() { + onCancellationRequested: function () { return { dispose() { /* empty */ - } + }, }; - } + }, }); function processArgs() { @@ -88,7 +88,7 @@ function processArgs() { { name: 'venv-path', alias: 'v', type: String }, { name: 'verbose', type: Boolean }, { name: 'version', type: Boolean }, - { name: 'watch', alias: 'w', type: Boolean } + { name: 'watch', alias: 'w', type: Boolean }, ]; let args: CommandLineOptions; @@ -131,7 +131,7 @@ function processArgs() { // Assume any relative paths are relative to the working directory. if (args.files && Array.isArray(args.files)) { options.fileSpecs = args.files; - options.fileSpecs = options.fileSpecs.map(f => combinePaths(process.cwd(), f)); + options.fileSpecs = options.fileSpecs.map((f) => combinePaths(process.cwd(), f)); } else { options.fileSpecs = []; } @@ -167,7 +167,7 @@ function processArgs() { const output = args.outputjson ? new NullConsole() : undefined; const service = new AnalyzerService('', createFromRealFileSystem(output), output); - service.setCompletionCallback(results => { + service.setCompletionCallback((results) => { if (results.fatalErrorOccurred) { process.exit(ExitStatus.FatalError); } @@ -282,21 +282,21 @@ function reportDiagnosticsAsJson( filesAnalyzed: filesInProgram, errorCount: 0, warningCount: 0, - timeInSec - } + timeInSec, + }, }; let errorCount = 0; let warningCount = 0; - fileDiagnostics.forEach(fileDiag => { - fileDiag.diagnostics.forEach(diag => { + fileDiagnostics.forEach((fileDiag) => { + fileDiag.diagnostics.forEach((diag) => { if (diag.category === DiagnosticCategory.Error || diag.category === DiagnosticCategory.Warning) { report.diagnostics.push({ file: fileDiag.filePath, severity: diag.category === DiagnosticCategory.Error ? 'error' : 'warning', message: diag.message, - range: diag.range + range: diag.range, }); if (diag.category === DiagnosticCategory.Error) { @@ -316,7 +316,7 @@ function reportDiagnosticsAsJson( return { errorCount, warningCount, - diagnosticCount: errorCount + warningCount + diagnosticCount: errorCount + warningCount, }; } @@ -324,15 +324,15 @@ function reportDiagnosticsAsText(fileDiagnostics: FileDiagnostics[]): Diagnostic let errorCount = 0; let warningCount = 0; - fileDiagnostics.forEach(fileDiagnostics => { + fileDiagnostics.forEach((fileDiagnostics) => { // Don't report unused code diagnostics. const fileErrorsAndWarnings = fileDiagnostics.diagnostics.filter( - diag => diag.category !== DiagnosticCategory.UnusedCode + (diag) => diag.category !== DiagnosticCategory.UnusedCode ); if (fileErrorsAndWarnings.length > 0) { console.log(`${fileDiagnostics.filePath}`); - fileErrorsAndWarnings.forEach(diag => { + fileErrorsAndWarnings.forEach((diag) => { let message = ' '; if (diag.range) { message += @@ -369,7 +369,7 @@ function reportDiagnosticsAsText(fileDiagnostics: FileDiagnostics[]): Diagnostic return { errorCount, warningCount, - diagnosticCount: errorCount + warningCount + diagnosticCount: errorCount + warningCount, }; } diff --git a/server/src/tests/checker.test.ts b/server/src/tests/checker.test.ts index 776330e10..cc47f911a 100644 --- a/server/src/tests/checker.test.ts +++ b/server/src/tests/checker.test.ts @@ -178,7 +178,7 @@ test('Builtins1', () => { 'zip', // These really shouldn't be exposed but are defined by builtins.pyi currently. 'function', - 'ellipsis' + 'ellipsis', ]; const moduleScope = AnalyzerNodeInfo.getScope(analysisResults[0].parseResults!.parseTree)!; diff --git a/server/src/tests/collectionUtils.test.ts b/server/src/tests/collectionUtils.test.ts index 1fa4e9fee..f876d9e67 100644 --- a/server/src/tests/collectionUtils.test.ts +++ b/server/src/tests/collectionUtils.test.ts @@ -37,7 +37,7 @@ test('UtilsAppendUndefinedValue', () => { test('UtilsFindEmpty', () => { const data: number[] = []; assert.equal( - utils.find(data, e => true), + utils.find(data, (e) => true), undefined ); }); @@ -45,7 +45,7 @@ test('UtilsFindEmpty', () => { test('UtilsFindNoMatch', () => { const data = [1]; assert.equal( - utils.find(data, e => false), + utils.find(data, (e) => false), undefined ); }); @@ -53,7 +53,7 @@ test('UtilsFindNoMatch', () => { test('UtilsFindMatchSimple', () => { const data = [1]; assert.equal( - utils.find(data, e => e === 1), + utils.find(data, (e) => e === 1), 1 ); }); @@ -61,7 +61,7 @@ test('UtilsFindMatchSimple', () => { test('UtilsFindMatch', () => { const data = [new D(1, 'Hello')]; assert.equal( - utils.find(data, e => e.value === 1), + utils.find(data, (e) => e.value === 1), data[0] ); }); @@ -81,21 +81,21 @@ test('UtilsStableSort', () => { const sorted = utils.stableSort(data, (a, b) => compareValues(a.value, b.value)); const result: string[] = []; - sorted.forEach(e => result.push(e.name)); + sorted.forEach((e) => result.push(e.name)); assert.deepEqual(result, ['Hello1', 'Hello2', 'Hello3', 'Hello4']); }); test('UtilsBinarySearch', () => { const data = [new D(1, 'Hello3'), new D(2, 'Hello1'), new D(3, 'Hello4'), new D(4, 'Hello2')]; - const index = utils.binarySearch(data, new D(3, 'Unused'), v => v.value, compareValues, 0); + const index = utils.binarySearch(data, new D(3, 'Unused'), (v) => v.value, compareValues, 0); assert.equal(index, 2); }); test('UtilsBinarySearchMiss', () => { const data = [new D(1, 'Hello3'), new D(2, 'Hello1'), new D(4, 'Hello4'), new D(5, 'Hello2')]; - const index = utils.binarySearch(data, new D(3, 'Unused'), v => v.value, compareValues, 0); + const index = utils.binarySearch(data, new D(3, 'Unused'), (v) => v.value, compareValues, 0); assert.equal(~index, 2); }); @@ -144,7 +144,7 @@ test('flatten', () => { const data: number[][] = [ [1, 2], [3, 4], - [5, 6] + [5, 6], ]; assert.deepEqual(utils.flatten(data), [1, 2, 3, 4, 5, 6]); }); diff --git a/server/src/tests/common.test.ts b/server/src/tests/common.test.ts index a559a929a..2be5d14a5 100644 --- a/server/src/tests/common.test.ts +++ b/server/src/tests/common.test.ts @@ -23,34 +23,34 @@ test('textRange overlap', () => { const textRangeOne: Range = { start: { line: 0, - character: 0 + character: 0, }, end: { line: 10, - character: 0 - } + character: 0, + }, }; const textRangeTwo: Range = { start: { line: 11, - character: 0 + character: 0, }, end: { line: 20, - character: 0 - } + character: 0, + }, }; const textRangeThree: Range = { start: { line: 5, - character: 0 + character: 0, }, end: { line: 15, - character: 0 - } + character: 0, + }, }; assert.equal(doRangesOverlap(textRangeOne, textRangeTwo), false); @@ -62,12 +62,12 @@ test('textRange contain', () => { const textRangeOne: Range = { start: { line: 0, - character: 5 + character: 5, }, end: { line: 10, - character: 1 - } + character: 1, + }, }; assert.equal(doesRangeContain(textRangeOne, { line: 0, character: 0 }), false); @@ -82,34 +82,34 @@ test('textRange equal', () => { const textRangeOne: Range = { start: { line: 0, - character: 0 + character: 0, }, end: { line: 10, - character: 0 - } + character: 0, + }, }; const textRangeTwo: Range = { start: { line: 0, - character: 0 + character: 0, }, end: { line: 10, - character: 0 - } + character: 0, + }, }; const textRangeThree: Range = { start: { line: 5, - character: 0 + character: 0, }, end: { line: 15, - character: 0 - } + character: 0, + }, }; assert.equal(rangesAreEqual(textRangeOne, textRangeTwo), true); diff --git a/server/src/tests/config.test.ts b/server/src/tests/config.test.ts index 5f33b48a6..2f4676448 100644 --- a/server/src/tests/config.test.ts +++ b/server/src/tests/config.test.ts @@ -54,7 +54,7 @@ test('FindFilesVirtualEnvAutoDetectExclude', () => { // There are 3 python files in the workspace, outside of myvenv // There is 1 python file in myvenv, which should be excluded - const fileNames = fileList.map(p => getBaseFileName(p)).sort(); + const fileNames = fileList.map((p) => getBaseFileName(p)).sort(); assert.deepEqual(fileNames, ['sample1.py', 'sample2.py', 'sample3.py']); }); @@ -72,7 +72,7 @@ test('FindFilesVirtualEnvAutoDetectInclude', () => { // There are 3 python files in the workspace, outside of myvenv // There is 1 more python file in excluded folder // There is 1 python file in myvenv, which should be included - const fileNames = fileList.map(p => getBaseFileName(p)).sort(); + const fileNames = fileList.map((p) => getBaseFileName(p)).sort(); assert.deepEqual(fileNames, ['library1.py', 'sample1.py', 'sample2.py', 'sample3.py']); }); @@ -201,8 +201,8 @@ test('AutoSearchPathsOn', () => { pythonPlatform: undefined, pythonVersion: 776, root: cwd, - extraPaths: [normalizePath(combinePaths(cwd, 'src'))] - } + extraPaths: [normalizePath(combinePaths(cwd, 'src'))], + }, ]; assert.deepEqual(configOptions.executionEnvironments, expectedExecEnvs); @@ -255,8 +255,8 @@ test('AutoSearchPathsOnWithConfigExecEnv', () => { pythonPlatform: undefined, pythonVersion: 773, root: cwd, - extraPaths: [] - } + extraPaths: [], + }, ]; assert.deepEqual(configOptions.executionEnvironments, expectedExecEnvs); diff --git a/server/src/tests/debug.test.ts b/server/src/tests/debug.test.ts index 7977dc953..889715508 100644 --- a/server/src/tests/debug.test.ts +++ b/server/src/tests/debug.test.ts @@ -81,7 +81,7 @@ test('DebugAssertNever', () => { const enum MyEnum { A, B, - C + C, } const unused = 5 as MyEnum; @@ -114,7 +114,7 @@ test('DebugFormatEnum', () => { enum MyEnum { A, B, - C + C, } assert(debug.formatEnum(MyEnum.A, MyEnum, false) === 'A'); }); diff --git a/server/src/tests/docStringToMarkdown.test.ts b/server/src/tests/docStringToMarkdown.test.ts index 8a2c5de4b..455c0a5c8 100644 --- a/server/src/tests/docStringToMarkdown.test.ts +++ b/server/src/tests/docStringToMarkdown.test.ts @@ -24,10 +24,10 @@ test('PlaintextIndention', () => { ['\nA\n B', 'A\n B'], ['\n A\n B', 'A\nB'], ['\nA\nB\n', 'A\nB'], - [' \n\nA \n \nB \n ', 'A\n\nB'] + [' \n\nA \n \nB \n ', 'A\n\nB'], ]; - all.forEach(v => _testConvertToMarkdown(v[0], v[1])); + all.forEach((v) => _testConvertToMarkdown(v[0], v[1])); }); test('NormalText', () => { diff --git a/server/src/tests/filesystem.test.ts b/server/src/tests/filesystem.test.ts index f26355faa..69355b0e4 100644 --- a/server/src/tests/filesystem.test.ts +++ b/server/src/tests/filesystem.test.ts @@ -66,7 +66,7 @@ test('CreateRich', () => { [normalizeSlashes('/a/b/2.txt')]: new vfs.File('hello2'), [normalizeSlashes('/a/3.txt')]: new vfs.File('hello3'), [normalizeSlashes('/4.txt')]: new vfs.File('hello4', { encoding: 'utf16le' }), - [normalizeSlashes('/a/b/../c/./5.txt')]: new vfs.File('hello5', { encoding: 'ucs2' }) + [normalizeSlashes('/a/b/../c/./5.txt')]: new vfs.File('hello5', { encoding: 'ucs2' }), }; const fs = new vfs.FileSystem(/*ignoreCase*/ true, { cwd, files }); @@ -151,7 +151,7 @@ test('createFromFileSystem1', () => { // file system will map physical file system to virtual one const fs = factory.createFromFileSystem(host.HOST, false, { documents: [new factory.TextDocument(filepath, content)], - cwd: factory.srcFolder + cwd: factory.srcFolder, }); // check existing typeshed folder on virtual path inherited from base snapshot from physical file system @@ -172,17 +172,17 @@ test('createFromFileSystemWithCustomTypeshedPath', () => { const invalidpath = normalizeSlashes(combinePaths(host.HOST.getWorkspaceRoot(), '../docs')); const fs = factory.createFromFileSystem(host.HOST, /* ignoreCase */ false, { cwd: factory.srcFolder, - meta: { [factory.typeshedFolder]: invalidpath } + meta: { [factory.typeshedFolder]: invalidpath }, }); const entries = fs.readdirSync(factory.typeshedFolder); - assert(entries.filter(e => e.endsWith('.md')).length > 0); + assert(entries.filter((e) => e.endsWith('.md')).length > 0); }); test('createFromFileSystemWithMetadata', () => { const fs = factory.createFromFileSystem(host.HOST, /* ignoreCase */ false, { cwd: factory.srcFolder, - meta: { unused: 'unused' } + meta: { unused: 'unused' }, }); assert(fs.existsSync(factory.srcFolder)); diff --git a/server/src/tests/fourSlashParser.test.ts b/server/src/tests/fourSlashParser.test.ts index 399ce7fe9..d26a8eb63 100644 --- a/server/src/tests/fourSlashParser.test.ts +++ b/server/src/tests/fourSlashParser.test.ts @@ -32,7 +32,7 @@ test('GlobalOptions', () => { const data = parseTestData('.', code, 'test.py'); assertOptions(data.globalOptions, [ ['libpath', '../dist/lib'], - ['pythonversion', '3.7'] + ['pythonversion', '3.7'], ]); assert.equal(data.files.length, 1); @@ -74,7 +74,7 @@ test('Extra file options', () => { assertOptions(data.globalOptions, []); assertOptions(data.files[0].fileOptions, [ ['filename', 'file1.py'], - ['library', 'false'] + ['library', 'false'], ]); }); @@ -220,12 +220,13 @@ test('Multiple Files', () => { const data = parseTestData('.', code, 'test.py'); assert.equal(data.files.length, 3); - assert.equal(data.files.filter(f => f.fileName === normalizeSlashes('./src/A.py'))[0].content, getContent('A')); + assert.equal(data.files.filter((f) => f.fileName === normalizeSlashes('./src/A.py'))[0].content, getContent('A')); assert.equal( - data.files.filter(f => f.fileName === normalizeSlashes(combinePaths(factory.libFolder, 'src/B.py')))[0].content, + data.files.filter((f) => f.fileName === normalizeSlashes(combinePaths(factory.libFolder, 'src/B.py')))[0] + .content, getContent('B') ); - assert.equal(data.files.filter(f => f.fileName === normalizeSlashes('./src/C.py'))[0].content, getContent('C')); + assert.equal(data.files.filter((f) => f.fileName === normalizeSlashes('./src/C.py'))[0].content, getContent('C')); }); test('Multiple Files with default name', () => { @@ -246,9 +247,12 @@ test('Multiple Files with default name', () => { const data = parseTestData('.', code, './src/test.py'); assert.equal(data.files.length, 3); - assert.equal(data.files.filter(f => f.fileName === normalizeSlashes('./src/test.py'))[0].content, getContent('A')); - assert.equal(data.files.filter(f => f.fileName === normalizeSlashes('./src/B.py'))[0].content, getContent('B')); - assert.equal(data.files.filter(f => f.fileName === normalizeSlashes('./src/C.py'))[0].content, getContent('C')); + assert.equal( + data.files.filter((f) => f.fileName === normalizeSlashes('./src/test.py'))[0].content, + getContent('A') + ); + assert.equal(data.files.filter((f) => f.fileName === normalizeSlashes('./src/B.py'))[0].content, getContent('B')); + assert.equal(data.files.filter((f) => f.fileName === normalizeSlashes('./src/C.py'))[0].content, getContent('C')); }); test('Multiple Files with markers', () => { @@ -270,16 +274,16 @@ test('Multiple Files with markers', () => { const data = parseTestData('.', code, 'test.py'); assert.equal(data.files.length, 3); - assert.equal(data.files.filter(f => f.fileName === normalizeSlashes('./src/A.py'))[0].content, getContent('A')); - assert.equal(data.files.filter(f => f.fileName === normalizeSlashes('./src/B.py'))[0].content, getContent('B')); - assert.equal(data.files.filter(f => f.fileName === normalizeSlashes('./src/C.py'))[0].content, getContent('C')); + assert.equal(data.files.filter((f) => f.fileName === normalizeSlashes('./src/A.py'))[0].content, getContent('A')); + assert.equal(data.files.filter((f) => f.fileName === normalizeSlashes('./src/B.py'))[0].content, getContent('B')); + assert.equal(data.files.filter((f) => f.fileName === normalizeSlashes('./src/C.py'))[0].content, getContent('C')); assert.equal(data.ranges.length, 3); assert(data.markerPositions.get('marker1')); assert(data.markerPositions.get('marker2')); - assert.equal(data.ranges.filter(r => r.marker).length, 2); + assert.equal(data.ranges.filter((r) => r.marker).length, 2); }); test('fourSlashWithFileSystem', () => { @@ -299,12 +303,12 @@ test('fourSlashWithFileSystem', () => { const data = parseTestData('.', code, 'unused'); const documents = data.files.map( - f => new factory.TextDocument(f.fileName, f.content, new Map(Object.entries(f.fileOptions))) + (f) => new factory.TextDocument(f.fileName, f.content, new Map(Object.entries(f.fileOptions))) ); const fs = factory.createFromFileSystem(host.HOST, /* ignoreCase */ false, { documents, - cwd: normalizeSlashes('/') + cwd: normalizeSlashes('/'), }); for (const file of data.files) { diff --git a/server/src/tests/fourSlashRunner.test.ts b/server/src/tests/fourSlashRunner.test.ts index cf5245308..d6e9c7267 100644 --- a/server/src/tests/fourSlashRunner.test.ts +++ b/server/src/tests/fourSlashRunner.test.ts @@ -22,13 +22,13 @@ describe('fourslash tests', () => { testFiles.push(file); } - testFiles.forEach(file => { + testFiles.forEach((file) => { describe(file, () => { const fn = normalizeSlashes(file); const justName = fn.replace(/^.*[\\/]/, ''); // TODO: make these to use promise/async rather than callback token - it('fourslash test ' + justName + ' runs correctly', cb => { + it('fourslash test ' + justName + ' runs correctly', (cb) => { runFourSlashTest(MODULE_PATH, fn, cb); }); }); diff --git a/server/src/tests/fourslash/completions.excluded.fourslash.ts b/server/src/tests/fourslash/completions.excluded.fourslash.ts index 8928bd99a..83ce3e514 100644 --- a/server/src/tests/fourslash/completions.excluded.fourslash.ts +++ b/server/src/tests/fourslash/completions.excluded.fourslash.ts @@ -6,6 +6,6 @@ helper.verifyCompletion('excluded', { marker1: { - completions: [{ label: 'capitalize' }] - } + completions: [{ label: 'capitalize' }], + }, }); diff --git a/server/src/tests/fourslash/completions.fourslash.ts b/server/src/tests/fourslash/completions.fourslash.ts index 5eace5b02..42c177d32 100644 --- a/server/src/tests/fourslash/completions.fourslash.ts +++ b/server/src/tests/fourslash/completions.fourslash.ts @@ -22,16 +22,16 @@ helper.verifyCompletion('exact', { label: 'some_func1', documentation: { kind: 'markdown', - value: '```python\nsome_func1: (a) -> None\n```\n---\nsome function docs' - } + value: '```python\nsome_func1: (a) -> None\n```\n---\nsome function docs', + }, }, { label: 'some_func2', documentation: { kind: 'markdown', - value: '```python\nsome_func2: (a) -> None\n```\n---\nanother function docs' - } - } - ] - } + value: '```python\nsome_func2: (a) -> None\n```\n---\nanother function docs', + }, + }, + ], + }, }); diff --git a/server/src/tests/fourslash/completions.included.fourslash.ts b/server/src/tests/fourslash/completions.included.fourslash.ts index db6d87671..c77b881fd 100644 --- a/server/src/tests/fourslash/completions.included.fourslash.ts +++ b/server/src/tests/fourslash/completions.included.fourslash.ts @@ -6,6 +6,6 @@ helper.verifyCompletion('included', { marker1: { - completions: [{ label: 'denominator' }, { label: 'imag' }, { label: 'numerator' }, { label: 'real' }] - } + completions: [{ label: 'denominator' }, { label: 'imag' }, { label: 'numerator' }, { label: 'real' }], + }, }); diff --git a/server/src/tests/fourslash/completions.libCodeAndStub.fourslash.skip.ts b/server/src/tests/fourslash/completions.libCodeAndStub.fourslash.skip.ts index 2040cd037..705fab295 100644 --- a/server/src/tests/fourslash/completions.libCodeAndStub.fourslash.skip.ts +++ b/server/src/tests/fourslash/completions.libCodeAndStub.fourslash.skip.ts @@ -30,10 +30,10 @@ helper.verifyCompletion('included', { label: 'Validator', documentation: { kind: 'markdown', - value: '```python\nclass Validator()\n```\n---\nThe validator class' - } - } - ] + value: '```python\nclass Validator()\n```\n---\nThe validator class', + }, + }, + ], }, marker2: { completions: [ @@ -42,9 +42,9 @@ helper.verifyCompletion('included', { documentation: { kind: 'markdown', value: - '```python\nis_valid: (self: Validator, text: str) -> bool\n```\n---\nChecks if the input string is valid.' - } - } - ] - } + '```python\nis_valid: (self: Validator, text: str) -> bool\n```\n---\nChecks if the input string is valid.', + }, + }, + ], + }, }); diff --git a/server/src/tests/fourslash/completions.libCodeNoStub.fourslash.ts b/server/src/tests/fourslash/completions.libCodeNoStub.fourslash.ts index 23ac082f6..1c0a07622 100644 --- a/server/src/tests/fourslash/completions.libCodeNoStub.fourslash.ts +++ b/server/src/tests/fourslash/completions.libCodeNoStub.fourslash.ts @@ -25,10 +25,10 @@ helper.verifyCompletion('included', { label: 'Validator', documentation: { kind: 'markdown', - value: '```python\nclass Validator()\n```\n---\nThe validator class' - } - } - ] + value: '```python\nclass Validator()\n```\n---\nThe validator class', + }, + }, + ], }, marker2: { completions: [ @@ -37,9 +37,9 @@ helper.verifyCompletion('included', { documentation: { kind: 'markdown', value: - '```python\nis_valid: (self: Validator, text: str) -> bool\n```\n---\nChecks if the input string is valid.' - } - } - ] - } + '```python\nis_valid: (self: Validator, text: str) -> bool\n```\n---\nChecks if the input string is valid.', + }, + }, + ], + }, }); diff --git a/server/src/tests/fourslash/completions.libStub.fourslash.ts b/server/src/tests/fourslash/completions.libStub.fourslash.ts index 48fb89be8..3caeb3c52 100644 --- a/server/src/tests/fourslash/completions.libStub.fourslash.ts +++ b/server/src/tests/fourslash/completions.libStub.fourslash.ts @@ -25,10 +25,10 @@ helper.verifyCompletion('included', { label: 'Validator', documentation: { kind: 'markdown', - value: '```python\nclass Validator()\n```\n---\nThe validator class' - } - } - ] + value: '```python\nclass Validator()\n```\n---\nThe validator class', + }, + }, + ], }, marker2: { completions: [ @@ -37,9 +37,9 @@ helper.verifyCompletion('included', { documentation: { kind: 'markdown', value: - '```python\nis_valid: (self: Validator, text: str) -> bool\n```\n---\nChecks if the input string is valid.' - } - } - ] - } + '```python\nis_valid: (self: Validator, text: str) -> bool\n```\n---\nChecks if the input string is valid.', + }, + }, + ], + }, }); diff --git a/server/src/tests/fourslash/dataclass4.fourslash.ts b/server/src/tests/fourslash/dataclass4.fourslash.ts index 257bb28d7..0c3637ac4 100644 --- a/server/src/tests/fourslash/dataclass4.fourslash.ts +++ b/server/src/tests/fourslash/dataclass4.fourslash.ts @@ -53,12 +53,12 @@ helper.verifyDiagnostics({ marker1: { category: 'error', message: `No parameter named "ddd"` }, marker2: { category: 'error', - message: `Argument of type "Literal['hello']" cannot be assigned to parameter "bbb" of type "int"\n "str" is incompatible with "int"` + message: `Argument of type "Literal['hello']" cannot be assigned to parameter "bbb" of type "int"\n "str" is incompatible with "int"`, }, marker3: { category: 'error', message: `Argument missing for parameter "ccc"` }, marker4: { category: 'error', message: 'Expected 3 positional arguments' }, marker5: { category: 'error', - message: 'Data fields without default value cannot appear after data fields with default values' - } + message: 'Data fields without default value cannot appear after data fields with default values', + }, }); diff --git a/server/src/tests/fourslash/dataclass5.fourslash.ts b/server/src/tests/fourslash/dataclass5.fourslash.ts index f9b1b68a2..0c9c71154 100644 --- a/server/src/tests/fourslash/dataclass5.fourslash.ts +++ b/server/src/tests/fourslash/dataclass5.fourslash.ts @@ -49,5 +49,5 @@ helper.verifyDiagnostics({ marker1: { category: 'error', message: `Expected no arguments to "D" constructor` }, - marker2: { category: 'error', message: `"D(3)" has type "Type[D]" and is not callable` } + marker2: { category: 'error', message: `"D(3)" has type "Type[D]" and is not callable` }, }); diff --git a/server/src/tests/fourslash/dataclass6.fourslash.ts b/server/src/tests/fourslash/dataclass6.fourslash.ts index b8db032e9..6401f2c3d 100644 --- a/server/src/tests/fourslash/dataclass6.fourslash.ts +++ b/server/src/tests/fourslash/dataclass6.fourslash.ts @@ -30,5 +30,5 @@ helper.verifyDiagnostics({ marker1: { category: 'error', message: 'Expected 1 positional argument' }, - marker2: { category: 'error', message: `Argument missing for parameter "y"` } + marker2: { category: 'error', message: `Argument missing for parameter "y"` }, }); diff --git a/server/src/tests/fourslash/dataclass7.fourslash.ts b/server/src/tests/fourslash/dataclass7.fourslash.ts index 256a808bc..7e3a0db22 100644 --- a/server/src/tests/fourslash/dataclass7.fourslash.ts +++ b/server/src/tests/fourslash/dataclass7.fourslash.ts @@ -56,10 +56,10 @@ helper.verifyDiagnostics({ marker1: { category: 'error', - message: `Argument of type "C1" cannot be assigned to parameter "aa" of type "C2"\n "C1" is incompatible with "C2"` + message: `Argument of type "C1" cannot be assigned to parameter "aa" of type "C2"\n "C1" is incompatible with "C2"`, }, marker2: { category: 'error', - message: 'Data fields without default value cannot appear after data fields with default values' - } + message: 'Data fields without default value cannot appear after data fields with default values', + }, }); diff --git a/server/src/tests/fourslash/fourslash.ts b/server/src/tests/fourslash/fourslash.ts index 30512e34a..46a97b4f2 100644 --- a/server/src/tests/fourslash/fourslash.ts +++ b/server/src/tests/fourslash/fourslash.ts @@ -143,6 +143,6 @@ declare namespace Consts { createTypeStub = 'pyright.createtypestub', restartServer = 'pyright.restartserver', orderImports = 'pyright.organizeimports', - addMissingOptionalToParam = 'pyright.addoptionalforparam' + addMissingOptionalToParam = 'pyright.addoptionalforparam', } } diff --git a/server/src/tests/fourslash/hover.fourslash.ts b/server/src/tests/fourslash/hover.fourslash.ts index fe842db21..1d5b1b4e9 100644 --- a/server/src/tests/fourslash/hover.fourslash.ts +++ b/server/src/tests/fourslash/hover.fourslash.ts @@ -18,6 +18,6 @@ helper.verifyHover({ marker1: { value: '```python\n(class) Validator\n```\nThe validator class', kind: 'markdown' }, marker2: { value: '```python\n(method) is_valid: (text: str) -> bool\n```\nChecks if the input string is valid.', - kind: 'markdown' - } + kind: 'markdown', + }, }); diff --git a/server/src/tests/fourslash/hover.libCodeAndStub.fourslash.skip.ts b/server/src/tests/fourslash/hover.libCodeAndStub.fourslash.skip.ts index 60c11bf55..c5df5fc40 100644 --- a/server/src/tests/fourslash/hover.libCodeAndStub.fourslash.skip.ts +++ b/server/src/tests/fourslash/hover.libCodeAndStub.fourslash.skip.ts @@ -27,6 +27,6 @@ helper.verifyHover({ marker1: { value: '```python\n(class) Validator\n```\nThe validator class', kind: 'markdown' }, marker2: { value: '```python\n(method) is_valid: (text: str) -> bool\n```\nChecks if the input string is valid.', - kind: 'markdown' - } + kind: 'markdown', + }, }); diff --git a/server/src/tests/fourslash/hover.libCodeNoStub.fourslash.ts b/server/src/tests/fourslash/hover.libCodeNoStub.fourslash.ts index 51e11eed4..268f00e5b 100644 --- a/server/src/tests/fourslash/hover.libCodeNoStub.fourslash.ts +++ b/server/src/tests/fourslash/hover.libCodeNoStub.fourslash.ts @@ -22,6 +22,6 @@ helper.verifyHover({ marker1: { value: '```python\n(class) Validator\n```\nThe validator class', kind: 'markdown' }, marker2: { value: '```python\n(method) is_valid: (text: str) -> bool\n```\nChecks if the input string is valid.', - kind: 'markdown' - } + kind: 'markdown', + }, }); diff --git a/server/src/tests/fourslash/hover.libStub.fourslash.ts b/server/src/tests/fourslash/hover.libStub.fourslash.ts index c35767c09..a636b677c 100644 --- a/server/src/tests/fourslash/hover.libStub.fourslash.ts +++ b/server/src/tests/fourslash/hover.libStub.fourslash.ts @@ -22,6 +22,6 @@ helper.verifyHover({ marker1: { value: '```python\n(class) Validator\n```\nThe validator class', kind: 'markdown' }, marker2: { value: '```python\n(method) is_valid: (text: str) -> bool\n```\nChecks if the input string is valid.', - kind: 'markdown' - } + kind: 'markdown', + }, }); diff --git a/server/src/tests/fourslash/importnotresolved.fourslash.ts b/server/src/tests/fourslash/importnotresolved.fourslash.ts index 397811467..c6e2cee31 100644 --- a/server/src/tests/fourslash/importnotresolved.fourslash.ts +++ b/server/src/tests/fourslash/importnotresolved.fourslash.ts @@ -9,5 +9,5 @@ helper.verifyDiagnostics({ marker1: { category: 'error', message: `Import "notexistant" could not be resolved` }, - marker2: { category: 'error', message: `Import "django" could not be resolved` } + marker2: { category: 'error', message: `Import "django" could not be resolved` }, }); diff --git a/server/src/tests/fourslash/missingTypeStub.codeAction.fourslash.ts b/server/src/tests/fourslash/missingTypeStub.codeAction.fourslash.ts index 0fc0ed340..706a64d70 100644 --- a/server/src/tests/fourslash/missingTypeStub.codeAction.fourslash.ts +++ b/server/src/tests/fourslash/missingTypeStub.codeAction.fourslash.ts @@ -24,9 +24,9 @@ helper.verifyCodeActions({ command: { title: 'Create Type Stub', command: Consts.Commands.createTypeStub, - arguments: ['\\', 'testLib', '\\.src\\test.py'] - } - } - ] - } + arguments: ['\\', 'testLib', '\\.src\\test.py'], + }, + }, + ], + }, }); diff --git a/server/src/tests/fourslash/missingTypeStub.command.fourslash.ts b/server/src/tests/fourslash/missingTypeStub.command.fourslash.ts index 4a4a9faf2..4afb7fa52 100644 --- a/server/src/tests/fourslash/missingTypeStub.command.fourslash.ts +++ b/server/src/tests/fourslash/missingTypeStub.command.fourslash.ts @@ -20,7 +20,7 @@ const filename = helper.getMarkerByName('marker').fileName; const command = { title: 'Create Type Stub', command: Consts.Commands.createTypeStub, - arguments: ['/', 'testLib', filename] + arguments: ['/', 'testLib', filename], }; helper.verifyCommand(command, { @@ -34,5 +34,5 @@ class MyLibrary: -` +`, }); diff --git a/server/src/tests/fourslash/missingTypeStub.fourslash.ts b/server/src/tests/fourslash/missingTypeStub.fourslash.ts index afe97f2fc..d778c8461 100644 --- a/server/src/tests/fourslash/missingTypeStub.fourslash.ts +++ b/server/src/tests/fourslash/missingTypeStub.fourslash.ts @@ -16,5 +16,5 @@ //// import [|/*marker*/testLi|]b helper.verifyDiagnostics({ - marker: { category: 'warning', message: `Stub file not found for "testLib"` } + marker: { category: 'warning', message: `Stub file not found for "testLib"` }, }); diff --git a/server/src/tests/fourslash/missingTypeStub.invokeCodeAction.fourslash.ts b/server/src/tests/fourslash/missingTypeStub.invokeCodeAction.fourslash.ts index da9ed5590..23fa95115 100644 --- a/server/src/tests/fourslash/missingTypeStub.invokeCodeAction.fourslash.ts +++ b/server/src/tests/fourslash/missingTypeStub.invokeCodeAction.fourslash.ts @@ -30,7 +30,7 @@ class MyLibrary: -` - } - } +`, + }, + }, }); diff --git a/server/src/tests/fourslash/orderImports1.command.fourslash.ts b/server/src/tests/fourslash/orderImports1.command.fourslash.ts index 30bee3e6a..4c3c06a74 100644 --- a/server/src/tests/fourslash/orderImports1.command.fourslash.ts +++ b/server/src/tests/fourslash/orderImports1.command.fourslash.ts @@ -10,11 +10,11 @@ helper.verifyCommand( { title: 'Quick action order imports 1', command: Consts.Commands.orderImports, - arguments: ['quickActionOrganizeImportTest1.py'] + arguments: ['quickActionOrganizeImportTest1.py'], }, { ['quickActionOrganizeImportTest1.py']: `import os import sys -import time` +import time`, } ); diff --git a/server/src/tests/fourslash/orderImports2.command.fourslash.ts b/server/src/tests/fourslash/orderImports2.command.fourslash.ts index b7f566980..42e290827 100644 --- a/server/src/tests/fourslash/orderImports2.command.fourslash.ts +++ b/server/src/tests/fourslash/orderImports2.command.fourslash.ts @@ -13,12 +13,12 @@ helper.verifyCommand( { title: 'Quick action order imports', command: Consts.Commands.orderImports, - arguments: ['quickActionOrganizeImportTest2.py'] + arguments: ['quickActionOrganizeImportTest2.py'], }, { ['quickActionOrganizeImportTest2.py']: `import math import os import sys -import time` +import time`, } ); diff --git a/server/src/tests/fourslash/signature.complicated.fourslash.ts b/server/src/tests/fourslash/signature.complicated.fourslash.ts index ecb338d11..e7e97e895 100644 --- a/server/src/tests/fourslash/signature.complicated.fourslash.ts +++ b/server/src/tests/fourslash/signature.complicated.fourslash.ts @@ -25,73 +25,73 @@ const xInitSignatures = [ { label: '(x: bool) -> None', - parameters: ['x: bool'] - } + parameters: ['x: bool'], + }, ]; const xComplicatedSignatures = [ { label: '(a: int, b: int, c: int = 1234, d: Optional[str] = None, **kwargs) -> Union[int, str]', - parameters: ['a: int', 'b: int', 'c: int = 1234', 'd: Optional[str] = None', '**kwargs'] - } + parameters: ['a: int', 'b: int', 'c: int = 1234', 'd: Optional[str] = None', '**kwargs'], + }, ]; const xCallSignatures = [ { label: '(z: float) -> complex', - parameters: ['z: float'] - } + parameters: ['z: float'], + }, ]; helper.verifySignature({ init: { signatures: xInitSignatures, activeParameter: 0, - activeSignature: 0 + activeSignature: 0, }, c1: { signatures: xComplicatedSignatures, activeParameter: 0, - activeSignature: 0 + activeSignature: 0, }, c2: { signatures: xComplicatedSignatures, activeParameter: 1, - activeSignature: 0 + activeSignature: 0, }, c3: { signatures: xComplicatedSignatures, activeParameter: 1, - activeSignature: 0 + activeSignature: 0, }, cA: { signatures: xComplicatedSignatures, activeParameter: 0, - activeSignature: 0 + activeSignature: 0, }, cB: { signatures: xComplicatedSignatures, activeParameter: 1, - activeSignature: 0 + activeSignature: 0, }, cX: { signatures: xComplicatedSignatures, activeParameter: 4, - activeSignature: 0 + activeSignature: 0, }, cD: { signatures: xComplicatedSignatures, activeParameter: 3, - activeSignature: 0 + activeSignature: 0, }, cZ: { signatures: xComplicatedSignatures, activeParameter: 4, - activeSignature: 0 + activeSignature: 0, }, call: { signatures: xCallSignatures, activeParameter: 0, - activeSignature: 0 - } + activeSignature: 0, + }, }); diff --git a/server/src/tests/fourslash/signature.overload.fourslash.ts b/server/src/tests/fourslash/signature.overload.fourslash.ts index 66bf076ae..bdfb1482a 100644 --- a/server/src/tests/fourslash/signature.overload.fourslash.ts +++ b/server/src/tests/fourslash/signature.overload.fourslash.ts @@ -20,37 +20,37 @@ const overloadedSignatures = [ { label: '(x: int) -> int', - parameters: ['x: int'] + parameters: ['x: int'], }, { label: '(x: int, y: int) -> str', - parameters: ['x: int', 'y: int'] + parameters: ['x: int', 'y: int'], }, { label: '(*args) -> None', - parameters: ['*args'] - } + parameters: ['*args'], + }, ]; helper.verifySignature({ o1: { signatures: overloadedSignatures, activeParameter: 0, - activeSignature: 0 + activeSignature: 0, }, o2: { signatures: overloadedSignatures, activeParameter: 1, - activeSignature: 1 + activeSignature: 1, }, o3: { signatures: overloadedSignatures, activeParameter: 0, - activeSignature: 2 + activeSignature: 2, }, o4: { signatures: overloadedSignatures, activeParameter: 0, - activeSignature: 2 - } + activeSignature: 2, + }, }); diff --git a/server/src/tests/fourslash/signature.simple.fourslash.ts b/server/src/tests/fourslash/signature.simple.fourslash.ts index aeefb016d..b4dde1cff 100644 --- a/server/src/tests/fourslash/signature.simple.fourslash.ts +++ b/server/src/tests/fourslash/signature.simple.fourslash.ts @@ -16,50 +16,50 @@ const simpleSignatures = [ { label: '(x: int, y: int) -> int', - parameters: ['x: int', 'y: int'] - } + parameters: ['x: int', 'y: int'], + }, ]; helper.verifySignature({ s1: { signatures: simpleSignatures, activeParameter: 0, - activeSignature: 0 + activeSignature: 0, }, s2: { signatures: simpleSignatures, activeParameter: 1, - activeSignature: 0 + activeSignature: 0, }, s3: { signatures: simpleSignatures, activeParameter: 0, - activeSignature: 0 + activeSignature: 0, }, s4: { signatures: simpleSignatures, activeParameter: 0, - activeSignature: 0 + activeSignature: 0, }, s5: { signatures: simpleSignatures, activeParameter: 1, - activeSignature: 0 + activeSignature: 0, }, s6: { signatures: simpleSignatures, activeParameter: 1, - activeSignature: 0 + activeSignature: 0, }, s7: { signatures: simpleSignatures, activeParameter: 1, - activeSignature: 0 + activeSignature: 0, }, sOutside: { - noSig: true + noSig: true, }, sNoCall: { - noSig: true - } + noSig: true, + }, }); diff --git a/server/src/tests/harness/fourslash/fourSlashParser.ts b/server/src/tests/harness/fourslash/fourSlashParser.ts index 8b36d417d..2ffa45c6b 100644 --- a/server/src/tests/harness/fourslash/fourSlashParser.ts +++ b/server/src/tests/harness/fourslash/fourSlashParser.ts @@ -13,7 +13,7 @@ import { getRelativePath, isRootedDiskPath, normalizePath, - normalizeSlashes + normalizeSlashes, } from '../../../common/pathUtils'; import { libFolder } from '../vfs/factory'; import { fileMetadataNames, FourSlashData, FourSlashFile, Marker, MetadataOptionNames, Range } from './fourSlashTypes'; @@ -130,7 +130,7 @@ export function parseTestData(basePath: string, contents: string, fileName: stri markers, globalOptions, files, - ranges + ranges, }; } @@ -148,7 +148,7 @@ interface RangeLocationInformation extends LocationInformation { const enum State { none, inSlashStarMarker, - inObjectMarker + inObjectMarker, } function reportError(fileName: string, line: number, col: number, message: string) { @@ -179,7 +179,7 @@ function recordObjectMarker( const marker: Marker = { fileName, position: location.position, - data: markerValue + data: markerValue, }; // Object markers can be anonymous @@ -201,7 +201,7 @@ function recordMarker( ): Marker | undefined { const marker: Marker = { fileName, - position: location.position + position: location.position, }; // Verify markers for uniqueness @@ -274,7 +274,7 @@ function parseFileContent( position: i - 1 - difference, sourcePosition: i - 1, sourceLine: line, - sourceColumn: column + sourceColumn: column, }); // copy all text up to marker position flush(i - 1); @@ -291,7 +291,7 @@ function parseFileContent( fileName, pos: rangeStart!.position, end: i - 1 - difference, - marker: rangeStart!.marker + marker: rangeStart!.marker, }; localRanges.push(range); @@ -306,7 +306,7 @@ function parseFileContent( position: i - 1 - difference, sourcePosition: i - 1, sourceLine: line, - sourceColumn: column + sourceColumn: column, }; } else if (previousChar === '{' && currentChar === '|') { // found an object marker start @@ -315,7 +315,7 @@ function parseFileContent( position: i - 1 - difference, sourcePosition: i - 1, sourceLine: line, - sourceColumn: column + sourceColumn: column, }; flush(i - 1); } @@ -411,7 +411,7 @@ function parseFileContent( // put ranges in the correct order localRanges = localRanges.sort((a, b) => (a.pos < b.pos ? -1 : a.pos === b.pos && a.end > b.end ? -1 : 1)); - localRanges.forEach(r => { + localRanges.forEach((r) => { ranges.push(r); }); @@ -419,7 +419,7 @@ function parseFileContent( content: output, fileOptions: {}, version: 0, - fileName + fileName, }; } @@ -431,5 +431,5 @@ function chompLeadingSpace(content: string) { } } - return lines.map(s => s.substr(1)).join('\n'); + return lines.map((s) => s.substr(1)).join('\n'); } diff --git a/server/src/tests/harness/fourslash/fourSlashTypes.ts b/server/src/tests/harness/fourslash/fourSlashTypes.ts index 6d2065cd3..a3701fe91 100644 --- a/server/src/tests/harness/fourslash/fourSlashTypes.ts +++ b/server/src/tests/harness/fourslash/fourSlashTypes.ts @@ -15,13 +15,13 @@ export const enum GlobalMetadataOptionNames { projectRoot = 'projectroot', ignoreCase = 'ignorecase', typeshed = 'typeshed', - asynctest = 'asynctest' + asynctest = 'asynctest', } /** Any option name not belong to this will become global option */ export const enum MetadataOptionNames { fileName = 'filename', - library = 'library' + library = 'library', } /** List of allowed file metadata names */ diff --git a/server/src/tests/harness/fourslash/runner.ts b/server/src/tests/harness/fourslash/runner.ts index 18a52e684..6061ed10f 100644 --- a/server/src/tests/harness/fourslash/runner.ts +++ b/server/src/tests/harness/fourslash/runner.ts @@ -57,7 +57,7 @@ export function runFourSlashTestContent( const state = new TestState(absoluteBasePath, testData, cb, mountPaths, importResolverFactory); const output = ts.transpileModule(content, { reportDiagnostics: true, - compilerOptions: { target: ts.ScriptTarget.ES2015 } + compilerOptions: { target: ts.ScriptTarget.ES2015 }, }); if (output.diagnostics!.length > 0) { throw new Error(`Syntax error in ${absoluteBasePath}: ${output.diagnostics![0].messageText}`); diff --git a/server/src/tests/harness/fourslash/testLanguageService.ts b/server/src/tests/harness/fourslash/testLanguageService.ts index 4a5af74c4..98706b1c1 100644 --- a/server/src/tests/harness/fourslash/testLanguageService.ts +++ b/server/src/tests/harness/fourslash/testLanguageService.ts @@ -15,7 +15,7 @@ import { LanguageServerInterface, ServerSettings, WindowInterface, - WorkspaceServiceInstance + WorkspaceServiceInstance, } from '../../../languageServerBase'; export class TestLanguageService implements LanguageServerInterface { @@ -37,7 +37,7 @@ export class TestLanguageService implements LanguageServerInterface { typeshedPath: this._workspace.serviceInstance.test_configOptions.typeshedPath, openFilesOnly: this._workspace.serviceInstance.test_configOptions.checkOnlyOpenFiles, useLibraryCodeForTypes: this._workspace.serviceInstance.test_configOptions.useLibraryCodeForTypes, - disableLanguageServices: this._workspace.disableLanguageServices + disableLanguageServices: this._workspace.disableLanguageServices, }; return settings; diff --git a/server/src/tests/harness/fourslash/testState.Consts.ts b/server/src/tests/harness/fourslash/testState.Consts.ts index 11ce0845f..543720bf7 100644 --- a/server/src/tests/harness/fourslash/testState.Consts.ts +++ b/server/src/tests/harness/fourslash/testState.Consts.ts @@ -21,6 +21,6 @@ export namespace Consts { createTypeStub = 'pyright.createtypestub', restartServer = 'pyright.restartserver', orderImports = 'pyright.organizeimports', - addMissingOptionalToParam = 'pyright.addoptionalforparam' + addMissingOptionalToParam = 'pyright.addoptionalforparam', } } diff --git a/server/src/tests/harness/fourslash/testState.ts b/server/src/tests/harness/fourslash/testState.ts index 713ad68a7..3d0cf626c 100644 --- a/server/src/tests/harness/fourslash/testState.ts +++ b/server/src/tests/harness/fourslash/testState.ts @@ -26,7 +26,7 @@ import { convertPathToUri, getBaseFileName, normalizePath, - normalizeSlashes + normalizeSlashes, } from '../../../common/pathUtils'; import { convertOffsetToPosition, convertPositionToOffset } from '../../../common/positionUtils'; import { getStringComparer } from '../../../common/stringUtils'; @@ -50,7 +50,7 @@ import { MultiMap, pythonSettingFilename, Range, - TestCancellationToken + TestCancellationToken, } from './fourSlashTypes'; import { TestLanguageService } from './testLanguageService'; @@ -138,7 +138,7 @@ export class TestState { rootPath: this.fs.getModulePath(), rootUri: convertPathToUri(this.fs.getModulePath()), serviceInstance: service, - disableLanguageServices: false + disableLanguageServices: false, }; if (this._files.length > 0) { @@ -218,7 +218,7 @@ export class TestState { if (markerPos === undefined) { throw new Error( `Unknown marker "${markerName}" Available markers: ${this.getMarkerNames() - .map(m => '"' + m + '"') + .map((m) => '"' + m + '"') .join(', ')}` ); } else { @@ -291,14 +291,14 @@ export class TestState { } getRangesInFile(fileName = this.activeFile.fileName) { - return this.getRanges().filter(r => r.fileName === fileName); + return this.getRanges().filter((r) => r.fileName === fileName); } getRangesByText(): Map { if (this.testData.rangesByText) { return this.testData.rangesByText; } - const result = this._createMultiMap(this.getRanges(), r => this._rangeText(r)); + const result = this._createMultiMap(this.getRanges(), (r) => this._rangeText(r)); this.testData.rangesByText = result; return result; @@ -375,7 +375,7 @@ export class TestState { const startPos = this._convertPositionToOffset(this.activeFile.fileName, { line: startIndex, character: 0 }); const endPos = this._convertPositionToOffset(this.activeFile.fileName, { line: endIndexInclusive + 1, - character: 0 + character: 0, }); this.replace(startPos, endPos - startPos, ''); } @@ -433,7 +433,7 @@ export class TestState { // organize things per file const resultPerFile = this._getDiagnosticsPerFile(); - const rangePerFile = this._createMultiMap(this.getRanges(), r => r.fileName); + const rangePerFile = this._createMultiMap(this.getRanges(), (r) => r.fileName); if (!hasDiagnostics(resultPerFile) && rangePerFile.size === 0) { // no errors and no error is expected. we are done @@ -450,7 +450,7 @@ export class TestState { } for (const [file, ranges] of rangePerFile.entries()) { - const rangesPerCategory = this._createMultiMap(ranges, r => { + const rangesPerCategory = this._createMultiMap(ranges, (r) => { if (map) { const name = this.getMarkerName(r.marker!); return map[name].category; @@ -477,7 +477,7 @@ export class TestState { for (const range of ranges) { const rangeSpan = TextRange.fromBounds(range.pos, range.end); - const matches = actual.filter(d => { + const matches = actual.filter((d) => { const diagnosticSpan = TextRange.fromBounds( convertPositionToOffset(d.range.start, lines)!, convertPositionToOffset(d.range.end, lines)! @@ -494,7 +494,7 @@ export class TestState { const name = this.getMarkerName(range.marker!); const message = map[name].message; - if (matches.filter(d => message === d.message).length !== 1) { + if (matches.filter((d) => message === d.message).length !== 1) { this._raiseError( `message doesn't match: ${message} of ${name} - ${stringify( range @@ -540,11 +540,12 @@ export class TestState { const command = { title: expected.command.title, command: expected.command.command, - arguments: expected.command.arguments?.map(a => normalizeSlashes(a)) + arguments: expected.command.arguments?.map((a) => normalizeSlashes(a)), }; const matches = actual.filter( - a => a.title === expected.title && a.kind! === expected.kind && this._deepEqual(a.command, command) + (a) => + a.title === expected.title && a.kind! === expected.kind && this._deepEqual(a.command, command) ); if (matches.length !== 1) { @@ -591,11 +592,11 @@ export class TestState { const name = this.getMarkerName(range.marker!); const controller = new CommandController(new TestLanguageService(this.workspace, this.console, this.fs)); - for (const codeAction of this._getCodeActions(range).filter(c => c.title === map[name].title)) { + for (const codeAction of this._getCodeActions(range).filter((c) => c.title === map[name].title)) { await controller.execute( { command: codeAction.command!.command, - arguments: codeAction.command?.arguments + arguments: codeAction.command?.arguments, }, CancellationToken.None ); @@ -701,21 +702,21 @@ export class TestState { assert.fail( `Expected ${expectedCompletions.length} items but received ${ result.items.length - }. Actual completions:\n${stringify(result.items.map(r => r.label))}` + }. Actual completions:\n${stringify(result.items.map((r) => r.label))}` ); } } for (let i = 0; i < expectedCompletions.length; i++) { const expected = expectedCompletions[i]; - const actualIndex = result.items.findIndex(a => a.label === expected.label); + const actualIndex = result.items.findIndex((a) => a.label === expected.label); if (actualIndex >= 0) { if (verifyMode === 'excluded') { // we're not supposed to find the completions passed to the test assert.fail( `Completion item with label "${ expected.label - }" unexpected. Actual completions:\n${stringify(result.items.map(r => r.label))}` + }" unexpected. Actual completions:\n${stringify(result.items.map((r) => r.label))}` ); } @@ -743,7 +744,7 @@ export class TestState { assert.fail( `Completion item with label "${ expected.label - }" expected. Actual completions:\n${stringify(result.items.map(r => r.label))}` + }" expected. Actual completions:\n${stringify(result.items.map((r) => r.label))}` ); } } @@ -752,7 +753,7 @@ export class TestState { if (verifyMode === 'exact') { if (result.items.length !== 0) { // we removed every item we found, there should not be any remaining - assert.fail(`Completion items unexpected: ${stringify(result.items.map(r => r.label))}`); + assert.fail(`Completion items unexpected: ${stringify(result.items.map((r) => r.label))}`); } } } else { @@ -802,7 +803,7 @@ export class TestState { assert.ok(sig.parameters); const actualParameters: string[] = []; - sig.parameters!.forEach(p => { + sig.parameters!.forEach((p) => { actualParameters.push(sig.label.substring(p.startOffset, p.endOffset)); }); @@ -859,7 +860,7 @@ export class TestState { private _getFileContent(fileName: string): string { const files = this.testData.files.filter( - f => comparePaths(f.fileName, fileName, this.fs.ignoreCase) === Comparison.EqualTo + (f) => comparePaths(f.fileName, fileName, this.fs.ignoreCase) === Comparison.EqualTo ); return files[0].content; } @@ -880,7 +881,7 @@ export class TestState { return { start: convertOffsetToPosition(startOffset, result.tokenizerOutput.lines), - end: convertOffsetToPosition(endOffset, result.tokenizerOutput.lines) + end: convertOffsetToPosition(endOffset, result.tokenizerOutput.lines), }; } @@ -1065,7 +1066,7 @@ export class TestState { let file: FourSlashFile | undefined; const availableNames: string[] = []; - this.testData.files.forEach(f => { + this.testData.files.forEach((f) => { const fn = normalizePath(f.fileName); if (fn) { if (fn === name) { @@ -1127,7 +1128,7 @@ export class TestState { } private _getDiagnosticsPerFile() { - const sourceFiles = this._files.map(f => this.program.getSourceFile(f)); + const sourceFiles = this._files.map((f) => this.program.getSourceFile(f)); const results = sourceFiles.map((sourceFile, index) => { if (sourceFile) { const diagnostics = sourceFile.getDiagnostics(this.configOptions) || []; @@ -1135,8 +1136,8 @@ export class TestState { const value = { filePath, parseResults: sourceFile.getParseResults(), - errors: diagnostics.filter(diag => diag.category === DiagnosticCategory.Error), - warnings: diagnostics.filter(diag => diag.category === DiagnosticCategory.Warning) + errors: diagnostics.filter((diag) => diag.category === DiagnosticCategory.Error), + warnings: diagnostics.filter((diag) => diag.category === DiagnosticCategory.Warning), }; return [filePath, value] as [string, typeof value]; } else { @@ -1175,7 +1176,7 @@ export class TestState { private async _waitForFile(filePath: string) { while (!this.fs.existsSync(filePath)) { - await new Promise(res => + await new Promise((res) => setTimeout(() => { res(); }, 200) @@ -1187,7 +1188,7 @@ export class TestState { const file = range.fileName; const textRange = { start: this._convertOffsetToPosition(file, range.pos), - end: this._convertOffsetToPosition(file, range.end) + end: this._convertOffsetToPosition(file, range.end), }; return CodeActionProvider.getCodeActionsForPosition(this.workspace, file, textRange, CancellationToken.None); diff --git a/server/src/tests/harness/host.ts b/server/src/tests/harness/host.ts index eb831fd38..8030f847d 100644 --- a/server/src/tests/harness/host.ts +++ b/server/src/tests/harness/host.ts @@ -15,7 +15,7 @@ import { fileExists, FileSystemEntries, getFileSize, - resolvePaths + resolvePaths, } from '../../common/pathUtils'; import { compareStringsCaseInsensitive, compareStringsCaseSensitive } from '../../common/stringUtils'; @@ -62,7 +62,7 @@ function createHost(): TestHost { /** Convert all lowercase chars to uppercase, and vice-versa */ function swapCase(s: string): string { - return s.replace(/\w/g, ch => { + return s.replace(/\w/g, (ch) => { const up = ch.toUpperCase(); return ch === up ? ch.toLowerCase() : up; }); @@ -162,17 +162,17 @@ function createHost(): TestHost { return { useCaseSensitiveFileNames: () => useCaseSensitiveFileNames, getFileSize: (path: string) => getFileSize(vfs, path), - readFile: path => readFile(path), + readFile: (path) => readFile(path), writeFile: (path, content) => { writeFile(path, content); }, - fileExists: path => fileExists(vfs, path), - directoryExists: path => directoryExists(vfs, path), + fileExists: (path) => fileExists(vfs, path), + directoryExists: (path) => directoryExists(vfs, path), listFiles, - log: s => { + log: (s) => { console.log(s); }, getWorkspaceRoot: () => resolvePaths(__dirname, '../../..'), - getAccessibleFileSystemEntries + getAccessibleFileSystemEntries, }; } diff --git a/server/src/tests/harness/utils.ts b/server/src/tests/harness/utils.ts index 3690c1f1b..e71c20d05 100644 --- a/server/src/tests/harness/utils.ts +++ b/server/src/tests/harness/utils.ts @@ -342,7 +342,7 @@ export const IO_ERROR_MESSAGE = Object.freeze({ EINVAL: 'invalid value', ENOTEMPTY: 'directory not empty', EPERM: 'operation not permitted', - EROFS: 'file system is read-only' + EROFS: 'file system is read-only', }); export function createIOError(code: keyof typeof IO_ERROR_MESSAGE, details = '') { diff --git a/server/src/tests/harness/vfs/factory.ts b/server/src/tests/harness/vfs/factory.ts index 0313ebd4c..b60caa0b5 100644 --- a/server/src/tests/harness/vfs/factory.ts +++ b/server/src/tests/harness/vfs/factory.ts @@ -19,7 +19,7 @@ import { MODULE_PATH, Mount, S_IFDIR, - S_IFREG + S_IFREG, } from './filesystem'; export class TextDocument { @@ -94,7 +94,7 @@ export function createFromFileSystem( // Add symlinks const symlink = document.meta.get('symlink'); if (symlink) { - for (const link of symlink.split(',').map(link => link.trim())) { + for (const link of symlink.split(',').map((link) => link.trim())) { fs.mkdirpSync(getDirectoryPath(link)); fs.symlinkSync(resolvePaths(fs.cwd(), document.file), link); } @@ -139,7 +139,7 @@ function getBuiltLocal( localCIFSCache = new FileSystem(/*ignoreCase*/ true, { files, cwd, - meta: {} + meta: {}, }); localCIFSCache.makeReadonly(); } @@ -193,6 +193,6 @@ function createResolver(host: TestHost): FileSystemResolver { }, readFileSync(path: string): Buffer { return bufferFrom(host.readFile(path)!, 'utf8'); - } + }, }; } diff --git a/server/src/tests/harness/vfs/filesystem.ts b/server/src/tests/harness/vfs/filesystem.ts index 4d202fb03..279ae8831 100644 --- a/server/src/tests/harness/vfs/filesystem.ts +++ b/server/src/tests/harness/vfs/filesystem.ts @@ -309,7 +309,7 @@ export class FileSystem { return { close: () => { /* left empty */ - } + }, }; } @@ -321,7 +321,7 @@ export class FileSystem { return { close: () => { /* left empty */ - } + }, }; } @@ -1108,7 +1108,7 @@ export class FileSystem { mtimeMs: time, ctimeMs: time, birthtimeMs: time, - nlink: 0 + nlink: 0, }; } @@ -1229,7 +1229,7 @@ export class FileSystem { ctimeMs: root.ctimeMs, birthtimeMs: root.birthtimeMs, nlink: root.nlink, - shadowRoot: root + shadowRoot: root, }; if (isSymlink(root)) { diff --git a/server/src/tests/harness/vfs/pathValidation.ts b/server/src/tests/harness/vfs/pathValidation.ts index cce6af901..f32bfdbc8 100644 --- a/server/src/tests/harness/vfs/pathValidation.ts +++ b/server/src/tests/harness/vfs/pathValidation.ts @@ -54,7 +54,7 @@ export const enum ValidationFlags { AllowNavigation, /** Path may only be a filename */ - Basename = RequireBasename | AllowExtname + Basename = RequireBasename | AllowExtname, } function validateComponents(components: string[], flags: ValidationFlags, hasTrailingSeparator: boolean) { diff --git a/server/src/tests/pathUtils.test.ts b/server/src/tests/pathUtils.test.ts index fa65b18a5..472c3f030 100644 --- a/server/src/tests/pathUtils.test.ts +++ b/server/src/tests/pathUtils.test.ts @@ -36,7 +36,7 @@ import { reducePathComponents, resolvePaths, stripFileExtension, - stripTrailingDirectorySeparator + stripTrailingDirectorySeparator, } from '../common/pathUtils'; test('getPathComponents1', () => { diff --git a/server/src/tests/testState.test.ts b/server/src/tests/testState.test.ts index 2015fbdc4..bdb52ceed 100644 --- a/server/src/tests/testState.test.ts +++ b/server/src/tests/testState.test.ts @@ -206,7 +206,7 @@ test('GoToEachMarker', () => { const marker2 = data.markerPositions.get('marker2'); const results: number[] = []; - state.goToEachMarker([marker1!, marker2!], m => { + state.goToEachMarker([marker1!, marker2!], (m) => { results.push(m.position); }); @@ -235,7 +235,7 @@ test('Markers', () => { assert.deepEqual( state .getMarkers() - .map(m => state.getMarkerName(m)) + .map((m) => state.getMarkerName(m)) .sort(compareStringsCaseSensitive), state.getMarkerNames().sort(comparePathsCaseSensitive) ); @@ -353,7 +353,7 @@ test('goToEachRange', () => { const { state } = parseAndGetTestState(code); const results: Range[] = []; - state.goToEachRange(r => { + state.goToEachRange((r) => { assert.equal(state.activeFile.fileName, r.fileName); results.push(r); }); @@ -378,7 +378,7 @@ test('getRangesInFile', () => { assert.deepEqual( state.getRangesInFile(data.files[0].fileName), - data.ranges.filter(r => r.fileName === data.files[0].fileName) + data.ranges.filter((r) => r.fileName === data.files[0].fileName) ); }); diff --git a/server/src/tests/testUtils.ts b/server/src/tests/testUtils.ts index f7d451682..4498852fa 100644 --- a/server/src/tests/testUtils.ts +++ b/server/src/tests/testUtils.ts @@ -78,7 +78,7 @@ export function parseSampleFile( return { fileContents: text, - parseResults: parseText(text, diagSink) + parseResults: parseText(text, diagSink), }; } @@ -91,7 +91,7 @@ export function buildAnalyzerFileInfo( const analysisDiagnostics = new TextRangeDiagnosticSink(parseResults.tokenizerOutput.lines); const fileInfo: AnalyzerFileInfo = { - importLookup: _ => undefined, + importLookup: (_) => undefined, futureImports: new Map(), builtinsScope: undefined, diagnosticSink: analysisDiagnostics, @@ -103,7 +103,7 @@ export function buildAnalyzerFileInfo( isStubFile: filePath.endsWith('.pyi'), isTypingStubFile: false, isBuiltInStubFile: false, - accessedSymbolMap: new Map() + accessedSymbolMap: new Map(), }; return fileInfo; @@ -127,7 +127,7 @@ export function bindSampleFile(fileName: string, configOptions = new ConfigOptio filePath, parseResults: parseInfo.parseResults, errors: fileInfo.diagnosticSink.getErrors(), - warnings: fileInfo.diagnosticSink.getWarnings() + warnings: fileInfo.diagnosticSink.getWarnings(), }; } @@ -140,7 +140,7 @@ export function typeAnalyzeSampleFiles( const importResolver = new ImportResolver(createFromRealFileSystem(), configOptions); const program = new Program(importResolver, configOptions); - const filePaths = fileNames.map(name => resolveSampleFilePath(name)); + const filePaths = fileNames.map((name) => resolveSampleFilePath(name)); program.setTrackedFiles(filePaths); while (program.analyze()) { @@ -148,15 +148,15 @@ export function typeAnalyzeSampleFiles( // specifying a timeout, it should complete the first time. } - const sourceFiles = filePaths.map(filePath => program.getSourceFile(filePath)); + const sourceFiles = filePaths.map((filePath) => program.getSourceFile(filePath)); return sourceFiles.map((sourceFile, index) => { if (sourceFile) { const diagnostics = sourceFile.getDiagnostics(configOptions) || []; const analysisResult: FileAnalysisResult = { filePath: sourceFile.getFilePath(), parseResults: sourceFile.getParseResults(), - errors: diagnostics.filter(diag => diag.category === DiagnosticCategory.Error), - warnings: diagnostics.filter(diag => diag.category === DiagnosticCategory.Warning) + errors: diagnostics.filter((diag) => diag.category === DiagnosticCategory.Error), + warnings: diagnostics.filter((diag) => diag.category === DiagnosticCategory.Warning), }; return analysisResult; } else { @@ -166,7 +166,7 @@ export function typeAnalyzeSampleFiles( filePath: '', parseResults: undefined, errors: [], - warnings: [] + warnings: [], }; return analysisResult; } diff --git a/server/src/tests/tokenizer.test.ts b/server/src/tests/tokenizer.test.ts index 83eed39ff..550650656 100644 --- a/server/src/tests/tokenizer.test.ts +++ b/server/src/tests/tokenizer.test.ts @@ -25,7 +25,7 @@ import { OperatorType, StringToken, StringTokenFlags, - TokenType + TokenType, } from '../parser/tokenizerTypes'; import * as TestUtils from './testUtils'; @@ -366,7 +366,7 @@ test('Strings: unclosed', () => { const ranges = [ [1, 8], [10, 18], - [29, 10] + [29, 10], ]; for (let i = 0; i < ranges.length; i += 1) { assert.equal(results.tokens.getItemAt(i).start, ranges[i][0]); @@ -382,7 +382,7 @@ test('Strings: escaped across multiple lines', () => { const ranges = [ [1, 6], - [8, 7] + [8, 7], ]; for (let i = 0; i < ranges.length; i += 1) { assert.equal(results.tokens.getItemAt(i).start, ranges[i][0]); @@ -398,7 +398,7 @@ test('Strings: block next to regular, double-quoted', () => { const ranges = [ [0, 8], - [8, 8] + [8, 8], ]; for (let i = 0; i < ranges.length; i += 1) { assert.equal(results.tokens.getItemAt(i).start, ranges[i][0]); @@ -414,7 +414,7 @@ test('Strings: block next to block, double-quoted', () => { const ranges = [ [0, 6], - [6, 2] + [6, 2], ]; for (let i = 0; i < ranges.length; i += 1) { assert.equal(results.tokens.getItemAt(i).start, ranges[i][0]); @@ -1294,7 +1294,7 @@ test('Operators', () => { OperatorType.BitwiseOrEqual, OperatorType.BitwiseXor, OperatorType.BitwiseXorEqual, - OperatorType.Walrus + OperatorType.Walrus, ]; assert.equal(results.tokens.count - _implicitTokenCount, lengths.length); assert.equal(results.tokens.count - _implicitTokenCount, operatorTypes.length); diff --git a/server/src/workspaceMap.ts b/server/src/workspaceMap.ts index 3f86b5dd6..ca57d92b7 100644 --- a/server/src/workspaceMap.ts +++ b/server/src/workspaceMap.ts @@ -17,7 +17,7 @@ export class WorkspaceMap extends Map { let bestRootPath: string | undefined; let bestInstance: WorkspaceServiceInstance | undefined; - this.forEach(workspace => { + this.forEach((workspace) => { if (workspace.rootPath) { // Is the file is under this workspace folder? if (filePath.startsWith(workspace.rootPath)) { @@ -51,7 +51,7 @@ export class WorkspaceMap extends Map { rootPath: '', rootUri: '', serviceInstance: this._ls.createAnalyzerService(this._defaultWorkspacePath), - disableLanguageServices: false + disableLanguageServices: false, }; this.set(this._defaultWorkspacePath, defaultWorkspace); this._ls.updateSettingsForWorkspace(defaultWorkspace).ignoreErrors(); diff --git a/server/webpack.config-cli.js b/server/webpack.config-cli.js index c1c48e866..d3741fd7a 100644 --- a/server/webpack.config-cli.js +++ b/server/webpack.config-cli.js @@ -16,11 +16,11 @@ module.exports = { target: 'node', output: { filename: 'pyright.js', - path: path.resolve(__dirname, '../dist') + path: path.resolve(__dirname, '../dist'), }, resolve: { modules: [path.resolve(__dirname, '.'), 'node_modules'], - extensions: ['.js', '.ts'] + extensions: ['.js', '.ts'], }, module: { @@ -29,17 +29,17 @@ module.exports = { test: /\.ts$/, loader: 'ts-loader', options: { - configFile: 'tsconfig.json' - } + configFile: 'tsconfig.json', + }, }, { test: /\.node$/, - loader: 'node-loader' - } - ] + loader: 'node-loader', + }, + ], }, node: { - fs: 'empty' - } + fs: 'empty', + }, }; diff --git a/server/webpack.config-server.js b/server/webpack.config-server.js index d34a16ea5..5ef01be90 100644 --- a/server/webpack.config-server.js +++ b/server/webpack.config-server.js @@ -16,14 +16,14 @@ module.exports = { devtool: 'source-map', output: { filename: 'server.bundle.js', - path: path.resolve(__dirname, '../client/server') + path: path.resolve(__dirname, '../client/server'), }, optimization: { - usedExports: true + usedExports: true, }, resolve: { modules: [path.resolve(__dirname, '.'), 'node_modules'], - extensions: ['.js', '.ts'] + extensions: ['.js', '.ts'], }, module: { rules: [ @@ -31,18 +31,18 @@ module.exports = { test: /\.ts$/, loader: 'ts-loader', options: { - configFile: 'tsconfig.json' - } + configFile: 'tsconfig.json', + }, }, { test: /\.node$/, - use: 'node-loader' - } - ] + use: 'node-loader', + }, + ], }, node: { fs: 'empty', __dirname: false, - __filename: false - } + __filename: false, + }, };