From ceccfd8867d64f5dcba4a19491e8e32ec94354d7 Mon Sep 17 00:00:00 2001 From: Alexander Date: Thu, 8 Aug 2019 21:30:18 +0300 Subject: [PATCH] array-type: [ default: array, generic: array ] --- .eslintrc.json | 2 +- scripts/failed-tests.d.ts | 2 +- scripts/types/ambient.d.ts | 4 +- src/compiler/builder.ts | 84 ++-- src/compiler/builderState.ts | 12 +- src/compiler/checker.ts | 218 ++++----- src/compiler/commandLineParser.ts | 80 ++-- src/compiler/core.ts | 198 ++++---- src/compiler/debug.ts | 2 +- src/compiler/emitter.ts | 16 +- src/compiler/factory.ts | 440 +++++++++--------- src/compiler/moduleSpecifiers.ts | 20 +- src/compiler/program.ts | 70 +-- src/compiler/resolutionCache.ts | 12 +- src/compiler/scanner.ts | 8 +- src/compiler/semver.ts | 16 +- src/compiler/sourcemap.ts | 6 +- src/compiler/sys.ts | 10 +- src/compiler/transformer.ts | 2 +- src/compiler/transformers/classFields.ts | 4 +- src/compiler/transformers/declarations.ts | 10 +- src/compiler/transformers/destructuring.ts | 2 +- src/compiler/transformers/es2015.ts | 2 +- src/compiler/transformers/es2018.ts | 2 +- src/compiler/transformers/generators.ts | 2 +- src/compiler/transformers/jsx.ts | 4 +- src/compiler/transformers/ts.ts | 12 +- src/compiler/transformers/utilities.ts | 2 +- src/compiler/tsbuild.ts | 64 +-- src/compiler/types.ts | 172 +++---- src/compiler/utilities.ts | 148 +++--- src/compiler/visitor.ts | 10 +- src/compiler/watch.ts | 40 +- src/compiler/watchUtilities.ts | 8 +- src/harness/client.ts | 4 +- src/harness/compiler.ts | 14 +- src/harness/documents.ts | 16 +- src/harness/fakes.ts | 4 +- src/harness/fourslash.ts | 176 +++---- src/harness/harness.ts | 26 +- src/harness/harnessLanguageService.ts | 8 +- src/harness/loggedIO.ts | 8 +- src/harness/sourceMapRecorder.ts | 6 +- src/harness/vfs.ts | 2 +- src/harness/virtualFileSystemWithWatch.ts | 40 +- src/harness/vpath.ts | 2 +- src/jsTyping/jsTyping.ts | 8 +- src/jsTyping/types.ts | 2 +- src/lib/es2015.collection.d.ts | 8 +- src/lib/es2015.core.d.ts | 6 +- src/lib/es2019.array.d.ts | 66 +-- src/lib/es2019.object.d.ts | 2 +- src/lib/es5.d.ts | 28 +- src/server/editorServices.ts | 16 +- src/server/project.ts | 32 +- src/server/protocol.ts | 22 +- src/server/scriptVersionCache.ts | 2 +- src/server/session.ts | 90 ++-- src/services/codeFixProvider.ts | 10 +- .../codefixes/convertFunctionToEs6Class.ts | 2 +- .../codefixes/convertToAsyncFunction.ts | 28 +- src/services/codefixes/convertToEs6Module.ts | 18 +- .../codefixes/disableJsDiagnostics.ts | 2 +- src/services/codefixes/fixAddMissingMember.ts | 2 +- .../fixExtendsInterfaceBecomesImplements.ts | 2 +- src/services/codefixes/fixUnreachableCode.ts | 2 +- src/services/codefixes/fixUnusedIdentifier.ts | 10 +- src/services/codefixes/helpers.ts | 12 +- src/services/codefixes/importFixes.ts | 36 +- src/services/codefixes/inferFromUsage.ts | 18 +- src/services/completions.ts | 20 +- src/services/documentHighlights.ts | 18 +- src/services/findAllReferences.ts | 50 +- src/services/formatting/formatting.ts | 4 +- src/services/formatting/rule.ts | 6 +- src/services/formatting/rules.ts | 12 +- src/services/formatting/rulesMap.ts | 4 +- src/services/formatting/smartIndenter.ts | 2 +- src/services/getEditsForFileRename.ts | 4 +- src/services/goToDefinition.ts | 10 +- src/services/importTracker.ts | 18 +- src/services/jsDoc.ts | 12 +- src/services/navigateTo.ts | 6 +- src/services/organizeImports.ts | 18 +- src/services/patternMatcher.ts | 4 +- src/services/refactorProvider.ts | 2 +- .../addOrRemoveBracesToArrowFunction.ts | 2 +- src/services/refactors/convertExport.ts | 2 +- src/services/refactors/convertImport.ts | 4 +- .../convertParamsToDestructuredObject.ts | 4 +- src/services/refactors/extractSymbol.ts | 34 +- src/services/refactors/extractType.ts | 8 +- .../generateGetAccessorAndSetAccessor.ts | 2 +- src/services/refactors/moveToNewFile.ts | 28 +- src/services/services.ts | 32 +- src/services/shims.ts | 10 +- src/services/signatureHelp.ts | 12 +- src/services/smartSelection.ts | 2 +- src/services/stringCompletions.ts | 50 +- src/services/symbolDisplay.ts | 2 +- src/services/textChanges.ts | 30 +- src/services/types.ts | 34 +- src/services/utilities.ts | 10 +- src/testRunner/projectsRunner.ts | 18 +- src/testRunner/unittests/builder.ts | 4 +- .../config/convertCompilerOptionsFromJson.ts | 4 +- .../unittests/config/projectReferences.ts | 6 +- src/testRunner/unittests/programApi.ts | 4 +- .../unittests/reuseProgramStructure.ts | 8 +- .../unittests/services/organizeImports.ts | 6 +- .../unittests/tsbuild/amdModulesWithOut.ts | 2 +- src/testRunner/unittests/tsbuild/helpers.ts | 28 +- src/testRunner/unittests/tsbuild/outFile.ts | 24 +- .../unittests/tsbuild/resolveJsonModule.ts | 2 +- src/testRunner/unittests/tsbuild/sample.ts | 4 +- .../unittests/tsbuild/transitiveReferences.ts | 2 +- .../unittests/tsbuild/watchEnvironment.ts | 2 +- src/testRunner/unittests/tsbuild/watchMode.ts | 80 ++-- .../unittests/tscWatch/emitAndErrorUpdates.ts | 18 +- src/testRunner/unittests/tscWatch/helpers.ts | 16 +- .../unittests/tscWatch/incremental.ts | 18 +- .../unittests/tscWatch/programUpdates.ts | 8 +- .../unittests/tscWatch/watchEnvironment.ts | 2 +- .../tsserver/cachingFileSystemInformation.ts | 6 +- .../unittests/tsserver/completions.ts | 6 +- .../unittests/tsserver/declarationFileMaps.ts | 18 +- .../unittests/tsserver/duplicatePackages.ts | 2 +- .../tsserver/events/projectLoading.ts | 2 +- .../events/projectUpdatedInBackground.ts | 8 +- .../tsserver/getApplicableRefactors.ts | 2 +- .../tsserver/getEditsForFileRename.ts | 6 +- src/testRunner/unittests/tsserver/helpers.ts | 18 +- .../unittests/tsserver/metadataInResponse.ts | 6 +- .../unittests/tsserver/projectErrors.ts | 16 +- .../unittests/tsserver/projectReferences.ts | 12 +- .../unittests/tsserver/resolutionCache.ts | 2 +- .../unittests/tsserver/typingsInstaller.ts | 2 +- .../unittests/tsserver/untitledFiles.ts | 2 +- src/tsc/tsc.ts | 2 +- src/tsserver/server.ts | 2 +- src/typingsInstallerCore/typingsInstaller.ts | 2 +- 141 files changed, 1620 insertions(+), 1620 deletions(-) diff --git a/.eslintrc.json b/.eslintrc.json index fb4ebc210b2..d10d3c3a265 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -16,7 +16,7 @@ ], "rules": { "@typescript-eslint/adjacent-overload-signatures": "error", - "@typescript-eslint/array-type": ["error", { "default": "array", "readonly": "generic" }], + "@typescript-eslint/array-type": "error", "camelcase": "off", "@typescript-eslint/camelcase": ["error", { "properties": "never", "allow": ["^[A-Za-z][a-zA-Za-z]+_[A-Za-z]+$"] }], "@typescript-eslint/class-name-casing": "error", diff --git a/scripts/failed-tests.d.ts b/scripts/failed-tests.d.ts index c17e0a5a39a..7eba4cc18fa 100644 --- a/scripts/failed-tests.d.ts +++ b/scripts/failed-tests.d.ts @@ -8,7 +8,7 @@ declare class FailedTestsReporter extends Mocha.reporters.Base { reporterOptions: FailedTestsReporter.ReporterOptions; reporter?: Mocha.reporters.Base; constructor(runner: Mocha.Runner, options?: { reporterOptions?: FailedTestsReporter.ReporterOptions }); - static writeFailures(file: string, passes: ReadonlyArray, failures: ReadonlyArray, keepFailed: boolean, done: (err?: NodeJS.ErrnoException) => void): void; + static writeFailures(file: string, passes: readonly Mocha.Test[], failures: readonly Mocha.Test[], keepFailed: boolean, done: (err?: NodeJS.ErrnoException) => void): void; done(failures: number, fn?: (failures: number) => void): void; } diff --git a/scripts/types/ambient.d.ts b/scripts/types/ambient.d.ts index ecfe29f9db6..9ea70adee50 100644 --- a/scripts/types/ambient.d.ts +++ b/scripts/types/ambient.d.ts @@ -19,7 +19,7 @@ declare module "vinyl" { cwd: string; base: string; path: string; - readonly history: ReadonlyArray; + readonly history: readonly string[]; contents: T; relative: string; dirname: string; @@ -45,7 +45,7 @@ declare module "vinyl" { cwd?: string; base?: string; path?: string; - history?: ReadonlyArray; + history?: readonly string[]; stat?: import("fs").Stats; contents?: T; sourceMap?: import("./sourcemaps").RawSourceMap | string; diff --git a/src/compiler/builder.ts b/src/compiler/builder.ts index b29d86dbb46..7e56a3cbb46 100644 --- a/src/compiler/builder.ts +++ b/src/compiler/builder.ts @@ -22,7 +22,7 @@ namespace ts { /** * Cache of semantic diagnostics for files with their Path being the key */ - semanticDiagnosticsPerFile?: ReadonlyMap | ReadonlyArray> | undefined; + semanticDiagnosticsPerFile?: ReadonlyMap | undefined; /** * The map has key by source file's path that has been changed */ @@ -30,7 +30,7 @@ namespace ts { /** * Set of affected files being iterated */ - affectedFiles?: ReadonlyArray | undefined; + affectedFiles?: readonly SourceFile[] | undefined; /** * Current changed file for iterating over affected files */ @@ -59,7 +59,7 @@ namespace ts { /** * Files pending to be emitted */ - affectedFilesPendingEmit?: ReadonlyArray | undefined; + affectedFilesPendingEmit?: readonly Path[] | undefined; /** * Current index to retrieve pending affected file */ @@ -78,7 +78,7 @@ namespace ts { /** * Cache of semantic diagnostics for files with their Path being the key */ - semanticDiagnosticsPerFile: Map> | undefined; + semanticDiagnosticsPerFile: Map | undefined; /** * The map has key by source file's path that has been changed */ @@ -86,7 +86,7 @@ namespace ts { /** * Set of affected files being iterated */ - affectedFiles: ReadonlyArray | undefined; + affectedFiles: readonly SourceFile[] | undefined; /** * Current index to retrieve affected file from */ @@ -127,7 +127,7 @@ namespace ts { /** * Files pending to be emitted */ - affectedFilesPendingEmit: ReadonlyArray | undefined; + affectedFilesPendingEmit: readonly Path[] | undefined; /** * Current index to retrieve pending affected file */ @@ -162,7 +162,7 @@ namespace ts { // With --out or --outFile, any change affects all semantic diagnostics so no need to cache them // With --isolatedModules, emitting changed file doesnt emit dependent files so we cant know of dependent files to retrieve errors so dont cache the errors if (!compilerOptions.outFile && !compilerOptions.out && !compilerOptions.isolatedModules) { - state.semanticDiagnosticsPerFile = createMap>(); + state.semanticDiagnosticsPerFile = createMap(); } state.changedFilesSet = createMap(); @@ -222,7 +222,7 @@ namespace ts { // Unchanged file copy diagnostics const diagnostics = oldState!.semanticDiagnosticsPerFile!.get(sourceFilePath); if (diagnostics) { - state.semanticDiagnosticsPerFile!.set(sourceFilePath, oldState!.hasReusableDiagnostic ? convertToDiagnostics(diagnostics as ReadonlyArray, newProgram, getCanonicalFileName) : diagnostics as ReadonlyArray); + state.semanticDiagnosticsPerFile!.set(sourceFilePath, oldState!.hasReusableDiagnostic ? convertToDiagnostics(diagnostics as readonly ReusableDiagnostic[], newProgram, getCanonicalFileName) : diagnostics as readonly Diagnostic[]); if (!state.semanticDiagnosticsFromOldState) { state.semanticDiagnosticsFromOldState = createMap(); } @@ -241,7 +241,7 @@ namespace ts { return state; } - function convertToDiagnostics(diagnostics: ReadonlyArray, newProgram: Program, getCanonicalFileName: GetCanonicalFileName): ReadonlyArray { + function convertToDiagnostics(diagnostics: readonly ReusableDiagnostic[], newProgram: Program, getCanonicalFileName: GetCanonicalFileName): readonly Diagnostic[] { if (!diagnostics.length) return emptyArray; const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(getOutputPathForBuildInfo(newProgram.getCompilerOptions())!, newProgram.getCurrentDirectory())); return diagnostics.map(diagnostic => { @@ -580,7 +580,7 @@ namespace ts { * Gets the semantic diagnostics either from cache if present, or otherwise from program and caches it * Note that it is assumed that the when asked about semantic diagnostics, the file has been taken out of affected files/changed file set */ - function getSemanticDiagnosticsOfFile(state: BuilderProgramState, sourceFile: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray { + function getSemanticDiagnosticsOfFile(state: BuilderProgramState, sourceFile: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[] { const path = sourceFile.path; if (state.semanticDiagnosticsPerFile) { const cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path); @@ -598,7 +598,7 @@ namespace ts { return diagnostics; } - export type ProgramBuildInfoDiagnostic = string | [string, ReadonlyArray]; + export type ProgramBuildInfoDiagnostic = string | [string, readonly ReusableDiagnostic[]]; export interface ProgramBuildInfo { fileInfos: MapLike; options: CompilerOptions; @@ -652,8 +652,8 @@ namespace ts { [ relativeToBuildInfo(key), state.hasReusableDiagnostic ? - value as ReadonlyArray : - convertToReusableDiagnostics(value as ReadonlyArray, relativeToBuildInfo) + value as readonly ReusableDiagnostic[] : + convertToReusableDiagnostics(value as readonly Diagnostic[], relativeToBuildInfo) ] : relativeToBuildInfo(key) )); @@ -693,7 +693,7 @@ namespace ts { function convertToReusableCompilerOptionValue(option: CommandLineOption | undefined, value: CompilerOptionsValue, relativeToBuildInfo: (path: string) => string) { if (option) { if (option.type === "list") { - const values = value as ReadonlyArray; + const values = value as readonly (string | number)[]; if (option.element.isFilePath && values.length) { return values.map(relativeToBuildInfo); } @@ -705,7 +705,7 @@ namespace ts { return value; } - function convertToReusableDiagnostics(diagnostics: ReadonlyArray, relativeToBuildInfo: (path: string) => string): ReadonlyArray { + function convertToReusableDiagnostics(diagnostics: readonly Diagnostic[], relativeToBuildInfo: (path: string) => string): readonly ReusableDiagnostic[] { Debug.assert(!!diagnostics.length); return diagnostics.map(diagnostic => { const result: ReusableDiagnostic = convertToReusableDiagnosticRelatedInformation(diagnostic, relativeToBuildInfo); @@ -738,10 +738,10 @@ namespace ts { newProgram: Program; host: BuilderProgramHost; oldProgram: BuilderProgram | undefined; - configFileParsingDiagnostics: ReadonlyArray; + configFileParsingDiagnostics: readonly Diagnostic[]; } - export function getBuilderCreationParameters(newProgramOrRootNames: Program | ReadonlyArray | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: BuilderProgram | CompilerHost, configFileParsingDiagnosticsOrOldProgram?: ReadonlyArray | BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): BuilderCreationParameters { + export function getBuilderCreationParameters(newProgramOrRootNames: Program | readonly string[] | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: BuilderProgram | CompilerHost, configFileParsingDiagnosticsOrOldProgram?: readonly Diagnostic[] | BuilderProgram, configFileParsingDiagnostics?: readonly Diagnostic[], projectReferences?: readonly ProjectReference[]): BuilderCreationParameters { let host: BuilderProgramHost; let newProgram: Program; let oldProgram: BuilderProgram; @@ -768,7 +768,7 @@ namespace ts { newProgram = newProgramOrRootNames; host = hostOrOptions as BuilderProgramHost; oldProgram = oldProgramOrHost as BuilderProgram; - configFileParsingDiagnostics = configFileParsingDiagnosticsOrOldProgram as ReadonlyArray; + configFileParsingDiagnostics = configFileParsingDiagnosticsOrOldProgram as readonly Diagnostic[]; } return { host, newProgram, oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics || emptyArray }; } @@ -925,7 +925,7 @@ namespace ts { * Return the semantic diagnostics for the next affected file or undefined if iteration is complete * If provided ignoreSourceFile would be called before getting the diagnostics and would ignore the sourceFile if the returned value was true */ - function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken?: CancellationToken, ignoreSourceFile?: (sourceFile: SourceFile) => boolean): AffectedFileResult> { + function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken?: CancellationToken, ignoreSourceFile?: (sourceFile: SourceFile) => boolean): AffectedFileResult { while (true) { const affected = getNextAffectedFile(state, cancellationToken, computeHash); if (!affected) { @@ -969,7 +969,7 @@ namespace ts { * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided, * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics */ - function getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray { + function getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[] { assertSourceFileOkWithoutNextAffectedCall(state, sourceFile); const compilerOptions = Debug.assertDefined(state.program).getCompilerOptions(); if (compilerOptions.outFile || compilerOptions.out) { @@ -996,7 +996,7 @@ namespace ts { } } - function addToAffectedFilesPendingEmit(state: BuilderProgramState, affectedFilesPendingEmit: ReadonlyArray) { + function addToAffectedFilesPendingEmit(state: BuilderProgramState, affectedFilesPendingEmit: readonly Path[]) { state.affectedFilesPendingEmit = concatenate(state.affectedFilesPendingEmit, affectedFilesPendingEmit); // affectedFilesPendingEmitIndex === undefined // - means the emit state.affectedFilesPendingEmit was undefined before adding current affected files @@ -1007,7 +1007,7 @@ namespace ts { } } - function getMapOfReferencedSet(mapLike: MapLike> | undefined, toPath: (path: string) => Path): ReadonlyMap | undefined { + function getMapOfReferencedSet(mapLike: MapLike | undefined, toPath: (path: string) => Path): ReadonlyMap | undefined { if (!mapLike) return undefined; const map = createMap(); // Copies keys/values from template. Note that for..in will not throw if @@ -1093,7 +1093,7 @@ namespace ts { function convertFromReusableCompilerOptionValue(option: CommandLineOption | undefined, value: CompilerOptionsValue, toAbsolutePath: (path: string) => string) { if (option) { if (option.type === "list") { - const values = value as ReadonlyArray; + const values = value as readonly (string | number)[]; if (option.element.isFilePath && values.length) { return values.map(toAbsolutePath); } @@ -1105,7 +1105,7 @@ namespace ts { return value; } - export function createRedirectedBuilderProgram(state: { program: Program | undefined; compilerOptions: CompilerOptions; }, configFileParsingDiagnostics: ReadonlyArray): BuilderProgram { + export function createRedirectedBuilderProgram(state: { program: Program | undefined; compilerOptions: CompilerOptions; }, configFileParsingDiagnostics: readonly Diagnostic[]): BuilderProgram { return { getState: notImplemented, backupState: noop, @@ -1188,31 +1188,31 @@ namespace ts { /** * Get a list of files in the program */ - getSourceFiles(): ReadonlyArray; + getSourceFiles(): readonly SourceFile[]; /** * Get the diagnostics for compiler options */ - getOptionsDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; + getOptionsDiagnostics(cancellationToken?: CancellationToken): readonly Diagnostic[]; /** * Get the diagnostics that dont belong to any file */ - getGlobalDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; + getGlobalDiagnostics(cancellationToken?: CancellationToken): readonly Diagnostic[]; /** * Get the diagnostics from config file parsing */ - getConfigFileParsingDiagnostics(): ReadonlyArray; + getConfigFileParsingDiagnostics(): readonly Diagnostic[]; /** * Get the syntax diagnostics, for all source files if source file is not supplied */ - getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[]; /** * Get the declaration diagnostics, for all source files if source file is not supplied */ - getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly DiagnosticWithLocation[]; /** * Get all the dependencies of the file */ - getAllDependencies(sourceFile: SourceFile): ReadonlyArray; + getAllDependencies(sourceFile: SourceFile): readonly string[]; /** * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program @@ -1222,7 +1222,7 @@ namespace ts { * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided, * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics */ - getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[]; /** * Emits the JavaScript and declaration files. * When targetSource file is specified, emits the files corresponding to that source file, @@ -1249,7 +1249,7 @@ namespace ts { * Gets the semantic diagnostics from the program for the next affected file and caches it * Returns undefined if the iteration is complete */ - getSemanticDiagnosticsOfNextAffectedFile(cancellationToken?: CancellationToken, ignoreSourceFile?: (sourceFile: SourceFile) => boolean): AffectedFileResult>; + getSemanticDiagnosticsOfNextAffectedFile(cancellationToken?: CancellationToken, ignoreSourceFile?: (sourceFile: SourceFile) => boolean): AffectedFileResult; } /** @@ -1268,9 +1268,9 @@ namespace ts { /** * Create the builder to manage semantic diagnostics and cache them */ - export function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; - export function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; - export function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames: Program | ReadonlyArray | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: CompilerHost | SemanticDiagnosticsBuilderProgram, configFileParsingDiagnosticsOrOldProgram?: ReadonlyArray | SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray) { + export function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: readonly Diagnostic[]): SemanticDiagnosticsBuilderProgram; + export function createSemanticDiagnosticsBuilderProgram(rootNames: readonly string[] | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: readonly Diagnostic[], projectReferences?: readonly ProjectReference[]): SemanticDiagnosticsBuilderProgram; + export function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames: Program | readonly string[] | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: CompilerHost | SemanticDiagnosticsBuilderProgram, configFileParsingDiagnosticsOrOldProgram?: readonly Diagnostic[] | SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: readonly Diagnostic[], projectReferences?: readonly ProjectReference[]) { return createBuilderProgram(BuilderProgramKind.SemanticDiagnosticsBuilderProgram, getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } @@ -1278,18 +1278,18 @@ namespace ts { * Create the builder that can handle the changes in program and iterate through changed files * to emit the those files and manage semantic diagnostics cache as well */ - export function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; - export function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; - export function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames: Program | ReadonlyArray | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: CompilerHost | EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnosticsOrOldProgram?: ReadonlyArray | EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray) { + export function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: readonly Diagnostic[]): EmitAndSemanticDiagnosticsBuilderProgram; + export function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: readonly string[] | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: readonly Diagnostic[], projectReferences?: readonly ProjectReference[]): EmitAndSemanticDiagnosticsBuilderProgram; + export function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames: Program | readonly string[] | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: CompilerHost | EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnosticsOrOldProgram?: readonly Diagnostic[] | EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: readonly Diagnostic[], projectReferences?: readonly ProjectReference[]) { return createBuilderProgram(BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } /** * Creates a builder thats just abstraction over program and can be used with watch */ - export function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; - export function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): BuilderProgram; - export function createAbstractBuilder(newProgramOrRootNames: Program | ReadonlyArray | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: CompilerHost | BuilderProgram, configFileParsingDiagnosticsOrOldProgram?: ReadonlyArray | BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): BuilderProgram { + export function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: readonly Diagnostic[]): BuilderProgram; + export function createAbstractBuilder(rootNames: readonly string[] | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: readonly Diagnostic[], projectReferences?: readonly ProjectReference[]): BuilderProgram; + export function createAbstractBuilder(newProgramOrRootNames: Program | readonly string[] | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: CompilerHost | BuilderProgram, configFileParsingDiagnosticsOrOldProgram?: readonly Diagnostic[] | BuilderProgram, configFileParsingDiagnostics?: readonly Diagnostic[], projectReferences?: readonly ProjectReference[]): BuilderProgram { const { newProgram, configFileParsingDiagnostics: newConfigFileParsingDiagnostics } = getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences); return createRedirectedBuilderProgram({ program: newProgram, compilerOptions: newProgram.getCompilerOptions() }, newConfigFileParsingDiagnostics); } diff --git a/src/compiler/builderState.ts b/src/compiler/builderState.ts index fa00d653a7c..7e1df9d2f52 100644 --- a/src/compiler/builderState.ts +++ b/src/compiler/builderState.ts @@ -69,11 +69,11 @@ namespace ts { /** * Cache of all files excluding default library file for the current program */ - allFilesExcludingDefaultLibraryFile?: ReadonlyArray; + allFilesExcludingDefaultLibraryFile?: readonly SourceFile[]; /** * Cache of all the file names */ - allFileNames?: ReadonlyArray; + allFileNames?: readonly string[]; } export function cloneMapOrUndefined(map: ReadonlyMap | undefined) { @@ -286,7 +286,7 @@ namespace ts.BuilderState { /** * Gets the files affected by the path from the program */ - export function getFilesAffectedBy(state: BuilderState, programOfThisState: Program, path: Path, cancellationToken: CancellationToken | undefined, computeHash: ComputeHash, cacheToUpdateSignature?: Map, exportedModulesMapCache?: ComputingExportedModulesMap): ReadonlyArray { + export function getFilesAffectedBy(state: BuilderState, programOfThisState: Program, path: Path, cancellationToken: CancellationToken | undefined, computeHash: ComputeHash, cacheToUpdateSignature?: Map, exportedModulesMapCache?: ComputingExportedModulesMap): readonly SourceFile[] { // Since the operation could be cancelled, the signatures are always stored in the cache // They will be committed once it is safe to use them // eg when calling this api from tsserver, if there is no cancellation of the operation @@ -407,7 +407,7 @@ namespace ts.BuilderState { /** * Get all the dependencies of the sourceFile */ - export function getAllDependencies(state: BuilderState, programOfThisState: Program, sourceFile: SourceFile): ReadonlyArray { + export function getAllDependencies(state: BuilderState, programOfThisState: Program, sourceFile: SourceFile): readonly string[] { const compilerOptions = programOfThisState.getCompilerOptions(); // With --out or --outFile all outputs go into single file, all files depend on each other if (compilerOptions.outFile || compilerOptions.out) { @@ -445,7 +445,7 @@ namespace ts.BuilderState { /** * Gets the names of all files from the program */ - function getAllFileNames(state: BuilderState, programOfThisState: Program): ReadonlyArray { + function getAllFileNames(state: BuilderState, programOfThisState: Program): readonly string[] { if (!state.allFileNames) { const sourceFiles = programOfThisState.getSourceFiles(); state.allFileNames = sourceFiles === emptyArray ? emptyArray : sourceFiles.map(file => file.fileName); @@ -496,7 +496,7 @@ namespace ts.BuilderState { /** * Gets all files of the program excluding the default library file */ - function getAllFilesExcludingDefaultLibraryFile(state: BuilderState, programOfThisState: Program, firstSourceFile: SourceFile): ReadonlyArray { + function getAllFilesExcludingDefaultLibraryFile(state: BuilderState, programOfThisState: Program, firstSourceFile: SourceFile): readonly SourceFile[] { // Use cached result if (state.allFilesExcludingDefaultLibraryFile) { return state.allFilesExcludingDefaultLibraryFile; diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 530b3b52c12..d06f93eaeca 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -1106,7 +1106,7 @@ namespace ts { }); } - function addDuplicateDeclarationError(errorNode: Node, message: DiagnosticMessage, symbolName: string, relatedNodes: ReadonlyArray | undefined) { + function addDuplicateDeclarationError(errorNode: Node, message: DiagnosticMessage, symbolName: string, relatedNodes: readonly Node[] | undefined) { const err = lookupOrIssueError(errorNode, message, symbolName); for (const relatedNode of relatedNodes || emptyArray) { err.relatedInformation = err.relatedInformation || []; @@ -3034,7 +3034,7 @@ namespace ts { return type; } - function createBooleanType(trueFalseTypes: ReadonlyArray): IntrinsicType & UnionType { + function createBooleanType(trueFalseTypes: readonly Type[]): IntrinsicType & UnionType { const type = getUnionType(trueFalseTypes); type.flags |= TypeFlags.Boolean; type.intrinsicName = "boolean"; @@ -3085,7 +3085,7 @@ namespace ts { return result || emptyArray; } - function setStructuredTypeMembers(type: StructuredType, members: SymbolTable, callSignatures: ReadonlyArray, constructSignatures: ReadonlyArray, stringIndexInfo: IndexInfo | undefined, numberIndexInfo: IndexInfo | undefined): ResolvedType { + function setStructuredTypeMembers(type: StructuredType, members: SymbolTable, callSignatures: readonly Signature[], constructSignatures: readonly Signature[], stringIndexInfo: IndexInfo | undefined, numberIndexInfo: IndexInfo | undefined): ResolvedType { (type).members = members; (type).properties = members === emptySymbols ? emptyArray : getNamedMembers(members); (type).callSignatures = callSignatures; @@ -3095,7 +3095,7 @@ namespace ts { return type; } - function createAnonymousType(symbol: Symbol | undefined, members: SymbolTable, callSignatures: ReadonlyArray, constructSignatures: ReadonlyArray, stringIndexInfo: IndexInfo | undefined, numberIndexInfo: IndexInfo | undefined): ResolvedType { + function createAnonymousType(symbol: Symbol | undefined, members: SymbolTable, callSignatures: readonly Signature[], constructSignatures: readonly Signature[], stringIndexInfo: IndexInfo | undefined, numberIndexInfo: IndexInfo | undefined): ResolvedType { return setStructuredTypeMembers(createObjectType(ObjectFlags.Anonymous, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } @@ -3905,7 +3905,7 @@ namespace ts { } function typeReferenceToTypeNode(type: TypeReference) { - const typeArguments: ReadonlyArray = type.typeArguments || emptyArray; + const typeArguments: readonly Type[] = type.typeArguments || emptyArray; if (type.target === globalArrayType || type.target === globalReadonlyArrayType) { if (context.flags & NodeBuilderFlags.WriteArrayAsGenericType) { const typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); @@ -3970,7 +3970,7 @@ namespace ts { } } } - let typeArgumentNodes: ReadonlyArray | undefined; + let typeArgumentNodes: readonly TypeNode[] | undefined; if (typeArguments.length > 0) { const typeParameterCount = (type.target.typeParameters || emptyArray).length; typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context); @@ -4146,7 +4146,7 @@ namespace ts { } } - function mapToTypeNodes(types: ReadonlyArray | undefined, context: NodeBuilderContext, isBareList?: boolean): TypeNode[] | undefined { + function mapToTypeNodes(types: readonly Type[] | undefined, context: NodeBuilderContext, isBareList?: boolean): TypeNode[] | undefined { if (some(types)) { if (checkTruncationLength(context)) { if (!isBareList) { @@ -4417,7 +4417,7 @@ namespace ts { return undefined; } (context.typeParameterSymbolList || (context.typeParameterSymbolList = createMap())).set(symbolId, true); - let typeParameterNodes: ReadonlyArray | ReadonlyArray | undefined; + let typeParameterNodes: readonly TypeNode[] | readonly TypeParameterDeclaration[] | undefined; if (context.flags & NodeBuilderFlags.WriteTypeParametersInQualifiedName && index < (chain.length - 1)) { const parentSymbol = symbol; const nextSymbol = chain[index + 1]; @@ -4496,7 +4496,7 @@ namespace ts { return specifier; } - function symbolToTypeNode(symbol: Symbol, context: NodeBuilderContext, meaning: SymbolFlags, overrideTypeArguments?: ReadonlyArray): TypeNode { + function symbolToTypeNode(symbol: Symbol, context: NodeBuilderContext, meaning: SymbolFlags, overrideTypeArguments?: readonly TypeNode[]): TypeNode { const chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & NodeBuilderFlags.UseAliasDefinedOutsideCurrentScope)); // If we're using aliases outside the current scope, dont bother with the module const isTypeOf = meaning === SymbolFlags.Value; @@ -4521,12 +4521,12 @@ namespace ts { const lastId = isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right; lastId.typeArguments = undefined; } - return createImportTypeNode(lit, nonRootParts as EntityName, typeParameterNodes as ReadonlyArray, isTypeOf); + return createImportTypeNode(lit, nonRootParts as EntityName, typeParameterNodes as readonly TypeNode[], isTypeOf); } else { const splitNode = getTopmostIndexedAccessType(nonRootParts); const qualifier = (splitNode.objectType as TypeReferenceNode).typeName; - return createIndexedAccessTypeNode(createImportTypeNode(lit, qualifier, typeParameterNodes as ReadonlyArray, isTypeOf), splitNode.indexType); + return createIndexedAccessTypeNode(createImportTypeNode(lit, qualifier, typeParameterNodes as readonly TypeNode[], isTypeOf), splitNode.indexType); } } @@ -4565,7 +4565,7 @@ namespace ts { return createIndexedAccessTypeNode(LHS, createLiteralTypeNode(createLiteral(symbolName))); } else { - return createIndexedAccessTypeNode(createTypeReferenceNode(LHS, typeParameterNodes as ReadonlyArray), createLiteralTypeNode(createLiteral(symbolName))); + return createIndexedAccessTypeNode(createTypeReferenceNode(LHS, typeParameterNodes as readonly TypeNode[]), createLiteralTypeNode(createLiteral(symbolName))); } } @@ -4708,7 +4708,7 @@ namespace ts { } } - function formatUnionTypes(types: ReadonlyArray): Type[] { + function formatUnionTypes(types: readonly Type[]): Type[] { const result: Type[] = []; let flags: TypeFlags = 0; for (let i = 0; i < types.length; i++) { @@ -6144,7 +6144,7 @@ namespace ts { // Appends the type parameters given by a list of declarations to a set of type parameters and returns the resulting set. // The function allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set // in-place and returns the same array. - function appendTypeParameters(typeParameters: TypeParameter[] | undefined, declarations: ReadonlyArray): TypeParameter[] | undefined { + function appendTypeParameters(typeParameters: TypeParameter[] | undefined, declarations: readonly TypeParameterDeclaration[]): TypeParameter[] | undefined { for (const declaration of declarations) { typeParameters = appendIfUnique(typeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration))); } @@ -6249,14 +6249,14 @@ namespace ts { return getEffectiveBaseTypeNode(type.symbol.valueDeclaration as ClassLikeDeclaration); } - function getConstructorsForTypeArguments(type: Type, typeArgumentNodes: ReadonlyArray | undefined, location: Node): ReadonlyArray { + function getConstructorsForTypeArguments(type: Type, typeArgumentNodes: readonly TypeNode[] | undefined, location: Node): readonly Signature[] { const typeArgCount = length(typeArgumentNodes); const isJavascript = isInJSFile(location); return filter(getSignaturesOfType(type, SignatureKind.Construct), sig => (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= length(sig.typeParameters)); } - function getInstantiatedConstructorsForTypeArguments(type: Type, typeArgumentNodes: ReadonlyArray | undefined, location: Node): ReadonlyArray { + function getInstantiatedConstructorsForTypeArguments(type: Type, typeArgumentNodes: readonly TypeNode[] | undefined, location: Node): readonly Signature[] { const signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); const typeArguments = map(typeArgumentNodes, getTypeFromTypeNode); return sameMap(signatures, sig => some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, isInJSFile(location)) : sig); @@ -7027,11 +7027,11 @@ namespace ts { return needApparentType ? getApparentType(type) : type; } - function resolveObjectTypeMembers(type: ObjectType, source: InterfaceTypeWithDeclaredMembers, typeParameters: ReadonlyArray, typeArguments: ReadonlyArray) { + function resolveObjectTypeMembers(type: ObjectType, source: InterfaceTypeWithDeclaredMembers, typeParameters: readonly TypeParameter[], typeArguments: readonly Type[]) { let mapper: TypeMapper; let members: SymbolTable; - let callSignatures: ReadonlyArray; - let constructSignatures: ReadonlyArray | undefined; + let callSignatures: readonly Signature[]; + let constructSignatures: readonly Signature[] | undefined; let stringIndexInfo: IndexInfo | undefined; let numberIndexInfo: IndexInfo | undefined; if (rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { @@ -7087,9 +7087,9 @@ namespace ts { function createSignature( declaration: SignatureDeclaration | JSDocSignature | undefined, - typeParameters: ReadonlyArray | undefined, + typeParameters: readonly TypeParameter[] | undefined, thisParameter: Symbol | undefined, - parameters: ReadonlyArray, + parameters: readonly Symbol[], resolvedReturnType: Type | undefined, resolvedTypePredicate: TypePredicate | undefined, minArgumentCount: number, @@ -7127,7 +7127,7 @@ namespace ts { return result; } - function getExpandedParameters(sig: Signature): ReadonlyArray { + function getExpandedParameters(sig: Signature): readonly Symbol[] { if (sig.hasRestParameter) { const restIndex = sig.parameters.length - 1; const restParameter = sig.parameters[restIndex]; @@ -7174,7 +7174,7 @@ namespace ts { return result; } - function findMatchingSignature(signatureList: ReadonlyArray, signature: Signature, partialMatch: boolean, ignoreThisTypes: boolean, ignoreReturnTypes: boolean): Signature | undefined { + function findMatchingSignature(signatureList: readonly Signature[], signature: Signature, partialMatch: boolean, ignoreThisTypes: boolean, ignoreReturnTypes: boolean): Signature | undefined { for (const s of signatureList) { if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, partialMatch ? compareTypesSubtypeOf : compareTypesIdentical)) { return s; @@ -7182,7 +7182,7 @@ namespace ts { } } - function findMatchingSignatures(signatureLists: ReadonlyArray>, signature: Signature, listIndex: number): Signature[] | undefined { + function findMatchingSignatures(signatureLists: readonly (readonly Signature[])[], signature: Signature, listIndex: number): Signature[] | undefined { if (signature.typeParameters) { // We require an exact match for generic signatures, so we only return signatures from the first // signature list and only if they have exact matches in the other signature lists. @@ -7213,7 +7213,7 @@ namespace ts { // Generic signatures must match exactly, but non-generic signatures are allowed to have extra optional // parameters and may differ in return types. When signatures differ in return types, the resulting return // type is the union of the constituent return types. - function getUnionSignatures(signatureLists: ReadonlyArray>): Signature[] { + function getUnionSignatures(signatureLists: readonly (readonly Signature[])[]): Signature[] { let result: Signature[] | undefined; let indexWithLengthOverOne: number | undefined; for (let i = 0; i < signatureLists.length; i++) { @@ -7335,7 +7335,7 @@ namespace ts { return result; } - function getUnionIndexInfo(types: ReadonlyArray, kind: IndexKind): IndexInfo | undefined { + function getUnionIndexInfo(types: readonly Type[], kind: IndexKind): IndexInfo | undefined { const indexTypes: Type[] = []; let isAnyReadonly = false; for (const type of types) { @@ -7375,7 +7375,7 @@ namespace ts { getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly); } - function findMixins(types: ReadonlyArray): ReadonlyArray { + function findMixins(types: readonly Type[]): readonly boolean[] { const constructorTypeCount = countWhere(types, (t) => getSignaturesOfType(t, SignatureKind.Construct).length > 0); const mixinFlags = map(types, isMixinConstructorType); if (constructorTypeCount > 0 && constructorTypeCount === countWhere(mixinFlags, (b) => b)) { @@ -7385,7 +7385,7 @@ namespace ts { return mixinFlags; } - function includeMixinType(type: Type, types: ReadonlyArray, mixinFlags: ReadonlyArray, index: number): Type { + function includeMixinType(type: Type, types: readonly Type[], mixinFlags: readonly boolean[], index: number): Type { const mixedTypes: Type[] = []; for (let i = 0; i < types.length; i++) { if (i === index) { @@ -7433,7 +7433,7 @@ namespace ts { setStructuredTypeMembers(type, emptySymbols, callSignatures || emptyArray, constructSignatures || emptyArray, stringIndexInfo, numberIndexInfo); } - function appendSignatures(signatures: Signature[] | undefined, newSignatures: ReadonlyArray) { + function appendSignatures(signatures: Signature[] | undefined, newSignatures: readonly Signature[]) { for (const sig of newSignatures) { if (!signatures || every(signatures, s => !compareSignaturesIdentical(s, sig, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, compareTypesIdentical))) { signatures = append(signatures, sig); @@ -7819,7 +7819,7 @@ namespace ts { }); } - function getAllPossiblePropertiesOfTypes(types: ReadonlyArray): Symbol[] { + function getAllPossiblePropertiesOfTypes(types: readonly Type[]): Symbol[] { const unionType = getUnionType(types); if (!(unionType.flags & TypeFlags.Union)) { return getAugmentedPropertiesOfType(unionType); @@ -8325,7 +8325,7 @@ namespace ts { return undefined; } - function getSignaturesOfStructuredType(type: Type, kind: SignatureKind): ReadonlyArray { + function getSignaturesOfStructuredType(type: Type, kind: SignatureKind): readonly Signature[] { if (type.flags & TypeFlags.StructuredType) { const resolved = resolveStructuredTypeMembers(type); return kind === SignatureKind.Call ? resolved.callSignatures : resolved.constructSignatures; @@ -8337,7 +8337,7 @@ namespace ts { * Return the signatures of the given kind in the given type. Creates synthetic union signatures when necessary and * maps primitive types and type parameters are to their apparent types. */ - function getSignaturesOfType(type: Type, kind: SignatureKind): ReadonlyArray { + function getSignaturesOfType(type: Type, kind: SignatureKind): readonly Signature[] { return getSignaturesOfStructuredType(getApparentType(type), kind); } @@ -8461,7 +8461,7 @@ namespace ts { * Gets the minimum number of type arguments needed to satisfy all non-optional type * parameters. */ - function getMinTypeArgumentCount(typeParameters: ReadonlyArray | undefined): number { + function getMinTypeArgumentCount(typeParameters: readonly TypeParameter[] | undefined): number { let minTypeArgumentCount = 0; if (typeParameters) { for (let i = 0; i < typeParameters.length; i++) { @@ -8481,9 +8481,9 @@ namespace ts { * @param typeParameters The requested type parameters. * @param minTypeArgumentCount The minimum number of required type arguments. */ - function fillMissingTypeArguments(typeArguments: ReadonlyArray, typeParameters: ReadonlyArray | undefined, minTypeArgumentCount: number, isJavaScriptImplicitAny: boolean): Type[]; - function fillMissingTypeArguments(typeArguments: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, minTypeArgumentCount: number, isJavaScriptImplicitAny: boolean): Type[] | undefined; - function fillMissingTypeArguments(typeArguments: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, minTypeArgumentCount: number, isJavaScriptImplicitAny: boolean) { + function fillMissingTypeArguments(typeArguments: readonly Type[], typeParameters: readonly TypeParameter[] | undefined, minTypeArgumentCount: number, isJavaScriptImplicitAny: boolean): Type[]; + function fillMissingTypeArguments(typeArguments: readonly Type[] | undefined, typeParameters: readonly TypeParameter[] | undefined, minTypeArgumentCount: number, isJavaScriptImplicitAny: boolean): Type[] | undefined; + function fillMissingTypeArguments(typeArguments: readonly Type[] | undefined, typeParameters: readonly TypeParameter[] | undefined, minTypeArgumentCount: number, isJavaScriptImplicitAny: boolean) { const numTypeParameters = length(typeParameters); if (!numTypeParameters) { return []; @@ -8810,7 +8810,7 @@ namespace ts { return undefined; } - function getSignatureInstantiation(signature: Signature, typeArguments: Type[] | undefined, isJavascript: boolean, inferredTypeParameters?: ReadonlyArray): Signature { + function getSignatureInstantiation(signature: Signature, typeArguments: Type[] | undefined, isJavascript: boolean, inferredTypeParameters?: readonly TypeParameter[]): Signature { const instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); if (inferredTypeParameters) { const returnSignature = getSingleCallOrConstructSignature(getReturnTypeOfSignature(instantiatedSignature)); @@ -8825,7 +8825,7 @@ namespace ts { return instantiatedSignature; } - function getSignatureInstantiationWithoutFillingInTypeArguments(signature: Signature, typeArguments: ReadonlyArray | undefined): Signature { + function getSignatureInstantiationWithoutFillingInTypeArguments(signature: Signature, typeArguments: readonly Type[] | undefined): Signature { const instantiations = signature.instantiations || (signature.instantiations = createMap()); const id = getTypeListId(typeArguments); let instantiation = instantiations.get(id); @@ -8835,11 +8835,11 @@ namespace ts { return instantiation; } - function createSignatureInstantiation(signature: Signature, typeArguments: ReadonlyArray | undefined): Signature { + function createSignatureInstantiation(signature: Signature, typeArguments: readonly Type[] | undefined): Signature { return instantiateSignature(signature, createSignatureTypeMapper(signature, typeArguments), /*eraseTypeParameters*/ true); } - function createSignatureTypeMapper(signature: Signature, typeArguments: ReadonlyArray | undefined): TypeMapper { + function createSignatureTypeMapper(signature: Signature, typeArguments: readonly Type[] | undefined): TypeMapper { return createTypeMapper(signature.typeParameters!, typeArguments); } @@ -9008,7 +9008,7 @@ namespace ts { return host && getSymbolOfNode(host); } - function getTypeListId(types: ReadonlyArray | undefined) { + function getTypeListId(types: readonly Type[] | undefined) { let result = ""; if (types) { const length = types.length; @@ -9036,7 +9036,7 @@ namespace ts { // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type // of an object literal or the anyFunctionType. This is because there are operations in the type checker // that care about the presence of such types at arbitrary depth in a containing type. - function getPropagatingFlagsOfTypes(types: ReadonlyArray, excludeKinds: TypeFlags): ObjectFlags { + function getPropagatingFlagsOfTypes(types: readonly Type[], excludeKinds: TypeFlags): ObjectFlags { let result: ObjectFlags = 0; for (const type of types) { if (!(type.flags & excludeKinds)) { @@ -9046,7 +9046,7 @@ namespace ts { return result & ObjectFlags.PropagatingFlags; } - function createTypeReference(target: GenericType, typeArguments: ReadonlyArray | undefined): TypeReference { + function createTypeReference(target: GenericType, typeArguments: readonly Type[] | undefined): TypeReference { const id = getTypeListId(typeArguments); let type = target.instantiations.get(id); if (!type) { @@ -9109,7 +9109,7 @@ namespace ts { return checkNoTypeArguments(node, symbol) ? type : errorType; } - function getTypeAliasInstantiation(symbol: Symbol, typeArguments: ReadonlyArray | undefined): Type { + function getTypeAliasInstantiation(symbol: Symbol, typeArguments: readonly Type[] | undefined): Type { const type = getDeclaredTypeOfSymbol(symbol); const links = getSymbolLinks(symbol); const typeParameters = links.typeParameters!; @@ -9539,7 +9539,7 @@ namespace ts { /** * Instantiates a global type that is generic with some element type, and returns that instantiation. */ - function createTypeFromGenericGlobalType(genericGlobalType: GenericType, typeArguments: ReadonlyArray): ObjectType { + function createTypeFromGenericGlobalType(genericGlobalType: GenericType, typeArguments: readonly Type[]): ObjectType { return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType; } @@ -9627,7 +9627,7 @@ namespace ts { return type; } - function createTupleType(elementTypes: ReadonlyArray, minLength = elementTypes.length, hasRestElement = false, readonly = false, associatedNames?: __String[]) { + function createTupleType(elementTypes: readonly Type[], minLength = elementTypes.length, hasRestElement = false, readonly = false, associatedNames?: __String[]) { const arity = elementTypes.length; if (arity === 1 && hasRestElement) { return createArrayType(elementTypes[0], readonly); @@ -9675,7 +9675,7 @@ namespace ts { return type.id; } - function containsType(types: ReadonlyArray, type: Type): boolean { + function containsType(types: readonly Type[], type: Type): boolean { return binarySearch(types, type, getTypeId, compareValues) >= 0; } @@ -9714,14 +9714,14 @@ namespace ts { // Add the given types to the given type set. Order is preserved, duplicates are removed, // and nested types of the given kind are flattened into the set. - function addTypesToUnion(typeSet: Type[], includes: TypeFlags, types: ReadonlyArray): TypeFlags { + function addTypesToUnion(typeSet: Type[], includes: TypeFlags, types: readonly Type[]): TypeFlags { for (const type of types) { includes = addTypeToUnion(typeSet, includes, type); } return includes; } - function isSetOfLiteralsFromSameEnum(types: ReadonlyArray): boolean { + function isSetOfLiteralsFromSameEnum(types: readonly Type[]): boolean { const first = types[0]; if (first.flags & TypeFlags.EnumLiteral) { const firstEnum = getParentOfSymbol(first.symbol); @@ -9799,7 +9799,7 @@ namespace ts { // expression constructs such as array literals and the || and ?: operators). Named types can // circularly reference themselves and therefore cannot be subtype reduced during their declaration. // For example, "type Item = string | (() => Item" is a named type that circularly references itself. - function getUnionType(types: ReadonlyArray, unionReduction: UnionReduction = UnionReduction.Literal, aliasSymbol?: Symbol, aliasTypeArguments?: ReadonlyArray): Type { + function getUnionType(types: readonly Type[], unionReduction: UnionReduction = UnionReduction.Literal, aliasSymbol?: Symbol, aliasTypeArguments?: readonly Type[]): Type { if (types.length === 0) { return neverType; } @@ -9833,7 +9833,7 @@ namespace ts { return getUnionTypeFromSortedList(typeSet, includes & TypeFlags.NotPrimitiveUnion ? 0 : ObjectFlags.PrimitiveUnion, aliasSymbol, aliasTypeArguments); } - function getUnionTypePredicate(signatures: ReadonlyArray): TypePredicate | undefined { + function getUnionTypePredicate(signatures: readonly Signature[]): TypePredicate | undefined { let first: TypePredicate | undefined; const types: Type[] = []; for (const sig of signatures) { @@ -9870,7 +9870,7 @@ namespace ts { } // This function assumes the constituent type list is sorted and deduplicated. - function getUnionTypeFromSortedList(types: Type[], objectFlags: ObjectFlags, aliasSymbol?: Symbol, aliasTypeArguments?: ReadonlyArray): Type { + function getUnionTypeFromSortedList(types: Type[], objectFlags: ObjectFlags, aliasSymbol?: Symbol, aliasTypeArguments?: readonly Type[]): Type { if (types.length === 0) { return neverType; } @@ -9936,7 +9936,7 @@ namespace ts { // Add the given types to the given type set. Order is preserved, freshness is removed from literal // types, duplicates are removed, and nested types of the given kind are flattened into the set. - function addTypesToIntersection(typeSet: Map, includes: TypeFlags, types: ReadonlyArray) { + function addTypesToIntersection(typeSet: Map, includes: TypeFlags, types: readonly Type[]) { for (const type of types) { includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); } @@ -10023,7 +10023,7 @@ namespace ts { return true; } - function createIntersectionType(types: Type[], aliasSymbol?: Symbol, aliasTypeArguments?: ReadonlyArray) { + function createIntersectionType(types: Type[], aliasSymbol?: Symbol, aliasTypeArguments?: readonly Type[]) { const result = createType(TypeFlags.Intersection); result.objectFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ TypeFlags.Nullable); result.types = types; @@ -10042,7 +10042,7 @@ namespace ts { // a type alias of the form "type List = T & { next: List }" cannot be reduced during its declaration. // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution // for intersections of types with signatures can be deterministic. - function getIntersectionType(types: ReadonlyArray, aliasSymbol?: Symbol, aliasTypeArguments?: ReadonlyArray): Type { + function getIntersectionType(types: readonly Type[], aliasSymbol?: Symbol, aliasTypeArguments?: readonly Type[]): Type { const typeMembershipMap: Map = createMap(); const includes = addTypesToIntersection(typeMembershipMap, 0, types); const typeSet: Type[] = arrayFrom(typeMembershipMap.values()); @@ -11185,9 +11185,9 @@ namespace ts { } } - function instantiateList(items: ReadonlyArray, mapper: TypeMapper, instantiator: (item: T, mapper: TypeMapper) => T): ReadonlyArray; - function instantiateList(items: ReadonlyArray | undefined, mapper: TypeMapper, instantiator: (item: T, mapper: TypeMapper) => T): ReadonlyArray | undefined; - function instantiateList(items: ReadonlyArray | undefined, mapper: TypeMapper, instantiator: (item: T, mapper: TypeMapper) => T): ReadonlyArray | undefined { + function instantiateList(items: readonly T[], mapper: TypeMapper, instantiator: (item: T, mapper: TypeMapper) => T): readonly T[]; + function instantiateList(items: readonly T[] | undefined, mapper: TypeMapper, instantiator: (item: T, mapper: TypeMapper) => T): readonly T[] | undefined; + function instantiateList(items: readonly T[] | undefined, mapper: TypeMapper, instantiator: (item: T, mapper: TypeMapper) => T): readonly T[] | undefined { if (items && items.length) { for (let i = 0; i < items.length; i++) { const item = items[i]; @@ -11205,13 +11205,13 @@ namespace ts { return items; } - function instantiateTypes(types: ReadonlyArray, mapper: TypeMapper): ReadonlyArray; - function instantiateTypes(types: ReadonlyArray | undefined, mapper: TypeMapper): ReadonlyArray | undefined; - function instantiateTypes(types: ReadonlyArray | undefined, mapper: TypeMapper): ReadonlyArray | undefined { + function instantiateTypes(types: readonly Type[], mapper: TypeMapper): readonly Type[]; + function instantiateTypes(types: readonly Type[] | undefined, mapper: TypeMapper): readonly Type[] | undefined; + function instantiateTypes(types: readonly Type[] | undefined, mapper: TypeMapper): readonly Type[] | undefined { return instantiateList(types, mapper, instantiateType); } - function instantiateSignatures(signatures: ReadonlyArray, mapper: TypeMapper): ReadonlyArray { + function instantiateSignatures(signatures: readonly Signature[], mapper: TypeMapper): readonly Signature[] { return instantiateList(signatures, mapper, instantiateSignature); } @@ -11223,7 +11223,7 @@ namespace ts { return (t: Type) => t === source1 ? target1 : t === source2 ? target2 : t; } - function makeArrayTypeMapper(sources: ReadonlyArray, targets: ReadonlyArray | undefined) { + function makeArrayTypeMapper(sources: readonly Type[], targets: readonly Type[] | undefined) { return (t: Type) => { for (let i = 0; i < sources.length; i++) { if (t === sources[i]) { @@ -11234,14 +11234,14 @@ namespace ts { }; } - function createTypeMapper(sources: ReadonlyArray, targets: ReadonlyArray | undefined): TypeMapper { + function createTypeMapper(sources: readonly TypeParameter[], targets: readonly Type[] | undefined): TypeMapper { Debug.assert(targets === undefined || sources.length === targets.length); return sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : sources.length === 2 ? makeBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : makeArrayTypeMapper(sources, targets); } - function createTypeEraser(sources: ReadonlyArray): TypeMapper { + function createTypeEraser(sources: readonly TypeParameter[]): TypeMapper { return createTypeMapper(sources, /*targets*/ undefined); } @@ -13186,7 +13186,7 @@ namespace ts { return result; } - function typeArgumentsRelatedTo(sources: ReadonlyArray = emptyArray, targets: ReadonlyArray = emptyArray, variances: ReadonlyArray = emptyArray, reportErrors: boolean, isIntersectionConstituent: boolean): Ternary { + function typeArgumentsRelatedTo(sources: readonly Type[] = emptyArray, targets: readonly Type[] = emptyArray, variances: readonly VarianceFlags[] = emptyArray, reportErrors: boolean, isIntersectionConstituent: boolean): Ternary { if (sources.length !== targets.length && relation === identityRelation) { return Ternary.False; } @@ -13243,7 +13243,7 @@ namespace ts { return result; } - function propagateSidebandVarianceFlags(typeArguments: ReadonlyArray, variances: VarianceFlags[]) { + function propagateSidebandVarianceFlags(typeArguments: readonly Type[], variances: VarianceFlags[]) { for (let i = 0; i < variances.length; i++) { const v = variances[i]; if (v & VarianceFlags.Unmeasurable) { @@ -13627,7 +13627,7 @@ namespace ts { } return Ternary.False; - function relateVariances(sourceTypeArguments: ReadonlyArray | undefined, targetTypeArguments: ReadonlyArray | undefined, variances: VarianceFlags[], isIntersectionConstituent: boolean) { + function relateVariances(sourceTypeArguments: readonly Type[] | undefined, targetTypeArguments: readonly Type[] | undefined, variances: VarianceFlags[], isIntersectionConstituent: boolean) { if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors, isIntersectionConstituent)) { return result; } @@ -14332,7 +14332,7 @@ namespace ts { // instantiations of the generic type for type arguments with known relations. The function // returns the emptyArray singleton if we're not in strictFunctionTypes mode or if the function // has been invoked recursively for the given generic type. - function getVariancesWorker(typeParameters: ReadonlyArray = emptyArray, cache: TCache, createMarkerType: (input: TCache, param: TypeParameter, marker: Type) => Type): VarianceFlags[] { + function getVariancesWorker(typeParameters: readonly TypeParameter[] = emptyArray, cache: TCache, createMarkerType: (input: TCache, param: TypeParameter, marker: Type) => Type): VarianceFlags[] { let variances = cache.variances; if (!variances) { // The emptyArray singleton is used to signal a recursive invocation. @@ -14383,7 +14383,7 @@ namespace ts { // Return true if the given type reference has a 'void' type argument for a covariant type parameter. // See comment at call in recursiveTypeRelatedTo for when this case matters. - function hasCovariantVoidArgument(typeArguments: ReadonlyArray, variances: VarianceFlags[]): boolean { + function hasCovariantVoidArgument(typeArguments: readonly Type[], variances: VarianceFlags[]): boolean { for (let i = 0; i < variances.length; i++) { if ((variances[i] & VarianceFlags.VarianceMask) === VarianceFlags.Covariant && typeArguments[i].flags & TypeFlags.Void) { return true; @@ -15244,7 +15244,7 @@ namespace ts { } } - function createInferenceContext(typeParameters: ReadonlyArray, signature: Signature | undefined, flags: InferenceFlags, compareTypes?: TypeComparer): InferenceContext { + function createInferenceContext(typeParameters: readonly TypeParameter[], signature: Signature | undefined, flags: InferenceFlags, compareTypes?: TypeComparer): InferenceContext { return createInferenceContextWorker(typeParameters.map(createInferenceInfo), signature, flags, compareTypes || compareTypesAssignable); } @@ -15728,7 +15728,7 @@ namespace ts { ]; } - function inferFromTypeArguments(sourceTypes: ReadonlyArray, targetTypes: ReadonlyArray, variances: ReadonlyArray) { + function inferFromTypeArguments(sourceTypes: readonly Type[], targetTypes: readonly Type[], variances: readonly VarianceFlags[]) { const count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; for (let i = 0; i < count; i++) { if (i < variances.length && (variances[i] & VarianceFlags.VarianceMask) === VarianceFlags.Contravariant) { @@ -20198,7 +20198,7 @@ namespace ts { return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace); } - function getUninstantiatedJsxSignaturesOfType(elementType: Type, caller: JsxOpeningLikeElement): ReadonlyArray { + function getUninstantiatedJsxSignaturesOfType(elementType: Type, caller: JsxOpeningLikeElement): readonly Signature[] { if (elementType.flags & TypeFlags.String) { return [anySignature]; } @@ -21158,7 +21158,7 @@ namespace ts { // interface B extends A { (x: 'foo'): string } // const b: B; // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void] - function reorderCandidates(signatures: ReadonlyArray, result: Signature[]): void { + function reorderCandidates(signatures: readonly Signature[], result: Signature[]): void { let lastParent: Node | undefined; let lastSymbol: Symbol | undefined; let cutoffIndex = 0; @@ -21208,7 +21208,7 @@ namespace ts { return !!arg && (arg.kind === SyntaxKind.SpreadElement || arg.kind === SyntaxKind.SyntheticExpression && (arg).isSpread); } - function getSpreadArgumentIndex(args: ReadonlyArray): number { + function getSpreadArgumentIndex(args: readonly Expression[]): number { return findIndex(args, isSpreadArgument); } @@ -21216,7 +21216,7 @@ namespace ts { return !!(t.flags & TypeFlags.Void); } - function hasCorrectArity(node: CallLikeExpression, args: ReadonlyArray, signature: Signature, signatureHelpTrailingComma = false) { + function hasCorrectArity(node: CallLikeExpression, args: readonly Expression[], signature: Signature, signatureHelpTrailingComma = false) { let argCount: number; let callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments let effectiveParameterCount = getParameterCount(signature); @@ -21351,7 +21351,7 @@ namespace ts { return getInferredTypes(context); } - function inferTypeArguments(node: CallLikeExpression, signature: Signature, args: ReadonlyArray, checkMode: CheckMode, context: InferenceContext): Type[] { + function inferTypeArguments(node: CallLikeExpression, signature: Signature, args: readonly Expression[], checkMode: CheckMode, context: InferenceContext): Type[] { if (isJsxOpeningLikeElement(node)) { return inferJsxTypeArguments(node, signature, checkMode, context); } @@ -21427,7 +21427,7 @@ namespace ts { return type; } - function getSpreadArgumentType(args: ReadonlyArray, index: number, argCount: number, restType: Type, context: InferenceContext | undefined) { + function getSpreadArgumentType(args: readonly Expression[], index: number, argCount: number, restType: Type, context: InferenceContext | undefined) { if (index >= argCount - 1) { const arg = args[argCount - 1]; if (isSpreadArgument(arg)) { @@ -21454,7 +21454,7 @@ namespace ts { createTupleType(append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true); } - function checkTypeArguments(signature: Signature, typeArgumentNodes: ReadonlyArray, reportErrors: boolean, headMessage?: DiagnosticMessage): Type[] | undefined { + function checkTypeArguments(signature: Signature, typeArgumentNodes: readonly TypeNode[], reportErrors: boolean, headMessage?: DiagnosticMessage): Type[] | undefined { const isJavascript = isInJSFile(signature.declaration); const typeParameters = signature.typeParameters!; const typeArgumentTypes = fillMissingTypeArguments(map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); @@ -21529,7 +21529,7 @@ namespace ts { function getSignatureApplicabilityError( node: CallLikeExpression, - args: ReadonlyArray, + args: readonly Expression[], signature: Signature, relation: Map, checkMode: CheckMode, @@ -21626,7 +21626,7 @@ namespace ts { /** * Returns the effective arguments for an expression that works like a function invocation. */ - function getEffectiveCallArguments(node: CallLikeExpression): ReadonlyArray { + function getEffectiveCallArguments(node: CallLikeExpression): readonly Expression[] { if (node.kind === SyntaxKind.TaggedTemplateExpression) { const template = node.template; const args: Expression[] = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; @@ -21664,7 +21664,7 @@ namespace ts { /** * Returns the synthetic argument list for a decorator invocation. */ - function getEffectiveDecoratorArguments(node: Decorator): ReadonlyArray { + function getEffectiveDecoratorArguments(node: Decorator): readonly Expression[] { const parent = node.parent; const expr = node.expression; switch (parent.kind) { @@ -21749,7 +21749,7 @@ namespace ts { } } - function getArgumentArityError(node: CallLikeExpression, signatures: ReadonlyArray, args: ReadonlyArray) { + function getArgumentArityError(node: CallLikeExpression, signatures: readonly Signature[], args: readonly Expression[]) { let min = Number.POSITIVE_INFINITY; let max = Number.NEGATIVE_INFINITY; let belowArgCount = Number.NEGATIVE_INFINITY; @@ -21825,7 +21825,7 @@ namespace ts { return related ? addRelatedInfo(diagnostic, related) : diagnostic; } - function getTypeArgumentArityError(node: Node, signatures: ReadonlyArray, typeArguments: NodeArray) { + function getTypeArgumentArityError(node: Node, signatures: readonly Signature[], typeArguments: NodeArray) { const argCount = typeArguments.length; // No overloads exist if (signatures.length === 1) { @@ -21853,7 +21853,7 @@ namespace ts { return createDiagnosticForNodeArray(getSourceFileOfNode(node), typeArguments, Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount); } - function resolveCall(node: CallLikeExpression, signatures: ReadonlyArray, candidatesOutArray: Signature[] | undefined, checkMode: CheckMode, fallbackError?: DiagnosticMessage): Signature { + function resolveCall(node: CallLikeExpression, signatures: readonly Signature[], candidatesOutArray: Signature[] | undefined, checkMode: CheckMode, fallbackError?: DiagnosticMessage): Signature { const isTaggedTemplate = node.kind === SyntaxKind.TaggedTemplateExpression; const isDecorator = node.kind === SyntaxKind.Decorator; const isJsxOpeningOrSelfClosingElement = isJsxOpeningLikeElement(node); @@ -22124,7 +22124,7 @@ namespace ts { function getCandidateForOverloadFailure( node: CallLikeExpression, candidates: Signature[], - args: ReadonlyArray, + args: readonly Expression[], hasCandidatesOutArray: boolean, ): Signature { Debug.assert(candidates.length > 0); // Else should not have called this. @@ -22136,7 +22136,7 @@ namespace ts { : createUnionOfSignaturesForOverloadFailure(candidates); } - function createUnionOfSignaturesForOverloadFailure(candidates: ReadonlyArray): Signature { + function createUnionOfSignaturesForOverloadFailure(candidates: readonly Signature[]): Signature { const thisParameters = mapDefined(candidates, c => c.thisParameter); let thisParameter: Symbol | undefined; if (thisParameters.length) { @@ -22174,16 +22174,16 @@ namespace ts { return signature.hasRestParameter ? numParams - 1 : numParams; } - function createCombinedSymbolFromTypes(sources: ReadonlyArray, types: Type[]): Symbol { + function createCombinedSymbolFromTypes(sources: readonly Symbol[], types: Type[]): Symbol { return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, UnionReduction.Subtype)); } - function createCombinedSymbolForOverloadFailure(sources: ReadonlyArray, type: Type): Symbol { + function createCombinedSymbolForOverloadFailure(sources: readonly Symbol[], type: Type): Symbol { // This function is currently only used for erroneous overloads, so it's good enough to just use the first source. return createSymbolWithType(first(sources), type); } - function pickLongestCandidateSignature(node: CallLikeExpression, candidates: Signature[], args: ReadonlyArray): Signature { + function pickLongestCandidateSignature(node: CallLikeExpression, candidates: Signature[], args: readonly Expression[]): Signature { // Pick the longest signature. This way we can get a contextual type for cases like: // declare function f(a: { xa: number; xb: number; }, b: number); // f({ | @@ -22197,7 +22197,7 @@ namespace ts { return candidate; } - const typeArgumentNodes: ReadonlyArray | undefined = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined; + const typeArgumentNodes: readonly TypeNode[] | undefined = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined; const instantiated = typeArgumentNodes ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isInJSFile(node))) : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args); @@ -22205,7 +22205,7 @@ namespace ts { return instantiated; } - function getTypeArgumentsFromNodes(typeArgumentNodes: ReadonlyArray, typeParameters: ReadonlyArray, isJs: boolean): ReadonlyArray { + function getTypeArgumentsFromNodes(typeArgumentNodes: readonly TypeNode[], typeParameters: readonly TypeParameter[], isJs: boolean): readonly Type[] { const typeArguments = typeArgumentNodes.map(getTypeOfNode); while (typeArguments.length > typeParameters.length) { typeArguments.pop(); @@ -22216,7 +22216,7 @@ namespace ts { return typeArguments; } - function inferSignatureInstantiationForOverloadFailure(node: CallLikeExpression, typeParameters: ReadonlyArray, candidate: Signature, args: ReadonlyArray): Signature { + function inferSignatureInstantiationForOverloadFailure(node: CallLikeExpression, typeParameters: readonly TypeParameter[], candidate: Signature, args: readonly Expression[]): Signature { const inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ isInJSFile(node) ? InferenceFlags.AnyDefault : InferenceFlags.None); const typeArgumentTypes = inferTypeArguments(node, candidate, args, CheckMode.SkipContextSensitive | CheckMode.SkipGenericFunctions, inferenceContext); return createSignatureInstantiation(candidate, typeArgumentTypes); @@ -22756,7 +22756,7 @@ namespace ts { * but is receiving too many arguments as part of the decorator invocation. * In those cases, a user may have meant to *call* the expression before using it as a decorator. */ - function isPotentiallyUncalledDecorator(decorator: Decorator, signatures: ReadonlyArray) { + function isPotentiallyUncalledDecorator(decorator: Decorator, signatures: readonly Signature[]) { return signatures.length && every(signatures, signature => signature.minArgumentCount === 0 && !signature.hasRestParameter && @@ -25125,7 +25125,7 @@ namespace ts { } } - function getUniqueTypeParameters(context: InferenceContext, typeParameters: ReadonlyArray): ReadonlyArray { + function getUniqueTypeParameters(context: InferenceContext, typeParameters: readonly TypeParameter[]): readonly TypeParameter[] { const result: TypeParameter[] = []; let oldTypeParameters: TypeParameter[] | undefined; let newTypeParameters: TypeParameter[] | undefined; @@ -25153,11 +25153,11 @@ namespace ts { return result; } - function hasTypeParameterByName(typeParameters: ReadonlyArray | undefined, name: __String) { + function hasTypeParameterByName(typeParameters: readonly TypeParameter[] | undefined, name: __String) { return some(typeParameters, tp => tp.symbol.escapedName === name); } - function getUniqueTypeParameterName(typeParameters: ReadonlyArray, baseName: __String) { + function getUniqueTypeParameterName(typeParameters: readonly TypeParameter[], baseName: __String) { let len = (baseName).length; while (len > 1 && (baseName).charCodeAt(len - 1) >= CharacterCodes._0 && (baseName).charCodeAt(len - 1) <= CharacterCodes._9) len--; const s = (baseName).slice(0, len); @@ -25924,12 +25924,12 @@ namespace ts { checkDecorators(node); } - function getEffectiveTypeArguments(node: TypeReferenceNode | ExpressionWithTypeArguments, typeParameters: ReadonlyArray): Type[] { + function getEffectiveTypeArguments(node: TypeReferenceNode | ExpressionWithTypeArguments, typeParameters: readonly TypeParameter[]): Type[] { return fillMissingTypeArguments(map(node.typeArguments!, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isInJSFile(node)); } - function checkTypeArgumentConstraints(node: TypeReferenceNode | ExpressionWithTypeArguments, typeParameters: ReadonlyArray): boolean { + function checkTypeArgumentConstraints(node: TypeReferenceNode | ExpressionWithTypeArguments, typeParameters: readonly TypeParameter[]): boolean { let typeArguments: Type[] | undefined; let mapper: TypeMapper | undefined; let result = true; @@ -26859,7 +26859,7 @@ namespace ts { } } - function getEntityNameForDecoratorMetadataFromTypeList(types: ReadonlyArray): EntityName | undefined { + function getEntityNameForDecoratorMetadataFromTypeList(types: readonly TypeNode[]): EntityName | undefined { let commonEntityName: EntityName | undefined; for (let typeNode of types) { while (typeNode.kind === SyntaxKind.ParenthesizedType) { @@ -27171,7 +27171,7 @@ namespace ts { | Exclude | TypeAliasDeclaration | InferTypeNode; - function checkUnusedIdentifiers(potentiallyUnusedIdentifiers: ReadonlyArray, addDiagnostic: AddUnusedDiagnostic) { + function checkUnusedIdentifiers(potentiallyUnusedIdentifiers: readonly PotentiallyUnusedIdentifier[], addDiagnostic: AddUnusedDiagnostic) { for (const node of potentiallyUnusedIdentifiers) { switch (node.kind) { case SyntaxKind.ClassDeclaration: @@ -29024,7 +29024,7 @@ namespace ts { /** * Check each type parameter and check that type parameters have no duplicate type parameter declarations */ - function checkTypeParameters(typeParameterDeclarations: ReadonlyArray | undefined) { + function checkTypeParameters(typeParameterDeclarations: readonly TypeParameterDeclaration[] | undefined) { if (typeParameterDeclarations) { let seenDefault = false; for (let i = 0; i < typeParameterDeclarations.length; i++) { @@ -29050,7 +29050,7 @@ namespace ts { } /** Check that type parameter defaults only reference previously declared type parameters */ - function checkTypeParametersNotReferenced(root: TypeNode, typeParameters: ReadonlyArray, index: number) { + function checkTypeParametersNotReferenced(root: TypeNode, typeParameters: readonly TypeParameterDeclaration[], index: number) { visit(root); function visit(node: Node) { if (node.kind === SyntaxKind.TypeReference) { @@ -29092,7 +29092,7 @@ namespace ts { } } - function areTypeParametersIdentical(declarations: ReadonlyArray, targetParameters: TypeParameter[]) { + function areTypeParametersIdentical(declarations: readonly (ClassDeclaration | InterfaceDeclaration)[], targetParameters: TypeParameter[]) { const maxTypeArgumentCount = length(targetParameters); const minTypeArgumentCount = getMinTypeArgumentCount(targetParameters); @@ -30598,7 +30598,7 @@ namespace ts { } } - function getPotentiallyUnusedIdentifiers(sourceFile: SourceFile): ReadonlyArray { + function getPotentiallyUnusedIdentifiers(sourceFile: SourceFile): readonly PotentiallyUnusedIdentifier[] { return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || emptyArray; } @@ -31330,11 +31330,11 @@ namespace ts { return ts.typeHasCallOrConstructSignatures(type, checker); } - function getRootSymbols(symbol: Symbol): ReadonlyArray { + function getRootSymbols(symbol: Symbol): readonly Symbol[] { const roots = getImmediateRootSymbols(symbol); return roots ? flatMap(roots, getRootSymbols) : [symbol]; } - function getImmediateRootSymbols(symbol: Symbol): ReadonlyArray | undefined { + function getImmediateRootSymbols(symbol: Symbol): readonly Symbol[] | undefined { if (getCheckFlags(symbol) & CheckFlags.Synthetic) { return mapDefined(getSymbolLinks(symbol).containingType!.types, type => getPropertyOfType(type, symbol.escapedName)); } @@ -32068,7 +32068,7 @@ namespace ts { amalgamatedDuplicates = createMap(); // Initialize global symbol table - let augmentations: ReadonlyArray[] | undefined; + let augmentations: (StringLiteral | Identifier)[][] | undefined; for (const file of host.getSourceFiles()) { if (file.redirectInfo) { continue; @@ -32597,7 +32597,7 @@ namespace ts { } } - function getNonSimpleParameters(parameters: ReadonlyArray): ReadonlyArray { + function getNonSimpleParameters(parameters: readonly ParameterDeclaration[]): readonly ParameterDeclaration[] { return filter(parameters, parameter => !!parameter.initializer || isBindingPattern(parameter.name) || isRestParameter(parameter)); } diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index f0f36dc765f..a603f835e15 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -865,19 +865,19 @@ namespace ts { ]; /* @internal */ - export const semanticDiagnosticsOptionDeclarations: ReadonlyArray = + export const semanticDiagnosticsOptionDeclarations: readonly CommandLineOption[] = optionDeclarations.filter(option => !!option.affectsSemanticDiagnostics); /* @internal */ - export const affectsEmitOptionDeclarations: ReadonlyArray = + export const affectsEmitOptionDeclarations: readonly CommandLineOption[] = optionDeclarations.filter(option => !!option.affectsEmit); /* @internal */ - export const moduleResolutionOptionDeclarations: ReadonlyArray = + export const moduleResolutionOptionDeclarations: readonly CommandLineOption[] = optionDeclarations.filter(option => !!option.affectsModuleResolution); /* @internal */ - export const sourceFileAffectingCompilerOptions: ReadonlyArray = optionDeclarations.filter(option => + export const sourceFileAffectingCompilerOptions: readonly CommandLineOption[] = optionDeclarations.filter(option => !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics); /* @internal */ @@ -978,7 +978,7 @@ namespace ts { } /*@internal*/ - export function createOptionNameMap(optionDeclarations: ReadonlyArray): OptionNameMap { + export function createOptionNameMap(optionDeclarations: readonly CommandLineOption[]): OptionNameMap { const optionNameMap = createMap(); const shortOptionNames = createMap(); forEach(optionDeclarations, option => { @@ -1036,7 +1036,7 @@ namespace ts { function parseCommandLineWorker( getOptionNameMap: () => OptionNameMap, [unknownOptionDiagnostic, optionTypeMismatchDiagnostic]: ParseCommandLineWorkerDiagnostics, - commandLine: ReadonlyArray, + commandLine: readonly string[], readFile?: (path: string) => string | undefined) { const options = {} as OptionsBase; const fileNames: string[] = []; @@ -1049,7 +1049,7 @@ namespace ts { errors }; - function parseStrings(args: ReadonlyArray) { + function parseStrings(args: readonly string[]) { let i = 0; while (i < args.length) { const s = args[i]; @@ -1146,7 +1146,7 @@ namespace ts { } } - export function parseCommandLine(commandLine: ReadonlyArray, readFile?: (path: string) => string | undefined): ParsedCommandLine { + export function parseCommandLine(commandLine: readonly string[], readFile?: (path: string) => string | undefined): ParsedCommandLine { return parseCommandLineWorker(getOptionNameMap, [ Diagnostics.Unknown_compiler_option_0, Diagnostics.Compiler_option_0_expects_an_argument @@ -1221,7 +1221,7 @@ namespace ts { } /* @internal */ - export function printHelp(optionsList: ReadonlyArray, syntaxPrefix = "") { + export function printHelp(optionsList: readonly CommandLineOption[], syntaxPrefix = "") { const output: string[] = []; // We want to align our "syntax" and "examples" commands to a certain margin. @@ -1430,7 +1430,7 @@ namespace ts { return text === undefined ? createCompilerDiagnostic(Diagnostics.The_specified_path_does_not_exist_Colon_0, fileName) : text; } - function commandLineOptionsToMap(options: ReadonlyArray) { + function commandLineOptionsToMap(options: readonly CommandLineOption[]) { return arrayToMap(options, option => option.name); } @@ -1747,10 +1747,10 @@ namespace ts { export interface TSConfig { compilerOptions: CompilerOptions; compileOnSave: boolean | undefined; - exclude?: ReadonlyArray; - files: ReadonlyArray | undefined; - include?: ReadonlyArray; - references: ReadonlyArray | undefined; + exclude?: readonly string[]; + files: readonly string[] | undefined; + include?: readonly string[]; + references: readonly ProjectReference[] | undefined; } /** @@ -1799,14 +1799,14 @@ namespace ts { return config; } - function filterSameAsDefaultInclude(specs: ReadonlyArray | undefined) { + function filterSameAsDefaultInclude(specs: readonly string[] | undefined) { if (!length(specs)) return undefined; if (length(specs) !== 1) return specs; if (specs![0] === "**/*") return undefined; return specs; } - function matchesSpecs(path: string, includeSpecs: ReadonlyArray | undefined, excludeSpecs: ReadonlyArray | undefined): (path: string) => boolean { + function matchesSpecs(path: string, includeSpecs: readonly string[] | undefined, excludeSpecs: readonly string[] | undefined): (path: string) => boolean { if (!includeSpecs) return _ => true; const patterns = getFileMatcherPatterns(path, excludeSpecs, includeSpecs, sys.useCaseSensitiveFileNames, sys.getCurrentDirectory()); const excludeRe = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, sys.useCaseSensitiveFileNames); @@ -1873,7 +1873,7 @@ namespace ts { } else { if (optionDefinition.type === "list") { - result.set(name, (value as ReadonlyArray).map(element => getNameOfCompilerOptionValue(element, customTypeMap)!)); // TODO: GH#18217 + result.set(name, (value as readonly (string | number)[]).map(element => getNameOfCompilerOptionValue(element, customTypeMap)!)); // TODO: GH#18217 } else { // There is a typeMap associated with this command-line option so use it to map value back to its name @@ -1892,7 +1892,7 @@ namespace ts { * @param fileNames array of filenames to be generated into tsconfig.json */ /* @internal */ - export function generateTSConfig(options: CompilerOptions, fileNames: ReadonlyArray, newLine: string): string { + export function generateTSConfig(options: CompilerOptions, fileNames: readonly string[], newLine: string): string { const compilerOptions = extend(options, defaultInitCompilerOptions); const compilerOptionsMap = serializeCompilerOptions(compilerOptions); return writeConfigurations(); @@ -2000,7 +2000,7 @@ namespace ts { * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ - export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray, extendedConfigCache?: Map): ParsedCommandLine { + export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: readonly FileExtensionInfo[], extendedConfigCache?: Map): ParsedCommandLine { return parseJsonConfigFileContentWorker(json, /*sourceFile*/ undefined, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache); } @@ -2011,7 +2011,7 @@ namespace ts { * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ - export function parseJsonSourceFileConfigFileContent(sourceFile: TsConfigSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray, extendedConfigCache?: Map): ParsedCommandLine { + export function parseJsonSourceFileConfigFileContent(sourceFile: TsConfigSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: readonly FileExtensionInfo[], extendedConfigCache?: Map): ParsedCommandLine { return parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache); } @@ -2049,7 +2049,7 @@ namespace ts { existingOptions: CompilerOptions = {}, configFileName?: string, resolutionStack: Path[] = [], - extraFileExtensions: ReadonlyArray = [], + extraFileExtensions: readonly FileExtensionInfo[] = [], extendedConfigCache?: Map ): ParsedCommandLine { Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined)); @@ -2075,10 +2075,10 @@ namespace ts { }; function getFileNames(): ExpandResult { - let filesSpecs: ReadonlyArray | undefined; + let filesSpecs: readonly string[] | undefined; if (hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { if (isArray(raw.files)) { - filesSpecs = >raw.files; + filesSpecs = raw.files; const hasReferences = hasProperty(raw, "references") && !isNullOrUndefined(raw.references); const hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; const hasExtends = hasProperty(raw, "extends"); @@ -2102,20 +2102,20 @@ namespace ts { } } - let includeSpecs: ReadonlyArray | undefined; + let includeSpecs: readonly string[] | undefined; if (hasProperty(raw, "include") && !isNullOrUndefined(raw.include)) { if (isArray(raw.include)) { - includeSpecs = >raw.include; + includeSpecs = raw.include; } else { createCompilerDiagnosticOnlyIfJson(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array"); } } - let excludeSpecs: ReadonlyArray | undefined; + let excludeSpecs: readonly string[] | undefined; if (hasProperty(raw, "exclude") && !isNullOrUndefined(raw.exclude)) { if (isArray(raw.exclude)) { - excludeSpecs = >raw.exclude; + excludeSpecs = raw.exclude; } else { createCompilerDiagnosticOnlyIfJson(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"); @@ -2503,7 +2503,7 @@ namespace ts { return options; } - function convertOptionsFromJson(optionDeclarations: ReadonlyArray, jsonOptions: any, basePath: string, + function convertOptionsFromJson(optionDeclarations: readonly CommandLineOption[], jsonOptions: any, basePath: string, defaultOptions: CompilerOptions | TypeAcquisition, diagnosticMessage: DiagnosticMessage, errors: Push) { if (!jsonOptions) { @@ -2576,7 +2576,7 @@ namespace ts { } } - function convertJsonOptionOfListType(option: CommandLineOptionOfListType, values: ReadonlyArray, basePath: string, errors: Push): any[] { + function convertJsonOptionOfListType(option: CommandLineOptionOfListType, values: readonly any[], basePath: string, errors: Push): any[] { return filter(map(values, v => convertJsonOption(option.element, v, basePath, errors)), v => !!v); } @@ -2653,18 +2653,18 @@ namespace ts { * @param errors An array for diagnostic reporting. */ function matchFileNames( - filesSpecs: ReadonlyArray | undefined, - includeSpecs: ReadonlyArray | undefined, - excludeSpecs: ReadonlyArray | undefined, + filesSpecs: readonly string[] | undefined, + includeSpecs: readonly string[] | undefined, + excludeSpecs: readonly string[] | undefined, basePath: string, options: CompilerOptions, host: ParseConfigHost, errors: Push, - extraFileExtensions: ReadonlyArray, + extraFileExtensions: readonly FileExtensionInfo[], jsonSourceFile: TsConfigSourceFile | undefined ): ExpandResult { basePath = normalizePath(basePath); - let validatedIncludeSpecs: ReadonlyArray | undefined, validatedExcludeSpecs: ReadonlyArray | undefined; + let validatedIncludeSpecs: readonly string[] | undefined, validatedExcludeSpecs: readonly string[] | undefined; // The exclude spec list is converted into a regular expression, which allows us to quickly // test whether a file or directory should be excluded before recursively traversing the @@ -2698,7 +2698,7 @@ namespace ts { * @param extraFileExtensions optionaly file extra file extension information from host */ /* @internal */ - export function getFileNamesFromConfigSpecs(spec: ConfigFileSpecs, basePath: string, options: CompilerOptions, host: ParseConfigHost, extraFileExtensions: ReadonlyArray = []): ExpandResult { + export function getFileNamesFromConfigSpecs(spec: ConfigFileSpecs, basePath: string, options: CompilerOptions, host: ParseConfigHost, extraFileExtensions: readonly FileExtensionInfo[] = []): ExpandResult { basePath = normalizePath(basePath); const keyMapper = host.useCaseSensitiveFileNames ? identity : toLowerCase; @@ -2733,7 +2733,7 @@ namespace ts { } } - let jsonOnlyIncludeRegexes: ReadonlyArray | undefined; + let jsonOnlyIncludeRegexes: readonly RegExp[] | undefined; if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { for (const file of host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined)) { if (fileExtensionIs(file, Extension.Json)) { @@ -2785,7 +2785,7 @@ namespace ts { }; } - function validateSpecs(specs: ReadonlyArray, errors: Push, allowTrailingRecursion: boolean, jsonSourceFile: TsConfigSourceFile | undefined, specKey: string): ReadonlyArray { + function validateSpecs(specs: readonly string[], errors: Push, allowTrailingRecursion: boolean, jsonSourceFile: TsConfigSourceFile | undefined, specKey: string): readonly string[] { return specs.filter(spec => { const diag = specToDiagnostic(spec, allowTrailingRecursion); if (diag !== undefined) { @@ -2814,7 +2814,7 @@ namespace ts { /** * Gets directories in a set of include patterns that should be watched for changes. */ - function getWildcardDirectories(include: ReadonlyArray | undefined, exclude: ReadonlyArray | undefined, path: string, useCaseSensitiveFileNames: boolean): MapLike { + function getWildcardDirectories(include: readonly string[] | undefined, exclude: readonly string[] | undefined, path: string, useCaseSensitiveFileNames: boolean): MapLike { // We watch a directory recursively if it contains a wildcard anywhere in a directory segment // of the pattern: // @@ -2888,7 +2888,7 @@ namespace ts { * @param extensionPriority The priority of the extension. * @param context The expansion context. */ - function hasFileWithHigherPriorityExtension(file: string, literalFiles: Map, wildcardFiles: Map, extensions: ReadonlyArray, keyMapper: (value: string) => string) { + function hasFileWithHigherPriorityExtension(file: string, literalFiles: Map, wildcardFiles: Map, extensions: readonly string[], keyMapper: (value: string) => string) { const extensionPriority = getExtensionPriority(file, extensions); const adjustedExtensionPriority = adjustExtensionPriority(extensionPriority, extensions); for (let i = ExtensionPriority.Highest; i < adjustedExtensionPriority; i++) { @@ -2910,7 +2910,7 @@ namespace ts { * @param extensionPriority The priority of the extension. * @param context The expansion context. */ - function removeWildcardFilesWithLowerPriorityExtension(file: string, wildcardFiles: Map, extensions: ReadonlyArray, keyMapper: (value: string) => string) { + function removeWildcardFilesWithLowerPriorityExtension(file: string, wildcardFiles: Map, extensions: readonly string[], keyMapper: (value: string) => string) { const extensionPriority = getExtensionPriority(file, extensions); const nextExtensionPriority = getNextLowestExtensionPriority(extensionPriority, extensions); for (let i = nextExtensionPriority; i < extensions.length; i++) { diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 4532ddb0504..1cfffa68b21 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -310,7 +310,7 @@ namespace ts { }; } - export function length(array: ReadonlyArray | undefined): number { + export function length(array: readonly any[] | undefined): number { return array ? array.length : 0; } @@ -319,7 +319,7 @@ namespace ts { * returns a truthy value, then returns that value. * If no such value is found, the callback is applied to each element of array and undefined is returned. */ - export function forEach(array: ReadonlyArray | undefined, callback: (element: T, index: number) => U | undefined): U | undefined { + export function forEach(array: readonly T[] | undefined, callback: (element: T, index: number) => U | undefined): U | undefined { if (array) { for (let i = 0; i < array.length; i++) { const result = callback(array[i], i); @@ -332,7 +332,7 @@ namespace ts { } /** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */ - export function firstDefined(array: ReadonlyArray | undefined, callback: (element: T, index: number) => U | undefined): U | undefined { + export function firstDefined(array: readonly T[] | undefined, callback: (element: T, index: number) => U | undefined): U | undefined { if (array === undefined) { return undefined; } @@ -359,7 +359,7 @@ namespace ts { } } - export function zipWith(arrayA: ReadonlyArray, arrayB: ReadonlyArray, callback: (a: T, b: U, index: number) => V): V[] { + export function zipWith(arrayA: readonly T[], arrayB: readonly U[], callback: (a: T, b: U, index: number) => V): V[] { const result: V[] = []; Debug.assertEqual(arrayA.length, arrayB.length); for (let i = 0; i < arrayA.length; i++) { @@ -368,7 +368,7 @@ namespace ts { return result; } - export function zipToIterator(arrayA: ReadonlyArray, arrayB: ReadonlyArray): Iterator<[T, U]> { + export function zipToIterator(arrayA: readonly T[], arrayB: readonly U[]): Iterator<[T, U]> { Debug.assertEqual(arrayA.length, arrayB.length); let i = 0; return { @@ -382,7 +382,7 @@ namespace ts { }; } - export function zipToMap(keys: ReadonlyArray, values: ReadonlyArray): Map { + export function zipToMap(keys: readonly string[], values: readonly T[]): Map { Debug.assert(keys.length === values.length); const map = createMap(); for (let i = 0; i < keys.length; ++i) { @@ -396,7 +396,7 @@ namespace ts { * returns a falsey value, then returns false. * If no such value is found, the callback is applied to each element of array and `true` is returned. */ - export function every(array: ReadonlyArray, callback: (element: T, index: number) => boolean): boolean { + export function every(array: readonly T[], callback: (element: T, index: number) => boolean): boolean { if (array) { for (let i = 0; i < array.length; i++) { if (!callback(array[i], i)) { @@ -409,9 +409,9 @@ namespace ts { } /** Works like Array.prototype.find, returning `undefined` if no element satisfying the predicate is found. */ - export function find(array: ReadonlyArray, predicate: (element: T, index: number) => element is U): U | undefined; - export function find(array: ReadonlyArray, predicate: (element: T, index: number) => boolean): T | undefined; - export function find(array: ReadonlyArray, predicate: (element: T, index: number) => boolean): T | undefined { + export function find(array: readonly T[], predicate: (element: T, index: number) => element is U): U | undefined; + export function find(array: readonly T[], predicate: (element: T, index: number) => boolean): T | undefined; + export function find(array: readonly T[], predicate: (element: T, index: number) => boolean): T | undefined { for (let i = 0; i < array.length; i++) { const value = array[i]; if (predicate(value, i)) { @@ -421,9 +421,9 @@ namespace ts { return undefined; } - export function findLast(array: ReadonlyArray, predicate: (element: T, index: number) => element is U): U | undefined; - export function findLast(array: ReadonlyArray, predicate: (element: T, index: number) => boolean): T | undefined; - export function findLast(array: ReadonlyArray, predicate: (element: T, index: number) => boolean): T | undefined { + export function findLast(array: readonly T[], predicate: (element: T, index: number) => element is U): U | undefined; + export function findLast(array: readonly T[], predicate: (element: T, index: number) => boolean): T | undefined; + export function findLast(array: readonly T[], predicate: (element: T, index: number) => boolean): T | undefined { for (let i = array.length - 1; i >= 0; i--) { const value = array[i]; if (predicate(value, i)) { @@ -434,7 +434,7 @@ namespace ts { } /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */ - export function findIndex(array: ReadonlyArray, predicate: (element: T, index: number) => boolean, startIndex?: number): number { + export function findIndex(array: readonly T[], predicate: (element: T, index: number) => boolean, startIndex?: number): number { for (let i = startIndex || 0; i < array.length; i++) { if (predicate(array[i], i)) { return i; @@ -443,7 +443,7 @@ namespace ts { return -1; } - export function findLastIndex(array: ReadonlyArray, predicate: (element: T, index: number) => boolean, startIndex?: number): number { + export function findLastIndex(array: readonly T[], predicate: (element: T, index: number) => boolean, startIndex?: number): number { for (let i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) { if (predicate(array[i], i)) { return i; @@ -456,7 +456,7 @@ namespace ts { * Returns the first truthy result of `callback`, or else fails. * This is like `forEach`, but never returns undefined. */ - export function findMap(array: ReadonlyArray, callback: (element: T, index: number) => U | undefined): U { + export function findMap(array: readonly T[], callback: (element: T, index: number) => U | undefined): U { for (let i = 0; i < array.length; i++) { const result = callback(array[i], i); if (result) { @@ -466,7 +466,7 @@ namespace ts { return Debug.fail(); } - export function contains(array: ReadonlyArray | undefined, value: T, equalityComparer: EqualityComparer = equateValues): boolean { + export function contains(array: readonly T[] | undefined, value: T, equalityComparer: EqualityComparer = equateValues): boolean { if (array) { for (const v of array) { if (equalityComparer(v, value)) { @@ -477,11 +477,11 @@ namespace ts { return false; } - export function arraysEqual(a: ReadonlyArray, b: ReadonlyArray, equalityComparer: EqualityComparer = equateValues): boolean { + export function arraysEqual(a: readonly T[], b: readonly T[], equalityComparer: EqualityComparer = equateValues): boolean { return a.length === b.length && a.every((x, i) => equalityComparer(x, b[i])); } - export function indexOfAnyCharCode(text: string, charCodes: ReadonlyArray, start?: number): number { + export function indexOfAnyCharCode(text: string, charCodes: readonly number[], start?: number): number { for (let i = start || 0; i < text.length; i++) { if (contains(charCodes, text.charCodeAt(i))) { return i; @@ -490,7 +490,7 @@ namespace ts { return -1; } - export function countWhere(array: ReadonlyArray, predicate: (x: T, i: number) => boolean): number { + export function countWhere(array: readonly T[], predicate: (x: T, i: number) => boolean): number { let count = 0; if (array) { for (let i = 0; i < array.length; i++) { @@ -509,13 +509,13 @@ namespace ts { */ export function filter(array: T[], f: (x: T) => x is U): U[]; export function filter(array: T[], f: (x: T) => boolean): T[]; - export function filter(array: ReadonlyArray, f: (x: T) => x is U): ReadonlyArray; - export function filter(array: ReadonlyArray, f: (x: T) => boolean): ReadonlyArray; + export function filter(array: readonly T[], f: (x: T) => x is U): readonly U[]; + export function filter(array: readonly T[], f: (x: T) => boolean): readonly T[]; export function filter(array: T[] | undefined, f: (x: T) => x is U): U[] | undefined; export function filter(array: T[] | undefined, f: (x: T) => boolean): T[] | undefined; - export function filter(array: ReadonlyArray | undefined, f: (x: T) => x is U): ReadonlyArray | undefined; - export function filter(array: ReadonlyArray | undefined, f: (x: T) => boolean): ReadonlyArray | undefined; - export function filter(array: ReadonlyArray | undefined, f: (x: T) => boolean): ReadonlyArray | undefined { + export function filter(array: readonly T[] | undefined, f: (x: T) => x is U): readonly U[] | undefined; + export function filter(array: readonly T[] | undefined, f: (x: T) => boolean): readonly T[] | undefined; + export function filter(array: readonly T[] | undefined, f: (x: T) => boolean): readonly T[] | undefined { if (array) { const len = array.length; let i = 0; @@ -551,9 +551,9 @@ namespace ts { array.length = 0; } - export function map(array: ReadonlyArray, f: (x: T, i: number) => U): U[]; - export function map(array: ReadonlyArray | undefined, f: (x: T, i: number) => U): U[] | undefined; - export function map(array: ReadonlyArray | undefined, f: (x: T, i: number) => U): U[] | undefined { + export function map(array: readonly T[], f: (x: T, i: number) => U): U[]; + export function map(array: readonly T[] | undefined, f: (x: T, i: number) => U): U[] | undefined; + export function map(array: readonly T[] | undefined, f: (x: T, i: number) => U): U[] | undefined { let result: U[] | undefined; if (array) { result = []; @@ -576,10 +576,10 @@ namespace ts { // Maps from T to T and avoids allocation if all elements map to themselves export function sameMap(array: T[], f: (x: T, i: number) => T): T[]; - export function sameMap(array: ReadonlyArray, f: (x: T, i: number) => T): ReadonlyArray; + export function sameMap(array: readonly T[], f: (x: T, i: number) => T): readonly T[]; export function sameMap(array: T[] | undefined, f: (x: T, i: number) => T): T[] | undefined; - export function sameMap(array: ReadonlyArray | undefined, f: (x: T, i: number) => T): ReadonlyArray | undefined; - export function sameMap(array: ReadonlyArray | undefined, f: (x: T, i: number) => T): ReadonlyArray | undefined { + export function sameMap(array: readonly T[] | undefined, f: (x: T, i: number) => T): readonly T[] | undefined; + export function sameMap(array: readonly T[] | undefined, f: (x: T, i: number) => T): readonly T[] | undefined { if (array) { for (let i = 0; i < array.length; i++) { const item = array[i]; @@ -602,7 +602,7 @@ namespace ts { * * @param array The array to flatten. */ - export function flatten(array: T[][] | ReadonlyArray | undefined>): T[] { + export function flatten(array: T[][] | readonly (T | readonly T[] | undefined)[]): T[] { const result = []; for (const v of array) { if (v) { @@ -623,7 +623,7 @@ namespace ts { * @param array The array to map. * @param mapfn The callback used to map the result into one or more values. */ - export function flatMap(array: ReadonlyArray | undefined, mapfn: (x: T, i: number) => U | ReadonlyArray | undefined): ReadonlyArray { + export function flatMap(array: readonly T[] | undefined, mapfn: (x: T, i: number) => U | readonly U[] | undefined): readonly U[] { let result: U[] | undefined; if (array) { for (let i = 0; i < array.length; i++) { @@ -641,7 +641,7 @@ namespace ts { return result || emptyArray; } - export function flatMapToMutable(array: ReadonlyArray | undefined, mapfn: (x: T, i: number) => U | ReadonlyArray | undefined): U[] { + export function flatMapToMutable(array: readonly T[] | undefined, mapfn: (x: T, i: number) => U | readonly U[] | undefined): U[] { const result: U[] = []; if (array) { for (let i = 0; i < array.length; i++) { @@ -659,7 +659,7 @@ namespace ts { return result; } - export function flatMapIterator(iter: Iterator, mapfn: (x: T) => ReadonlyArray | Iterator | undefined): Iterator { + export function flatMapIterator(iter: Iterator, mapfn: (x: T) => readonly U[] | Iterator | undefined): Iterator { const first = iter.next(); if (first.done) { return emptyIterator; @@ -694,8 +694,8 @@ namespace ts { * @param array The array to map. * @param mapfn The callback used to map the result into one or more values. */ - export function sameFlatMap(array: T[], mapfn: (x: T, i: number) => T | ReadonlyArray): T[]; - export function sameFlatMap(array: ReadonlyArray, mapfn: (x: T, i: number) => T | ReadonlyArray): ReadonlyArray; + export function sameFlatMap(array: T[], mapfn: (x: T, i: number) => T | readonly T[]): T[]; + export function sameFlatMap(array: readonly T[], mapfn: (x: T, i: number) => T | readonly T[]): readonly T[]; export function sameFlatMap(array: T[], mapfn: (x: T, i: number) => T | T[]): T[] { let result: T[] | undefined; if (array) { @@ -718,7 +718,7 @@ namespace ts { return result || array; } - export function mapAllOrFail(array: ReadonlyArray, mapFn: (x: T, i: number) => U | undefined): U[] | undefined { + export function mapAllOrFail(array: readonly T[], mapFn: (x: T, i: number) => U | undefined): U[] | undefined { const result: U[] = []; for (let i = 0; i < array.length; i++) { const mapped = mapFn(array[i], i); @@ -730,7 +730,7 @@ namespace ts { return result; } - export function mapDefined(array: ReadonlyArray | undefined, mapFn: (x: T, i: number) => U | undefined): U[] { + export function mapDefined(array: readonly T[] | undefined, mapFn: (x: T, i: number) => U | undefined): U[] { const result: U[] = []; if (array) { for (let i = 0; i < array.length; i++) { @@ -780,9 +780,9 @@ namespace ts { * @param keyfn A callback used to select the key for an element. * @param mapfn A callback used to map a contiguous chunk of values to a single value. */ - export function spanMap(array: ReadonlyArray, keyfn: (x: T, i: number) => K, mapfn: (chunk: T[], key: K, start: number, end: number) => U): U[]; - export function spanMap(array: ReadonlyArray | undefined, keyfn: (x: T, i: number) => K, mapfn: (chunk: T[], key: K, start: number, end: number) => U): U[] | undefined; - export function spanMap(array: ReadonlyArray | undefined, keyfn: (x: T, i: number) => K, mapfn: (chunk: T[], key: K, start: number, end: number) => U): U[] | undefined { + export function spanMap(array: readonly T[], keyfn: (x: T, i: number) => K, mapfn: (chunk: T[], key: K, start: number, end: number) => U): U[]; + export function spanMap(array: readonly T[] | undefined, keyfn: (x: T, i: number) => K, mapfn: (chunk: T[], key: K, start: number, end: number) => U): U[] | undefined; + export function spanMap(array: readonly T[] | undefined, keyfn: (x: T, i: number) => K, mapfn: (chunk: T[], key: K, start: number, end: number) => U): U[] | undefined { let result: U[] | undefined; if (array) { result = []; @@ -836,9 +836,9 @@ namespace ts { }); return result; } - export function some(array: ReadonlyArray | undefined): array is ReadonlyArray; - export function some(array: ReadonlyArray | undefined, predicate: (value: T) => boolean): boolean; - export function some(array: ReadonlyArray | undefined, predicate?: (value: T) => boolean): boolean { + export function some(array: readonly T[] | undefined): array is readonly T[]; + export function some(array: readonly T[] | undefined, predicate: (value: T) => boolean): boolean; + export function some(array: readonly T[] | undefined, predicate?: (value: T) => boolean): boolean { if (array) { if (predicate) { for (const v of array) { @@ -855,7 +855,7 @@ namespace ts { } /** Calls the callback with (start, afterEnd) index pairs for each range where 'pred' is true. */ - export function getRangesWhere(arr: ReadonlyArray, pred: (t: T) => boolean, cb: (start: number, afterEnd: number) => void): void { + export function getRangesWhere(arr: readonly T[], pred: (t: T) => boolean, cb: (start: number, afterEnd: number) => void): void { let start: number | undefined; for (let i = 0; i < arr.length; i++) { if (pred(arr[i])) { @@ -872,16 +872,16 @@ namespace ts { } export function concatenate(array1: T[], array2: T[]): T[]; - export function concatenate(array1: ReadonlyArray, array2: ReadonlyArray): ReadonlyArray; + export function concatenate(array1: readonly T[], array2: readonly T[]): readonly T[]; export function concatenate(array1: T[] | undefined, array2: T[] | undefined): T[]; - export function concatenate(array1: ReadonlyArray | undefined, array2: ReadonlyArray | undefined): ReadonlyArray; + export function concatenate(array1: readonly T[] | undefined, array2: readonly T[] | undefined): readonly T[]; export function concatenate(array1: T[], array2: T[]): T[] { if (!some(array2)) return array1; if (!some(array1)) return array2; return [...array1, ...array2]; } - function deduplicateRelational(array: ReadonlyArray, equalityComparer: EqualityComparer, comparer: Comparer) { + function deduplicateRelational(array: readonly T[], equalityComparer: EqualityComparer, comparer: Comparer) { // Perform a stable sort of the array. This ensures the first entry in a list of // duplicates remains the first entry in the result. const indices = array.map((_, i) => i); @@ -903,7 +903,7 @@ namespace ts { return deduplicated.map(i => array[i]); } - function deduplicateEquality(array: ReadonlyArray, equalityComparer: EqualityComparer) { + function deduplicateEquality(array: readonly T[], equalityComparer: EqualityComparer) { const result: T[] = []; for (const item of array) { pushIfUnique(result, item, equalityComparer); @@ -917,7 +917,7 @@ namespace ts { * @param comparer An optional `Comparer` used to sort entries before comparison, though the * result will remain in the original order in `array`. */ - export function deduplicate(array: ReadonlyArray, equalityComparer: EqualityComparer, comparer?: Comparer): T[] { + export function deduplicate(array: readonly T[], equalityComparer: EqualityComparer, comparer?: Comparer): T[] { return array.length === 0 ? [] : array.length === 1 ? array.slice() : comparer ? deduplicateRelational(array, equalityComparer, comparer) : @@ -966,13 +966,13 @@ namespace ts { } } - export function sortAndDeduplicate(array: ReadonlyArray): SortedReadonlyArray; - export function sortAndDeduplicate(array: ReadonlyArray, comparer: Comparer, equalityComparer?: EqualityComparer): SortedReadonlyArray; - export function sortAndDeduplicate(array: ReadonlyArray, comparer?: Comparer, equalityComparer?: EqualityComparer): SortedReadonlyArray { + export function sortAndDeduplicate(array: readonly string[]): SortedReadonlyArray; + export function sortAndDeduplicate(array: readonly T[], comparer: Comparer, equalityComparer?: EqualityComparer): SortedReadonlyArray; + export function sortAndDeduplicate(array: readonly T[], comparer?: Comparer, equalityComparer?: EqualityComparer): SortedReadonlyArray { return deduplicateSorted(sort(array, comparer), equalityComparer || comparer || compareStringsCaseSensitive as any as Comparer); } - export function arrayIsEqualTo(array1: ReadonlyArray | undefined, array2: ReadonlyArray | undefined, equalityComparer: (a: T, b: T, index: number) => boolean = equateValues): boolean { + export function arrayIsEqualTo(array1: readonly T[] | undefined, array2: readonly T[] | undefined, equalityComparer: (a: T, b: T, index: number) => boolean = equateValues): boolean { if (!array1 || !array2) { return array1 === array2; } @@ -994,10 +994,10 @@ namespace ts { * Compacts an array, removing any falsey elements. */ export function compact(array: (T | undefined | null | false | 0 | "")[]): T[]; - export function compact(array: ReadonlyArray): ReadonlyArray; + export function compact(array: readonly (T | undefined | null | false | 0 | "")[]): readonly T[]; // TSLint thinks these can be combined with the above - they cannot; they'd produce higher-priority inferences and prevent the falsey types from being stripped export function compact(array: T[]): T[]; - export function compact(array: ReadonlyArray): ReadonlyArray; + export function compact(array: readonly T[]): readonly T[]; export function compact(array: T[]): T[] { let result: T[] | undefined; if (array) { @@ -1059,7 +1059,7 @@ namespace ts { return result; } - export function sum, K extends string>(array: ReadonlyArray, prop: K): number { + export function sum, K extends string>(array: readonly T[], prop: K): number { let result = 0; for (const v of array) { result += v[prop]; @@ -1091,7 +1091,7 @@ namespace ts { * Gets the actual offset into an array for a relative offset. Negative offsets indicate a * position offset from the end of the array. */ - function toOffset(array: ReadonlyArray, offset: number) { + function toOffset(array: readonly any[], offset: number) { return offset < 0 ? array.length + offset : offset; } @@ -1105,9 +1105,9 @@ namespace ts { * @param start The offset in `from` at which to start copying values. * @param end The offset in `from` at which to stop copying values (non-inclusive). */ - export function addRange(to: T[], from: ReadonlyArray | undefined, start?: number, end?: number): T[]; - export function addRange(to: T[] | undefined, from: ReadonlyArray | undefined, start?: number, end?: number): T[] | undefined; - export function addRange(to: T[] | undefined, from: ReadonlyArray | undefined, start?: number, end?: number): T[] | undefined { + export function addRange(to: T[], from: readonly T[] | undefined, start?: number, end?: number): T[]; + export function addRange(to: T[] | undefined, from: readonly T[] | undefined, start?: number, end?: number): T[] | undefined; + export function addRange(to: T[] | undefined, from: readonly T[] | undefined, start?: number, end?: number): T[] | undefined { if (from === undefined || from.length === 0) return to; if (to === undefined) return from.slice(start, end); start = start === undefined ? 0 : toOffset(from, start); @@ -1146,7 +1146,7 @@ namespace ts { } } - function stableSortIndices(array: ReadonlyArray, indices: number[], comparer: Comparer) { + function stableSortIndices(array: readonly T[], indices: number[], comparer: Comparer) { // sort indices by value then position indices.sort((x, y) => comparer(array[x], array[y]) || compareValues(x, y)); } @@ -1154,11 +1154,11 @@ namespace ts { /** * Returns a new sorted array. */ - export function sort(array: ReadonlyArray, comparer?: Comparer): SortedReadonlyArray { + export function sort(array: readonly T[], comparer?: Comparer): SortedReadonlyArray { return (array.length === 0 ? array : array.slice().sort(comparer)) as SortedReadonlyArray; } - export function arrayIterator(array: ReadonlyArray): Iterator { + export function arrayIterator(array: readonly T[]): Iterator { let i = 0; return { next: () => { if (i === array.length) { @@ -1171,7 +1171,7 @@ namespace ts { }}; } - export function arrayReverseIterator(array: ReadonlyArray): Iterator { + export function arrayReverseIterator(array: readonly T[]): Iterator { let i = array.length; return { next: () => { @@ -1189,13 +1189,13 @@ namespace ts { /** * Stable sort of an array. Elements equal to each other maintain their relative position in the array. */ - export function stableSort(array: ReadonlyArray, comparer: Comparer): SortedReadonlyArray { + export function stableSort(array: readonly T[], comparer: Comparer): SortedReadonlyArray { const indices = array.map((_, i) => i); stableSortIndices(array, indices, comparer); return indices.map(i => array[i]) as SortedArray as SortedReadonlyArray; } - export function rangeEquals(array1: ReadonlyArray, array2: ReadonlyArray, pos: number, end: number) { + export function rangeEquals(array1: readonly T[], array2: readonly T[], pos: number, end: number) { while (pos < end) { if (array1[pos] !== array2[pos]) { return false; @@ -1209,7 +1209,7 @@ namespace ts { * Returns the element at a specific offset in an array if non-empty, `undefined` otherwise. * A negative offset indicates the element should be retrieved from the end of the array. */ - export function elementAt(array: ReadonlyArray | undefined, offset: number): T | undefined { + export function elementAt(array: readonly T[] | undefined, offset: number): T | undefined { if (array) { offset = toOffset(array, offset); if (offset < array.length) { @@ -1222,11 +1222,11 @@ namespace ts { /** * Returns the first element of an array if non-empty, `undefined` otherwise. */ - export function firstOrUndefined(array: ReadonlyArray): T | undefined { + export function firstOrUndefined(array: readonly T[]): T | undefined { return array.length === 0 ? undefined : array[0]; } - export function first(array: ReadonlyArray): T { + export function first(array: readonly T[]): T { Debug.assert(array.length !== 0); return array[0]; } @@ -1234,11 +1234,11 @@ namespace ts { /** * Returns the last element of an array if non-empty, `undefined` otherwise. */ - export function lastOrUndefined(array: ReadonlyArray): T | undefined { + export function lastOrUndefined(array: readonly T[]): T | undefined { return array.length === 0 ? undefined : array[array.length - 1]; } - export function last(array: ReadonlyArray): T { + export function last(array: readonly T[]): T { Debug.assert(array.length !== 0); return array[array.length - 1]; } @@ -1246,7 +1246,7 @@ namespace ts { /** * Returns the only element of an array if it contains only one element, `undefined` otherwise. */ - export function singleOrUndefined(array: ReadonlyArray | undefined): T | undefined { + export function singleOrUndefined(array: readonly T[] | undefined): T | undefined { return array && array.length === 1 ? array[0] : undefined; @@ -1257,16 +1257,16 @@ namespace ts { * array. */ export function singleOrMany(array: T[]): T | T[]; - export function singleOrMany(array: ReadonlyArray): T | ReadonlyArray; + export function singleOrMany(array: readonly T[]): T | readonly T[]; export function singleOrMany(array: T[] | undefined): T | T[] | undefined; - export function singleOrMany(array: ReadonlyArray | undefined): T | ReadonlyArray | undefined; - export function singleOrMany(array: ReadonlyArray | undefined): T | ReadonlyArray | undefined { + export function singleOrMany(array: readonly T[] | undefined): T | readonly T[] | undefined; + export function singleOrMany(array: readonly T[] | undefined): T | readonly T[] | undefined { return array && array.length === 1 ? array[0] : array; } - export function replaceElement(array: ReadonlyArray, index: number, value: T): T[] { + export function replaceElement(array: readonly T[], index: number, value: T): T[] { const result = array.slice(0); result[index] = value; return result; @@ -1283,7 +1283,7 @@ namespace ts { * @param keyComparer A callback used to compare two keys in a sorted array. * @param offset An offset into `array` at which to start the search. */ - export function binarySearch(array: ReadonlyArray, value: T, keySelector: (v: T) => U, keyComparer: Comparer, offset?: number): number { + export function binarySearch(array: readonly T[], value: T, keySelector: (v: T) => U, keyComparer: Comparer, offset?: number): number { return binarySearchKey(array, keySelector(value), keySelector, keyComparer, offset); } @@ -1297,7 +1297,7 @@ namespace ts { * @param keyComparer A callback used to compare two keys in a sorted array. * @param offset An offset into `array` at which to start the search. */ - export function binarySearchKey(array: ReadonlyArray, key: U, keySelector: (v: T) => U, keyComparer: Comparer, offset?: number): number { + export function binarySearchKey(array: readonly T[], key: U, keySelector: (v: T) => U, keyComparer: Comparer, offset?: number): number { if (!some(array)) { return -1; } @@ -1322,8 +1322,8 @@ namespace ts { return ~low; } - export function reduceLeft(array: ReadonlyArray | undefined, f: (memo: U, value: T, i: number) => U, initial: U, start?: number, count?: number): U; - export function reduceLeft(array: ReadonlyArray, f: (memo: T, value: T, i: number) => T): T | undefined; + export function reduceLeft(array: readonly T[] | undefined, f: (memo: U, value: T, i: number) => U, initial: U, start?: number, count?: number): U; + export function reduceLeft(array: readonly T[], f: (memo: T, value: T, i: number) => T): T | undefined; export function reduceLeft(array: T[], f: (memo: T, value: T, i: number) => T, initial?: T, start?: number, count?: number): T | undefined { if (array && array.length > 0) { const size = array.length; @@ -1465,9 +1465,9 @@ namespace ts { * the same key with the given 'makeKey' function, then the element with the higher * index in the array will be the one associated with the produced key. */ - export function arrayToMap(array: ReadonlyArray, makeKey: (value: T) => string | undefined): Map; - export function arrayToMap(array: ReadonlyArray, makeKey: (value: T) => string | undefined, makeValue: (value: T) => U): Map; - export function arrayToMap(array: ReadonlyArray, makeKey: (value: T) => string | undefined, makeValue: (value: T) => T | U = identity): Map { + export function arrayToMap(array: readonly T[], makeKey: (value: T) => string | undefined): Map; + export function arrayToMap(array: readonly T[], makeKey: (value: T) => string | undefined, makeValue: (value: T) => U): Map; + export function arrayToMap(array: readonly T[], makeKey: (value: T) => string | undefined, makeValue: (value: T) => T | U = identity): Map { const result = createMap(); for (const value of array) { const key = makeKey(value); @@ -1476,9 +1476,9 @@ namespace ts { return result; } - export function arrayToNumericMap(array: ReadonlyArray, makeKey: (value: T) => number): T[]; - export function arrayToNumericMap(array: ReadonlyArray, makeKey: (value: T) => number, makeValue: (value: T) => U): U[]; - export function arrayToNumericMap(array: ReadonlyArray, makeKey: (value: T) => number, makeValue: (value: T) => T | U = identity): (T | U)[] { + export function arrayToNumericMap(array: readonly T[], makeKey: (value: T) => number): T[]; + export function arrayToNumericMap(array: readonly T[], makeKey: (value: T) => number, makeValue: (value: T) => U): U[]; + export function arrayToNumericMap(array: readonly T[], makeKey: (value: T) => number, makeValue: (value: T) => T | U = identity): (T | U)[] { const result: (T | U)[] = []; for (const value of array) { result[makeKey(value)] = makeValue(value); @@ -1486,9 +1486,9 @@ namespace ts { return result; } - export function arrayToMultiMap(values: ReadonlyArray, makeKey: (value: T) => string): MultiMap; - export function arrayToMultiMap(values: ReadonlyArray, makeKey: (value: T) => string, makeValue: (value: T) => U): MultiMap; - export function arrayToMultiMap(values: ReadonlyArray, makeKey: (value: T) => string, makeValue: (value: T) => T | U = identity): MultiMap { + export function arrayToMultiMap(values: readonly T[], makeKey: (value: T) => string): MultiMap; + export function arrayToMultiMap(values: readonly T[], makeKey: (value: T) => string, makeValue: (value: T) => U): MultiMap; + export function arrayToMultiMap(values: readonly T[], makeKey: (value: T) => string, makeValue: (value: T) => T | U = identity): MultiMap { const result = createMultiMap(); for (const value of values) { result.add(makeKey(value), makeValue(value)); @@ -1496,7 +1496,7 @@ namespace ts { return result; } - export function group(values: ReadonlyArray, getGroupId: (value: T) => string): ReadonlyArray> { + export function group(values: readonly T[], getGroupId: (value: T) => string): readonly (readonly T[])[] { return arrayFrom(arrayToMultiMap(values, getGroupId).values()); } @@ -1582,12 +1582,12 @@ namespace ts { /** * Tests whether a value is an array. */ - export function isArray(value: any): value is ReadonlyArray<{}> { + export function isArray(value: any): value is readonly {}[] { return Array.isArray ? Array.isArray(value) : value instanceof Array; } export function toArray(value: T | T[]): T[]; - export function toArray(value: T | ReadonlyArray): ReadonlyArray; + export function toArray(value: T | readonly T[]): readonly T[]; export function toArray(value: T | T[]): T[] { return isArray(value) ? value : [value]; } @@ -2035,7 +2035,7 @@ namespace ts { return path.length > extension.length && endsWith(path, extension); } - export function fileExtensionIsOneOf(path: string, extensions: ReadonlyArray): boolean { + export function fileExtensionIsOneOf(path: string, extensions: readonly string[]): boolean { for (const extension of extensions) { if (fileExtensionIs(path, extension)) { return true; @@ -2123,7 +2123,7 @@ namespace ts { } /** Return the object corresponding to the best pattern to match `candidate`. */ - export function findBestPatternMatch(values: ReadonlyArray, getPattern: (value: T) => Pattern, candidate: string): T | undefined { + export function findBestPatternMatch(values: readonly T[], getPattern: (value: T) => Pattern, candidate: string): T | undefined { let matchedValue: T | undefined; // use length of prefix as betterness criteria let longestMatchPrefixLength = -1; @@ -2171,7 +2171,7 @@ namespace ts { return t === undefined ? undefined : [t]; } - export function enumerateInsertsAndDeletes(newItems: ReadonlyArray, oldItems: ReadonlyArray, comparer: (a: T, b: U) => Comparison, inserted: (newItem: T) => void, deleted: (oldItem: U) => void, unchanged?: (oldItem: U, newItem: T) => void) { + export function enumerateInsertsAndDeletes(newItems: readonly T[], oldItems: readonly U[], comparer: (a: T, b: U) => Comparison, inserted: (newItem: T) => void, deleted: (oldItem: U) => void, unchanged?: (oldItem: U, newItem: T) => void) { unchanged = unchanged || noop; let newIndex = 0; let oldIndex = 0; @@ -2211,13 +2211,13 @@ namespace ts { return result; } - export function cartesianProduct(arrays: ReadonlyArray[]) { + export function cartesianProduct(arrays: readonly T[][]) { const result: T[][] = []; cartesianProductWorker(arrays, result, /*outer*/ undefined, 0); return result; } - function cartesianProductWorker(arrays: ReadonlyArray>, result: (ReadonlyArray)[], outer: ReadonlyArray | undefined, index: number) { + function cartesianProductWorker(arrays: readonly (readonly T[])[], result: (readonly T[])[], outer: readonly T[] | undefined, index: number) { for (const element of arrays[index]) { let inner: T[]; if (outer) { diff --git a/src/compiler/debug.ts b/src/compiler/debug.ts index 95820f5999f..7e616535784 100644 --- a/src/compiler/debug.ts +++ b/src/compiler/debug.ts @@ -59,7 +59,7 @@ namespace ts { return value; } - export function assertEachDefined>(value: A, message?: string): A { + export function assertEachDefined(value: A, message?: string): A { for (const v of value) { assertDefined(v, message); } diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 0e166c04351..9eefa7a0dc4 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -19,7 +19,7 @@ namespace ts { */ export function forEachEmittedFile( host: EmitHost, action: (emitFileNames: EmitFileNames, sourceFileOrBundle: SourceFile | Bundle | undefined) => T, - sourceFilesOrTargetSourceFile?: ReadonlyArray | SourceFile, + sourceFilesOrTargetSourceFile?: readonly SourceFile[] | SourceFile, emitOnlyDtsFiles = false, onlyBuildInfo?: boolean, includeBuildInfo?: boolean) { @@ -170,7 +170,7 @@ namespace ts { } /*@internal*/ - export function getAllProjectOutputs(configFile: ParsedCommandLine, ignoreCase: boolean): ReadonlyArray { + export function getAllProjectOutputs(configFile: ParsedCommandLine, ignoreCase: boolean): readonly string[] { let outputs: string[] | undefined; const addOutput = (path: string | undefined) => path && (outputs || (outputs = [])).push(path); if (configFile.options.outFile || configFile.options.out) { @@ -623,7 +623,7 @@ namespace ts { /*@internal*/ /** File that isnt present resulting in error or output files */ - export type EmitUsingBuildInfoResult = string | ReadonlyArray; + export type EmitUsingBuildInfoResult = string | readonly OutputFile[]; /*@internal*/ export interface EmitUsingBuildInfoHost extends ModuleResolutionHost { @@ -633,7 +633,7 @@ namespace ts { getNewLine(): string; } - function createSourceFilesFromBundleBuildInfo(bundle: BundleBuildInfo, buildInfoDirectory: string, host: EmitUsingBuildInfoHost): ReadonlyArray { + function createSourceFilesFromBundleBuildInfo(bundle: BundleBuildInfo, buildInfoDirectory: string, host: EmitUsingBuildInfoHost): readonly SourceFile[] { const sourceFiles = bundle.sourceFiles.map(fileName => { const sourceFile = createNode(SyntaxKind.SourceFile, 0, 0) as SourceFile; sourceFile.fileName = getRelativePathFromDirectory( @@ -815,7 +815,7 @@ namespace ts { let containerPos = -1; let containerEnd = -1; let declarationListContainerEnd = -1; - let currentLineMap: ReadonlyArray | undefined; + let currentLineMap: readonly number[] | undefined; let detachedCommentsInfo: { nodePos: number, detachedCommentEndPos: number}[] | undefined; let hasWrittenComment = false; let commentsDisabled = !!printerOptions.removeComments; @@ -3446,7 +3446,7 @@ namespace ts { if (node.isDeclarationFile) emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); } - function emitTripleSlashDirectives(hasNoDefaultLib: boolean, files: ReadonlyArray, types: ReadonlyArray, libs: ReadonlyArray) { + function emitTripleSlashDirectives(hasNoDefaultLib: boolean, files: readonly FileReference[], types: readonly FileReference[], libs: readonly FileReference[]) { if (hasNoDefaultLib) { const pos = writer.getTextPos(); writeComment(`/// `); @@ -3513,7 +3513,7 @@ namespace ts { * Emits any prologue directives at the start of a Statement list, returning the * number of prologue directives written to the output. */ - function emitPrologueDirectives(statements: ReadonlyArray, sourceFile?: SourceFile, seenPrologueDirectives?: Map, recordBundleFileSection?: true): number { + function emitPrologueDirectives(statements: readonly Node[], sourceFile?: SourceFile, seenPrologueDirectives?: Map, recordBundleFileSection?: true): number { let needsToSetSourceFile = !!sourceFile; for (let i = 0; i < statements.length; i++) { const statement = statements[i]; @@ -3542,7 +3542,7 @@ namespace ts { return statements.length; } - function emitUnparsedPrologues(prologues: ReadonlyArray, seenPrologueDirectives: Map) { + function emitUnparsedPrologues(prologues: readonly UnparsedPrologue[], seenPrologueDirectives: Map) { for (const prologue of prologues) { if (!seenPrologueDirectives.has(prologue.data)) { writeLine(); diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index b542666e09d..4fafce4d314 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -16,11 +16,11 @@ namespace ts { } /* @internal */ export function createNodeArray(elements?: T[], hasTrailingComma?: boolean): MutableNodeArray; - export function createNodeArray(elements?: ReadonlyArray, hasTrailingComma?: boolean): NodeArray; + export function createNodeArray(elements?: readonly T[], hasTrailingComma?: boolean): NodeArray; /** * Make `elements` into a `NodeArray`. If `elements` is `undefined`, returns an empty `NodeArray`. */ - export function createNodeArray(elements?: ReadonlyArray, hasTrailingComma?: boolean): NodeArray { + export function createNodeArray(elements?: readonly T[], hasTrailingComma?: boolean): NodeArray { if (!elements || elements === emptyArray) { elements = []; } @@ -126,15 +126,15 @@ namespace ts { export function createIdentifier(text: string): Identifier; /* @internal */ - export function createIdentifier(text: string, typeArguments: ReadonlyArray | undefined): Identifier; - export function createIdentifier(text: string, typeArguments?: ReadonlyArray): Identifier { + export function createIdentifier(text: string, typeArguments: readonly (TypeNode | TypeParameterDeclaration)[] | undefined): Identifier; + export function createIdentifier(text: string, typeArguments?: readonly (TypeNode | TypeParameterDeclaration)[]): Identifier { const node = createSynthesizedNode(SyntaxKind.Identifier); node.escapedText = escapeLeadingUnderscores(text); node.originalKeywordKind = text ? stringToToken(text) : SyntaxKind.Unknown; node.autoGenerateFlags = GeneratedIdentifierFlags.None; node.autoGenerateId = 0; if (typeArguments) { - node.typeArguments = createNodeArray(typeArguments as ReadonlyArray); + node.typeArguments = createNodeArray(typeArguments as readonly TypeNode[]); } return node; } @@ -318,8 +318,8 @@ namespace ts { } export function createParameter( - decorators: ReadonlyArray | undefined, - modifiers: ReadonlyArray | undefined, + decorators: readonly Decorator[] | undefined, + modifiers: readonly Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, @@ -338,8 +338,8 @@ namespace ts { export function updateParameter( node: ParameterDeclaration, - decorators: ReadonlyArray | undefined, - modifiers: ReadonlyArray | undefined, + decorators: readonly Decorator[] | undefined, + modifiers: readonly Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, @@ -372,7 +372,7 @@ namespace ts { // Type Elements export function createPropertySignature( - modifiers: ReadonlyArray | undefined, + modifiers: readonly Modifier[] | undefined, name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, @@ -388,7 +388,7 @@ namespace ts { export function updatePropertySignature( node: PropertySignature, - modifiers: ReadonlyArray | undefined, + modifiers: readonly Modifier[] | undefined, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, @@ -403,8 +403,8 @@ namespace ts { } export function createProperty( - decorators: ReadonlyArray | undefined, - modifiers: ReadonlyArray | undefined, + decorators: readonly Decorator[] | undefined, + modifiers: readonly Modifier[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, @@ -422,8 +422,8 @@ namespace ts { export function updateProperty( node: PropertyDeclaration, - decorators: ReadonlyArray | undefined, - modifiers: ReadonlyArray | undefined, + decorators: readonly Decorator[] | undefined, + modifiers: readonly Modifier[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, @@ -440,8 +440,8 @@ namespace ts { } export function createMethodSignature( - typeParameters: ReadonlyArray | undefined, - parameters: ReadonlyArray, + typeParameters: readonly TypeParameterDeclaration[] | undefined, + parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined) { @@ -462,13 +462,13 @@ namespace ts { } export function createMethod( - decorators: ReadonlyArray | undefined, - modifiers: ReadonlyArray | undefined, + decorators: readonly Decorator[] | undefined, + modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, - typeParameters: ReadonlyArray | undefined, - parameters: ReadonlyArray, + typeParameters: readonly TypeParameterDeclaration[] | undefined, + parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) { const node = createSynthesizedNode(SyntaxKind.MethodDeclaration); @@ -486,13 +486,13 @@ namespace ts { export function updateMethod( node: MethodDeclaration, - decorators: ReadonlyArray | undefined, - modifiers: ReadonlyArray | undefined, + decorators: readonly Decorator[] | undefined, + modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, - typeParameters: ReadonlyArray | undefined, - parameters: ReadonlyArray, + typeParameters: readonly TypeParameterDeclaration[] | undefined, + parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) { return node.decorators !== decorators @@ -508,7 +508,7 @@ namespace ts { : node; } - export function createConstructor(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, parameters: ReadonlyArray, body: Block | undefined) { + export function createConstructor(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined) { const node = createSynthesizedNode(SyntaxKind.Constructor); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -521,9 +521,9 @@ namespace ts { export function updateConstructor( node: ConstructorDeclaration, - decorators: ReadonlyArray | undefined, - modifiers: ReadonlyArray | undefined, - parameters: ReadonlyArray, + decorators: readonly Decorator[] | undefined, + modifiers: readonly Modifier[] | undefined, + parameters: readonly ParameterDeclaration[], body: Block | undefined) { return node.decorators !== decorators || node.modifiers !== modifiers @@ -534,10 +534,10 @@ namespace ts { } export function createGetAccessor( - decorators: ReadonlyArray | undefined, - modifiers: ReadonlyArray | undefined, + decorators: readonly Decorator[] | undefined, + modifiers: readonly Modifier[] | undefined, name: string | PropertyName, - parameters: ReadonlyArray, + parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) { const node = createSynthesizedNode(SyntaxKind.GetAccessor); @@ -553,10 +553,10 @@ namespace ts { export function updateGetAccessor( node: GetAccessorDeclaration, - decorators: ReadonlyArray | undefined, - modifiers: ReadonlyArray | undefined, + decorators: readonly Decorator[] | undefined, + modifiers: readonly Modifier[] | undefined, name: PropertyName, - parameters: ReadonlyArray, + parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) { return node.decorators !== decorators @@ -570,10 +570,10 @@ namespace ts { } export function createSetAccessor( - decorators: ReadonlyArray | undefined, - modifiers: ReadonlyArray | undefined, + decorators: readonly Decorator[] | undefined, + modifiers: readonly Modifier[] | undefined, name: string | PropertyName, - parameters: ReadonlyArray, + parameters: readonly ParameterDeclaration[], body: Block | undefined) { const node = createSynthesizedNode(SyntaxKind.SetAccessor); node.decorators = asNodeArray(decorators); @@ -587,10 +587,10 @@ namespace ts { export function updateSetAccessor( node: SetAccessorDeclaration, - decorators: ReadonlyArray | undefined, - modifiers: ReadonlyArray | undefined, + decorators: readonly Decorator[] | undefined, + modifiers: readonly Modifier[] | undefined, name: PropertyName, - parameters: ReadonlyArray, + parameters: readonly ParameterDeclaration[], body: Block | undefined) { return node.decorators !== decorators || node.modifiers !== modifiers @@ -601,7 +601,7 @@ namespace ts { : node; } - export function createCallSignature(typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined) { + export function createCallSignature(typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined) { return createSignatureDeclaration(SyntaxKind.CallSignature, typeParameters, parameters, type) as CallSignatureDeclaration; } @@ -609,7 +609,7 @@ namespace ts { return updateSignatureDeclaration(node, typeParameters, parameters, type); } - export function createConstructSignature(typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined) { + export function createConstructSignature(typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined) { return createSignatureDeclaration(SyntaxKind.ConstructSignature, typeParameters, parameters, type) as ConstructSignatureDeclaration; } @@ -618,9 +618,9 @@ namespace ts { } export function createIndexSignature( - decorators: ReadonlyArray | undefined, - modifiers: ReadonlyArray | undefined, - parameters: ReadonlyArray, + decorators: readonly Decorator[] | undefined, + modifiers: readonly Modifier[] | undefined, + parameters: readonly ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration { const node = createSynthesizedNode(SyntaxKind.IndexSignature) as IndexSignatureDeclaration; node.decorators = asNodeArray(decorators); @@ -632,9 +632,9 @@ namespace ts { export function updateIndexSignature( node: IndexSignatureDeclaration, - decorators: ReadonlyArray | undefined, - modifiers: ReadonlyArray | undefined, - parameters: ReadonlyArray, + decorators: readonly Decorator[] | undefined, + modifiers: readonly Modifier[] | undefined, + parameters: readonly ParameterDeclaration[], type: TypeNode) { return node.parameters !== parameters || node.type !== type @@ -645,7 +645,7 @@ namespace ts { } /* @internal */ - export function createSignatureDeclaration(kind: SyntaxKind, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, typeArguments?: ReadonlyArray | undefined) { + export function createSignatureDeclaration(kind: SyntaxKind, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, typeArguments?: readonly TypeNode[] | undefined) { const node = createSynthesizedNode(kind) as SignatureDeclaration; node.typeParameters = asNodeArray(typeParameters); node.parameters = asNodeArray(parameters); @@ -682,7 +682,7 @@ namespace ts { : node; } - export function createTypeReferenceNode(typeName: string | EntityName, typeArguments: ReadonlyArray | undefined) { + export function createTypeReferenceNode(typeName: string | EntityName, typeArguments: readonly TypeNode[] | undefined) { const node = createSynthesizedNode(SyntaxKind.TypeReference) as TypeReferenceNode; node.typeName = asName(typeName); node.typeArguments = typeArguments && parenthesizeTypeParameters(typeArguments); @@ -696,7 +696,7 @@ namespace ts { : node; } - export function createFunctionTypeNode(typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined) { + export function createFunctionTypeNode(typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined) { return createSignatureDeclaration(SyntaxKind.FunctionType, typeParameters, parameters, type) as FunctionTypeNode; } @@ -704,7 +704,7 @@ namespace ts { return updateSignatureDeclaration(node, typeParameters, parameters, type); } - export function createConstructorTypeNode(typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined) { + export function createConstructorTypeNode(typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined) { return createSignatureDeclaration(SyntaxKind.ConstructorType, typeParameters, parameters, type) as ConstructorTypeNode; } @@ -724,7 +724,7 @@ namespace ts { : node; } - export function createTypeLiteralNode(members: ReadonlyArray | undefined) { + export function createTypeLiteralNode(members: readonly TypeElement[] | undefined) { const node = createSynthesizedNode(SyntaxKind.TypeLiteral) as TypeLiteralNode; node.members = createNodeArray(members); return node; @@ -748,13 +748,13 @@ namespace ts { : node; } - export function createTupleTypeNode(elementTypes: ReadonlyArray) { + export function createTupleTypeNode(elementTypes: readonly TypeNode[]) { const node = createSynthesizedNode(SyntaxKind.TupleType) as TupleTypeNode; node.elementTypes = createNodeArray(elementTypes); return node; } - export function updateTupleTypeNode(node: TupleTypeNode, elementTypes: ReadonlyArray) { + export function updateTupleTypeNode(node: TupleTypeNode, elementTypes: readonly TypeNode[]) { return node.elementTypes !== elementTypes ? updateNode(createTupleTypeNode(elementTypes), node) : node; @@ -784,7 +784,7 @@ namespace ts { : node; } - export function createUnionTypeNode(types: ReadonlyArray): UnionTypeNode { + export function createUnionTypeNode(types: readonly TypeNode[]): UnionTypeNode { return createUnionOrIntersectionTypeNode(SyntaxKind.UnionType, types); } @@ -792,7 +792,7 @@ namespace ts { return updateUnionOrIntersectionTypeNode(node, types); } - export function createIntersectionTypeNode(types: ReadonlyArray): IntersectionTypeNode { + export function createIntersectionTypeNode(types: readonly TypeNode[]): IntersectionTypeNode { return createUnionOrIntersectionTypeNode(SyntaxKind.IntersectionType, types); } @@ -800,7 +800,7 @@ namespace ts { return updateUnionOrIntersectionTypeNode(node, types); } - export function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: ReadonlyArray) { + export function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: readonly TypeNode[]) { const node = createSynthesizedNode(kind) as UnionTypeNode | IntersectionTypeNode; node.types = parenthesizeElementTypeMembers(types); return node; @@ -842,7 +842,7 @@ namespace ts { : node; } - export function createImportTypeNode(argument: TypeNode, qualifier?: EntityName, typeArguments?: ReadonlyArray, isTypeOf?: boolean) { + export function createImportTypeNode(argument: TypeNode, qualifier?: EntityName, typeArguments?: readonly TypeNode[], isTypeOf?: boolean) { const node = createSynthesizedNode(SyntaxKind.ImportType); node.argument = argument; node.qualifier = qualifier; @@ -851,7 +851,7 @@ namespace ts { return node; } - export function updateImportTypeNode(node: ImportTypeNode, argument: TypeNode, qualifier?: EntityName, typeArguments?: ReadonlyArray, isTypeOf?: boolean) { + export function updateImportTypeNode(node: ImportTypeNode, argument: TypeNode, qualifier?: EntityName, typeArguments?: readonly TypeNode[], isTypeOf?: boolean) { return node.argument !== argument || node.qualifier !== qualifier || node.typeArguments !== typeArguments @@ -935,25 +935,25 @@ namespace ts { // Binding Patterns - export function createObjectBindingPattern(elements: ReadonlyArray) { + export function createObjectBindingPattern(elements: readonly BindingElement[]) { const node = createSynthesizedNode(SyntaxKind.ObjectBindingPattern); node.elements = createNodeArray(elements); return node; } - export function updateObjectBindingPattern(node: ObjectBindingPattern, elements: ReadonlyArray) { + export function updateObjectBindingPattern(node: ObjectBindingPattern, elements: readonly BindingElement[]) { return node.elements !== elements ? updateNode(createObjectBindingPattern(elements), node) : node; } - export function createArrayBindingPattern(elements: ReadonlyArray) { + export function createArrayBindingPattern(elements: readonly ArrayBindingElement[]) { const node = createSynthesizedNode(SyntaxKind.ArrayBindingPattern); node.elements = createNodeArray(elements); return node; } - export function updateArrayBindingPattern(node: ArrayBindingPattern, elements: ReadonlyArray) { + export function updateArrayBindingPattern(node: ArrayBindingPattern, elements: readonly ArrayBindingElement[]) { return node.elements !== elements ? updateNode(createArrayBindingPattern(elements), node) : node; @@ -979,27 +979,27 @@ namespace ts { // Expression - export function createArrayLiteral(elements?: ReadonlyArray, multiLine?: boolean) { + export function createArrayLiteral(elements?: readonly Expression[], multiLine?: boolean) { const node = createSynthesizedNode(SyntaxKind.ArrayLiteralExpression); node.elements = parenthesizeListElements(createNodeArray(elements)); if (multiLine) node.multiLine = true; return node; } - export function updateArrayLiteral(node: ArrayLiteralExpression, elements: ReadonlyArray) { + export function updateArrayLiteral(node: ArrayLiteralExpression, elements: readonly Expression[]) { return node.elements !== elements ? updateNode(createArrayLiteral(elements, node.multiLine), node) : node; } - export function createObjectLiteral(properties?: ReadonlyArray, multiLine?: boolean) { + export function createObjectLiteral(properties?: readonly ObjectLiteralElementLike[], multiLine?: boolean) { const node = createSynthesizedNode(SyntaxKind.ObjectLiteralExpression); node.properties = createNodeArray(properties); if (multiLine) node.multiLine = true; return node; } - export function updateObjectLiteral(node: ObjectLiteralExpression, properties: ReadonlyArray) { + export function updateObjectLiteral(node: ObjectLiteralExpression, properties: readonly ObjectLiteralElementLike[]) { return node.properties !== properties ? updateNode(createObjectLiteral(properties, node.multiLine), node) : node; @@ -1036,7 +1036,7 @@ namespace ts { : node; } - export function createCall(expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray | undefined) { + export function createCall(expression: Expression, typeArguments: readonly TypeNode[] | undefined, argumentsArray: readonly Expression[] | undefined) { const node = createSynthesizedNode(SyntaxKind.CallExpression); node.expression = parenthesizeForAccess(expression); node.typeArguments = asNodeArray(typeArguments); @@ -1044,7 +1044,7 @@ namespace ts { return node; } - export function updateCall(node: CallExpression, expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray) { + export function updateCall(node: CallExpression, expression: Expression, typeArguments: readonly TypeNode[] | undefined, argumentsArray: readonly Expression[]) { return node.expression !== expression || node.typeArguments !== typeArguments || node.arguments !== argumentsArray @@ -1052,7 +1052,7 @@ namespace ts { : node; } - export function createNew(expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray | undefined) { + export function createNew(expression: Expression, typeArguments: readonly TypeNode[] | undefined, argumentsArray: readonly Expression[] | undefined) { const node = createSynthesizedNode(SyntaxKind.NewExpression); node.expression = parenthesizeForNew(expression); node.typeArguments = asNodeArray(typeArguments); @@ -1060,7 +1060,7 @@ namespace ts { return node; } - export function updateNew(node: NewExpression, expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray | undefined) { + export function updateNew(node: NewExpression, expression: Expression, typeArguments: readonly TypeNode[] | undefined, argumentsArray: readonly Expression[] | undefined) { return node.expression !== expression || node.typeArguments !== typeArguments || node.arguments !== argumentsArray @@ -1069,14 +1069,14 @@ namespace ts { } /** @deprecated */ export function createTaggedTemplate(tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; - export function createTaggedTemplate(tag: Expression, typeArguments: ReadonlyArray | undefined, template: TemplateLiteral): TaggedTemplateExpression; + export function createTaggedTemplate(tag: Expression, typeArguments: readonly TypeNode[] | undefined, template: TemplateLiteral): TaggedTemplateExpression; /** @internal */ - export function createTaggedTemplate(tag: Expression, typeArgumentsOrTemplate: ReadonlyArray | TemplateLiteral | undefined, template?: TemplateLiteral): TaggedTemplateExpression; - export function createTaggedTemplate(tag: Expression, typeArgumentsOrTemplate: ReadonlyArray | TemplateLiteral | undefined, template?: TemplateLiteral) { + export function createTaggedTemplate(tag: Expression, typeArgumentsOrTemplate: readonly TypeNode[] | TemplateLiteral | undefined, template?: TemplateLiteral): TaggedTemplateExpression; + export function createTaggedTemplate(tag: Expression, typeArgumentsOrTemplate: readonly TypeNode[] | TemplateLiteral | undefined, template?: TemplateLiteral) { const node = createSynthesizedNode(SyntaxKind.TaggedTemplateExpression); node.tag = parenthesizeForAccess(tag); if (template) { - node.typeArguments = asNodeArray(typeArgumentsOrTemplate as ReadonlyArray); + node.typeArguments = asNodeArray(typeArgumentsOrTemplate as readonly TypeNode[]); node.template = template; } else { @@ -1087,8 +1087,8 @@ namespace ts { } /** @deprecated */ export function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; - export function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, typeArguments: ReadonlyArray | undefined, template: TemplateLiteral): TaggedTemplateExpression; - export function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, typeArgumentsOrTemplate: ReadonlyArray | TemplateLiteral | undefined, template?: TemplateLiteral) { + export function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, typeArguments: readonly TypeNode[] | undefined, template: TemplateLiteral): TaggedTemplateExpression; + export function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, typeArgumentsOrTemplate: readonly TypeNode[] | TemplateLiteral | undefined, template?: TemplateLiteral) { return node.tag !== tag || (template ? node.typeArguments !== typeArgumentsOrTemplate || node.template !== template @@ -1124,11 +1124,11 @@ namespace ts { } export function createFunctionExpression( - modifiers: ReadonlyArray | undefined, + modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, - typeParameters: ReadonlyArray | undefined, - parameters: ReadonlyArray | undefined, + typeParameters: readonly TypeParameterDeclaration[] | undefined, + parameters: readonly ParameterDeclaration[] | undefined, type: TypeNode | undefined, body: Block) { const node = createSynthesizedNode(SyntaxKind.FunctionExpression); @@ -1144,11 +1144,11 @@ namespace ts { export function updateFunctionExpression( node: FunctionExpression, - modifiers: ReadonlyArray | undefined, + modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, - typeParameters: ReadonlyArray | undefined, - parameters: ReadonlyArray, + typeParameters: readonly TypeParameterDeclaration[] | undefined, + parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block) { return node.name !== name @@ -1163,9 +1163,9 @@ namespace ts { } export function createArrowFunction( - modifiers: ReadonlyArray | undefined, - typeParameters: ReadonlyArray | undefined, - parameters: ReadonlyArray, + modifiers: readonly Modifier[] | undefined, + typeParameters: readonly TypeParameterDeclaration[] | undefined, + parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, equalsGreaterThanToken: EqualsGreaterThanToken | undefined, body: ConciseBody) { @@ -1180,9 +1180,9 @@ namespace ts { } export function updateArrowFunction( node: ArrowFunction, - modifiers: ReadonlyArray | undefined, - typeParameters: ReadonlyArray | undefined, - parameters: ReadonlyArray, + modifiers: readonly Modifier[] | undefined, + typeParameters: readonly TypeParameterDeclaration[] | undefined, + parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, equalsGreaterThanToken: Token, body: ConciseBody @@ -1316,14 +1316,14 @@ namespace ts { : node; } - export function createTemplateExpression(head: TemplateHead, templateSpans: ReadonlyArray) { + export function createTemplateExpression(head: TemplateHead, templateSpans: readonly TemplateSpan[]) { const node = createSynthesizedNode(SyntaxKind.TemplateExpression); node.head = head; node.templateSpans = createNodeArray(templateSpans); return node; } - export function updateTemplateExpression(node: TemplateExpression, head: TemplateHead, templateSpans: ReadonlyArray) { + export function updateTemplateExpression(node: TemplateExpression, head: TemplateHead, templateSpans: readonly TemplateSpan[]) { return node.head !== head || node.templateSpans !== templateSpans ? updateNode(createTemplateExpression(head, templateSpans), node) @@ -1383,11 +1383,11 @@ namespace ts { } export function createClassExpression( - modifiers: ReadonlyArray | undefined, + modifiers: readonly Modifier[] | undefined, name: string | Identifier | undefined, - typeParameters: ReadonlyArray | undefined, - heritageClauses: ReadonlyArray | undefined, - members: ReadonlyArray) { + typeParameters: readonly TypeParameterDeclaration[] | undefined, + heritageClauses: readonly HeritageClause[] | undefined, + members: readonly ClassElement[]) { const node = createSynthesizedNode(SyntaxKind.ClassExpression); node.decorators = undefined; node.modifiers = asNodeArray(modifiers); @@ -1400,11 +1400,11 @@ namespace ts { export function updateClassExpression( node: ClassExpression, - modifiers: ReadonlyArray | undefined, + modifiers: readonly Modifier[] | undefined, name: Identifier | undefined, - typeParameters: ReadonlyArray | undefined, - heritageClauses: ReadonlyArray | undefined, - members: ReadonlyArray) { + typeParameters: readonly TypeParameterDeclaration[] | undefined, + heritageClauses: readonly HeritageClause[] | undefined, + members: readonly ClassElement[]) { return node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters @@ -1418,14 +1418,14 @@ namespace ts { return createSynthesizedNode(SyntaxKind.OmittedExpression); } - export function createExpressionWithTypeArguments(typeArguments: ReadonlyArray | undefined, expression: Expression) { + export function createExpressionWithTypeArguments(typeArguments: readonly TypeNode[] | undefined, expression: Expression) { const node = createSynthesizedNode(SyntaxKind.ExpressionWithTypeArguments); node.expression = parenthesizeForAccess(expression); node.typeArguments = asNodeArray(typeArguments); return node; } - export function updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, typeArguments: ReadonlyArray | undefined, expression: Expression) { + export function updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, typeArguments: readonly TypeNode[] | undefined, expression: Expression) { return node.typeArguments !== typeArguments || node.expression !== expression ? updateNode(createExpressionWithTypeArguments(typeArguments, expression), node) @@ -1493,20 +1493,20 @@ namespace ts { // Element - export function createBlock(statements: ReadonlyArray, multiLine?: boolean): Block { + export function createBlock(statements: readonly Statement[], multiLine?: boolean): Block { const block = createSynthesizedNode(SyntaxKind.Block); block.statements = createNodeArray(statements); if (multiLine) block.multiLine = multiLine; return block; } - export function updateBlock(node: Block, statements: ReadonlyArray) { + export function updateBlock(node: Block, statements: readonly Statement[]) { return node.statements !== statements ? updateNode(createBlock(statements, node.multiLine), node) : node; } - export function createVariableStatement(modifiers: ReadonlyArray | undefined, declarationList: VariableDeclarationList | ReadonlyArray) { + export function createVariableStatement(modifiers: readonly Modifier[] | undefined, declarationList: VariableDeclarationList | readonly VariableDeclaration[]) { const node = createSynthesizedNode(SyntaxKind.VariableStatement); node.decorators = undefined; node.modifiers = asNodeArray(modifiers); @@ -1514,7 +1514,7 @@ namespace ts { return node; } - export function updateVariableStatement(node: VariableStatement, modifiers: ReadonlyArray | undefined, declarationList: VariableDeclarationList) { + export function updateVariableStatement(node: VariableStatement, modifiers: readonly Modifier[] | undefined, declarationList: VariableDeclarationList) { return node.modifiers !== modifiers || node.declarationList !== declarationList ? updateNode(createVariableStatement(modifiers, declarationList), node) @@ -1764,26 +1764,26 @@ namespace ts { : node; } - export function createVariableDeclarationList(declarations: ReadonlyArray, flags = NodeFlags.None) { + export function createVariableDeclarationList(declarations: readonly VariableDeclaration[], flags = NodeFlags.None) { const node = createSynthesizedNode(SyntaxKind.VariableDeclarationList); node.flags |= flags & NodeFlags.BlockScoped; node.declarations = createNodeArray(declarations); return node; } - export function updateVariableDeclarationList(node: VariableDeclarationList, declarations: ReadonlyArray) { + export function updateVariableDeclarationList(node: VariableDeclarationList, declarations: readonly VariableDeclaration[]) { return node.declarations !== declarations ? updateNode(createVariableDeclarationList(declarations, node.flags), node) : node; } export function createFunctionDeclaration( - decorators: ReadonlyArray | undefined, - modifiers: ReadonlyArray | undefined, + decorators: readonly Decorator[] | undefined, + modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, - typeParameters: ReadonlyArray | undefined, - parameters: ReadonlyArray, + typeParameters: readonly TypeParameterDeclaration[] | undefined, + parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) { const node = createSynthesizedNode(SyntaxKind.FunctionDeclaration); @@ -1800,12 +1800,12 @@ namespace ts { export function updateFunctionDeclaration( node: FunctionDeclaration, - decorators: ReadonlyArray | undefined, - modifiers: ReadonlyArray | undefined, + decorators: readonly Decorator[] | undefined, + modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, - typeParameters: ReadonlyArray | undefined, - parameters: ReadonlyArray, + typeParameters: readonly TypeParameterDeclaration[] | undefined, + parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) { return node.decorators !== decorators @@ -1821,12 +1821,12 @@ namespace ts { } export function createClassDeclaration( - decorators: ReadonlyArray | undefined, - modifiers: ReadonlyArray | undefined, + decorators: readonly Decorator[] | undefined, + modifiers: readonly Modifier[] | undefined, name: string | Identifier | undefined, - typeParameters: ReadonlyArray | undefined, - heritageClauses: ReadonlyArray | undefined, - members: ReadonlyArray) { + typeParameters: readonly TypeParameterDeclaration[] | undefined, + heritageClauses: readonly HeritageClause[] | undefined, + members: readonly ClassElement[]) { const node = createSynthesizedNode(SyntaxKind.ClassDeclaration); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -1839,12 +1839,12 @@ namespace ts { export function updateClassDeclaration( node: ClassDeclaration, - decorators: ReadonlyArray | undefined, - modifiers: ReadonlyArray | undefined, + decorators: readonly Decorator[] | undefined, + modifiers: readonly Modifier[] | undefined, name: Identifier | undefined, - typeParameters: ReadonlyArray | undefined, - heritageClauses: ReadonlyArray | undefined, - members: ReadonlyArray) { + typeParameters: readonly TypeParameterDeclaration[] | undefined, + heritageClauses: readonly HeritageClause[] | undefined, + members: readonly ClassElement[]) { return node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name @@ -1856,12 +1856,12 @@ namespace ts { } export function createInterfaceDeclaration( - decorators: ReadonlyArray | undefined, - modifiers: ReadonlyArray | undefined, + decorators: readonly Decorator[] | undefined, + modifiers: readonly Modifier[] | undefined, name: string | Identifier, - typeParameters: ReadonlyArray | undefined, - heritageClauses: ReadonlyArray | undefined, - members: ReadonlyArray) { + typeParameters: readonly TypeParameterDeclaration[] | undefined, + heritageClauses: readonly HeritageClause[] | undefined, + members: readonly TypeElement[]) { const node = createSynthesizedNode(SyntaxKind.InterfaceDeclaration); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -1874,12 +1874,12 @@ namespace ts { export function updateInterfaceDeclaration( node: InterfaceDeclaration, - decorators: ReadonlyArray | undefined, - modifiers: ReadonlyArray | undefined, + decorators: readonly Decorator[] | undefined, + modifiers: readonly Modifier[] | undefined, name: Identifier, - typeParameters: ReadonlyArray | undefined, - heritageClauses: ReadonlyArray | undefined, - members: ReadonlyArray) { + typeParameters: readonly TypeParameterDeclaration[] | undefined, + heritageClauses: readonly HeritageClause[] | undefined, + members: readonly TypeElement[]) { return node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name @@ -1891,10 +1891,10 @@ namespace ts { } export function createTypeAliasDeclaration( - decorators: ReadonlyArray | undefined, - modifiers: ReadonlyArray | undefined, + decorators: readonly Decorator[] | undefined, + modifiers: readonly Modifier[] | undefined, name: string | Identifier, - typeParameters: ReadonlyArray | undefined, + typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode) { const node = createSynthesizedNode(SyntaxKind.TypeAliasDeclaration); node.decorators = asNodeArray(decorators); @@ -1907,10 +1907,10 @@ namespace ts { export function updateTypeAliasDeclaration( node: TypeAliasDeclaration, - decorators: ReadonlyArray | undefined, - modifiers: ReadonlyArray | undefined, + decorators: readonly Decorator[] | undefined, + modifiers: readonly Modifier[] | undefined, name: Identifier, - typeParameters: ReadonlyArray | undefined, + typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode) { return node.decorators !== decorators || node.modifiers !== modifiers @@ -1922,10 +1922,10 @@ namespace ts { } export function createEnumDeclaration( - decorators: ReadonlyArray | undefined, - modifiers: ReadonlyArray | undefined, + decorators: readonly Decorator[] | undefined, + modifiers: readonly Modifier[] | undefined, name: string | Identifier, - members: ReadonlyArray) { + members: readonly EnumMember[]) { const node = createSynthesizedNode(SyntaxKind.EnumDeclaration); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -1936,10 +1936,10 @@ namespace ts { export function updateEnumDeclaration( node: EnumDeclaration, - decorators: ReadonlyArray | undefined, - modifiers: ReadonlyArray | undefined, + decorators: readonly Decorator[] | undefined, + modifiers: readonly Modifier[] | undefined, name: Identifier, - members: ReadonlyArray) { + members: readonly EnumMember[]) { return node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name @@ -1948,7 +1948,7 @@ namespace ts { : node; } - export function createModuleDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: ModuleName, body: ModuleBody | undefined, flags = NodeFlags.None) { + export function createModuleDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags = NodeFlags.None) { const node = createSynthesizedNode(SyntaxKind.ModuleDeclaration); node.flags |= flags & (NodeFlags.Namespace | NodeFlags.NestedNamespace | NodeFlags.GlobalAugmentation); node.decorators = asNodeArray(decorators); @@ -1958,7 +1958,7 @@ namespace ts { return node; } - export function updateModuleDeclaration(node: ModuleDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: ModuleName, body: ModuleBody | undefined) { + export function updateModuleDeclaration(node: ModuleDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined) { return node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name @@ -1967,25 +1967,25 @@ namespace ts { : node; } - export function createModuleBlock(statements: ReadonlyArray) { + export function createModuleBlock(statements: readonly Statement[]) { const node = createSynthesizedNode(SyntaxKind.ModuleBlock); node.statements = createNodeArray(statements); return node; } - export function updateModuleBlock(node: ModuleBlock, statements: ReadonlyArray) { + export function updateModuleBlock(node: ModuleBlock, statements: readonly Statement[]) { return node.statements !== statements ? updateNode(createModuleBlock(statements), node) : node; } - export function createCaseBlock(clauses: ReadonlyArray): CaseBlock { + export function createCaseBlock(clauses: readonly CaseOrDefaultClause[]): CaseBlock { const node = createSynthesizedNode(SyntaxKind.CaseBlock); node.clauses = createNodeArray(clauses); return node; } - export function updateCaseBlock(node: CaseBlock, clauses: ReadonlyArray) { + export function updateCaseBlock(node: CaseBlock, clauses: readonly CaseOrDefaultClause[]) { return node.clauses !== clauses ? updateNode(createCaseBlock(clauses), node) : node; @@ -2003,7 +2003,7 @@ namespace ts { : node; } - export function createImportEqualsDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, moduleReference: ModuleReference) { + export function createImportEqualsDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, moduleReference: ModuleReference) { const node = createSynthesizedNode(SyntaxKind.ImportEqualsDeclaration); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -2012,7 +2012,7 @@ namespace ts { return node; } - export function updateImportEqualsDeclaration(node: ImportEqualsDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier, moduleReference: ModuleReference) { + export function updateImportEqualsDeclaration(node: ImportEqualsDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, moduleReference: ModuleReference) { return node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name @@ -2022,8 +2022,8 @@ namespace ts { } export function createImportDeclaration( - decorators: ReadonlyArray | undefined, - modifiers: ReadonlyArray | undefined, + decorators: readonly Decorator[] | undefined, + modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression): ImportDeclaration { const node = createSynthesizedNode(SyntaxKind.ImportDeclaration); @@ -2036,8 +2036,8 @@ namespace ts { export function updateImportDeclaration( node: ImportDeclaration, - decorators: ReadonlyArray | undefined, - modifiers: ReadonlyArray | undefined, + decorators: readonly Decorator[] | undefined, + modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression) { return node.decorators !== decorators @@ -2074,13 +2074,13 @@ namespace ts { : node; } - export function createNamedImports(elements: ReadonlyArray): NamedImports { + export function createNamedImports(elements: readonly ImportSpecifier[]): NamedImports { const node = createSynthesizedNode(SyntaxKind.NamedImports); node.elements = createNodeArray(elements); return node; } - export function updateNamedImports(node: NamedImports, elements: ReadonlyArray) { + export function updateNamedImports(node: NamedImports, elements: readonly ImportSpecifier[]) { return node.elements !== elements ? updateNode(createNamedImports(elements), node) : node; @@ -2100,7 +2100,7 @@ namespace ts { : node; } - export function createExportAssignment(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, isExportEquals: boolean | undefined, expression: Expression) { + export function createExportAssignment(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isExportEquals: boolean | undefined, expression: Expression) { const node = createSynthesizedNode(SyntaxKind.ExportAssignment); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -2109,7 +2109,7 @@ namespace ts { return node; } - export function updateExportAssignment(node: ExportAssignment, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, expression: Expression) { + export function updateExportAssignment(node: ExportAssignment, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, expression: Expression) { return node.decorators !== decorators || node.modifiers !== modifiers || node.expression !== expression @@ -2117,7 +2117,7 @@ namespace ts { : node; } - export function createExportDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, exportClause: NamedExports | undefined, moduleSpecifier?: Expression) { + export function createExportDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, exportClause: NamedExports | undefined, moduleSpecifier?: Expression) { const node = createSynthesizedNode(SyntaxKind.ExportDeclaration); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -2128,8 +2128,8 @@ namespace ts { export function updateExportDeclaration( node: ExportDeclaration, - decorators: ReadonlyArray | undefined, - modifiers: ReadonlyArray | undefined, + decorators: readonly Decorator[] | undefined, + modifiers: readonly Modifier[] | undefined, exportClause: NamedExports | undefined, moduleSpecifier: Expression | undefined) { return node.decorators !== decorators @@ -2140,13 +2140,13 @@ namespace ts { : node; } - export function createNamedExports(elements: ReadonlyArray) { + export function createNamedExports(elements: readonly ExportSpecifier[]) { const node = createSynthesizedNode(SyntaxKind.NamedExports); node.elements = createNodeArray(elements); return node; } - export function updateNamedExports(node: NamedExports, elements: ReadonlyArray) { + export function updateNamedExports(node: NamedExports, elements: readonly ExportSpecifier[]) { return node.elements !== elements ? updateNode(createNamedExports(elements), node) : node; @@ -2239,7 +2239,7 @@ namespace ts { // JSX - export function createJsxElement(openingElement: JsxOpeningElement, children: ReadonlyArray, closingElement: JsxClosingElement) { + export function createJsxElement(openingElement: JsxOpeningElement, children: readonly JsxChild[], closingElement: JsxClosingElement) { const node = createSynthesizedNode(SyntaxKind.JsxElement); node.openingElement = openingElement; node.children = createNodeArray(children); @@ -2247,7 +2247,7 @@ namespace ts { return node; } - export function updateJsxElement(node: JsxElement, openingElement: JsxOpeningElement, children: ReadonlyArray, closingElement: JsxClosingElement) { + export function updateJsxElement(node: JsxElement, openingElement: JsxOpeningElement, children: readonly JsxChild[], closingElement: JsxClosingElement) { return node.openingElement !== openingElement || node.children !== children || node.closingElement !== closingElement @@ -2255,7 +2255,7 @@ namespace ts { : node; } - export function createJsxSelfClosingElement(tagName: JsxTagNameExpression, typeArguments: ReadonlyArray | undefined, attributes: JsxAttributes) { + export function createJsxSelfClosingElement(tagName: JsxTagNameExpression, typeArguments: readonly TypeNode[] | undefined, attributes: JsxAttributes) { const node = createSynthesizedNode(SyntaxKind.JsxSelfClosingElement); node.tagName = tagName; node.typeArguments = asNodeArray(typeArguments); @@ -2263,7 +2263,7 @@ namespace ts { return node; } - export function updateJsxSelfClosingElement(node: JsxSelfClosingElement, tagName: JsxTagNameExpression, typeArguments: ReadonlyArray | undefined, attributes: JsxAttributes) { + export function updateJsxSelfClosingElement(node: JsxSelfClosingElement, tagName: JsxTagNameExpression, typeArguments: readonly TypeNode[] | undefined, attributes: JsxAttributes) { return node.tagName !== tagName || node.typeArguments !== typeArguments || node.attributes !== attributes @@ -2271,7 +2271,7 @@ namespace ts { : node; } - export function createJsxOpeningElement(tagName: JsxTagNameExpression, typeArguments: ReadonlyArray | undefined, attributes: JsxAttributes) { + export function createJsxOpeningElement(tagName: JsxTagNameExpression, typeArguments: readonly TypeNode[] | undefined, attributes: JsxAttributes) { const node = createSynthesizedNode(SyntaxKind.JsxOpeningElement); node.tagName = tagName; node.typeArguments = asNodeArray(typeArguments); @@ -2279,7 +2279,7 @@ namespace ts { return node; } - export function updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, typeArguments: ReadonlyArray | undefined, attributes: JsxAttributes) { + export function updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, typeArguments: readonly TypeNode[] | undefined, attributes: JsxAttributes) { return node.tagName !== tagName || node.typeArguments !== typeArguments || node.attributes !== attributes @@ -2299,7 +2299,7 @@ namespace ts { : node; } - export function createJsxFragment(openingFragment: JsxOpeningFragment, children: ReadonlyArray, closingFragment: JsxClosingFragment) { + export function createJsxFragment(openingFragment: JsxOpeningFragment, children: readonly JsxChild[], closingFragment: JsxClosingFragment) { const node = createSynthesizedNode(SyntaxKind.JsxFragment); node.openingFragment = openingFragment; node.children = createNodeArray(children); @@ -2329,7 +2329,7 @@ namespace ts { return createSynthesizedNode(SyntaxKind.JsxClosingFragment); } - export function updateJsxFragment(node: JsxFragment, openingFragment: JsxOpeningFragment, children: ReadonlyArray, closingFragment: JsxClosingFragment) { + export function updateJsxFragment(node: JsxFragment, openingFragment: JsxOpeningFragment, children: readonly JsxChild[], closingFragment: JsxClosingFragment) { return node.openingFragment !== openingFragment || node.children !== children || node.closingFragment !== closingFragment @@ -2351,13 +2351,13 @@ namespace ts { : node; } - export function createJsxAttributes(properties: ReadonlyArray) { + export function createJsxAttributes(properties: readonly JsxAttributeLike[]) { const node = createSynthesizedNode(SyntaxKind.JsxAttributes); node.properties = createNodeArray(properties); return node; } - export function updateJsxAttributes(node: JsxAttributes, properties: ReadonlyArray) { + export function updateJsxAttributes(node: JsxAttributes, properties: readonly JsxAttributeLike[]) { return node.properties !== properties ? updateNode(createJsxAttributes(properties), node) : node; @@ -2390,40 +2390,40 @@ namespace ts { // Clauses - export function createCaseClause(expression: Expression, statements: ReadonlyArray) { + export function createCaseClause(expression: Expression, statements: readonly Statement[]) { const node = createSynthesizedNode(SyntaxKind.CaseClause); node.expression = parenthesizeExpressionForList(expression); node.statements = createNodeArray(statements); return node; } - export function updateCaseClause(node: CaseClause, expression: Expression, statements: ReadonlyArray) { + export function updateCaseClause(node: CaseClause, expression: Expression, statements: readonly Statement[]) { return node.expression !== expression || node.statements !== statements ? updateNode(createCaseClause(expression, statements), node) : node; } - export function createDefaultClause(statements: ReadonlyArray) { + export function createDefaultClause(statements: readonly Statement[]) { const node = createSynthesizedNode(SyntaxKind.DefaultClause); node.statements = createNodeArray(statements); return node; } - export function updateDefaultClause(node: DefaultClause, statements: ReadonlyArray) { + export function updateDefaultClause(node: DefaultClause, statements: readonly Statement[]) { return node.statements !== statements ? updateNode(createDefaultClause(statements), node) : node; } - export function createHeritageClause(token: HeritageClause["token"], types: ReadonlyArray) { + export function createHeritageClause(token: HeritageClause["token"], types: readonly ExpressionWithTypeArguments[]) { const node = createSynthesizedNode(SyntaxKind.HeritageClause); node.token = token; node.types = createNodeArray(types); return node; } - export function updateHeritageClause(node: HeritageClause, types: ReadonlyArray) { + export function updateHeritageClause(node: HeritageClause, types: readonly ExpressionWithTypeArguments[]) { return node.types !== types ? updateNode(createHeritageClause(node.token, types), node) : node; @@ -2504,7 +2504,7 @@ namespace ts { // Top-level nodes - export function updateSourceFileNode(node: SourceFile, statements: ReadonlyArray, isDeclarationFile?: boolean, referencedFiles?: SourceFile["referencedFiles"], typeReferences?: SourceFile["typeReferenceDirectives"], hasNoDefaultLib?: boolean, libReferences?: SourceFile["libReferenceDirectives"]) { + export function updateSourceFileNode(node: SourceFile, statements: readonly Statement[], isDeclarationFile?: boolean, referencedFiles?: SourceFile["referencedFiles"], typeReferences?: SourceFile["typeReferenceDirectives"], hasNoDefaultLib?: boolean, libReferences?: SourceFile["libReferenceDirectives"]) { if ( node.statements !== statements || (isDeclarationFile !== undefined && node.isDeclarationFile !== isDeclarationFile) || @@ -2628,7 +2628,7 @@ namespace ts { return node; } - function flattenCommaElements(node: Expression): Expression | ReadonlyArray { + function flattenCommaElements(node: Expression): Expression | readonly Expression[] { if (nodeIsSynthesized(node) && !isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { if (node.kind === SyntaxKind.CommaListExpression) { return (node).elements; @@ -2640,19 +2640,19 @@ namespace ts { return node; } - export function createCommaList(elements: ReadonlyArray) { + export function createCommaList(elements: readonly Expression[]) { const node = createSynthesizedNode(SyntaxKind.CommaListExpression); node.elements = createNodeArray(sameFlatMap(elements, flattenCommaElements)); return node; } - export function updateCommaList(node: CommaListExpression, elements: ReadonlyArray) { + export function updateCommaList(node: CommaListExpression, elements: readonly Expression[]) { return node.elements !== elements ? updateNode(createCommaList(elements), node) : node; } - export function createBundle(sourceFiles: ReadonlyArray, prepends: ReadonlyArray = emptyArray) { + export function createBundle(sourceFiles: readonly SourceFile[], prepends: readonly (UnparsedSource | InputFiles)[] = emptyArray) { const node = createNode(SyntaxKind.Bundle); node.prepends = prepends; node.sourceFiles = sourceFiles; @@ -2959,7 +2959,7 @@ namespace ts { return node; } - export function updateBundle(node: Bundle, sourceFiles: ReadonlyArray, prepends: ReadonlyArray = emptyArray) { + export function updateBundle(node: Bundle, sourceFiles: readonly SourceFile[], prepends: readonly (UnparsedSource | InputFiles)[] = emptyArray) { if (node.sourceFiles !== sourceFiles || node.prepends !== prepends) { return createBundle(sourceFiles, prepends); } @@ -2968,9 +2968,9 @@ namespace ts { // Compound nodes - export function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray): CallExpression; - export function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray, param: ParameterDeclaration, paramValue: Expression): CallExpression; - export function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray, param?: ParameterDeclaration, paramValue?: Expression) { + export function createImmediatelyInvokedFunctionExpression(statements: readonly Statement[]): CallExpression; + export function createImmediatelyInvokedFunctionExpression(statements: readonly Statement[], param: ParameterDeclaration, paramValue: Expression): CallExpression; + export function createImmediatelyInvokedFunctionExpression(statements: readonly Statement[], param?: ParameterDeclaration, paramValue?: Expression) { return createCall( createFunctionExpression( /*modifiers*/ undefined, @@ -2986,9 +2986,9 @@ namespace ts { ); } - export function createImmediatelyInvokedArrowFunction(statements: ReadonlyArray): CallExpression; - export function createImmediatelyInvokedArrowFunction(statements: ReadonlyArray, param: ParameterDeclaration, paramValue: Expression): CallExpression; - export function createImmediatelyInvokedArrowFunction(statements: ReadonlyArray, param?: ParameterDeclaration, paramValue?: Expression) { + export function createImmediatelyInvokedArrowFunction(statements: readonly Statement[]): CallExpression; + export function createImmediatelyInvokedArrowFunction(statements: readonly Statement[], param: ParameterDeclaration, paramValue: Expression): CallExpression; + export function createImmediatelyInvokedArrowFunction(statements: readonly Statement[], param?: ParameterDeclaration, paramValue?: Expression) { return createCall( createArrowFunction( /*modifiers*/ undefined, @@ -3072,9 +3072,9 @@ namespace ts { return isString(value) || typeof value === "number" ? createLiteral(value) : value; } - function asNodeArray(array: ReadonlyArray): NodeArray; - function asNodeArray(array: ReadonlyArray | undefined): NodeArray | undefined; - function asNodeArray(array: ReadonlyArray | undefined): NodeArray | undefined { + function asNodeArray(array: readonly T[]): NodeArray; + function asNodeArray(array: readonly T[] | undefined): NodeArray | undefined; + function asNodeArray(array: readonly T[] | undefined): NodeArray | undefined { return array ? createNodeArray(array) : undefined; } @@ -3477,7 +3477,7 @@ namespace ts { } } - export function createFunctionCall(func: Expression, thisArg: Expression, argumentsList: ReadonlyArray, location?: TextRange) { + export function createFunctionCall(func: Expression, thisArg: Expression, argumentsList: readonly Expression[], location?: TextRange) { return setTextRange( createCall( createPropertyAccess(func, "call"), @@ -3513,7 +3513,7 @@ namespace ts { return createCall(createPropertyAccess(array, "slice"), /*typeArguments*/ undefined, argumentsList); } - export function createArrayConcat(array: Expression, values: ReadonlyArray) { + export function createArrayConcat(array: Expression, values: readonly Expression[]) { return createCall( createPropertyAccess(array, "concat"), /*typeArguments*/ undefined, @@ -3565,7 +3565,7 @@ namespace ts { ); } - export function createExpressionForJsxElement(jsxFactoryEntity: EntityName | undefined, reactNamespace: string, tagName: Expression, props: Expression, children: ReadonlyArray, parentElement: JsxOpeningLikeElement, location: TextRange): LeftHandSideExpression { + export function createExpressionForJsxElement(jsxFactoryEntity: EntityName | undefined, reactNamespace: string, tagName: Expression, props: Expression, children: readonly Expression[], parentElement: JsxOpeningLikeElement, location: TextRange): LeftHandSideExpression { const argumentsList = [tagName]; if (props) { argumentsList.push(props); @@ -3597,7 +3597,7 @@ namespace ts { ); } - export function createExpressionForJsxFragment(jsxFactoryEntity: EntityName | undefined, reactNamespace: string, children: ReadonlyArray, parentElement: JsxOpeningFragment, location: TextRange): LeftHandSideExpression { + export function createExpressionForJsxFragment(jsxFactoryEntity: EntityName | undefined, reactNamespace: string, children: readonly Expression[], parentElement: JsxOpeningFragment, location: TextRange): LeftHandSideExpression { const tagName = createPropertyAccess( createReactNamespace(reactNamespace, parentElement), "Fragment" @@ -3709,7 +3709,7 @@ namespace ts { };` }; - export function createSpreadHelper(context: TransformationContext, argumentList: ReadonlyArray, location?: TextRange) { + export function createSpreadHelper(context: TransformationContext, argumentList: readonly Expression[], location?: TextRange) { context.requestEmitHelper(readHelper); context.requestEmitHelper(spreadHelper); return setTextRange( @@ -3735,7 +3735,7 @@ namespace ts { };` }; - export function createSpreadArraysHelper(context: TransformationContext, argumentList: ReadonlyArray, location?: TextRange) { + export function createSpreadArraysHelper(context: TransformationContext, argumentList: readonly Expression[], location?: TextRange) { context.requestEmitHelper(spreadArraysHelper); return setTextRange( createCall( @@ -3905,7 +3905,7 @@ namespace ts { return { target, thisArg }; } - export function inlineExpressions(expressions: ReadonlyArray) { + export function inlineExpressions(expressions: readonly Expression[]) { // Avoid deeply nested comma expressions as traversing them during emit can result in "Maximum call // stack size exceeded" errors. return expressions.length > 10 @@ -4231,7 +4231,7 @@ namespace ts { * @param ensureUseStrict: boolean determining whether the function need to add prologue-directives * @param visitor: Optional callback used to visit any custom prologue directives. */ - export function addPrologue(target: Statement[], source: ReadonlyArray, ensureUseStrict?: boolean, visitor?: (node: Node) => VisitResult): number { + export function addPrologue(target: Statement[], source: readonly Statement[], ensureUseStrict?: boolean, visitor?: (node: Node) => VisitResult): number { const offset = addStandardPrologue(target, source, ensureUseStrict); return addCustomPrologue(target, source, offset, visitor); } @@ -4242,7 +4242,7 @@ namespace ts { * This function needs to be called whenever we transform the statement * list of a source file, namespace, or function-like body. */ - export function addStandardPrologue(target: Statement[], source: ReadonlyArray, ensureUseStrict?: boolean): number { + export function addStandardPrologue(target: Statement[], source: readonly Statement[], ensureUseStrict?: boolean): number { Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array"); let foundUseStrict = false; let statementOffset = 0; @@ -4272,9 +4272,9 @@ namespace ts { * This function needs to be called whenever we transform the statement * list of a source file, namespace, or function-like body. */ - export function addCustomPrologue(target: Statement[], source: ReadonlyArray, statementOffset: number, visitor?: (node: Node) => VisitResult): number; - export function addCustomPrologue(target: Statement[], source: ReadonlyArray, statementOffset: number | undefined, visitor?: (node: Node) => VisitResult): number | undefined; - export function addCustomPrologue(target: Statement[], source: ReadonlyArray, statementOffset: number | undefined, visitor?: (node: Node) => VisitResult): number | undefined { + export function addCustomPrologue(target: Statement[], source: readonly Statement[], statementOffset: number, visitor?: (node: Node) => VisitResult): number; + export function addCustomPrologue(target: Statement[], source: readonly Statement[], statementOffset: number | undefined, visitor?: (node: Node) => VisitResult): number | undefined; + export function addCustomPrologue(target: Statement[], source: readonly Statement[], statementOffset: number | undefined, visitor?: (node: Node) => VisitResult): number | undefined { const numStatements = source.length; while (statementOffset !== undefined && statementOffset < numStatements) { const statement = source[statementOffset]; @@ -4289,7 +4289,7 @@ namespace ts { return statementOffset; } - export function findUseStrictPrologue(statements: ReadonlyArray): Statement | undefined { + export function findUseStrictPrologue(statements: readonly Statement[]): Statement | undefined { for (const statement of statements) { if (isPrologueDirective(statement)) { if (isUseStrictPrologue(statement)) { @@ -4303,7 +4303,7 @@ namespace ts { return undefined; } - export function startsWithUseStrict(statements: ReadonlyArray) { + export function startsWithUseStrict(statements: readonly Statement[]) { const firstStatement = firstOrUndefined(statements); return firstStatement !== undefined && isPrologueDirective(firstStatement) @@ -4684,11 +4684,11 @@ namespace ts { return parenthesizeElementTypeMember(member); } - export function parenthesizeElementTypeMembers(members: ReadonlyArray) { + export function parenthesizeElementTypeMembers(members: readonly TypeNode[]) { return createNodeArray(sameMap(members, parenthesizeElementTypeMember)); } - export function parenthesizeTypeParameters(typeParameters: ReadonlyArray | undefined) { + export function parenthesizeTypeParameters(typeParameters: readonly TypeNode[] | undefined) { if (some(typeParameters)) { const params: TypeNode[] = []; for (let i = 0; i < typeParameters.length; ++i) { @@ -5159,18 +5159,18 @@ namespace ts { /** * Gets the elements of a BindingOrAssignmentPattern */ - export function getElementsOfBindingOrAssignmentPattern(name: BindingOrAssignmentPattern): ReadonlyArray { + export function getElementsOfBindingOrAssignmentPattern(name: BindingOrAssignmentPattern): readonly BindingOrAssignmentElement[] { switch (name.kind) { case SyntaxKind.ObjectBindingPattern: case SyntaxKind.ArrayBindingPattern: case SyntaxKind.ArrayLiteralExpression: // `a` in `{a}` // `a` in `[a]` - return >name.elements; + return name.elements; case SyntaxKind.ObjectLiteralExpression: // `a` in `{a}` - return >name.properties; + return name.properties; } } diff --git a/src/compiler/moduleSpecifiers.ts b/src/compiler/moduleSpecifiers.ts index e9a4219ecff..04c6a5584e6 100644 --- a/src/compiler/moduleSpecifiers.ts +++ b/src/compiler/moduleSpecifiers.ts @@ -41,7 +41,7 @@ namespace ts.moduleSpecifiers { importingSourceFileName: Path, toFileName: string, host: ModuleSpecifierResolutionHost, - files: ReadonlyArray, + files: readonly SourceFile[], redirectTargetsMap: RedirectTargetsMap, oldImportSpecifier: string, ): string | undefined { @@ -57,7 +57,7 @@ namespace ts.moduleSpecifiers { importingSourceFileName: Path, toFileName: string, host: ModuleSpecifierResolutionHost, - files: ReadonlyArray, + files: readonly SourceFile[], preferences: UserPreferences = {}, redirectTargetsMap: RedirectTargetsMap, ): string { @@ -69,7 +69,7 @@ namespace ts.moduleSpecifiers { importingSourceFileName: Path, toFileName: string, host: ModuleSpecifierResolutionHost, - files: ReadonlyArray, + files: readonly SourceFile[], redirectTargetsMap: RedirectTargetsMap, preferences: Preferences ): string { @@ -85,10 +85,10 @@ namespace ts.moduleSpecifiers { compilerOptions: CompilerOptions, importingSourceFile: SourceFile, host: ModuleSpecifierResolutionHost, - files: ReadonlyArray, + files: readonly SourceFile[], userPreferences: UserPreferences, redirectTargetsMap: RedirectTargetsMap, - ): ReadonlyArray { + ): readonly string[] { const ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); if (ambient) return [ambient]; @@ -174,7 +174,7 @@ namespace ts.moduleSpecifiers { return [getPathFromPathComponents(aParts), getPathFromPathComponents(bParts)]; } - function discoverProbableSymlinks(files: ReadonlyArray, getCanonicalFileName: GetCanonicalFileName, cwd: string): ReadonlyMap { + function discoverProbableSymlinks(files: readonly SourceFile[], getCanonicalFileName: GetCanonicalFileName, cwd: string): ReadonlyMap { const result = createMap(); const symlinks = flatten(mapDefined(files, sf => sf.resolvedModules && compact(arrayFrom(mapIterator(sf.resolvedModules.values(), res => @@ -190,7 +190,7 @@ namespace ts.moduleSpecifiers { * Looks for existing imports that use symlinks to this module. * Symlinks will be returned first so they are preferred over the real path. */ - function getAllModulePaths(files: ReadonlyArray, importingFileName: string, importedFileName: string, getCanonicalFileName: GetCanonicalFileName, host: ModuleSpecifierResolutionHost, redirectTargetsMap: RedirectTargetsMap): ReadonlyArray { + function getAllModulePaths(files: readonly SourceFile[], importingFileName: string, importedFileName: string, getCanonicalFileName: GetCanonicalFileName, host: ModuleSpecifierResolutionHost, redirectTargetsMap: RedirectTargetsMap): readonly string[] { const redirects = redirectTargetsMap.get(importedFileName); const importedFileNames = redirects ? [...redirects, importedFileName] : [importedFileName]; const cwd = host.getCurrentDirectory ? host.getCurrentDirectory() : ""; @@ -226,7 +226,7 @@ namespace ts.moduleSpecifiers { } } - function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex: string, relativeToBaseUrl: string, paths: MapLike>): string | undefined { + function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex: string, relativeToBaseUrl: string, paths: MapLike): string | undefined { for (const key in paths) { for (const patternText of paths[key]) { const pattern = removeFileExtension(normalizePath(patternText)); @@ -249,7 +249,7 @@ namespace ts.moduleSpecifiers { } } - function tryGetModuleNameFromRootDirs(rootDirs: ReadonlyArray, moduleFileName: string, sourceDirectory: string, getCanonicalFileName: (file: string) => string): string | undefined { + function tryGetModuleNameFromRootDirs(rootDirs: readonly string[], moduleFileName: string, sourceDirectory: string, getCanonicalFileName: (file: string) => string): string | undefined { const normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); if (normalizedTargetPath === undefined) { return undefined; @@ -404,7 +404,7 @@ namespace ts.moduleSpecifiers { return state > States.NodeModules ? { topLevelNodeModulesIndex, topLevelPackageNameIndex, packageRootIndex, fileNameIndex } : undefined; } - function getPathRelativeToRootDirs(path: string, rootDirs: ReadonlyArray, getCanonicalFileName: GetCanonicalFileName): string | undefined { + function getPathRelativeToRootDirs(path: string, rootDirs: readonly string[], getCanonicalFileName: GetCanonicalFileName): string | undefined { return firstDefined(rootDirs, rootDir => { const relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName)!; // TODO: GH#18217 return isPathRelativeToParent(relativePath) ? undefined : relativePath; diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 785e98c3f3b..61da045df8f 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -316,9 +316,9 @@ namespace ts { }; } - export function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; - /*@internal*/ export function getPreEmitDiagnostics(program: BuilderProgram, sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; - export function getPreEmitDiagnostics(program: Program | BuilderProgram, sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray { + export function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[]; + /*@internal*/ export function getPreEmitDiagnostics(program: BuilderProgram, sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[]; + export function getPreEmitDiagnostics(program: Program | BuilderProgram, sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[] { const diagnostics = [ ...program.getConfigFileParsingDiagnostics(), ...program.getOptionsDiagnostics(cancellationToken), @@ -340,7 +340,7 @@ namespace ts { getNewLine(): string; } - export function formatDiagnostics(diagnostics: ReadonlyArray, host: FormatDiagnosticsHost): string { + export function formatDiagnostics(diagnostics: readonly Diagnostic[], host: FormatDiagnosticsHost): string { let output = ""; for (const diagnostic of diagnostics) { @@ -465,7 +465,7 @@ namespace ts { return output; } - export function formatDiagnosticsWithColorAndContext(diagnostics: ReadonlyArray, host: FormatDiagnosticsHost): string { + export function formatDiagnosticsWithColorAndContext(diagnostics: readonly Diagnostic[], host: FormatDiagnosticsHost): string { let output = ""; for (const diagnostic of diagnostics) { if (diagnostic.file) { @@ -562,7 +562,7 @@ namespace ts { fileExists: (fileName: string) => boolean, hasInvalidatedResolution: HasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames: boolean, - projectReferences: ReadonlyArray | undefined + projectReferences: readonly ProjectReference[] | undefined ): boolean { // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date if (!program || hasChangedAutomaticTypeDirectiveNames) { @@ -647,7 +647,7 @@ namespace ts { } } - export function getConfigFileParsingDiagnostics(configFileParseResult: ParsedCommandLine): ReadonlyArray { + export function getConfigFileParsingDiagnostics(configFileParseResult: ParsedCommandLine): readonly Diagnostic[] { return configFileParseResult.options.configFile ? [...configFileParseResult.options.configFile.parseDiagnostics, ...configFileParseResult.errors] : configFileParseResult.errors; @@ -665,7 +665,7 @@ namespace ts { !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option))); } - function createCreateProgramOptions(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): CreateProgramOptions { + function createCreateProgramOptions(rootNames: readonly string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: readonly Diagnostic[]): CreateProgramOptions { return { rootNames, options, @@ -700,8 +700,8 @@ namespace ts { * @param configFileParsingDiagnostics - error during config file parsing * @returns A 'Program' object. */ - export function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program; - export function createProgram(rootNamesOrOptions: ReadonlyArray | CreateProgramOptions, _options?: CompilerOptions, _host?: CompilerHost, _oldProgram?: Program, _configFileParsingDiagnostics?: ReadonlyArray): Program { + export function createProgram(rootNames: readonly string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: readonly Diagnostic[]): Program; + export function createProgram(rootNamesOrOptions: readonly string[] | CreateProgramOptions, _options?: CompilerOptions, _host?: CompilerHost, _oldProgram?: Program, _configFileParsingDiagnostics?: readonly Diagnostic[]): Program { const createProgramOptions = isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options!, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; // TODO: GH#18217 const { rootNames, options, configFileParsingDiagnostics, projectReferences } = createProgramOptions; let { oldProgram } = createProgramOptions; @@ -800,13 +800,13 @@ namespace ts { * - undefined otherwise */ const filesByName = createMap(); - let missingFilePaths: ReadonlyArray | undefined; + let missingFilePaths: readonly Path[] | undefined; // stores 'filename -> file association' ignoring case // used to track cases when two file names differ only in casing const filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? createMap() : undefined; // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files - let resolvedProjectReferences: ReadonlyArray | undefined; + let resolvedProjectReferences: readonly (ResolvedProjectReference | undefined)[] | undefined; let projectReferenceRedirects: Map | undefined; let mapFromFileToProjectReferenceRedirects: Map | undefined; @@ -1528,7 +1528,7 @@ namespace ts { } function emitWorker(program: Program, sourceFile: SourceFile | undefined, writeFileCallback: WriteFileCallback | undefined, cancellationToken: CancellationToken | undefined, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult { - let declarationDiagnostics: ReadonlyArray = []; + let declarationDiagnostics: readonly Diagnostic[] = []; if (!emitOnlyDtsFiles) { if (options.noEmit) { @@ -1596,8 +1596,8 @@ namespace ts { function getDiagnosticsHelper( sourceFile: SourceFile, - getDiagnostics: (sourceFile: SourceFile, cancellationToken: CancellationToken) => ReadonlyArray, - cancellationToken: CancellationToken): ReadonlyArray { + getDiagnostics: (sourceFile: SourceFile, cancellationToken: CancellationToken) => readonly T[], + cancellationToken: CancellationToken): readonly T[] { if (sourceFile) { return getDiagnostics(sourceFile, cancellationToken); } @@ -1609,15 +1609,15 @@ namespace ts { })); } - function getSyntacticDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): ReadonlyArray { + function getSyntacticDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): readonly DiagnosticWithLocation[] { return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken); } - function getSemanticDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): ReadonlyArray { + function getSemanticDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): readonly Diagnostic[] { return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken); } - function getDeclarationDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): ReadonlyArray { + function getDeclarationDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): readonly DiagnosticWithLocation[] { const options = program.getCompilerOptions(); // collect diagnostics from the program only once if either no source file was specified or out/outFile is set (bundled emit) if (!sourceFile || options.out || options.outFile) { @@ -1628,7 +1628,7 @@ namespace ts { } } - function getSyntacticDiagnosticsForFile(sourceFile: SourceFile): ReadonlyArray { + function getSyntacticDiagnosticsForFile(sourceFile: SourceFile): readonly DiagnosticWithLocation[] { // For JavaScript files, we report semantic errors for using TypeScript-only // constructs from within a JavaScript file as syntactic errors. if (isSourceFileJS(sourceFile)) { @@ -1663,7 +1663,7 @@ namespace ts { } } - function getSemanticDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): ReadonlyArray { + function getSemanticDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): readonly Diagnostic[] { return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedSemanticDiagnosticsForFile, getSemanticDiagnosticsForFileNoCache); } @@ -1681,7 +1681,7 @@ namespace ts { // By default, only type-check .ts, .tsx, 'Deferred' and 'External' files (external files are added by plugins) const includeBindAndCheckDiagnostics = sourceFile.scriptKind === ScriptKind.TS || sourceFile.scriptKind === ScriptKind.TSX || sourceFile.scriptKind === ScriptKind.External || isCheckJs || sourceFile.scriptKind === ScriptKind.Deferred; - const bindDiagnostics: ReadonlyArray = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : emptyArray; + const bindDiagnostics: readonly Diagnostic[] = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : emptyArray; const checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : emptyArray; const fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); const programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); @@ -1700,7 +1700,7 @@ namespace ts { }); } - function getSuggestionDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): ReadonlyArray { + function getSuggestionDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): readonly DiagnosticWithLocation[] { return runWithCancellationToken(() => { return getDiagnosticsProducingTypeChecker().getSuggestionDiagnostics(sourceFile, cancellationToken); }); @@ -1916,7 +1916,7 @@ namespace ts { }); } - function getDeclarationDiagnosticsWorker(sourceFile: SourceFile, cancellationToken: CancellationToken): ReadonlyArray { + function getDeclarationDiagnosticsWorker(sourceFile: SourceFile, cancellationToken: CancellationToken): readonly DiagnosticWithLocation[] { return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedDeclarationDiagnosticsForFile, getDeclarationDiagnosticsForFileNoCache); } @@ -1933,7 +1933,7 @@ namespace ts { cancellationToken: CancellationToken, cache: DiagnosticCache, getDiagnostics: (sourceFile: SourceFile, cancellationToken: CancellationToken) => T[] | undefined, - ): ReadonlyArray { + ): readonly T[] { const cachedResult = sourceFile ? cache.perFile && cache.perFile.get(sourceFile.path) @@ -1955,7 +1955,7 @@ namespace ts { return result; } - function getDeclarationDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): ReadonlyArray { + function getDeclarationDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): readonly DiagnosticWithLocation[] { return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); } @@ -1984,7 +1984,7 @@ namespace ts { return rootNames.length ? sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()) : emptyArray as any as SortedReadonlyArray; } - function getConfigFileParsingDiagnostics(): ReadonlyArray { + function getConfigFileParsingDiagnostics(): readonly Diagnostic[] { return configFileParsingDiagnostics || emptyArray; } @@ -2427,21 +2427,21 @@ namespace ts { } function forEachProjectReference( - projectReferences: ReadonlyArray | undefined, - resolvedProjectReferences: ReadonlyArray | undefined, + projectReferences: readonly ProjectReference[] | undefined, + resolvedProjectReferences: readonly (ResolvedProjectReference | undefined)[] | undefined, cbResolvedRef: (resolvedRef: ResolvedProjectReference | undefined, index: number, parent: ResolvedProjectReference | undefined) => T | undefined, - cbRef?: (projectReferences: ReadonlyArray | undefined, parent: ResolvedProjectReference | undefined) => T | undefined + cbRef?: (projectReferences: readonly ProjectReference[] | undefined, parent: ResolvedProjectReference | undefined) => T | undefined ): T | undefined { let seenResolvedRefs: ResolvedProjectReference[] | undefined; return worker(projectReferences, resolvedProjectReferences, /*parent*/ undefined, cbResolvedRef, cbRef); function worker( - projectReferences: ReadonlyArray | undefined, - resolvedProjectReferences: ReadonlyArray | undefined, + projectReferences: readonly ProjectReference[] | undefined, + resolvedProjectReferences: readonly (ResolvedProjectReference | undefined)[] | undefined, parent: ResolvedProjectReference | undefined, cbResolvedRef: (resolvedRef: ResolvedProjectReference | undefined, index: number, parent: ResolvedProjectReference | undefined) => T | undefined, - cbRef?: (projectReferences: ReadonlyArray | undefined, parent: ResolvedProjectReference | undefined) => T | undefined, + cbRef?: (projectReferences: readonly ProjectReference[] | undefined, parent: ResolvedProjectReference | undefined) => T | undefined, ): T | undefined { // Visit project references first @@ -2650,7 +2650,7 @@ namespace ts { return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); } - function checkSourceFilesBelongToPath(sourceFiles: ReadonlyArray, rootDirectory: string): boolean { + function checkSourceFilesBelongToPath(sourceFiles: readonly SourceFile[], rootDirectory: string): boolean { let allFilesBelongToPath = true; const absoluteRootDirectoryPath = host.getCanonicalFileName(getNormalizedAbsolutePath(rootDirectory, currentDirectory)); @@ -3171,7 +3171,7 @@ namespace ts { getCurrentDirectory(): string; fileExists(fileName: string): boolean; readFile(fileName: string): string | undefined; - readDirectory?(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): string[]; + readDirectory?(rootDir: string, extensions: readonly string[], excludes: readonly string[] | undefined, includes: readonly string[], depth?: number): string[]; trace?(s: string): void; onUnRecoverableConfigFileDiagnostic?: DiagnosticReporter; } @@ -3198,7 +3198,7 @@ namespace ts { } /* @internal */ - export function createPrependNodes(projectReferences: ReadonlyArray | undefined, getCommandLine: (ref: ProjectReference, index: number) => ParsedCommandLine | undefined, readFile: (path: string) => string | undefined) { + export function createPrependNodes(projectReferences: readonly ProjectReference[] | undefined, getCommandLine: (ref: ProjectReference, index: number) => ParsedCommandLine | undefined, readFile: (path: string) => string | undefined) { if (!projectReferences) return emptyArray; let nodes: InputFiles[] | undefined; for (let i = 0; i < projectReferences.length; i++) { diff --git a/src/compiler/resolutionCache.ts b/src/compiler/resolutionCache.ts index 63ab157d200..414dc509d0f 100644 --- a/src/compiler/resolutionCache.ts +++ b/src/compiler/resolutionCache.ts @@ -12,7 +12,7 @@ namespace ts { invalidateResolutionOfFile(filePath: Path): void; removeResolutionsOfFile(filePath: Path): void; removeResolutionsFromProjectReferenceRedirects(filePath: Path): void; - setFilesWithInvalidatedNonRelativeUnresolvedImports(filesWithUnresolvedImports: Map>): void; + setFilesWithInvalidatedNonRelativeUnresolvedImports(filesWithUnresolvedImports: Map): void; createHasInvalidatedResolution(forceAllFilesAsInvalidated?: boolean): HasInvalidatedResolution; startCachingPerDirectoryResolution(): void; @@ -25,7 +25,7 @@ namespace ts { } interface ResolutionWithFailedLookupLocations { - readonly failedLookupLocations: ReadonlyArray; + readonly failedLookupLocations: readonly string[]; isInvalidated?: boolean; refCount?: number; } @@ -120,7 +120,7 @@ namespace ts { export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootDirForResolution: string | undefined, logChangesWhenResolvingModule: boolean): ResolutionCache { let filesWithChangedSetOfUnresolvedImports: Path[] | undefined; let filesWithInvalidatedResolutions: Map | undefined; - let filesWithInvalidatedNonRelativeUnresolvedImports: ReadonlyMap> | undefined; + let filesWithInvalidatedNonRelativeUnresolvedImports: ReadonlyMap | undefined; let allFilesHaveInvalidatedResolution = false; const nonRelativeExternalModuleResolutions = createMultiMap(); @@ -287,7 +287,7 @@ namespace ts { } function resolveNamesWithLocalCache( - names: ReadonlyArray, + names: readonly string[], containingFile: string, redirectedReference: ResolvedProjectReference | undefined, cache: Map>, @@ -295,7 +295,7 @@ namespace ts { loader: (name: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference) => T, getResolutionWithResolvedFileName: GetResolutionWithResolvedFileName, shouldRetryResolution: (t: T) => boolean, - reusedNames: ReadonlyArray | undefined, + reusedNames: readonly string[] | undefined, logChanges: boolean): (R | undefined)[] { const path = resolutionHost.toPath(containingFile); @@ -689,7 +689,7 @@ namespace ts { ); } - function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap: ReadonlyMap>) { + function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap: ReadonlyMap) { Debug.assert(filesWithInvalidatedNonRelativeUnresolvedImports === filesMap || filesWithInvalidatedNonRelativeUnresolvedImports === undefined); filesWithInvalidatedNonRelativeUnresolvedImports = filesMap; } diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts index 3f8eddc9a89..570b16318db 100644 --- a/src/compiler/scanner.ts +++ b/src/compiler/scanner.ts @@ -257,7 +257,7 @@ namespace ts { const unicodeESNextIdentifierStart = [65, 90, 97, 122, 170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 895, 895, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1488, 1514, 1519, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2144, 2154, 2208, 2228, 2230, 2237, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2432, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2556, 2556, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2809, 2809, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3133, 3133, 3160, 3162, 3168, 3169, 3200, 3200, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3412, 3414, 3423, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6264, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6430, 6480, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7401, 7404, 7406, 7411, 7413, 7414, 7418, 7418, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12443, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40943, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42653, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42943, 42946, 42950, 42999, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43261, 43262, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43488, 43492, 43494, 43503, 43514, 43518, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43646, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43879, 43888, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66176, 66204, 66208, 66256, 66304, 66335, 66349, 66378, 66384, 66421, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 67072, 67382, 67392, 67413, 67424, 67431, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68096, 68112, 68115, 68117, 68119, 68121, 68149, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68324, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68899, 69376, 69404, 69415, 69415, 69424, 69445, 69600, 69622, 69635, 69687, 69763, 69807, 69840, 69864, 69891, 69926, 69956, 69956, 69968, 70002, 70006, 70006, 70019, 70066, 70081, 70084, 70106, 70106, 70108, 70108, 70144, 70161, 70163, 70187, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70366, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70461, 70461, 70480, 70480, 70493, 70497, 70656, 70708, 70727, 70730, 70751, 70751, 70784, 70831, 70852, 70853, 70855, 70855, 71040, 71086, 71128, 71131, 71168, 71215, 71236, 71236, 71296, 71338, 71352, 71352, 71424, 71450, 71680, 71723, 71840, 71903, 71935, 71935, 72096, 72103, 72106, 72144, 72161, 72161, 72163, 72163, 72192, 72192, 72203, 72242, 72250, 72250, 72272, 72272, 72284, 72329, 72349, 72349, 72384, 72440, 72704, 72712, 72714, 72750, 72768, 72768, 72818, 72847, 72960, 72966, 72968, 72969, 72971, 73008, 73030, 73030, 73056, 73061, 73063, 73064, 73066, 73097, 73112, 73112, 73440, 73458, 73728, 74649, 74752, 74862, 74880, 75075, 77824, 78894, 82944, 83526, 92160, 92728, 92736, 92766, 92880, 92909, 92928, 92975, 92992, 92995, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94032, 94032, 94099, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101106, 110592, 110878, 110928, 110930, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 123136, 123180, 123191, 123197, 123214, 123214, 123584, 123627, 124928, 125124, 125184, 125251, 125259, 125259, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173782, 173824, 177972, 177984, 178205, 178208, 183969, 183984, 191456, 194560, 195101]; const unicodeESNextIdentifierPart = [48, 57, 65, 90, 95, 95, 97, 122, 170, 170, 181, 181, 183, 183, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 895, 895, 902, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1519, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2045, 2045, 2048, 2093, 2112, 2139, 2144, 2154, 2208, 2228, 2230, 2237, 2259, 2273, 2275, 2403, 2406, 2415, 2417, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2556, 2556, 2558, 2558, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2809, 2815, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3072, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3162, 3168, 3171, 3174, 3183, 3200, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3328, 3331, 3333, 3340, 3342, 3344, 3346, 3396, 3398, 3400, 3402, 3406, 3412, 3415, 3423, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3558, 3567, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4969, 4977, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6264, 6272, 6314, 6320, 6389, 6400, 6430, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6618, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6832, 6845, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7376, 7378, 7380, 7418, 7424, 7673, 7675, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40943, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42737, 42775, 42783, 42786, 42888, 42891, 42943, 42946, 42950, 42999, 43047, 43072, 43123, 43136, 43205, 43216, 43225, 43232, 43255, 43259, 43259, 43261, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43488, 43518, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43879, 43888, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65071, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66045, 66045, 66176, 66204, 66208, 66256, 66272, 66272, 66304, 66335, 66349, 66378, 66384, 66426, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66720, 66729, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 67072, 67382, 67392, 67413, 67424, 67431, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68099, 68101, 68102, 68108, 68115, 68117, 68119, 68121, 68149, 68152, 68154, 68159, 68159, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68326, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68903, 68912, 68921, 69376, 69404, 69415, 69415, 69424, 69456, 69600, 69622, 69632, 69702, 69734, 69743, 69759, 69818, 69840, 69864, 69872, 69881, 69888, 69940, 69942, 69951, 69956, 69958, 69968, 70003, 70006, 70006, 70016, 70084, 70089, 70092, 70096, 70106, 70108, 70108, 70144, 70161, 70163, 70199, 70206, 70206, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70378, 70384, 70393, 70400, 70403, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70459, 70468, 70471, 70472, 70475, 70477, 70480, 70480, 70487, 70487, 70493, 70499, 70502, 70508, 70512, 70516, 70656, 70730, 70736, 70745, 70750, 70751, 70784, 70853, 70855, 70855, 70864, 70873, 71040, 71093, 71096, 71104, 71128, 71133, 71168, 71232, 71236, 71236, 71248, 71257, 71296, 71352, 71360, 71369, 71424, 71450, 71453, 71467, 71472, 71481, 71680, 71738, 71840, 71913, 71935, 71935, 72096, 72103, 72106, 72151, 72154, 72161, 72163, 72164, 72192, 72254, 72263, 72263, 72272, 72345, 72349, 72349, 72384, 72440, 72704, 72712, 72714, 72758, 72760, 72768, 72784, 72793, 72818, 72847, 72850, 72871, 72873, 72886, 72960, 72966, 72968, 72969, 72971, 73014, 73018, 73018, 73020, 73021, 73023, 73031, 73040, 73049, 73056, 73061, 73063, 73064, 73066, 73102, 73104, 73105, 73107, 73112, 73120, 73129, 73440, 73462, 73728, 74649, 74752, 74862, 74880, 75075, 77824, 78894, 82944, 83526, 92160, 92728, 92736, 92766, 92768, 92777, 92880, 92909, 92912, 92916, 92928, 92982, 92992, 92995, 93008, 93017, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94031, 94087, 94095, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101106, 110592, 110878, 110928, 110930, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 113821, 113822, 119141, 119145, 119149, 119154, 119163, 119170, 119173, 119179, 119210, 119213, 119362, 119364, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 120782, 120831, 121344, 121398, 121403, 121452, 121461, 121461, 121476, 121476, 121499, 121503, 121505, 121519, 122880, 122886, 122888, 122904, 122907, 122913, 122915, 122916, 122918, 122922, 123136, 123180, 123184, 123197, 123200, 123209, 123214, 123214, 123584, 123641, 124928, 125124, 125136, 125142, 125184, 125259, 125264, 125273, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173782, 173824, 177972, 177984, 178205, 178208, 183969, 183984, 191456, 194560, 195101, 917760, 917999]; - function lookupInUnicodeMap(code: number, map: ReadonlyArray): boolean { + function lookupInUnicodeMap(code: number, map: readonly number[]): boolean { // Bail out quickly if it couldn't possibly be in the map. if (code < map[0]) { return false; @@ -359,7 +359,7 @@ namespace ts { } /* @internal */ - export function computePositionOfLineAndCharacter(lineStarts: ReadonlyArray, line: number, character: number, debugText?: string, allowEdits?: true): number { + export function computePositionOfLineAndCharacter(lineStarts: readonly number[], line: number, character: number, debugText?: string, allowEdits?: true): number { if (line < 0 || line >= lineStarts.length) { if (allowEdits) { // Clamp line to nearest allowable value @@ -387,7 +387,7 @@ namespace ts { } /* @internal */ - export function getLineStarts(sourceFile: SourceFileLike): ReadonlyArray { + export function getLineStarts(sourceFile: SourceFileLike): readonly number[] { return sourceFile.lineMap || (sourceFile.lineMap = computeLineStarts(sourceFile.text)); } @@ -395,7 +395,7 @@ namespace ts { /** * We assume the first line starts at position 0 and 'position' is non-negative. */ - export function computeLineAndCharacterOfPosition(lineStarts: ReadonlyArray, position: number): LineAndCharacter { + export function computeLineAndCharacterOfPosition(lineStarts: readonly number[], position: number): LineAndCharacter { let lineNumber = binarySearch(lineStarts, position, identity, compareValues); if (lineNumber < 0) { // If the actual position was not found, diff --git a/src/compiler/semver.ts b/src/compiler/semver.ts index 33623f45542..b4f9ca03e33 100644 --- a/src/compiler/semver.ts +++ b/src/compiler/semver.ts @@ -35,8 +35,8 @@ namespace ts { readonly major: number; readonly minor: number; readonly patch: number; - readonly prerelease: ReadonlyArray; - readonly build: ReadonlyArray; + readonly prerelease: readonly string[]; + readonly build: readonly string[]; constructor(text: string); constructor(major: number, minor?: number, patch?: number, prerelease?: string, build?: string); @@ -120,7 +120,7 @@ namespace ts { }; } - function comparePrerelaseIdentifiers(left: ReadonlyArray, right: ReadonlyArray) { + function comparePrerelaseIdentifiers(left: readonly string[], right: readonly string[]) { // https://semver.org/#spec-item-11 // > When major, minor, and patch are equal, a pre-release version has lower precedence // > than a normal version. @@ -168,7 +168,7 @@ namespace ts { * Describes a semantic version range, per https://github.com/npm/node-semver#ranges */ export class VersionRange { - private _alternatives: ReadonlyArray>; + private _alternatives: readonly (readonly Comparator[])[]; constructor(spec: string) { this._alternatives = spec ? Debug.assertDefined(parseRange(spec), "Invalid range spec.") : emptyArray; @@ -349,7 +349,7 @@ namespace ts { return { operator, operand }; } - function testDisjunction(version: Version, alternatives: ReadonlyArray>) { + function testDisjunction(version: Version, alternatives: readonly (readonly Comparator[])[]) { // an empty disjunction is treated as "*" (all versions) if (alternatives.length === 0) return true; for (const alternative of alternatives) { @@ -358,7 +358,7 @@ namespace ts { return false; } - function testAlternative(version: Version, comparators: ReadonlyArray) { + function testAlternative(version: Version, comparators: readonly Comparator[]) { for (const comparator of comparators) { if (!testComparator(version, comparator.operator, comparator.operand)) return false; } @@ -377,11 +377,11 @@ namespace ts { } } - function formatDisjunction(alternatives: ReadonlyArray>) { + function formatDisjunction(alternatives: readonly (readonly Comparator[])[]) { return map(alternatives, formatAlternative).join(" || ") || "*"; } - function formatAlternative(comparators: ReadonlyArray) { + function formatAlternative(comparators: readonly Comparator[]) { return map(comparators, formatComparator).join(" "); } diff --git a/src/compiler/sourcemap.ts b/src/compiler/sourcemap.ts index 9491c700d39..5fae21601a3 100644 --- a/src/compiler/sourcemap.ts +++ b/src/compiler/sourcemap.ts @@ -286,7 +286,7 @@ namespace ts { getLineText(line: number): string; } - export function getLineInfo(text: string, lineStarts: ReadonlyArray): LineInfo { + export function getLineInfo(text: string, lineStarts: readonly number[]): LineInfo { return { getLineCount: () => lineStarts.length, getLineText: line => text.substring(lineStarts[line], lineStarts[line + 1]) @@ -623,9 +623,9 @@ namespace ts { const generatedFile = host.getSourceFileLike(generatedAbsoluteFilePath); const sourceFileAbsolutePaths = map.sources.map(source => getNormalizedAbsolutePath(source, sourceRoot)); const sourceToSourceIndexMap = createMapFromEntries(sourceFileAbsolutePaths.map((source, i) => [host.getCanonicalFileName(source), i] as [string, number])); - let decodedMappings: ReadonlyArray | undefined; + let decodedMappings: readonly MappedPosition[] | undefined; let generatedMappings: SortedReadonlyArray | undefined; - let sourceMappings: ReadonlyArray> | undefined; + let sourceMappings: readonly SortedReadonlyArray[] | undefined; return { getSourcePosition, diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index 1e9f37a567f..f589d792e11 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -383,7 +383,7 @@ namespace ts { export interface RecursiveDirectoryWatcherHost { watchDirectory: HostWatchDirectory; useCaseSensitiveFileNames: boolean; - getAccessibleSortedChildDirectories(path: string): ReadonlyArray; + getAccessibleSortedChildDirectories(path: string): readonly string[]; directoryExists(dir: string): boolean; realpath(s: string): string; } @@ -398,7 +398,7 @@ namespace ts { interface ChildDirectoryWatcher extends FileWatcher { dirName: string; } - type ChildWatches = ReadonlyArray; + type ChildWatches = readonly ChildDirectoryWatcher[]; interface HostDirectoryWatcher { watcher: FileWatcher; childWatches: ChildWatches; @@ -625,7 +625,7 @@ namespace ts { getExecutingFilePath(): string; getCurrentDirectory(): string; getDirectories(path: string): string[]; - readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; + readDirectory(path: string, extensions?: readonly string[], exclude?: readonly string[], include?: readonly string[], depth?: number): string[]; getModifiedTime?(path: string): Date | undefined; setModifiedTime?(path: string, time: Date): void; deleteFile?(path: string): void; @@ -696,7 +696,7 @@ namespace ts { readFile(path: string): string | undefined; writeFile(path: string, contents: string): void; getDirectories(path: string): string[]; - readDirectory(path: string, extensions?: ReadonlyArray, basePaths?: ReadonlyArray, excludeEx?: string, includeFileEx?: string, includeDirEx?: string): string[]; + readDirectory(path: string, extensions?: readonly string[], basePaths?: readonly string[], excludeEx?: string, includeFileEx?: string, includeDirEx?: string): string[]; watchFile?(path: string, callback: FileWatcherCallback): FileWatcher; watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; realpath(path: string): string; @@ -1227,7 +1227,7 @@ namespace ts { } } - function readDirectory(path: string, extensions?: ReadonlyArray, excludes?: ReadonlyArray, includes?: ReadonlyArray, depth?: number): string[] { + function readDirectory(path: string, extensions?: readonly string[], excludes?: readonly string[], includes?: readonly string[], depth?: number): string[] { return matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath); } diff --git a/src/compiler/transformer.ts b/src/compiler/transformer.ts index d520571e6df..bd8f34ee128 100644 --- a/src/compiler/transformer.ts +++ b/src/compiler/transformer.ts @@ -139,7 +139,7 @@ namespace ts { * @param transforms An array of `TransformerFactory` callbacks. * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. */ - export function transformNodes(resolver: EmitResolver | undefined, host: EmitHost | undefined, options: CompilerOptions, nodes: ReadonlyArray, transformers: ReadonlyArray>, allowDtsFiles: boolean): TransformationResult { + export function transformNodes(resolver: EmitResolver | undefined, host: EmitHost | undefined, options: CompilerOptions, nodes: readonly T[], transformers: readonly TransformerFactory[], allowDtsFiles: boolean): TransformationResult { const enabledSyntaxKindFeatures = new Array(SyntaxKind.Count); let lexicalEnvironmentVariableDeclarations: VariableDeclaration[]; let lexicalEnvironmentFunctionDeclarations: FunctionDeclaration[]; diff --git a/src/compiler/transformers/classFields.ts b/src/compiler/transformers/classFields.ts index 048e4623656..4efe4ad7b38 100644 --- a/src/compiler/transformers/classFields.ts +++ b/src/compiler/transformers/classFields.ts @@ -376,7 +376,7 @@ namespace ts { * @param properties An array of property declarations to transform. * @param receiver The receiver on which each property should be assigned. */ - function addInitializedPropertyStatements(statements: Statement[], properties: ReadonlyArray, receiver: LeftHandSideExpression) { + function addInitializedPropertyStatements(statements: Statement[], properties: readonly PropertyDeclaration[], receiver: LeftHandSideExpression) { for (const property of properties) { const statement = createExpressionStatement(transformInitializedProperty(property, receiver)); setSourceMapRange(statement, moveRangePastModifiers(property)); @@ -392,7 +392,7 @@ namespace ts { * @param properties An array of property declarations to transform. * @param receiver The receiver on which each property should be assigned. */ - function generateInitializedPropertyExpressions(properties: ReadonlyArray, receiver: LeftHandSideExpression) { + function generateInitializedPropertyExpressions(properties: readonly PropertyDeclaration[], receiver: LeftHandSideExpression) { const expressions: Expression[] = []; for (const property of properties) { const expression = transformInitializedProperty(property, receiver); diff --git a/src/compiler/transformers/declarations.ts b/src/compiler/transformers/declarations.ts index 115cbe108ee..3aa70698cf6 100644 --- a/src/compiler/transformers/declarations.ts +++ b/src/compiler/transformers/declarations.ts @@ -83,14 +83,14 @@ namespace ts { let currentSourceFile: SourceFile; let refs: Map; let libs: Map; - let emittedImports: ReadonlyArray | undefined; // must be declared in container so it can be `undefined` while transformer's first pass + let emittedImports: readonly AnyImportSyntax[] | undefined; // must be declared in container so it can be `undefined` while transformer's first pass const resolver = context.getEmitResolver(); const options = context.getCompilerOptions(); const newLine = getNewLineCharacter(options); const { noResolve, stripInternal } = options; return transformRoot; - function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives: ReadonlyArray | undefined): void { + function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives: readonly string[] | undefined): void { if (!typeReferenceDirectives) { return; } @@ -1177,7 +1177,7 @@ namespace ts { const modifiers = createNodeArray(ensureModifiers(input)); const typeParameters = ensureTypeParams(input, input.typeParameters); const ctor = getFirstConstructorWithBody(input); - let parameterProperties: ReadonlyArray | undefined; + let parameterProperties: readonly PropertyDeclaration[] | undefined; if (ctor) { const oldDiag = getSymbolAccessibilityDiagnostic; parameterProperties = compact(flatMap(ctor.parameters, (param) => { @@ -1350,11 +1350,11 @@ namespace ts { return isExportAssignment(node) || isExportDeclaration(node); } - function hasScopeMarker(statements: ReadonlyArray) { + function hasScopeMarker(statements: readonly Statement[]) { return some(statements, isScopeMarker); } - function ensureModifiers(node: Node): ReadonlyArray | undefined { + function ensureModifiers(node: Node): readonly Modifier[] | undefined { const currentFlags = getModifierFlags(node); const newFlags = ensureModifierFlags(node); if (currentFlags === newFlags) { diff --git a/src/compiler/transformers/destructuring.ts b/src/compiler/transformers/destructuring.ts index 8946db3f60b..10645cdc184 100644 --- a/src/compiler/transformers/destructuring.ts +++ b/src/compiler/transformers/destructuring.ts @@ -532,7 +532,7 @@ namespace ts { /** Given value: o, propName: p, pattern: { a, b, ...p } from the original statement * `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);` */ - function createRestCall(context: TransformationContext, value: Expression, elements: ReadonlyArray, computedTempVariables: ReadonlyArray, location: TextRange): Expression { + function createRestCall(context: TransformationContext, value: Expression, elements: readonly BindingOrAssignmentElement[], computedTempVariables: readonly Expression[], location: TextRange): Expression { context.requestEmitHelper(restHelper); const propertyNames: Expression[] = []; let computedTempVariableOffset = 0; diff --git a/src/compiler/transformers/es2015.ts b/src/compiler/transformers/es2015.ts index f51708eb07d..1b7054a7b40 100644 --- a/src/compiler/transformers/es2015.ts +++ b/src/compiler/transformers/es2015.ts @@ -2067,7 +2067,7 @@ namespace ts { return visitEachChild(node, visitor, context); } - function getRangeUnion(declarations: ReadonlyArray): TextRange { + function getRangeUnion(declarations: readonly Node[]): TextRange { // declarations may not be sorted by position. // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes. let pos = -1, end = -1; diff --git a/src/compiler/transformers/es2018.ts b/src/compiler/transformers/es2018.ts index 67f361d0471..3383c4fa889 100644 --- a/src/compiler/transformers/es2018.ts +++ b/src/compiler/transformers/es2018.ts @@ -204,7 +204,7 @@ namespace ts { return visitEachChild(node, visitor, context); } - function chunkObjectLiteralElements(elements: ReadonlyArray): Expression[] { + function chunkObjectLiteralElements(elements: readonly ObjectLiteralElementLike[]): Expression[] { let chunkObject: ObjectLiteralElementLike[] | undefined; const objects: Expression[] = []; for (const e of elements) { diff --git a/src/compiler/transformers/generators.ts b/src/compiler/transformers/generators.ts index 8423aa252f1..0efee59fb59 100644 --- a/src/compiler/transformers/generators.ts +++ b/src/compiler/transformers/generators.ts @@ -1172,7 +1172,7 @@ namespace ts { return visitEachChild(node, visitor, context); } - function transformAndEmitStatements(statements: ReadonlyArray, start = 0) { + function transformAndEmitStatements(statements: readonly Statement[], start = 0) { const numStatements = statements.length; for (let i = start; i < numStatements; i++) { transformAndEmitStatement(statements[i]); diff --git a/src/compiler/transformers/jsx.ts b/src/compiler/transformers/jsx.ts index 2fe343da134..4b75deb95cb 100644 --- a/src/compiler/transformers/jsx.ts +++ b/src/compiler/transformers/jsx.ts @@ -84,7 +84,7 @@ namespace ts { return visitJsxOpeningFragment(node.openingFragment, node.children, isChild, /*location*/ node); } - function visitJsxOpeningLikeElement(node: JsxOpeningLikeElement, children: ReadonlyArray | undefined, isChild: boolean, location: TextRange) { + function visitJsxOpeningLikeElement(node: JsxOpeningLikeElement, children: readonly JsxChild[] | undefined, isChild: boolean, location: TextRange) { const tagName = getTagName(node); let objectProperties: Expression | undefined; const attrs = node.attributes.properties; @@ -133,7 +133,7 @@ namespace ts { return element; } - function visitJsxOpeningFragment(node: JsxOpeningFragment, children: ReadonlyArray, isChild: boolean, location: TextRange) { + function visitJsxOpeningFragment(node: JsxOpeningFragment, children: readonly JsxChild[], isChild: boolean, location: TextRange) { const element = createExpressionForJsxFragment( context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace!, // TODO: GH#18217 diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index 00bf1aecf32..90b0ebfca56 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -580,7 +580,7 @@ namespace ts { return parameter.decorators !== undefined && parameter.decorators.length > 0; } - function getClassFacts(node: ClassDeclaration, staticProperties: ReadonlyArray) { + function getClassFacts(node: ClassDeclaration, staticProperties: readonly PropertyDeclaration[]) { let facts = ClassFacts.None; if (some(staticProperties)) facts |= ClassFacts.HasStaticInitializedProperties; const extendsClauseElement = getEffectiveBaseTypeNode(node); @@ -924,7 +924,7 @@ namespace ts { * @param isStatic A value indicating whether to retrieve static or instance members of * the class. */ - function getDecoratedClassElements(node: ClassExpression | ClassDeclaration, isStatic: boolean): ReadonlyArray { + function getDecoratedClassElements(node: ClassExpression | ClassDeclaration, isStatic: boolean): readonly ClassElement[] { return filter(node.members, isStatic ? m => isStaticDecoratedClassElement(m, node) : m => isInstanceDecoratedClassElement(m, node)); } @@ -963,8 +963,8 @@ namespace ts { * A structure describing the decorators for a class element. */ interface AllDecorators { - decorators: ReadonlyArray | undefined; - parameters?: ReadonlyArray | undefined>; + decorators: readonly Decorator[] | undefined; + parameters?: readonly (readonly Decorator[] | undefined)[]; } /** @@ -974,7 +974,7 @@ namespace ts { * @param node The function-like node. */ function getDecoratorsOfParameters(node: FunctionLikeDeclaration | undefined) { - let decorators: (ReadonlyArray | undefined)[] | undefined; + let decorators: (readonly Decorator[] | undefined)[] | undefined; if (node) { const parameters = node.parameters; const firstParameterIsThis = parameters.length > 0 && parameterIsThisKeyword(parameters[0]); @@ -1588,7 +1588,7 @@ namespace ts { return createIdentifier("Object"); } - function serializeTypeList(types: ReadonlyArray): SerializedTypeNode { + function serializeTypeList(types: readonly TypeNode[]): SerializedTypeNode { // Note when updating logic here also update getEntityNameForDecoratorMetadata // so that aliases can be marked as referenced let serializedUnion: SerializedTypeNode | undefined; diff --git a/src/compiler/transformers/utilities.ts b/src/compiler/transformers/utilities.ts index f5f8a298a49..6a07a9bb4b5 100644 --- a/src/compiler/transformers/utilities.ts +++ b/src/compiler/transformers/utilities.ts @@ -303,7 +303,7 @@ namespace ts { * @param node The class node. * @param isStatic A value indicating whether to get properties from the static or instance side of the class. */ - export function getInitializedProperties(node: ClassExpression | ClassDeclaration, isStatic: boolean): ReadonlyArray { + export function getInitializedProperties(node: ClassExpression | ClassDeclaration, isStatic: boolean): readonly PropertyDeclaration[] { return filter(node.members, isStatic ? isStaticInitializedProperty : isInstanceInitializedProperty); } diff --git a/src/compiler/tsbuild.ts b/src/compiler/tsbuild.ts index ff9f02faa83..da087dd422c 100644 --- a/src/compiler/tsbuild.ts +++ b/src/compiler/tsbuild.ts @@ -282,7 +282,7 @@ namespace ts { getNextInvalidatedProject(cancellationToken?: CancellationToken): InvalidatedProject | undefined; // Currently used for testing but can be made public if needed: - /*@internal*/ getBuildOrder(): ReadonlyArray; + /*@internal*/ getBuildOrder(): readonly ResolvedConfigFileName[]; // Testing only /*@internal*/ getUpToDateStatusOfProject(project: string): UpToDateStatus; @@ -332,11 +332,11 @@ namespace ts { return result; } - export function createSolutionBuilder(host: SolutionBuilderHost, rootNames: ReadonlyArray, defaultOptions: BuildOptions): SolutionBuilder { + export function createSolutionBuilder(host: SolutionBuilderHost, rootNames: readonly string[], defaultOptions: BuildOptions): SolutionBuilder { return createSolutionBuilderWorker(/*watch*/ false, host, rootNames, defaultOptions); } - export function createSolutionBuilderWithWatch(host: SolutionBuilderWithWatchHost, rootNames: ReadonlyArray, defaultOptions: BuildOptions): SolutionBuilder { + export function createSolutionBuilderWithWatch(host: SolutionBuilderWithWatchHost, rootNames: readonly string[], defaultOptions: BuildOptions): SolutionBuilder { return createSolutionBuilderWorker(/*watch*/ true, host, rootNames, defaultOptions); } @@ -362,7 +362,7 @@ namespace ts { // State of solution readonly options: BuildOptions; readonly baseCompilerOptions: CompilerOptions; - readonly rootNames: ReadonlyArray; + readonly rootNames: readonly string[]; readonly resolvedConfigFilePaths: Map; readonly configFileCache: ConfigFileMap; @@ -372,7 +372,7 @@ namespace ts { readonly extendedConfigCache: Map; readonly builderPrograms: ConfigFileMap; - readonly diagnostics: ConfigFileMap>; + readonly diagnostics: ConfigFileMap; readonly projectPendingBuild: ConfigFileMap; readonly projectErrorsReported: ConfigFileMap; @@ -380,7 +380,7 @@ namespace ts { readonly moduleResolutionCache: ModuleResolutionCache | undefined; // Mutable state - buildOrder: ReadonlyArray | undefined; + buildOrder: readonly ResolvedConfigFileName[] | undefined; readFileWithCache: (f: string) => string | undefined; projectCompilerOptions: CompilerOptions; cache: SolutionBuilderStateCache | undefined; @@ -403,7 +403,7 @@ namespace ts { writeLog: (s: string) => void; } - function createSolutionBuilderState(watch: boolean, hostOrHostWithWatch: SolutionBuilderHost | SolutionBuilderWithWatchHost, rootNames: ReadonlyArray, options: BuildOptions): SolutionBuilderState { + function createSolutionBuilderState(watch: boolean, hostOrHostWithWatch: SolutionBuilderHost | SolutionBuilderWithWatchHost, rootNames: readonly string[], options: BuildOptions): SolutionBuilderState { const host = hostOrHostWithWatch as SolutionBuilderHost; const hostWithWatch = hostOrHostWithWatch as SolutionBuilderWithWatchHost; const currentDirectory = host.getCurrentDirectory(); @@ -524,7 +524,7 @@ namespace ts { return resolveConfigFileProjectName(resolvePath(state.currentDirectory, name)); } - function createBuildOrder(state: SolutionBuilderState, roots: ReadonlyArray): ReadonlyArray { + function createBuildOrder(state: SolutionBuilderState, roots: readonly ResolvedConfigFileName[]): readonly ResolvedConfigFileName[] { const temporaryMarks = createMap() as ConfigFileMap; const permanentMarks = createMap() as ConfigFileMap; const circularityReportStack: string[] = []; @@ -726,7 +726,7 @@ namespace ts { readonly kind: InvalidatedProjectKind; readonly project: ResolvedConfigFileName; /*@internal*/ readonly projectPath: ResolvedConfigFilePath; - /*@internal*/ readonly buildOrder: ReadonlyArray; + /*@internal*/ readonly buildOrder: readonly ResolvedConfigFileName[]; /** * To dispose this project and ensure that all the necessary actions are taken and state is updated accordingly */ @@ -749,14 +749,14 @@ namespace ts { getBuilderProgram(): T | undefined; getProgram(): Program | undefined; getSourceFile(fileName: string): SourceFile | undefined; - getSourceFiles(): ReadonlyArray; - getOptionsDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; - getGlobalDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; - getConfigFileParsingDiagnostics(): ReadonlyArray; - getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; - getAllDependencies(sourceFile: SourceFile): ReadonlyArray; - getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; - getSemanticDiagnosticsOfNextAffectedFile(cancellationToken?: CancellationToken, ignoreSourceFile?: (sourceFile: SourceFile) => boolean): AffectedFileResult>; + getSourceFiles(): readonly SourceFile[]; + getOptionsDiagnostics(cancellationToken?: CancellationToken): readonly Diagnostic[]; + getGlobalDiagnostics(cancellationToken?: CancellationToken): readonly Diagnostic[]; + getConfigFileParsingDiagnostics(): readonly Diagnostic[]; + getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[]; + getAllDependencies(sourceFile: SourceFile): readonly string[]; + getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[]; + getSemanticDiagnosticsOfNextAffectedFile(cancellationToken?: CancellationToken, ignoreSourceFile?: (sourceFile: SourceFile) => boolean): AffectedFileResult; /* * Calling emit directly with targetSourceFile and emitOnlyDtsFiles set to true is not advised since * emit in build system is responsible in updating status of the project @@ -793,7 +793,7 @@ namespace ts { project: ResolvedConfigFileName, projectPath: ResolvedConfigFilePath, config: ParsedCommandLine, - buildOrder: ReadonlyArray + buildOrder: readonly ResolvedConfigFileName[] ): UpdateOutputFileStampsProject { let updateOutputFileStampsPending = true; return { @@ -823,7 +823,7 @@ namespace ts { projectPath: ResolvedConfigFilePath, projectIndex: number, config: ParsedCommandLine, - buildOrder: ReadonlyArray, + buildOrder: readonly ResolvedConfigFileName[], ): BuildInvalidedProject | UpdateBundleProject { enum Step { CreateProgram, @@ -928,7 +928,7 @@ namespace ts { return program && action(program); } - function withProgramOrEmptyArray(action: (program: T) => ReadonlyArray): ReadonlyArray { + function withProgramOrEmptyArray(action: (program: T) => readonly U[]): readonly U[] { return withProgramOrUndefined(action) || emptyArray; } @@ -969,7 +969,7 @@ namespace ts { step++; } - function handleDiagnostics(diagnostics: ReadonlyArray, errorFlags: BuildResultFlags, errorType: string) { + function handleDiagnostics(diagnostics: readonly Diagnostic[], errorFlags: BuildResultFlags, errorType: string) { if (diagnostics.length) { buildResult = buildErrors( state, @@ -1238,7 +1238,7 @@ namespace ts { function getNextInvalidatedProject( state: SolutionBuilderState, - buildOrder: ReadonlyArray, + buildOrder: readonly ResolvedConfigFileName[], reportQueue: boolean ): InvalidatedProject | undefined { if (!state.projectPendingBuild.size) return undefined; @@ -1364,7 +1364,7 @@ namespace ts { state: SolutionBuilderState, resolvedPath: ResolvedConfigFilePath, program: T | undefined, - diagnostics: ReadonlyArray, + diagnostics: readonly Diagnostic[], errorFlags: BuildResultFlags, errorType: string ) { @@ -1674,7 +1674,7 @@ namespace ts { projectPath: ResolvedConfigFilePath, projectIndex: number, config: ParsedCommandLine, - buildOrder: ReadonlyArray, + buildOrder: readonly ResolvedConfigFileName[], buildResult: BuildResultFlags ) { // Queue only if there are no errors @@ -1956,7 +1956,7 @@ namespace ts { ); } - function startWatching(state: SolutionBuilderState, buildOrder: ReadonlyArray) { + function startWatching(state: SolutionBuilderState, buildOrder: readonly ResolvedConfigFileName[]) { if (!state.watchAllProjectsPending) return; state.watchAllProjectsPending = false; for (const resolved of buildOrder) { @@ -1979,9 +1979,9 @@ namespace ts { * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but * can dynamically add/remove other projects based on changes on the rootNames' references */ - function createSolutionBuilderWorker(watch: false, host: SolutionBuilderHost, rootNames: ReadonlyArray, defaultOptions: BuildOptions): SolutionBuilder; - function createSolutionBuilderWorker(watch: true, host: SolutionBuilderWithWatchHost, rootNames: ReadonlyArray, defaultOptions: BuildOptions): SolutionBuilder; - function createSolutionBuilderWorker(watch: boolean, hostOrHostWithWatch: SolutionBuilderHost | SolutionBuilderWithWatchHost, rootNames: ReadonlyArray, options: BuildOptions): SolutionBuilder { + function createSolutionBuilderWorker(watch: false, host: SolutionBuilderHost, rootNames: readonly string[], defaultOptions: BuildOptions): SolutionBuilder; + function createSolutionBuilderWorker(watch: true, host: SolutionBuilderWithWatchHost, rootNames: readonly string[], defaultOptions: BuildOptions): SolutionBuilder; + function createSolutionBuilderWorker(watch: boolean, hostOrHostWithWatch: SolutionBuilderHost | SolutionBuilderWithWatchHost, rootNames: readonly string[], options: BuildOptions): SolutionBuilder { const state = createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options); return { build: (project, cancellationToken) => build(state, project, cancellationToken), @@ -2017,11 +2017,11 @@ namespace ts { } } - function reportErrors({ host }: SolutionBuilderState, errors: ReadonlyArray) { + function reportErrors({ host }: SolutionBuilderState, errors: readonly Diagnostic[]) { errors.forEach(err => host.reportDiagnostic(err)); } - function reportAndStoreErrors(state: SolutionBuilderState, proj: ResolvedConfigFilePath, errors: ReadonlyArray) { + function reportAndStoreErrors(state: SolutionBuilderState, proj: ResolvedConfigFilePath, errors: readonly Diagnostic[]) { reportErrors(state, errors); state.projectErrorsReported.set(proj, true); if (errors.length) { @@ -2033,7 +2033,7 @@ namespace ts { reportAndStoreErrors(state, proj, [state.configFileCache.get(proj) as Diagnostic]); } - function reportErrorSummary(state: SolutionBuilderState, buildOrder: ReadonlyArray) { + function reportErrorSummary(state: SolutionBuilderState, buildOrder: readonly ResolvedConfigFileName[]) { if (!state.needsSummary || (!state.watch && !state.host.reportErrorSummary)) return; state.needsSummary = false; const { diagnostics } = state; @@ -2057,7 +2057,7 @@ namespace ts { /** * Report the build ordering inferred from the current project graph if we're in verbose mode */ - function reportBuildQueue(state: SolutionBuilderState, buildQueue: ReadonlyArray) { + function reportBuildQueue(state: SolutionBuilderState, buildQueue: readonly ResolvedConfigFileName[]) { if (state.options.verbose) { reportStatus(state, Diagnostics.Projects_in_this_build_Colon_0, buildQueue.map(s => "\r\n * " + relName(state, s)).join("")); } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index e267082e45c..0cc967d7294 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -639,7 +639,7 @@ namespace ts { export interface JSDocContainer { /* @internal */ jsDoc?: JSDoc[]; // JSDoc that directly precedes this node - /* @internal */ jsDocCache?: ReadonlyArray; // Cache for getJSDocTags + /* @internal */ jsDocCache?: readonly JSDocTag[]; // Cache for getJSDocTags } export type HasJSDoc = @@ -2512,8 +2512,8 @@ namespace ts { export interface JSDocSignature extends JSDocType, Declaration { kind: SyntaxKind.JSDocSignature; - typeParameters?: ReadonlyArray; - parameters: ReadonlyArray; + typeParameters?: readonly JSDocTemplateTag[]; + parameters: readonly JSDocParameterTag[]; type: JSDocReturnTag | undefined; } @@ -2536,7 +2536,7 @@ namespace ts { export interface JSDocTypeLiteral extends JSDocType { kind: SyntaxKind.JSDocTypeLiteral; - jsDocPropertyTags?: ReadonlyArray; + jsDocPropertyTags?: readonly JSDocPropertyLikeTag[]; /** If true, then this type literal represents an *array* of its type. */ isArrayType?: boolean; } @@ -2642,7 +2642,7 @@ namespace ts { */ export interface SourceFileLike { readonly text: string; - lineMap?: ReadonlyArray; + lineMap?: readonly number[]; /* @internal */ getPositionOfLineAndCharacter?(line: number, character: number, allowEdits?: true): number; } @@ -2688,11 +2688,11 @@ namespace ts { */ /* @internal */ redirectInfo?: RedirectInfo; - amdDependencies: ReadonlyArray; + amdDependencies: readonly AmdDependency[]; moduleName?: string; - referencedFiles: ReadonlyArray; - typeReferenceDirectives: ReadonlyArray; - libReferenceDirectives: ReadonlyArray; + referencedFiles: readonly FileReference[]; + typeReferenceDirectives: readonly FileReference[]; + libReferenceDirectives: readonly FileReference[]; languageVariant: LanguageVariant; isDeclarationFile: boolean; @@ -2741,22 +2741,22 @@ namespace ts { /* @internal */ jsDocDiagnostics?: DiagnosticWithLocation[]; // Stores additional file-level diagnostics reported by the program - /* @internal */ additionalSyntacticDiagnostics?: ReadonlyArray; + /* @internal */ additionalSyntacticDiagnostics?: readonly DiagnosticWithLocation[]; // Stores a line map for the file. // This field should never be used directly to obtain line map, use getLineMap function instead. - /* @internal */ lineMap: ReadonlyArray; + /* @internal */ lineMap: readonly number[]; /* @internal */ classifiableNames?: ReadonlyUnderscoreEscapedMap; // Stores a mapping 'external module reference text' -> 'resolved file name' | undefined // It is used to resolve module names in the checker. // Content of this field should never be used directly - use getResolvedModuleFileName/setResolvedModuleFileName functions instead /* @internal */ resolvedModules?: Map; /* @internal */ resolvedTypeReferenceDirectiveNames: Map; - /* @internal */ imports: ReadonlyArray; + /* @internal */ imports: readonly StringLiteralLike[]; // Identifier only if `declare global` - /* @internal */ moduleAugmentations: ReadonlyArray; + /* @internal */ moduleAugmentations: (StringLiteral | Identifier)[]; /* @internal */ patternAmbientModules?: PatternAmbientModule[]; - /* @internal */ ambientModuleNames: ReadonlyArray; + /* @internal */ ambientModuleNames: readonly string[]; /* @internal */ checkJsDirective?: CheckJsDirective; /* @internal */ version: string; /* @internal */ pragmas: ReadonlyPragmaMap; @@ -2767,15 +2767,15 @@ namespace ts { } /*@internal*/ - export type ExportedModulesFromDeclarationEmit = ReadonlyArray; + export type ExportedModulesFromDeclarationEmit = readonly Symbol[]; export interface Bundle extends Node { kind: SyntaxKind.Bundle; - prepends: ReadonlyArray; - sourceFiles: ReadonlyArray; - /* @internal */ syntheticFileReferences?: ReadonlyArray; - /* @internal */ syntheticTypeReferences?: ReadonlyArray; - /* @internal */ syntheticLibReferences?: ReadonlyArray; + prepends: readonly (InputFiles | UnparsedSource)[]; + sourceFiles: readonly SourceFile[]; + /* @internal */ syntheticFileReferences?: readonly FileReference[]; + /* @internal */ syntheticTypeReferences?: readonly FileReference[]; + /* @internal */ syntheticLibReferences?: readonly FileReference[]; /* @internal */ hasNoDefaultLib?: boolean; } @@ -2798,19 +2798,19 @@ namespace ts { kind: SyntaxKind.UnparsedSource; fileName: string; text: string; - prologues: ReadonlyArray; - helpers: ReadonlyArray | undefined; + prologues: readonly UnparsedPrologue[]; + helpers: readonly UnscopedEmitHelper[] | undefined; // References and noDefaultLibAre Dts only - referencedFiles: ReadonlyArray; - typeReferenceDirectives: ReadonlyArray | undefined; - libReferenceDirectives: ReadonlyArray; + referencedFiles: readonly FileReference[]; + typeReferenceDirectives: readonly string[] | undefined; + libReferenceDirectives: readonly FileReference[]; hasNoDefaultLib?: boolean; sourceMapPath?: string; sourceMapText?: string; - syntheticReferences?: ReadonlyArray; - texts: ReadonlyArray; + syntheticReferences?: readonly UnparsedSyntheticReference[]; + texts: readonly UnparsedSourceText[]; /*@internal*/ oldFileOfCurrentEmit?: boolean; /*@internal*/ parsedSourceMap?: RawSourceMap | false | undefined; // Adding this to satisfy services, fix later @@ -2837,7 +2837,7 @@ namespace ts { kind: SyntaxKind.UnparsedPrepend; data: string; parent: UnparsedSource; - texts: ReadonlyArray; + texts: readonly UnparsedTextLike[]; } export interface UnparsedTextLike extends UnparsedSection { @@ -2879,7 +2879,7 @@ namespace ts { export interface ParseConfigHost { useCaseSensitiveFileNames: boolean; - readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): ReadonlyArray; + readDirectory(rootDir: string, extensions: readonly string[], excludes: readonly string[] | undefined, includes: readonly string[], depth?: number): readonly string[]; /** * Gets a value indicating whether the specified path exists and is a file. @@ -2903,7 +2903,7 @@ namespace ts { data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, - sourceFiles?: ReadonlyArray, + sourceFiles?: readonly SourceFile[], ) => void; export class OperationCanceledException { } @@ -2921,19 +2921,19 @@ namespace ts { /** * Get a list of root file names that were passed to a 'createProgram' */ - getRootFileNames(): ReadonlyArray; + getRootFileNames(): readonly string[]; /** * Get a list of files in the program */ - getSourceFiles(): ReadonlyArray; + getSourceFiles(): readonly SourceFile[]; /** * Get a list of file names that were passed to 'createProgram' or referenced in a * program source file but could not be located. */ /* @internal */ - getMissingFilePaths(): ReadonlyArray; + getMissingFilePaths(): readonly Path[]; /** * Emits the JavaScript and declaration files. If targetSourceFile is not specified, then @@ -2947,14 +2947,14 @@ namespace ts { */ emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult; - getOptionsDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; - getGlobalDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; - getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + getOptionsDiagnostics(cancellationToken?: CancellationToken): readonly Diagnostic[]; + getGlobalDiagnostics(cancellationToken?: CancellationToken): readonly Diagnostic[]; + getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly DiagnosticWithLocation[]; /** The first time this is called, it will return global diagnostics (no location). */ - getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; - getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; - getConfigFileParsingDiagnostics(): ReadonlyArray; - /* @internal */ getSuggestionDiagnostics(sourceFile: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[]; + getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly DiagnosticWithLocation[]; + getConfigFileParsingDiagnostics(): readonly Diagnostic[]; + /* @internal */ getSuggestionDiagnostics(sourceFile: SourceFile, cancellationToken?: CancellationToken): readonly DiagnosticWithLocation[]; /** * Gets a type checker that can be used to semantically analyze source files in the program. @@ -2996,8 +2996,8 @@ namespace ts { /* @internal */ getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined; - getProjectReferences(): ReadonlyArray | undefined; - getResolvedProjectReferences(): ReadonlyArray | undefined; + getProjectReferences(): readonly ProjectReference[] | undefined; + getResolvedProjectReferences(): readonly (ResolvedProjectReference | undefined)[] | undefined; /*@internal*/ getProjectReferenceRedirect(fileName: string): string | undefined; /*@internal*/ getResolvedProjectReferenceToRedirect(fileName: string): ResolvedProjectReference | undefined; /*@internal*/ forEachResolvedProjectReference(cb: (resolvedProjectReference: ResolvedProjectReference | undefined, resolvedProjectReferencePath: Path) => T | undefined): T | undefined; @@ -3007,12 +3007,12 @@ namespace ts { } /* @internal */ - export type RedirectTargetsMap = ReadonlyMap>; + export type RedirectTargetsMap = ReadonlyMap; export interface ResolvedProjectReference { commandLine: ParsedCommandLine; sourceFile: SourceFile; - references?: ReadonlyArray; + references?: readonly (ResolvedProjectReference | undefined)[]; } /* @internal */ @@ -3040,8 +3040,8 @@ namespace ts { /*@internal*/ export interface EmitTransformers { - scriptTransformers: ReadonlyArray>; - declarationTransformers: ReadonlyArray>; + scriptTransformers: readonly TransformerFactory[]; + declarationTransformers: readonly TransformerFactory[]; } export interface SourceMapSpan { @@ -3061,7 +3061,7 @@ namespace ts { /* @internal */ export interface SourceMapEmitResult { - inputSourceFileNames: ReadonlyArray; // Input source file (which one can use on program to get the file), 1:1 mapping with the sourceMap.sources list + inputSourceFileNames: readonly string[]; // Input source file (which one can use on program to get the file), 1:1 mapping with the sourceMap.sources list sourceMap: RawSourceMap; } @@ -3085,7 +3085,7 @@ namespace ts { export interface EmitResult { emitSkipped: boolean; /** Contains declaration emit diagnostics */ - diagnostics: ReadonlyArray; + diagnostics: readonly Diagnostic[]; emittedFiles?: string[]; // Array of files the compiler wrote to disk /* @internal */ sourceMaps?: SourceMapEmitResult[]; // Array of sourceMapData if compiler emitted sourcemaps /* @internal */ exportedModulesFromDeclarationEmit?: ExportedModulesFromDeclarationEmit; @@ -3095,7 +3095,7 @@ namespace ts { export interface TypeCheckerHost extends ModuleSpecifierResolutionHost { getCompilerOptions(): CompilerOptions; - getSourceFiles(): ReadonlyArray; + getSourceFiles(): readonly SourceFile[]; getSourceFile(fileName: string): SourceFile | undefined; getResolvedTypeReferenceDirectives(): ReadonlyMap; getProjectReferenceRedirect(fileName: string): string | undefined; @@ -3110,7 +3110,7 @@ namespace ts { getPropertyOfType(type: Type, propertyName: string): Symbol | undefined; /* @internal */ getTypeOfPropertyOfType(type: Type, propertyName: string): Type | undefined; getIndexInfoOfType(type: Type, kind: IndexKind): IndexInfo | undefined; - getSignaturesOfType(type: Type, kind: SignatureKind): ReadonlyArray; + getSignaturesOfType(type: Type, kind: SignatureKind): readonly Signature[]; getIndexTypeOfType(type: Type, kind: IndexKind): Type | undefined; getBaseTypes(type: InterfaceType): BaseType[]; getBaseTypeOfLiteralType(type: Type): Type; @@ -3182,7 +3182,7 @@ namespace ts { getFullyQualifiedName(symbol: Symbol): string; getAugmentedPropertiesOfType(type: Type): Symbol[]; - getRootSymbols(symbol: Symbol): ReadonlyArray; + getRootSymbols(symbol: Symbol): readonly Symbol[]; getContextualType(node: Expression): Type | undefined; /* @internal */ getContextualTypeForObjectLiteralElement(element: ObjectLiteralElementLike): Type | undefined; /* @internal */ getContextualTypeForArgumentAtIndex(call: CallLikeExpression, argIndex: number): Type | undefined; @@ -3196,7 +3196,7 @@ namespace ts { */ getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[], argumentCount?: number): Signature | undefined; /* @internal */ getResolvedSignatureForSignatureHelp(node: CallLikeExpression, candidatesOutArray?: Signature[], argumentCount?: number): Signature | undefined; - /* @internal */ getExpandedParameters(sig: Signature): ReadonlyArray; + /* @internal */ getExpandedParameters(sig: Signature): readonly Symbol[]; /* @internal */ hasEffectiveRestParameter(sig: Signature): boolean; getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined; isImplementationOfOverload(node: SignatureDeclaration): boolean | undefined; @@ -3294,7 +3294,7 @@ namespace ts { * So for `{ a } | { b }`, this will include both `a` and `b`. * Does not include properties of primitive types. */ - /* @internal */ getAllPossiblePropertiesOfTypes(type: ReadonlyArray): Symbol[]; + /* @internal */ getAllPossiblePropertiesOfTypes(type: readonly Type[]): Symbol[]; /* @internal */ resolveName(name: string, location: Node, meaning: SymbolFlags, excludeGlobals: boolean): Symbol | undefined; /* @internal */ getJsxNamespace(location?: Node): string; @@ -3322,7 +3322,7 @@ namespace ts { * Does *not* get *all* suggestion diagnostics, just the ones that were convenient to report in the checker. * Others are added in computeSuggestionDiagnostics. */ - /* @internal */ getSuggestionDiagnostics(file: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + /* @internal */ getSuggestionDiagnostics(file: SourceFile, cancellationToken?: CancellationToken): readonly DiagnosticWithLocation[]; /** * Depending on the operation performed, it may be appropriate to throw away the checker @@ -3331,7 +3331,7 @@ namespace ts { */ runWithCancellationToken(token: CancellationToken, cb: (checker: TypeChecker) => T): T; - /* @internal */ getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol: Symbol): ReadonlyArray | undefined; + /* @internal */ getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol: Symbol): readonly TypeParameter[] | undefined; } /* @internal */ @@ -3450,9 +3450,9 @@ namespace ts { /* @internal */ export interface SymbolWalker { /** Note: Return values are not ordered. */ - walkType(root: Type): { visitedTypes: ReadonlyArray, visitedSymbols: ReadonlyArray }; + walkType(root: Type): { visitedTypes: readonly Type[], visitedSymbols: readonly Symbol[] }; /** Note: Return values are not ordered. */ - walkSymbol(root: Symbol): { visitedTypes: ReadonlyArray, visitedSymbols: ReadonlyArray }; + walkSymbol(root: Symbol): { visitedTypes: readonly Type[], visitedSymbols: readonly Symbol[] }; } // This was previously deprecated in our public API, but is still used internally @@ -4038,7 +4038,7 @@ namespace ts { symbol: Symbol; // Symbol associated with type (if any) pattern?: DestructuringPattern; // Destructuring pattern represented by type (if any) aliasSymbol?: Symbol; // Alias associated with type - aliasTypeArguments?: ReadonlyArray; // Alias type arguments (if any) + aliasTypeArguments?: readonly Type[]; // Alias type arguments (if any) /* @internal */ aliasTypeArgumentsContainsMarker?: boolean; // Alias type arguments (if any) /* @internal */ permissiveInstantiation?: Type; // Instantiation with type parameters mapped to wildcard type @@ -4143,8 +4143,8 @@ namespace ts { objectFlags: ObjectFlags; /* @internal */ members?: SymbolTable; // Properties by name /* @internal */ properties?: Symbol[]; // Properties - /* @internal */ callSignatures?: ReadonlyArray; // Call signatures of type - /* @internal */ constructSignatures?: ReadonlyArray; // Construct signatures of type + /* @internal */ callSignatures?: readonly Signature[]; // Call signatures of type + /* @internal */ constructSignatures?: readonly Signature[]; // Construct signatures of type /* @internal */ stringIndexInfo?: IndexInfo; // String indexing info /* @internal */ numberIndexInfo?: IndexInfo; // Numeric indexing info } @@ -4184,7 +4184,7 @@ namespace ts { */ export interface TypeReference extends ObjectType { target: GenericType; // Type reference target - typeArguments?: ReadonlyArray; // Type reference type arguments (undefined if none) + typeArguments?: readonly Type[]; // Type reference type arguments (undefined if none) /* @internal */ literalType?: TypeReference; // Clone of type with ObjectFlags.ArrayLiteral set } @@ -4285,8 +4285,8 @@ namespace ts { export interface ResolvedType extends ObjectType, UnionOrIntersectionType { members: SymbolTable; // Properties by name properties: Symbol[]; // Properties - callSignatures: ReadonlyArray; // Call signatures of type - constructSignatures: ReadonlyArray; // Construct signatures of type + callSignatures: readonly Signature[]; // Call signatures of type + constructSignatures: readonly Signature[]; // Construct signatures of type } /* @internal */ @@ -4429,8 +4429,8 @@ namespace ts { export interface Signature { declaration?: SignatureDeclaration | JSDocSignature; // Originating declaration - typeParameters?: ReadonlyArray; // Type parameters (undefined if non-generic) - parameters: ReadonlyArray; // Parameters + typeParameters?: readonly TypeParameter[]; // Type parameters (undefined if non-generic) + parameters: readonly Symbol[]; // Parameters /* @internal */ thisParameter?: Symbol; // symbol of this-type parameter /* @internal */ @@ -4537,7 +4537,7 @@ namespace ts { mapper: TypeMapper; // Mapper that fixes inferences nonFixingMapper: TypeMapper; // Mapper that doesn't fix inferences returnMapper?: TypeMapper; // Type mapper for inferences from return types (if any) - inferredTypeParameters?: ReadonlyArray; // Inferred type parameters for function result + inferredTypeParameters?: readonly TypeParameter[]; // Inferred type parameters for function result } /* @internal */ @@ -4846,7 +4846,7 @@ namespace ts { options: CompilerOptions; typeAcquisition?: TypeAcquisition; fileNames: string[]; - projectReferences?: ReadonlyArray; + projectReferences?: readonly ProjectReference[]; raw?: any; errors: Diagnostic[]; wildcardDirectories?: MapLike; @@ -4861,17 +4861,17 @@ namespace ts { /* @internal */ export interface ConfigFileSpecs { - filesSpecs: ReadonlyArray | undefined; + filesSpecs: readonly string[] | undefined; /** * Present to report errors (user specified specs), validatedIncludeSpecs are used for file name matching */ - includeSpecs?: ReadonlyArray; + includeSpecs?: readonly string[]; /** * Present to report errors (user specified specs), validatedExcludeSpecs are used for file name matching */ - excludeSpecs?: ReadonlyArray; - validatedIncludeSpecs?: ReadonlyArray; - validatedExcludeSpecs?: ReadonlyArray; + excludeSpecs?: readonly string[]; + validatedIncludeSpecs?: readonly string[]; + validatedExcludeSpecs?: readonly string[]; wildcardDirectories: MapLike; } @@ -4882,12 +4882,12 @@ namespace ts { } export interface CreateProgramOptions { - rootNames: ReadonlyArray; + rootNames: readonly string[]; options: CompilerOptions; - projectReferences?: ReadonlyArray; + projectReferences?: readonly ProjectReference[]; host?: CompilerHost; oldProgram?: Program; - configFileParsingDiagnostics?: ReadonlyArray; + configFileParsingDiagnostics?: readonly Diagnostic[]; } /* @internal */ @@ -5154,7 +5154,7 @@ namespace ts { export interface ResolvedModuleWithFailedLookupLocations { readonly resolvedModule: ResolvedModuleFull | undefined; /* @internal */ - readonly failedLookupLocations: ReadonlyArray; + readonly failedLookupLocations: readonly string[]; } export interface ResolvedTypeReferenceDirective { @@ -5169,7 +5169,7 @@ namespace ts { export interface ResolvedTypeReferenceDirectiveWithFailedLookupLocations { readonly resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective | undefined; - readonly failedLookupLocations: ReadonlyArray; + readonly failedLookupLocations: readonly string[]; } /* @internal */ @@ -5186,7 +5186,7 @@ namespace ts { getCanonicalFileName(fileName: string): string; useCaseSensitiveFileNames(): boolean; getNewLine(): string; - readDirectory?(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): string[]; + readDirectory?(rootDir: string, extensions: readonly string[], excludes: readonly string[] | undefined, includes: readonly string[], depth?: number): string[]; /* * CompilerHost must either implement resolveModuleNames (in case if it wants to be completely in charge of @@ -5296,7 +5296,7 @@ namespace ts { export interface SourceMapSource { fileName: string; text: string; - /* @internal */ lineMap: ReadonlyArray; + /* @internal */ lineMap: readonly number[]; skipTrivia?: (pos: number) => number; } @@ -5421,7 +5421,7 @@ namespace ts { /* @internal */ export interface EmitHost extends ScriptReferenceHost, ModuleSpecifierResolutionHost { - getSourceFiles(): ReadonlyArray; + getSourceFiles(): readonly SourceFile[]; useCaseSensitiveFileNames(): boolean; getCurrentDirectory(): string; @@ -5435,7 +5435,7 @@ namespace ts { isEmitBlocked(emitFileName: string): boolean; - getPrependNodes(): ReadonlyArray; + getPrependNodes(): readonly (InputFiles | UnparsedSource)[]; writeFile: WriteFileCallback; getProgramBuildInfo(): ProgramBuildInfo | undefined; @@ -5696,7 +5696,7 @@ namespace ts { js?: BundleFileInfo; dts?: BundleFileInfo; commonSourceDirectory: string; - sourceFiles: ReadonlyArray; + sourceFiles: readonly string[]; } /* @internal */ @@ -5793,7 +5793,7 @@ namespace ts { */ /* @internal */ export interface SourceMapGenerator { - getSources(): ReadonlyArray; + getSources(): readonly string[]; /** * Adds a source to the source map. */ @@ -5888,7 +5888,7 @@ namespace ts { reportPrivateInBaseOfClassExpression?(propertyName: string): void; reportInaccessibleUniqueSymbolError?(): void; reportLikelyUnsafeImportRequiredError?(specifier: string): void; - moduleResolverHost?: ModuleSpecifierResolutionHost & { getSourceFiles(): ReadonlyArray, getCommonSourceDirectory(): string }; + moduleResolverHost?: ModuleSpecifierResolutionHost & { getSourceFiles(): readonly SourceFile[], getCommonSourceDirectory(): string }; trackReferencedAmbientModule?(decl: ModuleDeclaration, symbol: Symbol): void; trackExternalModuleSymbolOfImportTypeNode?(symbol: Symbol): void; } @@ -6100,7 +6100,7 @@ namespace ts { (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never; /* @internal */ - type ArgumentDefinitionToFieldUnion>> = { + type ArgumentDefinitionToFieldUnion[]> = { [K in keyof T]: PragmaArgTypeOptional }[Extract]; // The mapped type maps over only the tuple members, but this reindex gets _all_ members - by extracting only `number` keys, we get only the tuple members @@ -6109,7 +6109,7 @@ namespace ts { */ /* @internal */ type PragmaArgumentType = - ConcretePragmaSpecs[KPrag] extends { args: ReadonlyArray> } + ConcretePragmaSpecs[KPrag] extends { args: readonly PragmaArgumentSpecification[] } ? UnionToIntersection> : never; diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 9c0e71e28ea..5932b574d87 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -6,7 +6,7 @@ namespace ts { return pathIsRelative(moduleName) || isRootedDiskPath(moduleName); } - export function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): SortedReadonlyArray { + export function sortAndDeduplicateDiagnostics(diagnostics: readonly T[]): SortedReadonlyArray { return sortAndDeduplicate(diagnostics, compareDiagnostics); } } @@ -44,7 +44,7 @@ namespace ts { return !!map && !!map.size; } - export function createSymbolTable(symbols?: ReadonlyArray): SymbolTable { + export function createSymbolTable(symbols?: readonly Symbol[]): SymbolTable { const result = createMap() as SymbolTable; if (symbols) { for (const symbol of symbols) { @@ -189,10 +189,10 @@ namespace ts { * * @param array the array of input elements. */ - export function arrayToSet(array: ReadonlyArray): Map; - export function arrayToSet(array: ReadonlyArray, makeKey: (value: T) => string | undefined): Map; - export function arrayToSet(array: ReadonlyArray, makeKey: (value: T) => __String | undefined): UnderscoreEscapedMap; - export function arrayToSet(array: ReadonlyArray, makeKey?: (value: any) => string | __String | undefined): Map | UnderscoreEscapedMap { + export function arrayToSet(array: readonly string[]): Map; + export function arrayToSet(array: readonly T[], makeKey: (value: T) => string | undefined): Map; + export function arrayToSet(array: readonly T[], makeKey: (value: T) => __String | undefined): UnderscoreEscapedMap; + export function arrayToSet(array: readonly any[], makeKey?: (value: any) => string | __String | undefined): Map | UnderscoreEscapedMap { return arrayToMap(array, makeKey || (s => s), () => true); } @@ -269,8 +269,8 @@ namespace ts { } export function hasChangesInResolutions( - names: ReadonlyArray, - newResolutions: ReadonlyArray, + names: readonly string[], + newResolutions: readonly T[], oldResolutions: ReadonlyMap | undefined, comparer: (oldResolution: T, newResolution: T) => boolean): boolean { Debug.assert(names.length === newResolutions.length); @@ -407,7 +407,7 @@ namespace ts { return !nodeIsMissing(node); } - function insertStatementsAfterPrologue(to: T[], from: ReadonlyArray | undefined, isPrologueDirective: (node: Node) => boolean): T[] { + function insertStatementsAfterPrologue(to: T[], from: readonly T[] | undefined, isPrologueDirective: (node: Node) => boolean): T[] { if (from === undefined || from.length === 0) return to; let statementIndex = 0; // skip all prologue directives to insert at the correct position @@ -441,11 +441,11 @@ namespace ts { /** * Prepends statements to an array while taking care of prologue directives. */ - export function insertStatementsAfterStandardPrologue(to: T[], from: ReadonlyArray | undefined): T[] { + export function insertStatementsAfterStandardPrologue(to: T[], from: readonly T[] | undefined): T[] { return insertStatementsAfterPrologue(to, from, isPrologueDirective); } - export function insertStatementsAfterCustomPrologue(to: T[], from: ReadonlyArray | undefined): T[] { + export function insertStatementsAfterCustomPrologue(to: T[], from: readonly T[] | undefined): T[] { return insertStatementsAfterPrologue(to, from, isAnyPrologueDirective); } @@ -555,7 +555,7 @@ namespace ts { * Note: it is expected that the `nodeArray` and the `node` are within the same file. * For example, searching for a `SourceFile` in a `SourceFile[]` wouldn't work. */ - export function indexOfNode(nodeArray: ReadonlyArray, node: Node) { + export function indexOfNode(nodeArray: readonly Node[], node: Node) { return binarySearch(nodeArray, node, getPos, compareValues); } @@ -1308,7 +1308,7 @@ namespace ts { return predicate && predicate.kind === TypePredicateKind.This; } - export function getPropertyAssignment(objectLiteral: ObjectLiteralExpression, key: string, key2?: string): ReadonlyArray { + export function getPropertyAssignment(objectLiteral: ObjectLiteralExpression, key: string, key2?: string): readonly PropertyAssignment[] { return objectLiteral.properties.filter((property): property is PropertyAssignment => { if (property.kind === SyntaxKind.PropertyAssignment) { const propName = getTextOfPropertyName(property.name); @@ -1332,7 +1332,7 @@ namespace ts { undefined); } - export function getTsConfigPropArray(tsConfigSourceFile: TsConfigSourceFile | undefined, propKey: string): ReadonlyArray { + export function getTsConfigPropArray(tsConfigSourceFile: TsConfigSourceFile | undefined, propKey: string): readonly PropertyAssignment[] { const jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile); return jsonObjectLiteral ? getPropertyAssignment(jsonObjectLiteral, propKey) : emptyArray; } @@ -2206,7 +2206,7 @@ namespace ts { : undefined; } - export function getJSDocCommentsAndTags(hostNode: Node): ReadonlyArray { + export function getJSDocCommentsAndTags(hostNode: Node): readonly (JSDoc | JSDocTag)[] { let result: (JSDoc | JSDocTag)[] | undefined; // Pull parameter comments from declaring function as well if (isVariableLike(hostNode) && hasInitializer(hostNode) && hasJSDocNodes(hostNode.initializer!)) { @@ -2597,7 +2597,7 @@ namespace ts { } /** Returns the node in an `extends` or `implements` clause of a class or interface. */ - export function getAllSuperTypeNodes(node: Node): ReadonlyArray { + export function getAllSuperTypeNodes(node: Node): readonly TypeNode[] { return isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || emptyArray : isClassLike(node) ? concatenate(singleElementArray(getEffectiveBaseTypeNode(node)), getClassImplementsHeritageClauseElements(node)) || emptyArray : emptyArray; @@ -3464,7 +3464,7 @@ namespace ts { * @param host An EmitHost. * @param targetSourceFile An optional target source file to emit. */ - export function getSourceFilesToEmit(host: EmitHost, targetSourceFile?: SourceFile): ReadonlyArray { + export function getSourceFilesToEmit(host: EmitHost, targetSourceFile?: SourceFile): readonly SourceFile[] { const options = host.getCompilerOptions(); const isSourceFileFromExternalLibrary = (file: SourceFile) => host.isSourceFileFromExternalLibrary(file); const getResolvedProjectReferenceToRedirect = (fileName: string) => host.getResolvedProjectReferenceToRedirect(fileName); @@ -3505,7 +3505,7 @@ namespace ts { return combinePaths(newDirPath, sourceFilePath); } - export function writeFile(host: { writeFile: WriteFileCallback; }, diagnostics: DiagnosticCollection, fileName: string, data: string, writeByteOrderMark: boolean, sourceFiles?: ReadonlyArray) { + export function writeFile(host: { writeFile: WriteFileCallback; }, diagnostics: DiagnosticCollection, fileName: string, data: string, writeByteOrderMark: boolean, sourceFiles?: readonly SourceFile[]) { host.writeFile(fileName, data, writeByteOrderMark, hostErrorMessage => { diagnostics.add(createCompilerDiagnostic(Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); }, sourceFiles); @@ -3515,7 +3515,7 @@ namespace ts { return getLineAndCharacterOfPosition(currentSourceFile, pos).line; } - export function getLineOfLocalPositionFromLineMap(lineMap: ReadonlyArray, pos: number) { + export function getLineOfLocalPositionFromLineMap(lineMap: readonly number[], pos: number) { return computeLineAndCharacterOfPosition(lineMap, pos).line; } @@ -3633,7 +3633,7 @@ namespace ts { node.type || (isInJSFile(node) ? getJSDocReturnType(node) : undefined); } - export function getJSDocTypeParameterDeclarations(node: DeclarationWithTypeParameters): ReadonlyArray { + export function getJSDocTypeParameterDeclarations(node: DeclarationWithTypeParameters): readonly TypeParameterDeclaration[] { return flatMap(getJSDocTags(node), tag => isNonTypeAliasTemplate(tag) ? tag.typeParameters : undefined); } @@ -3651,11 +3651,11 @@ namespace ts { return parameter && getEffectiveTypeAnnotationNode(parameter); } - export function emitNewLineBeforeLeadingComments(lineMap: ReadonlyArray, writer: EmitTextWriter, node: TextRange, leadingComments: ReadonlyArray | undefined) { + export function emitNewLineBeforeLeadingComments(lineMap: readonly number[], writer: EmitTextWriter, node: TextRange, leadingComments: readonly CommentRange[] | undefined) { emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments); } - export function emitNewLineBeforeLeadingCommentsOfPosition(lineMap: ReadonlyArray, writer: EmitTextWriter, pos: number, leadingComments: ReadonlyArray | undefined) { + export function emitNewLineBeforeLeadingCommentsOfPosition(lineMap: readonly number[], writer: EmitTextWriter, pos: number, leadingComments: readonly CommentRange[] | undefined) { // If the leading comments start on different line than the start of node, write new line if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos && getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) { @@ -3663,7 +3663,7 @@ namespace ts { } } - export function emitNewLineBeforeLeadingCommentOfPosition(lineMap: ReadonlyArray, writer: EmitTextWriter, pos: number, commentPos: number) { + export function emitNewLineBeforeLeadingCommentOfPosition(lineMap: readonly number[], writer: EmitTextWriter, pos: number, commentPos: number) { // If the leading comments start on different line than the start of node, write new line if (pos !== commentPos && getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) { @@ -3673,13 +3673,13 @@ namespace ts { export function emitComments( text: string, - lineMap: ReadonlyArray, + lineMap: readonly number[], writer: EmitTextWriter, - comments: ReadonlyArray | undefined, + comments: readonly CommentRange[] | undefined, leadingSeparator: boolean, trailingSeparator: boolean, newLine: string, - writeComment: (text: string, lineMap: ReadonlyArray, writer: EmitTextWriter, commentPos: number, commentEnd: number, newLine: string) => void) { + writeComment: (text: string, lineMap: readonly number[], writer: EmitTextWriter, commentPos: number, commentEnd: number, newLine: string) => void) { if (comments && comments.length > 0) { if (leadingSeparator) { writer.writeSpace(" "); @@ -3711,8 +3711,8 @@ namespace ts { * Detached comment is a comment at the top of file or function body that is separated from * the next statement by space. */ - export function emitDetachedComments(text: string, lineMap: ReadonlyArray, writer: EmitTextWriter, - writeComment: (text: string, lineMap: ReadonlyArray, writer: EmitTextWriter, commentPos: number, commentEnd: number, newLine: string) => void, + export function emitDetachedComments(text: string, lineMap: readonly number[], writer: EmitTextWriter, + writeComment: (text: string, lineMap: readonly number[], writer: EmitTextWriter, commentPos: number, commentEnd: number, newLine: string) => void, node: TextRange, newLine: string, removeComments: boolean) { let leadingComments: CommentRange[] | undefined; let currentDetachedCommentInfo: { nodePos: number, detachedCommentEndPos: number } | undefined; @@ -3775,7 +3775,7 @@ namespace ts { } - export function writeCommentRange(text: string, lineMap: ReadonlyArray, writer: EmitTextWriter, commentPos: number, commentEnd: number, newLine: string) { + export function writeCommentRange(text: string, lineMap: readonly number[], writer: EmitTextWriter, commentPos: number, commentEnd: number, newLine: string) { if (text.charCodeAt(commentPos + 1) === CharacterCodes.asterisk) { const firstCommentLineAndCharacter = computeLineAndCharacterOfPosition(lineMap, commentPos); const lineCount = lineMap.length; @@ -4786,7 +4786,7 @@ namespace ts { * This function will then merge those changes into a single change range valid between V1 and * Vn. */ - export function collapseTextChangeRangesAcrossMultipleVersions(changes: ReadonlyArray): TextChangeRange { + export function collapseTextChangeRangesAcrossMultipleVersions(changes: readonly TextChangeRange[]): TextChangeRange { if (changes.length === 0) { return unchangedTextChangeRange; } @@ -5262,7 +5262,7 @@ namespace ts { * * For binding patterns, parameter tags are matched by position. */ - export function getJSDocParameterTags(param: ParameterDeclaration): ReadonlyArray { + export function getJSDocParameterTags(param: ParameterDeclaration): readonly JSDocParameterTag[] { if (param.name) { if (isIdentifier(param.name)) { const name = param.name.escapedText; @@ -5291,7 +5291,7 @@ namespace ts { * node are returned first, so in the previous example, the template * tag on the containing function expression would be first. */ - export function getJSDocTypeParameterTags(param: TypeParameterDeclaration): ReadonlyArray { + export function getJSDocTypeParameterTags(param: TypeParameterDeclaration): readonly JSDocTemplateTag[] { const name = param.name.escapedText; return getJSDocTags(param.parent).filter((tag): tag is JSDocTemplateTag => isJSDocTemplateTag(tag) && tag.typeParameters.some(tp => tp.name.escapedText === name)); @@ -5392,7 +5392,7 @@ namespace ts { } /** Get all JSDoc tags related to a node, including those on parent nodes. */ - export function getJSDocTags(node: Node): ReadonlyArray { + export function getJSDocTags(node: Node): readonly JSDocTag[] { let tags = (node as JSDocContainer).jsDocCache; // If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing. if (tags === undefined) { @@ -5409,7 +5409,7 @@ namespace ts { } /** Gets all JSDoc tags of a specified kind, or undefined if not present. */ - export function getAllJSDocTagsOfKind(node: Node, kind: SyntaxKind): ReadonlyArray { + export function getAllJSDocTagsOfKind(node: Node, kind: SyntaxKind): readonly JSDocTag[] { return getJSDocTags(node).filter(doc => doc.kind === kind); } @@ -5417,7 +5417,7 @@ namespace ts { * Gets the effective type parameters. If the node was parsed in a * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. */ - export function getEffectiveTypeParameterDeclarations(node: DeclarationWithTypeParameters): ReadonlyArray { + export function getEffectiveTypeParameterDeclarations(node: DeclarationWithTypeParameters): readonly TypeParameterDeclaration[] { if (isJSDocSignature(node)) { return emptyArray; } @@ -6221,7 +6221,7 @@ namespace ts { // Node Arrays /* @internal */ - export function isNodeArray(array: ReadonlyArray): array is NodeArray { + export function isNodeArray(array: readonly T[]): array is NodeArray { return array.hasOwnProperty("pos") && array.hasOwnProperty("end"); } @@ -7607,7 +7607,7 @@ namespace ts { * Reduce an array of path components to a more simplified path by navigating any * `"."` or `".."` entries in the path. */ - export function reducePathComponents(components: ReadonlyArray) { + export function reducePathComponents(components: readonly string[]) { if (!some(components)) return []; const reduced = [components[0]]; for (let i = 1; i < components.length; i++) { @@ -7646,7 +7646,7 @@ namespace ts { * Formats a parsed path consisting of a root component (at index 0) and zero or more path * segments (at indices > 0). */ - export function getPathFromPathComponents(pathComponents: ReadonlyArray) { + export function getPathFromPathComponents(pathComponents: readonly string[]) { if (pathComponents.length === 0) return ""; const root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]); @@ -7657,7 +7657,7 @@ namespace ts { return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory)); } - function getPathWithoutRoot(pathComponents: ReadonlyArray) { + function getPathWithoutRoot(pathComponents: readonly string[]) { if (pathComponents.length === 0) return ""; return pathComponents.slice(1).join(directorySeparator); } @@ -7756,8 +7756,8 @@ namespace ts { * getBaseFileName("/path/to/file.js", ".ext", true) === "file.js" * ``` */ - export function getBaseFileName(path: string, extensions: string | ReadonlyArray, ignoreCase: boolean): string; - export function getBaseFileName(path: string, extensions?: string | ReadonlyArray, ignoreCase?: boolean) { + export function getBaseFileName(path: string, extensions: string | readonly string[], ignoreCase: boolean): string; + export function getBaseFileName(path: string, extensions?: string | readonly string[], ignoreCase?: boolean) { path = normalizeSlashes(path); // if the path provided is itself the root, then it has not file name. @@ -7964,7 +7964,7 @@ namespace ts { return stringContains(getBaseFileName(fileName), "."); } - export const commonPackageFolders: ReadonlyArray = ["node_modules", "bower_components", "jspm_packages"]; + export const commonPackageFolders: readonly string[] = ["node_modules", "bower_components", "jspm_packages"]; const implicitExcludePathRegexPattern = `(?!(${commonPackageFolders.join("|")})(/|$))`; @@ -8012,7 +8012,7 @@ namespace ts { exclude: excludeMatcher }; - export function getRegularExpressionForWildcard(specs: ReadonlyArray | undefined, basePath: string, usage: "files" | "directories" | "exclude"): string | undefined { + export function getRegularExpressionForWildcard(specs: readonly string[] | undefined, basePath: string, usage: "files" | "directories" | "exclude"): string | undefined { const patterns = getRegularExpressionsForWildcards(specs, basePath, usage); if (!patterns || !patterns.length) { return undefined; @@ -8024,7 +8024,7 @@ namespace ts { return `^(${pattern})${terminator}`; } - export function getRegularExpressionsForWildcards(specs: ReadonlyArray | undefined, basePath: string, usage: "files" | "directories" | "exclude"): ReadonlyArray | undefined { + export function getRegularExpressionsForWildcards(specs: readonly string[] | undefined, basePath: string, usage: "files" | "directories" | "exclude"): readonly string[] | undefined { if (specs === undefined || specs.length === 0) { return undefined; } @@ -8122,22 +8122,22 @@ namespace ts { } export interface FileSystemEntries { - readonly files: ReadonlyArray; - readonly directories: ReadonlyArray; + readonly files: readonly string[]; + readonly directories: readonly string[]; } export interface FileMatcherPatterns { /** One pattern for each "include" spec. */ - includeFilePatterns: ReadonlyArray | undefined; + includeFilePatterns: readonly string[] | undefined; /** One pattern matching one of any of the "include" specs. */ includeFilePattern: string | undefined; includeDirectoryPattern: string | undefined; excludePattern: string | undefined; - basePaths: ReadonlyArray; + basePaths: readonly string[]; } /** @param path directory of the tsconfig.json */ - export function getFileMatcherPatterns(path: string, excludes: ReadonlyArray | undefined, includes: ReadonlyArray | undefined, useCaseSensitiveFileNames: boolean, currentDirectory: string): FileMatcherPatterns { + export function getFileMatcherPatterns(path: string, excludes: readonly string[] | undefined, includes: readonly string[] | undefined, useCaseSensitiveFileNames: boolean, currentDirectory: string): FileMatcherPatterns { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); const absolutePath = combinePaths(currentDirectory, path); @@ -8156,7 +8156,7 @@ namespace ts { } /** @param path directory of the tsconfig.json */ - export function matchFiles(path: string, extensions: ReadonlyArray | undefined, excludes: ReadonlyArray | undefined, includes: ReadonlyArray | undefined, useCaseSensitiveFileNames: boolean, currentDirectory: string, depth: number | undefined, getFileSystemEntries: (path: string) => FileSystemEntries, realpath: (path: string) => string): string[] { + export function matchFiles(path: string, extensions: readonly string[] | undefined, excludes: readonly string[] | undefined, includes: readonly string[] | undefined, useCaseSensitiveFileNames: boolean, currentDirectory: string, depth: number | undefined, getFileSystemEntries: (path: string) => FileSystemEntries, realpath: (path: string) => string): string[] { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); @@ -8220,7 +8220,7 @@ namespace ts { /** * Computes the unique non-wildcard base paths amongst the provided include patterns. */ - function getBasePaths(path: string, includes: ReadonlyArray | undefined, useCaseSensitiveFileNames: boolean): string[] { + function getBasePaths(path: string, includes: readonly string[] | undefined, useCaseSensitiveFileNames: boolean): string[] { // Storage for our results in the form of literal paths (e.g. the paths as written by the user). const basePaths: string[] = [path]; @@ -8292,18 +8292,18 @@ namespace ts { /** * List of supported extensions in order of file resolution precedence. */ - export const supportedTSExtensions: ReadonlyArray = [Extension.Ts, Extension.Tsx, Extension.Dts]; - export const supportedTSExtensionsWithJson: ReadonlyArray = [Extension.Ts, Extension.Tsx, Extension.Dts, Extension.Json]; + export const supportedTSExtensions: readonly Extension[] = [Extension.Ts, Extension.Tsx, Extension.Dts]; + export const supportedTSExtensionsWithJson: readonly Extension[] = [Extension.Ts, Extension.Tsx, Extension.Dts, Extension.Json]; /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ - export const supportedTSExtensionsForExtractExtension: ReadonlyArray = [Extension.Dts, Extension.Ts, Extension.Tsx]; - export const supportedJSExtensions: ReadonlyArray = [Extension.Js, Extension.Jsx]; - export const supportedJSAndJsonExtensions: ReadonlyArray = [Extension.Js, Extension.Jsx, Extension.Json]; - const allSupportedExtensions: ReadonlyArray = [...supportedTSExtensions, ...supportedJSExtensions]; - const allSupportedExtensionsWithJson: ReadonlyArray = [...supportedTSExtensions, ...supportedJSExtensions, Extension.Json]; + export const supportedTSExtensionsForExtractExtension: readonly Extension[] = [Extension.Dts, Extension.Ts, Extension.Tsx]; + export const supportedJSExtensions: readonly Extension[] = [Extension.Js, Extension.Jsx]; + export const supportedJSAndJsonExtensions: readonly Extension[] = [Extension.Js, Extension.Jsx, Extension.Json]; + const allSupportedExtensions: readonly Extension[] = [...supportedTSExtensions, ...supportedJSExtensions]; + const allSupportedExtensionsWithJson: readonly Extension[] = [...supportedTSExtensions, ...supportedJSExtensions, Extension.Json]; - export function getSupportedExtensions(options?: CompilerOptions): ReadonlyArray; - export function getSupportedExtensions(options?: CompilerOptions, extraFileExtensions?: ReadonlyArray): ReadonlyArray; - export function getSupportedExtensions(options?: CompilerOptions, extraFileExtensions?: ReadonlyArray): ReadonlyArray { + export function getSupportedExtensions(options?: CompilerOptions): readonly Extension[]; + export function getSupportedExtensions(options?: CompilerOptions, extraFileExtensions?: readonly FileExtensionInfo[]): readonly string[]; + export function getSupportedExtensions(options?: CompilerOptions, extraFileExtensions?: readonly FileExtensionInfo[]): readonly string[] { const needJsExtensions = options && options.allowJs; if (!extraFileExtensions || extraFileExtensions.length === 0) { @@ -8318,7 +8318,7 @@ namespace ts { return deduplicate(extensions, equateStringsCaseSensitive, compareStringsCaseSensitive); } - export function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options: CompilerOptions | undefined, supportedExtensions: ReadonlyArray): ReadonlyArray { + export function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options: CompilerOptions | undefined, supportedExtensions: readonly string[]): readonly string[] { if (!options || !options.resolveJsonModule) { return supportedExtensions; } if (supportedExtensions === allSupportedExtensions) { return allSupportedExtensionsWithJson; } if (supportedExtensions === supportedTSExtensions) { return supportedTSExtensionsWithJson; } @@ -8341,7 +8341,7 @@ namespace ts { return some(supportedTSExtensions, extension => fileExtensionIs(fileName, extension)); } - export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions, extraFileExtensions?: ReadonlyArray) { + export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions, extraFileExtensions?: readonly FileExtensionInfo[]) { if (!fileName) { return false; } const supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions); @@ -8366,7 +8366,7 @@ namespace ts { Lowest = DeclarationAndJavaScriptFiles, } - export function getExtensionPriority(path: string, supportedExtensions: ReadonlyArray): ExtensionPriority { + export function getExtensionPriority(path: string, supportedExtensions: readonly string[]): ExtensionPriority { for (let i = supportedExtensions.length - 1; i >= 0; i--) { if (fileExtensionIs(path, supportedExtensions[i])) { return adjustExtensionPriority(i, supportedExtensions); @@ -8381,7 +8381,7 @@ namespace ts { /** * Adjusts an extension priority to be the highest priority within the same range. */ - export function adjustExtensionPriority(extensionPriority: ExtensionPriority, supportedExtensions: ReadonlyArray): ExtensionPriority { + export function adjustExtensionPriority(extensionPriority: ExtensionPriority, supportedExtensions: readonly string[]): ExtensionPriority { if (extensionPriority < ExtensionPriority.DeclarationAndJavaScriptFiles) { return ExtensionPriority.TypeScriptFiles; } @@ -8396,7 +8396,7 @@ namespace ts { /** * Gets the next lowest extension priority for a given priority. */ - export function getNextLowestExtensionPriority(extensionPriority: ExtensionPriority, supportedExtensions: ReadonlyArray): ExtensionPriority { + export function getNextLowestExtensionPriority(extensionPriority: ExtensionPriority, supportedExtensions: readonly string[]): ExtensionPriority { if (extensionPriority < ExtensionPriority.DeclarationAndJavaScriptFiles) { return ExtensionPriority.DeclarationAndJavaScriptFiles; } @@ -8429,8 +8429,8 @@ namespace ts { } export function changeAnyExtension(path: string, ext: string): string; - export function changeAnyExtension(path: string, ext: string, extensions: string | ReadonlyArray, ignoreCase: boolean): string; - export function changeAnyExtension(path: string, ext: string, extensions?: string | ReadonlyArray, ignoreCase?: boolean) { + export function changeAnyExtension(path: string, ext: string, extensions: string | readonly string[], ignoreCase: boolean): string; + export function changeAnyExtension(path: string, ext: string, extensions?: string | readonly string[], ignoreCase?: boolean) { const pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); return pathext ? path.slice(0, path.length - pathext.length) + (startsWith(ext, ".") ? ext : "." + ext) : path; } @@ -8477,7 +8477,7 @@ namespace ts { return find(extensionsToRemove, e => fileExtensionIs(path, e)); } - function getAnyExtensionFromPathWorker(path: string, extensions: string | ReadonlyArray, stringEqualityComparer: (a: string, b: string) => boolean) { + function getAnyExtensionFromPathWorker(path: string, extensions: string | readonly string[], stringEqualityComparer: (a: string, b: string) => boolean) { if (typeof extensions === "string") extensions = [extensions]; for (let extension of extensions) { if (!startsWith(extension, ".")) extension = "." + extension; @@ -8498,8 +8498,8 @@ namespace ts { /** * Gets the file extension for a path, provided it is one of the provided extensions. */ - export function getAnyExtensionFromPath(path: string, extensions: string | ReadonlyArray, ignoreCase: boolean): string; - export function getAnyExtensionFromPath(path: string, extensions?: string | ReadonlyArray, ignoreCase?: boolean): string { + export function getAnyExtensionFromPath(path: string, extensions: string | readonly string[], ignoreCase: boolean): string; + export function getAnyExtensionFromPath(path: string, extensions?: string | readonly string[], ignoreCase?: boolean): string { // Retrieves any string from the final "." onwards from a base file name. // Unlike extensionFromPath, which throws an exception on unrecognized extensions. if (extensions) { @@ -8528,7 +8528,7 @@ namespace ts { * Return an exact match if possible, or a pattern match, or undefined. * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.) */ - export function matchPatternOrExact(patternStrings: ReadonlyArray, candidate: string): string | Pattern | undefined { + export function matchPatternOrExact(patternStrings: readonly string[], candidate: string): string | Pattern | undefined { const patterns: Pattern[] = []; for (const patternString of patternStrings) { const pattern = tryParsePattern(patternString); @@ -8546,7 +8546,7 @@ namespace ts { export type Mutable = { -readonly [K in keyof T]: T[K] }; - export function sliceAfter(arr: ReadonlyArray, value: T): ReadonlyArray { + export function sliceAfter(arr: readonly T[], value: T): readonly T[] { const index = arr.indexOf(value); Debug.assert(index !== -1); return arr.slice(index); @@ -8560,7 +8560,7 @@ namespace ts { return diagnostic; } - export function minAndMax(arr: ReadonlyArray, getValue: (value: T) => number): { readonly min: number, readonly max: number } { + export function minAndMax(arr: readonly T[], getValue: (value: T) => number): { readonly min: number, readonly max: number } { Debug.assert(arr.length !== 0); let min = getValue(arr[0]); let max = min; diff --git a/src/compiler/visitor.ts b/src/compiler/visitor.ts index 29801ea10bd..7b56439a8f6 100644 --- a/src/compiler/visitor.ts +++ b/src/compiler/visitor.ts @@ -928,7 +928,7 @@ namespace ts { * * @param nodes The NodeArray. */ - function extractSingleNode(nodes: ReadonlyArray): Node | undefined { + function extractSingleNode(nodes: readonly Node[]): Node | undefined { Debug.assert(nodes.length <= 1, "Too many nodes written to output."); return singleOrUndefined(nodes); } @@ -1456,13 +1456,13 @@ namespace ts { /** * Merges generated lexical declarations into a new statement list. */ - export function mergeLexicalEnvironment(statements: NodeArray, declarations: ReadonlyArray | undefined): NodeArray; + export function mergeLexicalEnvironment(statements: NodeArray, declarations: readonly Statement[] | undefined): NodeArray; /** * Appends generated lexical declarations to an array of statements. */ - export function mergeLexicalEnvironment(statements: Statement[], declarations: ReadonlyArray | undefined): Statement[]; - export function mergeLexicalEnvironment(statements: Statement[] | NodeArray, declarations: ReadonlyArray | undefined) { + export function mergeLexicalEnvironment(statements: Statement[], declarations: readonly Statement[] | undefined): Statement[]; + export function mergeLexicalEnvironment(statements: Statement[] | NodeArray, declarations: readonly Statement[] | undefined) { if (!some(declarations)) { return statements; } @@ -1477,7 +1477,7 @@ namespace ts { * * @param nodes The NodeArray. */ - export function liftToBlock(nodes: ReadonlyArray): Statement { + export function liftToBlock(nodes: readonly Node[]): Statement { Debug.assert(every(nodes, isStatement), "Cannot lift nodes to a Block."); return singleOrUndefined(nodes) || createBlock(>nodes); } diff --git a/src/compiler/watch.ts b/src/compiler/watch.ts index 8c5bd5eab2c..d230a9382c5 100644 --- a/src/compiler/watch.ts +++ b/src/compiler/watch.ts @@ -88,7 +88,7 @@ namespace ts { return result; } - export function getErrorCountForSummary(diagnostics: ReadonlyArray) { + export function getErrorCountForSummary(diagnostics: readonly Diagnostic[]) { return countWhere(diagnostics, diagnostic => diagnostic.category === DiagnosticCategory.Error); } @@ -110,12 +110,12 @@ namespace ts { export interface ProgramToEmitFilesAndReportErrors { getCurrentDirectory(): string; getCompilerOptions(): CompilerOptions; - getSourceFiles(): ReadonlyArray; - getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; - getOptionsDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; - getGlobalDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; - getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; - getConfigFileParsingDiagnostics(): ReadonlyArray; + getSourceFiles(): readonly SourceFile[]; + getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[]; + getOptionsDiagnostics(cancellationToken?: CancellationToken): readonly Diagnostic[]; + getGlobalDiagnostics(cancellationToken?: CancellationToken): readonly Diagnostic[]; + getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[]; + getConfigFileParsingDiagnostics(): readonly Diagnostic[]; emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult; } @@ -404,7 +404,7 @@ namespace ts { /** * Creates the watch compiler host from system for compiling root files and options in watch mode */ - export function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: ReadonlyArray): WatchCompilerHostOfFilesAndCompilerOptions { + export function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: readonly ProjectReference[]): WatchCompilerHostOfFilesAndCompilerOptions { const host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus) as WatchCompilerHostOfFilesAndCompilerOptions; host.rootFiles = rootFiles; host.options = options; @@ -413,10 +413,10 @@ namespace ts { } export interface IncrementalCompilationOptions { - rootNames: ReadonlyArray; + rootNames: readonly string[]; options: CompilerOptions; - configFileParsingDiagnostics?: ReadonlyArray; - projectReferences?: ReadonlyArray; + configFileParsingDiagnostics?: readonly Diagnostic[]; + projectReferences?: readonly ProjectReference[]; host?: CompilerHost; reportDiagnostic?: DiagnosticReporter; reportErrorSummary?: ReportEmitErrorSummary; @@ -466,10 +466,10 @@ namespace ts { } export interface IncrementalProgramOptions { - rootNames: ReadonlyArray; + rootNames: readonly string[]; options: CompilerOptions; - configFileParsingDiagnostics?: ReadonlyArray; - projectReferences?: ReadonlyArray; + configFileParsingDiagnostics?: readonly Diagnostic[]; + projectReferences?: readonly ProjectReference[]; host?: CompilerHost; createProgram?: CreateProgram; } @@ -485,7 +485,7 @@ namespace ts { export type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void; /** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */ - export type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray | undefined) => T; + export type CreateProgram = (rootNames: readonly string[] | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: readonly Diagnostic[], projectReferences?: readonly ProjectReference[] | undefined) => T; /** Host that has watch functionality used in --watch mode */ export interface WatchHost { @@ -531,7 +531,7 @@ namespace ts { /** If provided, used in resolutions as well as handling directory structure */ getDirectories?(path: string): string[]; /** If provided, used to cache and handle directory structure modifications */ - readDirectory?(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; + readDirectory?(path: string, extensions?: readonly string[], exclude?: readonly string[], include?: readonly string[], depth?: number): string[]; /** Symbol links resolution */ realpath?(path: string): string; @@ -575,7 +575,7 @@ namespace ts { options: CompilerOptions; /** Project References */ - projectReferences?: ReadonlyArray; + projectReferences?: readonly ProjectReference[]; } /** @@ -592,7 +592,7 @@ namespace ts { * Used to generate source file names from the config file and its include, exclude, files rules * and also to cache the directory stucture */ - readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; + readDirectory(path: string, extensions?: readonly string[], exclude?: readonly string[], include?: readonly string[], depth?: number): string[]; } /** @@ -632,8 +632,8 @@ namespace ts { * Create the watch compiler host for either configFile or fileNames and its options */ export function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfConfigFile; - export function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: ReadonlyArray): WatchCompilerHostOfFilesAndCompilerOptions; - export function createWatchCompilerHost(rootFilesOrConfigFileName: string | string[], options: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: ReadonlyArray): WatchCompilerHostOfFilesAndCompilerOptions | WatchCompilerHostOfConfigFile { + export function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: readonly ProjectReference[]): WatchCompilerHostOfFilesAndCompilerOptions; + export function createWatchCompilerHost(rootFilesOrConfigFileName: string | string[], options: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: readonly ProjectReference[]): WatchCompilerHostOfFilesAndCompilerOptions | WatchCompilerHostOfConfigFile { if (isArray(rootFilesOrConfigFileName)) { return createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options!, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences); // TODO: GH#18217 } diff --git a/src/compiler/watchUtilities.ts b/src/compiler/watchUtilities.ts index 7c11dcf2856..ce133a6d76f 100644 --- a/src/compiler/watchUtilities.ts +++ b/src/compiler/watchUtilities.ts @@ -10,7 +10,7 @@ namespace ts { // TODO: GH#18217 Optional methods are frequently used as non-optional directoryExists?(path: string): boolean; getDirectories?(path: string): string[]; - readDirectory?(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; + readDirectory?(path: string, extensions?: readonly string[], exclude?: readonly string[], include?: readonly string[], depth?: number): string[]; realpath?(path: string): string; createDirectory?(path: string): void; @@ -26,7 +26,7 @@ namespace ts { useCaseSensitiveFileNames: boolean; getDirectories(path: string): string[]; - readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; + readDirectory(path: string, extensions?: readonly string[], exclude?: readonly string[], include?: readonly string[], depth?: number): string[]; /** Returns the queried result for the file exists and directory exists if at all it was done */ addOrDeleteFileOrDirectory(fileOrDirectory: string, fileOrDirectoryPath: Path): FileAndDirectoryExistence | undefined; @@ -113,7 +113,7 @@ namespace ts { return getCanonicalFileName(name1) === getCanonicalFileName(name2); } - function hasEntry(entries: ReadonlyArray, name: string) { + function hasEntry(entries: readonly string[], name: string) { return some(entries, file => fileNameEqual(file, name)); } @@ -168,7 +168,7 @@ namespace ts { return host.getDirectories!(rootDir); } - function readDirectory(rootDir: string, extensions?: ReadonlyArray, excludes?: ReadonlyArray, includes?: ReadonlyArray, depth?: number): string[] { + function readDirectory(rootDir: string, extensions?: readonly string[], excludes?: readonly string[], includes?: readonly string[], depth?: number): string[] { const rootDirPath = toPath(rootDir); const result = tryReadDirectory(rootDir, rootDirPath); if (result) { diff --git a/src/harness/client.ts b/src/harness/client.ts index 4f8e84dcdaf..82337a8ce5b 100644 --- a/src/harness/client.ts +++ b/src/harness/client.ts @@ -588,7 +588,7 @@ namespace ts.server { return notImplemented(); } - getCodeFixesAtPosition(file: string, start: number, end: number, errorCodes: ReadonlyArray): ReadonlyArray { + getCodeFixesAtPosition(file: string, start: number, end: number, errorCodes: readonly number[]): readonly CodeFixAction[] { const args: protocol.CodeFixRequestArgs = { ...this.createFileRangeRequestArgs(file, start, end), errorCodes }; const request = this.processRequest(CommandNames.GetCodeFixes, args); @@ -666,7 +666,7 @@ namespace ts.server { }; } - organizeImports(_scope: OrganizeImportsScope, _formatOptions: FormatCodeSettings): ReadonlyArray { + organizeImports(_scope: OrganizeImportsScope, _formatOptions: FormatCodeSettings): readonly FileTextChanges[] { return notImplemented(); } diff --git a/src/harness/compiler.ts b/src/harness/compiler.ts index 70bda90ef32..880163a10f6 100644 --- a/src/harness/compiler.ts +++ b/src/harness/compiler.ts @@ -38,7 +38,7 @@ namespace compiler { * Correlates compilation inputs and outputs */ export interface CompilationOutput { - readonly inputs: ReadonlyArray; + readonly inputs: readonly documents.TextDocument[]; readonly js: documents.TextDocument | undefined; readonly dts: documents.TextDocument | undefined; readonly map: documents.TextDocument | undefined; @@ -49,7 +49,7 @@ namespace compiler { public readonly program: ts.Program | undefined; public readonly result: ts.EmitResult | undefined; public readonly options: ts.CompilerOptions; - public readonly diagnostics: ReadonlyArray; + public readonly diagnostics: readonly ts.Diagnostic[]; public readonly js: ReadonlyMap; public readonly dts: ReadonlyMap; public readonly maps: ReadonlyMap; @@ -58,7 +58,7 @@ namespace compiler { private _inputs: documents.TextDocument[] = []; private _inputsAndOutputs: collections.SortedMap; - constructor(host: fakes.CompilerHost, options: ts.CompilerOptions, program: ts.Program | undefined, result: ts.EmitResult | undefined, diagnostics: ReadonlyArray) { + constructor(host: fakes.CompilerHost, options: ts.CompilerOptions, program: ts.Program | undefined, result: ts.EmitResult | undefined, diagnostics: readonly ts.Diagnostic[]) { this.host = host; this.program = program; this.result = result; @@ -143,15 +143,15 @@ namespace compiler { return this.host.vfs; } - public get inputs(): ReadonlyArray { + public get inputs(): readonly documents.TextDocument[] { return this._inputs; } - public get outputs(): ReadonlyArray { + public get outputs(): readonly documents.TextDocument[] { return this.host.outputs; } - public get traces(): ReadonlyArray { + public get traces(): readonly string[] { return this.host.traces; } @@ -172,7 +172,7 @@ namespace compiler { return this._inputsAndOutputs.get(vpath.resolve(this.vfs.cwd(), path)); } - public getInputs(path: string): ReadonlyArray | undefined { + public getInputs(path: string): readonly documents.TextDocument[] | undefined { const outputs = this.getInputsAndOutputs(path); return outputs && outputs.inputs; } diff --git a/src/harness/documents.ts b/src/harness/documents.ts index 312339287e2..c07142e794f 100644 --- a/src/harness/documents.ts +++ b/src/harness/documents.ts @@ -7,7 +7,7 @@ namespace documents { public readonly file: string; public readonly text: string; - private _lineStarts: ReadonlyArray | undefined; + private _lineStarts: readonly number[] | undefined; private _testFile: Harness.Compiler.TestFile | undefined; constructor(file: string, text: string, meta?: Map) { @@ -16,7 +16,7 @@ namespace documents { this.meta = meta || new Map(); } - public get lineStarts(): ReadonlyArray { + public get lineStarts(): readonly number[] { return this._lineStarts || (this._lineStarts = ts.computeLineStarts(this.text)); } @@ -64,10 +64,10 @@ namespace documents { public readonly version: number; public readonly file: string; public readonly sourceRoot: string | undefined; - public readonly sources: ReadonlyArray = []; - public readonly sourcesContent: ReadonlyArray | undefined; - public readonly mappings: ReadonlyArray = []; - public readonly names: ReadonlyArray | undefined; + public readonly sources: readonly string[] = []; + public readonly sourcesContent: readonly string[] | undefined; + public readonly mappings: readonly Mapping[] = []; + public readonly names: readonly string[] | undefined; private static readonly _mappingRegExp = /([A-Za-z0-9+/]+),?|(;)|./g; private static readonly _sourceMappingURLRegExp = /^\/\/[#@]\s*sourceMappingURL\s*=\s*(.*?)\s*$/mig; @@ -156,11 +156,11 @@ namespace documents { return url === undefined ? undefined : this.fromUrl(url); } - public getMappingsForEmittedLine(emittedLine: number): ReadonlyArray | undefined { + public getMappingsForEmittedLine(emittedLine: number): readonly Mapping[] | undefined { return this._emittedLineMappings[emittedLine]; } - public getMappingsForSourceLine(sourceIndex: number, sourceLine: number): ReadonlyArray | undefined { + public getMappingsForSourceLine(sourceIndex: number, sourceLine: number): readonly Mapping[] | undefined { const mappingsForSource = this._sourceLineMappings[sourceIndex]; return mappingsForSource && mappingsForSource[sourceLine]; } diff --git a/src/harness/fakes.ts b/src/harness/fakes.ts index 31e64e2c931..f212f0f6787 100644 --- a/src/harness/fakes.ts +++ b/src/harness/fakes.ts @@ -86,7 +86,7 @@ namespace fakes { return result; } - public readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[] { + public readDirectory(path: string, extensions?: readonly string[], exclude?: readonly string[], include?: readonly string[], depth?: number): string[] { return ts.matchFiles(path, extensions, exclude, include, this.useCaseSensitiveFileNames, this.getCurrentDirectory(), depth, path => this.getAccessibleFileSystemEntries(path), path => this.realpath(path)); } @@ -276,7 +276,7 @@ namespace fakes { return this.sys.getDirectories(path); } - public readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[] { + public readDirectory(path: string, extensions?: readonly string[], exclude?: readonly string[], include?: readonly string[], depth?: number): string[] { return this.sys.readDirectory(path, extensions, exclude, include, depth); } diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index 6dc708e8b8c..9a6dc01f680 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -188,7 +188,7 @@ namespace FourSlash { // Add input file which has matched file name with the given reference-file path. // This is necessary when resolveReference flag is specified - private addMatchedInputFile(referenceFilePath: string, extensions: ReadonlyArray | undefined) { + private addMatchedInputFile(referenceFilePath: string, extensions: readonly string[] | undefined) { const inputFiles = this.inputFiles; const languageServiceAdapterHost = this.languageServiceAdapterHost; const didAdd = tryAdd(referenceFilePath); @@ -392,7 +392,7 @@ namespace FourSlash { this.goToPosition(marker.position); } - public goToEachMarker(markers: ReadonlyArray, action: (marker: Marker, index: number) => void) { + public goToEachMarker(markers: readonly Marker[], action: (marker: Marker, index: number) => void) { assert(markers.length); for (let i = 0; i < markers.length; i++) { this.goToMarker(markers[i]); @@ -493,7 +493,7 @@ namespace FourSlash { ]; } - private getAllDiagnostics(): ReadonlyArray { + private getAllDiagnostics(): readonly ts.Diagnostic[] { return ts.flatMap(this.languageServiceAdapterHost.getFilenames(), fileName => { if (!ts.isAnySupportedFileExtension(fileName)) { return []; @@ -534,7 +534,7 @@ namespace FourSlash { predicate(start!, start! + length!, startMarker.position, endMarker === undefined ? undefined : endMarker.position)); // TODO: GH#18217 } - private printErrorLog(expectErrors: boolean, errors: ReadonlyArray): void { + private printErrorLog(expectErrors: boolean, errors: readonly ts.Diagnostic[]): void { if (expectErrors) { Harness.IO.log("Expected error not found. Error list is:"); } @@ -631,7 +631,7 @@ namespace FourSlash { this.verifyGoToX(arg0, endMarkerNames, () => this.getGoToDefinitionAndBoundSpan()); } - private getGoToDefinition(): ReadonlyArray { + private getGoToDefinition(): readonly ts.DefinitionInfo[] { return this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition)!; } @@ -644,12 +644,12 @@ namespace FourSlash { this.languageService.getTypeDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition)); } - private verifyGoToX(arg0: any, endMarkerNames: ArrayOrSingle | undefined, getDefs: () => ReadonlyArray | ts.DefinitionInfoAndBoundSpan | undefined) { + private verifyGoToX(arg0: any, endMarkerNames: ArrayOrSingle | undefined, getDefs: () => readonly ts.DefinitionInfo[] | ts.DefinitionInfoAndBoundSpan | undefined) { if (endMarkerNames) { this.verifyGoToXPlain(arg0, endMarkerNames, getDefs); } else if (ts.isArray(arg0)) { - const pairs = arg0 as ReadonlyArray<[ArrayOrSingle, ArrayOrSingle]>; + const pairs = arg0 as readonly [ArrayOrSingle, ArrayOrSingle][]; for (const [start, end] of pairs) { this.verifyGoToXPlain(start, end, getDefs); } @@ -664,7 +664,7 @@ namespace FourSlash { } } - private verifyGoToXPlain(startMarkerNames: ArrayOrSingle, endMarkerNames: ArrayOrSingle, getDefs: () => ReadonlyArray | ts.DefinitionInfoAndBoundSpan | undefined) { + private verifyGoToXPlain(startMarkerNames: ArrayOrSingle, endMarkerNames: ArrayOrSingle, getDefs: () => readonly ts.DefinitionInfo[] | ts.DefinitionInfoAndBoundSpan | undefined) { for (const start of toArray(startMarkerNames)) { this.verifyGoToXSingle(start, endMarkerNames, getDefs); } @@ -676,14 +676,14 @@ namespace FourSlash { } } - private verifyGoToXSingle(startMarkerName: string, endMarkerNames: ArrayOrSingle, getDefs: () => ReadonlyArray | ts.DefinitionInfoAndBoundSpan | undefined) { + private verifyGoToXSingle(startMarkerName: string, endMarkerNames: ArrayOrSingle, getDefs: () => readonly ts.DefinitionInfo[] | ts.DefinitionInfoAndBoundSpan | undefined) { this.goToMarker(startMarkerName); this.verifyGoToXWorker(toArray(endMarkerNames), getDefs, startMarkerName); } - private verifyGoToXWorker(endMarkers: ReadonlyArray, getDefs: () => ReadonlyArray | ts.DefinitionInfoAndBoundSpan | undefined, startMarkerName?: string) { + private verifyGoToXWorker(endMarkers: readonly string[], getDefs: () => readonly ts.DefinitionInfo[] | ts.DefinitionInfoAndBoundSpan | undefined, startMarkerName?: string) { const defs = getDefs(); - let definitions: ReadonlyArray; + let definitions: readonly ts.DefinitionInfo[]; let testName: string; if (!defs || ts.isArray(defs)) { @@ -859,7 +859,7 @@ namespace FourSlash { } } - private verifyCompletionsAreExactly(actual: ReadonlyArray, expected: ReadonlyArray, marker?: ArrayOrSingle) { + private verifyCompletionsAreExactly(actual: readonly ts.CompletionEntry[], expected: readonly FourSlashInterface.ExpectedCompletionEntry[], marker?: ArrayOrSingle) { // First pass: test that names are right. Then we'll test details. assert.deepEqual(actual.map(a => a.name), expected.map(e => typeof e === "string" ? e : e.name), marker ? "At marker " + JSON.stringify(marker) : undefined); @@ -953,7 +953,7 @@ namespace FourSlash { } } - private verifyDocumentHighlightsRespectFilesList(files: ReadonlyArray): void { + private verifyDocumentHighlightsRespectFilesList(files: readonly string[]): void { const startFile = this.activeFile.fileName; for (const fileName of files) { const searchFileNames = startFile === fileName ? [startFile] : [startFile, fileName]; @@ -964,7 +964,7 @@ namespace FourSlash { } } - public verifyReferenceGroups(starts: ArrayOrSingle | ArrayOrSingle, parts: ReadonlyArray): void { + public verifyReferenceGroups(starts: ArrayOrSingle | ArrayOrSingle, parts: readonly FourSlashInterface.ReferenceGroup[]): void { interface ReferenceGroupJson { definition: string | { text: string, range: ts.TextSpan }; references: ts.ReferenceEntry[]; @@ -1012,9 +1012,9 @@ namespace FourSlash { } // Necessary to have this function since `findReferences` isn't implemented in `client.ts` - public verifyGetReferencesForServerTest(expected: ReadonlyArray): void { + public verifyGetReferencesForServerTest(expected: readonly ts.ReferenceEntry[]): void { const refs = this.getReferencesAtCaret(); - assert.deepEqual | undefined>(refs, expected); + assert.deepEqual(refs, expected); } public verifySingleReferenceGroup(definition: FourSlashInterface.ReferenceGroupDefinition, ranges?: Range[] | string) { @@ -1093,21 +1093,21 @@ namespace FourSlash { return this.languageService.findReferences(this.activeFile.fileName, this.currentCaretPosition); } - public getSyntacticDiagnostics(expected: ReadonlyArray) { + public getSyntacticDiagnostics(expected: readonly FourSlashInterface.Diagnostic[]) { const diagnostics = this.languageService.getSyntacticDiagnostics(this.activeFile.fileName); this.testDiagnostics(expected, diagnostics, "error"); } - public getSemanticDiagnostics(expected: ReadonlyArray) { + public getSemanticDiagnostics(expected: readonly FourSlashInterface.Diagnostic[]) { const diagnostics = this.languageService.getSemanticDiagnostics(this.activeFile.fileName); this.testDiagnostics(expected, diagnostics, "error"); } - public getSuggestionDiagnostics(expected: ReadonlyArray): void { + public getSuggestionDiagnostics(expected: readonly FourSlashInterface.Diagnostic[]): void { this.testDiagnostics(expected, this.languageService.getSuggestionDiagnostics(this.activeFile.fileName), "suggestion"); } - private testDiagnostics(expected: ReadonlyArray, diagnostics: ReadonlyArray, category: string) { + private testDiagnostics(expected: readonly FourSlashInterface.Diagnostic[], diagnostics: readonly ts.Diagnostic[], category: string) { assert.deepEqual(ts.realizeDiagnostics(diagnostics, "\n"), expected.map((e): ts.RealizedDiagnostic => ({ message: e.message, category, @@ -1203,7 +1203,7 @@ namespace FourSlash { const references = this.languageService.findRenameLocations( this.activeFile.fileName, this.currentCaretPosition, findInStrings, findInComments, providePrefixAndSuffixTextForRename); - const sort = (locations: ReadonlyArray | undefined) => + const sort = (locations: readonly ts.RenameLocation[] | undefined) => locations && ts.sort(locations, (r1, r2) => ts.compareStringsCaseSensitive(r1.fileName, r2.fileName) || r1.textSpan.start - r2.textSpan.start); assert.deepEqual(sort(references), sort(ranges.map((rangeOrOptions): ts.RenameLocation => { const { range, ...prefixSuffixText } = "range" in rangeOrOptions ? rangeOrOptions : { range: rangeOrOptions }; // eslint-disable-line no-in-operator @@ -1234,7 +1234,7 @@ namespace FourSlash { } } - public verifySignatureHelpPresence(expectPresent: boolean, triggerReason: ts.SignatureHelpTriggerReason | undefined, markers: ReadonlyArray) { + public verifySignatureHelpPresence(expectPresent: boolean, triggerReason: ts.SignatureHelpTriggerReason | undefined, markers: readonly (string | Marker)[]) { if (markers.length) { for (const marker of markers) { this.goToMarker(marker); @@ -1253,7 +1253,7 @@ namespace FourSlash { } } - public verifySignatureHelp(optionses: ReadonlyArray) { + public verifySignatureHelp(optionses: readonly FourSlashInterface.VerifySignatureHelpOptions[]) { for (const options of optionses) { if (options.marker === undefined) { this.verifySignatureHelpWorker(options); @@ -1308,7 +1308,7 @@ namespace FourSlash { assert.equal(actualTag.text, expectedTag.text, this.assertionMessageAtLastKnownMarker("signature help tag " + actualTag.name)); }); - const allKeys: ReadonlyArray = [ + const allKeys: readonly (keyof FourSlashInterface.VerifySignatureHelpOptions)[] = [ "marker", "triggerReason", "overloadsCount", @@ -1448,7 +1448,7 @@ namespace FourSlash { Harness.Baseline.runBaseline(baselineFile, this.baselineCurrentFileLocations(pos => this.getBreakpointStatementLocation(pos)!)); } - private getEmitFiles(): ReadonlyArray { + private getEmitFiles(): readonly FourSlashFile[] { // Find file to be emitted const emitFiles: FourSlashFile[] = []; // List of FourSlashFile that has emitThisFile flag on @@ -1468,7 +1468,7 @@ namespace FourSlash { return emitFiles; } - public verifyGetEmitOutput(expectedOutputFiles: ReadonlyArray): void { + public verifyGetEmitOutput(expectedOutputFiles: readonly string[]): void { const outputFiles = ts.flatMap(this.getEmitFiles(), e => this.languageService.getEmitOutput(e.fileName).outputFiles); assert.deepEqual(outputFiles.map(f => f.name), expectedOutputFiles); @@ -1802,7 +1802,7 @@ namespace FourSlash { * @returns The number of characters added to the file as a result of the edits. * May be negative. */ - private applyEdits(fileName: string, edits: ReadonlyArray, isFormattingEdit: boolean): number { + private applyEdits(fileName: string, edits: readonly ts.TextChange[], isFormattingEdit: boolean): number { // Get a snapshot of the content of the file so we can make sure any formatting edits didn't destroy non-whitespace characters const oldContent = this.getFileContent(fileName); let runningOffset = 0; @@ -1964,7 +1964,7 @@ namespace FourSlash { public verifyRangesInImplementationList(markerName: string) { this.goToMarker(markerName); - const implementations: ReadonlyArray = this.languageService.getImplementationAtPosition(this.activeFile.fileName, this.currentCaretPosition)!; + const implementations: readonly ImplementationLocationInformation[] = this.languageService.getImplementationAtPosition(this.activeFile.fileName, this.currentCaretPosition)!; if (!implementations || !implementations.length) { this.raiseError("verifyRangesInImplementationList failed - expected to find at least one implementation location but got 0"); } @@ -2376,7 +2376,7 @@ namespace FourSlash { ts.Debug.assertEqual(fixWithId!.fixAllDescription, fixAllDescription); const { changes, commands } = this.languageService.getCombinedCodeFix({ type: "file", fileName: this.activeFile.fileName }, fixId, this.formatCodeSettings, ts.emptyOptions); - assert.deepEqual | undefined>(commands, expectedCommands); + assert.deepEqual(commands, expectedCommands); this.verifyNewContent({ newFileContent }, changes); } @@ -2412,7 +2412,7 @@ namespace FourSlash { } } - private verifyNewContent({ newFileContent, newRangeContent }: FourSlashInterface.NewContentOptions, changes: ReadonlyArray): void { + private verifyNewContent({ newFileContent, newRangeContent }: FourSlashInterface.NewContentOptions, changes: readonly ts.FileTextChanges[]): void { if (newRangeContent !== undefined) { assert(newFileContent === undefined); assert(changes.length === 1, "Affected 0 or more than 1 file, must use 'newFileContent' instead of 'newRangeContent'"); @@ -2442,7 +2442,7 @@ namespace FourSlash { } } - private verifyNewContentAfterChange({ newFileContent, newRangeContent }: FourSlashInterface.NewContentOptions, changedFiles: ReadonlyArray) { + private verifyNewContentAfterChange({ newFileContent, newRangeContent }: FourSlashInterface.NewContentOptions, changedFiles: readonly string[]) { const assertedChangedFiles = !newFileContent || typeof newFileContent === "string" ? [this.activeFile.fileName] : ts.getOwnKeys(newFileContent); @@ -2468,7 +2468,7 @@ namespace FourSlash { * Rerieves a codefix satisfying the parameters, or undefined if no such codefix is found. * @param fileName Path to file where error should be retrieved from. */ - private getCodeFixes(fileName: string, errorCode?: number, preferences: ts.UserPreferences = ts.emptyOptions): ReadonlyArray { + private getCodeFixes(fileName: string, errorCode?: number, preferences: ts.UserPreferences = ts.emptyOptions): readonly ts.CodeFixAction[] { const diagnosticsForCodeFix = this.getDiagnostics(fileName, /*includeSuggestions*/ true).map(diagnostic => ({ start: diagnostic.start, length: diagnostic.length, @@ -2484,7 +2484,7 @@ namespace FourSlash { }); } - private applyChanges(changes: ReadonlyArray): void { + private applyChanges(changes: readonly ts.FileTextChanges[]): void { for (const change of changes) { this.applyEdits(change.fileName, change.textChanges, /*isFormattingEdit*/ false); } @@ -2642,7 +2642,7 @@ namespace FourSlash { } } - public verifyNavigateTo(options: ReadonlyArray): void { + public verifyNavigateTo(options: readonly FourSlashInterface.VerifyNavigateToOptions[]): void { for (const { pattern, expected, fileName } of options) { const items = this.languageService.getNavigateToItems(pattern, /*maxResultCount*/ undefined, fileName); this.assertObjectsEqual(items, expected.map((e): ts.NavigateToItem => ({ @@ -2738,7 +2738,7 @@ namespace FourSlash { } } - private getDocumentHighlightsAtCurrentPosition(fileNamesToSearch: ReadonlyArray) { + private getDocumentHighlightsAtCurrentPosition(fileNamesToSearch: readonly string[]) { const filesToSearch = fileNamesToSearch.map(name => ts.combinePaths(this.basePath, name)); return this.languageService.getDocumentHighlights(this.activeFile.fileName, this.currentCaretPosition, filesToSearch); } @@ -2793,7 +2793,7 @@ namespace FourSlash { } } - private verifyDocumentHighlights(expectedRanges: Range[], fileNames: ReadonlyArray = [this.activeFile.fileName]) { + private verifyDocumentHighlights(expectedRanges: Range[], fileNames: readonly string[] = [this.activeFile.fileName]) { fileNames = ts.map(fileNames, ts.normalizePath); const documentHighlights = this.getDocumentHighlightsAtCurrentPosition(fileNames) || []; @@ -2881,7 +2881,7 @@ namespace FourSlash { } } - public verifyRefactorsAvailable(names: ReadonlyArray): void { + public verifyRefactorsAvailable(names: readonly string[]): void { assert.deepEqual(unique(this.getApplicableRefactorsAtSelection(), r => r.name), names); } @@ -2986,7 +2986,7 @@ namespace FourSlash { this.verifyNewContent({ newFileContent: options.newFileContents }, editInfo.edits); } - private testNewFileContents(edits: ReadonlyArray, newFileContents: { [fileName: string]: string }, description: string): void { + private testNewFileContents(edits: readonly ts.FileTextChanges[], newFileContents: { [fileName: string]: string }, description: string): void { for (const { fileName, textChanges } of edits) { const newContent = newFileContents[fileName]; if (newContent === undefined) { @@ -3099,7 +3099,7 @@ namespace FourSlash { } } - private tryFindFileWorker(name: string): { readonly file: FourSlashFile | undefined; readonly availableNames: ReadonlyArray; } { + private tryFindFileWorker(name: string): { readonly file: FourSlashFile | undefined; readonly availableNames: readonly string[]; } { name = ts.normalizePath(name); // names are stored in the compiler with this relative path, this allows people to use goTo.file on just the fileName name = name.indexOf("/") === -1 ? (this.basePath + "/" + name) : name; @@ -3163,10 +3163,10 @@ namespace FourSlash { private getApplicableRefactorsAtSelection() { return this.getApplicableRefactorsWorker(this.getSelection(), this.activeFile.fileName); } - private getApplicableRefactors(rangeOrMarker: Range | Marker, preferences = ts.emptyOptions): ReadonlyArray { + private getApplicableRefactors(rangeOrMarker: Range | Marker, preferences = ts.emptyOptions): readonly ts.ApplicableRefactorInfo[] { return this.getApplicableRefactorsWorker("position" in rangeOrMarker ? rangeOrMarker.position : rangeOrMarker, rangeOrMarker.fileName, preferences); // eslint-disable-line no-in-operator } - private getApplicableRefactorsWorker(positionOrRange: number | ts.TextRange, fileName: string, preferences = ts.emptyOptions): ReadonlyArray { + private getApplicableRefactorsWorker(positionOrRange: number | ts.TextRange, fileName: string, preferences = ts.emptyOptions): readonly ts.ApplicableRefactorInfo[] { return this.languageService.getApplicableRefactors(fileName, positionOrRange, preferences) || ts.emptyArray; } @@ -3175,7 +3175,7 @@ namespace FourSlash { } } - function updateTextRangeForTextChanges({ pos, end }: ts.TextRange, textChanges: ReadonlyArray): ts.TextRange { + function updateTextRangeForTextChanges({ pos, end }: ts.TextRange, textChanges: readonly ts.TextChange[]): ts.TextRange { forEachTextChange(textChanges, change => { const update = (p: number): number => updatePosition(p, change.span.start, ts.textSpanEnd(change.span), change.newText); pos = update(pos); @@ -3185,7 +3185,7 @@ namespace FourSlash { } /** Apply each textChange in order, updating future changes to account for the text offset of previous changes. */ - function forEachTextChange(changes: ReadonlyArray, cb: (change: ts.TextChange) => void): void { + function forEachTextChange(changes: readonly ts.TextChange[], cb: (change: ts.TextChange) => void): void { // Copy this so we don't ruin someone else's copy changes = JSON.parse(JSON.stringify(changes)); for (let i = 0; i < changes.length; i++) { @@ -3659,7 +3659,7 @@ ${code} } /** Collects an array of unique outputs. */ - function unique(inputs: ReadonlyArray, getOutput: (t: T) => string): string[] { + function unique(inputs: readonly T[], getOutput: (t: T) => string): string[] { const set = ts.createMap(); for (const input of inputs) { const out = getOutput(input); @@ -3668,7 +3668,7 @@ ${code} return ts.arrayFrom(set.keys()); } - function toArray(x: ArrayOrSingle): ReadonlyArray { + function toArray(x: ArrayOrSingle): readonly T[] { return ts.isArray(x) ? x : [x]; } @@ -3693,7 +3693,7 @@ ${code} return s.replace(/\s/g, ""); } - function findDuplicatedElement(a: ReadonlyArray, equal: (a: T, b: T) => boolean): T | undefined { + function findDuplicatedElement(a: readonly T[], equal: (a: T, b: T) => boolean): T | undefined { for (let i = 0; i < a.length; i++) { for (let j = i + 1; j < a.length; j++) { if (equal(a[i], a[j])) { @@ -3777,9 +3777,9 @@ namespace FourSlashInterface { this.state.goToMarker(name); } - public eachMarker(markers: ReadonlyArray, action: (marker: FourSlash.Marker, index: number) => void): void; + public eachMarker(markers: readonly string[], action: (marker: FourSlash.Marker, index: number) => void): void; public eachMarker(action: (marker: FourSlash.Marker, index: number) => void): void; - public eachMarker(a: ReadonlyArray | ((marker: FourSlash.Marker, index: number) => void), b?: (marker: FourSlash.Marker, index: number) => void): void { + public eachMarker(a: readonly string[] | ((marker: FourSlash.Marker, index: number) => void), b?: (marker: FourSlash.Marker, index: number) => void): void { const markers = typeof a === "function" ? this.state.getMarkers() : a.map(m => this.state.getMarkerByName(m)); this.state.goToEachMarker(markers, typeof a === "function" ? a : b!); } @@ -3913,7 +3913,7 @@ namespace FourSlashInterface { this.state.verifyApplicableRefactorAvailableForRange(this.negative); } - public refactorsAvailable(names: ReadonlyArray): void { + public refactorsAvailable(names: readonly string[]): void { this.state.verifyRefactorsAvailable(names); } @@ -4030,7 +4030,7 @@ namespace FourSlashInterface { this.state.verifyNoReferences(markerNameOrRange); } - public getReferencesForServerTest(expected: ReadonlyArray) { + public getReferencesForServerTest(expected: readonly ts.ReferenceEntry[]) { this.state.verifyGetReferencesForServerTest(expected); } @@ -4062,7 +4062,7 @@ namespace FourSlashInterface { this.state.baselineCurrentFileNameOrDottedNameSpans(); } - public getEmitOutput(expectedOutputFiles: ReadonlyArray): void { + public getEmitOutput(expectedOutputFiles: readonly string[]): void { this.state.verifyGetEmitOutput(expectedOutputFiles); } @@ -4219,15 +4219,15 @@ namespace FourSlashInterface { this.state.verifyQuickInfoDisplayParts(kind, kindModifiers, textSpan, displayParts, documentation, tags); } - public getSyntacticDiagnostics(expected: ReadonlyArray) { + public getSyntacticDiagnostics(expected: readonly Diagnostic[]) { this.state.getSyntacticDiagnostics(expected); } - public getSemanticDiagnostics(expected: ReadonlyArray) { + public getSemanticDiagnostics(expected: readonly Diagnostic[]) { this.state.getSemanticDiagnostics(expected); } - public getSuggestionDiagnostics(expected: ReadonlyArray) { + public getSuggestionDiagnostics(expected: readonly Diagnostic[]) { this.state.getSuggestionDiagnostics(expected); } @@ -4578,13 +4578,13 @@ namespace FourSlashInterface { sortText: SortText.GlobalsOrKeywords }); } - export const keywordsWithUndefined: ReadonlyArray = res; - export const keywords: ReadonlyArray = keywordsWithUndefined.filter(k => k.name !== "undefined"); + export const keywordsWithUndefined: readonly ExpectedCompletionEntryObject[] = res; + export const keywords: readonly ExpectedCompletionEntryObject[] = keywordsWithUndefined.filter(k => k.name !== "undefined"); - export const typeKeywords: ReadonlyArray = + export const typeKeywords: readonly ExpectedCompletionEntryObject[] = ["false", "null", "true", "void", "any", "boolean", "keyof", "never", "readonly", "number", "object", "string", "symbol", "undefined", "unique", "unknown", "bigint"].map(keywordEntry); - const globalTypeDecls: ReadonlyArray = [ + const globalTypeDecls: readonly ExpectedCompletionEntryObject[] = [ interfaceEntry("Symbol"), typeEntry("PropertyKey"), interfaceEntry("PropertyDescriptor"), @@ -4689,7 +4689,7 @@ namespace FourSlashInterface { sortText: SortText.GlobalsOrKeywords }; export const globalTypes = globalTypesPlus([]); - export function globalTypesPlus(plus: ReadonlyArray): ReadonlyArray { + export function globalTypesPlus(plus: readonly ExpectedCompletionEntry[]): readonly ExpectedCompletionEntry[] { return [ globalThisEntry, ...globalTypeDecls, @@ -4698,10 +4698,10 @@ namespace FourSlashInterface { ]; } - export const typeAssertionKeywords: ReadonlyArray = + export const typeAssertionKeywords: readonly ExpectedCompletionEntry[] = globalTypesPlus([keywordEntry("const")]); - function getInJsKeywords(keywords: ReadonlyArray): ReadonlyArray { + function getInJsKeywords(keywords: readonly ExpectedCompletionEntryObject[]): readonly ExpectedCompletionEntryObject[] { return keywords.filter(keyword => { switch (keyword.name) { case "enum": @@ -4737,19 +4737,19 @@ namespace FourSlashInterface { }); } - export const classElementKeywords: ReadonlyArray = + export const classElementKeywords: readonly ExpectedCompletionEntryObject[] = ["private", "protected", "public", "static", "abstract", "async", "constructor", "get", "readonly", "set"].map(keywordEntry); export const classElementInJsKeywords = getInJsKeywords(classElementKeywords); - export const constructorParameterKeywords: ReadonlyArray = + export const constructorParameterKeywords: readonly ExpectedCompletionEntryObject[] = ["private", "protected", "public", "readonly"].map((name): ExpectedCompletionEntryObject => ({ name, kind: "keyword", sortText: SortText.GlobalsOrKeywords })); - export const functionMembers: ReadonlyArray = [ + export const functionMembers: readonly ExpectedCompletionEntryObject[] = [ methodEntry("apply"), methodEntry("call"), methodEntry("bind"), @@ -4759,7 +4759,7 @@ namespace FourSlashInterface { propertyEntry("caller"), ]; - export const stringMembers: ReadonlyArray = [ + export const stringMembers: readonly ExpectedCompletionEntryObject[] = [ methodEntry("toString"), methodEntry("charAt"), methodEntry("charCodeAt"), @@ -4783,14 +4783,14 @@ namespace FourSlashInterface { methodEntry("valueOf"), ]; - export const functionMembersWithPrototype: ReadonlyArray = [ + export const functionMembersWithPrototype: readonly ExpectedCompletionEntryObject[] = [ ...functionMembers.slice(0, 4), propertyEntry("prototype"), ...functionMembers.slice(4), ]; // TODO: Shouldn't propose type keywords in statement position - export const statementKeywordsWithTypes: ReadonlyArray = [ + export const statementKeywordsWithTypes: readonly ExpectedCompletionEntryObject[] = [ "break", "case", "catch", @@ -4850,7 +4850,7 @@ namespace FourSlashInterface { "bigint", ].map(keywordEntry); - export const statementKeywords: ReadonlyArray = statementKeywordsWithTypes.filter(k => { + export const statementKeywords: readonly ExpectedCompletionEntryObject[] = statementKeywordsWithTypes.filter(k => { const name = k.name; switch (name) { case "false": @@ -4868,7 +4868,7 @@ namespace FourSlashInterface { export const statementInJsKeywords = getInJsKeywords(statementKeywords); - export const globalsVars: ReadonlyArray = [ + export const globalsVars: readonly ExpectedCompletionEntryObject[] = [ functionEntry("eval"), functionEntry("parseInt"), functionEntry("parseFloat"), @@ -4913,7 +4913,7 @@ namespace FourSlashInterface { moduleEntry("Intl"), ]; - const globalKeywordsInsideFunction: ReadonlyArray = [ + const globalKeywordsInsideFunction: readonly ExpectedCompletionEntryObject[] = [ "break", "case", "catch", @@ -4965,7 +4965,7 @@ namespace FourSlashInterface { sortText: SortText.GlobalsOrKeywords }; // TODO: many of these are inappropriate to always provide - export const globalsInsideFunction = (plus: ReadonlyArray): ReadonlyArray => [ + export const globalsInsideFunction = (plus: readonly ExpectedCompletionEntry[]): readonly ExpectedCompletionEntry[] => [ { name: "arguments", kind: "local var" }, ...plus, globalThisEntry, @@ -4977,7 +4977,7 @@ namespace FourSlashInterface { const globalInJsKeywordsInsideFunction = getInJsKeywords(globalKeywordsInsideFunction); // TODO: many of these are inappropriate to always provide - export const globalsInJsInsideFunction = (plus: ReadonlyArray): ReadonlyArray => [ + export const globalsInJsInsideFunction = (plus: readonly ExpectedCompletionEntry[]): readonly ExpectedCompletionEntry[] => [ { name: "arguments", kind: "local var" }, globalThisEntry, ...globalsVars, @@ -4987,7 +4987,7 @@ namespace FourSlashInterface { ]; // TODO: many of these are inappropriate to always provide - export const globalKeywords: ReadonlyArray = [ + export const globalKeywords: readonly ExpectedCompletionEntryObject[] = [ "break", "case", "catch", @@ -5049,7 +5049,7 @@ namespace FourSlashInterface { export const globalInJsKeywords = getInJsKeywords(globalKeywords); - export const insideMethodKeywords: ReadonlyArray = [ + export const insideMethodKeywords: readonly ExpectedCompletionEntryObject[] = [ "break", "case", "catch", @@ -5097,21 +5097,21 @@ namespace FourSlashInterface { export const insideMethodInJsKeywords = getInJsKeywords(insideMethodKeywords); - export const globals: ReadonlyArray = [ + export const globals: readonly ExpectedCompletionEntryObject[] = [ globalThisEntry, ...globalsVars, undefinedVarEntry, ...globalKeywords ]; - export const globalsInJs: ReadonlyArray = [ + export const globalsInJs: readonly ExpectedCompletionEntryObject[] = [ globalThisEntry, ...globalsVars, undefinedVarEntry, ...globalInJsKeywords ]; - export function globalsPlus(plus: ReadonlyArray): ReadonlyArray { + export function globalsPlus(plus: readonly ExpectedCompletionEntry[]): readonly ExpectedCompletionEntry[] { return [ globalThisEntry, ...globalsVars, @@ -5120,7 +5120,7 @@ namespace FourSlashInterface { ...globalKeywords]; } - export function globalsInJsPlus(plus: ReadonlyArray): ReadonlyArray { + export function globalsInJsPlus(plus: readonly ExpectedCompletionEntry[]): readonly ExpectedCompletionEntry[] { return [ globalThisEntry, ...globalsVars, @@ -5157,7 +5157,7 @@ namespace FourSlashInterface { readonly text?: string; readonly documentation?: string; readonly sourceDisplay?: string; - readonly tags?: ReadonlyArray; + readonly tags?: readonly ts.JSDocTagInfo[]; readonly sortText?: ts.Completions.SortText; } @@ -5188,14 +5188,14 @@ namespace FourSlashInterface { /** @default false */ readonly isVariadic?: boolean; /** @default ts.emptyArray */ - readonly tags?: ReadonlyArray; + readonly tags?: readonly ts.JSDocTagInfo[]; readonly triggerReason?: ts.SignatureHelpTriggerReason; } export interface VerifyNavigateToOptions { readonly pattern: string; readonly fileName?: string; - readonly expected: ReadonlyArray; + readonly expected: readonly ExpectedNavigateToItem[]; } export interface ExpectedNavigateToItem { @@ -5209,7 +5209,7 @@ namespace FourSlashInterface { readonly containerKind?: ts.ScriptElementKind; } - export type ArrayOrSingle = T | ReadonlyArray; + export type ArrayOrSingle = T | readonly T[]; export interface VerifyCompletionListContainsOptions extends ts.UserPreferences { triggerCharacter?: ts.CompletionsTriggerCharacter; @@ -5220,7 +5220,7 @@ namespace FourSlashInterface { } export interface VerifyDocumentHighlightsOptions { - filesToSearch?: ReadonlyArray; + filesToSearch?: readonly string[]; } export type NewFileContent = string | { readonly [filename: string]: string }; @@ -5237,7 +5237,7 @@ namespace FourSlashInterface { readonly index?: number; readonly preferences?: ts.UserPreferences; readonly applyChanges?: boolean; - readonly commands?: ReadonlyArray; + readonly commands?: readonly ts.CodeActionCommand[]; } export interface VerifyCodeFixAvailableOptions { @@ -5249,13 +5249,13 @@ namespace FourSlashInterface { fixId: string; fixAllDescription: string; newFileContent: NewFileContent; - commands: ReadonlyArray<{}>; + commands: readonly {}[]; } export interface VerifyRefactorOptions { name: string; actionName: string; - refactors: ReadonlyArray; + refactors: readonly ts.ApplicableRefactorInfo[]; } export interface VerifyCompletionActionOptions extends NewContentOptions { @@ -5284,10 +5284,10 @@ namespace FourSlashInterface { readonly preferences?: ts.UserPreferences; } - export type RenameLocationsOptions = ReadonlyArray | { + export type RenameLocationsOptions = readonly RenameLocationOptions[] | { readonly findInStrings?: boolean; readonly findInComments?: boolean; - readonly ranges: ReadonlyArray; + readonly ranges: readonly RenameLocationOptions[]; readonly providePrefixAndSuffixTextForRename?: boolean; }; export type RenameLocationOptions = FourSlash.Range | { readonly range: FourSlash.Range, readonly prefixText?: string, readonly suffixText?: string }; diff --git a/src/harness/harness.ts b/src/harness/harness.ts index 2f7c1a9f30c..ae37035aa84 100644 --- a/src/harness/harness.ts +++ b/src/harness/harness.ts @@ -16,7 +16,7 @@ const assert: typeof _chai.assert = _chai.assert; } assertDeepImpl(a, b, msg); - function arrayExtraKeysObject(a: ReadonlyArray<{} | null | undefined>): object { + function arrayExtraKeysObject(a: readonly ({} | null | undefined)[]): object { const obj: { [key: string]: {} | null | undefined } = {}; for (const key in a) { if (Number.isNaN(Number(key))) { @@ -177,7 +177,7 @@ namespace Utils { return a !== undefined && typeof a.pos === "number"; } - export function convertDiagnostics(diagnostics: ReadonlyArray) { + export function convertDiagnostics(diagnostics: readonly ts.Diagnostic[]) { return diagnostics.map(convertDiagnostic); } @@ -248,7 +248,7 @@ namespace Utils { o.containsParseError = true; } - for (const propertyName of Object.getOwnPropertyNames(n) as ReadonlyArray) { + for (const propertyName of Object.getOwnPropertyNames(n) as readonly (keyof ts.SourceFile | keyof ts.Identifier)[]) { switch (propertyName) { case "parent": case "symbol": @@ -303,7 +303,7 @@ namespace Utils { } } - export function assertDiagnosticsEquals(array1: ReadonlyArray, array2: ReadonlyArray) { + export function assertDiagnosticsEquals(array1: readonly ts.Diagnostic[], array2: readonly ts.Diagnostic[]) { if (array1 === array2) { return; } @@ -462,7 +462,7 @@ namespace Harness { getExecutingFilePath(): string; getWorkspaceRoot(): string; exit(exitCode?: number): void; - readDirectory(path: string, extension?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): ReadonlyArray; + readDirectory(path: string, extension?: readonly string[], exclude?: readonly string[], include?: readonly string[], depth?: number): readonly string[]; getAccessibleFileSystemEntries(dirname: string): ts.FileSystemEntries; tryEnableSourceMapsForHost?(): void; getEnvironmentVariable?(name: string): string; @@ -875,8 +875,8 @@ namespace Harness { currentDirectory: string; } - export function prepareDeclarationCompilationContext(inputFiles: ReadonlyArray, - otherFiles: ReadonlyArray, + export function prepareDeclarationCompilationContext(inputFiles: readonly TestFile[], + otherFiles: readonly TestFile[], result: compiler.CompilationResult, harnessSettings: TestCaseParser.CompilerSettings & HarnessOptions, options: ts.CompilerOptions, @@ -955,12 +955,12 @@ namespace Harness { return { declInputFiles, declOtherFiles, declResult: output }; } - export function minimalDiagnosticsToString(diagnostics: ReadonlyArray, pretty?: boolean) { + export function minimalDiagnosticsToString(diagnostics: readonly ts.Diagnostic[], pretty?: boolean) { const host = { getCanonicalFileName, getCurrentDirectory: () => "", getNewLine: () => IO.newLine() }; return (pretty ? ts.formatDiagnosticsWithColorAndContext : ts.formatDiagnostics)(diagnostics, host); } - export function getErrorBaseline(inputFiles: ReadonlyArray, diagnostics: ReadonlyArray, pretty?: boolean) { + export function getErrorBaseline(inputFiles: readonly TestFile[], diagnostics: readonly ts.Diagnostic[], pretty?: boolean) { let outputLines = ""; const gen = iterateErrorBaseline(inputFiles, diagnostics, { pretty }); for (let {done, value} = gen.next(); !done; { done, value } = gen.next()) { @@ -975,7 +975,7 @@ namespace Harness { export const diagnosticSummaryMarker = "__diagnosticSummary"; export const globalErrorsMarker = "__globalErrors"; - export function *iterateErrorBaseline(inputFiles: ReadonlyArray, diagnostics: ReadonlyArray, options?: { pretty?: boolean, caseSensitive?: boolean, currentDirectory?: string }): IterableIterator<[string, string, number]> { + export function *iterateErrorBaseline(inputFiles: readonly TestFile[], diagnostics: readonly ts.Diagnostic[], options?: { pretty?: boolean, caseSensitive?: boolean, currentDirectory?: string }): IterableIterator<[string, string, number]> { diagnostics = ts.sort(diagnostics, ts.compareDiagnostics); let outputLines = ""; // Count up all errors that were found in files other than lib.d.ts so we don't miss any @@ -1127,7 +1127,7 @@ namespace Harness { assert.equal(totalErrorsReportedInNonLibraryFiles + numLibraryDiagnostics + numTest262HarnessDiagnostics, diagnostics.length, "total number of errors"); } - export function doErrorBaseline(baselinePath: string, inputFiles: ReadonlyArray, errors: ReadonlyArray, pretty?: boolean) { + export function doErrorBaseline(baselinePath: string, inputFiles: readonly TestFile[], errors: readonly ts.Diagnostic[], pretty?: boolean) { Baseline.runBaseline(baselinePath.replace(/\.tsx?$/, ".errors.txt"), !errors || (errors.length === 0) ? null : getErrorBaseline(inputFiles, errors, pretty)); // eslint-disable-line no-null/no-null } @@ -1291,7 +1291,7 @@ namespace Harness { } } - export function doJsEmitBaseline(baselinePath: string, header: string, options: ts.CompilerOptions, result: compiler.CompilationResult, tsConfigFiles: ReadonlyArray, toBeCompiled: ReadonlyArray, otherFiles: ReadonlyArray, harnessSettings: TestCaseParser.CompilerSettings) { + export function doJsEmitBaseline(baselinePath: string, header: string, options: ts.CompilerOptions, result: compiler.CompilationResult, tsConfigFiles: readonly TestFile[], toBeCompiled: readonly TestFile[], otherFiles: readonly TestFile[], harnessSettings: TestCaseParser.CompilerSettings) { if (!options.noEmit && !options.emitDeclarationOnly && result.js.size === 0 && result.diagnostics.length === 0) { throw new Error("Expected at least one js file to be emitted or at least one error to be created."); } @@ -1349,7 +1349,7 @@ namespace Harness { return "//// [" + fileName + "]\r\n" + utils.removeTestPathPrefixes(file.text); } - export function collateOutputs(outputFiles: ReadonlyArray): string { + export function collateOutputs(outputFiles: readonly documents.TextDocument[]): string { const gen = iterateOutputs(outputFiles); // Emit them let result = ""; diff --git a/src/harness/harnessLanguageService.ts b/src/harness/harnessLanguageService.ts index edd27361489..b688b4822db 100644 --- a/src/harness/harnessLanguageService.ts +++ b/src/harness/harnessLanguageService.ts @@ -252,7 +252,7 @@ namespace Harness.LanguageService { return this.sys.fileExists(fileName); } - readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[] { + readDirectory(path: string, extensions?: readonly string[], exclude?: readonly string[], include?: readonly string[], depth?: number): string[] { return this.sys.readDirectory(path, extensions, exclude, include, depth); } @@ -558,10 +558,10 @@ namespace Harness.LanguageService { getApplicableRefactors(): ts.ApplicableRefactorInfo[] { throw new Error("Not supported on the shim."); } - organizeImports(_scope: ts.OrganizeImportsScope, _formatOptions: ts.FormatCodeSettings): ReadonlyArray { + organizeImports(_scope: ts.OrganizeImportsScope, _formatOptions: ts.FormatCodeSettings): readonly ts.FileTextChanges[] { throw new Error("Not supported on the shim."); } - getEditsForFileRename(): ReadonlyArray { + getEditsForFileRename(): readonly ts.FileTextChanges[] { throw new Error("Not supported on the shim."); } getEmitOutput(fileName: string): ts.EmitOutput { @@ -724,7 +724,7 @@ namespace Harness.LanguageService { return ts.sys.getEnvironmentVariable(name); } - readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[] { + readDirectory(path: string, extensions?: readonly string[], exclude?: readonly string[], include?: readonly string[], depth?: number): string[] { return this.host.readDirectory(path, extensions, exclude, include, depth); } diff --git a/src/harness/loggedIO.ts b/src/harness/loggedIO.ts index ffa9344a863..5fad3405e0e 100644 --- a/src/harness/loggedIO.ts +++ b/src/harness/loggedIO.ts @@ -62,11 +62,11 @@ interface IoLog { }[]; directoriesRead: { path: string, - extensions: ReadonlyArray | undefined, - exclude: ReadonlyArray | undefined, - include: ReadonlyArray | undefined, + extensions: readonly string[] | undefined, + exclude: readonly string[] | undefined, + include: readonly string[] | undefined, depth: number | undefined, - result: ReadonlyArray, + result: readonly string[], }[]; useCaseSensitiveFileNames?: boolean; } diff --git a/src/harness/sourceMapRecorder.ts b/src/harness/sourceMapRecorder.ts index 829e047eade..e0d6765bcf7 100644 --- a/src/harness/sourceMapRecorder.ts +++ b/src/harness/sourceMapRecorder.ts @@ -44,7 +44,7 @@ namespace Harness.SourceMapRecorder { let sourceMapNames: string[] | null | undefined; let jsFile: documents.TextDocument; - let jsLineMap: ReadonlyArray; + let jsLineMap: readonly number[]; let tsCode: string; let tsLineMap: number[]; @@ -153,7 +153,7 @@ namespace Harness.SourceMapRecorder { writeJsFileLines(jsLineMap.length); } - function getTextOfLine(line: number, lineMap: ReadonlyArray, code: string) { + function getTextOfLine(line: number, lineMap: readonly number[], code: string) { const startPos = lineMap[line]; const endPos = lineMap[line + 1]; const text = code.substring(startPos, endPos); @@ -275,7 +275,7 @@ namespace Harness.SourceMapRecorder { } } - export function getSourceMapRecord(sourceMapDataList: ReadonlyArray, program: ts.Program, jsFiles: ReadonlyArray, declarationFiles: ReadonlyArray) { + export function getSourceMapRecord(sourceMapDataList: readonly ts.SourceMapEmitResult[], program: ts.Program, jsFiles: readonly documents.TextDocument[], declarationFiles: readonly documents.TextDocument[]) { const sourceMapRecorder = new Compiler.WriterAggregator(); for (let i = 0; i < sourceMapDataList.length; i++) { diff --git a/src/harness/vfs.ts b/src/harness/vfs.ts index 450d50d525c..cf0ba198410 100644 --- a/src/harness/vfs.ts +++ b/src/harness/vfs.ts @@ -1160,7 +1160,7 @@ namespace vfs { export interface FileSystemCreateOptions extends FileSystemOptions { // Sets the documents to add to the file system. - documents?: ReadonlyArray; + documents?: readonly documents.TextDocument[]; } export type Axis = "ancestors" | "ancestors-or-self" | "self" | "descendants-or-self" | "descendants"; diff --git a/src/harness/virtualFileSystemWithWatch.ts b/src/harness/virtualFileSystemWithWatch.ts index 13b87e1c91a..d50cbdad184 100644 --- a/src/harness/virtualFileSystemWithWatch.ts +++ b/src/harness/virtualFileSystemWithWatch.ts @@ -39,7 +39,7 @@ interface Array {}` environmentVariables?: Map; } - export function createWatchedSystem(fileOrFolderList: ReadonlyArray, params?: TestServerHostCreationParameters): TestServerHost { + export function createWatchedSystem(fileOrFolderList: readonly FileOrFolderOrSymLink[], params?: TestServerHostCreationParameters): TestServerHost { if (!params) { params = {}; } @@ -54,7 +54,7 @@ interface Array {}` return host; } - export function createServerHost(fileOrFolderList: ReadonlyArray, params?: TestServerHostCreationParameters): TestServerHost { + export function createServerHost(fileOrFolderList: readonly FileOrFolderOrSymLink[], params?: TestServerHostCreationParameters): TestServerHost { if (!params) { params = {}; } @@ -128,7 +128,7 @@ interface Array {}` return s && isString((s).symLink); } - function invokeWatcherCallbacks(callbacks: ReadonlyArray | undefined, invokeCallback: (cb: T) => void): void { + function invokeWatcherCallbacks(callbacks: readonly T[] | undefined, invokeCallback: (cb: T) => void): void { if (callbacks) { // The array copy is made to ensure that even if one of the callback removes the callbacks, // we dont miss any callbacks following it @@ -139,7 +139,7 @@ interface Array {}` } } - function getDiffInKeys(map: Map, expectedKeys: ReadonlyArray) { + function getDiffInKeys(map: Map, expectedKeys: readonly string[]) { if (map.size === expectedKeys.length) { return ""; } @@ -166,11 +166,11 @@ interface Array {}` return `\n\nNotInActual: ${notInActual}\nDuplicates: ${duplicates}\nInActualButNotInExpected: ${inActualNotExpected}`; } - export function verifyMapSize(caption: string, map: Map, expectedKeys: ReadonlyArray) { + export function verifyMapSize(caption: string, map: Map, expectedKeys: readonly string[]) { assert.equal(map.size, expectedKeys.length, `${caption}: incorrect size of map: Actual keys: ${arrayFrom(map.keys())} Expected: ${expectedKeys}${getDiffInKeys(map, expectedKeys)}`); } - function checkMapKeys(caption: string, map: Map, expectedKeys: ReadonlyArray) { + function checkMapKeys(caption: string, map: Map, expectedKeys: readonly string[]) { verifyMapSize(caption, map, expectedKeys); for (const name of expectedKeys) { assert.isTrue(map.has(name), `${caption} is expected to contain ${name}, actual keys: ${arrayFrom(map.keys())}`); @@ -178,8 +178,8 @@ interface Array {}` } export function checkMultiMapKeyCount(caption: string, actual: MultiMap, expectedKeys: ReadonlyMap): void; - export function checkMultiMapKeyCount(caption: string, actual: MultiMap, expectedKeys: ReadonlyArray, eachKeyCount: number): void; - export function checkMultiMapKeyCount(caption: string, actual: MultiMap, expectedKeysMapOrArray: ReadonlyMap | ReadonlyArray, eachKeyCount?: number) { + export function checkMultiMapKeyCount(caption: string, actual: MultiMap, expectedKeys: readonly string[], eachKeyCount: number): void; + export function checkMultiMapKeyCount(caption: string, actual: MultiMap, expectedKeysMapOrArray: ReadonlyMap | readonly string[], eachKeyCount?: number) { const expectedKeys = isArray(expectedKeysMapOrArray) ? arrayToMap(expectedKeysMapOrArray, s => s, () => eachKeyCount!) : expectedKeysMapOrArray; verifyMapSize(caption, actual, arrayFrom(expectedKeys.keys())); expectedKeys.forEach((count, name) => { @@ -188,7 +188,7 @@ interface Array {}` }); } - export function checkArray(caption: string, actual: ReadonlyArray, expected: ReadonlyArray) { + export function checkArray(caption: string, actual: readonly string[], expected: readonly string[]) { checkMapKeys(caption, arrayToMap(actual, identity), expected); assert.equal(actual.length, expected.length, `${caption}: incorrect actual number of files, expected:\r\n${expected.join("\r\n")}\r\ngot: ${actual.join("\r\n")}`); for (const f of expected) { @@ -201,8 +201,8 @@ interface Array {}` } export function checkWatchedFilesDetailed(host: TestServerHost, expectedFiles: ReadonlyMap): void; - export function checkWatchedFilesDetailed(host: TestServerHost, expectedFiles: ReadonlyArray, eachFileWatchCount: number): void; - export function checkWatchedFilesDetailed(host: TestServerHost, expectedFiles: ReadonlyMap | ReadonlyArray, eachFileWatchCount?: number) { + export function checkWatchedFilesDetailed(host: TestServerHost, expectedFiles: readonly string[], eachFileWatchCount: number): void; + export function checkWatchedFilesDetailed(host: TestServerHost, expectedFiles: ReadonlyMap | readonly string[], eachFileWatchCount?: number) { if (isArray(expectedFiles)) { checkMultiMapKeyCount("watchedFiles", host.watchedFiles, expectedFiles, eachFileWatchCount!); } @@ -216,8 +216,8 @@ interface Array {}` } export function checkWatchedDirectoriesDetailed(host: TestServerHost, expectedDirectories: ReadonlyMap, recursive: boolean): void; - export function checkWatchedDirectoriesDetailed(host: TestServerHost, expectedDirectories: ReadonlyArray, eachDirectoryWatchCount: number, recursive: boolean): void; - export function checkWatchedDirectoriesDetailed(host: TestServerHost, expectedDirectories: ReadonlyMap | ReadonlyArray, recursiveOrEachDirectoryWatchCount: boolean | number, recursive?: boolean) { + export function checkWatchedDirectoriesDetailed(host: TestServerHost, expectedDirectories: readonly string[], eachDirectoryWatchCount: number, recursive: boolean): void; + export function checkWatchedDirectoriesDetailed(host: TestServerHost, expectedDirectories: ReadonlyMap | readonly string[], recursiveOrEachDirectoryWatchCount: boolean | number, recursive?: boolean) { if (isArray(expectedDirectories)) { checkMultiMapKeyCount(`watchedDirectories${recursive ? " recursive" : ""}`, recursive ? host.watchedDirectoriesRecursive : host.watchedDirectories, expectedDirectories, recursiveOrEachDirectoryWatchCount as number); } @@ -227,7 +227,7 @@ interface Array {}` } } - export function checkOutputContains(host: TestServerHost, expected: ReadonlyArray) { + export function checkOutputContains(host: TestServerHost, expected: readonly string[]) { const mapExpected = arrayToSet(expected); const mapSeen = createMap(); for (const f of host.getOutput()) { @@ -240,7 +240,7 @@ interface Array {}` assert.equal(mapExpected.size, 0, `Output has missing ${JSON.stringify(arrayFrom(mapExpected.keys()))} in ${JSON.stringify(host.getOutput())}`); } - export function checkOutputDoesNotContain(host: TestServerHost, expectedToBeAbsent: string[] | ReadonlyArray) { + export function checkOutputDoesNotContain(host: TestServerHost, expectedToBeAbsent: string[] | readonly string[]) { const mapExpectedToBeAbsent = arrayToSet(expectedToBeAbsent); for (const f of host.getOutput()) { assert.isFalse(mapExpectedToBeAbsent.has(f), `Contains ${f} in ${JSON.stringify(host.getOutput())}`); @@ -348,7 +348,7 @@ interface Array {}` private readonly customRecursiveWatchDirectory: HostWatchDirectory | undefined; public require: ((initialPath: string, moduleName: string) => server.RequireResult) | undefined; - constructor(public withSafeList: boolean, public useCaseSensitiveFileNames: boolean, executingFilePath: string, currentDirectory: string, fileOrFolderorSymLinkList: ReadonlyArray, public readonly newLine = "\n", public readonly useWindowsStylePath?: boolean, private readonly environmentVariables?: Map) { + constructor(public withSafeList: boolean, public useCaseSensitiveFileNames: boolean, executingFilePath: string, currentDirectory: string, fileOrFolderorSymLinkList: readonly FileOrFolderOrSymLink[], public readonly newLine = "\n", public readonly useWindowsStylePath?: boolean, private readonly environmentVariables?: Map) { this.getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); this.toPath = s => toPath(s, currentDirectory, this.getCanonicalFileName); this.executingFilePath = this.getHostSpecificPath(executingFilePath); @@ -429,11 +429,11 @@ interface Array {}` return new Date(this.time); } - reloadFS(fileOrFolderOrSymLinkList: ReadonlyArray, options?: Partial) { + reloadFS(fileOrFolderOrSymLinkList: readonly FileOrFolderOrSymLink[], options?: Partial) { const mapNewLeaves = createMap(); const isNewFs = this.fs.size === 0; fileOrFolderOrSymLinkList = fileOrFolderOrSymLinkList.concat(this.withSafeList ? safeList : []); - const filesOrFoldersToLoad: ReadonlyArray = !this.useWindowsStylePath ? fileOrFolderOrSymLinkList : + const filesOrFoldersToLoad: readonly FileOrFolderOrSymLink[] = !this.useWindowsStylePath ? fileOrFolderOrSymLinkList : fileOrFolderOrSymLinkList.map(f => { const result = clone(f); result.path = this.getHostSpecificPath(f.path); @@ -826,7 +826,7 @@ interface Array {}` return []; } - readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[] { + readDirectory(path: string, extensions?: readonly string[], exclude?: readonly string[], include?: readonly string[], depth?: number): string[] { return matchFiles(path, extensions, exclude, include, this.useCaseSensitiveFileNames, this.getCurrentDirectory(), depth, (dir) => { const directories: string[] = []; const files: string[] = []; @@ -973,7 +973,7 @@ interface Array {}` this.output.push(message); } - getOutput(): ReadonlyArray { + getOutput(): readonly string[] { return this.output; } diff --git a/src/harness/vpath.ts b/src/harness/vpath.ts index 68ba0465e50..31419e976ff 100644 --- a/src/harness/vpath.ts +++ b/src/harness/vpath.ts @@ -115,7 +115,7 @@ namespace vpath { return extname(path, ".map", /*ignoreCase*/ false).length > 0; } - const javaScriptSourceMapExtensions: ReadonlyArray = [".js.map", ".jsx.map"]; + const javaScriptSourceMapExtensions: readonly string[] = [".js.map", ".jsx.map"]; export function isJavaScriptSourceMap(path: string) { return extname(path, javaScriptSourceMapExtensions, /*ignoreCase*/ false).length > 0; diff --git a/src/jsTyping/jsTyping.ts b/src/jsTyping/jsTyping.ts index 172d041cc01..70efac4aee1 100644 --- a/src/jsTyping/jsTyping.ts +++ b/src/jsTyping/jsTyping.ts @@ -5,7 +5,7 @@ namespace ts.JsTyping { directoryExists(path: string): boolean; fileExists(fileName: string): boolean; readFile(path: string, encoding?: string): string | undefined; - readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray | undefined, depth?: number): string[]; + readDirectory(rootDir: string, extensions: readonly string[], excludes: readonly string[] | undefined, includes: readonly string[] | undefined, depth?: number): string[]; } interface PackageJson { @@ -29,7 +29,7 @@ namespace ts.JsTyping { return availableVersion.compareTo(cachedTyping.version) <= 0; } - export const nodeCoreModuleList: ReadonlyArray = [ + export const nodeCoreModuleList: readonly string[] = [ "assert", "async_hooks", "buffer", @@ -109,7 +109,7 @@ namespace ts.JsTyping { safeList: SafeList, packageNameToTypingLocation: ReadonlyMap, typeAcquisition: TypeAcquisition, - unresolvedImports: ReadonlyArray, + unresolvedImports: readonly string[], typesRegistry: ReadonlyMap>): { cachedTypingPaths: string[], newTypingNames: string[], filesToWatch: string[] } { @@ -192,7 +192,7 @@ namespace ts.JsTyping { inferredTypings.set(typingName, undefined!); // TODO: GH#18217 } } - function addInferredTypings(typingNames: ReadonlyArray, message: string) { + function addInferredTypings(typingNames: readonly string[], message: string) { if (log) log(`${message}: ${JSON.stringify(typingNames)}`); forEach(typingNames, addInferredTyping); } diff --git a/src/jsTyping/types.ts b/src/jsTyping/types.ts index f9e2a38fea7..0857dff1133 100644 --- a/src/jsTyping/types.ts +++ b/src/jsTyping/types.ts @@ -72,7 +72,7 @@ declare namespace ts.server { readonly kind: EventBeginInstallTypes | EventEndInstallTypes; readonly eventId: number; readonly typingsInstallerVersion: string; - readonly packagesToInstall: ReadonlyArray; + readonly packagesToInstall: readonly string[]; } export interface BeginInstallTypes extends InstallTypes { diff --git a/src/lib/es2015.collection.d.ts b/src/lib/es2015.collection.d.ts index 4f293f0f6c3..83a7719acef 100644 --- a/src/lib/es2015.collection.d.ts +++ b/src/lib/es2015.collection.d.ts @@ -10,7 +10,7 @@ interface Map { interface MapConstructor { new(): Map; - new(entries?: ReadonlyArray | null): Map; + new(entries?: readonly (readonly [K, V])[] | null): Map; readonly prototype: Map; } declare var Map: MapConstructor; @@ -30,7 +30,7 @@ interface WeakMap { } interface WeakMapConstructor { - new (entries?: ReadonlyArray<[K, V]> | null): WeakMap; + new (entries?: readonly [K, V][] | null): WeakMap; readonly prototype: WeakMap; } declare var WeakMap: WeakMapConstructor; @@ -45,7 +45,7 @@ interface Set { } interface SetConstructor { - new (values?: ReadonlyArray | null): Set; + new (values?: readonly T[] | null): Set; readonly prototype: Set; } declare var Set: SetConstructor; @@ -63,7 +63,7 @@ interface WeakSet { } interface WeakSetConstructor { - new (values?: ReadonlyArray | null): WeakSet; + new (values?: readonly T[] | null): WeakSet; readonly prototype: WeakSet; } declare var WeakSet: WeakSetConstructor; diff --git a/src/lib/es2015.core.d.ts b/src/lib/es2015.core.d.ts index 9e9120e9428..8a3e4cf80f6 100644 --- a/src/lib/es2015.core.d.ts +++ b/src/lib/es2015.core.d.ts @@ -329,8 +329,8 @@ interface ReadonlyArray { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (this: void, value: T, index: number, obj: ReadonlyArray) => value is S, thisArg?: any): S | undefined; - find(predicate: (value: T, index: number, obj: ReadonlyArray) => unknown, thisArg?: any): T | undefined; + find(predicate: (this: void, value: T, index: number, obj: readonly T[]) => value is S, thisArg?: any): S | undefined; + find(predicate: (value: T, index: number, obj: readonly T[]) => unknown, thisArg?: any): T | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -341,7 +341,7 @@ interface ReadonlyArray { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: T, index: number, obj: ReadonlyArray) => unknown, thisArg?: any): number; + findIndex(predicate: (value: T, index: number, obj: readonly T[]) => unknown, thisArg?: any): number; } interface RegExp { diff --git a/src/lib/es2019.array.d.ts b/src/lib/es2019.array.d.ts index 3240da61025..4e664011f52 100644 --- a/src/lib/es2019.array.d.ts +++ b/src/lib/es2019.array.d.ts @@ -11,7 +11,7 @@ interface ReadonlyArray { * thisArg is omitted, undefined is used as the this value. */ flatMap ( - callback: (this: This, value: T, index: number, array: T[]) => U | ReadonlyArray, + callback: (this: This, value: T, index: number, array: T[]) => U | readonly U[], thisArg?: This ): U[] @@ -23,26 +23,26 @@ interface ReadonlyArray { * @param depth The maximum recursion depth */ flat(this: - ReadonlyArray | + readonly U[][][][][] | - ReadonlyArray> | - ReadonlyArray[]> | - ReadonlyArray[][]> | - ReadonlyArray[][][]> | + readonly (readonly U[][][][])[] | + readonly readonly U[][][][][] | + readonly readonly U[][][][][] | + readonly readonly U[][][][][] | - ReadonlyArray>> | - ReadonlyArray[][]>> | - ReadonlyArray>[][]> | - ReadonlyArray[]>[]> | - ReadonlyArray>[]> | - ReadonlyArray[]>> | + readonly (readonly (readonly U[][][])[])[] | + readonly (readonly readonly U[][][][])[] | + readonly readonly (readonly U[])[][][][] | + readonly readonly readonly U[][][][][] | + readonly readonly (readonly U[][])[][][] | + readonly (readonly readonly U[][][][])[] | - ReadonlyArray>>> | - ReadonlyArray[]>>> | - ReadonlyArray>[]>> | - ReadonlyArray>>[]> | + readonly (readonly (readonly (readonly U[][])[])[])[] | + readonly (readonly (readonly readonly U[][][])[])[] | + readonly (readonly readonly (readonly U[])[][][])[] | + readonly readonly (readonly (readonly U[])[])[][][] | - ReadonlyArray>>>>, + readonly (readonly (readonly (readonly (readonly U[])[])[])[])[], depth: 4): U[]; /** @@ -52,17 +52,17 @@ interface ReadonlyArray { * @param depth The maximum recursion depth */ flat(this: - ReadonlyArray | + readonly U[][][][] | - ReadonlyArray[][]> | - ReadonlyArray[]> | - ReadonlyArray> | + readonly readonly U[][][][] | + readonly readonly U[][][][] | + readonly (readonly U[][][])[] | - ReadonlyArray>> | - ReadonlyArray[]>> | - ReadonlyArray>[]> | + readonly (readonly (readonly U[][])[])[] | + readonly (readonly readonly U[][][])[] | + readonly readonly (readonly U[])[][][] | - ReadonlyArray>>>, + readonly (readonly (readonly (readonly U[])[])[])[], depth: 3): U[]; /** @@ -72,12 +72,12 @@ interface ReadonlyArray { * @param depth The maximum recursion depth */ flat(this: - ReadonlyArray | + readonly U[][][] | - ReadonlyArray> | - ReadonlyArray[]> | + readonly (readonly U[][])[] | + readonly readonly U[][][] | - ReadonlyArray>>, + readonly (readonly (readonly U[])[])[], depth: 2): U[]; /** @@ -87,8 +87,8 @@ interface ReadonlyArray { * @param depth The maximum recursion depth */ flat(this: - ReadonlyArray | - ReadonlyArray>, + readonly U[][] | + readonly (readonly U[])[], depth?: 1 ): U[]; @@ -98,7 +98,7 @@ interface ReadonlyArray { * * @param depth The maximum recursion depth */ - flat(this: ReadonlyArray, depth: 0): U[]; + flat(this: readonly U[], depth: 0): U[]; /** * Returns a new array with all sub-array elements concatenated into it recursively up to the @@ -122,7 +122,7 @@ interface Array { * thisArg is omitted, undefined is used as the this value. */ flatMap ( - callback: (this: This, value: T, index: number, array: T[]) => U | ReadonlyArray, + callback: (this: This, value: T, index: number, array: T[]) => U | readonly U[], thisArg?: This ): U[] diff --git a/src/lib/es2019.object.d.ts b/src/lib/es2019.object.d.ts index 7d50b6d1508..69b185d7ca9 100644 --- a/src/lib/es2019.object.d.ts +++ b/src/lib/es2019.object.d.ts @@ -11,5 +11,5 @@ interface ObjectConstructor { * Returns an object created by key-value entries for properties and methods * @param entries An iterable object that contains key-value entries for properties and methods. */ - fromEntries(entries: Iterable>): any; + fromEntries(entries: Iterable): any; } diff --git a/src/lib/es5.d.ts b/src/lib/es5.d.ts index bb5b46a13c2..07048926b35 100644 --- a/src/lib/es5.d.ts +++ b/src/lib/es5.d.ts @@ -196,7 +196,7 @@ interface ObjectConstructor { * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. * @param o Object on which to lock the attributes. */ - freeze(a: T[]): ReadonlyArray; + freeze(a: T[]): readonly T[]; /** * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. @@ -582,7 +582,7 @@ interface NumberConstructor { declare var Number: NumberConstructor; interface TemplateStringsArray extends ReadonlyArray { - readonly raw: ReadonlyArray; + readonly raw: readonly string[]; } /** @@ -1114,63 +1114,63 @@ interface ReadonlyArray { * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - every(callbackfn: (value: T, index: number, array: ReadonlyArray) => unknown, thisArg?: any): boolean; + every(callbackfn: (value: T, index: number, array: readonly T[]) => unknown, thisArg?: any): boolean; /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - some(callbackfn: (value: T, index: number, array: ReadonlyArray) => unknown, thisArg?: any): boolean; + some(callbackfn: (value: T, index: number, array: readonly T[]) => unknown, thisArg?: any): boolean; /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (value: T, index: number, array: ReadonlyArray) => void, thisArg?: any): void; + forEach(callbackfn: (value: T, index: number, array: readonly T[]) => void, thisArg?: any): void; /** * Calls a defined callback function on each element of an array, and returns an array that contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (value: T, index: number, array: ReadonlyArray) => U, thisArg?: any): U[]; + map(callbackfn: (value: T, index: number, array: readonly T[]) => U, thisArg?: any): U[]; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => value is S, thisArg?: any): S[]; + filter(callbackfn: (value: T, index: number, array: readonly T[]) => value is S, thisArg?: any): S[]; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => unknown, thisArg?: any): T[]; + filter(callbackfn: (value: T, index: number, array: readonly T[]) => unknown, thisArg?: any): T[]; /** * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ - reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T): T; - reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue: T): T; + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T): T; + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T, initialValue: T): T; /** * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ - reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray) => U, initialValue: U): U; + reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: readonly T[]) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T): T; - reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue: T): T; + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T): T; + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T, initialValue: T): T; /** * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray) => U, initialValue: U): U; + reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: readonly T[]) => U, initialValue: U): U; readonly [n: number]: T; } diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index 90b44abc48f..733eaffbf60 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -34,7 +34,7 @@ namespace ts.server { export interface ConfigFileDiagEvent { eventName: typeof ConfigFileDiagEvent; - data: { triggerFile: string, configFileName: string, diagnostics: ReadonlyArray }; + data: { triggerFile: string, configFileName: string, diagnostics: readonly Diagnostic[] }; } export interface ProjectLanguageServiceStateEvent { @@ -281,7 +281,7 @@ namespace ts.server { export interface OpenConfiguredProjectResult { configFileName?: NormalizedPath; - configFileErrors?: ReadonlyArray; + configFileErrors?: readonly Diagnostic[]; } interface AssignProjectResult extends OpenConfiguredProjectResult { @@ -375,8 +375,8 @@ namespace ts.server { eventHandler?: ProjectServiceEventHandler; suppressDiagnosticEvents?: boolean; throttleWaitMilliseconds?: number; - globalPlugins?: ReadonlyArray; - pluginProbeLocations?: ReadonlyArray; + globalPlugins?: readonly string[]; + pluginProbeLocations?: readonly string[]; allowLocalPluginLoads?: boolean; typesMapLocation?: string; syntaxOnly?: boolean; @@ -519,8 +519,8 @@ namespace ts.server { private readonly eventHandler?: ProjectServiceEventHandler; private readonly suppressDiagnosticEvents?: boolean; - public readonly globalPlugins: ReadonlyArray; - public readonly pluginProbeLocations: ReadonlyArray; + public readonly globalPlugins: readonly string[]; + public readonly pluginProbeLocations: readonly string[]; public readonly allowLocalPluginLoads: boolean; private currentPluginConfigOverrides: Map | undefined; @@ -777,7 +777,7 @@ namespace ts.server { this.delayEnsureProjectForOpenFiles(); } - private delayUpdateProjectGraphs(projects: ReadonlyArray) { + private delayUpdateProjectGraphs(projects: readonly Project[]) { if (projects.length) { for (const project of projects) { this.delayUpdateProjectGraph(project); @@ -2640,7 +2640,7 @@ namespace ts.server { private assignProjectToOpenedScriptInfo(info: ScriptInfo): AssignProjectResult { let configFileName: NormalizedPath | undefined; - let configFileErrors: ReadonlyArray | undefined; + let configFileErrors: readonly Diagnostic[] | undefined; let project: ConfiguredProject | ExternalProject | undefined = this.findExternalProjectContainingOpenScriptInfo(info); let defaultConfigProject: ConfiguredProject | undefined; if (!project && !this.syntaxOnly) { // Checking syntaxOnly is an optimization diff --git a/src/server/project.ts b/src/server/project.ts index 46448232463..e6d66ec8ef7 100644 --- a/src/server/project.ts +++ b/src/server/project.ts @@ -75,7 +75,7 @@ namespace ts.server { /* @internal */ export interface ProjectFilesWithTSDiagnostics extends protocol.ProjectFiles { - projectErrors: ReadonlyArray; + projectErrors: readonly Diagnostic[]; } export interface PluginCreateInfo { @@ -133,7 +133,7 @@ namespace ts.server { * Maop does not contain entries for files that do not have unresolved imports * This helps in containing the set of files to invalidate */ - cachedUnresolvedImportsPerFile = createMap>(); + cachedUnresolvedImportsPerFile = createMap(); /*@internal*/ lastCachedUnresolvedImportsList: SortedReadonlyArray | undefined; @@ -310,7 +310,7 @@ namespace ts.server { return this.projectStateVersion.toString(); } - getProjectReferences(): ReadonlyArray | undefined { + getProjectReferences(): readonly ProjectReference[] | undefined { return undefined; } @@ -378,7 +378,7 @@ namespace ts.server { return this.projectService.host.useCaseSensitiveFileNames; } - readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[] { + readDirectory(path: string, extensions?: readonly string[], exclude?: readonly string[], include?: readonly string[], depth?: number): string[] { return this.directoryStructureHost.readDirectory!(path, extensions, exclude, include, depth); } @@ -497,11 +497,11 @@ namespace ts.server { /** * Get the errors that dont have any file name associated */ - getGlobalProjectErrors(): ReadonlyArray { + getGlobalProjectErrors(): readonly Diagnostic[] { return emptyArray; } - getAllProjectErrors(): ReadonlyArray { + getAllProjectErrors(): readonly Diagnostic[] { return emptyArray; } @@ -714,7 +714,7 @@ namespace ts.server { }); } - getExcludedFiles(): ReadonlyArray { + getExcludedFiles(): readonly NormalizedPath[] { return emptyArray; } @@ -858,7 +858,7 @@ namespace ts.server { const hasAddedorRemovedFiles = this.hasAddedorRemovedFiles; this.hasAddedorRemovedFiles = false; - const changedFiles: ReadonlyArray = this.resolutionCache.finishRecordingFilesWithChangedResolutions() || emptyArray; + const changedFiles: readonly Path[] = this.resolutionCache.finishRecordingFilesWithChangedResolutions() || emptyArray; for (const file of changedFiles) { // delete cached information for changed files @@ -1322,12 +1322,12 @@ namespace ts.server { } } - function getUnresolvedImports(program: Program, cachedUnresolvedImportsPerFile: Map>): SortedReadonlyArray { + function getUnresolvedImports(program: Program, cachedUnresolvedImportsPerFile: Map): SortedReadonlyArray { const ambientModules = program.getTypeChecker().getAmbientModules().map(mod => stripQuotes(mod.getName())); return sortAndDeduplicate(flatMap(program.getSourceFiles(), sourceFile => extractUnresolvedImportsFromSourceFile(sourceFile, ambientModules, cachedUnresolvedImportsPerFile))); } - function extractUnresolvedImportsFromSourceFile(file: SourceFile, ambientModules: ReadonlyArray, cachedUnresolvedImportsPerFile: Map>): ReadonlyArray { + function extractUnresolvedImportsFromSourceFile(file: SourceFile, ambientModules: readonly string[], cachedUnresolvedImportsPerFile: Map): readonly string[] { return getOrUpdate(cachedUnresolvedImportsPerFile, file.path, () => { if (!file.resolvedModules) return emptyArray; let unresolvedImports: string[] | undefined; @@ -1489,7 +1489,7 @@ namespace ts.server { private projectErrors: Diagnostic[] | undefined; - private projectReferences: ReadonlyArray | undefined; + private projectReferences: readonly ProjectReference[] | undefined; /*@internal*/ projectOptions?: ProjectOptions | true; @@ -1553,11 +1553,11 @@ namespace ts.server { return asNormalizedPath(this.getProjectName()); } - getProjectReferences(): ReadonlyArray | undefined { + getProjectReferences(): readonly ProjectReference[] | undefined { return this.projectReferences; } - updateReferences(refs: ReadonlyArray | undefined) { + updateReferences(refs: readonly ProjectReference[] | undefined) { this.projectReferences = refs; } @@ -1599,14 +1599,14 @@ namespace ts.server { /** * Get the errors that dont have any file name associated */ - getGlobalProjectErrors(): ReadonlyArray { + getGlobalProjectErrors(): readonly Diagnostic[] { return filter(this.projectErrors, diagnostic => !diagnostic.file) || emptyArray; } /** * Get all the project errors */ - getAllProjectErrors(): ReadonlyArray { + getAllProjectErrors(): readonly Diagnostic[] { return this.projectErrors || emptyArray; } @@ -1711,7 +1711,7 @@ namespace ts.server { * These are created only if a host explicitly calls `openExternalProject`. */ export class ExternalProject extends Project { - excludedFiles: ReadonlyArray = []; + excludedFiles: readonly NormalizedPath[] = []; private typeAcquisition!: TypeAcquisition; // TODO: GH#18217 /*@internal*/ constructor(public externalProjectName: string, diff --git a/src/server/protocol.ts b/src/server/protocol.ts index 00f1d8e7c6f..0674f1c142d 100644 --- a/src/server/protocol.ts +++ b/src/server/protocol.ts @@ -633,7 +633,7 @@ namespace ts.server.protocol { } export interface OrganizeImportsResponse extends Response { - body: ReadonlyArray; + body: readonly FileCodeEdits[]; } export interface GetEditsForFileRenameRequest extends Request { @@ -648,7 +648,7 @@ namespace ts.server.protocol { } export interface GetEditsForFileRenameResponse extends Response { - body: ReadonlyArray; + body: readonly FileCodeEdits[]; } /** @@ -717,7 +717,7 @@ namespace ts.server.protocol { /** * Errorcodes we want to get the fixes for. */ - errorCodes: ReadonlyArray; + errorCodes: readonly number[]; } export interface GetCombinedCodeFixRequestArgs { @@ -907,7 +907,7 @@ namespace ts.server.protocol { } export interface DefinitionInfoAndBoundSpan { - definitions: ReadonlyArray; + definitions: readonly FileSpanWithContext[]; textSpan: TextSpan; } @@ -1067,7 +1067,7 @@ namespace ts.server.protocol { /** * The file locations referencing the symbol. */ - refs: ReadonlyArray; + refs: readonly ReferencesResponseItem[]; /** * The name of the symbol. @@ -1125,7 +1125,7 @@ namespace ts.server.protocol { /* @internal */ export interface RenameFullResponse extends Response { - readonly body: ReadonlyArray; + readonly body: readonly RenameLocation[]; } /** @@ -1198,7 +1198,7 @@ namespace ts.server.protocol { /** * An array of span groups (one per file) that refer to the item to be renamed. */ - locs: ReadonlyArray; + locs: readonly SpanGroup[]; } /** @@ -1876,8 +1876,8 @@ namespace ts.server.protocol { } export interface CombinedCodeActions { - changes: ReadonlyArray; - commands?: ReadonlyArray<{}>; + changes: readonly FileCodeEdits[]; + commands?: readonly {}[]; } export interface CodeFixAction extends CodeAction { @@ -2106,7 +2106,7 @@ namespace ts.server.protocol { readonly isGlobalCompletion: boolean; readonly isMemberCompletion: boolean; readonly isNewIdentifierLocation: boolean; - readonly entries: ReadonlyArray; + readonly entries: readonly CompletionEntry[]; } export interface CompletionDetailsResponse extends Response { @@ -2929,7 +2929,7 @@ namespace ts.server.protocol { /** * list of packages to install */ - packages: ReadonlyArray; + packages: readonly string[]; } export interface BeginInstallTypesEventBody extends InstallTypesEventBody { diff --git a/src/server/scriptVersionCache.ts b/src/server/scriptVersionCache.ts index afd8f67ecbe..3daa9968a2f 100644 --- a/src/server/scriptVersionCache.ts +++ b/src/server/scriptVersionCache.ts @@ -363,7 +363,7 @@ namespace ts.server { } class LineIndexSnapshot implements IScriptSnapshot { - constructor(readonly version: number, readonly cache: ScriptVersionCache, readonly index: LineIndex, readonly changesSincePreviousVersion: ReadonlyArray = emptyArray) { + constructor(readonly version: number, readonly cache: ScriptVersionCache, readonly index: LineIndex, readonly changesSincePreviousVersion: readonly TextChange[] = emptyArray) { } getText(rangeStart: number, rangeEnd: number) { diff --git a/src/server/session.ts b/src/server/session.ts index 54d120faa19..10fbd496e67 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -113,7 +113,7 @@ namespace ts.server { project: Project; } - function allEditsBeforePos(edits: ReadonlyArray, pos: number): boolean { + function allEditsBeforePos(edits: readonly TextChange[], pos: number): boolean { return edits.every(edit => textSpanEnd(edit.span) < pos); } @@ -258,8 +258,8 @@ namespace ts.server { }; } - type Projects = ReadonlyArray | { - readonly projects: ReadonlyArray; + type Projects = readonly Project[] | { + readonly projects: readonly Project[]; readonly symLinkedProjects: MultiMap; }; @@ -270,7 +270,7 @@ namespace ts.server { defaultValue: T, getValue: (path: Path) => T, projects: Projects, - action: (project: Project, value: T) => ReadonlyArray | U | undefined, + action: (project: Project, value: T) => readonly U[] | U | undefined, ): U[] { const outputs = flatMapToMutable(isArray(projects) ? projects : projects.projects, project => action(project, defaultValue)); if (!isArray(projects) && projects.symLinkedProjects) { @@ -282,7 +282,7 @@ namespace ts.server { return deduplicate(outputs, equateValues); } - function combineProjectOutputFromEveryProject(projectService: ProjectService, action: (project: Project) => ReadonlyArray, areEqual: (a: T, b: T) => boolean) { + function combineProjectOutputFromEveryProject(projectService: ProjectService, action: (project: Project) => readonly T[], areEqual: (a: T, b: T) => boolean) { const outputs: T[] = []; projectService.forEachEnabledProject(project => { const theseOutputs = action(project); @@ -294,7 +294,7 @@ namespace ts.server { function combineProjectOutputWhileOpeningReferencedProjects( projects: Projects, defaultProject: Project, - action: (project: Project) => ReadonlyArray, + action: (project: Project) => readonly T[], getLocation: (t: T) => DocumentPosition, resultsEqual: (a: T, b: T) => boolean, ): T[] { @@ -321,7 +321,7 @@ namespace ts.server { findInStrings: boolean, findInComments: boolean, hostPreferences: UserPreferences - ): ReadonlyArray { + ): readonly RenameLocation[] { const outputs: RenameLocation[] = []; combineProjectOutputWorker( @@ -351,7 +351,7 @@ namespace ts.server { projects: Projects, defaultProject: Project, initialLocation: DocumentPosition - ): ReadonlyArray { + ): readonly ReferencedSymbol[] { const outputs: ReferencedSymbol[] = []; combineProjectOutputWorker( @@ -545,8 +545,8 @@ namespace ts.server { throttleWaitMilliseconds?: number; noGetErrOnBackgroundUpdate?: boolean; - globalPlugins?: ReadonlyArray; - pluginProbeLocations?: ReadonlyArray; + globalPlugins?: readonly string[]; + pluginProbeLocations?: readonly string[]; allowLocalPluginLoads?: boolean; typesMapLocation?: string; } @@ -763,8 +763,8 @@ namespace ts.server { let metadata: unknown; if (isArray(info)) { res.body = info; - metadata = (info as WithMetadata>).metadata; - delete (info as WithMetadata>).metadata; + metadata = (info as WithMetadata).metadata; + delete (info as WithMetadata).metadata; } else if (typeof info === "object") { if ((info as WithMetadata<{}>).metadata) { @@ -805,7 +805,7 @@ namespace ts.server { this.sendDiagnosticsEvent(file, project, project.getLanguageService().getSuggestionDiagnostics(file), "suggestionDiag"); } - private sendDiagnosticsEvent(file: NormalizedPath, project: Project, diagnostics: ReadonlyArray, kind: protocol.DiagnosticEventKind): void { + private sendDiagnosticsEvent(file: NormalizedPath, project: Project, diagnostics: readonly Diagnostic[], kind: protocol.DiagnosticEventKind): void { try { this.event({ file, diagnostics: diagnostics.map(diag => formatDiag(file, project, diag)) }, kind); } @@ -927,7 +927,7 @@ namespace ts.server { ); } - private convertToDiagnosticsWithLinePositionFromDiagnosticFile(diagnostics: ReadonlyArray): protocol.DiagnosticWithLinePosition[] { + private convertToDiagnosticsWithLinePositionFromDiagnosticFile(diagnostics: readonly Diagnostic[]): protocol.DiagnosticWithLinePosition[] { return diagnostics.map(d => ({ message: flattenDiagnosticMessageText(d.messageText, this.host.newLine), start: d.start!, // TODO: GH#18217 @@ -954,7 +954,7 @@ namespace ts.server { ); } - private convertToDiagnosticsWithLinePosition(diagnostics: ReadonlyArray, scriptInfo: ScriptInfo | undefined): protocol.DiagnosticWithLinePosition[] { + private convertToDiagnosticsWithLinePosition(diagnostics: readonly Diagnostic[], scriptInfo: ScriptInfo | undefined): protocol.DiagnosticWithLinePosition[] { return diagnostics.map(d => { message: flattenDiagnosticMessageText(d.messageText, this.host.newLine), start: d.start, @@ -970,8 +970,8 @@ namespace ts.server { } private getDiagnosticsWorker( - args: protocol.FileRequestArgs, isSemantic: boolean, selector: (project: Project, file: string) => ReadonlyArray, includeLinePosition: boolean - ): ReadonlyArray | ReadonlyArray { + args: protocol.FileRequestArgs, isSemantic: boolean, selector: (project: Project, file: string) => readonly Diagnostic[], includeLinePosition: boolean + ): readonly protocol.DiagnosticWithLinePosition[] | readonly protocol.Diagnostic[] { const { project, file } = this.getFileAndProject(args); if (isSemantic && isDeclarationFileInJSOnlyNonConfiguredProject(project, file)) { return emptyArray; @@ -983,14 +983,14 @@ namespace ts.server { : diagnostics.map(d => formatDiag(file, project, d)); } - private getDefinition(args: protocol.FileLocationRequestArgs, simplifiedResult: boolean): ReadonlyArray | ReadonlyArray { + private getDefinition(args: protocol.FileLocationRequestArgs, simplifiedResult: boolean): readonly protocol.FileSpanWithContext[] | readonly DefinitionInfo[] { const { file, project } = this.getFileAndProject(args); const position = this.getPositionInFile(args, file); const definitions = this.mapDefinitionInfoLocations(project.getLanguageService().getDefinitionAtPosition(file, position) || emptyArray, project); return simplifiedResult ? this.mapDefinitionInfo(definitions, project) : definitions.map(Session.mapToOriginalLocation); } - private mapDefinitionInfoLocations(definitions: ReadonlyArray, project: Project): ReadonlyArray { + private mapDefinitionInfoLocations(definitions: readonly DefinitionInfo[], project: Project): readonly DefinitionInfo[] { return definitions.map((info): DefinitionInfo => { const newDocumentSpan = getMappedDocumentSpan(info, project); return !newDocumentSpan ? info : { @@ -1038,7 +1038,7 @@ namespace ts.server { return project.getLanguageService().getEmitOutput(file); } - private mapDefinitionInfo(definitions: ReadonlyArray, project: Project): ReadonlyArray { + private mapDefinitionInfo(definitions: readonly DefinitionInfo[], project: Project): readonly protocol.FileSpanWithContext[] { return definitions.map(def => this.toFileSpanWithContext(def.fileName, def.textSpan, def.contextSpan, project)); } @@ -1085,7 +1085,7 @@ namespace ts.server { fileSpan; } - private getTypeDefinition(args: protocol.FileLocationRequestArgs): ReadonlyArray { + private getTypeDefinition(args: protocol.FileLocationRequestArgs): readonly protocol.FileSpanWithContext[] { const { file, project } = this.getFileAndProject(args); const position = this.getPositionInFile(args, file); @@ -1093,7 +1093,7 @@ namespace ts.server { return this.mapDefinitionInfo(definitions, project); } - private mapImplementationLocations(implementations: ReadonlyArray, project: Project): ReadonlyArray { + private mapImplementationLocations(implementations: readonly ImplementationLocation[], project: Project): readonly ImplementationLocation[] { return implementations.map((info): ImplementationLocation => { const newDocumentSpan = getMappedDocumentSpan(info, project); return !newDocumentSpan ? info : { @@ -1104,7 +1104,7 @@ namespace ts.server { }); } - private getImplementation(args: protocol.FileLocationRequestArgs, simplifiedResult: boolean): ReadonlyArray | ReadonlyArray { + private getImplementation(args: protocol.FileLocationRequestArgs, simplifiedResult: boolean): readonly protocol.FileSpanWithContext[] | readonly ImplementationLocation[] { const { file, project } = this.getFileAndProject(args); const position = this.getPositionInFile(args, file); const implementations = this.mapImplementationLocations(project.getLanguageService().getImplementationAtPosition(file, position) || emptyArray, project); @@ -1113,7 +1113,7 @@ namespace ts.server { implementations.map(Session.mapToOriginalLocation); } - private getOccurrences(args: protocol.FileLocationRequestArgs): ReadonlyArray { + private getOccurrences(args: protocol.FileLocationRequestArgs): readonly protocol.OccurrencesResponseItem[] { const { file, project } = this.getFileAndProject(args); const position = this.getPositionInFile(args, file); const occurrences = project.getLanguageService().getOccurrencesAtPosition(file, position); @@ -1131,7 +1131,7 @@ namespace ts.server { emptyArray; } - private getSyntacticDiagnosticsSync(args: protocol.SyntacticDiagnosticsSyncRequestArgs): ReadonlyArray | ReadonlyArray { + private getSyntacticDiagnosticsSync(args: protocol.SyntacticDiagnosticsSyncRequestArgs): readonly protocol.Diagnostic[] | readonly protocol.DiagnosticWithLinePosition[] { const { configFile } = this.getConfigFileAndProject(args); if (configFile) { // all the config file errors are reported as part of semantic check so nothing to report here @@ -1141,7 +1141,7 @@ namespace ts.server { return this.getDiagnosticsWorker(args, /*isSemantic*/ false, (project, file) => project.getLanguageService().getSyntacticDiagnostics(file), !!args.includeLinePosition); } - private getSemanticDiagnosticsSync(args: protocol.SemanticDiagnosticsSyncRequestArgs): ReadonlyArray | ReadonlyArray { + private getSemanticDiagnosticsSync(args: protocol.SemanticDiagnosticsSyncRequestArgs): readonly protocol.Diagnostic[] | readonly protocol.DiagnosticWithLinePosition[] { const { configFile, project } = this.getConfigFileAndProject(args); if (configFile) { return this.getConfigFileDiagnostics(configFile, project!, !!args.includeLinePosition); // TODO: GH#18217 @@ -1149,7 +1149,7 @@ namespace ts.server { return this.getDiagnosticsWorker(args, /*isSemantic*/ true, (project, file) => project.getLanguageService().getSemanticDiagnostics(file), !!args.includeLinePosition); } - private getSuggestionDiagnosticsSync(args: protocol.SuggestionDiagnosticsSyncRequestArgs): ReadonlyArray | ReadonlyArray { + private getSuggestionDiagnosticsSync(args: protocol.SuggestionDiagnosticsSyncRequestArgs): readonly protocol.Diagnostic[] | readonly protocol.DiagnosticWithLinePosition[] { const { configFile } = this.getConfigFileAndProject(args); if (configFile) { // Currently there are no info diagnostics for config files. @@ -1166,7 +1166,7 @@ namespace ts.server { return tag === undefined ? undefined : { newText: tag.newText, caretOffset: 0 }; } - private getDocumentHighlights(args: protocol.DocumentHighlightsRequestArgs, simplifiedResult: boolean): ReadonlyArray | ReadonlyArray { + private getDocumentHighlights(args: protocol.DocumentHighlightsRequestArgs, simplifiedResult: boolean): readonly protocol.DocumentHighlightsItem[] | readonly DocumentHighlights[] { const { file, project } = this.getFileAndProject(args); const position = this.getPositionInFile(args, file); const documentHighlights = project.getLanguageService().getDocumentHighlights(file, position, args.filesToSearch); @@ -1212,7 +1212,7 @@ namespace ts.server { } private getProjects(args: protocol.FileRequestArgs, getScriptInfoEnsuringProjectsUptoDate?: boolean, ignoreNoProjectError?: boolean): Projects { - let projects: ReadonlyArray | undefined; + let projects: readonly Project[] | undefined; let symLinkedProjects: MultiMap | undefined; if (args.projectFileName) { const project = this.getProject(args.projectFileName); @@ -1252,7 +1252,7 @@ namespace ts.server { return info.getDefaultProject(); } - private getRenameLocations(args: protocol.RenameRequestArgs, simplifiedResult: boolean): protocol.RenameResponseBody | ReadonlyArray { + private getRenameLocations(args: protocol.RenameRequestArgs, simplifiedResult: boolean): protocol.RenameResponseBody | readonly RenameLocation[] { const file = toNormalizedPath(args.file); const position = this.getPositionInFile(args, file); const projects = this.getProjects(args); @@ -1283,7 +1283,7 @@ namespace ts.server { } } - private toSpanGroups(locations: ReadonlyArray): ReadonlyArray { + private toSpanGroups(locations: readonly RenameLocation[]): readonly protocol.SpanGroup[] { const map = createMap(); for (const { fileName, textSpan, contextSpan, originalContextSpan: _2, originalTextSpan: _, originalFileName: _1, ...prefixSuffixText } of locations) { let group = map.get(fileName); @@ -1294,7 +1294,7 @@ namespace ts.server { return arrayFrom(map.values()); } - private getReferences(args: protocol.FileLocationRequestArgs, simplifiedResult: boolean): protocol.ReferencesResponseBody | undefined | ReadonlyArray { + private getReferences(args: protocol.FileLocationRequestArgs, simplifiedResult: boolean): protocol.ReferencesResponseBody | undefined | readonly ReferencedSymbol[] { const file = toNormalizedPath(args.file); const projects = this.getProjects(args); const position = this.getPositionInFile(args, file); @@ -1313,7 +1313,7 @@ namespace ts.server { const nameSpan = nameInfo && nameInfo.textSpan; const symbolStartOffset = nameSpan ? scriptInfo.positionToLineOffset(nameSpan.start).offset : 0; const symbolName = nameSpan ? scriptInfo.getSnapshot().getText(nameSpan.start, textSpanEnd(nameSpan)) : ""; - const refs: ReadonlyArray = flatMap(references, referencedSymbol => + const refs: readonly protocol.ReferencesResponseItem[] = flatMap(references, referencedSymbol => referencedSymbol.references.map(({ fileName, textSpan, contextSpan, isWriteAccess, isDefinition }): protocol.ReferencesResponseItem => { const scriptInfo = Debug.assertDefined(this.projectService.getScriptInfo(fileName)); const span = toProtocolTextSpanWithContext(textSpan, contextSpan, scriptInfo); @@ -1547,7 +1547,7 @@ namespace ts.server { }); } - private getCompletions(args: protocol.CompletionsRequestArgs, kind: protocol.CommandTypes.CompletionInfo | protocol.CommandTypes.Completions | protocol.CommandTypes.CompletionsFull): WithMetadata> | protocol.CompletionInfo | CompletionInfo | undefined { + private getCompletions(args: protocol.CompletionsRequestArgs, kind: protocol.CommandTypes.CompletionInfo | protocol.CommandTypes.Completions | protocol.CommandTypes.CompletionsFull): WithMetadata | protocol.CompletionInfo | CompletionInfo | undefined { const { file, project } = this.getFileAndProject(args); const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file)!; const position = this.getPosition(args, scriptInfo); @@ -1573,7 +1573,7 @@ namespace ts.server { }).sort((a, b) => compareStringsCaseSensitiveUI(a.name, b.name)); if (kind === protocol.CommandTypes.Completions) { - if (completions.metadata) (entries as WithMetadata>).metadata = completions.metadata; + if (completions.metadata) (entries as WithMetadata).metadata = completions.metadata; return entries; } @@ -1584,7 +1584,7 @@ namespace ts.server { return res; } - private getCompletionEntryDetails(args: protocol.CompletionDetailsRequestArgs, simplifiedResult: boolean): ReadonlyArray | ReadonlyArray { + private getCompletionEntryDetails(args: protocol.CompletionDetailsRequestArgs, simplifiedResult: boolean): readonly protocol.CompletionEntryDetails[] | readonly CompletionEntryDetails[] { const { file, project } = this.getFileAndProject(args); const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file)!; const position = this.getPosition(args, scriptInfo); @@ -1599,7 +1599,7 @@ namespace ts.server { : result; } - private getCompileOnSaveAffectedFileList(args: protocol.FileRequestArgs): ReadonlyArray { + private getCompileOnSaveAffectedFileList(args: protocol.FileRequestArgs): readonly protocol.CompileOnSaveAffectedFileListSingleProject[] { const projects = this.getProjects(args, /*getScriptInfoEnsuringProjectsUptoDate*/ true, /*ignoreNoProjectError*/ true); const info = this.projectService.getScriptInfo(args.file); if (!info) { @@ -1773,7 +1773,7 @@ namespace ts.server { : tree; } - private getNavigateToItems(args: protocol.NavtoRequestArgs, simplifiedResult: boolean): ReadonlyArray | ReadonlyArray { + private getNavigateToItems(args: protocol.NavtoRequestArgs, simplifiedResult: boolean): readonly protocol.NavtoItem[] | readonly NavigateToItem[] { const full = this.getFullNavigateToItems(args); return !simplifiedResult ? full : full.map((navItem) => { const { file, project } = this.getFileAndProject({ file: navItem.fileName }); @@ -1800,7 +1800,7 @@ namespace ts.server { }); } - private getFullNavigateToItems(args: protocol.NavtoRequestArgs): ReadonlyArray { + private getFullNavigateToItems(args: protocol.NavtoRequestArgs): readonly NavigateToItem[] { const { currentFileOnly, searchValue, maxResultCount } = args; if (currentFileOnly) { const { file, project } = this.getFileAndProject(args); @@ -1899,7 +1899,7 @@ namespace ts.server { } } - private organizeImports({ scope }: protocol.OrganizeImportsRequestArgs, simplifiedResult: boolean): ReadonlyArray | ReadonlyArray { + private organizeImports({ scope }: protocol.OrganizeImportsRequestArgs, simplifiedResult: boolean): readonly protocol.FileCodeEdits[] | readonly FileTextChanges[] { Debug.assert(scope.type === "file"); const { file, project } = this.getFileAndProject(scope.args); const changes = project.getLanguageService().organizeImports({ type: "file", fileName: file }, this.getFormatOptions(file), this.getPreferences(file)); @@ -1911,7 +1911,7 @@ namespace ts.server { } } - private getEditsForFileRename(args: protocol.GetEditsForFileRenameRequestArgs, simplifiedResult: boolean): ReadonlyArray | ReadonlyArray { + private getEditsForFileRename(args: protocol.GetEditsForFileRenameRequestArgs, simplifiedResult: boolean): readonly protocol.FileCodeEdits[] | readonly FileTextChanges[] { const oldPath = toNormalizedPath(args.oldFilePath); const newPath = toNormalizedPath(args.newFilePath); const formatOptions = this.getHostFormatOptions(); @@ -1923,7 +1923,7 @@ namespace ts.server { return simplifiedResult ? changes.map(c => this.mapTextChangeToCodeEdit(c)) : changes; } - private getCodeFixes(args: protocol.CodeFixRequestArgs, simplifiedResult: boolean): ReadonlyArray | ReadonlyArray | undefined { + private getCodeFixes(args: protocol.CodeFixRequestArgs, simplifiedResult: boolean): readonly protocol.CodeFixAction[] | readonly CodeFixAction[] | undefined { const { file, project } = this.getFileAndProject(args); const scriptInfo = project.getScriptInfoForNormalizedPath(file)!; @@ -1986,7 +1986,7 @@ namespace ts.server { return { fixName, description, changes: this.mapTextChangesToCodeEdits(changes), commands, fixId, fixAllDescription }; } - private mapTextChangesToCodeEdits(textChanges: ReadonlyArray): protocol.FileCodeEdits[] { + private mapTextChangesToCodeEdits(textChanges: readonly FileTextChanges[]): protocol.FileCodeEdits[] { return textChanges.map(change => this.mapTextChangeToCodeEdit(change)); } @@ -2628,13 +2628,13 @@ namespace ts.server { } /* @internal */ // Exported only for tests - export function getLocationInNewDocument(oldText: string, renameFilename: string, renameLocation: number, edits: ReadonlyArray): protocol.Location { + export function getLocationInNewDocument(oldText: string, renameFilename: string, renameLocation: number, edits: readonly FileTextChanges[]): protocol.Location { const newText = applyEdits(oldText, renameFilename, edits); const { line, character } = computeLineAndCharacterOfPosition(computeLineStarts(newText), renameLocation); return { line: line + 1, offset: character + 1 }; } - function applyEdits(text: string, textFilename: string, edits: ReadonlyArray): string { + function applyEdits(text: string, textFilename: string, edits: readonly FileTextChanges[]): string { for (const { fileName, textChanges } of edits) { if (fileName !== textFilename) { continue; diff --git a/src/services/codeFixProvider.ts b/src/services/codeFixProvider.ts index 8d42fdcc6c2..68059c3d3fd 100644 --- a/src/services/codeFixProvider.ts +++ b/src/services/codeFixProvider.ts @@ -1,9 +1,9 @@ /* @internal */ namespace ts { export interface CodeFixRegistration { - errorCodes: ReadonlyArray; + errorCodes: readonly number[]; getCodeActions(context: CodeFixContext): CodeFixAction[] | undefined; - fixIds?: ReadonlyArray; + fixIds?: readonly string[]; getAllCodeActions?(context: CodeFixAllContext): CombinedCodeActions; } @@ -30,7 +30,7 @@ namespace ts { export type DiagnosticAndArguments = DiagnosticMessage | [DiagnosticMessage, string] | [DiagnosticMessage, string, string]; function diagnosticToString(diag: DiagnosticAndArguments): string { return isArray(diag) - ? formatStringFromArgs(getLocaleSpecificMessage(diag[0]), diag.slice(1) as ReadonlyArray) + ? formatStringFromArgs(getLocaleSpecificMessage(diag[0]), diag.slice(1) as readonly string[]) : getLocaleSpecificMessage(diag); } @@ -62,7 +62,7 @@ namespace ts { return arrayFrom(errorCodeToFixes.keys()); } - export function getFixes(context: CodeFixContext): ReadonlyArray { + export function getFixes(context: CodeFixContext): readonly CodeFixAction[] { return flatMap(errorCodeToFixes.get(String(context.errorCode)) || emptyArray, f => f.getCodeActions(context)); } @@ -89,7 +89,7 @@ namespace ts { return createCombinedCodeActions(changes, commands.length === 0 ? undefined : commands); } - export function eachDiagnostic({ program, sourceFile, cancellationToken }: CodeFixAllContext, errorCodes: ReadonlyArray, cb: (diag: DiagnosticWithLocation) => void): void { + export function eachDiagnostic({ program, sourceFile, cancellationToken }: CodeFixAllContext, errorCodes: readonly number[], cb: (diag: DiagnosticWithLocation) => void): void { for (const diag of program.getSemanticDiagnostics(sourceFile, cancellationToken).concat(computeSuggestionDiagnostics(sourceFile, program, cancellationToken))) { if (contains(errorCodes, diag.code)) { cb(diag as DiagnosticWithLocation); diff --git a/src/services/codefixes/convertFunctionToEs6Class.ts b/src/services/codefixes/convertFunctionToEs6Class.ts index b87a78106ad..0769cb26162 100644 --- a/src/services/codefixes/convertFunctionToEs6Class.ts +++ b/src/services/codefixes/convertFunctionToEs6Class.ts @@ -186,7 +186,7 @@ namespace ts.codefix { } } - function getModifierKindFromSource(source: Node, kind: SyntaxKind): ReadonlyArray | undefined { + function getModifierKindFromSource(source: Node, kind: SyntaxKind): readonly Modifier[] | undefined { return filter(source.modifiers, modifier => modifier.kind === kind); } } diff --git a/src/services/codefixes/convertToAsyncFunction.ts b/src/services/codefixes/convertToAsyncFunction.ts index 406e0f5f589..935f6654409 100644 --- a/src/services/codefixes/convertToAsyncFunction.ts +++ b/src/services/codefixes/convertToAsyncFunction.ts @@ -23,7 +23,7 @@ namespace ts.codefix { interface SynthBindingPattern { readonly kind: SynthBindingNameKind.BindingPattern; - readonly elements: ReadonlyArray; + readonly elements: readonly SynthBindingName[]; readonly bindingPattern: BindingPattern; readonly types: Type[]; } @@ -43,7 +43,7 @@ namespace ts.codefix { interface Transformer { readonly checker: TypeChecker; readonly synthNamesMap: Map; // keys are the symbol id of the identifier - readonly allVarNames: ReadonlyArray; + readonly allVarNames: readonly SymbolAndIdentifier[]; readonly setOfExpressionsToReturn: ReadonlyMap; // keys are the node ids of the expressions readonly constIdentifiers: Identifier[]; readonly originalTypeMap: ReadonlyMap; // keys are the node id of the identifier @@ -102,7 +102,7 @@ namespace ts.codefix { } } - function getReturnStatementsWithPromiseHandlers(body: Block): ReadonlyArray { + function getReturnStatementsWithPromiseHandlers(body: Block): readonly ReturnStatement[] { const res: ReturnStatement[] = []; forEachReturnStatement(body, ret => { if (isReturnStatementWithFixablePromiseHandler(ret)) res.push(ret); @@ -281,7 +281,7 @@ namespace ts.codefix { // dispatch function to recursively build the refactoring // should be kept up to date with isFixablePromiseHandler in suggestionDiagnostics.ts - function transformExpression(node: Expression, transformer: Transformer, outermostParent: CallExpression, prevArgName?: SynthBindingName): ReadonlyArray { + function transformExpression(node: Expression, transformer: Transformer, outermostParent: CallExpression, prevArgName?: SynthBindingName): readonly Statement[] { if (!node) { return emptyArray; } @@ -306,7 +306,7 @@ namespace ts.codefix { return emptyArray; } - function transformCatch(node: CallExpression, transformer: Transformer, prevArgName?: SynthBindingName): ReadonlyArray { + function transformCatch(node: CallExpression, transformer: Transformer, prevArgName?: SynthBindingName): readonly Statement[] { const func = node.arguments[0]; const argName = getArgBindingName(func, transformer); const shouldReturn = transformer.setOfExpressionsToReturn.get(getNodeId(node).toString()); @@ -365,7 +365,7 @@ namespace ts.codefix { return compact([varDeclList, tryStatement, destructuredResult]); } - function getIdentifierTextsFromBindingName(bindingName: BindingName): ReadonlyArray { + function getIdentifierTextsFromBindingName(bindingName: BindingName): readonly string[] { if (isIdentifier(bindingName)) return [bindingName.text]; return flatMap(bindingName.elements, element => { if (isOmittedExpression(element)) return []; @@ -378,7 +378,7 @@ namespace ts.codefix { return createSynthIdentifier(renamedPrevArg); } - function transformThen(node: CallExpression, transformer: Transformer, outermostParent: CallExpression, prevArgName?: SynthBindingName): ReadonlyArray { + function transformThen(node: CallExpression, transformer: Transformer, outermostParent: CallExpression, prevArgName?: SynthBindingName): readonly Statement[] { const [res, rej] = node.arguments; if (!res) { @@ -405,13 +405,13 @@ namespace ts.codefix { return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); } - function getFlagOfBindingName(bindingName: SynthBindingName, constIdentifiers: ReadonlyArray): NodeFlags { + function getFlagOfBindingName(bindingName: SynthBindingName, constIdentifiers: readonly Identifier[]): NodeFlags { const identifiers = getIdentifierTextsFromBindingName(getNode(bindingName)); const inArr: boolean = constIdentifiers.some(elem => contains(identifiers, elem.text)); return inArr ? NodeFlags.Const : NodeFlags.Let; } - function transformPromiseCall(node: Expression, transformer: Transformer, prevArgName?: SynthBindingName): ReadonlyArray { + function transformPromiseCall(node: Expression, transformer: Transformer, prevArgName?: SynthBindingName): readonly Statement[] { const shouldReturn = transformer.setOfExpressionsToReturn.get(getNodeId(node).toString()); // the identifier is empty when the handler (.then()) ignores the argument - In this situation we do not need to save the result of the promise returning call const originalNodeParent = node.original ? node.original.parent : node.parent; @@ -425,7 +425,7 @@ namespace ts.codefix { return [createReturn(getSynthesizedDeepClone(node))]; } - function createTransformedStatement(prevArgName: SynthBindingName | undefined, rightHandSide: Expression, transformer: Transformer): ReadonlyArray { + function createTransformedStatement(prevArgName: SynthBindingName | undefined, rightHandSide: Expression, transformer: Transformer): readonly Statement[] { if (!prevArgName || isEmpty(prevArgName)) { // if there's no argName to assign to, there still might be side effects return [createStatement(rightHandSide)]; @@ -441,7 +441,7 @@ namespace ts.codefix { } // should be kept up to date with isFixablePromiseArgument in suggestionDiagnostics.ts - function getTransformationBody(func: Expression, prevArgName: SynthBindingName | undefined, argName: SynthBindingName | undefined, parent: CallExpression, transformer: Transformer): ReadonlyArray { + function getTransformationBody(func: Expression, prevArgName: SynthBindingName | undefined, argName: SynthBindingName | undefined, parent: CallExpression, transformer: Transformer): readonly Statement[] { const shouldReturn = transformer.setOfExpressionsToReturn.get(getNodeId(parent).toString()); switch (func.kind) { @@ -539,7 +539,7 @@ namespace ts.codefix { } - function removeReturns(stmts: ReadonlyArray, prevArgName: SynthBindingName | undefined, transformer: Transformer, seenReturnStatement: boolean): ReadonlyArray { + function removeReturns(stmts: readonly Statement[], prevArgName: SynthBindingName | undefined, transformer: Transformer, seenReturnStatement: boolean): readonly Statement[] { const ret: Statement[] = []; for (const stmt of stmts) { if (isReturnStatement(stmt)) { @@ -569,7 +569,7 @@ namespace ts.codefix { } - function getInnerTransformationBody(transformer: Transformer, innerRetStmts: ReadonlyArray, prevArgName?: SynthBindingName) { + function getInnerTransformationBody(transformer: Transformer, innerRetStmts: readonly Node[], prevArgName?: SynthBindingName) { let innerCbBody: Statement[] = []; for (const stmt of innerRetStmts) { @@ -663,7 +663,7 @@ namespace ts.codefix { return { kind: SynthBindingNameKind.Identifier, identifier, types, numberOfAssignmentsOriginal }; } - function createSynthBindingPattern(bindingPattern: BindingPattern, elements: ReadonlyArray = emptyArray, types: Type[] = []): SynthBindingPattern { + function createSynthBindingPattern(bindingPattern: BindingPattern, elements: readonly SynthBindingName[] = emptyArray, types: Type[] = []): SynthBindingPattern { return { kind: SynthBindingNameKind.BindingPattern, bindingPattern, elements, types }; } diff --git a/src/services/codefixes/convertToEs6Module.ts b/src/services/codefixes/convertToEs6Module.ts index 8dd9bf3539c..72f7e0c005f 100644 --- a/src/services/codefixes/convertToEs6Module.ts +++ b/src/services/codefixes/convertToEs6Module.ts @@ -163,7 +163,7 @@ namespace ts.codefix { } /** Converts `const name = require("moduleSpecifier").propertyName` */ - function convertPropertyAccessImport(name: BindingName, propertyName: string, moduleSpecifier: StringLiteralLike, identifiers: Identifiers, quotePreference: QuotePreference): ReadonlyArray { + function convertPropertyAccessImport(name: BindingName, propertyName: string, moduleSpecifier: StringLiteralLike, identifiers: Identifiers, quotePreference: QuotePreference): readonly Node[] { switch (name.kind) { case SyntaxKind.ObjectBindingPattern: case SyntaxKind.ArrayBindingPattern: { @@ -224,7 +224,7 @@ namespace ts.codefix { * Convert `module.exports = { ... }` to individual exports.. * We can't always do this if the module has interesting members -- then it will be a default export instead. */ - function tryChangeModuleExportsObject(object: ObjectLiteralExpression): [ReadonlyArray, ModuleExportsChanged] | undefined { + function tryChangeModuleExportsObject(object: ObjectLiteralExpression): [readonly Statement[], ModuleExportsChanged] | undefined { const statements = mapAllOrFail(object.properties, prop => { switch (prop.kind) { case SyntaxKind.GetAccessor: @@ -270,7 +270,7 @@ namespace ts.codefix { } } - function convertReExportAll(reExported: StringLiteralLike, checker: TypeChecker): [ReadonlyArray, ModuleExportsChanged] { + function convertReExportAll(reExported: StringLiteralLike, checker: TypeChecker): [readonly Statement[], ModuleExportsChanged] { // `module.exports = require("x");` ==> `export * from "x"; export { default } from "x";` const moduleSpecifier = reExported.text; const moduleSymbol = checker.getSymbolAtLocation(reExported); @@ -349,7 +349,7 @@ namespace ts.codefix { identifiers: Identifiers, target: ScriptTarget, quotePreference: QuotePreference, - ): ReadonlyArray { + ): readonly Node[] { switch (name.kind) { case SyntaxKind.ObjectBindingPattern: { const importSpecifiers = mapAllOrFail(name.elements, e => @@ -385,7 +385,7 @@ namespace ts.codefix { * Convert `import x = require("x").` * Also converts uses like `x.y()` to `y()` and uses a named import. */ - function convertSingleIdentifierImport(file: SourceFile, name: Identifier, moduleSpecifier: StringLiteralLike, changes: textChanges.ChangeTracker, checker: TypeChecker, identifiers: Identifiers, quotePreference: QuotePreference): ReadonlyArray { + function convertSingleIdentifierImport(file: SourceFile, name: Identifier, moduleSpecifier: StringLiteralLike, changes: textChanges.ChangeTracker, checker: TypeChecker, identifiers: Identifiers, quotePreference: QuotePreference): readonly Node[] { const nameSymbol = checker.getSymbolAtLocation(name); // Maps from module property name to name actually used. (The same if there isn't shadowing.) const namedBindingsNames = createMap(); @@ -444,7 +444,7 @@ namespace ts.codefix { readonly additional: Map; } - type FreeIdentifiers = ReadonlyMap>; + type FreeIdentifiers = ReadonlyMap; function collectFreeIdentifiers(file: SourceFile): FreeIdentifiers { const map = createMultiMap(); forEachFreeIdentifier(file, id => map.add(id.text, id)); @@ -476,7 +476,7 @@ namespace ts.codefix { // Node helpers - function functionExpressionToDeclaration(name: string | undefined, additionalModifiers: ReadonlyArray, fn: FunctionExpression | ArrowFunction | MethodDeclaration): FunctionDeclaration { + function functionExpressionToDeclaration(name: string | undefined, additionalModifiers: readonly Modifier[], fn: FunctionExpression | ArrowFunction | MethodDeclaration): FunctionDeclaration { return createFunctionDeclaration( getSynthesizedDeepClones(fn.decorators), // TODO: GH#19915 Don't think this is even legal. concatenate(additionalModifiers, getSynthesizedDeepClones(fn.modifiers)), @@ -488,7 +488,7 @@ namespace ts.codefix { convertToFunctionBody(getSynthesizedDeepClone(fn.body!))); } - function classExpressionToDeclaration(name: string | undefined, additionalModifiers: ReadonlyArray, cls: ClassExpression): ClassDeclaration { + function classExpressionToDeclaration(name: string | undefined, additionalModifiers: readonly Modifier[], cls: ClassExpression): ClassDeclaration { return createClassDeclaration( getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal. concatenate(additionalModifiers, getSynthesizedDeepClones(cls.modifiers)), @@ -508,7 +508,7 @@ namespace ts.codefix { return createImportSpecifier(propertyName !== undefined && propertyName !== name ? createIdentifier(propertyName) : undefined, createIdentifier(name)); } - function makeConst(modifiers: ReadonlyArray | undefined, name: string | BindingName, init: Expression): VariableStatement { + function makeConst(modifiers: readonly Modifier[] | undefined, name: string | BindingName, init: Expression): VariableStatement { return createVariableStatement( modifiers, createVariableDeclarationList( diff --git a/src/services/codefixes/disableJsDiagnostics.ts b/src/services/codefixes/disableJsDiagnostics.ts index 4cdd7eb42d2..bde8b118264 100644 --- a/src/services/codefixes/disableJsDiagnostics.ts +++ b/src/services/codefixes/disableJsDiagnostics.ts @@ -2,7 +2,7 @@ namespace ts.codefix { const fixName = "disableJsDiagnostics"; const fixId = "disableJsDiagnostics"; - const errorCodes = mapDefined(Object.keys(Diagnostics) as ReadonlyArray, key => { + const errorCodes = mapDefined(Object.keys(Diagnostics) as readonly (keyof typeof Diagnostics)[], key => { const diag = Diagnostics[key]; return diag.category === DiagnosticCategory.Error ? diag.code : undefined; }); diff --git a/src/services/codefixes/fixAddMissingMember.ts b/src/services/codefixes/fixAddMissingMember.ts index 843d22554ed..2e24fd2253d 100644 --- a/src/services/codefixes/fixAddMissingMember.ts +++ b/src/services/codefixes/fixAddMissingMember.ts @@ -83,7 +83,7 @@ namespace ts.codefix { }, }); - function getAllSupers(decl: ClassOrInterface | undefined, checker: TypeChecker): ReadonlyArray { + function getAllSupers(decl: ClassOrInterface | undefined, checker: TypeChecker): readonly ClassOrInterface[] { const res: ClassLikeDeclaration[] = []; while (decl) { const superElement = getClassExtendsHeritageElement(decl); diff --git a/src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts b/src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts index 78dc6b1ae19..1e2af29f63e 100644 --- a/src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts +++ b/src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts @@ -26,7 +26,7 @@ namespace ts.codefix { return extendsToken.kind === SyntaxKind.ExtendsKeyword ? { extendsToken, heritageClauses } : undefined; } - function doChanges(changes: textChanges.ChangeTracker, sourceFile: SourceFile, extendsToken: Node, heritageClauses: ReadonlyArray): void { + function doChanges(changes: textChanges.ChangeTracker, sourceFile: SourceFile, extendsToken: Node, heritageClauses: readonly HeritageClause[]): void { changes.replaceNode(sourceFile, extendsToken, createToken(SyntaxKind.ImplementsKeyword)); // If there is already an implements clause, replace the implements keyword with a comma. diff --git a/src/services/codefixes/fixUnreachableCode.ts b/src/services/codefixes/fixUnreachableCode.ts index 2d1c2f0fc38..2d45de950b1 100644 --- a/src/services/codefixes/fixUnreachableCode.ts +++ b/src/services/codefixes/fixUnreachableCode.ts @@ -48,7 +48,7 @@ namespace ts.codefix { } } - function lastWhere(a: ReadonlyArray, pred: (value: T) => boolean): T | undefined { + function lastWhere(a: readonly T[], pred: (value: T) => boolean): T | undefined { let last: T | undefined; for (const value of a) { if (!pred(value)) break; diff --git a/src/services/codefixes/fixUnusedIdentifier.ts b/src/services/codefixes/fixUnusedIdentifier.ts index de071ded24c..059c8194f8e 100644 --- a/src/services/codefixes/fixUnusedIdentifier.ts +++ b/src/services/codefixes/fixUnusedIdentifier.ts @@ -125,7 +125,7 @@ namespace ts.codefix { return token.kind === SyntaxKind.ImportKeyword ? tryCast(token.parent, isImportDeclaration) : undefined; } - function tryDeleteFullDestructure(token: Node, changes: textChanges.ChangeTracker, sourceFile: SourceFile, checker: TypeChecker, sourceFiles: ReadonlyArray, isFixAll: boolean): boolean { + function tryDeleteFullDestructure(token: Node, changes: textChanges.ChangeTracker, sourceFile: SourceFile, checker: TypeChecker, sourceFiles: readonly SourceFile[], isFixAll: boolean): boolean { if (token.kind !== SyntaxKind.OpenBraceToken || !isObjectBindingPattern(token.parent)) return false; const decl = token.parent.parent; if (decl.kind === SyntaxKind.Parameter) { @@ -174,7 +174,7 @@ namespace ts.codefix { return false; } - function tryDeleteDeclaration(sourceFile: SourceFile, token: Node, changes: textChanges.ChangeTracker, checker: TypeChecker, sourceFiles: ReadonlyArray, isFixAll: boolean) { + function tryDeleteDeclaration(sourceFile: SourceFile, token: Node, changes: textChanges.ChangeTracker, checker: TypeChecker, sourceFiles: readonly SourceFile[], isFixAll: boolean) { tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, isFixAll); if (isIdentifier(token)) deleteAssignments(changes, sourceFile, token, checker); } @@ -188,7 +188,7 @@ namespace ts.codefix { }); } - function tryDeleteDeclarationWorker(token: Node, changes: textChanges.ChangeTracker, sourceFile: SourceFile, checker: TypeChecker, sourceFiles: ReadonlyArray, isFixAll: boolean): void { + function tryDeleteDeclarationWorker(token: Node, changes: textChanges.ChangeTracker, sourceFile: SourceFile, checker: TypeChecker, sourceFiles: readonly SourceFile[], isFixAll: boolean): void { const { parent } = token; if (isParameter(parent)) { tryDeleteParameter(changes, sourceFile, parent, checker, sourceFiles, isFixAll); @@ -198,7 +198,7 @@ namespace ts.codefix { } } - function tryDeleteParameter(changes: textChanges.ChangeTracker, sourceFile: SourceFile, p: ParameterDeclaration, checker: TypeChecker, sourceFiles: ReadonlyArray, isFixAll: boolean): void { + function tryDeleteParameter(changes: textChanges.ChangeTracker, sourceFile: SourceFile, p: ParameterDeclaration, checker: TypeChecker, sourceFiles: readonly SourceFile[], isFixAll: boolean): void { if (mayDeleteParameter(p, checker, isFixAll)) { if (p.modifiers && p.modifiers.length > 0 && (!isIdentifier(p.name) || FindAllReferences.Core.isSymbolReferencedInFile(p.name, checker, sourceFile))) { @@ -246,7 +246,7 @@ namespace ts.codefix { } } - function deleteUnusedArguments(changes: textChanges.ChangeTracker, sourceFile: SourceFile, deletedParameter: ParameterDeclaration, sourceFiles: ReadonlyArray, checker: TypeChecker): void { + function deleteUnusedArguments(changes: textChanges.ChangeTracker, sourceFile: SourceFile, deletedParameter: ParameterDeclaration, sourceFiles: readonly SourceFile[], checker: TypeChecker): void { FindAllReferences.Core.eachSignatureCall(deletedParameter.parent, sourceFiles, checker, call => { const index = deletedParameter.parent.parameters.indexOf(deletedParameter); if (call.arguments.length > index) { // Just in case the call didn't provide enough arguments. diff --git a/src/services/codefixes/helpers.ts b/src/services/codefixes/helpers.ts index 71cb8b04b8a..b2182064a38 100644 --- a/src/services/codefixes/helpers.ts +++ b/src/services/codefixes/helpers.ts @@ -6,7 +6,7 @@ namespace ts.codefix { * @param possiblyMissingSymbols The collection of symbols to filter and then get insertions for. * @returns Empty string iff there are no member insertions. */ - export function createMissingMemberNodes(classDeclaration: ClassLikeDeclaration, possiblyMissingSymbols: ReadonlyArray, context: TypeConstructionContext, preferences: UserPreferences, out: (node: ClassElement) => void): void { + export function createMissingMemberNodes(classDeclaration: ClassLikeDeclaration, possiblyMissingSymbols: readonly Symbol[], context: TypeConstructionContext, preferences: UserPreferences, out: (node: ClassElement) => void): void { const classMembers = classDeclaration.symbol.members!; for (const symbol of possiblyMissingSymbols) { if (!classMembers.has(symbol.escapedName)) { @@ -186,10 +186,10 @@ namespace ts.codefix { } function createMethodImplementingSignatures( - signatures: ReadonlyArray, + signatures: readonly Signature[], name: PropertyName, optional: boolean, - modifiers: ReadonlyArray | undefined, + modifiers: readonly Modifier[] | undefined, preferences: UserPreferences, ): MethodDeclaration { /** This is *a* signature with the maximal number of arguments, @@ -237,11 +237,11 @@ namespace ts.codefix { } function createStubbedMethod( - modifiers: ReadonlyArray | undefined, + modifiers: readonly Modifier[] | undefined, name: PropertyName, optional: boolean, - typeParameters: ReadonlyArray | undefined, - parameters: ReadonlyArray, + typeParameters: readonly TypeParameterDeclaration[] | undefined, + parameters: readonly ParameterDeclaration[], returnType: TypeNode | undefined, preferences: UserPreferences ): MethodDeclaration { diff --git a/src/services/codefixes/importFixes.ts b/src/services/codefixes/importFixes.ts index 62a2cc9077d..248f34065a5 100644 --- a/src/services/codefixes/importFixes.ts +++ b/src/services/codefixes/importFixes.ts @@ -1,7 +1,7 @@ /* @internal */ namespace ts.codefix { export const importFixId = "fixMissingImport"; - const errorCodes: ReadonlyArray = [ + const errorCodes: readonly number[] = [ Diagnostics.Cannot_find_name_0.code, Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, @@ -176,7 +176,7 @@ namespace ts.codefix { return { description, changes, commands }; } - function getAllReExportingModules(importingFile: SourceFile, exportedSymbol: Symbol, exportingModuleSymbol: Symbol, symbolName: string, sourceFile: SourceFile, compilerOptions: CompilerOptions, checker: TypeChecker, allSourceFiles: ReadonlyArray): ReadonlyArray { + function getAllReExportingModules(importingFile: SourceFile, exportedSymbol: Symbol, exportingModuleSymbol: Symbol, symbolName: string, sourceFile: SourceFile, compilerOptions: CompilerOptions, checker: TypeChecker, allSourceFiles: readonly SourceFile[]): readonly SymbolExportInfo[] { const result: SymbolExportInfo[] = []; forEachExternalModule(checker, allSourceFiles, (moduleSymbol, moduleFile) => { // Don't import from a re-export when looking "up" like to `./index` or `../index`. @@ -203,14 +203,14 @@ namespace ts.codefix { } function getFixForImport( - exportInfos: ReadonlyArray, + exportInfos: readonly SymbolExportInfo[], symbolName: string, position: number | undefined, program: Program, sourceFile: SourceFile, host: LanguageServiceHost, preferences: UserPreferences, - ): ReadonlyArray { + ): readonly ImportFix[] { const checker = program.getTypeChecker(); const existingImports = flatMap(exportInfos, info => getExistingImportDeclarations(info, checker, sourceFile)); const useNamespace = position === undefined ? undefined : tryUseExistingNamespaceImport(existingImports, symbolName, position, checker); @@ -220,7 +220,7 @@ namespace ts.codefix { return [...(useNamespace ? [useNamespace] : emptyArray), ...addImport]; } - function tryUseExistingNamespaceImport(existingImports: ReadonlyArray, symbolName: string, position: number, checker: TypeChecker): FixUseNamespaceImport | undefined { + function tryUseExistingNamespaceImport(existingImports: readonly FixAddToExistingImportInfo[], symbolName: string, position: number, checker: TypeChecker): FixUseNamespaceImport | undefined { // It is possible that multiple import statements with the same specifier exist in the file. // e.g. // @@ -244,7 +244,7 @@ namespace ts.codefix { }); } - function tryAddToExistingImport(existingImports: ReadonlyArray): FixAddToExistingImport | undefined { + function tryAddToExistingImport(existingImports: readonly FixAddToExistingImportInfo[]): FixAddToExistingImport | undefined { return firstDefined(existingImports, ({ declaration, importKind }): FixAddToExistingImport | undefined => { if (declaration.kind !== SyntaxKind.ImportDeclaration) return undefined; const { importClause } = declaration; @@ -266,7 +266,7 @@ namespace ts.codefix { } } - function getExistingImportDeclarations({ moduleSymbol, importKind, exportedSymbolIsTypeOnly }: SymbolExportInfo, checker: TypeChecker, sourceFile: SourceFile): ReadonlyArray { + function getExistingImportDeclarations({ moduleSymbol, importKind, exportedSymbolIsTypeOnly }: SymbolExportInfo, checker: TypeChecker, sourceFile: SourceFile): readonly FixAddToExistingImportInfo[] { // Can't use an es6 import for a type in JS. return exportedSymbolIsTypeOnly && isSourceFileJS(sourceFile) ? emptyArray : mapDefined(sourceFile.imports, moduleSpecifier => { const i = importFromModuleSpecifier(moduleSpecifier); @@ -279,10 +279,10 @@ namespace ts.codefix { program: Program, sourceFile: SourceFile, position: number | undefined, - moduleSymbols: ReadonlyArray, + moduleSymbols: readonly SymbolExportInfo[], host: LanguageServiceHost, preferences: UserPreferences, - ): ReadonlyArray { + ): readonly (FixAddNewImport | FixUseImportType)[] { const isJs = isSourceFileJS(sourceFile); const choicesForEachExportingModule = flatMap(moduleSymbols, ({ moduleSymbol, importKind, exportedSymbolIsTypeOnly }) => moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap) @@ -294,14 +294,14 @@ namespace ts.codefix { } function getFixesForAddImport( - exportInfos: ReadonlyArray, - existingImports: ReadonlyArray, + exportInfos: readonly SymbolExportInfo[], + existingImports: readonly FixAddToExistingImportInfo[], program: Program, sourceFile: SourceFile, position: number | undefined, host: LanguageServiceHost, preferences: UserPreferences, - ): ReadonlyArray { + ): readonly (FixAddNewImport | FixUseImportType)[] { const existingDeclaration = firstDefined(existingImports, newImportInfoFromExistingSpecifier); return existingDeclaration ? [existingDeclaration] : getNewImportInfos(program, sourceFile, position, exportInfos, host, preferences); } @@ -315,7 +315,7 @@ namespace ts.codefix { return expression && isStringLiteral(expression) ? { kind: ImportFixKind.AddNew, moduleSpecifier: expression.text, importKind } : undefined; } - interface FixesInfo { readonly fixes: ReadonlyArray; readonly symbolName: string; } + interface FixesInfo { readonly fixes: readonly ImportFix[]; readonly symbolName: string; } function getFixesInfo(context: CodeFixContextBase, errorCode: number, pos: number): FixesInfo | undefined { const symbolToken = getTokenAtPosition(context.sourceFile, pos); const info = errorCode === Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code @@ -330,7 +330,7 @@ namespace ts.codefix { if (!umdSymbol) return undefined; const symbol = checker.getAliasedSymbol(umdSymbol); const symbolName = umdSymbol.name; - const exportInfos: ReadonlyArray = [{ moduleSymbol: symbol, importKind: getUmdImportKind(sourceFile, program.getCompilerOptions()), exportedSymbolIsTypeOnly: false }]; + const exportInfos: readonly SymbolExportInfo[] = [{ moduleSymbol: symbol, importKind: getUmdImportKind(sourceFile, program.getCompilerOptions()), exportedSymbolIsTypeOnly: false }]; const fixes = getFixForImport(exportInfos, symbolName, isIdentifier(token) ? token.getStart(sourceFile) : undefined, program, sourceFile, host, preferences); return { fixes, symbolName }; } @@ -397,7 +397,7 @@ namespace ts.codefix { sourceFile: SourceFile, checker: TypeChecker, program: Program, - ): ReadonlyMap> { + ): ReadonlyMap { // For each original symbol, keep all re-exports of that symbol together so we can call `getCodeActionsForImport` on the whole group at once. // Maps symbol id to info for modules providing that symbol (original export + re-exports). const originalSymbolToExportInfos = createMultiMap(); @@ -525,7 +525,7 @@ namespace ts.codefix { } } - function doAddExistingFix(changes: textChanges.ChangeTracker, sourceFile: SourceFile, clause: ImportClause, defaultImport: string | undefined, namedImports: ReadonlyArray): void { + function doAddExistingFix(changes: textChanges.ChangeTracker, sourceFile: SourceFile, clause: ImportClause, defaultImport: string | undefined, namedImports: readonly string[]): void { if (defaultImport) { Debug.assert(!clause.name); changes.insertNodeAt(sourceFile, clause.getStart(sourceFile), createIdentifier(defaultImport), { suffix: ", " }); @@ -605,7 +605,7 @@ namespace ts.codefix { return some(declarations, decl => !!(getMeaningFromDeclaration(decl) & meaning)); } - export function forEachExternalModuleToImportFrom(checker: TypeChecker, from: SourceFile, allSourceFiles: ReadonlyArray, cb: (module: Symbol) => void) { + export function forEachExternalModuleToImportFrom(checker: TypeChecker, from: SourceFile, allSourceFiles: readonly SourceFile[], cb: (module: Symbol) => void) { forEachExternalModule(checker, allSourceFiles, (module, sourceFile) => { if (sourceFile === undefined || sourceFile !== from && isImportablePath(from.fileName, sourceFile.fileName)) { cb(module); @@ -613,7 +613,7 @@ namespace ts.codefix { }); } - function forEachExternalModule(checker: TypeChecker, allSourceFiles: ReadonlyArray, cb: (module: Symbol, sourceFile: SourceFile | undefined) => void) { + function forEachExternalModule(checker: TypeChecker, allSourceFiles: readonly SourceFile[], cb: (module: Symbol, sourceFile: SourceFile | undefined) => void) { for (const ambient of checker.getAmbientModules()) { cb(ambient, /*sourceFile*/ undefined); } diff --git a/src/services/codefixes/inferFromUsage.ts b/src/services/codefixes/inferFromUsage.ts index e7040dd2d85..f55bdbf458e 100644 --- a/src/services/codefixes/inferFromUsage.ts +++ b/src/services/codefixes/inferFromUsage.ts @@ -292,7 +292,7 @@ namespace ts.codefix { } } - function annotateJSDocParameters(changes: textChanges.ChangeTracker, sourceFile: SourceFile, parameterInferences: ReadonlyArray, program: Program, host: LanguageServiceHost): void { + function annotateJSDocParameters(changes: textChanges.ChangeTracker, sourceFile: SourceFile, parameterInferences: readonly ParameterInference[], program: Program, host: LanguageServiceHost): void { const signature = parameterInferences.length && parameterInferences[0].declaration.parent; if (!signature) { return; @@ -310,7 +310,7 @@ namespace ts.codefix { addJSDocTags(changes, sourceFile, signature, paramTags); } - function addJSDocTags(changes: textChanges.ChangeTracker, sourceFile: SourceFile, parent: HasJSDoc, newTags: ReadonlyArray): void { + function addJSDocTags(changes: textChanges.ChangeTracker, sourceFile: SourceFile, parent: HasJSDoc, newTags: readonly JSDocTag[]): void { const comments = mapDefined(parent.jsDoc, j => j.comment); const oldTags = flatMapToMutable(parent.jsDoc, j => j.tags); const unmergedNewTags = newTags.filter(newTag => !oldTags || !oldTags.some((tag, i) => { @@ -349,7 +349,7 @@ namespace ts.codefix { } } - function getReferences(token: PropertyName | Token, program: Program, cancellationToken: CancellationToken): ReadonlyArray { + function getReferences(token: PropertyName | Token, program: Program, cancellationToken: CancellationToken): readonly Identifier[] { // Position shouldn't matter since token is not a SourceFile. return mapDefined(FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), entry => entry.kind !== FindAllReferences.EntryKind.Span ? tryCast(entry.node, isIdentifier) : undefined); @@ -362,7 +362,7 @@ namespace ts.codefix { return InferFromReference.unifyFromContext(types, checker); } - function inferFunctionReferencesFromUsage(containingFunction: FunctionLike, sourceFile: SourceFile, program: Program, cancellationToken: CancellationToken): ReadonlyArray | undefined { + function inferFunctionReferencesFromUsage(containingFunction: FunctionLike, sourceFile: SourceFile, program: Program, cancellationToken: CancellationToken): readonly Identifier[] | undefined { let searchToken; switch (containingFunction.kind) { case SyntaxKind.Constructor: @@ -415,7 +415,7 @@ namespace ts.codefix { candidateThisTypes?: Type[]; } - export function inferTypesFromReferences(references: ReadonlyArray, checker: TypeChecker, cancellationToken: CancellationToken): Type[] { + export function inferTypesFromReferences(references: readonly Identifier[], checker: TypeChecker, cancellationToken: CancellationToken): Type[] { const usageContext: UsageContext = {}; for (const reference of references) { cancellationToken.throwIfCancellationRequested(); @@ -424,7 +424,7 @@ namespace ts.codefix { return inferFromContext(usageContext, checker); } - export function inferTypeForParametersFromReferences(references: ReadonlyArray | undefined, declaration: FunctionLike, program: Program, cancellationToken: CancellationToken): ParameterInference[] | undefined { + export function inferTypeForParametersFromReferences(references: readonly Identifier[] | undefined, declaration: FunctionLike, program: Program, cancellationToken: CancellationToken): ParameterInference[] | undefined { if (references === undefined || references.length === 0 || !declaration.parameters) { return undefined; } @@ -467,7 +467,7 @@ namespace ts.codefix { }); } - export function inferTypeForThisFromReferences(references: ReadonlyArray, program: Program, cancellationToken: CancellationToken) { + export function inferTypeForThisFromReferences(references: readonly Identifier[], program: Program, cancellationToken: CancellationToken) { if (references.length === 0) { return undefined; } @@ -742,7 +742,7 @@ namespace ts.codefix { low: (t: Type) => boolean; } - function removeLowPriorityInferences(inferences: ReadonlyArray, priorities: Priority[]): Type[] { + function removeLowPriorityInferences(inferences: readonly Type[], priorities: Priority[]): Type[] { const toRemove: ((t: Type) => boolean)[] = []; for (const i of inferences) { for (const { high, low } of priorities) { @@ -755,7 +755,7 @@ namespace ts.codefix { return inferences.filter(i => toRemove.every(f => !f(i))); } - export function unifyFromContext(inferences: ReadonlyArray, checker: TypeChecker, fallback = checker.getAnyType()): Type { + export function unifyFromContext(inferences: readonly Type[], checker: TypeChecker, fallback = checker.getAnyType()): Type { if (!inferences.length) return fallback; // 1. string or number individually override string | number diff --git a/src/services/completions.ts b/src/services/completions.ts index 19039e7eec1..8b4c62ea699 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -304,7 +304,7 @@ namespace ts.Completions { } export function getCompletionEntriesFromSymbols( - symbols: ReadonlyArray, + symbols: readonly Symbol[], entries: Push, location: Node | undefined, sourceFile: SourceFile, @@ -567,7 +567,7 @@ namespace ts.Completions { type IsJsxInitializer = boolean | Identifier; interface CompletionData { readonly kind: CompletionDataKind.Data; - readonly symbols: ReadonlyArray; + readonly symbols: readonly Symbol[]; readonly completionKind: CompletionKind; readonly isInSnippetScope: boolean; /** Note that the presence of this alone doesn't mean that we need a conversion. Only do that if the completion is not an ordinary identifier. */ @@ -575,7 +575,7 @@ namespace ts.Completions { readonly isNewIdentifierLocation: boolean; readonly location: Node | undefined; readonly keywordFilters: KeywordCompletionFilters; - readonly literals: ReadonlyArray; + readonly literals: readonly (string | number | PseudoBigInt)[]; readonly symbolToOriginInfoMap: SymbolOriginInfoMap; readonly recommendedCompletion: Symbol | undefined; readonly previousToken: Node | undefined; @@ -1466,7 +1466,7 @@ namespace ts.Completions { completionKind = CompletionKind.ObjectPropertyDeclaration; let typeMembers: Symbol[] | undefined; - let existingMembers: ReadonlyArray | undefined; + let existingMembers: readonly Declaration[] | undefined; if (objectLikeContainer.kind === SyntaxKind.ObjectLiteralExpression) { const typeForObject = typeChecker.getContextualType(objectLikeContainer); @@ -1876,7 +1876,7 @@ namespace ts.Completions { * @returns Symbols to be suggested in an object binding pattern or object literal expression, barring those whose declarations * do not occur at the current position and have not otherwise been typed. */ - function filterObjectMembersList(contextualMemberSymbols: Symbol[], existingMembers: ReadonlyArray): Symbol[] { + function filterObjectMembersList(contextualMemberSymbols: Symbol[], existingMembers: readonly Declaration[]): Symbol[] { if (existingMembers.length === 0) { return contextualMemberSymbols; } @@ -1925,7 +1925,7 @@ namespace ts.Completions { * * @returns Symbols to be suggested in an class element depending on existing memebers and symbol flags */ - function filterClassMembersList(baseSymbols: ReadonlyArray, existingMembers: ReadonlyArray, currentClassElementModifierFlags: ModifierFlags): Symbol[] { + function filterClassMembersList(baseSymbols: readonly Symbol[], existingMembers: readonly ClassElement[], currentClassElementModifierFlags: ModifierFlags): Symbol[] { const existingMemberNames = createUnderscoreEscapedMap(); for (const m of existingMembers) { // Ignore omitted expressions for missing members @@ -2031,8 +2031,8 @@ namespace ts.Completions { } // A cache of completion entries for keywords, these do not change between sessions - const _keywordCompletions: ReadonlyArray[] = []; - const allKeywordsCompletions: () => ReadonlyArray = memoize(() => { + const _keywordCompletions: CompletionEntry[][] = []; + const allKeywordsCompletions: () => readonly CompletionEntry[] = memoize(() => { const res: CompletionEntry[] = []; for (let i = SyntaxKind.FirstKeyword; i <= SyntaxKind.LastKeyword; i++) { res.push({ @@ -2045,7 +2045,7 @@ namespace ts.Completions { return res; }); - function getKeywordCompletions(keywordFilter: KeywordCompletionFilters, filterOutTsOnlyKeywords: boolean): ReadonlyArray { + function getKeywordCompletions(keywordFilter: KeywordCompletionFilters, filterOutTsOnlyKeywords: boolean): readonly CompletionEntry[] { if (!filterOutTsOnlyKeywords) return getTypescriptKeywordCompletions(keywordFilter); const index = keywordFilter + KeywordCompletionFilters.Last + 1; @@ -2055,7 +2055,7 @@ namespace ts.Completions { ); } - function getTypescriptKeywordCompletions(keywordFilter: KeywordCompletionFilters): ReadonlyArray { + function getTypescriptKeywordCompletions(keywordFilter: KeywordCompletionFilters): readonly CompletionEntry[] { return _keywordCompletions[keywordFilter] || (_keywordCompletions[keywordFilter] = allKeywordsCompletions().filter(entry => { const kind = stringToToken(entry.name)!; switch (keywordFilter) { diff --git a/src/services/documentHighlights.ts b/src/services/documentHighlights.ts index 3a48fbb8cb7..6ee6e5fac8c 100644 --- a/src/services/documentHighlights.ts +++ b/src/services/documentHighlights.ts @@ -1,6 +1,6 @@ /* @internal */ namespace ts.DocumentHighlights { - export function getDocumentHighlights(program: Program, cancellationToken: CancellationToken, sourceFile: SourceFile, position: number, sourceFilesToSearch: ReadonlyArray): DocumentHighlights[] | undefined { + export function getDocumentHighlights(program: Program, cancellationToken: CancellationToken, sourceFile: SourceFile, position: number, sourceFilesToSearch: readonly SourceFile[]): DocumentHighlights[] | undefined { const node = getTouchingPropertyName(sourceFile, position); if (node.parent && (isJsxOpeningElement(node.parent) && node.parent.tagName === node || isJsxClosingElement(node.parent))) { @@ -21,7 +21,7 @@ namespace ts.DocumentHighlights { }; } - function getSemanticDocumentHighlights(position: number, node: Node, program: Program, cancellationToken: CancellationToken, sourceFilesToSearch: ReadonlyArray): DocumentHighlights[] | undefined { + function getSemanticDocumentHighlights(position: number, node: Node, program: Program, cancellationToken: CancellationToken, sourceFilesToSearch: readonly SourceFile[]): DocumentHighlights[] | undefined { const sourceFilesSet = arrayToSet(sourceFilesToSearch, f => f.fileName); const referenceEntries = FindAllReferences.getReferenceEntriesForNode(position, node, program, sourceFilesToSearch, cancellationToken, /*options*/ undefined, sourceFilesSet); if (!referenceEntries) return undefined; @@ -86,16 +86,16 @@ namespace ts.DocumentHighlights { : undefined; } - function getFromAllDeclarations(nodeTest: (node: Node) => node is T, keywords: ReadonlyArray): HighlightSpan[] | undefined { + function getFromAllDeclarations(nodeTest: (node: Node) => node is T, keywords: readonly SyntaxKind[]): HighlightSpan[] | undefined { return useParent(node.parent, nodeTest, decl => mapDefined(decl.symbol.declarations, d => nodeTest(d) ? find(d.getChildren(sourceFile), c => contains(keywords, c.kind)) : undefined)); } - function useParent(node: Node, nodeTest: (node: Node) => node is T, getNodes: (node: T, sourceFile: SourceFile) => ReadonlyArray | undefined): HighlightSpan[] | undefined { + function useParent(node: Node, nodeTest: (node: Node) => node is T, getNodes: (node: T, sourceFile: SourceFile) => readonly Node[] | undefined): HighlightSpan[] | undefined { return nodeTest(node) ? highlightSpans(getNodes(node, sourceFile)) : undefined; } - function highlightSpans(nodes: ReadonlyArray | undefined): HighlightSpan[] | undefined { + function highlightSpans(nodes: readonly Node[] | undefined): HighlightSpan[] | undefined { return nodes && nodes.map(node => getHighlightSpanForNode(node, sourceFile)); } } @@ -104,7 +104,7 @@ namespace ts.DocumentHighlights { * Aggregates all throw-statements within this node *without* crossing * into function boundaries and try-blocks with catch-clauses. */ - function aggregateOwnedThrowStatements(node: Node): ReadonlyArray | undefined { + function aggregateOwnedThrowStatements(node: Node): readonly ThrowStatement[] | undefined { if (isThrowStatement(node)) { return [node]; } @@ -145,11 +145,11 @@ namespace ts.DocumentHighlights { return undefined; } - function aggregateAllBreakAndContinueStatements(node: Node): ReadonlyArray | undefined { + function aggregateAllBreakAndContinueStatements(node: Node): readonly BreakOrContinueStatement[] | undefined { return isBreakOrContinueStatement(node) ? [node] : isFunctionLike(node) ? undefined : flatMapChildren(node, aggregateAllBreakAndContinueStatements); } - function flatMapChildren(node: Node, cb: (child: Node) => ReadonlyArray | T | undefined): ReadonlyArray { + function flatMapChildren(node: Node, cb: (child: Node) => readonly T[] | T | undefined): readonly T[] { const result: T[] = []; node.forEachChild(child => { const value = cb(child); @@ -192,7 +192,7 @@ namespace ts.DocumentHighlights { return mapDefined(getNodesToSearchForModifier(declaration, modifierToFlag(modifier)), node => findModifier(node, modifier)); } - function getNodesToSearchForModifier(declaration: Node, modifierFlag: ModifierFlags): ReadonlyArray | undefined { + function getNodesToSearchForModifier(declaration: Node, modifierFlag: ModifierFlags): readonly Node[] | undefined { // Types of node whose children might have modifiers. const container = declaration.parent as ModuleBlock | SourceFile | Block | CaseClause | DefaultClause | ConstructorDeclaration | MethodDeclaration | FunctionDeclaration | ObjectTypeDeclaration; switch (container.kind) { diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index 447a5ffe61d..7837c246d16 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -2,7 +2,7 @@ namespace ts.FindAllReferences { export interface SymbolAndEntries { readonly definition: Definition | undefined; - readonly references: ReadonlyArray; + readonly references: readonly Entry[]; } export const enum DefinitionKind { Symbol, Label, Keyword, This, String } @@ -189,7 +189,7 @@ namespace ts.FindAllReferences { readonly providePrefixAndSuffixTextForRename?: boolean; } - export function findReferencedSymbols(program: Program, cancellationToken: CancellationToken, sourceFiles: ReadonlyArray, sourceFile: SourceFile, position: number): ReferencedSymbol[] | undefined { + export function findReferencedSymbols(program: Program, cancellationToken: CancellationToken, sourceFiles: readonly SourceFile[], sourceFile: SourceFile, position: number): ReferencedSymbol[] | undefined { const node = getTouchingPropertyName(sourceFile, position); const referencedSymbols = Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken); const checker = program.getTypeChecker(); @@ -201,14 +201,14 @@ namespace ts.FindAllReferences { }); } - export function getImplementationsAtPosition(program: Program, cancellationToken: CancellationToken, sourceFiles: ReadonlyArray, sourceFile: SourceFile, position: number): ImplementationLocation[] | undefined { + export function getImplementationsAtPosition(program: Program, cancellationToken: CancellationToken, sourceFiles: readonly SourceFile[], sourceFile: SourceFile, position: number): ImplementationLocation[] | undefined { const node = getTouchingPropertyName(sourceFile, position); const referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position); const checker = program.getTypeChecker(); return map(referenceEntries, entry => toImplementationLocation(entry, checker)); } - function getImplementationReferenceEntries(program: Program, cancellationToken: CancellationToken, sourceFiles: ReadonlyArray, node: Node, position: number): ReadonlyArray | undefined { + function getImplementationReferenceEntries(program: Program, cancellationToken: CancellationToken, sourceFiles: readonly SourceFile[], node: Node, position: number): readonly Entry[] | undefined { if (node.kind === SyntaxKind.SourceFile) { return undefined; } @@ -234,7 +234,7 @@ namespace ts.FindAllReferences { } export function findReferenceOrRenameEntries( - program: Program, cancellationToken: CancellationToken, sourceFiles: ReadonlyArray, node: Node, position: number, options: Options | undefined, + program: Program, cancellationToken: CancellationToken, sourceFiles: readonly SourceFile[], node: Node, position: number, options: Options | undefined, convertEntry: ToReferenceOrRenameEntry, ): T[] | undefined { return map(flattenEntries(Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), entry => convertEntry(entry, node, program.getTypeChecker())); @@ -246,15 +246,15 @@ namespace ts.FindAllReferences { position: number, node: Node, program: Program, - sourceFiles: ReadonlyArray, + sourceFiles: readonly SourceFile[], cancellationToken: CancellationToken, options: Options = {}, sourceFilesSet: ReadonlyMap = arrayToSet(sourceFiles, f => f.fileName), - ): ReadonlyArray | undefined { + ): readonly Entry[] | undefined { return flattenEntries(Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet)); } - function flattenEntries(referenceSymbols: ReadonlyArray | undefined): ReadonlyArray | undefined { + function flattenEntries(referenceSymbols: readonly SymbolAndEntries[] | undefined): readonly Entry[] | undefined { return referenceSymbols && flatMap(referenceSymbols, r => r.references); } @@ -533,7 +533,7 @@ namespace ts.FindAllReferences { // eslint-disable-next-line no-redeclare namespace ts.FindAllReferences.Core { /** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */ - export function getReferencedSymbolsForNode(position: number, node: Node, program: Program, sourceFiles: ReadonlyArray, cancellationToken: CancellationToken, options: Options = {}, sourceFilesSet: ReadonlyMap = arrayToSet(sourceFiles, f => f.fileName)): ReadonlyArray | undefined { + export function getReferencedSymbolsForNode(position: number, node: Node, program: Program, sourceFiles: readonly SourceFile[], cancellationToken: CancellationToken, options: Options = {}, sourceFilesSet: ReadonlyMap = arrayToSet(sourceFiles, f => f.fileName)): readonly SymbolAndEntries[] | undefined { if (isSourceFile(node)) { const reference = GoToDefinition.getReferenceAtPosition(node, position, program); const moduleSymbol = reference && program.getTypeChecker().getMergedSymbol(reference.file.symbol); @@ -584,7 +584,7 @@ namespace ts.FindAllReferences.Core { return undefined; } - function getReferencedSymbolsForModuleIfDeclaredBySourceFile(symbol: Symbol, program: Program, sourceFiles: ReadonlyArray, cancellationToken: CancellationToken, options: Options, sourceFilesSet: ReadonlyMap) { + function getReferencedSymbolsForModuleIfDeclaredBySourceFile(symbol: Symbol, program: Program, sourceFiles: readonly SourceFile[], cancellationToken: CancellationToken, options: Options, sourceFilesSet: ReadonlyMap) { const moduleSourceFile = symbol.flags & SymbolFlags.Module ? find(symbol.declarations, isSourceFile) : undefined; if (!moduleSourceFile) return undefined; const exportEquals = symbol.exports!.get(InternalSymbolName.ExportEquals); @@ -651,7 +651,7 @@ namespace ts.FindAllReferences.Core { return program.getSourceFiles().indexOf(sourceFile); } - function getReferencedSymbolsForModule(program: Program, symbol: Symbol, excludeImportTypeOfExportEquals: boolean, sourceFiles: ReadonlyArray, sourceFilesSet: ReadonlyMap): SymbolAndEntries[] { + function getReferencedSymbolsForModule(program: Program, symbol: Symbol, excludeImportTypeOfExportEquals: boolean, sourceFiles: readonly SourceFile[], sourceFilesSet: ReadonlyMap): SymbolAndEntries[] { Debug.assert(!!symbol.valueDeclaration); const references = mapDefined(findModuleReferences(program, sourceFiles, symbol), reference => { @@ -716,7 +716,7 @@ namespace ts.FindAllReferences.Core { } /** getReferencedSymbols for special node kinds. */ - function getReferencedSymbolsSpecial(node: Node, sourceFiles: ReadonlyArray, cancellationToken: CancellationToken): SymbolAndEntries[] | undefined { + function getReferencedSymbolsSpecial(node: Node, sourceFiles: readonly SourceFile[], cancellationToken: CancellationToken): SymbolAndEntries[] | undefined { if (isTypeKeyword(node.kind)) { // A modifier readonly (like on a property declaration) is not special; // a readonly type keyword (like `readonly string[]`) is. @@ -756,7 +756,7 @@ namespace ts.FindAllReferences.Core { } /** Core find-all-references algorithm for a normal symbol. */ - function getReferencedSymbolsForSymbol(originalSymbol: Symbol, node: Node | undefined, sourceFiles: ReadonlyArray, sourceFilesSet: ReadonlyMap, checker: TypeChecker, cancellationToken: CancellationToken, options: Options): SymbolAndEntries[] { + function getReferencedSymbolsForSymbol(originalSymbol: Symbol, node: Node | undefined, sourceFiles: readonly SourceFile[], sourceFilesSet: ReadonlyMap, checker: TypeChecker, cancellationToken: CancellationToken, options: Options): SymbolAndEntries[] { const symbol = node && skipPastExportOrImportSpecifierOrUnion(originalSymbol, node, checker, /*useLocalSymbolForExportSpecifier*/ !isForRenameWithPrefixAndSuffixText(options)) || originalSymbol; // Compute the meaning from the location and the symbol it references @@ -845,8 +845,8 @@ namespace ts.FindAllReferences.Core { readonly text: string; readonly escapedText: __String; /** Only set if `options.implementations` is true. These are the symbols checked to get the implementations of a property access. */ - readonly parents: ReadonlyArray | undefined; - readonly allSearchSymbols: ReadonlyArray; + readonly parents: readonly Symbol[] | undefined; + readonly allSearchSymbols: readonly Symbol[]; /** * Whether a symbol is in the search set. @@ -898,7 +898,7 @@ namespace ts.FindAllReferences.Core { readonly markSeenReExportRHS = nodeSeenTracker(); constructor( - readonly sourceFiles: ReadonlyArray, + readonly sourceFiles: readonly SourceFile[], readonly sourceFilesSet: ReadonlyMap, readonly specialSearchKind: SpecialSearchKind, readonly checker: TypeChecker, @@ -960,7 +960,7 @@ namespace ts.FindAllReferences.Core { // Source file ID → symbol ID → Whether the symbol has been searched for in the source file. private readonly sourceFileToSeenSymbols: Map[] = []; /** Returns `true` the first time we search for a symbol in a file and `false` afterwards. */ - markSearchedSymbols(sourceFile: SourceFile, symbols: ReadonlyArray): boolean { + markSearchedSymbols(sourceFile: SourceFile, symbols: readonly Symbol[]): boolean { const sourceId = getNodeId(sourceFile); const seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = createMap()); @@ -1011,7 +1011,7 @@ namespace ts.FindAllReferences.Core { } export function eachExportReference( - sourceFiles: ReadonlyArray, + sourceFiles: readonly SourceFile[], checker: TypeChecker, cancellationToken: CancellationToken | undefined, exportSymbol: Symbol, @@ -1162,7 +1162,7 @@ namespace ts.FindAllReferences.Core { } } - export function eachSignatureCall(signature: SignatureDeclaration, sourceFiles: ReadonlyArray, checker: TypeChecker, cb: (call: CallExpression) => void): void { + export function eachSignatureCall(signature: SignatureDeclaration, sourceFiles: readonly SourceFile[], checker: TypeChecker, cb: (call: CallExpression) => void): void { if (!signature.name || !isIdentifier(signature.name)) return; const symbol = Debug.assertDefined(checker.getSymbolAtLocation(signature.name)); @@ -1181,11 +1181,11 @@ namespace ts.FindAllReferences.Core { } } - function getPossibleSymbolReferenceNodes(sourceFile: SourceFile, symbolName: string, container: Node = sourceFile): ReadonlyArray { + function getPossibleSymbolReferenceNodes(sourceFile: SourceFile, symbolName: string, container: Node = sourceFile): readonly Node[] { return getPossibleSymbolReferencePositions(sourceFile, symbolName, container).map(pos => getTouchingPropertyName(sourceFile, pos)); } - function getPossibleSymbolReferencePositions(sourceFile: SourceFile, symbolName: string, container: Node = sourceFile): ReadonlyArray { + function getPossibleSymbolReferencePositions(sourceFile: SourceFile, symbolName: string, container: Node = sourceFile): readonly number[] { const positions: number[] = []; /// TODO: Cache symbol existence for files to save text search @@ -1252,7 +1252,7 @@ namespace ts.FindAllReferences.Core { } } - function getAllReferencesForKeyword(sourceFiles: ReadonlyArray, keywordKind: SyntaxKind, cancellationToken: CancellationToken, filter?: (node: Node) => boolean): SymbolAndEntries[] | undefined { + function getAllReferencesForKeyword(sourceFiles: readonly SourceFile[], keywordKind: SyntaxKind, cancellationToken: CancellationToken, filter?: (node: Node) => boolean): SymbolAndEntries[] | undefined { const references = flatMap(sourceFiles, sourceFile => { cancellationToken.throwIfCancellationRequested(); return mapDefined(getPossibleSymbolReferenceNodes(sourceFile, tokenToString(keywordKind)!, sourceFile), referenceLocation => { @@ -1743,7 +1743,7 @@ namespace ts.FindAllReferences.Core { return node.kind === SyntaxKind.Identifier && node.parent.kind === SyntaxKind.Parameter && (node.parent).name === node; } - function getReferencesForThisKeyword(thisOrSuperKeyword: Node, sourceFiles: ReadonlyArray, cancellationToken: CancellationToken): SymbolAndEntries[] | undefined { + function getReferencesForThisKeyword(thisOrSuperKeyword: Node, sourceFiles: readonly SourceFile[], cancellationToken: CancellationToken): SymbolAndEntries[] | undefined { let searchSpaceNode = getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); // Whether 'this' occurs in a static context within a class. @@ -1810,7 +1810,7 @@ namespace ts.FindAllReferences.Core { }]; } - function getReferencesForStringLiteral(node: StringLiteral, sourceFiles: ReadonlyArray, cancellationToken: CancellationToken): SymbolAndEntries[] { + function getReferencesForStringLiteral(node: StringLiteral, sourceFiles: readonly SourceFile[], cancellationToken: CancellationToken): SymbolAndEntries[] { const references = flatMap(sourceFiles, sourceFile => { cancellationToken.throwIfCancellationRequested(); return mapDefined(getPossibleSymbolReferenceNodes(sourceFile, node.text), ref => @@ -2031,7 +2031,7 @@ namespace ts.FindAllReferences.Core { * symbol may have a different parent symbol if the local type's symbol does not declare the property * being accessed (i.e. it is declared in some parent class or interface) */ - function getParentSymbolsOfPropertyAccess(location: Node, symbol: Symbol, checker: TypeChecker): ReadonlyArray | undefined { + function getParentSymbolsOfPropertyAccess(location: Node, symbol: Symbol, checker: TypeChecker): readonly Symbol[] | undefined { const propertyAccessExpression = isRightSideOfPropertyAccess(location) ? location.parent : undefined; const lhsType = propertyAccessExpression && checker.getTypeAtLocation(propertyAccessExpression.expression); const res = mapDefined(lhsType && (lhsType.isUnionOrIntersection() ? lhsType.types : lhsType.symbol === symbol.parent ? undefined : [lhsType]), t => diff --git a/src/services/formatting/formatting.ts b/src/services/formatting/formatting.ts index 561ea5b75b3..f9b0d752db7 100644 --- a/src/services/formatting/formatting.ts +++ b/src/services/formatting/formatting.ts @@ -228,7 +228,7 @@ namespace ts.formatting { * This function will return a predicate that for a given text range will tell * if there are any parse errors that overlap with the range. */ - function prepareRangeContainsErrorFunction(errors: ReadonlyArray, originalRange: TextRange): (r: TextRange) => boolean { + function prepareRangeContainsErrorFunction(errors: readonly Diagnostic[], originalRange: TextRange): (r: TextRange) => boolean { if (!errors.length) { return rangeHasNoErrors; } @@ -1222,7 +1222,7 @@ namespace ts.formatting { position === range.end && (range.kind === SyntaxKind.SingleLineCommentTrivia || position === sourceFile.getFullWidth())); } - function getOpenTokenForList(node: Node, list: ReadonlyArray) { + function getOpenTokenForList(node: Node, list: readonly Node[]) { switch (node.kind) { case SyntaxKind.Constructor: case SyntaxKind.FunctionDeclaration: diff --git a/src/services/formatting/rule.ts b/src/services/formatting/rule.ts index aa1bb6b43e9..a3548952324 100644 --- a/src/services/formatting/rule.ts +++ b/src/services/formatting/rule.ts @@ -3,13 +3,13 @@ namespace ts.formatting { export interface Rule { // Used for debugging to identify each rule based on the property name it's assigned to. readonly debugName: string; - readonly context: ReadonlyArray; + readonly context: readonly ContextPredicate[]; readonly action: RuleAction; readonly flags: RuleFlags; } export type ContextPredicate = (context: FormattingContext) => boolean; - export const anyContext: ReadonlyArray = emptyArray; + export const anyContext: readonly ContextPredicate[] = emptyArray; export const enum RuleAction { Ignore = 1 << 0, @@ -24,7 +24,7 @@ namespace ts.formatting { } export interface TokenRange { - readonly tokens: ReadonlyArray; + readonly tokens: readonly SyntaxKind[]; readonly isSpecific: boolean; } } \ No newline at end of file diff --git a/src/services/formatting/rules.ts b/src/services/formatting/rules.ts index d0af828b03e..670048eb737 100644 --- a/src/services/formatting/rules.ts +++ b/src/services/formatting/rules.ts @@ -364,24 +364,24 @@ namespace ts.formatting { */ function rule( debugName: string, - left: SyntaxKind | ReadonlyArray | TokenRange, - right: SyntaxKind | ReadonlyArray | TokenRange, - context: ReadonlyArray, + left: SyntaxKind | readonly SyntaxKind[] | TokenRange, + right: SyntaxKind | readonly SyntaxKind[] | TokenRange, + context: readonly ContextPredicate[], action: RuleAction, flags: RuleFlags = RuleFlags.None, ): RuleSpec { return { leftTokenRange: toTokenRange(left), rightTokenRange: toTokenRange(right), rule: { debugName, context, action, flags } }; } - function tokenRangeFrom(tokens: ReadonlyArray): TokenRange { + function tokenRangeFrom(tokens: readonly SyntaxKind[]): TokenRange { return { tokens, isSpecific: true }; } - function toTokenRange(arg: SyntaxKind | ReadonlyArray | TokenRange): TokenRange { + function toTokenRange(arg: SyntaxKind | readonly SyntaxKind[] | TokenRange): TokenRange { return typeof arg === "number" ? tokenRangeFrom([arg]) : isArray(arg) ? tokenRangeFrom(arg) : arg; } - function tokenRangeFromRange(from: SyntaxKind, to: SyntaxKind, except: ReadonlyArray = []): TokenRange { + function tokenRangeFromRange(from: SyntaxKind, to: SyntaxKind, except: readonly SyntaxKind[] = []): TokenRange { const tokens: SyntaxKind[] = []; for (let token = from; token <= to; token++) { if (!contains(except, token)) { diff --git a/src/services/formatting/rulesMap.ts b/src/services/formatting/rulesMap.ts index 228e5c6fcee..9c57fa8f8c8 100644 --- a/src/services/formatting/rulesMap.ts +++ b/src/services/formatting/rulesMap.ts @@ -14,7 +14,7 @@ namespace ts.formatting { } export type RulesMap = (context: FormattingContext) => Rule | undefined; - function createRulesMap(rules: ReadonlyArray): RulesMap { + function createRulesMap(rules: readonly RuleSpec[]): RulesMap { const map = buildMap(rules); return context => { const bucket = map[getRuleBucketIndex(context.currentTokenSpan.kind, context.nextTokenSpan.kind)]; @@ -22,7 +22,7 @@ namespace ts.formatting { }; } - function buildMap(rules: ReadonlyArray): ReadonlyArray> { + function buildMap(rules: readonly RuleSpec[]): readonly (readonly Rule[])[] { // Map from bucket index to array of rules const map: Rule[][] = new Array(mapRowLength * mapRowLength); // This array is used only during construction of the rulesbucket in the map diff --git a/src/services/formatting/smartIndenter.ts b/src/services/formatting/smartIndenter.ts index e45d59e8839..5958190169a 100644 --- a/src/services/formatting/smartIndenter.ts +++ b/src/services/formatting/smartIndenter.ts @@ -430,7 +430,7 @@ namespace ts.formatting { return Value.Unknown; } - function deriveActualIndentationFromList(list: ReadonlyArray, index: number, sourceFile: SourceFile, options: EditorSettings): number { + function deriveActualIndentationFromList(list: readonly Node[], index: number, sourceFile: SourceFile, options: EditorSettings): number { Debug.assert(index >= 0 && index < list.length); const node = list[index]; diff --git a/src/services/getEditsForFileRename.ts b/src/services/getEditsForFileRename.ts index 66cc88c2677..e2428eeaade 100644 --- a/src/services/getEditsForFileRename.ts +++ b/src/services/getEditsForFileRename.ts @@ -8,7 +8,7 @@ namespace ts { formatContext: formatting.FormatContext, _preferences: UserPreferences, sourceMapper: SourceMapper, - ): ReadonlyArray { + ): readonly FileTextChanges[] { const useCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames(host); const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); const oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper); @@ -91,7 +91,7 @@ namespace ts { function updatePaths(property: PropertyAssignment): boolean { // Type annotation needed due to #7294 - const elements: ReadonlyArray = isArrayLiteralExpression(property.initializer) ? property.initializer.elements : [property.initializer]; + const elements: readonly Expression[] = isArrayLiteralExpression(property.initializer) ? property.initializer.elements : [property.initializer]; let foundExactMatch = false; for (const element of elements) { foundExactMatch = tryUpdateString(element) || foundExactMatch; diff --git a/src/services/goToDefinition.ts b/src/services/goToDefinition.ts index e514ca01e79..09b78a7f05b 100644 --- a/src/services/goToDefinition.ts +++ b/src/services/goToDefinition.ts @@ -1,6 +1,6 @@ /* @internal */ namespace ts.GoToDefinition { - export function getDefinitionAtPosition(program: Program, sourceFile: SourceFile, position: number): ReadonlyArray | undefined { + export function getDefinitionAtPosition(program: Program, sourceFile: SourceFile, position: number): readonly DefinitionInfo[] | undefined { const reference = getReferenceAtPosition(sourceFile, position, program); if (reference) { return [getDefinitionInfoForFileReference(reference.fileName, reference.file.fileName)]; @@ -129,7 +129,7 @@ namespace ts.GoToDefinition { } /// Goto type - export function getTypeDefinitionAtPosition(typeChecker: TypeChecker, sourceFile: SourceFile, position: number): ReadonlyArray | undefined { + export function getTypeDefinitionAtPosition(typeChecker: TypeChecker, sourceFile: SourceFile, position: number): readonly DefinitionInfo[] | undefined { const node = getTouchingPropertyName(sourceFile, position); if (node === sourceFile) { return undefined; @@ -145,7 +145,7 @@ namespace ts.GoToDefinition { return fromReturnType && fromReturnType.length !== 0 ? fromReturnType : definitionFromType(typeAtLocation, typeChecker, node); } - function definitionFromType(type: Type, checker: TypeChecker, node: Node): ReadonlyArray { + function definitionFromType(type: Type, checker: TypeChecker, node: Node): readonly DefinitionInfo[] { return flatMap(type.isUnion() && !(type.flags & TypeFlags.Enum) ? type.types : [type], t => t.symbol && getDefinitionFromSymbol(checker, t.symbol, node)); } @@ -253,7 +253,7 @@ namespace ts.GoToDefinition { : undefined; } - function getSignatureDefinition(signatureDeclarations: ReadonlyArray | undefined, selectConstructors: boolean): DefinitionInfo[] | undefined { + function getSignatureDefinition(signatureDeclarations: readonly Declaration[] | undefined, selectConstructors: boolean): DefinitionInfo[] | undefined { if (!signatureDeclarations) { return undefined; } @@ -296,7 +296,7 @@ namespace ts.GoToDefinition { return createDefinitionInfo(decl, typeChecker, decl.symbol, decl); } - export function findReferenceInPosition(refs: ReadonlyArray, pos: number): FileReference | undefined { + export function findReferenceInPosition(refs: readonly FileReference[], pos: number): FileReference | undefined { return find(refs, ref => textRangeContainsPositionInclusive(ref, pos)); } diff --git a/src/services/importTracker.ts b/src/services/importTracker.ts index 5890a39f461..85d2027603c 100644 --- a/src/services/importTracker.ts +++ b/src/services/importTracker.ts @@ -3,16 +3,16 @@ namespace ts.FindAllReferences { export interface ImportsResult { /** For every import of the symbol, the location and local symbol for the import. */ - importSearches: ReadonlyArray<[Identifier, Symbol]>; + importSearches: readonly [Identifier, Symbol][]; /** For rename imports/exports `{ foo as bar }`, `foo` is not a local, so it may be added as a reference immediately without further searching. */ - singleReferences: ReadonlyArray; + singleReferences: readonly (Identifier | StringLiteral)[]; /** List of source files that may (or may not) use the symbol via a namespace. (For UMD modules this is every file.) */ - indirectUsers: ReadonlyArray; + indirectUsers: readonly SourceFile[]; } export type ImportTracker = (exportSymbol: Symbol, exportInfo: ExportInfo, isForRename: boolean) => ImportsResult; /** Creates the imports map and returns an ImportTracker that uses it. Call this lazily to avoid calling `getDirectImportsMap` unnecessarily. */ - export function createImportTracker(sourceFiles: ReadonlyArray, sourceFilesSet: ReadonlyMap, checker: TypeChecker, cancellationToken: CancellationToken | undefined): ImportTracker { + export function createImportTracker(sourceFiles: readonly SourceFile[], sourceFilesSet: ReadonlyMap, checker: TypeChecker, cancellationToken: CancellationToken | undefined): ImportTracker { const allDirectImports = getDirectImportsMap(sourceFiles, checker, cancellationToken); return (exportSymbol, exportInfo, isForRename) => { const { directImports, indirectUsers } = getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, exportInfo, checker, cancellationToken); @@ -38,13 +38,13 @@ namespace ts.FindAllReferences { /** Returns import statements that directly reference the exporting module, and a list of files that may access the module through a namespace. */ function getImportersForExport( - sourceFiles: ReadonlyArray, + sourceFiles: readonly SourceFile[], sourceFilesSet: ReadonlyMap, allDirectImports: Map, { exportingModuleSymbol, exportKind }: ExportInfo, checker: TypeChecker, cancellationToken: CancellationToken | undefined, - ): { directImports: Importer[], indirectUsers: ReadonlyArray } { + ): { directImports: Importer[], indirectUsers: readonly SourceFile[] } { const markSeenDirectImport = nodeSeenTracker(); const markSeenIndirectUser = nodeSeenTracker(); const directImports: Importer[] = []; @@ -55,7 +55,7 @@ namespace ts.FindAllReferences { return { directImports, indirectUsers: getIndirectUsers() }; - function getIndirectUsers(): ReadonlyArray { + function getIndirectUsers(): readonly SourceFile[] { if (isAvailableThroughGlobal) { // It has `export as namespace`, so anything could potentially use it. return sourceFiles; @@ -333,7 +333,7 @@ namespace ts.FindAllReferences { | { kind: "import", literal: StringLiteralLike } /** or */ | { kind: "reference", referencingFile: SourceFile, ref: FileReference }; - export function findModuleReferences(program: Program, sourceFiles: ReadonlyArray, searchModuleSymbol: Symbol): ModuleReference[] { + export function findModuleReferences(program: Program, sourceFiles: readonly SourceFile[], searchModuleSymbol: Symbol): ModuleReference[] { const refs: ModuleReference[] = []; const checker = program.getTypeChecker(); for (const referencingFile of sourceFiles) { @@ -363,7 +363,7 @@ namespace ts.FindAllReferences { } /** Returns a map from a module symbol Id to all import statements that directly reference the module. */ - function getDirectImportsMap(sourceFiles: ReadonlyArray, checker: TypeChecker, cancellationToken: CancellationToken | undefined): Map { + function getDirectImportsMap(sourceFiles: readonly SourceFile[], checker: TypeChecker, cancellationToken: CancellationToken | undefined): Map { const map = createMap(); for (const sourceFile of sourceFiles) { diff --git a/src/services/jsDoc.ts b/src/services/jsDoc.ts index f14a3a1e5d5..f5c86bcf9cb 100644 --- a/src/services/jsDoc.ts +++ b/src/services/jsDoc.ts @@ -82,7 +82,7 @@ namespace ts.JsDoc { let jsDocTagNameCompletionEntries: CompletionEntry[]; let jsDocTagCompletionEntries: CompletionEntry[]; - export function getJsDocCommentsFromDeclarations(declarations: ReadonlyArray): SymbolDisplayPart[] { + export function getJsDocCommentsFromDeclarations(declarations: readonly Declaration[]): SymbolDisplayPart[] { // Only collect doc comments from duplicate declarations once: // In case of a union property there might be same declaration multiple times // which only varies in type parameter @@ -102,7 +102,7 @@ namespace ts.JsDoc { return documentationComment; } - function getCommentHavingNodes(declaration: Declaration): ReadonlyArray { + function getCommentHavingNodes(declaration: Declaration): readonly (JSDoc | JSDocTag)[] { switch (declaration.kind) { case SyntaxKind.JSDocParameterTag: case SyntaxKind.JSDocPropertyTag: @@ -163,7 +163,7 @@ namespace ts.JsDoc { * returns a truthy value, then returns that value. * If no such value is found, the callback is applied to each element of array and undefined is returned. */ - function forEachUnique(array: ReadonlyArray | undefined, callback: (element: T, index: number) => U): U | undefined { + function forEachUnique(array: readonly T[] | undefined, callback: (element: T, index: number) => U): U | undefined { if (array) { for (let i = 0; i < array.length; i++) { if (array.indexOf(array[i]) === i) { @@ -327,7 +327,7 @@ namespace ts.JsDoc { return text.slice(lineStart, pos); } - function parameterDocComments(parameters: ReadonlyArray, isJavaScriptFile: boolean, indentationStr: string, newLine: string): string { + function parameterDocComments(parameters: readonly ParameterDeclaration[], isJavaScriptFile: boolean, indentationStr: string, newLine: string): string { return parameters.map(({ name, dotDotDotToken }, i) => { const paramName = name.kind === SyntaxKind.Identifier ? name.text : "param" + i; const type = isJavaScriptFile ? (dotDotDotToken ? "{...any} " : "{any} ") : ""; @@ -337,7 +337,7 @@ namespace ts.JsDoc { interface CommentOwnerInfo { readonly commentOwner: Node; - readonly parameters?: ReadonlyArray; + readonly parameters?: readonly ParameterDeclaration[]; } function getCommentOwnerInfo(tokenAtPos: Node): CommentOwnerInfo | undefined { return forEachAncestor(tokenAtPos, getCommentOwnerInfoWorker); @@ -400,7 +400,7 @@ namespace ts.JsDoc { * @param rightHandSide the expression which may contain an appropriate set of parameters * @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'. */ - function getParametersFromRightHandSideOfAssignment(rightHandSide: Expression): ReadonlyArray { + function getParametersFromRightHandSideOfAssignment(rightHandSide: Expression): readonly ParameterDeclaration[] { while (rightHandSide.kind === SyntaxKind.ParenthesizedExpression) { rightHandSide = (rightHandSide).expression; } diff --git a/src/services/navigateTo.ts b/src/services/navigateTo.ts index 2c3910be80c..bcd0fbe2736 100644 --- a/src/services/navigateTo.ts +++ b/src/services/navigateTo.ts @@ -8,7 +8,7 @@ namespace ts.NavigateTo { readonly declaration: Declaration; } - export function getNavigateToItems(sourceFiles: ReadonlyArray, checker: TypeChecker, cancellationToken: CancellationToken, searchValue: string, maxResultCount: number | undefined, excludeDtsFiles: boolean): NavigateToItem[] { + export function getNavigateToItems(sourceFiles: readonly SourceFile[], checker: TypeChecker, cancellationToken: CancellationToken, searchValue: string, maxResultCount: number | undefined, excludeDtsFiles: boolean): NavigateToItem[] { const patternMatcher = createPatternMatcher(searchValue); if (!patternMatcher) return emptyArray; const rawItems: RawNavigateToItem[] = []; @@ -30,7 +30,7 @@ namespace ts.NavigateTo { return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); } - function getItemsFromNamedDeclaration(patternMatcher: PatternMatcher, name: string, declarations: ReadonlyArray, checker: TypeChecker, fileName: string, rawItems: Push): void { + function getItemsFromNamedDeclaration(patternMatcher: PatternMatcher, name: string, declarations: readonly Declaration[], checker: TypeChecker, fileName: string, rawItems: Push): void { // First do a quick check to see if the name of the declaration matches the // last portion of the (possibly) dotted name they're searching for. const match = patternMatcher.getMatchForLastSegmentOfPattern(name); @@ -84,7 +84,7 @@ namespace ts.NavigateTo { return isPropertyNameLiteral(node) && (containers.push(getTextOfIdentifierOrLiteral(node)), true); } - function getContainers(declaration: Declaration): ReadonlyArray { + function getContainers(declaration: Declaration): readonly string[] { const containers: string[] = []; // First, if we started with a computed property name, then add all but the last diff --git a/src/services/organizeImports.ts b/src/services/organizeImports.ts index 81c9108749f..bf4545dbbd0 100644 --- a/src/services/organizeImports.ts +++ b/src/services/organizeImports.ts @@ -17,7 +17,7 @@ namespace ts.OrganizeImports { const changeTracker = textChanges.ChangeTracker.fromContext({ host, formatContext }); - const coalesceAndOrganizeImports = (importGroup: ReadonlyArray) => coalesceImports(removeUnusedImports(importGroup, sourceFile, program)); + const coalesceAndOrganizeImports = (importGroup: readonly ImportDeclaration[]) => coalesceImports(removeUnusedImports(importGroup, sourceFile, program)); // All of the old ImportDeclarations in the file, in syntactic order. const topLevelImportDecls = sourceFile.statements.filter(isImportDeclaration); @@ -40,8 +40,8 @@ namespace ts.OrganizeImports { return changeTracker.getChanges(); function organizeImportsWorker( - oldImportDecls: ReadonlyArray, - coalesce: (group: ReadonlyArray) => ReadonlyArray) { + oldImportDecls: readonly T[], + coalesce: (group: readonly T[]) => readonly T[]) { if (length(oldImportDecls) === 0) { return; @@ -81,7 +81,7 @@ namespace ts.OrganizeImports { } } - function removeUnusedImports(oldImports: ReadonlyArray, sourceFile: SourceFile, program: Program) { + function removeUnusedImports(oldImports: readonly ImportDeclaration[], sourceFile: SourceFile, program: Program) { const typeChecker = program.getTypeChecker(); const jsxNamespace = typeChecker.getJsxNamespace(sourceFile); const jsxElementsPresent = !!(sourceFile.transformFlags & TransformFlags.ContainsJsx); @@ -169,7 +169,7 @@ namespace ts.OrganizeImports { /** * @param importGroup a list of ImportDeclarations, all with the same module name. */ - export function coalesceImports(importGroup: ReadonlyArray) { + export function coalesceImports(importGroup: readonly ImportDeclaration[]) { if (importGroup.length === 0) { return importGroup; } @@ -246,7 +246,7 @@ namespace ts.OrganizeImports { * * NB: There may be overlap between `defaultImports` and `namespaceImports`/`namedImports`. */ - function getCategorizedImports(importGroup: ReadonlyArray) { + function getCategorizedImports(importGroup: readonly ImportDeclaration[]) { let importWithoutClause: ImportDeclaration | undefined; const defaultImports: ImportDeclaration[] = []; const namespaceImports: ImportDeclaration[] = []; @@ -289,7 +289,7 @@ namespace ts.OrganizeImports { /** * @param exportGroup a list of ExportDeclarations, all with the same module name. */ - export function coalesceExports(exportGroup: ReadonlyArray) { + export function coalesceExports(exportGroup: readonly ExportDeclaration[]) { if (exportGroup.length === 0) { return exportGroup; } @@ -327,7 +327,7 @@ namespace ts.OrganizeImports { * may lack parent pointers. The desired parts can easily be recovered based on the * categorization. */ - function getCategorizedExports(exportGroup: ReadonlyArray) { + function getCategorizedExports(exportGroup: readonly ExportDeclaration[]) { let exportWithoutClause: ExportDeclaration | undefined; const namedExports: ExportDeclaration[] = []; @@ -362,7 +362,7 @@ namespace ts.OrganizeImports { importDeclaration.moduleSpecifier); } - function sortSpecifiers(specifiers: ReadonlyArray) { + function sortSpecifiers(specifiers: readonly T[]) { return stableSort(specifiers, (s1, s2) => compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) || compareIdentifiers(s1.name, s2.name)); diff --git a/src/services/patternMatcher.ts b/src/services/patternMatcher.ts index 46b7ff624e4..254a684fc49 100644 --- a/src/services/patternMatcher.ts +++ b/src/services/patternMatcher.ts @@ -38,7 +38,7 @@ namespace ts { // Fully checks a candidate, with an dotted container, against the search pattern. // The candidate must match the last part of the search pattern, and the dotted container // must match the preceding segments of the pattern. - getFullMatch(candidateContainers: ReadonlyArray, candidate: string): PatternMatch | undefined; + getFullMatch(candidateContainers: readonly string[], candidate: string): PatternMatch | undefined; // Whether or not the pattern contained dots or not. Clients can use this to determine // If they should call getMatches, or if getMatchesForLastSegmentOfPattern is sufficient. @@ -115,7 +115,7 @@ namespace ts { }; } - function getFullMatch(candidateContainers: ReadonlyArray, candidate: string, dotSeparatedSegments: ReadonlyArray, stringToWordSpans: Map): PatternMatch | undefined { + function getFullMatch(candidateContainers: readonly string[], candidate: string, dotSeparatedSegments: readonly Segment[], stringToWordSpans: Map): PatternMatch | undefined { // First, check that the last part of the dot separated pattern matches the name of the // candidate. If not, then there's no point in proceeding and doing the more // expensive work. diff --git a/src/services/refactorProvider.ts b/src/services/refactorProvider.ts index e1ac6a58f8d..7c6529dd404 100644 --- a/src/services/refactorProvider.ts +++ b/src/services/refactorProvider.ts @@ -5,7 +5,7 @@ namespace ts { getEditsForAction(context: RefactorContext, actionName: string): RefactorEditInfo | undefined; /** Compute (quickly) which actions are available here */ - getAvailableActions(context: RefactorContext): ReadonlyArray; + getAvailableActions(context: RefactorContext): readonly ApplicableRefactorInfo[]; } export interface RefactorContext extends textChanges.TextChangesContext { diff --git a/src/services/refactors/addOrRemoveBracesToArrowFunction.ts b/src/services/refactors/addOrRemoveBracesToArrowFunction.ts index 97d6f4d6667..89a03c3c239 100644 --- a/src/services/refactors/addOrRemoveBracesToArrowFunction.ts +++ b/src/services/refactors/addOrRemoveBracesToArrowFunction.ts @@ -15,7 +15,7 @@ namespace ts.refactor.addOrRemoveBracesToArrowFunction { addBraces: boolean; } - function getAvailableActions(context: RefactorContext): ReadonlyArray { + function getAvailableActions(context: RefactorContext): readonly ApplicableRefactorInfo[] { const { file, startPosition } = context; const info = getConvertibleArrowFunctionAtPosition(file, startPosition); if (!info) return emptyArray; diff --git a/src/services/refactors/convertExport.ts b/src/services/refactors/convertExport.ts index 64c7e7567b8..7fbe136ada0 100644 --- a/src/services/refactors/convertExport.ts +++ b/src/services/refactors/convertExport.ts @@ -4,7 +4,7 @@ namespace ts.refactor { const actionNameDefaultToNamed = "Convert default export to named export"; const actionNameNamedToDefault = "Convert named export to default export"; registerRefactor(refactorName, { - getAvailableActions(context): ReadonlyArray { + getAvailableActions(context): readonly ApplicableRefactorInfo[] { const info = getInfo(context); if (!info) return emptyArray; const description = info.wasDefault ? Diagnostics.Convert_default_export_to_named_export.message : Diagnostics.Convert_named_export_to_default_export.message; diff --git a/src/services/refactors/convertImport.ts b/src/services/refactors/convertImport.ts index 862717e728a..45eeca579df 100644 --- a/src/services/refactors/convertImport.ts +++ b/src/services/refactors/convertImport.ts @@ -4,7 +4,7 @@ namespace ts.refactor { const actionNameNamespaceToNamed = "Convert namespace import to named imports"; const actionNameNamedToNamespace = "Convert named imports to namespace import"; registerRefactor(refactorName, { - getAvailableActions(context): ReadonlyArray { + getAvailableActions(context): readonly ApplicableRefactorInfo[] { const i = getImportToConvert(context); if (!i) return emptyArray; const description = i.kind === SyntaxKind.NamespaceImport ? Diagnostics.Convert_namespace_import_to_named_imports.message : Diagnostics.Convert_named_imports_to_namespace_import.message; @@ -123,7 +123,7 @@ namespace ts.refactor { } } - function updateImport(old: ImportDeclaration, defaultImportName: Identifier | undefined, elements: ReadonlyArray | undefined): ImportDeclaration { + function updateImport(old: ImportDeclaration, defaultImportName: Identifier | undefined, elements: readonly ImportSpecifier[] | undefined): ImportDeclaration { return createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createImportClause(defaultImportName, elements && elements.length ? createNamedImports(elements) : undefined), old.moduleSpecifier); } diff --git a/src/services/refactors/convertParamsToDestructuredObject.ts b/src/services/refactors/convertParamsToDestructuredObject.ts index f93f19b495a..275f14a4a57 100644 --- a/src/services/refactors/convertParamsToDestructuredObject.ts +++ b/src/services/refactors/convertParamsToDestructuredObject.ts @@ -5,7 +5,7 @@ namespace ts.refactor.convertParamsToDestructuredObject { registerRefactor(refactorName, { getEditsForAction, getAvailableActions }); - function getAvailableActions(context: RefactorContext): ReadonlyArray { + function getAvailableActions(context: RefactorContext): readonly ApplicableRefactorInfo[] { const { file, startPosition } = context; const isJSFile = isSourceFileJS(file); if (isJSFile) return emptyArray; // TODO: GH#30113 @@ -87,7 +87,7 @@ namespace ts.refactor.convertParamsToDestructuredObject { return groupedReferences; - function groupReferences(referenceEntries: ReadonlyArray): GroupedReferences { + function groupReferences(referenceEntries: readonly FindAllReferences.Entry[]): GroupedReferences { const classReferences: ClassReferences = { accessExpressions: [], typeUsages: [] }; const groupedReferences: GroupedReferences = { functionCalls: [], declarations: [], classReferences, valid: true }; const functionSymbols = map(functionNames, getSymbolTargetAtLocation); diff --git a/src/services/refactors/extractSymbol.ts b/src/services/refactors/extractSymbol.ts index 94ad67afe10..12170d8779b 100644 --- a/src/services/refactors/extractSymbol.ts +++ b/src/services/refactors/extractSymbol.ts @@ -7,7 +7,7 @@ namespace ts.refactor.extractSymbol { * Compute the associated code actions * Exported for tests. */ - export function getAvailableActions(context: RefactorContext): ReadonlyArray { + export function getAvailableActions(context: RefactorContext): readonly ApplicableRefactorInfo[] { const rangeToExtract = getRangeToExtract(context.file, getRefactorContextSpan(context)); const targetRange = rangeToExtract.targetRange; @@ -167,7 +167,7 @@ namespace ts.refactor.extractSymbol { */ type RangeToExtract = { readonly targetRange?: never; - readonly errors: ReadonlyArray; + readonly errors: readonly Diagnostic[]; } | { readonly targetRange: TargetRange; readonly errors?: never; @@ -576,7 +576,7 @@ namespace ts.refactor.extractSymbol { interface Extraction { readonly description: string; - readonly errors: ReadonlyArray; + readonly errors: readonly Diagnostic[]; } interface ScopeExtractions { @@ -589,7 +589,7 @@ namespace ts.refactor.extractSymbol { * Each returned ExtractResultForScope corresponds to a possible target scope and is either a set of changes * or an error explaining why we can't extract into that scope. */ - function getPossibleExtractions(targetRange: TargetRange, context: RefactorContext): ReadonlyArray | undefined { + function getPossibleExtractions(targetRange: TargetRange, context: RefactorContext): readonly ScopeExtractions[] | undefined { const { scopes, readsAndWrites: { functionErrorsPerScope, constantErrorsPerScope } } = getPossibleExtractionsWorker(targetRange, context); // Need the inner type annotation to avoid https://github.com/Microsoft/TypeScript/issues/7547 const extractions = scopes.map((scope, i): ScopeExtractions => { @@ -708,7 +708,7 @@ namespace ts.refactor.extractSymbol { node: Statement | Expression | Block, scope: Scope, { usages: usagesInScope, typeParameterUsages, substitutions }: ScopeUsages, - exposedVariableDeclarations: ReadonlyArray, + exposedVariableDeclarations: readonly VariableDeclaration[], range: TargetRange, context: RefactorContext): RefactorEditInfo { @@ -752,13 +752,13 @@ namespace ts.refactor.extractSymbol { const typeParametersAndDeclarations = arrayFrom(typeParameterUsages.values()).map(type => ({ type, declaration: getFirstDeclaration(type) })); const sortedTypeParametersAndDeclarations = typeParametersAndDeclarations.sort(compareTypesByDeclarationOrder); - const typeParameters: ReadonlyArray | undefined = sortedTypeParametersAndDeclarations.length === 0 + const typeParameters: readonly TypeParameterDeclaration[] | undefined = sortedTypeParametersAndDeclarations.length === 0 ? undefined : sortedTypeParametersAndDeclarations.map(t => t.declaration as TypeParameterDeclaration); // Strictly speaking, we should check whether each name actually binds to the appropriate type // parameter. In cases of shadowing, they may not. - const callTypeArguments: ReadonlyArray | undefined = typeParameters !== undefined + const callTypeArguments: readonly TypeNode[] | undefined = typeParameters !== undefined ? typeParameters.map(decl => createTypeReferenceNode(decl.name, /*typeArguments*/ undefined)) : undefined; @@ -1157,7 +1157,7 @@ namespace ts.refactor.extractSymbol { } } - function transformFunctionBody(body: Node, exposedVariableDeclarations: ReadonlyArray, writes: ReadonlyArray | undefined, substitutions: ReadonlyMap, hasReturn: boolean): { body: Block, returnValueProperty: string | undefined } { + function transformFunctionBody(body: Node, exposedVariableDeclarations: readonly VariableDeclaration[], writes: readonly UsageEntry[] | undefined, substitutions: ReadonlyMap, hasReturn: boolean): { body: Block, returnValueProperty: string | undefined } { const hasWritesOrVariableDeclarations = writes !== undefined || exposedVariableDeclarations.length > 0; if (isBlock(body) && !hasWritesOrVariableDeclarations && substitutions.size === 0) { // already block, no declarations or writes to propagate back, no substitutions - can use node as is @@ -1224,7 +1224,7 @@ namespace ts.refactor.extractSymbol { } } - function getStatementsOrClassElements(scope: Scope): ReadonlyArray | ReadonlyArray { + function getStatementsOrClassElements(scope: Scope): readonly Statement[] | readonly ClassElement[] { if (isFunctionLikeDeclaration(scope)) { const body = scope.body!; // TODO: GH#18217 if (isBlock(body)) { @@ -1314,8 +1314,8 @@ namespace ts.refactor.extractSymbol { } function getPropertyAssignmentsForWritesAndVariableDeclarations( - exposedVariableDeclarations: ReadonlyArray, - writes: ReadonlyArray | undefined + exposedVariableDeclarations: readonly VariableDeclaration[], + writes: readonly UsageEntry[] | undefined ): ShorthandPropertyAssignment[] { const variableAssignments = map(exposedVariableDeclarations, v => createShorthandPropertyAssignment(v.symbol.name)); const writeAssignments = map(writes, w => createShorthandPropertyAssignment(w.symbol.name)); @@ -1328,7 +1328,7 @@ namespace ts.refactor.extractSymbol { : variableAssignments.concat(writeAssignments); } - function isReadonlyArray(v: any): v is ReadonlyArray { + function isReadonlyArray(v: any): v is readonly any[] { return isArray(v); } @@ -1368,10 +1368,10 @@ namespace ts.refactor.extractSymbol { interface ReadsAndWrites { readonly target: Expression | Block; - readonly usagesPerScope: ReadonlyArray; - readonly functionErrorsPerScope: ReadonlyArray>; - readonly constantErrorsPerScope: ReadonlyArray>; - readonly exposedVariableDeclarations: ReadonlyArray; + readonly usagesPerScope: readonly ScopeUsages[]; + readonly functionErrorsPerScope: readonly (readonly Diagnostic[])[]; + readonly constantErrorsPerScope: readonly (readonly Diagnostic[])[]; + readonly exposedVariableDeclarations: readonly VariableDeclaration[]; } function collectReadsAndWrites( targetRange: TargetRange, @@ -1399,7 +1399,7 @@ namespace ts.refactor.extractSymbol { let expressionDiagnostic: Diagnostic | undefined; if (expression === undefined) { - const statements = targetRange.range as ReadonlyArray; + const statements = targetRange.range as readonly Statement[]; const start = first(statements).getStart(); const end = last(statements).end; expressionDiagnostic = createFileDiagnostic(sourceFile, start, end - start, Messages.expressionExpected); diff --git a/src/services/refactors/extractType.ts b/src/services/refactors/extractType.ts index 28a6539389c..5feb78d3e90 100644 --- a/src/services/refactors/extractType.ts +++ b/src/services/refactors/extractType.ts @@ -4,7 +4,7 @@ namespace ts.refactor { const extractToTypeAlias = "Extract to type alias"; const extractToTypeDef = "Extract to typedef"; registerRefactor(refactorName, { - getAvailableActions(context): ReadonlyArray { + getAvailableActions(context): readonly ApplicableRefactorInfo[] { const info = getRangeToExtract(context); if (!info) return emptyArray; @@ -35,7 +35,7 @@ namespace ts.refactor { } }); - interface Info { isJS: boolean; selection: TypeNode; firstStatement: Statement; typeParameters: ReadonlyArray; } + interface Info { isJS: boolean; selection: TypeNode; firstStatement: Statement; typeParameters: readonly TypeParameterDeclaration[]; } function getRangeToExtract(context: RefactorContext): Info | undefined { const { file, startPosition } = context; @@ -107,7 +107,7 @@ namespace ts.refactor { } } - function doTypeAliasChange(changes: textChanges.ChangeTracker, file: SourceFile, name: string, firstStatement: Statement, selection: TypeNode, typeParameters: ReadonlyArray) { + function doTypeAliasChange(changes: textChanges.ChangeTracker, file: SourceFile, name: string, firstStatement: Statement, selection: TypeNode, typeParameters: readonly TypeParameterDeclaration[]) { const newTypeNode = createTypeAliasDeclaration( /* decorators */ undefined, /* modifiers */ undefined, @@ -119,7 +119,7 @@ namespace ts.refactor { changes.replaceNode(file, selection, createTypeReferenceNode(name, typeParameters.map(id => createTypeReferenceNode(id.name, /* typeArguments */ undefined)))); } - function doTypedefChange(changes: textChanges.ChangeTracker, file: SourceFile, name: string, firstStatement: Statement, selection: TypeNode, typeParameters: ReadonlyArray) { + function doTypedefChange(changes: textChanges.ChangeTracker, file: SourceFile, name: string, firstStatement: Statement, selection: TypeNode, typeParameters: readonly TypeParameterDeclaration[]) { const node = createNode(SyntaxKind.JSDocTypedefTag); node.tagName = createIdentifier("typedef"); // TODO: jsdoc factory https://github.com/Microsoft/TypeScript/pull/29539 node.fullName = createIdentifier(name); diff --git a/src/services/refactors/generateGetAccessorAndSetAccessor.ts b/src/services/refactors/generateGetAccessorAndSetAccessor.ts index 4091599951a..62427bdc688 100644 --- a/src/services/refactors/generateGetAccessorAndSetAccessor.ts +++ b/src/services/refactors/generateGetAccessorAndSetAccessor.ts @@ -20,7 +20,7 @@ namespace ts.refactor.generateGetAccessorAndSetAccessor { readonly renameAccessor: boolean; } - function getAvailableActions(context: RefactorContext): ReadonlyArray { + function getAvailableActions(context: RefactorContext): readonly ApplicableRefactorInfo[] { if (!getConvertibleFieldAtPosition(context)) return emptyArray; return [{ diff --git a/src/services/refactors/moveToNewFile.ts b/src/services/refactors/moveToNewFile.ts index 8da05ee55e1..debd4311aef 100644 --- a/src/services/refactors/moveToNewFile.ts +++ b/src/services/refactors/moveToNewFile.ts @@ -2,7 +2,7 @@ namespace ts.refactor { const refactorName = "Move to a new file"; registerRefactor(refactorName, { - getAvailableActions(context): ReadonlyArray { + getAvailableActions(context): readonly ApplicableRefactorInfo[] { if (!context.preferences.allowTextChangesInNewFiles || getStatementsToMove(context) === undefined) return emptyArray; const description = getLocaleSpecificMessage(Diagnostics.Move_to_a_new_file); return [{ name: refactorName, description, actions: [{ name: refactorName, description }] }]; @@ -15,7 +15,7 @@ namespace ts.refactor { } }); - interface RangeToMove { readonly toMove: ReadonlyArray; readonly afterLast: Statement | undefined; } + interface RangeToMove { readonly toMove: readonly Statement[]; readonly afterLast: Statement | undefined; } function getRangeToMove(context: RefactorContext): RangeToMove | undefined { const { file } = context; const range = createTextRangeFromSpan(getRefactorContextSpan(context)); @@ -61,8 +61,8 @@ namespace ts.refactor { readonly afterLast: Statement | undefined; } interface ToMove { - readonly all: ReadonlyArray; - readonly ranges: ReadonlyArray; + readonly all: readonly Statement[]; + readonly ranges: readonly StatementRange[]; } // Filters imports out of the range of statements to move. Imports will be copied to the new file anyway, and may still be needed in the old file. @@ -109,7 +109,7 @@ namespace ts.refactor { function getNewStatementsAndRemoveFromOldFile( oldFile: SourceFile, usage: UsageInfo, changes: textChanges.ChangeTracker, toMove: ToMove, program: Program, newModuleName: string, preferences: UserPreferences, - ): ReadonlyArray { + ): readonly Statement[] { const checker = program.getTypeChecker(); if (!oldFile.externalModuleIndicator && !oldFile.commonJsModuleIndicator) { @@ -135,13 +135,13 @@ namespace ts.refactor { ]; } - function deleteMovedStatements(sourceFile: SourceFile, moved: ReadonlyArray, changes: textChanges.ChangeTracker) { + function deleteMovedStatements(sourceFile: SourceFile, moved: readonly StatementRange[], changes: textChanges.ChangeTracker) { for (const { first, afterLast } of moved) { changes.deleteNodeRangeExcludingEnd(sourceFile, first, afterLast); } } - function deleteUnusedOldImports(oldFile: SourceFile, toMove: ReadonlyArray, changes: textChanges.ChangeTracker, toDelete: ReadonlySymbolSet, checker: TypeChecker) { + function deleteUnusedOldImports(oldFile: SourceFile, toMove: readonly Statement[], changes: textChanges.ChangeTracker, toDelete: ReadonlySymbolSet, checker: TypeChecker) { for (const statement of oldFile.statements) { if (contains(toMove, statement)) continue; forEachImportInStatement(statement, i => deleteUnusedImports(oldFile, i, changes, name => toDelete.has(checker.getSymbolAtLocation(name)!))); @@ -283,7 +283,7 @@ namespace ts.refactor { return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports, quotePreference); } - function makeImportOrRequire(defaultImport: Identifier | undefined, imports: ReadonlyArray, path: string, useEs6Imports: boolean, quotePreference: QuotePreference): Statement | undefined { + function makeImportOrRequire(defaultImport: Identifier | undefined, imports: readonly string[], path: string, useEs6Imports: boolean, quotePreference: QuotePreference): Statement | undefined { path = ensurePathIsNonModuleName(path); if (useEs6Imports) { const specifiers = imports.map(i => createImportSpecifier(/*propertyName*/ undefined, createIdentifier(i))); @@ -306,7 +306,7 @@ namespace ts.refactor { return createCall(createIdentifier("require"), /*typeArguments*/ undefined, [moduleSpecifier]); } - function addExports(sourceFile: SourceFile, toMove: ReadonlyArray, needExport: ReadonlySymbolSet, useEs6Exports: boolean): ReadonlyArray { + function addExports(sourceFile: SourceFile, toMove: readonly Statement[], needExport: ReadonlySymbolSet, useEs6Exports: boolean): readonly Statement[] { return flatMap(toMove, statement => { if (isTopLevelDeclarationStatement(statement) && !isExported(sourceFile, statement, useEs6Exports) && @@ -398,7 +398,7 @@ namespace ts.refactor { checker: TypeChecker, useEs6ModuleSyntax: boolean, quotePreference: QuotePreference, - ): ReadonlyArray { + ): readonly SupportedImportStatement[] { const copiedOldImports: SupportedImportStatement[] = []; for (const oldStatement of oldFile.statements) { forEachImportInStatement(oldStatement, i => { @@ -459,7 +459,7 @@ namespace ts.refactor { // Subset of oldImportsNeededByNewFile that are will no longer be used in the old file. readonly unusedImportsFromOldFile: ReadonlySymbolSet; } - function getUsageInfo(oldFile: SourceFile, toMove: ReadonlyArray, checker: TypeChecker): UsageInfo { + function getUsageInfo(oldFile: SourceFile, toMove: readonly Statement[], checker: TypeChecker): UsageInfo { const movedSymbols = new SymbolSet(); const oldImportsNeededByNewFile = new SymbolSet(); const newFileImportsFromOldFile = new SymbolSet(); @@ -743,7 +743,7 @@ namespace ts.refactor { } } - function addExport(decl: TopLevelDeclarationStatement, useEs6Exports: boolean): ReadonlyArray | undefined { + function addExport(decl: TopLevelDeclarationStatement, useEs6Exports: boolean): readonly Statement[] | undefined { return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl); } function addEs6Export(d: TopLevelDeclarationStatement): TopLevelDeclarationStatement { @@ -771,10 +771,10 @@ namespace ts.refactor { return Debug.assertNever(d); } } - function addCommonjsExport(decl: TopLevelDeclarationStatement): ReadonlyArray | undefined { + function addCommonjsExport(decl: TopLevelDeclarationStatement): readonly Statement[] | undefined { return [decl, ...getNamesToExportInCommonJS(decl).map(createExportAssignment)]; } - function getNamesToExportInCommonJS(decl: TopLevelDeclarationStatement): ReadonlyArray { + function getNamesToExportInCommonJS(decl: TopLevelDeclarationStatement): readonly string[] { switch (decl.kind) { case SyntaxKind.FunctionDeclaration: case SyntaxKind.ClassDeclaration: diff --git a/src/services/services.ts b/src/services/services.ts index 1abd8d2b5b3..371b4e3f52c 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -396,10 +396,10 @@ namespace ts { getApparentProperties(): Symbol[] { return this.checker.getAugmentedPropertiesOfType(this); } - getCallSignatures(): ReadonlyArray { + getCallSignatures(): readonly Signature[] { return this.checker.getSignaturesOfType(this, SignatureKind.Call); } - getConstructSignatures(): ReadonlyArray { + getConstructSignatures(): readonly Signature[] { return this.checker.getSignaturesOfType(this, SignatureKind.Construct); } getStringIndexType(): Type | undefined { @@ -509,7 +509,7 @@ namespace ts { return getJSDocTags(node).some(tag => tag.tagName.text === "inheritDoc"); } - function getDocumentationComment(declarations: ReadonlyArray | undefined, checker: TypeChecker | undefined): SymbolDisplayPart[] { + function getDocumentationComment(declarations: readonly Declaration[] | undefined, checker: TypeChecker | undefined): SymbolDisplayPart[] { if (!declarations) return emptyArray; let doc = JsDoc.getJsDocCommentsFromDeclarations(declarations); @@ -531,7 +531,7 @@ namespace ts { * @param typeChecker A TypeChecker, used to find inherited properties. * @returns A filled array of documentation comments if any were found, otherwise an empty array. */ - function findInheritedJSDocComments(declaration: Declaration, propertyName: string, typeChecker: TypeChecker): ReadonlyArray | undefined { + function findInheritedJSDocComments(declaration: Declaration, propertyName: string, typeChecker: TypeChecker): readonly SymbolDisplayPart[] | undefined { return firstDefined(declaration.parent ? getAllSuperTypeNodes(declaration.parent) : emptyArray, superTypeNode => { const superType = typeChecker.getTypeAtLocation(superTypeNode); const baseProperty = superType && typeChecker.getPropertyOfType(superType, propertyName); @@ -549,7 +549,7 @@ namespace ts { public originalFileName!: string; public text!: string; public scriptSnapshot!: IScriptSnapshot; - public lineMap!: ReadonlyArray; + public lineMap!: readonly number[]; public statements!: NodeArray; public endOfFileToken!: Token; @@ -581,7 +581,7 @@ namespace ts { public nameTable: UnderscoreEscapedMap | undefined; public resolvedModules: Map | undefined; public resolvedTypeReferenceDirectiveNames!: Map; - public imports!: ReadonlyArray; + public imports!: readonly StringLiteralLike[]; public moduleAugmentations!: StringLiteral[]; private namedDeclarations: Map | undefined; public ambientModuleNames!: string[]; @@ -603,7 +603,7 @@ namespace ts { return getLineAndCharacterOfPosition(this, position); } - public getLineStarts(): ReadonlyArray { + public getLineStarts(): readonly number[] { return getLineStarts(this); } @@ -895,7 +895,7 @@ namespace ts { return this._compilationSettings; } - public getProjectReferences(): ReadonlyArray | undefined { + public getProjectReferences(): readonly ProjectReference[] | undefined { return this.host.getProjectReferences && this.host.getProjectReferences(); } @@ -1519,7 +1519,7 @@ namespace ts { } /// Goto definition - function getDefinitionAtPosition(fileName: string, position: number): ReadonlyArray | undefined { + function getDefinitionAtPosition(fileName: string, position: number): readonly DefinitionInfo[] | undefined { synchronizeHostData(); return GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position); } @@ -1529,7 +1529,7 @@ namespace ts { return GoToDefinition.getDefinitionAndBoundSpan(program, getValidSourceFile(fileName), position); } - function getTypeDefinitionAtPosition(fileName: string, position: number): ReadonlyArray | undefined { + function getTypeDefinitionAtPosition(fileName: string, position: number): readonly DefinitionInfo[] | undefined { synchronizeHostData(); return GoToDefinition.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position); } @@ -1542,7 +1542,7 @@ namespace ts { } /// References and Occurrences - function getOccurrencesAtPosition(fileName: string, position: number): ReadonlyArray | undefined { + function getOccurrencesAtPosition(fileName: string, position: number): readonly ReferenceEntry[] | undefined { return flatMap( getDocumentHighlights(fileName, position, [fileName]), entry => entry.highlightSpans.map(highlightSpan => ({ @@ -1556,7 +1556,7 @@ namespace ts { ); } - function getDocumentHighlights(fileName: string, position: number, filesToSearch: ReadonlyArray): DocumentHighlights[] | undefined { + function getDocumentHighlights(fileName: string, position: number, filesToSearch: readonly string[]): DocumentHighlights[] | undefined { const normalizedFileName = normalizePath(fileName); Debug.assert(filesToSearch.some(f => normalizePath(f) === normalizedFileName)); synchronizeHostData(); @@ -1809,7 +1809,7 @@ namespace ts { return []; } - function getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings, preferences: UserPreferences = emptyOptions): ReadonlyArray { + function getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: readonly number[], formatOptions: FormatCodeSettings, preferences: UserPreferences = emptyOptions): readonly CodeFixAction[] { synchronizeHostData(); const sourceFile = getValidSourceFile(fileName); const span = createTextSpanFromBounds(start, end); @@ -1830,7 +1830,7 @@ namespace ts { return codefix.getAllFixes({ fixId, sourceFile, program, host, cancellationToken, formatContext, preferences }); } - function organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences = emptyOptions): ReadonlyArray { + function organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences = emptyOptions): readonly FileTextChanges[] { synchronizeHostData(); Debug.assert(scope.type === "file"); const sourceFile = getValidSourceFile(scope.fileName); @@ -1839,7 +1839,7 @@ namespace ts { return OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences); } - function getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences = emptyOptions): ReadonlyArray { + function getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences = emptyOptions): readonly FileTextChanges[] { return ts.getEditsForFileRename(getProgram()!, oldFilePath, newFilePath, host, formatting.getFormatContext(formatOptions), preferences, sourceMapper); } @@ -2252,7 +2252,7 @@ namespace ts { /** Gets all symbols for one property. Does not get symbols for every property. */ /* @internal */ - export function getPropertySymbolsFromContextualType(node: ObjectLiteralElementWithName, checker: TypeChecker, contextualType: Type, unionSymbolOk: boolean): ReadonlyArray { + export function getPropertySymbolsFromContextualType(node: ObjectLiteralElementWithName, checker: TypeChecker, contextualType: Type, unionSymbolOk: boolean): readonly Symbol[] { const name = getNameFromPropertyName(node.name); if (!name) return emptyArray; if (!contextualType.isUnion()) { diff --git a/src/services/shims.ts b/src/services/shims.ts index a4f1131812b..d500e93791b 100644 --- a/src/services/shims.ts +++ b/src/services/shims.ts @@ -28,7 +28,7 @@ namespace ts { packageNameToTypingLocation: Map; // The map of package names to their cached typing locations and installed versions typeAcquisition: TypeAcquisition; // Used to customize the type acquisition process compilerOptions: CompilerOptions; // Used as a source for typing inference - unresolvedImports: ReadonlyArray; // List of unresolved module ids from imports + unresolvedImports: readonly string[]; // List of unresolved module ids from imports typesRegistry: ReadonlyMap>; // The map of available typings in npm to maps of TS versions to their latest supported versions } @@ -465,7 +465,7 @@ namespace ts { return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); } - public readDirectory(path: string, extensions?: ReadonlyArray, exclude?: string[], include?: string[], depth?: number): string[] { + public readDirectory(path: string, extensions?: readonly string[], exclude?: string[], include?: string[], depth?: number): string[] { const pattern = getFileMatcherPatterns(path, exclude, include, this.shimHost.useCaseSensitiveFileNames!(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217 return JSON.parse(this.shimHost.readDirectory( @@ -510,7 +510,7 @@ namespace ts { } } - public readDirectory(rootDir: string, extensions: ReadonlyArray, exclude: ReadonlyArray, include: ReadonlyArray, depth?: number): string[] { + public readDirectory(rootDir: string, extensions: readonly string[], exclude: readonly string[], include: readonly string[], depth?: number): string[] { const pattern = getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames!(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217 return JSON.parse(this.shimHost.readDirectory( @@ -598,7 +598,7 @@ namespace ts { code: number; reportsUnnecessary?: {}; } - export function realizeDiagnostics(diagnostics: ReadonlyArray, newLine: string): RealizedDiagnostic[] { + export function realizeDiagnostics(diagnostics: readonly Diagnostic[], newLine: string): RealizedDiagnostic[] { return diagnostics.map(d => realizeDiagnostic(d, newLine)); } @@ -671,7 +671,7 @@ namespace ts { }); } - private realizeDiagnostics(diagnostics: ReadonlyArray): { message: string; start: number; length: number; category: string; }[] { + private realizeDiagnostics(diagnostics: readonly Diagnostic[]): { message: string; start: number; length: number; category: string; }[] { const newLine = getNewLineOrDefaultFromHost(this.host); return realizeDiagnostics(diagnostics, newLine); } diff --git a/src/services/signatureHelp.ts b/src/services/signatureHelp.ts index 8226e3c38bf..799fff86ecf 100644 --- a/src/services/signatureHelp.ts +++ b/src/services/signatureHelp.ts @@ -63,7 +63,7 @@ namespace ts.SignatureHelp { const enum CandidateOrTypeKind { Candidate, Type } interface CandidateInfo { readonly kind: CandidateOrTypeKind.Candidate; - readonly candidates: ReadonlyArray; + readonly candidates: readonly Signature[]; readonly resolvedSignature: Signature; } interface TypeInfo { @@ -491,7 +491,7 @@ namespace ts.SignatureHelp { const signatureHelpNodeBuilderFlags = NodeBuilderFlags.OmitParameterModifiers | NodeBuilderFlags.IgnoreErrors | NodeBuilderFlags.UseAliasDefinedOutsideCurrentScope; function createSignatureHelpItems( - candidates: ReadonlyArray, + candidates: readonly Signature[], resolvedSignature: Signature, { isTypeParameterList, argumentCount, argumentsSpan: applicableSpan, invocation, argumentIndex }: ArgumentListInfo, sourceFile: SourceFile, @@ -524,7 +524,7 @@ namespace ts.SignatureHelp { return { items, applicableSpan, selectedItemIndex: 0, argumentIndex, argumentCount }; } - function getTypeHelpItem(symbol: Symbol, typeParameters: ReadonlyArray, checker: TypeChecker, enclosingDeclaration: Node, sourceFile: SourceFile): SignatureHelpItem { + function getTypeHelpItem(symbol: Symbol, typeParameters: readonly TypeParameter[], checker: TypeChecker, enclosingDeclaration: Node, sourceFile: SourceFile): SignatureHelpItem { const typeSymbolDisplay = symbolToDisplayParts(checker, symbol); const printer = createPrinter({ removeComments: true }); @@ -538,7 +538,7 @@ namespace ts.SignatureHelp { const separatorDisplayParts: SymbolDisplayPart[] = [punctuationPart(SyntaxKind.CommaToken), spacePart()]; - function getSignatureHelpItem(candidateSignature: Signature, callTargetDisplayParts: ReadonlyArray, isTypeParameterList: boolean, checker: TypeChecker, enclosingDeclaration: Node, sourceFile: SourceFile): SignatureHelpItem { + function getSignatureHelpItem(candidateSignature: Signature, callTargetDisplayParts: readonly SymbolDisplayPart[], isTypeParameterList: boolean, checker: TypeChecker, enclosingDeclaration: Node, sourceFile: SourceFile): SignatureHelpItem { const { isVariadic, parameters, prefix, suffix } = (isTypeParameterList ? itemInfoForTypeParameters : itemInfoForParameters)(candidateSignature, checker, enclosingDeclaration, sourceFile); const prefixDisplayParts = [...callTargetDisplayParts, ...prefix]; const suffixDisplayParts = [...suffix, ...returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker)]; @@ -547,7 +547,7 @@ namespace ts.SignatureHelp { return { isVariadic, prefixDisplayParts, suffixDisplayParts, separatorDisplayParts, parameters, documentation, tags }; } - function returnTypeToDisplayParts(candidateSignature: Signature, enclosingDeclaration: Node, checker: TypeChecker): ReadonlyArray { + function returnTypeToDisplayParts(candidateSignature: Signature, enclosingDeclaration: Node, checker: TypeChecker): readonly SymbolDisplayPart[] { return mapToDisplayParts(writer => { writer.writePunctuation(":"); writer.writeSpace(" "); @@ -561,7 +561,7 @@ namespace ts.SignatureHelp { }); } - interface SignatureHelpItemInfo { readonly isVariadic: boolean; readonly parameters: SignatureHelpParameter[]; readonly prefix: ReadonlyArray; readonly suffix: ReadonlyArray; } + interface SignatureHelpItemInfo { readonly isVariadic: boolean; readonly parameters: SignatureHelpParameter[]; readonly prefix: readonly SymbolDisplayPart[]; readonly suffix: readonly SymbolDisplayPart[]; } function itemInfoForTypeParameters(candidateSignature: Signature, checker: TypeChecker, enclosingDeclaration: Node, sourceFile: SourceFile): SignatureHelpItemInfo { const typeParameters = (candidateSignature.target || candidateSignature).typeParameters; diff --git a/src/services/smartSelection.ts b/src/services/smartSelection.ts index 0a2adcd9507..2aaf0cf0795 100644 --- a/src/services/smartSelection.ts +++ b/src/services/smartSelection.ts @@ -126,7 +126,7 @@ namespace ts.SmartSelectionRange { * selected all together, even though in the AST they’re just siblings of each * other as well as of other top-level statements and declarations. */ - function getSelectionChildren(node: Node): ReadonlyArray { + function getSelectionChildren(node: Node): readonly Node[] { // Group top-level imports if (isSourceFile(node)) { return groupChildren(node.getChildAt(0).getChildren(), isImport); diff --git a/src/services/stringCompletions.ts b/src/services/stringCompletions.ts index e8163131977..0103e7fb853 100644 --- a/src/services/stringCompletions.ts +++ b/src/services/stringCompletions.ts @@ -66,7 +66,7 @@ namespace ts.Completions.StringCompletions { } } - function convertPathCompletions(pathCompletions: ReadonlyArray): CompletionInfo { + function convertPathCompletions(pathCompletions: readonly PathCompletion[]): CompletionInfo { const isGlobalCompletion = false; // We don't want the editor to offer any other completions, such as snippets, inside a comment. const isNewIdentifierLocation = true; // The user may type in a path that doesn't yet exist, creating a "new identifier" with respect to the collection of identifiers the server is aware of. const entries = pathCompletions.map(({ name, kind, span, extension }): CompletionEntry => @@ -91,15 +91,15 @@ namespace ts.Completions.StringCompletions { const enum StringLiteralCompletionKind { Paths, Properties, Types } interface StringLiteralCompletionsFromProperties { readonly kind: StringLiteralCompletionKind.Properties; - readonly symbols: ReadonlyArray; + readonly symbols: readonly Symbol[]; readonly hasIndexSignature: boolean; } interface StringLiteralCompletionsFromTypes { readonly kind: StringLiteralCompletionKind.Types; - readonly types: ReadonlyArray; + readonly types: readonly StringLiteralType[]; readonly isNewIdentifier: boolean; } - type StringLiteralCompletion = { readonly kind: StringLiteralCompletionKind.Paths, readonly paths: ReadonlyArray } | StringLiteralCompletionsFromProperties | StringLiteralCompletionsFromTypes; + type StringLiteralCompletion = { readonly kind: StringLiteralCompletionKind.Paths, readonly paths: readonly PathCompletion[] } | StringLiteralCompletionsFromProperties | StringLiteralCompletionsFromTypes; function getStringLiteralCompletionEntries(sourceFile: SourceFile, node: StringLiteralLike, position: number, typeChecker: TypeChecker, compilerOptions: CompilerOptions, host: LanguageServiceHost): StringLiteralCompletion | undefined { const { parent } = node; switch (parent.kind) { @@ -192,7 +192,7 @@ namespace ts.Completions.StringCompletions { } } - function getAlreadyUsedTypesInStringLiteralUnion(union: UnionTypeNode, current: LiteralTypeNode): ReadonlyArray { + function getAlreadyUsedTypesInStringLiteralUnion(union: UnionTypeNode, current: LiteralTypeNode): readonly string[] { return mapDefined(union.types, type => type !== current && isLiteralTypeNode(type) && isStringLiteral(type.literal) ? type.literal.text : undefined); } @@ -217,7 +217,7 @@ namespace ts.Completions.StringCompletions { return type && { kind: StringLiteralCompletionKind.Properties, symbols: type.getApparentProperties(), hasIndexSignature: hasIndexSignature(type) }; } - function getStringLiteralTypes(type: Type | undefined, uniques = createMap()): ReadonlyArray { + function getStringLiteralTypes(type: Type | undefined, uniques = createMap()): readonly StringLiteralType[] { if (!type) return emptyArray; type = skipConstraint(type); return type.isUnion() ? flatMap(type.types, t => getStringLiteralTypes(t, uniques)) : @@ -240,16 +240,16 @@ namespace ts.Completions.StringCompletions { return nameAndKind(name, ScriptElementKind.directory, /*extension*/ undefined); } - function addReplacementSpans(text: string, textStart: number, names: ReadonlyArray): ReadonlyArray { + function addReplacementSpans(text: string, textStart: number, names: readonly NameAndKind[]): readonly PathCompletion[] { const span = getDirectoryFragmentTextSpan(text, textStart); return names.map(({ name, kind, extension }): PathCompletion => ({ name, kind, extension, span })); } - function getStringLiteralCompletionsFromModuleNames(sourceFile: SourceFile, node: LiteralExpression, compilerOptions: CompilerOptions, host: LanguageServiceHost, typeChecker: TypeChecker): ReadonlyArray { + function getStringLiteralCompletionsFromModuleNames(sourceFile: SourceFile, node: LiteralExpression, compilerOptions: CompilerOptions, host: LanguageServiceHost, typeChecker: TypeChecker): readonly PathCompletion[] { return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker)); } - function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile: SourceFile, node: LiteralExpression, compilerOptions: CompilerOptions, host: LanguageServiceHost, typeChecker: TypeChecker): ReadonlyArray { + function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile: SourceFile, node: LiteralExpression, compilerOptions: CompilerOptions, host: LanguageServiceHost, typeChecker: TypeChecker): readonly NameAndKind[] { const literalValue = normalizeSlashes(node.text); const scriptPath = sourceFile.path; @@ -261,7 +261,7 @@ namespace ts.Completions.StringCompletions { } interface ExtensionOptions { - readonly extensions: ReadonlyArray; + readonly extensions: readonly Extension[]; readonly includeExtensions: boolean; } function getExtensionOptions(compilerOptions: CompilerOptions, includeExtensions = false): ExtensionOptions { @@ -278,7 +278,7 @@ namespace ts.Completions.StringCompletions { } } - function getSupportedExtensionsForModuleResolution(compilerOptions: CompilerOptions): ReadonlyArray { + function getSupportedExtensionsForModuleResolution(compilerOptions: CompilerOptions): readonly Extension[] { const extensions = getSupportedExtensions(compilerOptions); return compilerOptions.resolveJsonModule && getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.NodeJs ? extensions.concat(Extension.Json) : @@ -289,7 +289,7 @@ namespace ts.Completions.StringCompletions { * Takes a script path and returns paths for all potential folders that could be merged with its * containing folder via the "rootDirs" compiler option */ - function getBaseDirectoriesFromRootDirs(rootDirs: string[], basePath: string, scriptDirectory: string, ignoreCase: boolean): ReadonlyArray { + function getBaseDirectoriesFromRootDirs(rootDirs: string[], basePath: string, scriptDirectory: string, ignoreCase: boolean): readonly string[] { // Make all paths absolute/normalized if they are not already rootDirs = rootDirs.map(rootDirectory => normalizePath(isRootedDiskPath(rootDirectory) ? rootDirectory : combinePaths(basePath, rootDirectory))); @@ -304,7 +304,7 @@ namespace ts.Completions.StringCompletions { compareStringsCaseSensitive); } - function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs: string[], fragment: string, scriptDirectory: string, extensionOptions: ExtensionOptions, compilerOptions: CompilerOptions, host: LanguageServiceHost, exclude: string): ReadonlyArray { + function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs: string[], fragment: string, scriptDirectory: string, extensionOptions: ExtensionOptions, compilerOptions: CompilerOptions, host: LanguageServiceHost, exclude: string): readonly NameAndKind[] { const basePath = compilerOptions.project || host.getCurrentDirectory(); const ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); const baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase); @@ -398,7 +398,7 @@ namespace ts.Completions.StringCompletions { return result; } - function addCompletionEntriesFromPaths(result: NameAndKind[], fragment: string, baseDirectory: string, fileExtensions: ReadonlyArray, paths: MapLike, host: LanguageServiceHost) { + function addCompletionEntriesFromPaths(result: NameAndKind[], fragment: string, baseDirectory: string, fileExtensions: readonly string[], paths: MapLike, host: LanguageServiceHost) { for (const path in paths) { if (!hasProperty(paths, path)) continue; const patterns = paths[path]; @@ -420,7 +420,7 @@ namespace ts.Completions.StringCompletions { * Modules from node_modules (i.e. those listed in package.json) * This includes all files that are found in node_modules/moduleName/ with acceptable file extensions */ - function getCompletionEntriesForNonRelativeModules(fragment: string, scriptPath: string, compilerOptions: CompilerOptions, host: LanguageServiceHost, typeChecker: TypeChecker): ReadonlyArray { + function getCompletionEntriesForNonRelativeModules(fragment: string, scriptPath: string, compilerOptions: CompilerOptions, host: LanguageServiceHost, typeChecker: TypeChecker): readonly NameAndKind[] { const { baseUrl, paths } = compilerOptions; const result: NameAndKind[] = []; @@ -472,8 +472,8 @@ namespace ts.Completions.StringCompletions { } function getCompletionsForPathMapping( - path: string, patterns: ReadonlyArray, fragment: string, baseUrl: string, fileExtensions: ReadonlyArray, host: LanguageServiceHost, - ): ReadonlyArray { + path: string, patterns: readonly string[], fragment: string, baseUrl: string, fileExtensions: readonly string[], host: LanguageServiceHost, + ): readonly NameAndKind[] { if (!endsWith(path, "*")) { // For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion. return !stringContains(path, "*") ? justPathMappingName(path) : emptyArray; @@ -484,12 +484,12 @@ namespace ts.Completions.StringCompletions { return remainingFragment === undefined ? justPathMappingName(pathPrefix) : flatMap(patterns, pattern => getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host)); - function justPathMappingName(name: string): ReadonlyArray { + function justPathMappingName(name: string): readonly NameAndKind[] { return startsWith(name, fragment) ? [directoryResult(name)] : emptyArray; } } - function getModulesForPathsPattern(fragment: string, baseUrl: string, pattern: string, fileExtensions: ReadonlyArray, host: LanguageServiceHost): ReadonlyArray | undefined { + function getModulesForPathsPattern(fragment: string, baseUrl: string, pattern: string, fileExtensions: readonly string[], host: LanguageServiceHost): readonly NameAndKind[] | undefined { if (!host.readDirectory) { return undefined; } @@ -546,7 +546,7 @@ namespace ts.Completions.StringCompletions { return path[0] === directorySeparator ? path.slice(1) : path; } - function getAmbientModuleCompletions(fragment: string, fragmentDirectory: string | undefined, checker: TypeChecker): ReadonlyArray { + function getAmbientModuleCompletions(fragment: string, fragmentDirectory: string | undefined, checker: TypeChecker): readonly string[] { // Get modules that the type checker picked up const ambientModules = checker.getAmbientModules().map(sym => stripQuotes(sym.name)); const nonRelativeModuleNames = ambientModules.filter(moduleName => startsWith(moduleName, fragment)); @@ -561,7 +561,7 @@ namespace ts.Completions.StringCompletions { return nonRelativeModuleNames; } - function getTripleSlashReferenceCompletion(sourceFile: SourceFile, position: number, compilerOptions: CompilerOptions, host: LanguageServiceHost): ReadonlyArray | undefined { + function getTripleSlashReferenceCompletion(sourceFile: SourceFile, position: number, compilerOptions: CompilerOptions, host: LanguageServiceHost): readonly PathCompletion[] | undefined { const token = getTokenAtPosition(sourceFile, position); const commentRanges = getLeadingCommentRanges(sourceFile.text, token.pos); const range = commentRanges && find(commentRanges, commentRange => position >= commentRange.pos && position <= commentRange.end); @@ -582,7 +582,7 @@ namespace ts.Completions.StringCompletions { return addReplacementSpans(toComplete, range.pos + prefix.length, names); } - function getCompletionEntriesFromTypings(host: LanguageServiceHost, options: CompilerOptions, scriptPath: string, fragmentDirectory: string | undefined, extensionOptions: ExtensionOptions, result: NameAndKind[] = []): ReadonlyArray { + function getCompletionEntriesFromTypings(host: LanguageServiceHost, options: CompilerOptions, scriptPath: string, fragmentDirectory: string | undefined, extensionOptions: ExtensionOptions, result: NameAndKind[] = []): readonly NameAndKind[] { // Check for typings specified in compiler options const seen = createMap(); @@ -648,7 +648,7 @@ namespace ts.Completions.StringCompletions { return packageJson; } - function enumerateNodeModulesVisibleToScript(host: LanguageServiceHost, scriptPath: string): ReadonlyArray { + function enumerateNodeModulesVisibleToScript(host: LanguageServiceHost, scriptPath: string): readonly string[] { if (!host.readFile || !host.fileExists) return emptyArray; const result: string[] = []; @@ -701,13 +701,13 @@ namespace ts.Completions.StringCompletions { */ const tripleSlashDirectiveFragmentRegex = /^(\/\/\/\s* = ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]; + const nodeModulesDependencyKeys: readonly string[] = ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]; function tryGetDirectories(host: LanguageServiceHost, directoryName: string): string[] { return tryIOAndConsumeErrors(host, host.getDirectories, directoryName) || []; } - function tryReadDirectory(host: LanguageServiceHost, path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray): ReadonlyArray { + function tryReadDirectory(host: LanguageServiceHost, path: string, extensions?: readonly string[], exclude?: readonly string[], include?: readonly string[]): readonly string[] { return tryIOAndConsumeErrors(host, host.readDirectory, path, extensions, exclude, include) || emptyArray; } diff --git a/src/services/symbolDisplay.ts b/src/services/symbolDisplay.ts index 0bdfde9fad0..0dc540dcaca 100644 --- a/src/services/symbolDisplay.ts +++ b/src/services/symbolDisplay.ts @@ -603,7 +603,7 @@ namespace ts.SymbolDisplay { } } - function addSignatureDisplayParts(signature: Signature, allSignatures: ReadonlyArray, flags = TypeFormatFlags.None) { + function addSignatureDisplayParts(signature: Signature, allSignatures: readonly Signature[], flags = TypeFormatFlags.None) { addRange(displayParts, signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | TypeFormatFlags.WriteTypeArgumentsOfSignature)); if (allSignatures.length > 1) { displayParts.push(spacePart()); diff --git a/src/services/textChanges.ts b/src/services/textChanges.ts index f3e5bf9bfb5..188cf5c53e5 100644 --- a/src/services/textChanges.ts +++ b/src/services/textChanges.ts @@ -144,7 +144,7 @@ namespace ts.textChanges { interface ReplaceWithMultipleNodes extends BaseChange { readonly kind: ChangeKind.ReplaceWithMultipleNodes; - readonly nodes: ReadonlyArray; + readonly nodes: readonly Node[]; readonly options?: ReplaceWithMultipleNodesOptions; } @@ -230,7 +230,7 @@ namespace ts.textChanges { export class ChangeTracker { private readonly changes: Change[] = []; - private readonly newFiles: { readonly oldFile: SourceFile | undefined, readonly fileName: string, readonly statements: ReadonlyArray }[] = []; + private readonly newFiles: { readonly oldFile: SourceFile | undefined, readonly fileName: string, readonly statements: readonly Statement[] }[] = []; private readonly classesWithNodesInsertedAtStart = createMap<{ readonly node: ClassDeclaration | InterfaceDeclaration | ObjectLiteralExpression, readonly sourceFile: SourceFile }>(); // Set implemented as Map private readonly deletedNodes: { readonly sourceFile: SourceFile, readonly node: Node | NodeArray }[] = []; @@ -283,11 +283,11 @@ namespace ts.textChanges { this.replaceRange(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNode, options); } - private replaceRangeWithNodes(sourceFile: SourceFile, range: TextRange, newNodes: ReadonlyArray, options: ReplaceWithMultipleNodesOptions & ConfigurableStartEnd = {}): void { + private replaceRangeWithNodes(sourceFile: SourceFile, range: TextRange, newNodes: readonly Node[], options: ReplaceWithMultipleNodesOptions & ConfigurableStartEnd = {}): void { this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile, range, options, nodes: newNodes }); } - public replaceNodeWithNodes(sourceFile: SourceFile, oldNode: Node, newNodes: ReadonlyArray, options: ChangeNodeOptions = useNonAdjustedPositions): void { + public replaceNodeWithNodes(sourceFile: SourceFile, oldNode: Node, newNodes: readonly Node[], options: ChangeNodeOptions = useNonAdjustedPositions): void { this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options); } @@ -295,7 +295,7 @@ namespace ts.textChanges { this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, useNonAdjustedPositions), text); } - public replaceNodeRangeWithNodes(sourceFile: SourceFile, startNode: Node, endNode: Node, newNodes: ReadonlyArray, options: ReplaceWithMultipleNodesOptions & ConfigurableStartEnd = useNonAdjustedPositions): void { + public replaceNodeRangeWithNodes(sourceFile: SourceFile, startNode: Node, endNode: Node, newNodes: readonly Node[], options: ReplaceWithMultipleNodesOptions & ConfigurableStartEnd = useNonAdjustedPositions): void { this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); } @@ -313,7 +313,7 @@ namespace ts.textChanges { this.replaceRange(sourceFile, createRange(pos), newNode, options); } - private insertNodesAt(sourceFile: SourceFile, pos: number, newNodes: ReadonlyArray, options: ReplaceWithMultipleNodesOptions = {}): void { + private insertNodesAt(sourceFile: SourceFile, pos: number, newNodes: readonly Node[], options: ReplaceWithMultipleNodesOptions = {}): void { this.replaceRangeWithNodes(sourceFile, createRange(pos), newNodes, options); } @@ -406,7 +406,7 @@ namespace ts.textChanges { this.insertNodeAt(sourceFile, start, type, { prefix: "this: ", suffix }); } - public insertTypeParameters(sourceFile: SourceFile, node: SignatureDeclaration, typeParameters: ReadonlyArray): void { + public insertTypeParameters(sourceFile: SourceFile, node: SignatureDeclaration, typeParameters: readonly TypeParameterDeclaration[]): void { // If no `(`, is an arrow function `x => x`, so use the pos of the first parameter const start = (findChildOfKind(node, SyntaxKind.OpenParenToken, sourceFile) || first(node.parameters)).getStart(sourceFile); this.insertNodesAt(sourceFile, start, typeParameters, { prefix: "<", suffix: ">" }); @@ -448,7 +448,7 @@ namespace ts.textChanges { } } - private replaceConstructorBody(sourceFile: SourceFile, ctr: ConstructorDeclaration, statements: ReadonlyArray): void { + private replaceConstructorBody(sourceFile: SourceFile, ctr: ConstructorDeclaration, statements: readonly Statement[]): void { this.replaceNode(sourceFile, ctr.body!, createBlock(statements, /*multiLine*/ true)); } @@ -505,7 +505,7 @@ namespace ts.textChanges { this.insertNodeAt(sourceFile, list.end, newNode, { prefix: ", " }); } - public insertNodesAfter(sourceFile: SourceFile, after: Node, newNodes: ReadonlyArray): void { + public insertNodesAfter(sourceFile: SourceFile, after: Node, newNodes: readonly Node[]): void { const endPosition = this.insertNodeAfterWorker(sourceFile, after, first(newNodes)); this.insertNodesAt(sourceFile, endPosition, newNodes, this.getInsertNodeAfterOptions(sourceFile, after)); } @@ -759,7 +759,7 @@ namespace ts.textChanges { return changes; } - public createNewFile(oldFile: SourceFile | undefined, fileName: string, statements: ReadonlyArray): void { + public createNewFile(oldFile: SourceFile | undefined, fileName: string, statements: readonly Statement[]): void { this.newFiles.push({ oldFile, fileName, statements }); } } @@ -778,12 +778,12 @@ namespace ts.textChanges { export type ValidateNonFormattedText = (node: Node, text: string) => void; - export function getNewFileText(statements: ReadonlyArray, scriptKind: ScriptKind, newLineCharacter: string, formatContext: formatting.FormatContext): string { + export function getNewFileText(statements: readonly Statement[], scriptKind: ScriptKind, newLineCharacter: string, formatContext: formatting.FormatContext): string { return changesToText.newFileChangesWorker(/*oldFile*/ undefined, scriptKind, statements, newLineCharacter, formatContext); } namespace changesToText { - export function getTextChangesFromChanges(changes: ReadonlyArray, newLineCharacter: string, formatContext: formatting.FormatContext, validate: ValidateNonFormattedText | undefined): FileTextChanges[] { + export function getTextChangesFromChanges(changes: readonly Change[], newLineCharacter: string, formatContext: formatting.FormatContext, validate: ValidateNonFormattedText | undefined): FileTextChanges[] { return group(changes, c => c.sourceFile.path).map(changesInFile => { const sourceFile = changesInFile[0].sourceFile; // order changes by start position @@ -800,12 +800,12 @@ namespace ts.textChanges { }); } - export function newFileChanges(oldFile: SourceFile | undefined, fileName: string, statements: ReadonlyArray, newLineCharacter: string, formatContext: formatting.FormatContext): FileTextChanges { + export function newFileChanges(oldFile: SourceFile | undefined, fileName: string, statements: readonly Statement[], newLineCharacter: string, formatContext: formatting.FormatContext): FileTextChanges { const text = newFileChangesWorker(oldFile, getScriptKindFromFileName(fileName), statements, newLineCharacter, formatContext); return { fileName, textChanges: [createTextChange(createTextSpan(0, 0), text)], isNewFile: true }; } - export function newFileChangesWorker(oldFile: SourceFile | undefined, scriptKind: ScriptKind, statements: ReadonlyArray, newLineCharacter: string, formatContext: formatting.FormatContext): string { + export function newFileChangesWorker(oldFile: SourceFile | undefined, scriptKind: ScriptKind, statements: readonly Statement[], newLineCharacter: string, formatContext: formatting.FormatContext): string { // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this const nonFormattedText = statements.map(s => getNonformattedText(s, oldFile, newLineCharacter).text).join(newLineCharacter); const sourceFile = createSourceFile("any file name", nonFormattedText, ScriptTarget.ESNext, /*setParentNodes*/ true, scriptKind); @@ -859,7 +859,7 @@ namespace ts.textChanges { } } - export function applyChanges(text: string, changes: ReadonlyArray): string { + export function applyChanges(text: string, changes: readonly TextChange[]): string { for (let i = changes.length - 1; i >= 0; i--) { const { span, newText } = changes[i]; text = `${text.substring(0, span.start)}${newText}${text.substring(textSpanEnd(span))}`; diff --git a/src/services/types.ts b/src/services/types.ts index 4b13a08b84b..5c66fb6dd63 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -42,8 +42,8 @@ namespace ts { getProperties(): Symbol[]; getProperty(propertyName: string): Symbol | undefined; getApparentProperties(): Symbol[]; - getCallSignatures(): ReadonlyArray; - getConstructSignatures(): ReadonlyArray; + getCallSignatures(): readonly Signature[]; + getConstructSignatures(): readonly Signature[]; getStringIndexType(): Type | undefined; getNumberIndexType(): Type | undefined; getBaseTypes(): BaseType[] | undefined; @@ -76,11 +76,11 @@ namespace ts { /* @internal */ scriptSnapshot: IScriptSnapshot | undefined; /* @internal */ nameTable: UnderscoreEscapedMap | undefined; - /* @internal */ getNamedDeclarations(): Map>; + /* @internal */ getNamedDeclarations(): Map; getLineAndCharacterOfPosition(pos: number): LineAndCharacter; getLineEndOfPosition(pos: number): number; - getLineStarts(): ReadonlyArray; + getLineStarts(): readonly number[]; getPositionOfLineAndCharacter(line: number, character: number): number; update(newText: string, textChangeRange: TextChangeRange): SourceFile; @@ -178,7 +178,7 @@ namespace ts { getScriptKind?(fileName: string): ScriptKind; getScriptVersion(fileName: string): string; getScriptSnapshot(fileName: string): IScriptSnapshot | undefined; - getProjectReferences?(): ReadonlyArray | undefined; + getProjectReferences?(): readonly ProjectReference[] | undefined; getLocalizedDiagnosticMessages?(): any; getCancellationToken?(): HostCancellationToken; getCurrentDirectory(): string; @@ -192,7 +192,7 @@ namespace ts { * LS host can optionally implement these methods to support completions for module specifiers. * Without these methods, only completions for ambient modules will be provided. */ - readDirectory?(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; + readDirectory?(path: string, extensions?: readonly string[], exclude?: readonly string[], include?: readonly string[], depth?: number): string[]; readFile?(path: string, encoding?: string): string | undefined; realpath?(path: string): string; fileExists?(path: string): boolean; @@ -292,21 +292,21 @@ namespace ts { getSignatureHelpItems(fileName: string, position: number, options: SignatureHelpItemsOptions | undefined): SignatureHelpItems | undefined; getRenameInfo(fileName: string, position: number, options?: RenameInfoOptions): RenameInfo; - findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean, providePrefixAndSuffixTextForRename?: boolean): ReadonlyArray | undefined; + findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean, providePrefixAndSuffixTextForRename?: boolean): readonly RenameLocation[] | undefined; getSmartSelectionRange(fileName: string, position: number): SelectionRange; - getDefinitionAtPosition(fileName: string, position: number): ReadonlyArray | undefined; + getDefinitionAtPosition(fileName: string, position: number): readonly DefinitionInfo[] | undefined; getDefinitionAndBoundSpan(fileName: string, position: number): DefinitionInfoAndBoundSpan | undefined; - getTypeDefinitionAtPosition(fileName: string, position: number): ReadonlyArray | undefined; - getImplementationAtPosition(fileName: string, position: number): ReadonlyArray | undefined; + getTypeDefinitionAtPosition(fileName: string, position: number): readonly DefinitionInfo[] | undefined; + getImplementationAtPosition(fileName: string, position: number): readonly ImplementationLocation[] | undefined; getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[] | undefined; findReferences(fileName: string, position: number): ReferencedSymbol[] | undefined; getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[] | undefined; /** @deprecated */ - getOccurrencesAtPosition(fileName: string, position: number): ReadonlyArray | undefined; + getOccurrencesAtPosition(fileName: string, position: number): readonly ReferenceEntry[] | undefined; getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string, excludeDtsFiles?: boolean): NavigateToItem[]; getNavigationBarItems(fileName: string): NavigationBarItem[]; @@ -336,7 +336,7 @@ namespace ts { /** @internal */ getSourceMapper(): SourceMapper; - getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray; + getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: readonly number[], formatOptions: FormatCodeSettings, preferences: UserPreferences): readonly CodeFixAction[]; getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions; /* eslint-disable @typescript-eslint/unified-signatures */ @@ -353,8 +353,8 @@ namespace ts { getApplicableRefactors(fileName: string, positionOrRange: number | TextRange, preferences: UserPreferences | undefined): ApplicableRefactorInfo[]; getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string, preferences: UserPreferences | undefined): RefactorEditInfo | undefined; - organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): ReadonlyArray; - getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): ReadonlyArray; + organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; + getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; @@ -531,8 +531,8 @@ namespace ts { } export interface CombinedCodeActions { - changes: ReadonlyArray; - commands?: ReadonlyArray; + changes: readonly FileTextChanges[]; + commands?: readonly CodeActionCommand[]; } // Publicly, this type is just `{}`. Internally it is a union of all the actions we use. @@ -773,7 +773,7 @@ namespace ts { } export interface DefinitionInfoAndBoundSpan { - definitions?: ReadonlyArray; + definitions?: readonly DefinitionInfo[]; textSpan: TextSpan; } diff --git a/src/services/utilities.ts b/src/services/utilities.ts index cdf8331333f..5300a343389 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -958,7 +958,7 @@ namespace ts { isPossiblyTypeArgumentPosition(info.called, sourceFile, checker)); } - export function getPossibleGenericSignatures(called: Expression, typeArgumentCount: number, checker: TypeChecker): ReadonlyArray { + export function getPossibleGenericSignatures(called: Expression, typeArgumentCount: number, checker: TypeChecker): readonly Signature[] { const type = checker.getTypeAtLocation(called); const signatures = isNewExpression(called.parent) ? type.getConstructSignatures() : type.getCallSignatures(); return signatures.filter(candidate => !!candidate.typeParameters && candidate.typeParameters.length >= typeArgumentCount); @@ -1217,7 +1217,7 @@ namespace ts { return { span, newText }; } - export const typeKeywords: ReadonlyArray = [ + export const typeKeywords: readonly SyntaxKind[] = [ SyntaxKind.AnyKeyword, SyntaxKind.BigIntKeyword, SyntaxKind.BooleanKeyword, @@ -1294,11 +1294,11 @@ namespace ts { return createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host)); } - export function makeImportIfNecessary(defaultImport: Identifier | undefined, namedImports: ReadonlyArray | undefined, moduleSpecifier: string, quotePreference: QuotePreference): ImportDeclaration | undefined { + export function makeImportIfNecessary(defaultImport: Identifier | undefined, namedImports: readonly ImportSpecifier[] | undefined, moduleSpecifier: string, quotePreference: QuotePreference): ImportDeclaration | undefined { return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference) : undefined; } - export function makeImport(defaultImport: Identifier | undefined, namedImports: ReadonlyArray | undefined, moduleSpecifier: string | Expression, quotePreference: QuotePreference): ImportDeclaration { + export function makeImport(defaultImport: Identifier | undefined, namedImports: readonly ImportSpecifier[] | undefined, moduleSpecifier: string | Expression, quotePreference: QuotePreference): ImportDeclaration { return createImportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, @@ -1816,7 +1816,7 @@ namespace ts { * to be on the reference, rather than the declaration, because it's closer to where the * user was before extracting it. */ - export function getRenameLocation(edits: ReadonlyArray, renameFilename: string, name: string, preferLastLocation: boolean): number { + export function getRenameLocation(edits: readonly FileTextChanges[], renameFilename: string, name: string, preferLastLocation: boolean): number { let delta = 0; let lastPos = -1; for (const { fileName, textChanges } of edits) { diff --git a/src/testRunner/projectsRunner.ts b/src/testRunner/projectsRunner.ts index 97cbf52872b..eeb9e076f0c 100644 --- a/src/testRunner/projectsRunner.ts +++ b/src/testRunner/projectsRunner.ts @@ -3,7 +3,7 @@ namespace project { interface ProjectRunnerTestCase { scenario: string; projectRoot: string; // project where it lives - this also is the current directory when compiling - inputFiles: ReadonlyArray; // list of input files to be given to program + inputFiles: readonly string[]; // list of input files to be given to program resolveMapRoot?: boolean; // should we resolve this map root and give compiler the absolute disk path as map root? resolveSourceRoot?: boolean; // should we resolve this source root and give compiler the absolute disk path as map root? baselineCheck?: boolean; // Verify the baselines of output files, if this is false, we will write to output to the disk but there is no verification of baselines @@ -13,21 +13,21 @@ namespace project { interface ProjectRunnerTestCaseResolutionInfo extends ProjectRunnerTestCase { // Apart from actual test case the results of the resolution - resolvedInputFiles: ReadonlyArray; // List of files that were asked to read by compiler - emittedFiles: ReadonlyArray; // List of files that were emitted by the compiler + resolvedInputFiles: readonly string[]; // List of files that were asked to read by compiler + emittedFiles: readonly string[]; // List of files that were emitted by the compiler } interface CompileProjectFilesResult { - configFileSourceFiles: ReadonlyArray; + configFileSourceFiles: readonly ts.SourceFile[]; moduleKind: ts.ModuleKind; program?: ts.Program; compilerOptions?: ts.CompilerOptions; - errors: ReadonlyArray; - sourceMapData?: ReadonlyArray; + errors: readonly ts.Diagnostic[]; + sourceMapData?: readonly ts.SourceMapEmitResult[]; } interface BatchCompileProjectTestCaseResult extends CompileProjectFilesResult { - outputFiles?: ReadonlyArray; + outputFiles?: readonly documents.TextDocument[]; } export class ProjectRunner extends RunnerBase { @@ -307,8 +307,8 @@ namespace project { return url; } - private compileProjectFiles(moduleKind: ts.ModuleKind, configFileSourceFiles: ReadonlyArray, - getInputFiles: () => ReadonlyArray, + private compileProjectFiles(moduleKind: ts.ModuleKind, configFileSourceFiles: readonly ts.SourceFile[], + getInputFiles: () => readonly string[], compilerHost: ts.CompilerHost, compilerOptions: ts.CompilerOptions): CompileProjectFilesResult { diff --git a/src/testRunner/unittests/builder.ts b/src/testRunner/unittests/builder.ts index dd5bb48ce3e..bf0415f1359 100644 --- a/src/testRunner/unittests/builder.ts +++ b/src/testRunner/unittests/builder.ts @@ -71,7 +71,7 @@ namespace ts { }); }); - function makeAssertChanges(getProgram: () => Program): (fileNames: ReadonlyArray) => void { + function makeAssertChanges(getProgram: () => Program): (fileNames: readonly string[]) => void { const host: BuilderProgramHost = { useCaseSensitiveFileNames: returnTrue }; let builderProgram: EmitAndSemanticDiagnosticsBuilderProgram | undefined; return fileNames => { @@ -85,7 +85,7 @@ namespace ts { }; } - function makeAssertChangesWithCancellationToken(getProgram: () => Program): (fileNames: ReadonlyArray, cancelAfterEmitLength?: number) => void { + function makeAssertChangesWithCancellationToken(getProgram: () => Program): (fileNames: readonly string[], cancelAfterEmitLength?: number) => void { const host: BuilderProgramHost = { useCaseSensitiveFileNames: returnTrue }; let builderProgram: EmitAndSemanticDiagnosticsBuilderProgram | undefined; let cancel = false; diff --git a/src/testRunner/unittests/config/convertCompilerOptionsFromJson.ts b/src/testRunner/unittests/config/convertCompilerOptionsFromJson.ts index 9246bbac825..ffc972d8c4f 100644 --- a/src/testRunner/unittests/config/convertCompilerOptionsFromJson.ts +++ b/src/testRunner/unittests/config/convertCompilerOptionsFromJson.ts @@ -8,7 +8,7 @@ namespace ts { interface ExpectedResultWithParsingSuccess { compilerOptions: CompilerOptions; - errors: ReadonlyArray; + errors: readonly Diagnostic[]; } interface ExpectedResultWithParsingFailure { @@ -59,7 +59,7 @@ namespace ts { } } - function verifyErrors(actualErrors: Diagnostic[], expectedErrors: ReadonlyArray, ignoreLocation?: boolean) { + function verifyErrors(actualErrors: Diagnostic[], expectedErrors: readonly Diagnostic[], ignoreLocation?: boolean) { assert.isTrue(expectedErrors.length === actualErrors.length, `Expected error: ${JSON.stringify(expectedErrors.map(getDiagnosticString), undefined, " ")}. Actual error: ${JSON.stringify(actualErrors.map(getDiagnosticString), undefined, " ")}.`); for (let i = 0; i < actualErrors.length; i++) { const actualError = actualErrors[i]; diff --git a/src/testRunner/unittests/config/projectReferences.ts b/src/testRunner/unittests/config/projectReferences.ts index 305cc726c97..f546813c85a 100644 --- a/src/testRunner/unittests/config/projectReferences.ts +++ b/src/testRunner/unittests/config/projectReferences.ts @@ -1,7 +1,7 @@ namespace ts { interface TestProjectSpecification { configFileName?: string; - references?: ReadonlyArray; + references?: readonly (string | ProjectReference)[]; files: { [fileName: string]: string }; outputFiles?: { [fileName: string]: string }; config?: object; @@ -11,14 +11,14 @@ namespace ts { [path: string]: TestProjectSpecification; } - function assertHasError(message: string, errors: ReadonlyArray, diag: DiagnosticMessage) { + function assertHasError(message: string, errors: readonly Diagnostic[], diag: DiagnosticMessage) { if (!errors.some(e => e.code === diag.code)) { const errorString = errors.map(e => ` ${e.file ? e.file.fileName : "[global]"}: ${e.messageText}`).join("\r\n"); assert(false, `${message}: Did not find any diagnostic for ${diag.message} in:\r\n${errorString}`); } } - function assertNoErrors(message: string, errors: ReadonlyArray) { + function assertNoErrors(message: string, errors: readonly Diagnostic[]) { if (errors && errors.length > 0) { assert(false, `${message}: Expected no errors, but found:\r\n${errors.map(e => ` ${e.messageText}`).join("\r\n")}`); } diff --git a/src/testRunner/unittests/programApi.ts b/src/testRunner/unittests/programApi.ts index 01ef6610dba..51e1b8ffa50 100644 --- a/src/testRunner/unittests/programApi.ts +++ b/src/testRunner/unittests/programApi.ts @@ -1,5 +1,5 @@ namespace ts { - function verifyMissingFilePaths(missingPaths: ReadonlyArray, expected: ReadonlyArray) { + function verifyMissingFilePaths(missingPaths: readonly Path[], expected: readonly string[]) { assert.isDefined(missingPaths); const map = arrayToSet(expected) as Map; for (const missing of missingPaths) { @@ -152,7 +152,7 @@ namespace ts { assertIsExternal(program, [a, fooIndex], f => f !== a); }); - function assertIsExternal(program: Program, files: ReadonlyArray, isExternalExpected: (file: documents.TextDocument) => boolean): void { + function assertIsExternal(program: Program, files: readonly documents.TextDocument[], isExternalExpected: (file: documents.TextDocument) => boolean): void { for (const file of files) { const actual = program.isSourceFileFromExternalLibrary(program.getSourceFile(file.file)!); const expected = isExternalExpected(file); diff --git a/src/testRunner/unittests/reuseProgramStructure.ts b/src/testRunner/unittests/reuseProgramStructure.ts index c9ea0e77fec..b9c1dc1a37a 100644 --- a/src/testRunner/unittests/reuseProgramStructure.ts +++ b/src/testRunner/unittests/reuseProgramStructure.ts @@ -18,7 +18,7 @@ namespace ts { } export interface ProgramWithSourceTexts extends Program { - sourceTexts?: ReadonlyArray; + sourceTexts?: readonly NamedSourceText[]; host: TestCompilerHost; } @@ -104,7 +104,7 @@ namespace ts { return file; } - export function createTestCompilerHost(texts: ReadonlyArray, target: ScriptTarget, oldProgram?: ProgramWithSourceTexts, useGetSourceFileByPath?: boolean) { + export function createTestCompilerHost(texts: readonly NamedSourceText[], target: ScriptTarget, oldProgram?: ProgramWithSourceTexts, useGetSourceFileByPath?: boolean) { const files = arrayToMap(texts, t => t.name, t => { if (oldProgram) { let oldFile = oldProgram.getSourceFile(t.name); @@ -152,7 +152,7 @@ namespace ts { return program; } - export function updateProgram(oldProgram: ProgramWithSourceTexts, rootNames: ReadonlyArray, options: CompilerOptions, updater: (files: NamedSourceText[]) => void, newTexts?: NamedSourceText[], useGetSourceFileByPath?: boolean) { + export function updateProgram(oldProgram: ProgramWithSourceTexts, rootNames: readonly string[], options: CompilerOptions, updater: (files: NamedSourceText[]) => void, newTexts?: NamedSourceText[], useGetSourceFileByPath?: boolean) { if (!newTexts) { newTexts = oldProgram.sourceTexts!.slice(0); } @@ -164,7 +164,7 @@ namespace ts { return program; } - export function updateProgramText(files: ReadonlyArray, fileName: string, newProgramText: string) { + export function updateProgramText(files: readonly NamedSourceText[], fileName: string, newProgramText: string) { const file = find(files, f => f.name === fileName)!; file.text = file.text.updateProgram(newProgramText); } diff --git a/src/testRunner/unittests/services/organizeImports.ts b/src/testRunner/unittests/services/organizeImports.ts index db6dfa8c83c..984091a2aa1 100644 --- a/src/testRunner/unittests/services/organizeImports.ts +++ b/src/testRunner/unittests/services/organizeImports.ts @@ -831,14 +831,14 @@ export * from "lib"; } }); - function parseImports(...importStrings: string[]): ReadonlyArray { + function parseImports(...importStrings: string[]): readonly ImportDeclaration[] { const sourceFile = createSourceFile("a.ts", importStrings.join("\n"), ScriptTarget.ES2015, /*setParentNodes*/ true, ScriptKind.TS); const imports = filter(sourceFile.statements, isImportDeclaration); assert.equal(imports.length, importStrings.length); return imports; } - function parseExports(...exportStrings: string[]): ReadonlyArray { + function parseExports(...exportStrings: string[]): readonly ExportDeclaration[] { const sourceFile = createSourceFile("a.ts", exportStrings.join("\n"), ScriptTarget.ES2015, /*setParentNodes*/ true, ScriptKind.TS); const exports = filter(sourceFile.statements, isExportDeclaration); assert.equal(exports.length, exportStrings.length); @@ -920,7 +920,7 @@ export * from "lib"; } } - function assertListEqual(list1: ReadonlyArray, list2: ReadonlyArray) { + function assertListEqual(list1: readonly Node[], list2: readonly Node[]) { if (list1 === undefined || list2 === undefined) { assert.isUndefined(list1); assert.isUndefined(list2); diff --git a/src/testRunner/unittests/tsbuild/amdModulesWithOut.ts b/src/testRunner/unittests/tsbuild/amdModulesWithOut.ts index 3e1cab9b4a0..2834dbddb60 100644 --- a/src/testRunner/unittests/tsbuild/amdModulesWithOut.ts +++ b/src/testRunner/unittests/tsbuild/amdModulesWithOut.ts @@ -22,7 +22,7 @@ namespace ts { "/src/app/module.tsbuildinfo" ] ]; - type Sources = [string, ReadonlyArray]; + type Sources = [string, readonly string[]]; const enum source { config, ts } const sources: [Sources, Sources] = [ [ diff --git a/src/testRunner/unittests/tsbuild/helpers.ts b/src/testRunner/unittests/tsbuild/helpers.ts index d0746a0fc27..0248d8e278a 100644 --- a/src/testRunner/unittests/tsbuild/helpers.ts +++ b/src/testRunner/unittests/tsbuild/helpers.ts @@ -82,19 +82,19 @@ declare const console: { log(msg: any): void; };`; return fs; } - export function verifyOutputsPresent(fs: vfs.FileSystem, outputs: ReadonlyArray) { + export function verifyOutputsPresent(fs: vfs.FileSystem, outputs: readonly string[]) { for (const output of outputs) { assert(fs.existsSync(output), `Expect file ${output} to exist`); } } - export function verifyOutputsAbsent(fs: vfs.FileSystem, outputs: ReadonlyArray) { + export function verifyOutputsAbsent(fs: vfs.FileSystem, outputs: readonly string[]) { for (const output of outputs) { assert.isFalse(fs.existsSync(output), `Expect file ${output} to not exist`); } } - function generateSourceMapBaselineFiles(fs: vfs.FileSystem, mapFileNames: ReadonlyArray) { + function generateSourceMapBaselineFiles(fs: vfs.FileSystem, mapFileNames: readonly string[]) { for (const mapFile of mapFileNames) { if (!fs.existsSync(mapFile)) continue; const text = Harness.SourceMapRecorder.getSourceMapRecordWithVFS(fs, mapFile); @@ -104,7 +104,7 @@ declare const console: { log(msg: any): void; };`; // [tsbuildinfo, js, dts] export type BuildInfoSectionBaselineFiles = [string, string | undefined, string | undefined]; - function generateBuildInfoSectionBaselineFiles(fs: vfs.FileSystem, buildInfoFileNames: ReadonlyArray) { + function generateBuildInfoSectionBaselineFiles(fs: vfs.FileSystem, buildInfoFileNames: readonly BuildInfoSectionBaselineFiles[]) { for (const [file, jsFile, dtsFile] of buildInfoFileNames) { if (!fs.existsSync(file)) continue; @@ -162,9 +162,9 @@ declare const console: { log(msg: any): void; };`; interface BuildInput { fs: vfs.FileSystem; tick: () => void; - rootNames: ReadonlyArray; - expectedMapFileNames: ReadonlyArray; - expectedBuildInfoFilesForSectionBaselines?: ReadonlyArray; + rootNames: readonly string[]; + expectedMapFileNames: readonly string[]; + expectedBuildInfoFilesForSectionBaselines?: readonly BuildInfoSectionBaselineFiles[]; modifyFs: (fs: vfs.FileSystem) => void; } @@ -207,7 +207,7 @@ Mismatch Actual(path, actual, expected): ${JSON.stringify(arrayFrom(mapDefinedIt }); } - export function getReadFilesMap(filesReadOnce: ReadonlyArray, ...filesWithTwoReadCalls: string[]) { + export function getReadFilesMap(filesReadOnce: readonly string[], ...filesWithTwoReadCalls: string[]) { const map = arrayToMap(filesReadOnce, identity, () => 1); for (const fileWithTwoReadCalls of filesWithTwoReadCalls) { map.set(fileWithTwoReadCalls, 2); @@ -216,7 +216,7 @@ Mismatch Actual(path, actual, expected): ${JSON.stringify(arrayFrom(mapDefinedIt } export interface ExpectedBuildOutput { - expectedDiagnostics?: ReadonlyArray; + expectedDiagnostics?: readonly fakes.ExpectedDiagnostic[]; expectedReadFiles?: ReadonlyMap; } @@ -230,12 +230,12 @@ Mismatch Actual(path, actual, expected): ${JSON.stringify(arrayFrom(mapDefinedIt time: () => number; tick: () => void; proj: string; - rootNames: ReadonlyArray; - expectedMapFileNames: ReadonlyArray; - expectedBuildInfoFilesForSectionBaselines?: ReadonlyArray; + rootNames: readonly string[]; + expectedMapFileNames: readonly string[]; + expectedBuildInfoFilesForSectionBaselines?: readonly BuildInfoSectionBaselineFiles[]; lastProjectOutputJs: string; initialBuild: BuildState; - outputFiles?: ReadonlyArray; + outputFiles?: readonly string[]; incrementalDtsChangedBuild?: BuildState; incrementalDtsUnchangedBuild?: BuildState; incrementalHeaderChangedBuild?: BuildState; @@ -286,7 +286,7 @@ Mismatch Actual(path, actual, expected): ${JSON.stringify(arrayFrom(mapDefinedIt } }); - function incrementalBuild(subScenario: string, incrementalModifyFs: (fs: vfs.FileSystem) => void, incrementalExpectedDiagnostics: ReadonlyArray | undefined, incrementalExpectedReadFiles: ReadonlyMap | undefined) { + function incrementalBuild(subScenario: string, incrementalModifyFs: (fs: vfs.FileSystem) => void, incrementalExpectedDiagnostics: readonly fakes.ExpectedDiagnostic[] | undefined, incrementalExpectedReadFiles: ReadonlyMap | undefined) { describe(subScenario, () => { let newFs: vfs.FileSystem; let actualReadFileMap: Map; diff --git a/src/testRunner/unittests/tsbuild/outFile.ts b/src/testRunner/unittests/tsbuild/outFile.ts index f562d4dc26b..71f4470823d 100644 --- a/src/testRunner/unittests/tsbuild/outFile.ts +++ b/src/testRunner/unittests/tsbuild/outFile.ts @@ -29,7 +29,7 @@ namespace ts { ] ]; const relOutputFiles = outputFiles.map(v => v.map(relName)) as [OutputFile, OutputFile, OutputFile]; - type Sources = [string, ReadonlyArray]; + type Sources = [string, readonly string[]]; const enum source { config, ts } const enum part { one, two, three } const sources: [Sources, Sources, Sources] = [ @@ -63,7 +63,7 @@ namespace ts { outputFiles[project.third][ext.jsmap], outputFiles[project.third][ext.dtsmap] ]; - const expectedTsbuildInfoFileNames: ReadonlyArray = [ + const expectedTsbuildInfoFileNames: readonly BuildInfoSectionBaselineFiles[] = [ [outputFiles[project.first][ext.buildinfo], outputFiles[project.first][ext.js], outputFiles[project.first][ext.dts]], [outputFiles[project.second][ext.buildinfo], outputFiles[project.second][ext.js], outputFiles[project.second][ext.dts]], [outputFiles[project.third][ext.buildinfo], outputFiles[project.third][ext.js], outputFiles[project.third][ext.dts]] @@ -75,7 +75,7 @@ namespace ts { ...outputFiles[project.second], ...outputFiles[project.third] ]; - let initialExpectedDiagnostics: ReadonlyArray = [ + let initialExpectedDiagnostics: readonly fakes.ExpectedDiagnostic[] = [ getExpectedDiagnosticForProjectsInBuild(relSources[project.first][source.config], relSources[project.second][source.config], relSources[project.third][source.config]), [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, relSources[project.first][source.config], relOutputFiles[project.first][ext.js]], [Diagnostics.Building_project_0, sources[project.first][source.config]], @@ -102,7 +102,7 @@ namespace ts { ] ); - let dtsChangedExpectedDiagnostics: ReadonlyArray = [ + let dtsChangedExpectedDiagnostics: readonly fakes.ExpectedDiagnostic[] = [ getExpectedDiagnosticForProjectsInBuild(relSources[project.first][source.config], relSources[project.second][source.config], relSources[project.third][source.config]), [Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relSources[project.first][source.config], relOutputFiles[project.first][ext.js], relSources[project.first][source.ts][part.one]], [Diagnostics.Building_project_0, sources[project.first][source.config]], @@ -129,7 +129,7 @@ namespace ts { outputFiles[project.first][ext.dts], // dts changes so once read old content, and once new (to emit third) ); - let dtsChangedExpectedDiagnosticsDependOrdered: ReadonlyArray = [ + let dtsChangedExpectedDiagnosticsDependOrdered: readonly fakes.ExpectedDiagnostic[] = [ getExpectedDiagnosticForProjectsInBuild(relSources[project.first][source.config], relSources[project.second][source.config], relSources[project.third][source.config]), [Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relSources[project.first][source.config], relOutputFiles[project.first][ext.js], relSources[project.first][source.ts][part.one]], [Diagnostics.Building_project_0, sources[project.first][source.config]], @@ -140,7 +140,7 @@ namespace ts { ]; let dtsChangedExpectedReadFilesDependOrdered: ReadonlyMap = getDtsChangedReadFilesDependOrdered(); - let dtsUnchangedExpectedDiagnostics: ReadonlyArray = [ + let dtsUnchangedExpectedDiagnostics: readonly fakes.ExpectedDiagnostic[] = [ getExpectedDiagnosticForProjectsInBuild(relSources[project.first][source.config], relSources[project.second][source.config], relSources[project.third][source.config]), [Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relSources[project.first][source.config], relOutputFiles[project.first][ext.js], relSources[project.first][source.ts][part.one]], [Diagnostics.Building_project_0, sources[project.first][source.config]], @@ -166,7 +166,7 @@ namespace ts { ] ); - let dtsUnchangedExpectedDiagnosticsDependOrdered: ReadonlyArray = [ + let dtsUnchangedExpectedDiagnosticsDependOrdered: readonly fakes.ExpectedDiagnostic[] = [ getExpectedDiagnosticForProjectsInBuild(relSources[project.first][source.config], relSources[project.second][source.config], relSources[project.third][source.config]), [Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relSources[project.first][source.config], relOutputFiles[project.first][ext.js], relSources[project.first][source.ts][part.one]], [Diagnostics.Building_project_0, sources[project.first][source.config]], @@ -201,7 +201,7 @@ namespace ts { return ts.createSolutionBuilder(host, ["/src/third"], { dry: false, force: false, verbose: true, ...(baseOptions || {}) }); } - function getInitialExpectedReadFiles(additionalSourceFiles?: ReadonlyArray) { + function getInitialExpectedReadFiles(additionalSourceFiles?: readonly string[]) { if (!additionalSourceFiles) return initialExpectedReadFiles; const expectedReadFiles = cloneMap(initialExpectedReadFiles); for (const path of additionalSourceFiles) { @@ -219,7 +219,7 @@ namespace ts { return value; } - function getDtsChangedReadFiles(dependOrdered?: boolean, additionalSourceFiles?: ReadonlyArray) { + function getDtsChangedReadFiles(dependOrdered?: boolean, additionalSourceFiles?: readonly string[]) { const value = dependOrdered ? dtsChangedExpectedReadFilesDependOrdered : dtsChangedExpectedReadFiles; if (!additionalSourceFiles) return value; const expectedReadFiles = cloneMap(value); @@ -238,7 +238,7 @@ namespace ts { return value; } - function getDtsUnchangedReadFiles(dependOrdered?: boolean, additionalSourceFiles?: ReadonlyArray) { + function getDtsUnchangedReadFiles(dependOrdered?: boolean, additionalSourceFiles?: readonly string[]) { const value = dependOrdered ? dtsUnchangedExpectedReadFilesDependOrdered : dtsUnchangedExpectedReadFiles; if (!additionalSourceFiles || additionalSourceFiles.length !== 3) return value; const expectedReadFiles = cloneMap(value); @@ -251,8 +251,8 @@ namespace ts { scenario: string; modifyFs: (fs: vfs.FileSystem) => void; modifyAgainFs?: (fs: vfs.FileSystem) => void; - additionalSourceFiles?: ReadonlyArray; - expectedBuildInfoFilesForSectionBaselines?: ReadonlyArray; + additionalSourceFiles?: readonly string[]; + expectedBuildInfoFilesForSectionBaselines?: readonly BuildInfoSectionBaselineFiles[]; dependOrdered?: true; ignoreDtsChanged?: true; ignoreDtsUnchanged?: true; diff --git a/src/testRunner/unittests/tsbuild/resolveJsonModule.ts b/src/testRunner/unittests/tsbuild/resolveJsonModule.ts index 7793ef5375c..8f389888d6c 100644 --- a/src/testRunner/unittests/tsbuild/resolveJsonModule.ts +++ b/src/testRunner/unittests/tsbuild/resolveJsonModule.ts @@ -16,7 +16,7 @@ namespace ts { verifyProjectWithResolveJsonModuleWithFs(fs, configFile, allExpectedOutputs, ...expectedDiagnosticMessages); } - function verifyProjectWithResolveJsonModuleWithFs(fs: vfs.FileSystem, configFile: string, allExpectedOutputs: ReadonlyArray, ...expectedDiagnosticMessages: fakes.ExpectedDiagnostic[]) { + function verifyProjectWithResolveJsonModuleWithFs(fs: vfs.FileSystem, configFile: string, allExpectedOutputs: readonly string[], ...expectedDiagnosticMessages: fakes.ExpectedDiagnostic[]) { const host = new fakes.SolutionBuilderHost(fs); const builder = createSolutionBuilder(host, [configFile], { dry: false, force: false, verbose: false }); builder.build(); diff --git a/src/testRunner/unittests/tsbuild/sample.ts b/src/testRunner/unittests/tsbuild/sample.ts index bf56279f169..420c7a468aa 100644 --- a/src/testRunner/unittests/tsbuild/sample.ts +++ b/src/testRunner/unittests/tsbuild/sample.ts @@ -407,8 +407,8 @@ namespace ts { function verifyBuildNextResult( expected: SolutionBuilderResult | undefined, - presentOutputs: ReadonlyArray, - absentOutputs: ReadonlyArray + presentOutputs: readonly string[], + absentOutputs: readonly string[] ) { const project = builder.getNextInvalidatedProject(); const result = project && project.done(); diff --git a/src/testRunner/unittests/tsbuild/transitiveReferences.ts b/src/testRunner/unittests/tsbuild/transitiveReferences.ts index 614796b2a85..623b7897f9d 100644 --- a/src/testRunner/unittests/tsbuild/transitiveReferences.ts +++ b/src/testRunner/unittests/tsbuild/transitiveReferences.ts @@ -25,7 +25,7 @@ namespace ts { projFs = undefined!; // Release the contents }); - function verifyBuild(modifyDiskLayout: (fs: vfs.FileSystem) => void, allExpectedOutputs: ReadonlyArray, expectedFileTraces: ReadonlyArray, ...expectedDiagnostics: fakes.ExpectedDiagnostic[]) { + function verifyBuild(modifyDiskLayout: (fs: vfs.FileSystem) => void, allExpectedOutputs: readonly string[], expectedFileTraces: readonly string[], ...expectedDiagnostics: fakes.ExpectedDiagnostic[]) { const fs = projFs.shadow(); const host = new fakes.SolutionBuilderHost(fs); modifyDiskLayout(fs); diff --git a/src/testRunner/unittests/tsbuild/watchEnvironment.ts b/src/testRunner/unittests/tsbuild/watchEnvironment.ts index f73b9f1174e..f3c076b09ac 100644 --- a/src/testRunner/unittests/tsbuild/watchEnvironment.ts +++ b/src/testRunner/unittests/tsbuild/watchEnvironment.ts @@ -70,7 +70,7 @@ namespace ts.tscWatch { system.writeFile(typing.path, `${typing.content}export const typing1 = 10;`); system.checkTimeoutQueueLength(0); - function flatArray(arr: T[][]): ReadonlyArray { + function flatArray(arr: T[][]): readonly T[] { return flatMap(arr, identity); } function pkgs(cb: (index: number) => T): T[] { diff --git a/src/testRunner/unittests/tsbuild/watchMode.ts b/src/testRunner/unittests/tsbuild/watchMode.ts index 31ed96cece1..5dda0f9b01f 100644 --- a/src/testRunner/unittests/tsbuild/watchMode.ts +++ b/src/testRunner/unittests/tsbuild/watchMode.ts @@ -4,7 +4,7 @@ namespace ts.tscWatch { import getFileFromProject = TestFSWithWatch.getTsBuildProjectFile; type TsBuildWatchSystem = WatchedSystem & { writtenFiles: Map; }; - function createTsBuildWatchSystem(fileOrFolderList: ReadonlyArray, params?: TestFSWithWatch.TestServerHostCreationParameters) { + function createTsBuildWatchSystem(fileOrFolderList: readonly TestFSWithWatch.FileOrFolderOrSymLink[], params?: TestFSWithWatch.TestServerHostCreationParameters) { const host = createWatchedSystem(fileOrFolderList, params) as TsBuildWatchSystem; const originalWriteFile = host.writeFile; host.writtenFiles = createMap(); @@ -17,7 +17,7 @@ namespace ts.tscWatch { } - export function createSolutionBuilder(system: WatchedSystem, rootNames: ReadonlyArray, defaultOptions?: BuildOptions) { + export function createSolutionBuilder(system: WatchedSystem, rootNames: readonly string[], defaultOptions?: BuildOptions) { const host = createSolutionBuilderHost(system); host.now = system.now.bind(system); return ts.createSolutionBuilder(host, rootNames, defaultOptions || {}); @@ -29,7 +29,7 @@ namespace ts.tscWatch { return host; } - function createSolutionBuilderWithWatch(system: TsBuildWatchSystem, rootNames: ReadonlyArray, defaultOptions?: BuildOptions) { + function createSolutionBuilderWithWatch(system: TsBuildWatchSystem, rootNames: readonly string[], defaultOptions?: BuildOptions) { const host = createSolutionBuilderWithWatchHost(system); const solutionBuilder = ts.createSolutionBuilderWithWatch(host, rootNames, defaultOptions || { watch: true }); solutionBuilder.build(); @@ -92,7 +92,7 @@ namespace ts.tscWatch { return getOutputFileNames(subProject, baseFileNameWithoutExtension).map(f => transformOutputToOutputFileStamp(f, host)); } - function getOutputFileStamps(host: TsBuildWatchSystem, additionalFiles?: ReadonlyArray<[SubProject, string]>): OutputFileStamp[] { + function getOutputFileStamps(host: TsBuildWatchSystem, additionalFiles?: readonly [SubProject, string][]): OutputFileStamp[] { const result = [ ...getOutputStamps(host, SubProject.core, "anotherModule"), ...getOutputStamps(host, SubProject.core, "index"), @@ -106,7 +106,7 @@ namespace ts.tscWatch { return result; } - function verifyChangedFiles(actualStamps: OutputFileStamp[], oldTimeStamps: OutputFileStamp[], changedFiles: ReadonlyArray, modifiedTimeStampFiles: ReadonlyArray) { + function verifyChangedFiles(actualStamps: OutputFileStamp[], oldTimeStamps: OutputFileStamp[], changedFiles: readonly string[], modifiedTimeStampFiles: readonly string[]) { for (let i = 0; i < oldTimeStamps.length; i++) { const actual = actualStamps[i]; const old = oldTimeStamps[i]; @@ -125,7 +125,7 @@ namespace ts.tscWatch { let logic: SubProjectFiles; let tests: SubProjectFiles; let ui: SubProjectFiles; - let allFiles: ReadonlyArray; + let allFiles: readonly File[]; let testProjectExpectedWatchedFiles: string[]; let testProjectExpectedWatchedDirectoriesRecursive: string[]; @@ -149,7 +149,7 @@ namespace ts.tscWatch { testProjectExpectedWatchedDirectoriesRecursive = undefined!; }); - function createSolutionInWatchMode(allFiles: ReadonlyArray, defaultOptions?: BuildOptions, disableConsoleClears?: boolean) { + function createSolutionInWatchMode(allFiles: readonly File[], defaultOptions?: BuildOptions, disableConsoleClears?: boolean) { const host = createTsBuildWatchSystem(allFiles, { currentDirectory: projectsLocation }); createSolutionBuilderWithWatch(host, [`${project}/${SubProject.tests}`], defaultOptions); verifyWatches(host); @@ -200,8 +200,8 @@ namespace ts.tscWatch { content: `export const newFileConst = 30;` }; - function verifyProjectChanges(allFilesGetter: () => ReadonlyArray) { - function createSolutionInWatchModeToVerifyChanges(additionalFiles?: ReadonlyArray<[SubProject, string]>) { + function verifyProjectChanges(allFilesGetter: () => readonly File[]) { + function createSolutionInWatchModeToVerifyChanges(additionalFiles?: readonly [SubProject, string][]) { const host = createSolutionInWatchMode(allFilesGetter()); return { host, verifyChangeWithFile, verifyChangeAfterTimeout, verifyWatches }; @@ -290,7 +290,7 @@ function foo() { }`, /*local*/ true); }); it("builds when new file is added, and its subsequent updates", () => { - const additinalFiles: ReadonlyArray<[SubProject, string]> = [[SubProject.core, newFileWithoutExtension]]; + const additinalFiles: readonly [SubProject, string][] = [[SubProject.core, newFileWithoutExtension]]; const { verifyChangeWithFile } = createSolutionInWatchModeToVerifyChanges(additinalFiles); verifyChange(newFile.content); @@ -568,7 +568,7 @@ let x: string = 10;`); `${subProjectLocation}/tsconfig${Extension.TsBuildInfo}` ]; - function verifyDtsErrors(host: TsBuildWatchSystem, isIncremental: boolean, expectedErrors: ReadonlyArray) { + function verifyDtsErrors(host: TsBuildWatchSystem, isIncremental: boolean, expectedErrors: readonly string[]) { (isIncremental ? checkOutputErrorsIncremental : checkOutputErrorsInitial)(host, expectedErrors); outputs.forEach(f => assert.equal(host.fileExists(f), !expectedErrors.length, `Expected file ${f} to ${!expectedErrors.length ? "exist" : "not exist"}`)); } @@ -646,16 +646,16 @@ let x: string = 10;`); describe("tsc-watch and tsserver works with project references", () => { describe("invoking when references are already built", () => { - function verifyWatchesOfProject(host: TsBuildWatchSystem, expectedWatchedFiles: ReadonlyArray, expectedWatchedDirectoriesRecursive: ReadonlyArray, expectedWatchedDirectories?: ReadonlyArray) { + function verifyWatchesOfProject(host: TsBuildWatchSystem, expectedWatchedFiles: readonly string[], expectedWatchedDirectoriesRecursive: readonly string[], expectedWatchedDirectories?: readonly string[]) { checkWatchedFilesDetailed(host, expectedWatchedFiles, 1); checkWatchedDirectoriesDetailed(host, expectedWatchedDirectories || emptyArray, 1, /*recursive*/ false); checkWatchedDirectoriesDetailed(host, expectedWatchedDirectoriesRecursive, 1, /*recursive*/ true); } - function createSolutionOfProject(allFiles: ReadonlyArray, + function createSolutionOfProject(allFiles: readonly File[], currentDirectory: string, solutionBuilderconfig: string, - getOutputFileStamps: (host: TsBuildWatchSystem) => ReadonlyArray) { + getOutputFileStamps: (host: TsBuildWatchSystem) => readonly OutputFileStamp[]) { // Build the composite project const host = createTsBuildWatchSystem(allFiles, { currentDirectory }); const solutionBuilder = createSolutionBuilder(host, [solutionBuilderconfig], {}); @@ -668,11 +668,11 @@ let x: string = 10;`); } function createSolutionAndWatchModeOfProject( - allFiles: ReadonlyArray, + allFiles: readonly File[], currentDirectory: string, solutionBuilderconfig: string, watchConfig: string, - getOutputFileStamps: (host: TsBuildWatchSystem) => ReadonlyArray) { + getOutputFileStamps: (host: TsBuildWatchSystem) => readonly OutputFileStamp[]) { // Build the composite project const { host, solutionBuilder } = createSolutionOfProject(allFiles, currentDirectory, solutionBuilderconfig, getOutputFileStamps); @@ -683,11 +683,11 @@ let x: string = 10;`); return { host, solutionBuilder, watch }; } - function createSolutionAndServiceOfProject(allFiles: ReadonlyArray, + function createSolutionAndServiceOfProject(allFiles: readonly File[], currentDirectory: string, solutionBuilderconfig: string, openFileName: string, - getOutputFileStamps: (host: TsBuildWatchSystem) => ReadonlyArray) { + getOutputFileStamps: (host: TsBuildWatchSystem) => readonly OutputFileStamp[]) { // Build the composite project const { host, solutionBuilder } = createSolutionOfProject(allFiles, currentDirectory, solutionBuilderconfig, getOutputFileStamps); @@ -698,12 +698,12 @@ let x: string = 10;`); return { host, solutionBuilder, service }; } - function checkProjectActualFiles(service: projectSystem.TestProjectService, configFile: string, expectedFiles: ReadonlyArray) { + function checkProjectActualFiles(service: projectSystem.TestProjectService, configFile: string, expectedFiles: readonly string[]) { projectSystem.checkNumberOfProjects(service, { configuredProjects: 1 }); projectSystem.checkProjectActualFiles(service.configuredProjects.get(configFile.toLowerCase())!, expectedFiles); } - function verifyDependencies(watch: Watch, filePath: string, expected: ReadonlyArray) { + function verifyDependencies(watch: Watch, filePath: string, expected: readonly string[]) { checkArray(`${filePath} dependencies`, watch.getBuilderProgram().getAllDependencies(watch().getSourceFile(filePath)!), expected); } @@ -729,7 +729,7 @@ let x: string = 10;`); function verifyScenario( edit: (host: TsBuildWatchSystem, solutionBuilder: SolutionBuilder) => void, - expectedFilesAfterEdit: () => ReadonlyArray + expectedFilesAfterEdit: () => readonly string[] ) { it("with tsc-watch", () => { const { host, solutionBuilder, watch } = createSolutionAndWatchMode(); @@ -833,11 +833,11 @@ export function gfoo() { function verifyWatchState( host: TsBuildWatchSystem, watch: Watch, - expectedProgramFiles: ReadonlyArray, - expectedWatchedFiles: ReadonlyArray, - expectedWatchedDirectoriesRecursive: ReadonlyArray, - dependencies: ReadonlyArray<[string, ReadonlyArray]>, - expectedWatchedDirectories?: ReadonlyArray) { + expectedProgramFiles: readonly string[], + expectedWatchedFiles: readonly string[], + expectedWatchedDirectoriesRecursive: readonly string[], + dependencies: readonly [string, readonly string[]][], + expectedWatchedDirectories?: readonly string[]) { checkProgramActualFiles(watch(), expectedProgramFiles); verifyWatchesOfProject(host, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, expectedWatchedDirectories); for (const [file, deps] of dependencies) { @@ -903,7 +903,7 @@ export function gfoo() { ...projectSystem.getTypeRootsFromLocation(multiFolder ? getFilePathInProject(project, "c") : getProjectPath(project)) ].map(s => s.toLowerCase()); - const defaultDependencies: ReadonlyArray<[string, ReadonlyArray]> = [ + const defaultDependencies: readonly [string, readonly string[]][] = [ [aDts, [aDts]], [bDts, [bDts, aDts]], [refs.path, [refs.path]], @@ -926,17 +926,17 @@ export function gfoo() { verifyWatchState(host, watch, expectedProgramFiles, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, defaultDependencies, expectedWatchedDirectories); } - function verifyProject(host: TsBuildWatchSystem, service: projectSystem.TestProjectService, orphanInfos?: ReadonlyArray) { + function verifyProject(host: TsBuildWatchSystem, service: projectSystem.TestProjectService, orphanInfos?: readonly string[]) { verifyServerState(host, service, expectedProgramFiles, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, orphanInfos); } function verifyServerState( host: TsBuildWatchSystem, service: projectSystem.TestProjectService, - expectedProgramFiles: ReadonlyArray, - expectedWatchedFiles: ReadonlyArray, - expectedWatchedDirectoriesRecursive: ReadonlyArray, - orphanInfos?: ReadonlyArray) { + expectedProgramFiles: readonly string[], + expectedWatchedFiles: readonly string[], + expectedWatchedDirectoriesRecursive: readonly string[], + orphanInfos?: readonly string[]) { checkProjectActualFiles(service, cTsconfig.path, expectedProgramFiles.concat(cTsconfig.path)); const watchedFiles = expectedWatchedFiles.filter(f => f !== cTs.path.toLowerCase()); if (orphanInfos) { @@ -952,14 +952,14 @@ export function gfoo() { function verifyScenario( edit: (host: TsBuildWatchSystem, solutionBuilder: SolutionBuilder) => void, - expectedEditErrors: ReadonlyArray, - expectedProgramFiles: ReadonlyArray, - expectedWatchedFiles: ReadonlyArray, - expectedWatchedDirectoriesRecursive: ReadonlyArray, - dependencies: ReadonlyArray<[string, ReadonlyArray]>, + expectedEditErrors: readonly string[], + expectedProgramFiles: readonly string[], + expectedWatchedFiles: readonly string[], + expectedWatchedDirectoriesRecursive: readonly string[], + dependencies: readonly [string, readonly string[]][], revert?: (host: TsBuildWatchSystem) => void, - orphanInfosAfterEdit?: ReadonlyArray, - orphanInfosAfterRevert?: ReadonlyArray) { + orphanInfosAfterEdit?: readonly string[], + orphanInfosAfterRevert?: readonly string[]) { it("with tsc-watch", () => { const { host, solutionBuilder, watch } = createSolutionAndWatchMode(); @@ -1170,7 +1170,7 @@ export function gfoo() { ...projectSystem.getTypeRootsFromLocation(getProjectPath(project)) ].map(s => s.toLowerCase()); - const defaultDependencies: ReadonlyArray<[string, ReadonlyArray]> = [ + const defaultDependencies: readonly [string, readonly string[]][] = [ [aDts, [aDts]], [bDts, [bDts, aDts]], [refs.path, [refs.path]], diff --git a/src/testRunner/unittests/tscWatch/emitAndErrorUpdates.ts b/src/testRunner/unittests/tscWatch/emitAndErrorUpdates.ts index b76c9a985d4..f41b07b157d 100644 --- a/src/testRunner/unittests/tscWatch/emitAndErrorUpdates.ts +++ b/src/testRunner/unittests/tscWatch/emitAndErrorUpdates.ts @@ -16,11 +16,11 @@ namespace ts.tscWatch { }; } - function getOutputFileStampsAndErrors(host: WatchedSystem, watch: Watch, directoryFiles: ReadonlyArray) { + function getOutputFileStampsAndErrors(host: WatchedSystem, watch: Watch, directoryFiles: readonly File[]) { return directoryFiles.map(d => getOutputFileStampAndError(host, watch, d)); } - function findStampAndErrors(stampsAndErrors: ReadonlyArray>, file: File) { + function findStampAndErrors(stampsAndErrors: readonly ReturnType[], file: File) { return find(stampsAndErrors, info => info.file === file)!; } @@ -28,8 +28,8 @@ namespace ts.tscWatch { file: File, emitExpected: boolean, errorRefershExpected: boolean, - beforeChangeFileStampsAndErrors: ReadonlyArray>, - afterChangeFileStampsAndErrors: ReadonlyArray> + beforeChangeFileStampsAndErrors: readonly ReturnType[], + afterChangeFileStampsAndErrors: readonly ReturnType[] ) { const beforeChange = findStampAndErrors(beforeChangeFileStampsAndErrors, file); const afterChange = findStampAndErrors(afterChangeFileStampsAndErrors, file); @@ -53,11 +53,11 @@ namespace ts.tscWatch { interface VerifyEmitAndErrorUpdates { change: (host: WatchedSystem) => void; - getInitialErrors: (watch: Watch) => ReadonlyArray | ReadonlyArray; - getIncrementalErrors: (watch: Watch) => ReadonlyArray | ReadonlyArray; - filesWithNewEmit: ReadonlyArray; - filesWithOnlyErrorRefresh: ReadonlyArray; - filesNotTouched: ReadonlyArray; + getInitialErrors: (watch: Watch) => readonly Diagnostic[] | readonly string[]; + getIncrementalErrors: (watch: Watch) => readonly Diagnostic[] | readonly string[]; + filesWithNewEmit: readonly File[]; + filesWithOnlyErrorRefresh: readonly File[]; + filesNotTouched: readonly File[]; configFile?: File; } diff --git a/src/testRunner/unittests/tscWatch/helpers.ts b/src/testRunner/unittests/tscWatch/helpers.ts index 69ef2c5f5bb..39d2c9a5aad 100644 --- a/src/testRunner/unittests/tscWatch/helpers.ts +++ b/src/testRunner/unittests/tscWatch/helpers.ts @@ -21,11 +21,11 @@ namespace ts.tscWatch { content: "let y = 1" }; - export function checkProgramActualFiles(program: Program, expectedFiles: ReadonlyArray) { + export function checkProgramActualFiles(program: Program, expectedFiles: readonly string[]) { checkArray(`Program actual files`, program.getSourceFiles().map(file => file.fileName), expectedFiles); } - export function checkProgramRootFiles(program: Program, expectedFiles: ReadonlyArray) { + export function checkProgramRootFiles(program: Program, expectedFiles: readonly string[]) { checkArray(`Program rootFileNames`, program.getRootFileNames(), expectedFiles); } @@ -59,7 +59,7 @@ namespace ts.tscWatch { logsBeforeWatchDiagnostic: string[] | undefined, preErrorsWatchDiagnostic: Diagnostic | undefined, logsBeforeErrors: string[] | undefined, - errors: ReadonlyArray | ReadonlyArray, + errors: readonly Diagnostic[] | readonly string[], disableConsoleClears?: boolean | undefined, ...postErrorsWatchDiagnostics: Diagnostic[] | string[] ) { @@ -128,13 +128,13 @@ namespace ts.tscWatch { } } - function createErrorsFoundCompilerDiagnostic(errors: ReadonlyArray | ReadonlyArray) { + function createErrorsFoundCompilerDiagnostic(errors: readonly Diagnostic[] | readonly string[]) { return errors.length === 1 ? createCompilerDiagnostic(Diagnostics.Found_1_error_Watching_for_file_changes) : createCompilerDiagnostic(Diagnostics.Found_0_errors_Watching_for_file_changes, errors.length); } - export function checkOutputErrorsInitial(host: WatchedSystem, errors: ReadonlyArray | ReadonlyArray, disableConsoleClears?: boolean, logsBeforeErrors?: string[]) { + export function checkOutputErrorsInitial(host: WatchedSystem, errors: readonly Diagnostic[] | readonly string[], disableConsoleClears?: boolean, logsBeforeErrors?: string[]) { checkOutputErrors( host, /*logsBeforeWatchDiagnostic*/ undefined, @@ -145,7 +145,7 @@ namespace ts.tscWatch { createErrorsFoundCompilerDiagnostic(errors)); } - export function checkOutputErrorsIncremental(host: WatchedSystem, errors: ReadonlyArray | ReadonlyArray, disableConsoleClears?: boolean, logsBeforeWatchDiagnostic?: string[], logsBeforeErrors?: string[]) { + export function checkOutputErrorsIncremental(host: WatchedSystem, errors: readonly Diagnostic[] | readonly string[], disableConsoleClears?: boolean, logsBeforeWatchDiagnostic?: string[], logsBeforeErrors?: string[]) { checkOutputErrors( host, logsBeforeWatchDiagnostic, @@ -156,7 +156,7 @@ namespace ts.tscWatch { createErrorsFoundCompilerDiagnostic(errors)); } - export function checkOutputErrorsIncrementalWithExit(host: WatchedSystem, errors: ReadonlyArray | ReadonlyArray, expectedExitCode: ExitStatus, disableConsoleClears?: boolean, logsBeforeWatchDiagnostic?: string[], logsBeforeErrors?: string[]) { + export function checkOutputErrorsIncrementalWithExit(host: WatchedSystem, errors: readonly Diagnostic[] | readonly string[], expectedExitCode: ExitStatus, disableConsoleClears?: boolean, logsBeforeWatchDiagnostic?: string[], logsBeforeErrors?: string[]) { checkOutputErrors( host, logsBeforeWatchDiagnostic, @@ -167,7 +167,7 @@ namespace ts.tscWatch { assert.equal(host.exitCode, expectedExitCode); } - export function checkNormalBuildErrors(host: WatchedSystem, errors: ReadonlyArray | ReadonlyArray, reportErrorSummary?: boolean) { + export function checkNormalBuildErrors(host: WatchedSystem, errors: readonly Diagnostic[] | readonly string[], reportErrorSummary?: boolean) { checkOutputErrors( host, /*logsBeforeWatchDiagnostic*/ undefined, diff --git a/src/testRunner/unittests/tscWatch/incremental.ts b/src/testRunner/unittests/tscWatch/incremental.ts index 6c72a4bfe9c..e3be07691e1 100644 --- a/src/testRunner/unittests/tscWatch/incremental.ts +++ b/src/testRunner/unittests/tscWatch/incremental.ts @@ -8,13 +8,13 @@ namespace ts.tscWatch { }; interface VerifyIncrementalWatchEmitInput { - files: ReadonlyArray; + files: readonly File[]; optionsToExtend?: CompilerOptions; - expectedInitialEmit: ReadonlyArray; - expectedInitialErrors: ReadonlyArray; + expectedInitialEmit: readonly File[]; + expectedInitialErrors: readonly string[]; modifyFs?: (host: WatchedSystem) => void; - expectedIncrementalEmit?: ReadonlyArray; - expectedIncrementalErrors?: ReadonlyArray; + expectedIncrementalEmit?: readonly File[]; + expectedIncrementalErrors?: readonly string[]; } function verifyIncrementalWatchEmit(input: VerifyIncrementalWatchEmitInput) { it("with tsc --w", () => { @@ -52,7 +52,7 @@ namespace ts.tscWatch { interface VerifyIncrementalWatchEmitWorkerInput { input: VerifyIncrementalWatchEmitInput; emitAndReportErrors: (configFile: string, host: WatchedSystem, optionsToExtend?: CompilerOptions) => { close(): void; }; - verifyErrors: (host: WatchedSystem, errors: ReadonlyArray) => void; + verifyErrors: (host: WatchedSystem, errors: readonly string[]) => void; } function verifyIncrementalWatchEmitWorker({ input: { @@ -100,8 +100,8 @@ namespace ts.tscWatch { writtenFiles: Map; emitAndReportErrors: VerifyIncrementalWatchEmitWorkerInput["emitAndReportErrors"]; verifyErrors: VerifyIncrementalWatchEmitWorkerInput["verifyErrors"]; - expectedEmit: ReadonlyArray; - expectedErrors: ReadonlyArray; + expectedEmit: readonly File[]; + expectedErrors: readonly string[]; } function verifyBuild({ host, optionsToExtend, writtenFiles, emitAndReportErrors, @@ -120,7 +120,7 @@ namespace ts.tscWatch { return getBuildInfoText(buildInfo); } - function checkFileEmit(actual: Map, expected: ReadonlyArray) { + function checkFileEmit(actual: Map, expected: readonly File[]) { assert.equal(actual.size, expected.length, `Actual: ${JSON.stringify(arrayFrom(actual.entries()), /*replacer*/ undefined, " ")}\nExpected: ${JSON.stringify(expected, /*replacer*/ undefined, " ")}`); expected.forEach(file => { let expectedContent = file.content; diff --git a/src/testRunner/unittests/tscWatch/programUpdates.ts b/src/testRunner/unittests/tscWatch/programUpdates.ts index f9e6f0ae986..c303c7099ab 100644 --- a/src/testRunner/unittests/tscWatch/programUpdates.ts +++ b/src/testRunner/unittests/tscWatch/programUpdates.ts @@ -916,7 +916,7 @@ namespace ts.tscWatch { }); describe("should not trigger should not trigger recompilation because of program emit", () => { - function verifyWithOptions(options: CompilerOptions, outputFiles: ReadonlyArray) { + function verifyWithOptions(options: CompilerOptions, outputFiles: readonly string[]) { const proj = "/user/username/projects/myproject"; const file1: File = { path: `${proj}/file1.ts`, @@ -1056,14 +1056,14 @@ export default test;`; getDiagnosticOfFileFromProgram(watch(), bFile.path, bFile.content.indexOf("y /"), 1, Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type) ]); - function changeParameterType(parameterName: string, toType: string, expectedErrors: ReadonlyArray) { + function changeParameterType(parameterName: string, toType: string, expectedErrors: readonly Diagnostic[]) { const newContent = bFileContent.replace(new RegExp(`${parameterName}\: [a-z]*`), `${parameterName}: ${toType}`); verifyErrorsWithBFileContents(newContent, expectedErrors); verifyErrorsWithBFileContents(bFileContent, emptyArray); } - function verifyErrorsWithBFileContents(content: string, expectedErrors: ReadonlyArray) { + function verifyErrorsWithBFileContents(content: string, expectedErrors: readonly Diagnostic[]) { host.writeFile(bFile.path, content); host.runQueuedTimeoutCallbacks(); checkOutputErrorsIncremental(host, expectedErrors); @@ -1266,7 +1266,7 @@ interface Document { verifyConfigChange({ skipLibCheck: true }, [aFile]); verifyConfigChange({}, [libFileWithDocument, aFile, bFile]); - function verifyConfigChange(compilerOptions: CompilerOptions, errorInFiles: ReadonlyArray) { + function verifyConfigChange(compilerOptions: CompilerOptions, errorInFiles: readonly File[]) { host.writeFile(configFile.path, JSON.stringify({ compilerOptions })); host.runQueuedTimeoutCallbacks(); verifyProgramFiles(); diff --git a/src/testRunner/unittests/tscWatch/watchEnvironment.ts b/src/testRunner/unittests/tscWatch/watchEnvironment.ts index ad07d8d1610..d4fee6c2c8e 100644 --- a/src/testRunner/unittests/tscWatch/watchEnvironment.ts +++ b/src/testRunner/unittests/tscWatch/watchEnvironment.ts @@ -102,7 +102,7 @@ namespace ts.tscWatch { host.runQueuedTimeoutCallbacks(); verifyProgram(checkOutputErrorsIncremental); - function verifyProgram(checkOutputErrors: (host: WatchedSystem, errors: ReadonlyArray) => void) { + function verifyProgram(checkOutputErrors: (host: WatchedSystem, errors: readonly Diagnostic[]) => void) { checkProgramActualFiles(watch(), programFiles.map(f => f.path)); checkOutputErrors(host, emptyArray); diff --git a/src/testRunner/unittests/tsserver/cachingFileSystemInformation.ts b/src/testRunner/unittests/tsserver/cachingFileSystemInformation.ts index 9efb95dbc5a..31fdef1d20a 100644 --- a/src/testRunner/unittests/tsserver/cachingFileSystemInformation.ts +++ b/src/testRunner/unittests/tsserver/cachingFileSystemInformation.ts @@ -15,7 +15,7 @@ namespace ts.projectSystem { } type CalledMaps = CalledMapsWithSingleArg | CalledMapsWithFiveArgs; function createCallsTrackingHost(host: TestServerHost) { - const calledMaps: Record> & Record, ReadonlyArray, ReadonlyArray, number]>> = { + const calledMaps: Record> & Record> = { fileExists: setCallsTrackingWithSingleArgFn(CalledMapsWithSingleArg.fileExists), directoryExists: setCallsTrackingWithSingleArgFn(CalledMapsWithSingleArg.directoryExists), getDirectories: setCallsTrackingWithSingleArgFn(CalledMapsWithSingleArg.getDirectories), @@ -68,7 +68,7 @@ namespace ts.projectSystem { TestFSWithWatch.checkMultiMapKeyCount(callback, calledMaps[callback], expectedKeys); } - function verifyCalledOnEachEntryNTimes(callback: CalledMaps, expectedKeys: ReadonlyArray, nTimes: number) { + function verifyCalledOnEachEntryNTimes(callback: CalledMaps, expectedKeys: readonly string[], nTimes: number) { TestFSWithWatch.checkMultiMapKeyCount(callback, calledMaps[callback], expectedKeys, nTimes); } @@ -76,7 +76,7 @@ namespace ts.projectSystem { iterateOnCalledMaps(key => verifyNoCall(key)); } - function verifyNoHostCallsExceptFileExistsOnce(expectedKeys: ReadonlyArray) { + function verifyNoHostCallsExceptFileExistsOnce(expectedKeys: readonly string[]) { verifyCalledOnEachEntryNTimes(CalledMapsWithSingleArg.fileExists, expectedKeys, 1); verifyNoCall(CalledMapsWithSingleArg.directoryExists); verifyNoCall(CalledMapsWithSingleArg.getDirectories); diff --git a/src/testRunner/unittests/tsserver/completions.ts b/src/testRunner/unittests/tsserver/completions.ts index 1cd44539d68..1e50af89359 100644 --- a/src/testRunner/unittests/tsserver/completions.ts +++ b/src/testRunner/unittests/tsserver/completions.ts @@ -68,7 +68,7 @@ namespace ts.projectSystem { source: [{ text: "./a", kind: "text" }], tags: undefined, }; - assert.deepEqual | undefined>(detailsResponse, [ + assert.deepEqual(detailsResponse, [ { codeActions: [ { @@ -97,10 +97,10 @@ namespace ts.projectSystem { readonly arguments: protocol.CompletionDetailsRequestArgs; } interface CompletionDetailsFullResponse extends protocol.Response { - readonly body?: ReadonlyArray; + readonly body?: readonly CompletionEntryDetails[]; } const detailsFullResponse = executeSessionRequest(session, protocol.CommandTypes.CompletionDetailsFull, detailsRequestArgs); - assert.deepEqual | undefined>(detailsFullResponse, [ + assert.deepEqual(detailsFullResponse, [ { codeActions: [ { diff --git a/src/testRunner/unittests/tsserver/declarationFileMaps.ts b/src/testRunner/unittests/tsserver/declarationFileMaps.ts index 734af2a68fe..d1c64fe46ce 100644 --- a/src/testRunner/unittests/tsserver/declarationFileMaps.ts +++ b/src/testRunner/unittests/tsserver/declarationFileMaps.ts @@ -24,7 +24,7 @@ namespace ts.projectSystem { }; } - function checkDeclarationFiles(file: File, session: TestSession, expectedFiles: ReadonlyArray): void { + function checkDeclarationFiles(file: File, session: TestSession, expectedFiles: readonly File[]): void { openFilesForSession([file], session); const project = Debug.assertDefined(session.getProjectService().getDefaultProjectForFile(file.path as server.NormalizedPath, /*ensureProject*/ false)); const program = project.getCurrentProgram()!; @@ -282,7 +282,7 @@ namespace ts.projectSystem { it("navigateTo", () => { const session = makeSampleProjects(); const response = executeSessionRequest(session, CommandNames.Navto, { file: userTs.path, searchValue: "fn" }); - assert.deepEqual | undefined>(response, [ + assert.deepEqual(response, [ { ...protocolFileSpanFromSubstring({ file: bDts, @@ -328,7 +328,7 @@ namespace ts.projectSystem { contextText: "export function fnA() {}", lineText: "export function fnA() {}" }); - const referencesUserTs = (userTs: File): ReadonlyArray => [ + const referencesUserTs = (userTs: File): readonly protocol.ReferencesResponseItem[] => [ makeReferenceItem({ file: userTs, isDefinition: false, @@ -365,14 +365,14 @@ namespace ts.projectSystem { }); interface ReferencesFullRequest extends protocol.FileLocationRequest { readonly command: protocol.CommandTypes.ReferencesFull; } - interface ReferencesFullResponse extends protocol.Response { readonly body: ReadonlyArray; } + interface ReferencesFullResponse extends protocol.Response { readonly body: readonly ReferencedSymbol[]; } it("findAllReferencesFull", () => { const session = makeSampleProjects(); const responseFull = executeSessionRequest(session, protocol.CommandTypes.ReferencesFull, protocolFileLocationFromSubstring(userTs, "fnA()")); - assert.deepEqual>(responseFull, [ + assert.deepEqual(responseFull, [ { definition: { ...documentSpanFromSubstring({ @@ -425,7 +425,7 @@ namespace ts.projectSystem { const responseFull = executeSessionRequest(session, protocol.CommandTypes.ReferencesFull, protocolFileLocationFromSubstring(bTs, "f()")); - assert.deepEqual>(responseFull, [ + assert.deepEqual(responseFull, [ { definition: { ...documentSpanFromSubstring({ @@ -556,7 +556,7 @@ namespace ts.projectSystem { it("renameLocationsFull", () => { const session = makeSampleProjects(); const response = executeSessionRequest(session, protocol.CommandTypes.RenameLocationsFull, protocolFileLocationFromSubstring(userTs, "fnA()")); - assert.deepEqual>(response, [ + assert.deepEqual(response, [ renameLocation({ file: userTs, text: "fnA" }), renameLocation({ file: aTs, text: "fnA", contextText: "export function fnA() {}" }), ]); @@ -607,7 +607,7 @@ namespace ts.projectSystem { oldFilePath: aTs.path, newFilePath: "/a/aNew.ts", }); - assert.deepEqual>(response, [ + assert.deepEqual(response, [ { fileName: userTs.path, textChanges: [ @@ -651,7 +651,7 @@ namespace ts.projectSystem { oldFilePath: aTs.path, newFilePath: "/a/src/a1.ts", }); - assert.deepEqual>(response, []); // Should not change anything + assert.deepEqual(response, []); // Should not change anything }); }); } diff --git a/src/testRunner/unittests/tsserver/duplicatePackages.ts b/src/testRunner/unittests/tsserver/duplicatePackages.ts index ec85eb6a82f..3de23225cd7 100644 --- a/src/testRunner/unittests/tsserver/duplicatePackages.ts +++ b/src/testRunner/unittests/tsserver/duplicatePackages.ts @@ -31,7 +31,7 @@ namespace ts.projectSystem { endOffset: 4, errorCodes: [Diagnostics.Cannot_find_name_0.code], }); - assert.deepEqual | undefined>(response, [ + assert.deepEqual(response, [ { description: `Import 'foo' from module "foo"`, fixName: "import", diff --git a/src/testRunner/unittests/tsserver/events/projectLoading.ts b/src/testRunner/unittests/tsserver/events/projectLoading.ts index 7a881ff1380..cb22f41ff25 100644 --- a/src/testRunner/unittests/tsserver/events/projectLoading.ts +++ b/src/testRunner/unittests/tsserver/events/projectLoading.ts @@ -19,7 +19,7 @@ namespace ts.projectSystem { clearEvents: () => void; verifyProjectLoadEvents: (expected: [server.ProjectLoadingStartEvent, server.ProjectLoadingFinishEvent]) => void; }) { - function createSessionToVerifyEvent(files: ReadonlyArray) { + function createSessionToVerifyEvent(files: readonly File[]) { const host = createServerHost(files); const originalReadFile = host.readFile; const { session, getNumberOfEvents, clearEvents, verifyProjectLoadEvents } = createSession(host); diff --git a/src/testRunner/unittests/tsserver/events/projectUpdatedInBackground.ts b/src/testRunner/unittests/tsserver/events/projectUpdatedInBackground.ts index 05a43cb4a15..958202cdd19 100644 --- a/src/testRunner/unittests/tsserver/events/projectUpdatedInBackground.ts +++ b/src/testRunner/unittests/tsserver/events/projectUpdatedInBackground.ts @@ -1,6 +1,6 @@ namespace ts.projectSystem { describe("unittests:: tsserver:: events:: ProjectsUpdatedInBackground", () => { - function verifyFiles(caption: string, actual: ReadonlyArray, expected: ReadonlyArray) { + function verifyFiles(caption: string, actual: readonly string[], expected: readonly string[]) { assert.equal(actual.length, expected.length, `Incorrect number of ${caption}. Actual: ${actual} Expected: ${expected}`); const seen = createMap(); forEach(actual, f => { @@ -528,11 +528,11 @@ namespace ts.projectSystem { return JSON.stringify(event && { eventName: event.eventName, data: event.data }); } - function eventsToString(events: ReadonlyArray) { + function eventsToString(events: readonly server.ProjectsUpdatedInBackgroundEvent[]) { return "[" + map(events, eventToString).join(",") + "]"; } - function verifyProjectsUpdatedInBackgroundEventHandler(expectedEvents: ReadonlyArray) { + function verifyProjectsUpdatedInBackgroundEventHandler(expectedEvents: readonly server.ProjectsUpdatedInBackgroundEvent[]) { assert.equal(projectChangedEvents.length, expectedEvents.length, `Incorrect number of events Actual: ${eventsToString(projectChangedEvents)} Expected: ${eventsToString(expectedEvents)}`); forEach(projectChangedEvents, (actualEvent, i) => { const expectedEvent = expectedEvents[i]; @@ -565,7 +565,7 @@ namespace ts.projectSystem { verifyInitialOpen: createVerifyInitialOpen(session, verifyProjectsUpdatedInBackgroundEventHandler) }; - function verifyProjectsUpdatedInBackgroundEventHandler(expected: ReadonlyArray) { + function verifyProjectsUpdatedInBackgroundEventHandler(expected: readonly server.ProjectsUpdatedInBackgroundEvent[]) { const expectedEvents: protocol.ProjectsUpdatedInBackgroundEventBody[] = map(expected, e => { return { openFiles: e.data.openFiles diff --git a/src/testRunner/unittests/tsserver/getApplicableRefactors.ts b/src/testRunner/unittests/tsserver/getApplicableRefactors.ts index 1f9576e1d63..bec4a654560 100644 --- a/src/testRunner/unittests/tsserver/getApplicableRefactors.ts +++ b/src/testRunner/unittests/tsserver/getApplicableRefactors.ts @@ -6,7 +6,7 @@ namespace ts.projectSystem { openFilesForSession([aTs], session); const response = executeSessionRequest( session, protocol.CommandTypes.GetApplicableRefactors, { file: aTs.path, line: 1, offset: 1 }); - assert.deepEqual | undefined>(response, []); + assert.deepEqual(response, []); }); }); } diff --git a/src/testRunner/unittests/tsserver/getEditsForFileRename.ts b/src/testRunner/unittests/tsserver/getEditsForFileRename.ts index 2b28de7b121..5dcd3e96fdb 100644 --- a/src/testRunner/unittests/tsserver/getEditsForFileRename.ts +++ b/src/testRunner/unittests/tsserver/getEditsForFileRename.ts @@ -22,7 +22,7 @@ namespace ts.projectSystem { Debug.assert(!!project.resolveModuleNames); const edits = project.getLanguageService().getEditsForFileRename("/old.ts", "/new.ts", testFormatSettings, emptyOptions); - assert.deepEqual>(edits, [{ + assert.deepEqual(edits, [{ fileName: "/user.ts", textChanges: [{ span: textSpanFromSubstring(userTs.content, "./old"), @@ -61,7 +61,7 @@ namespace ts.projectSystem { oldFilePath: aOldTs.path, newFilePath: "/a/new.ts", }); - assert.deepEqual>(response, [ + assert.deepEqual(response, [ { fileName: aTsconfig.path, textChanges: [{ ...protocolTextSpanFromSubstring(aTsconfig.content, "./old.ts"), newText: "new.ts" }], @@ -90,7 +90,7 @@ namespace ts.projectSystem { oldFilePath: "/b.ts", newFilePath: cTs.path, }); - assert.deepEqual>(response, [ + assert.deepEqual(response, [ { fileName: "/tsconfig.json", textChanges: [{ ...protocolTextSpanFromSubstring(tsconfig.content, "./b.ts"), newText: "c.ts" }], diff --git a/src/testRunner/unittests/tsserver/helpers.ts b/src/testRunner/unittests/tsserver/helpers.ts index 22a091d3937..1fb35935906 100644 --- a/src/testRunner/unittests/tsserver/helpers.ts +++ b/src/testRunner/unittests/tsserver/helpers.ts @@ -223,7 +223,7 @@ namespace ts.projectSystem { this.service = this.session.getProjectService(); } - getEvents(): ReadonlyArray { + getEvents(): readonly server.ProjectServiceEvent[] { const events = this.events; this.events = []; return events; @@ -248,7 +248,7 @@ namespace ts.projectSystem { this.events.forEach(event => assert.notEqual(event.eventName, eventName)); } - checkSingleConfigFileDiagEvent(configFileName: string, triggerFile: string, errors: ReadonlyArray) { + checkSingleConfigFileDiagEvent(configFileName: string, triggerFile: string, errors: readonly ConfigFileDiagnostic[]) { const eventData = this.getEvent(server.ConfigFileDiagEvent); assert.equal(eventData.configFileName, configFileName); assert.equal(eventData.triggerFile, triggerFile); @@ -447,11 +447,11 @@ namespace ts.projectSystem { return iterResult.value; } - export function checkProjectActualFiles(project: server.Project, expectedFiles: ReadonlyArray) { + export function checkProjectActualFiles(project: server.Project, expectedFiles: readonly string[]) { checkArray(`${server.ProjectKind[project.projectKind]} project, actual files`, project.getFileNames(), expectedFiles); } - export function checkProjectRootFiles(project: server.Project, expectedFiles: ReadonlyArray) { + export function checkProjectRootFiles(project: server.Project, expectedFiles: readonly string[]) { checkArray(`${server.ProjectKind[project.projectKind]} project, rootFileNames`, project.getRootFiles(), expectedFiles); } @@ -491,7 +491,7 @@ namespace ts.projectSystem { checkArray("Open files", arrayFrom(projectService.openFiles.keys(), path => projectService.getScriptInfoForPath(path as Path)!.fileName), expectedFiles.map(file => file.path)); } - export function checkScriptInfos(projectService: server.ProjectService, expectedFiles: ReadonlyArray) { + export function checkScriptInfos(projectService: server.ProjectService, expectedFiles: readonly string[]) { checkArray("ScriptInfos files", arrayFrom(projectService.filenameToScriptInfo.values(), info => info.fileName), expectedFiles); } @@ -664,14 +664,14 @@ namespace ts.projectSystem { session.executeCommand(makeSessionRequest(command, args)); } - export function openFilesForSession(files: ReadonlyArray, session: server.Session): void { + export function openFilesForSession(files: readonly (File | { readonly file: File | string, readonly projectRootPath: string })[], session: server.Session): void { for (const file of files) { session.executeCommand(makeSessionRequest(CommandNames.Open, "projectRootPath" in file ? { file: typeof file.file === "string" ? file.file : file.file.path, projectRootPath: file.projectRootPath } : { file: file.path })); // eslint-disable-line no-in-operator } } - export function closeFilesForSession(files: ReadonlyArray, session: server.Session): void { + export function closeFilesForSession(files: readonly File[], session: server.Session): void { for (const file of files) { session.executeCommand(makeSessionRequest(CommandNames.Close, { file: file.path })); } @@ -686,7 +686,7 @@ namespace ts.projectSystem { return formatStringFromArgs(diagnosticMessage.message, errorTextArguments); } - export function verifyDiagnostics(actual: ReadonlyArray, expected: ReadonlyArray) { + export function verifyDiagnostics(actual: readonly server.protocol.Diagnostic[], expected: readonly ErrorInformation[]) { const expectedErrors = expected.map(getProtocolDiagnosticMessage); assert.deepEqual(actual.map(diag => flattenDiagnosticMessageText(diag.text, "\n")), expectedErrors); } @@ -699,7 +699,7 @@ namespace ts.projectSystem { checkNthEvent(session, server.toEvent(eventName, diagnostics), 0, isMostRecent); } - export function createDiagnostic(start: protocol.Location, end: protocol.Location, message: DiagnosticMessage, args: ReadonlyArray = [], category = diagnosticCategoryName(message), reportsUnnecessary?: {}, relatedInformation?: protocol.DiagnosticRelatedInformation[]): protocol.Diagnostic { + export function createDiagnostic(start: protocol.Location, end: protocol.Location, message: DiagnosticMessage, args: readonly string[] = [], category = diagnosticCategoryName(message), reportsUnnecessary?: {}, relatedInformation?: protocol.DiagnosticRelatedInformation[]): protocol.Diagnostic { return { start, end, text: formatStringFromArgs(message.message, args), code: message.code, category, reportsUnnecessary, relatedInformation, source: undefined }; } diff --git a/src/testRunner/unittests/tsserver/metadataInResponse.ts b/src/testRunner/unittests/tsserver/metadataInResponse.ts index a2df56e6ee5..10b1c58d737 100644 --- a/src/testRunner/unittests/tsserver/metadataInResponse.ts +++ b/src/testRunner/unittests/tsserver/metadataInResponse.ts @@ -24,7 +24,7 @@ namespace ts.projectSystem { compilerOptions: { plugins: [{ name: "myplugin" }] } }) }; - function createHostWithPlugin(files: ReadonlyArray) { + function createHostWithPlugin(files: readonly File[]) { const host = createServerHost(files); host.require = (_initialPath, moduleName) => { assert.equal(moduleName, "myplugin"); @@ -54,7 +54,7 @@ namespace ts.projectSystem { line: 1, offset: aTs.content.indexOf("this.") + 1 + "this.".length }; - const expectedCompletionEntries: ReadonlyArray = [ + const expectedCompletionEntries: readonly protocol.CompletionEntry[] = [ { name: "foo", kind: ScriptElementKind.memberFunctionElement, kindModifiers: "", sortText: "0" }, { name: "prop", kind: ScriptElementKind.memberVariableElement, kindModifiers: "", sortText: "0" } ]; @@ -63,7 +63,7 @@ namespace ts.projectSystem { const host = createHostWithPlugin([aTs, tsconfig]); const session = createSession(host); openFilesForSession([aTs], session); - verifyCommandWithMetadata>(session, host, { + verifyCommandWithMetadata(session, host, { command: protocol.CommandTypes.Completions, arguments: completionRequestArgs }, expectedCompletionEntries); diff --git a/src/testRunner/unittests/tsserver/projectErrors.ts b/src/testRunner/unittests/tsserver/projectErrors.ts index 10e6d3b972d..86e772bebb5 100644 --- a/src/testRunner/unittests/tsserver/projectErrors.ts +++ b/src/testRunner/unittests/tsserver/projectErrors.ts @@ -1,11 +1,11 @@ namespace ts.projectSystem { describe("unittests:: tsserver:: Project Errors", () => { - function checkProjectErrors(projectFiles: server.ProjectFilesWithTSDiagnostics, expectedErrors: ReadonlyArray): void { + function checkProjectErrors(projectFiles: server.ProjectFilesWithTSDiagnostics, expectedErrors: readonly string[]): void { assert.isTrue(projectFiles !== undefined, "missing project files"); checkProjectErrorsWorker(projectFiles.projectErrors, expectedErrors); } - function checkProjectErrorsWorker(errors: ReadonlyArray, expectedErrors: ReadonlyArray): void { + function checkProjectErrorsWorker(errors: readonly Diagnostic[], expectedErrors: readonly string[]): void { assert.equal(errors ? errors.length : 0, expectedErrors.length, `expected ${expectedErrors.length} error in the list`); if (expectedErrors.length) { for (let i = 0; i < errors.length; i++) { @@ -774,7 +774,7 @@ declare module '@custom/plugin' { command: server.CommandNames.CompilerOptionsDiagnosticsFull, seq: 2, arguments: { projectFileName: projectName } - }).response as ReadonlyArray; + }).response as readonly protocol.DiagnosticWithLinePosition[]; assert.isTrue(diags.length === 0); session.executeCommand({ @@ -788,7 +788,7 @@ declare module '@custom/plugin' { command: server.CommandNames.CompilerOptionsDiagnosticsFull, seq: 4, arguments: { projectFileName: projectName } - }).response as ReadonlyArray; + }).response as readonly protocol.DiagnosticWithLinePosition[]; assert.isTrue(diagsAfterUpdate.length === 0); }); @@ -815,7 +815,7 @@ declare module '@custom/plugin' { command: server.CommandNames.CompilerOptionsDiagnosticsFull, seq: 2, arguments: { projectFileName } - }).response as ReadonlyArray; + }).response as readonly server.protocol.DiagnosticWithLinePosition[]; assert.isTrue(diags.length === 0); session.executeCommand({ @@ -833,7 +833,7 @@ declare module '@custom/plugin' { command: server.CommandNames.CompilerOptionsDiagnosticsFull, seq: 4, arguments: { projectFileName } - }).response as ReadonlyArray; + }).response as readonly server.protocol.DiagnosticWithLinePosition[]; assert.isTrue(diagsAfterUpdate.length === 0); }); }); @@ -873,7 +873,7 @@ declare module '@custom/plugin' { command: server.CommandNames.SemanticDiagnosticsSync, seq: 2, arguments: { file: configFile.path, projectFileName: projectName, includeLinePosition: true } - }).response as ReadonlyArray; + }).response as readonly server.protocol.DiagnosticWithLinePosition[]; assert.isTrue(diags.length === 2); configFile.content = configFileContentWithoutCommentLine; @@ -884,7 +884,7 @@ declare module '@custom/plugin' { command: server.CommandNames.SemanticDiagnosticsSync, seq: 2, arguments: { file: configFile.path, projectFileName: projectName, includeLinePosition: true } - }).response as ReadonlyArray; + }).response as readonly server.protocol.DiagnosticWithLinePosition[]; assert.isTrue(diagsAfterEdit.length === 2); verifyDiagnostic(diags[0], diagsAfterEdit[0]); diff --git a/src/testRunner/unittests/tsserver/projectReferences.ts b/src/testRunner/unittests/tsserver/projectReferences.ts index 4941c650d99..7db9d755b26 100644 --- a/src/testRunner/unittests/tsserver/projectReferences.ts +++ b/src/testRunner/unittests/tsserver/projectReferences.ts @@ -1,6 +1,6 @@ namespace ts.projectSystem { describe("unittests:: tsserver:: with project references and tsbuild", () => { - function createHost(files: ReadonlyArray, rootNames: ReadonlyArray) { + function createHost(files: readonly File[], rootNames: readonly string[]) { const host = createServerHost(files); // ts build should succeed @@ -150,12 +150,12 @@ fn5(); const files = [dependencyTs, dependencyConfig, mainTs, mainConfig, libFile, randomFile, randomConfig]; - function verifyScriptInfos(session: TestSession, host: TestServerHost, openInfos: ReadonlyArray, closedInfos: ReadonlyArray, otherWatchedFiles: ReadonlyArray) { + function verifyScriptInfos(session: TestSession, host: TestServerHost, openInfos: readonly string[], closedInfos: readonly string[], otherWatchedFiles: readonly string[]) { checkScriptInfos(session.getProjectService(), openInfos.concat(closedInfos)); checkWatchedFiles(host, closedInfos.concat(otherWatchedFiles).map(f => f.toLowerCase())); } - function verifyInfosWithRandom(session: TestSession, host: TestServerHost, openInfos: ReadonlyArray, closedInfos: ReadonlyArray, otherWatchedFiles: ReadonlyArray) { + function verifyInfosWithRandom(session: TestSession, host: TestServerHost, openInfos: readonly string[], closedInfos: readonly string[], otherWatchedFiles: readonly string[]) { verifyScriptInfos(session, host, openInfos.concat(randomFile.path), closedInfos, otherWatchedFiles.concat(randomConfig.path)); } @@ -281,14 +281,14 @@ fn5(); // Open File, expectedProjectActualFiles, actionGetter, openFileLastLine interface DocumentPositionMapperVerifier { openFile: File; - expectedProjectActualFiles: ReadonlyArray; + expectedProjectActualFiles: readonly string[]; actionGetter: SessionActionGetter; openFileLastLine: number; } function verifyDocumentPositionMapperUpdates( mainScenario: string, - verifier: ReadonlyArray, - closedInfos: ReadonlyArray, + verifier: readonly DocumentPositionMapperVerifier[], + closedInfos: readonly string[], withRefs: boolean) { const openFiles = verifier.map(v => v.openFile); diff --git a/src/testRunner/unittests/tsserver/resolutionCache.ts b/src/testRunner/unittests/tsserver/resolutionCache.ts index e9be75b90c1..85af2bb36b0 100644 --- a/src/testRunner/unittests/tsserver/resolutionCache.ts +++ b/src/testRunner/unittests/tsserver/resolutionCache.ts @@ -602,7 +602,7 @@ namespace ts.projectSystem { return `Reusing resolution of module '${moduleName}' to file '${file.path}' from old program.`; } - function verifyWatchesWithConfigFile(host: TestServerHost, files: File[], openFile: File, extraExpectedDirectories?: ReadonlyArray) { + function verifyWatchesWithConfigFile(host: TestServerHost, files: File[], openFile: File, extraExpectedDirectories?: readonly string[]) { const expectedRecursiveDirectories = arrayToSet([projectLocation, `${projectLocation}/${nodeModulesAtTypes}`, ...(extraExpectedDirectories || emptyArray)]); checkWatchedFiles(host, mapDefined(files, f => { if (f === openFile) { diff --git a/src/testRunner/unittests/tsserver/typingsInstaller.ts b/src/testRunner/unittests/tsserver/typingsInstaller.ts index 79b4f01aa06..0428055bba5 100644 --- a/src/testRunner/unittests/tsserver/typingsInstaller.ts +++ b/src/testRunner/unittests/tsserver/typingsInstaller.ts @@ -1005,7 +1005,7 @@ namespace ts.projectSystem { content: "module.exports = 0", }; - const typeNames: ReadonlyArray = ["commander"]; + const typeNames: readonly string[] = ["commander"]; const typePath = (name: string): string => `${cachePath}/node_modules/@types/${name}/index.d.ts`; const host = createServerHost([file, commanderJS]); const installer = new (class extends Installer { diff --git a/src/testRunner/unittests/tsserver/untitledFiles.ts b/src/testRunner/unittests/tsserver/untitledFiles.ts index 845a53eb218..7f5c36ac6e2 100644 --- a/src/testRunner/unittests/tsserver/untitledFiles.ts +++ b/src/testRunner/unittests/tsserver/untitledFiles.ts @@ -23,7 +23,7 @@ namespace ts.projectSystem { endOffset: 5, errorCodes: [Diagnostics.Cannot_find_name_0_Did_you_mean_1.code], }); - assert.deepEqual | undefined>(response, [ + assert.deepEqual(response, [ { description: "Change spelling to 'foo'", fixAllDescription: "Fix all detected spelling errors", diff --git a/src/tsc/tsc.ts b/src/tsc/tsc.ts index 50953f86ae7..fc75e28d504 100644 --- a/src/tsc/tsc.ts +++ b/src/tsc/tsc.ts @@ -235,7 +235,7 @@ namespace ts { undefined; } - function performCompilation(rootNames: string[], projectReferences: ReadonlyArray | undefined, options: CompilerOptions, configFileParsingDiagnostics?: ReadonlyArray) { + function performCompilation(rootNames: string[], projectReferences: readonly ProjectReference[] | undefined, options: CompilerOptions, configFileParsingDiagnostics?: readonly Diagnostic[]) { const host = createCompilerHost(options); const currentDirectory = host.getCurrentDirectory(); const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames()); diff --git a/src/tsserver/server.ts b/src/tsserver/server.ts index 8f373764878..f8b183dcc06 100644 --- a/src/tsserver/server.ts +++ b/src/tsserver/server.ts @@ -939,7 +939,7 @@ namespace ts.server { const npmLocation = findArgument(Arguments.NpmLocation); const validateDefaultNpmLocation = hasArgument(Arguments.ValidateDefaultNpmLocation); - function parseStringArray(argName: string): ReadonlyArray { + function parseStringArray(argName: string): readonly string[] { const arg = findArgument(argName); if (arg === undefined) { return emptyArray; diff --git a/src/typingsInstallerCore/typingsInstaller.ts b/src/typingsInstallerCore/typingsInstaller.ts index 447a9aa7f04..2b94b887420 100644 --- a/src/typingsInstallerCore/typingsInstaller.ts +++ b/src/typingsInstallerCore/typingsInstaller.ts @@ -267,7 +267,7 @@ namespace ts.server.typingsInstaller { this.knownCachesSet.set(cacheLocation, true); } - private filterTypings(typingsToInstall: ReadonlyArray): ReadonlyArray { + private filterTypings(typingsToInstall: readonly string[]): readonly string[] { return mapDefined(typingsToInstall, typing => { const typingKey = mangleScopedPackageName(typing); if (this.missingTypingsSet.get(typingKey)) {