diff --git a/scripts/processDiagnosticMessages.mjs b/scripts/processDiagnosticMessages.mjs index 85f029e1d3765..f66c30996feca 100644 --- a/scripts/processDiagnosticMessages.mjs +++ b/scripts/processDiagnosticMessages.mjs @@ -92,6 +92,7 @@ function buildInfoFileOutput(messageTable, inputFilePathRel) { " return { code, category, key, message, reportsUnnecessary, elidedInCompatabilityPyramid, reportsDeprecated };", "}", "", + "/* eslint-disable @typescript-eslint/no-unnecessary-type-assertion*/", // type assertions are needed for isolatedDeclarations "/** @internal */", "export const Diagnostics = {", ]; @@ -101,7 +102,7 @@ function buildInfoFileOutput(messageTable, inputFilePathRel) { const argElidedInCompatabilityPyramid = elidedInCompatabilityPyramid ? `${!reportsUnnecessary ? ", /*reportsUnnecessary*/ undefined" : ""}, /*elidedInCompatabilityPyramid*/ ${elidedInCompatabilityPyramid}` : ""; const argReportsDeprecated = reportsDeprecated ? `${!argElidedInCompatabilityPyramid ? ", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined" : ""}, /*reportsDeprecated*/ ${reportsDeprecated}` : ""; - result.push(` ${propName}: diag(${code}, DiagnosticCategory.${category}, "${createKey(propName, code)}", ${JSON.stringify(name)}${argReportsUnnecessary}${argElidedInCompatabilityPyramid}${argReportsDeprecated}),`); + result.push(` ${propName}: diag(${code}, DiagnosticCategory.${category}, "${createKey(propName, code)}", ${JSON.stringify(name)}${argReportsUnnecessary}${argElidedInCompatabilityPyramid}${argReportsDeprecated}) satisfies DiagnosticMessage as DiagnosticMessage,`); }); result.push("};"); diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 1666c90883e80..7f61986a80fb8 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -509,7 +509,7 @@ export function createFlowNode(flags: FlowFlags, node: unknown, antecedent: Flow const binder = /* @__PURE__ */ createBinder(); /** @internal */ -export function bindSourceFile(file: SourceFile, options: CompilerOptions) { +export function bindSourceFile(file: SourceFile, options: CompilerOptions): void { performance.mark("beforeBind"); binder(file, options); performance.mark("afterBind"); diff --git a/src/compiler/builder.ts b/src/compiler/builder.ts index 6b0d7a24b3f2f..40d3fca7ac2a7 100644 --- a/src/compiler/builder.ts +++ b/src/compiler/builder.ts @@ -277,7 +277,7 @@ function toBuilderProgramStateWithDefinedProgram(state: ReusableBuilderProgramSt * * @internal */ -export function getBuilderFileEmit(options: CompilerOptions) { +export function getBuilderFileEmit(options: CompilerOptions): BuilderFileEmit { let result = BuilderFileEmit.Js; if (options.sourceMap) result = result | BuilderFileEmit.JsMap; if (options.inlineSourceMap) result = result | BuilderFileEmit.JsInlineMap; @@ -733,7 +733,7 @@ export function getPendingEmitKindWithSeen( seenOldOptionsOrEmitKind: CompilerOptions | BuilderFileEmit | undefined, emitOnlyDtsFiles: boolean | undefined, isForDtsErrors: boolean, -) { +): BuilderFileEmit { let pendingKind = getPendingEmitKind(optionsOrEmitKind, seenOldOptionsOrEmitKind); if (emitOnlyDtsFiles) pendingKind = pendingKind & BuilderFileEmit.AllDts; if (isForDtsErrors) pendingKind = pendingKind & BuilderFileEmit.DtsErrors; @@ -1623,7 +1623,7 @@ export function computeSignatureWithDiagnostics( text: string, host: HostForComputeHash, data: WriteFileCallbackData | undefined, -) { +): string { text = getTextHandlingSourceMapForSignature(text, data); let sourceFileDirectory: string | undefined; if (data?.diagnostics?.length) { @@ -2395,7 +2395,10 @@ export function getBuildInfoFileVersionMap( program: IncrementalBuildInfo, buildInfoPath: string, host: Pick, -) { +): { + fileInfos: Map; + roots: Map; +} { const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames()); const fileInfos = new Map(); @@ -2440,7 +2443,7 @@ export function getNonIncrementalBuildInfoRoots( buildInfo: BuildInfo, buildInfoPath: string, host: Pick, -) { +): Path[] | undefined { if (!isNonIncrementalBuildInfo(buildInfo)) return undefined; const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames()); diff --git a/src/compiler/builderState.ts b/src/compiler/builderState.ts index 0e571d233d7e8..cf9932e94631b 100644 --- a/src/compiler/builderState.ts +++ b/src/compiler/builderState.ts @@ -292,11 +292,11 @@ export namespace BuilderState { /** * Returns true if oldState is reusable, that is the emitKind = module/non module has not changed */ - export function canReuseOldState(newReferencedMap: ReadonlyManyToManyPathMap | undefined, oldState: BuilderState | undefined) { + export function canReuseOldState(newReferencedMap: ReadonlyManyToManyPathMap | undefined, oldState: BuilderState | undefined): boolean | undefined { return oldState && !oldState.referencedMap === !newReferencedMap; } - export function createReferencedMap(options: CompilerOptions) { + export function createReferencedMap(options: CompilerOptions): ManyToManyPathMap | undefined { return options.module !== ModuleKind.None && !options.outFile ? createManyToManyPathMap() : undefined; @@ -346,7 +346,7 @@ export namespace BuilderState { /** * Releases needed properties */ - export function releaseCache(state: BuilderState) { + export function releaseCache(state: BuilderState): void { state.allFilesExcludingDefaultLibraryFile = undefined; state.allFileNames = undefined; } @@ -391,7 +391,7 @@ export namespace BuilderState { return (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, cancellationToken, host); } - export function updateSignatureOfFile(state: BuilderState, signature: string | undefined, path: Path) { + export function updateSignatureOfFile(state: BuilderState, signature: string | undefined, path: Path): void { state.fileInfos.get(path)!.signature = signature; (state.hasCalledUpdateShapeSignature ||= new Set()).add(path); } @@ -402,7 +402,7 @@ export namespace BuilderState { cancellationToken: CancellationToken | undefined, host: HostForComputeHash, onNewSignature: (signature: string, sourceFiles: readonly SourceFile[]) => void, - ) { + ): void { programOfThisState.emit( sourceFile, (fileName, text, _writeByteOrderMark, _onError, sourceFiles, data) => { @@ -434,8 +434,8 @@ export namespace BuilderState { sourceFile: SourceFile, cancellationToken: CancellationToken | undefined, host: HostForComputeHash, - useFileVersionAsSignature = state.useFileVersionAsSignature, - ) { + useFileVersionAsSignature: boolean | undefined = state.useFileVersionAsSignature, + ): boolean { // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate if (state.hasCalledUpdateShapeSignature?.has(sourceFile.resolvedPath)) return false; @@ -507,7 +507,7 @@ export namespace BuilderState { /** * Gets the files referenced by the the file path */ - export function getReferencedByPaths(state: Readonly, referencedFilePath: Path) { + export function getReferencedByPaths(state: Readonly, referencedFilePath: Path): Path[] { const keys = state.referencedMap!.getKeys(referencedFilePath); return keys ? arrayFrom(keys.keys()) : []; } diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index a6561122df5fe..3bd8265d103df 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -1449,7 +1449,7 @@ export function getSymbolId(symbol: Symbol): SymbolId { } /** @internal */ -export function isInstantiatedModule(node: ModuleDeclaration, preserveConstEnums: boolean) { +export function isInstantiatedModule(node: ModuleDeclaration, preserveConstEnums: boolean): boolean { const moduleState = getModuleInstanceState(node); return moduleState === ModuleInstanceState.Instantiated || (preserveConstEnums && moduleState === ModuleInstanceState.ConstEnumOnly); @@ -52687,7 +52687,7 @@ function getIterationTypesKeyFromIterationTypeKind(typeKind: IterationTypeKind) } /** @internal */ -export function signatureHasRestParameter(s: Signature) { +export function signatureHasRestParameter(s: Signature): boolean { return !!(s.flags & SignatureFlags.HasRestParameter); } diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 9797d9f96cc66..4a55972d28cda 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -138,7 +138,7 @@ const jsxOptionMap = new Map(Object.entries({ })); /** @internal */ -export const inverseJsxOptionMap = new Map(mapIterator(jsxOptionMap.entries(), ([key, value]: [string, JsxEmit]) => ["" + value, key] as const)); +export const inverseJsxOptionMap: Map = new Map(mapIterator(jsxOptionMap.entries(), ([key, value]: [string, JsxEmit]) => ["" + value, key] as const)); // NOTE: The order here is important to default lib ordering as entries will have the same // order in the generated program (see `getDefaultLibPriority` in program.ts). This @@ -248,7 +248,7 @@ const libEntries: [string, string][] = [ * * @internal */ -export const libs = libEntries.map(entry => entry[0]); +export const libs: string[] = libEntries.map(entry => entry[0]); /** * A map of lib names to lib files. This map is used both for parsing the "lib" command line @@ -256,7 +256,7 @@ export const libs = libEntries.map(entry => entry[0]); * * @internal */ -export const libMap = new Map(libEntries); +export const libMap: Map = new Map(libEntries); // Watch related options @@ -1797,7 +1797,7 @@ function createDiagnosticForInvalidCustomType(opt: CommandLineOptionOfCustomType } /** @internal */ -export function parseCustomTypeOption(opt: CommandLineOptionOfCustomType, value: string | undefined, errors: Diagnostic[]) { +export function parseCustomTypeOption(opt: CommandLineOptionOfCustomType, value: string | undefined, errors: Diagnostic[]): string | number | undefined { return convertJsonOptionOfCustomType(opt, (value ?? "").trim(), errors); } @@ -1864,7 +1864,12 @@ export function parseCommandLineWorker( diagnostics: ParseCommandLineWorkerDiagnostics, commandLine: readonly string[], readFile?: (path: string) => string | undefined, -) { +): { + options: OptionsBase; + watchOptions: WatchOptions | undefined; + fileNames: string[]; + errors: Diagnostic[]; +} { const options = {} as OptionsBase; let watchOptions: WatchOptions | undefined; const fileNames: string[] = []; @@ -2856,7 +2861,7 @@ export function generateTSConfig(options: CompilerOptions, fileNames: readonly s } /** @internal */ -export function convertToOptionsWithAbsolutePaths(options: CompilerOptions, toAbsolutePath: (path: string) => string) { +export function convertToOptionsWithAbsolutePaths(options: CompilerOptions, toAbsolutePath: (path: string) => string): CompilerOptions { const result: CompilerOptions = {}; const optionsNameMap = getOptionsNameMap().optionsNameMap; @@ -2917,7 +2922,7 @@ export function parseJsonSourceFileConfigFileContent(sourceFile: TsConfigSourceF } /** @internal */ -export function setConfigFileInOptions(options: CompilerOptions, configFile: TsConfigSourceFile | undefined) { +export function setConfigFileInOptions(options: CompilerOptions, configFile: TsConfigSourceFile | undefined): void { if (configFile) { Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile }); } @@ -3234,12 +3239,12 @@ function shouldReportNoInputFiles(fileNames: string[], canJsonReportNoInutFiles: } /** @internal */ -export function canJsonReportNoInputFiles(raw: any) { +export function canJsonReportNoInputFiles(raw: any): boolean { return !hasProperty(raw, "files") && !hasProperty(raw, "references"); } /** @internal */ -export function updateErrorForNoInputFiles(fileNames: string[], configFileName: string, configFileSpecs: ConfigFileSpecs, configParseDiagnostics: Diagnostic[], canJsonReportNoInutFiles: boolean) { +export function updateErrorForNoInputFiles(fileNames: string[], configFileName: string, configFileSpecs: ConfigFileSpecs, configParseDiagnostics: Diagnostic[], canJsonReportNoInutFiles: boolean): boolean { const existingErrors = configParseDiagnostics.length; if (shouldReportNoInputFiles(fileNames, canJsonReportNoInutFiles)) { configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName)); @@ -3927,7 +3932,7 @@ export function matchesExclude( excludeSpecs: readonly string[] | undefined, useCaseSensitiveFileNames: boolean, currentDirectory: string, -) { +): boolean { return matchesExcludeWorker( pathToCheck, filter(excludeSpecs, spec => !invalidDotDotAfterRecursiveWildcard(spec)), diff --git a/src/compiler/core.ts b/src/compiler/core.ts index fc692f1a65d2b..abb546f844212 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -329,7 +329,7 @@ export function map(array: readonly T[] | undefined, f: (x: T, i: number) } /** @internal */ -export function* mapIterator(iter: Iterable, mapFn: (x: T) => U) { +export function* mapIterator(iter: Iterable, mapFn: (x: T) => U): Generator { for (const x of iter) { yield mapFn(x); } @@ -434,7 +434,7 @@ export function flatMapToMutable(array: readonly T[] | undefined, mapfn: ( } /** @internal */ -export function* flatMapIterator(iter: Iterable, mapfn: (x: T) => readonly U[] | Iterable | undefined) { +export function* flatMapIterator(iter: Iterable, mapfn: (x: T) => readonly U[] | Iterable | undefined): Generator { for (const x of iter) { const iter2 = mapfn(x); if (!iter2) continue; @@ -505,7 +505,8 @@ export function mapDefined(array: readonly T[] | undefined, mapFn: (x: T, } /** @internal */ -export function* mapDefinedIterator(iter: Iterable, mapFn: (x: T) => U | undefined) { +// eslint-disable-next-line no-restricted-syntax +export function* mapDefinedIterator(iter: Iterable, mapFn: (x: T) => U | undefined): Generator { for (const x of iter) { const value = mapFn(x); if (value !== undefined) { @@ -515,7 +516,7 @@ export function* mapDefinedIterator(iter: Iterable, mapFn: (x: T) => U } /** @internal */ -export function getOrUpdate(map: Map, key: K, callback: () => V) { +export function getOrUpdate(map: Map, key: K, callback: () => V): V { if (map.has(key)) { return map.get(key)!; } @@ -525,7 +526,7 @@ export function getOrUpdate(map: Map, key: K, callback: () => V) { } /** @internal */ -export function tryAddToSet(set: Set, value: T) { +export function tryAddToSet(set: Set, value: T): boolean { if (!set.has(value)) { set.add(value); return true; @@ -534,7 +535,7 @@ export function tryAddToSet(set: Set, value: T) { } /** @internal */ -export function* singleIterator(value: T) { +export function* singleIterator(value: T): Generator { yield value; } @@ -1039,14 +1040,14 @@ export function toSorted(array: readonly T[], comparer?: Comparer): Sorted } /** @internal */ -export function* arrayReverseIterator(array: readonly T[]) { +export function* arrayReverseIterator(array: readonly T[]): Generator { for (let i = array.length - 1; i >= 0; i--) { yield array[i]; } } /** @internal */ -export function rangeEquals(array1: readonly T[], array2: readonly T[], pos: number, end: number) { +export function rangeEquals(array1: readonly T[], array2: readonly T[], pos: number, end: number): boolean { while (pos < end) { if (array1[pos] !== array2[pos]) { return false; @@ -1346,7 +1347,7 @@ export function arrayFrom(iterator: Iterable, map?: (t: T) => U): (T | } /** @internal */ -export function assign(t: T, ...args: (T | undefined)[]) { +export function assign(t: T, ...args: (T | undefined)[]): T { for (const arg of args) { if (arg === undefined) continue; for (const p in arg) { @@ -1366,7 +1367,7 @@ export function assign(t: T, ...args: (T | undefined)[]) { * * @internal */ -export function equalOwnProperties(left: MapLike | undefined, right: MapLike | undefined, equalityComparer: EqualityComparer = equateValues) { +export function equalOwnProperties(left: MapLike | undefined, right: MapLike | undefined, equalityComparer: EqualityComparer = equateValues): boolean { if (left === right) return true; if (!left || !right) return false; for (const key in left) { @@ -1509,7 +1510,7 @@ export function extend(first: T1, second: T2): T1 & T2 { } /** @internal */ -export function copyProperties(first: T1, second: T2) { +export function copyProperties(first: T1, second: T2): void { for (const id in second) { if (hasOwnProperty.call(second, id)) { (first as any)[id] = second[id]; @@ -1824,7 +1825,7 @@ export function returnUndefined(): undefined { * * @internal */ -export function identity(x: T) { +export function identity(x: T): T { return x; } @@ -1871,7 +1872,7 @@ const fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_. ]+/g; * * @internal */ -export function toFileNameLowerCase(x: string) { +export function toFileNameLowerCase(x: string): string { return fileNameLowerCaseRegExp.test(x) ? x.replace(fileNameLowerCaseRegExp, toLowerCase) : x; @@ -1933,7 +1934,7 @@ export const enum AssertionLevel { export type AnyFunction = (...args: never[]) => void; /** @internal */ -export function equateValues(a: T, b: T) { +export function equateValues(a: T, b: T): boolean { return a === b; } @@ -1947,7 +1948,7 @@ export function equateValues(a: T, b: T) { * * @internal */ -export function equateStringsCaseInsensitive(a: string, b: string) { +export function equateStringsCaseInsensitive(a: string, b: string): boolean { return a === b || a !== undefined && b !== undefined @@ -1962,7 +1963,7 @@ export function equateStringsCaseInsensitive(a: string, b: string) { * * @internal */ -export function equateStringsCaseSensitive(a: string, b: string) { +export function equateStringsCaseSensitive(a: string, b: string): boolean { return equateValues(a, b); } @@ -2026,7 +2027,7 @@ export function min(items: readonly T[], compare: Comparer): T | undefined * * @internal */ -export function compareStringsCaseInsensitive(a: string, b: string) { +export function compareStringsCaseInsensitive(a: string, b: string): Comparison { if (a === b) return Comparison.EqualTo; if (a === undefined) return Comparison.LessThan; if (b === undefined) return Comparison.GreaterThan; @@ -2047,7 +2048,7 @@ export function compareStringsCaseInsensitive(a: string, b: string) { * * @internal */ -export function compareStringsCaseInsensitiveEslintCompatible(a: string, b: string) { +export function compareStringsCaseInsensitiveEslintCompatible(a: string, b: string): Comparison { if (a === b) return Comparison.EqualTo; if (a === undefined) return Comparison.LessThan; if (b === undefined) return Comparison.GreaterThan; @@ -2073,7 +2074,7 @@ export function compareStringsCaseSensitive(a: string | undefined, b: string | u } /** @internal */ -export function getStringComparer(ignoreCase?: boolean) { +export function getStringComparer(ignoreCase?: boolean): typeof compareStringsCaseInsensitive { return ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive; } @@ -2103,12 +2104,12 @@ let uiComparerCaseSensitive: Comparer | undefined; let uiLocale: string | undefined; /** @internal */ -export function getUILocale() { +export function getUILocale(): string | undefined { return uiLocale; } /** @internal */ -export function setUILocale(value: string | undefined) { +export function setUILocale(value: string | undefined): void { if (uiLocale !== value) { uiLocale = value; uiComparerCaseSensitive = undefined; @@ -2127,7 +2128,7 @@ export function setUILocale(value: string | undefined) { * * @internal */ -export function compareStringsCaseSensitiveUI(a: string, b: string) { +export function compareStringsCaseSensitiveUI(a: string, b: string): Comparison { uiComparerCaseSensitive ??= createUIStringComparer(uiLocale); return uiComparerCaseSensitive(a, b); } @@ -2265,7 +2266,7 @@ export function tryRemoveSuffix(str: string, suffix: string): string | undefined * * @internal */ -export function removeMinAndVersionNumbers(fileName: string) { +export function removeMinAndVersionNumbers(fileName: string): string { // We used to use the regex /[.-]((min)|(\d+(\.\d+)*))$/ and would just .replace it twice. // Unfortunately, that regex has O(n^2) performance because v8 doesn't match from the end of the string. // Instead, we now essentially scan the filename (backwards) ourselves. @@ -2353,7 +2354,7 @@ function unorderedRemoveItemAt(array: T[], index: number): void { * * @internal */ -export function unorderedRemoveItem(array: T[], item: T) { +export function unorderedRemoveItem(array: T[], item: T): boolean { return unorderedRemoveFirstItemWhere(array, element => element === item); } @@ -2441,7 +2442,7 @@ export function tryRemovePrefix(str: string, prefix: string, getCanonicalFileNam } /** @internal */ -export function isPatternMatch({ prefix, suffix }: Pattern, candidate: string) { +export function isPatternMatch({ prefix, suffix }: Pattern, candidate: string): boolean { return candidate.length >= prefix.length + suffix.length && startsWith(candidate, prefix) && endsWith(candidate, suffix); @@ -2449,7 +2450,7 @@ export function isPatternMatch({ prefix, suffix }: Pattern, candidate: string) { /** @internal */ export function and(f: (arg: T) => boolean, g: (arg: T) => boolean) { - return (arg: T) => f(arg) && g(arg); + return (arg: T): boolean => f(arg) && g(arg); } /** @internal */ @@ -2486,7 +2487,7 @@ export function singleElementArray(t: T | undefined): T[] | undefined { } /** @internal */ -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) { +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): boolean { unchanged ??= noop; let newIndex = 0; let oldIndex = 0; @@ -2525,7 +2526,7 @@ export function enumerateInsertsAndDeletes(newItems: readonly T[], oldItem } /** @internal */ -export function cartesianProduct(arrays: readonly T[][]) { +export function cartesianProduct(arrays: readonly T[][]): T[][] { const result: T[][] = []; cartesianProductWorker(arrays, result, /*outer*/ undefined, 0); return result; diff --git a/src/compiler/debug.ts b/src/compiler/debug.ts index 7468b2aeceaaa..166ed9025be25 100644 --- a/src/compiler/debug.ts +++ b/src/compiler/debug.ts @@ -113,7 +113,7 @@ export interface LoggingHost { export namespace Debug { /* eslint-disable prefer-const */ let currentAssertionLevel = AssertionLevel.None; - export let currentLogLevel = LogLevel.Warning; + export let currentLogLevel: LogLevel = LogLevel.Warning; export let isDebugging = false; export let loggingHost: LoggingHost | undefined; /* eslint-enable prefer-const */ @@ -154,11 +154,11 @@ export namespace Debug { const assertionCache: Partial> = {}; - export function getAssertionLevel() { + export function getAssertionLevel(): AssertionLevel { return currentAssertionLevel; } - export function setAssertionLevel(level: AssertionLevel) { + export function setAssertionLevel(level: AssertionLevel): void { const prevAssertionLevel = currentAssertionLevel; currentAssertionLevel = level; @@ -365,7 +365,7 @@ export namespace Debug { export function type(value: unknown): asserts value is T; export function type(_value: unknown) {} - export function getFunctionName(func: AnyFunction) { + export function getFunctionName(func: AnyFunction): any { if (typeof func !== "function") { return ""; } @@ -386,7 +386,7 @@ export namespace Debug { /** * Formats an enum value as a string for debugging and debug assertions. */ - export function formatEnum(value = 0, enumObject: any, isFlags?: boolean) { + export function formatEnum(value = 0, enumObject: any, isFlags?: boolean): string { const members = getEnumMembers(enumObject); if (value === 0) { return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0"; @@ -549,7 +549,7 @@ export namespace Debug { } } - export function attachFlowNodeDebugInfo(flowNode: FlowNode) { + export function attachFlowNodeDebugInfo(flowNode: FlowNode): FlowNode { if (isDebugInfoEnabled) { if (typeof Object.setPrototypeOf === "function") { // if we're in es2015, attach the method to a shared prototype for `FlowNode` @@ -589,7 +589,7 @@ export namespace Debug { } } - export function attachNodeArrayDebugInfo(array: NodeArray) { + export function attachNodeArrayDebugInfo(array: NodeArray): void { if (isDebugInfoEnabled) { if (typeof Object.setPrototypeOf === "function") { // if we're in es2015, attach the method to a shared prototype for `NodeArray` @@ -610,7 +610,7 @@ export namespace Debug { /** * Injects debug information into frequently used types. */ - export function enableDebugInfo() { + export function enableDebugInfo(): void { if (isDebugInfoEnabled) return; // avoid recomputing @@ -806,7 +806,7 @@ export namespace Debug { isDebugInfoEnabled = true; } - export function formatVariance(varianceFlags: VarianceFlags) { + export function formatVariance(varianceFlags: VarianceFlags): string { const variance = varianceFlags & VarianceFlags.VarianceMask; let result = variance === VarianceFlags.Invariant ? "in out" : variance === VarianceFlags.Bivariant ? "[bivariant]" : @@ -861,11 +861,11 @@ m2: ${(this.mapper2 as unknown as DebugTypeMapper).__debugToString().split("\n") return mapper; } - export function printControlFlowGraph(flowNode: FlowNode) { + export function printControlFlowGraph(flowNode: FlowNode): void { return console.log(formatControlFlowGraph(flowNode)); } - export function formatControlFlowGraph(flowNode: FlowNode) { + export function formatControlFlowGraph(flowNode: FlowNode): string { let nextDebugFlowId = -1; function getDebugFlowNodeId(f: FlowNode) { diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index f79fdf2136407..c34f6b68692d0 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -428,7 +428,7 @@ import * as performance from "./_namespaces/ts.performance.js"; const brackets = createBracketsMap(); /** @internal */ -export function isBuildInfoFile(file: string) { +export function isBuildInfoFile(file: string): boolean { return fileExtensionIs(file, Extension.TsBuildInfo); } @@ -450,7 +450,7 @@ export function forEachEmittedFile( forceDtsEmit = false, onlyBuildInfo?: boolean, includeBuildInfo?: boolean, -) { +): T | undefined { const sourceFiles = isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile, forceDtsEmit); const options = host.getCompilerOptions(); if (!onlyBuildInfo) { @@ -478,7 +478,7 @@ export function forEachEmittedFile( } } -export function getTsBuildInfoEmitOutputFilePath(options: CompilerOptions) { +export function getTsBuildInfoEmitOutputFilePath(options: CompilerOptions): string | undefined { const configFile = options.configFilePath; if (!canEmitTsBuildInfo(options)) return undefined; if (options.tsBuildInfoFile) return options.tsBuildInfoFile; @@ -500,7 +500,7 @@ export function getTsBuildInfoEmitOutputFilePath(options: CompilerOptions) { } /** @internal */ -export function canEmitTsBuildInfo(options: CompilerOptions) { +export function canEmitTsBuildInfo(options: CompilerOptions): boolean { return isIncrementalCompilation(options) || !!options.tscBuild; } @@ -561,12 +561,12 @@ function getOutputPathWithoutChangingExt( } /** @internal */ -export function getOutputDeclarationFileName(inputFileName: string, configFile: ParsedCommandLine, ignoreCase: boolean, getCommonSourceDirectory = () => getCommonSourceDirectoryOfConfig(configFile, ignoreCase)) { +export function getOutputDeclarationFileName(inputFileName: string, configFile: ParsedCommandLine, ignoreCase: boolean, getCommonSourceDirectory = (): string => getCommonSourceDirectoryOfConfig(configFile, ignoreCase)): string { return getOutputDeclarationFileNameWorker(inputFileName, configFile.options, ignoreCase, getCommonSourceDirectory); } /** @internal */ -export function getOutputDeclarationFileNameWorker(inputFileName: string, options: CompilerOptions, ignoreCase: boolean, getCommonSourceDirectory: () => string) { +export function getOutputDeclarationFileNameWorker(inputFileName: string, options: CompilerOptions, ignoreCase: boolean, getCommonSourceDirectory: () => string): string { return changeExtension( getOutputPathWithoutChangingExt(inputFileName, ignoreCase, options.declarationDir || options.outDir, getCommonSourceDirectory), getDeclarationEmitExtensionForPath(inputFileName), @@ -722,7 +722,7 @@ export function getFirstProjectOutput(configFile: ParsedCommandLine, ignoreCase: } /** @internal */ -export function emitResolverSkipsTypeChecking(emitOnly: boolean | EmitOnly | undefined, forceDtsEmit: boolean | undefined) { +export function emitResolverSkipsTypeChecking(emitOnly: boolean | EmitOnly | undefined, forceDtsEmit: boolean | undefined): boolean { return !!forceDtsEmit && !!emitOnly; } @@ -1113,7 +1113,7 @@ export function emitFiles( } /** @internal */ -export function getBuildInfoText(buildInfo: BuildInfo) { +export function getBuildInfoText(buildInfo: BuildInfo): string { return JSON.stringify(buildInfo); } @@ -1174,16 +1174,16 @@ const enum PipelinePhase { } /** @internal */ -export const createPrinterWithDefaults = /* @__PURE__ */ memoize(() => createPrinter({})); +export const createPrinterWithDefaults: () => Printer = /* @__PURE__ */ memoize(() => createPrinter({})); /** @internal */ -export const createPrinterWithRemoveComments = /* @__PURE__ */ memoize(() => createPrinter({ removeComments: true })); +export const createPrinterWithRemoveComments: () => Printer = /* @__PURE__ */ memoize(() => createPrinter({ removeComments: true })); /** @internal */ -export const createPrinterWithRemoveCommentsNeverAsciiEscape = /* @__PURE__ */ memoize(() => createPrinter({ removeComments: true, neverAsciiEscape: true })); +export const createPrinterWithRemoveCommentsNeverAsciiEscape: () => Printer = /* @__PURE__ */ memoize(() => createPrinter({ removeComments: true, neverAsciiEscape: true })); /** @internal */ -export const createPrinterWithRemoveCommentsOmitTrailingSemicolon = /* @__PURE__ */ memoize(() => createPrinter({ removeComments: true, omitTrailingSemicolon: true })); +export const createPrinterWithRemoveCommentsOmitTrailingSemicolon: () => Printer = /* @__PURE__ */ memoize(() => createPrinter({ removeComments: true, omitTrailingSemicolon: true })); export function createPrinter(printerOptions: PrinterOptions = {}, handlers: PrintHandlers = {}): Printer { // Why var? It avoids TDZ checks in the runtime which can be costly. diff --git a/src/compiler/executeCommandLine.ts b/src/compiler/executeCommandLine.ts index 0f8fdd25ccc2a..b3b92260081d7 100644 --- a/src/compiler/executeCommandLine.ts +++ b/src/compiler/executeCommandLine.ts @@ -733,7 +733,7 @@ function executeCommandLineWorker( } /** @internal */ -export function isBuild(commandLineArgs: readonly string[]) { +export function isBuild(commandLineArgs: readonly string[]): boolean { if (commandLineArgs.length > 0 && commandLineArgs[0].charCodeAt(0) === CharacterCodes.minus) { const firstOption = commandLineArgs[0].slice(commandLineArgs[0].charCodeAt(1) === CharacterCodes.minus ? 2 : 1).toLowerCase(); return firstOption === "build" || firstOption === "b"; diff --git a/src/compiler/expressionToTypeNode.ts b/src/compiler/expressionToTypeNode.ts index 047611a5d45f7..bc0b7201ca1f2 100644 --- a/src/compiler/expressionToTypeNode.ts +++ b/src/compiler/expressionToTypeNode.ts @@ -66,7 +66,15 @@ import { } from "./_namespaces/ts.js"; /** @internal */ -export function createSyntacticTypeNodeBuilder(options: CompilerOptions, resolver: SyntacticTypeNodeBuilderResolver) { +export function createSyntacticTypeNodeBuilder( + options: CompilerOptions, + resolver: SyntacticTypeNodeBuilderResolver, +): { + typeFromExpression: (node: Expression, context: SyntacticTypeNodeBuilderContext, isConstContext?: boolean, requiresAddingUndefined?: boolean, preserveLiterals?: boolean) => boolean | undefined; + serializeTypeOfDeclaration: (node: HasInferredType, context: SyntacticTypeNodeBuilderContext) => boolean | undefined; + serializeReturnTypeForSignature: (node: SignatureDeclaration | JSDocSignature, context: SyntacticTypeNodeBuilderContext) => boolean | undefined; + serializeTypeOfExpression: (expr: Expression, context: SyntacticTypeNodeBuilderContext, addUndefined?: boolean, preserveLiterals?: boolean) => boolean; +} { const strictNullChecks = getStrictOptionValue(options, "strictNullChecks"); return { diff --git a/src/compiler/factory/emitHelpers.ts b/src/compiler/factory/emitHelpers.ts index 8cc453299e3f8..722e408e0743b 100644 --- a/src/compiler/factory/emitHelpers.ts +++ b/src/compiler/factory/emitHelpers.ts @@ -685,7 +685,7 @@ export function createEmitHelperFactory(context: TransformationContext): EmitHel } /** @internal */ -export function compareEmitHelpers(x: EmitHelper, y: EmitHelper) { +export function compareEmitHelpers(x: EmitHelper, y: EmitHelper): Comparison { if (x === y) return Comparison.EqualTo; if (x.priority === y.priority) return Comparison.EqualTo; if (x.priority === undefined) return Comparison.GreaterThan; diff --git a/src/compiler/factory/emitNode.ts b/src/compiler/factory/emitNode.ts index 5b90c578148d1..beadc29d4ca6b 100644 --- a/src/compiler/factory/emitNode.ts +++ b/src/compiler/factory/emitNode.ts @@ -59,7 +59,7 @@ export function getOrCreateEmitNode(node: Node): EmitNode { * Clears any `EmitNode` entries from parse-tree nodes. * @param sourceFile A source file. */ -export function disposeEmitNodes(sourceFile: SourceFile | undefined) { +export function disposeEmitNodes(sourceFile: SourceFile | undefined): void { // During transformation we may need to annotate a parse tree node with transient // transformation properties. As parse tree nodes live longer than transformation // nodes, we need to make sure we reclaim any memory allocated for custom ranges @@ -89,7 +89,7 @@ export function removeAllComments(node: T): T { /** * Sets flags that control emit behavior of a node. */ -export function setEmitFlags(node: T, emitFlags: EmitFlags) { +export function setEmitFlags(node: T, emitFlags: EmitFlags): T { getOrCreateEmitNode(node).flags = emitFlags; return node; } @@ -99,7 +99,7 @@ export function setEmitFlags(node: T, emitFlags: EmitFlags) { * * @internal */ -export function addEmitFlags(node: T, emitFlags: EmitFlags) { +export function addEmitFlags(node: T, emitFlags: EmitFlags): T { const emitNode = getOrCreateEmitNode(node); emitNode.flags = emitNode.flags | emitFlags; return node; @@ -110,7 +110,7 @@ export function addEmitFlags(node: T, emitFlags: EmitFlags) { * * @internal */ -export function setInternalEmitFlags(node: T, emitFlags: InternalEmitFlags) { +export function setInternalEmitFlags(node: T, emitFlags: InternalEmitFlags): T { getOrCreateEmitNode(node).internalFlags = emitFlags; return node; } @@ -120,7 +120,7 @@ export function setInternalEmitFlags(node: T, emitFlags: Interna * * @internal */ -export function addInternalEmitFlags(node: T, emitFlags: InternalEmitFlags) { +export function addInternalEmitFlags(node: T, emitFlags: InternalEmitFlags): T { const emitNode = getOrCreateEmitNode(node); emitNode.internalFlags = emitNode.internalFlags | emitFlags; return node; @@ -136,7 +136,7 @@ export function getSourceMapRange(node: Node): SourceMapRange { /** * Sets a custom text range to use when emitting source maps. */ -export function setSourceMapRange(node: T, range: SourceMapRange | undefined) { +export function setSourceMapRange(node: T, range: SourceMapRange | undefined): T { getOrCreateEmitNode(node).sourceMapRange = range; return node; } @@ -151,7 +151,7 @@ export function getTokenSourceMapRange(node: Node, token: SyntaxKind): SourceMap /** * Sets the TextRange to use for source maps for a token of a node. */ -export function setTokenSourceMapRange(node: T, token: SyntaxKind, range: SourceMapRange | undefined) { +export function setTokenSourceMapRange(node: T, token: SyntaxKind, range: SourceMapRange | undefined): T { const emitNode = getOrCreateEmitNode(node); const tokenSourceMapRanges = emitNode.tokenSourceMapRanges ?? (emitNode.tokenSourceMapRanges = []); tokenSourceMapRanges[token] = range; @@ -163,7 +163,7 @@ export function setTokenSourceMapRange(node: T, token: SyntaxKin * * @internal */ -export function getStartsOnNewLine(node: Node) { +export function getStartsOnNewLine(node: Node): boolean | undefined { return node.emitNode?.startsOnNewLine; } @@ -172,7 +172,7 @@ export function getStartsOnNewLine(node: Node) { * * @internal */ -export function setStartsOnNewLine(node: T, newLine: boolean) { +export function setStartsOnNewLine(node: T, newLine: boolean): T { getOrCreateEmitNode(node).startsOnNewLine = newLine; return node; } @@ -187,7 +187,7 @@ export function getCommentRange(node: Node): TextRange { /** * Sets a custom text range to use when emitting comments. */ -export function setCommentRange(node: T, range: TextRange) { +export function setCommentRange(node: T, range: TextRange): T { getOrCreateEmitNode(node).commentRange = range; return node; } @@ -196,12 +196,12 @@ export function getSyntheticLeadingComments(node: Node): SynthesizedComment[] | return node.emitNode?.leadingComments; } -export function setSyntheticLeadingComments(node: T, comments: SynthesizedComment[] | undefined) { +export function setSyntheticLeadingComments(node: T, comments: SynthesizedComment[] | undefined): T { getOrCreateEmitNode(node).leadingComments = comments; return node; } -export function addSyntheticLeadingComment(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean) { +export function addSyntheticLeadingComment(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean): T { return setSyntheticLeadingComments(node, append(getSyntheticLeadingComments(node), { kind, pos: -1, end: -1, hasTrailingNewLine, text })); } @@ -209,12 +209,12 @@ export function getSyntheticTrailingComments(node: Node): SynthesizedComment[] | return node.emitNode?.trailingComments; } -export function setSyntheticTrailingComments(node: T, comments: SynthesizedComment[] | undefined) { +export function setSyntheticTrailingComments(node: T, comments: SynthesizedComment[] | undefined): T { getOrCreateEmitNode(node).trailingComments = comments; return node; } -export function addSyntheticTrailingComment(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean) { +export function addSyntheticTrailingComment(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean): T { return setSyntheticTrailingComments(node, append(getSyntheticTrailingComments(node), { kind, pos: -1, end: -1, hasTrailingNewLine, text })); } @@ -286,7 +286,7 @@ export function getEmitHelpers(node: Node): EmitHelper[] | undefined { /** * Moves matching emit helpers from a source node to a target node. */ -export function moveEmitHelpers(source: Node, target: Node, predicate: (helper: EmitHelper) => boolean) { +export function moveEmitHelpers(source: Node, target: Node, predicate: (helper: EmitHelper) => boolean): void { const sourceEmitNode = source.emitNode; const sourceEmitHelpers = sourceEmitNode && sourceEmitNode.helpers; if (!some(sourceEmitHelpers)) return; @@ -348,7 +348,7 @@ export function getTypeNode(node: T): TypeNode | undefined { } /** @internal */ -export function setIdentifierTypeArguments(node: T, typeArguments: NodeArray | undefined) { +export function setIdentifierTypeArguments(node: T, typeArguments: NodeArray | undefined): T { getOrCreateEmitNode(node).identifierTypeArguments = typeArguments; return node; } @@ -359,7 +359,7 @@ export function getIdentifierTypeArguments(node: Identifier): NodeArray(node: T, autoGenerate: AutoGenerateInfo | undefined) { +export function setIdentifierAutoGenerate(node: T, autoGenerate: AutoGenerateInfo | undefined): T { getOrCreateEmitNode(node).autoGenerate = autoGenerate; return node; } @@ -370,7 +370,7 @@ export function getIdentifierAutoGenerate(node: Identifier | PrivateIdentifier): } /** @internal */ -export function setIdentifierGeneratedImportReference(node: T, value: ImportSpecifier | undefined) { +export function setIdentifierGeneratedImportReference(node: T, value: ImportSpecifier | undefined): T { getOrCreateEmitNode(node).generatedImportReference = value; return node; } diff --git a/src/compiler/factory/nodeChildren.ts b/src/compiler/factory/nodeChildren.ts index 3946ee89417bc..da8e074415e00 100644 --- a/src/compiler/factory/nodeChildren.ts +++ b/src/compiler/factory/nodeChildren.ts @@ -41,7 +41,7 @@ export function setNodeChildren(node: Node, sourceFile: SourceFileLike, children } /** @internal */ -export function unsetNodeChildren(node: Node, origSourceFile: SourceFileLike) { +export function unsetNodeChildren(node: Node, origSourceFile: SourceFileLike): void { if (node.kind === SyntaxKind.SyntaxList) { // Syntax lists are synthesized and we store their children directly on them. // They are a special case where we expect incremental parsing to toss them away entirely @@ -52,7 +52,7 @@ export function unsetNodeChildren(node: Node, origSourceFile: SourceFileLike) { } /** @internal */ -export function transferSourceFileChildren(sourceFile: SourceFileLike, targetSourceFile: SourceFileLike) { +export function transferSourceFileChildren(sourceFile: SourceFileLike, targetSourceFile: SourceFileLike): void { const map = sourceFileToNodeChildren.get(sourceFile); if (map !== undefined) { sourceFileToNodeChildren.delete(sourceFile); diff --git a/src/compiler/factory/nodeFactory.ts b/src/compiler/factory/nodeFactory.ts index 90b9071efe594..c26720aa60a0b 100644 --- a/src/compiler/factory/nodeFactory.ts +++ b/src/compiler/factory/nodeFactory.ts @@ -476,7 +476,7 @@ export const enum NodeFactoryFlags { const nodeFactoryPatchers: ((factory: NodeFactory) => void)[] = []; /** @internal @knipignore */ -export function addNodeFactoryPatcher(fn: (factory: NodeFactory) => void) { +export function addNodeFactoryPatcher(fn: (factory: NodeFactory) => void): void { nodeFactoryPatchers.push(fn); } @@ -7389,7 +7389,7 @@ const syntheticFactory: BaseNodeFactory = { createBaseNode: kind => makeSynthetic(baseFactory.createBaseNode(kind)), }; -export const factory = createNodeFactory(NodeFactoryFlags.NoIndentationOnFreshPropertyAccess, syntheticFactory); +export const factory: NodeFactory = createNodeFactory(NodeFactoryFlags.NoIndentationOnFreshPropertyAccess, syntheticFactory); let SourceMapSource: new (fileName: string, text: string, skipTrivia?: (pos: number) => number) => SourceMapSource; diff --git a/src/compiler/factory/utilities.ts b/src/compiler/factory/utilities.ts index d6d0de9e515c1..945150f28957a 100644 --- a/src/compiler/factory/utilities.ts +++ b/src/compiler/factory/utilities.ts @@ -179,7 +179,7 @@ import { // Compound nodes /** @internal */ -export function createEmptyExports(factory: NodeFactory) { +export function createEmptyExports(factory: NodeFactory): ExportDeclaration { return factory.createExportDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports([]), /*moduleSpecifier*/ undefined); } @@ -512,7 +512,13 @@ export function createExpressionForObjectLiteralElementLike(factory: NodeFactory * * @internal */ -export function expandPreOrPostfixIncrementOrDecrementExpression(factory: NodeFactory, node: PrefixUnaryExpression | PostfixUnaryExpression, expression: Expression, recordTempVariable: (node: Identifier) => void, resultVariable: Identifier | undefined) { +export function expandPreOrPostfixIncrementOrDecrementExpression( + factory: NodeFactory, + node: PrefixUnaryExpression | PostfixUnaryExpression, + expression: Expression, + recordTempVariable: (node: Identifier) => void, + resultVariable: Identifier | undefined, +): Expression { const operator = node.operator; Debug.assert(operator === SyntaxKind.PlusPlusToken || operator === SyntaxKind.MinusMinusToken, "Expected 'node' to be a pre- or post-increment or pre- or post-decrement expression"); @@ -546,7 +552,7 @@ export function expandPreOrPostfixIncrementOrDecrementExpression(factory: NodeFa * * @internal */ -export function isInternalName(node: Identifier) { +export function isInternalName(node: Identifier): boolean { return (getEmitFlags(node) & EmitFlags.InternalName) !== 0; } @@ -555,7 +561,7 @@ export function isInternalName(node: Identifier) { * * @internal */ -export function isLocalName(node: Identifier) { +export function isLocalName(node: Identifier): boolean { return (getEmitFlags(node) & EmitFlags.LocalName) !== 0; } @@ -565,7 +571,7 @@ export function isLocalName(node: Identifier) { * * @internal */ -export function isExportName(node: Identifier) { +export function isExportName(node: Identifier): boolean { return (getEmitFlags(node) & EmitFlags.ExportName) !== 0; } @@ -589,7 +595,7 @@ export function findUseStrictPrologue(statements: readonly Statement[]): Stateme } /** @internal */ -export function startsWithUseStrict(statements: readonly Statement[]) { +export function startsWithUseStrict(statements: readonly Statement[]): boolean { const firstStatement = firstOrUndefined(statements); return firstStatement !== undefined && isPrologueDirective(firstStatement) @@ -621,7 +627,7 @@ export function getJSDocTypeAssertionType(node: JSDocTypeAssertion): TypeNode { } /** @internal */ -export function isOuterExpression(node: Node, kinds = OuterExpressionKinds.All): node is OuterExpression { +export function isOuterExpression(node: Node, kinds: OuterExpressionKinds = OuterExpressionKinds.All): node is OuterExpression { switch (node.kind) { case SyntaxKind.ParenthesizedExpression: if (kinds & OuterExpressionKinds.ExcludeJSDocTypeAssertion && isJSDocTypeAssertion(node)) { @@ -657,7 +663,7 @@ export function skipOuterExpressions(node: Node, kinds = OuterExpressionKinds.Al } /** @internal */ -export function walkUpOuterExpressions(node: Expression, kinds = OuterExpressionKinds.All): Node { +export function walkUpOuterExpressions(node: Expression, kinds: OuterExpressionKinds = OuterExpressionKinds.All): Node { let parent = node.parent; while (isOuterExpression(parent, kinds)) { parent = parent.parent; @@ -672,21 +678,21 @@ export function startOnNewLine(node: T): T { } /** @internal */ -export function getExternalHelpersModuleName(node: SourceFile) { +export function getExternalHelpersModuleName(node: SourceFile): Identifier | undefined { const parseNode = getOriginalNode(node, isSourceFile); const emitNode = parseNode && parseNode.emitNode; return emitNode && emitNode.externalHelpersModuleName; } /** @internal */ -export function hasRecordedExternalHelpers(sourceFile: SourceFile) { +export function hasRecordedExternalHelpers(sourceFile: SourceFile): boolean { const parseNode = getOriginalNode(sourceFile, isSourceFile); const emitNode = parseNode && parseNode.emitNode; return !!emitNode && (!!emitNode.externalHelpersModuleName || !!emitNode.externalHelpers); } /** @internal */ -export function createExternalHelpersImportDeclarationIfNeeded(nodeFactory: NodeFactory, helperFactory: EmitHelperFactory, sourceFile: SourceFile, compilerOptions: CompilerOptions, hasExportStarsToExportValues?: boolean, hasImportStar?: boolean, hasImportDefault?: boolean) { +export function createExternalHelpersImportDeclarationIfNeeded(nodeFactory: NodeFactory, helperFactory: EmitHelperFactory, sourceFile: SourceFile, compilerOptions: CompilerOptions, hasExportStarsToExportValues?: boolean, hasImportStar?: boolean, hasImportDefault?: boolean): ImportDeclaration | undefined { if (compilerOptions.importHelpers && isEffectiveExternalModule(sourceFile, compilerOptions)) { let namedBindings: NamedImportBindings | undefined; const moduleKind = getEmitModuleKind(compilerOptions); @@ -801,7 +807,7 @@ export function getLocalNameForExternalImport(factory: NodeFactory, node: Import * * @internal */ -export function getExternalModuleNameLiteral(factory: NodeFactory, importNode: ImportDeclaration | ExportDeclaration | ImportEqualsDeclaration | ImportCall, sourceFile: SourceFile, host: EmitHost, resolver: EmitResolver, compilerOptions: CompilerOptions) { +export function getExternalModuleNameLiteral(factory: NodeFactory, importNode: ImportDeclaration | ExportDeclaration | ImportEqualsDeclaration | ImportCall, sourceFile: SourceFile, host: EmitHost, resolver: EmitResolver, compilerOptions: CompilerOptions): StringLiteral | undefined { const moduleName = getExternalModuleName(importNode); if (moduleName && isStringLiteral(moduleName)) { return tryGetModuleNameFromDeclaration(importNode, host, factory, resolver, compilerOptions) @@ -1079,7 +1085,7 @@ export function getElementsOfBindingOrAssignmentPattern(name: BindingOrAssignmen } /** @internal */ -export function getJSDocTypeAliasName(fullName: JSDocNamespaceBody | undefined) { +export function getJSDocTypeAliasName(fullName: JSDocNamespaceBody | undefined): Identifier | undefined { if (fullName) { let rightNode = fullName; while (true) { @@ -1505,7 +1511,7 @@ export function elideNodes(factory: NodeFactory, nodes: NodeArra * * @internal */ -export function getNodeForGeneratedName(name: GeneratedIdentifier | GeneratedPrivateIdentifier) { +export function getNodeForGeneratedName(name: GeneratedIdentifier | GeneratedPrivateIdentifier): Node | GeneratedIdentifier | GeneratedPrivateIdentifier { const autoGenerate = name.emitNode.autoGenerate; if (autoGenerate.flags & GeneratedIdentifierFlags.Node) { const autoGenerateId = autoGenerate.id; @@ -1598,7 +1604,7 @@ export function formatGeneratedName(privateName: boolean, prefix: string | Gener * * @internal */ -export function createAccessorPropertyBackingField(factory: NodeFactory, node: PropertyDeclaration, modifiers: ModifiersArray | undefined, initializer: Expression | undefined) { +export function createAccessorPropertyBackingField(factory: NodeFactory, node: PropertyDeclaration, modifiers: ModifiersArray | undefined, initializer: Expression | undefined): PropertyDeclaration { return factory.updatePropertyDeclaration( node, modifiers, @@ -1712,7 +1718,7 @@ function flattenCommaListWorker(node: Expression, expressions: Expression[]) { * * @internal */ -export function flattenCommaList(node: Expression) { +export function flattenCommaList(node: Expression): Expression[] { const expressions: Expression[] = []; flattenCommaListWorker(node, expressions); return expressions; diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index 850a8a7f381cb..dcbc239381b10 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -296,7 +296,7 @@ function initializeResolutionField(value: T[]): T[] | undefined { return value.length ? value : undefined; } /** @internal */ -export function updateResolutionField(to: T[] | undefined, value: T[] | undefined) { +export function updateResolutionField(to: T[] | undefined, value: T[] | undefined): T[] | undefined { if (!value?.length) return to; if (!to?.length) return value; to.push(...value); @@ -453,7 +453,10 @@ function readPackageJsonTypesVersionPaths(jsonContent: PackageJson, state: Modul let typeScriptVersion: Version | undefined; /** @internal */ -export function getPackageJsonTypesVersionsPaths(typesVersions: MapLike>) { +export function getPackageJsonTypesVersionsPaths(typesVersions: MapLike>): { + version: string; + paths: MapLike; +} | undefined { if (!typeScriptVersion) typeScriptVersion = new Version(version); for (const key in typesVersions) { @@ -747,7 +750,7 @@ function getNodeResolutionFeatures(options: CompilerOptions) { } /** @internal */ -export function getConditions(options: CompilerOptions, resolutionMode?: ResolutionMode) { +export function getConditions(options: CompilerOptions, resolutionMode?: ResolutionMode): string[] { const moduleResolution = getEmitModuleResolutionKind(options); if (resolutionMode === undefined) { if (moduleResolution === ModuleResolutionKind.Bundler) { @@ -951,7 +954,7 @@ function compilerOptionValueToString(value: unknown): string { } /** @internal */ -export function getKeyForCompilerOptions(options: CompilerOptions, affectingOptionDeclarations: readonly CommandLineOption[]) { +export function getKeyForCompilerOptions(options: CompilerOptions, affectingOptionDeclarations: readonly CommandLineOption[]): string { return affectingOptionDeclarations.map(option => compilerOptionValueToString(getCompilerOptionValue(options, option))).join("|") + `|${options.pathsBasePath}`; } @@ -1382,7 +1385,10 @@ export function createTypeReferenceDirectiveResolutionCache( } /** @internal */ -export function getOptionsForLibraryResolution(options: CompilerOptions) { +export function getOptionsForLibraryResolution(options: CompilerOptions): { + moduleResolution: ModuleResolutionKind; + traceResolution: boolean | undefined; +} { return { moduleResolution: ModuleResolutionKind.Node10, traceResolution: options.traceResolution }; } @@ -2553,7 +2559,7 @@ export function parsePackageName(moduleName: string): { packageName: string; res } /** @internal */ -export function allKeysStartWithDot(obj: MapLike) { +export function allKeysStartWithDot(obj: MapLike): boolean { return every(getOwnKeys(obj), k => startsWith(k, ".")); } @@ -2674,7 +2680,7 @@ function loadModuleFromImports(extensions: Extensions, moduleName: string, direc * From https://github.com/nodejs/node/blob/8f39f51cbbd3b2de14b9ee896e26421cc5b20121/lib/internal/modules/esm/resolve.js#L722 - * "longest" has some nuance as to what "longest" means in the presence of pattern trailers */ -export function comparePatternKeys(a: string, b: string) { +export function comparePatternKeys(a: string, b: string): 1 | 0 | -1 { const aPatternIndex = a.indexOf("*"); const bPatternIndex = b.indexOf("*"); const baseLenA = aPatternIndex === -1 ? a.length : aPatternIndex + 1; @@ -2962,7 +2968,7 @@ function getLoadModuleFromTargetImportOrExport(extensions: Extensions, state: Mo } /** @internal */ -export function isApplicableVersionedTypesKey(conditions: readonly string[], key: string) { +export function isApplicableVersionedTypesKey(conditions: readonly string[], key: string): boolean { if (!conditions.includes("types")) return false; // only apply versioned types conditions if the types condition is applied if (!startsWith(key, "types@")) return false; const range = VersionRange.tryParse(key.substring("types@".length)); @@ -3302,7 +3308,7 @@ function resolveFromTypeRoot(moduleName: string, state: ModuleResolutionState) { // Program errors validate that `noEmit` or `emitDeclarationOnly` is also set, // so this function doesn't check them to avoid propagating errors. /** @internal */ -export function shouldAllowImportingTsExtension(compilerOptions: CompilerOptions, fromFileName?: string) { +export function shouldAllowImportingTsExtension(compilerOptions: CompilerOptions, fromFileName?: string): boolean | "" | undefined { return !!compilerOptions.allowImportingTsExtensions || fromFileName && isDeclarationFileName(fromFileName); } diff --git a/src/compiler/moduleSpecifiers.ts b/src/compiler/moduleSpecifiers.ts index fa1727b523b4d..ea583e75d5c80 100644 --- a/src/compiler/moduleSpecifiers.ts +++ b/src/compiler/moduleSpecifiers.ts @@ -390,7 +390,7 @@ export function getModuleSpecifiersWithCacheInfo( importingSourceFile: SourceFile | FutureSourceFile, host: ModuleSpecifierResolutionHost, userPreferences: UserPreferences, - options: ModuleSpecifierOptions = {}, + options: ModuleSpecifierOptions | undefined = {}, forAutoImport: boolean, ): ModuleSpecifierResult { let computedWithoutCache = false; @@ -1403,7 +1403,7 @@ function processEnding(fileName: string, allowedEndings: readonly ModuleSpecifie } /** @internal */ -export function tryGetRealFileNameForNonJsDeclarationFileName(fileName: string) { +export function tryGetRealFileNameForNonJsDeclarationFileName(fileName: string): string | undefined { const baseName = getBaseFileName(fileName); if (!endsWith(fileName, Extension.Ts) || !baseName.includes(".d.") || fileExtensionIsOneOf(baseName, [Extension.Dts])) return undefined; const noExtension = removeExtension(fileName, Extension.Ts); diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index c95c4759b9c12..b325e97d64cf7 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -458,14 +458,14 @@ function visitNodes(cbNode: (node: Node) => T, cbNodes: ((node: NodeArray 0; } @@ -66,7 +66,7 @@ export function isRootedDiskPath(path: string) { * * @internal */ -export function isDiskPathRoot(path: string) { +export function isDiskPathRoot(path: string): boolean { const rootLength = getEncodedRootLength(path); return rootLength > 0 && rootLength === path.length; } @@ -137,7 +137,7 @@ export function fileExtensionIsOneOf(path: string, extensions: readonly string[] * * @internal */ -export function hasTrailingDirectorySeparator(path: string) { +export function hasTrailingDirectorySeparator(path: string): boolean { return path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1)); } @@ -247,7 +247,7 @@ function getEncodedRootLength(path: string): number { * * @internal */ -export function getRootLength(path: string) { +export function getRootLength(path: string): number { const rootLength = getEncodedRootLength(path); return rootLength < 0 ? ~rootLength : rootLength; } @@ -509,7 +509,7 @@ export function getPathComponents(path: string, currentDirectory = "") { * * @internal */ -export function getPathFromPathComponents(pathComponents: readonly T[], length?: number) { +export function getPathFromPathComponents(pathComponents: readonly T[], length?: number): T { if (pathComponents.length === 0) return "" as T; const root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]); @@ -535,7 +535,7 @@ export function normalizeSlashes(path: string): string { * * @internal */ -export function reducePathComponents(components: readonly string[]) { +export function reducePathComponents(components: readonly string[]): string[] { if (!some(components)) return []; const reduced = [components[0]]; for (let i = 1; i < components.length; i++) { @@ -619,12 +619,12 @@ export function resolvePath(path: string, ...paths: (string | undefined)[]): str * * @internal */ -export function getNormalizedPathComponents(path: string, currentDirectory: string | undefined) { +export function getNormalizedPathComponents(path: string, currentDirectory: string | undefined): string[] { return reducePathComponents(getPathComponents(path, currentDirectory)); } /** @internal */ -export function getNormalizedAbsolutePath(fileName: string, currentDirectory: string | undefined) { +export function getNormalizedAbsolutePath(fileName: string, currentDirectory: string | undefined): string { return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); } @@ -654,7 +654,7 @@ function getPathWithoutRoot(pathComponents: readonly string[]) { } /** @internal */ -export function getNormalizedAbsolutePathWithoutRoot(fileName: string, currentDirectory: string | undefined) { +export function getNormalizedAbsolutePathWithoutRoot(fileName: string, currentDirectory: string | undefined): string { return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory)); } @@ -767,7 +767,7 @@ export function changeAnyExtension(path: string, ext: string, extensions?: strin * changeFullExtension("file.d.ts", ".js") === "file.js" * ``` */ -export function changeFullExtension(path: string, newExtension: string) { +export function changeFullExtension(path: string, newExtension: string): string { const declarationExtension = getDeclarationFileExtension(path); if (declarationExtension) { return path.slice(0, path.length - declarationExtension.length) + @@ -822,7 +822,7 @@ function comparePathsWorker(a: string, b: string, componentComparer: (a: string, * * @internal */ -export function comparePathsCaseSensitive(a: string, b: string) { +export function comparePathsCaseSensitive(a: string, b: string): Comparison { return comparePathsWorker(a, b, compareStringsCaseSensitive); } @@ -831,7 +831,7 @@ export function comparePathsCaseSensitive(a: string, b: string) { * * @internal */ -export function comparePathsCaseInsensitive(a: string, b: string) { +export function comparePathsCaseInsensitive(a: string, b: string): Comparison { return comparePathsWorker(a, b, compareStringsCaseInsensitive); } @@ -960,12 +960,12 @@ export function convertToRelativePath(absoluteOrRelativePath: string, basePath: } /** @internal */ -export function getRelativePathFromFile(from: string, to: string, getCanonicalFileName: GetCanonicalFileName) { +export function getRelativePathFromFile(from: string, to: string, getCanonicalFileName: GetCanonicalFileName): string { return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName)); } /** @internal */ -export function getRelativePathToDirectoryOrUrl(directoryPathOrUrl: string, relativeOrAbsolutePath: string, currentDirectory: string, getCanonicalFileName: GetCanonicalFileName, isAbsolutePathAnUrl: boolean) { +export function getRelativePathToDirectoryOrUrl(directoryPathOrUrl: string, relativeOrAbsolutePath: string, currentDirectory: string, getCanonicalFileName: GetCanonicalFileName, isAbsolutePathAnUrl: boolean): string { const pathComponents = getPathComponentsRelativeTo( resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), @@ -1010,6 +1010,6 @@ export function forEachAncestorDirectory(directory: P, call } /** @internal */ -export function isNodeModulesDirectory(dirPath: Path) { +export function isNodeModulesDirectory(dirPath: Path): boolean { return endsWith(dirPath, "/node_modules"); } diff --git a/src/compiler/performance.ts b/src/compiler/performance.ts index 6784d1d0f7dce..e176474b37ba8 100644 --- a/src/compiler/performance.ts +++ b/src/compiler/performance.ts @@ -26,7 +26,7 @@ export interface Timer { } /** @internal */ -export function createTimerIf(condition: boolean, measureName: string, startMarkName: string, endMarkName: string) { +export function createTimerIf(condition: boolean, measureName: string, startMarkName: string, endMarkName: string): Timer { return condition ? createTimer(measureName, startMarkName, endMarkName) : nullTimer; } @@ -71,7 +71,7 @@ const durations = new Map(); * * @internal */ -export function mark(markName: string) { +export function mark(markName: string): void { if (enabled) { const count = counts.get(markName) ?? 0; counts.set(markName, count + 1); @@ -94,7 +94,7 @@ export function mark(markName: string) { * * @internal */ -export function measure(measureName: string, startMarkName?: string, endMarkName?: string) { +export function measure(measureName: string, startMarkName?: string, endMarkName?: string): void { if (enabled) { const end = (endMarkName !== undefined ? marks.get(endMarkName) : undefined) ?? timestamp(); const start = (startMarkName !== undefined ? marks.get(startMarkName) : undefined) ?? timeorigin; @@ -111,7 +111,7 @@ export function measure(measureName: string, startMarkName?: string, endMarkName * * @internal */ -export function getCount(markName: string) { +export function getCount(markName: string): number { return counts.get(markName) || 0; } @@ -122,7 +122,7 @@ export function getCount(markName: string) { * * @internal */ -export function getDuration(measureName: string) { +export function getDuration(measureName: string): number { return durations.get(measureName) || 0; } @@ -133,24 +133,24 @@ export function getDuration(measureName: string) { * * @internal */ -export function forEachMeasure(cb: (measureName: string, duration: number) => void) { +export function forEachMeasure(cb: (measureName: string, duration: number) => void): void { durations.forEach((duration, measureName) => cb(measureName, duration)); } /** @internal */ -export function forEachMark(cb: (markName: string) => void) { +export function forEachMark(cb: (markName: string) => void): void { marks.forEach((_time, markName) => cb(markName)); } /** @internal */ -export function clearMeasures(name?: string) { +export function clearMeasures(name?: string): void { if (name !== undefined) durations.delete(name); else durations.clear(); performanceImpl?.clearMeasures(name); } /** @internal */ -export function clearMarks(name?: string) { +export function clearMarks(name?: string): void { if (name !== undefined) { counts.delete(name); marks.delete(name); @@ -167,7 +167,7 @@ export function clearMarks(name?: string) { * * @internal */ -export function isEnabled() { +export function isEnabled(): boolean { return enabled; } @@ -199,7 +199,7 @@ export function enable(system: System = sys) { * * @internal */ -export function disable() { +export function disable(): void { if (enabled) { marks.clear(); counts.clear(); diff --git a/src/compiler/performanceCore.ts b/src/compiler/performanceCore.ts index ba03e7a3314b9..38d8badace719 100644 --- a/src/compiler/performanceCore.ts +++ b/src/compiler/performanceCore.ts @@ -90,7 +90,7 @@ const nativePerformanceHooks = tryGetPerformanceHooks(); const nativePerformanceTime = nativePerformanceHooks?.performanceTime; /** @internal */ -export function tryGetNativePerformanceHooks() { +export function tryGetNativePerformanceHooks(): PerformanceHooks | undefined { return nativePerformanceHooks; } @@ -99,4 +99,4 @@ export function tryGetNativePerformanceHooks() { * * @internal */ -export const timestamp = nativePerformanceTime ? () => nativePerformanceTime.now() : Date.now; +export const timestamp: () => number = nativePerformanceTime ? () => nativePerformanceTime.now() : Date.now; diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 198dfa0975457..48aa11b4046b6 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -521,7 +521,15 @@ export function changeCompilerHostLikeToUseCache( host: CompilerHostLikeForCache, toPath: (fileName: string) => Path, getSourceFile?: CompilerHost["getSourceFile"], -) { +): { + originalReadFile: (fileName: string, encoding?: string) => string | undefined; + originalFileExists: (fileName: string) => boolean; + originalDirectoryExists: ((directory: string) => boolean) | undefined; + originalCreateDirectory: ((directory: string) => void) | undefined; + originalWriteFile: WriteFileCallback | undefined; + getSourceFileWithCache: ((fileName: string, languageVersionOrOptions: ScriptTarget | CreateSourceFileOptions, onError?: (message: string) => void, shouldCreateNewSourceFile?: boolean) => SourceFile | undefined) | undefined; + readFileWithCache: (fileName: string) => string | undefined; +} { const originalReadFile = host.readFile; const originalFileExists = host.fileExists; const originalDirectoryExists = host.directoryExists; @@ -704,7 +712,7 @@ function getCategoryFormat(category: DiagnosticCategory): ForegroundColorEscapeS } /** @internal */ -export function formatColorAndReset(text: string, formatStyle: string) { +export function formatColorAndReset(text: string, formatStyle: string): string { return formatStyle + text + resetEscapeSequence; } @@ -763,7 +771,7 @@ function formatCodeSpan(file: SourceFile, start: number, length: number, indent: } /** @internal */ -export function formatLocation(file: SourceFile, start: number, host: FormatDiagnosticsHost, color = formatColorAndReset) { +export function formatLocation(file: SourceFile, start: number, host: FormatDiagnosticsHost, color: typeof formatColorAndReset = formatColorAndReset): string { const { line: firstLine, character: firstLineChar } = getLineAndCharacterOfPosition(file, start); // TODO: GH#18217 const relativeFileName = host ? convertToRelativePath(file.fileName, host.getCurrentDirectory(), fileName => host.getCanonicalFileName(fileName)) : file.fileName; @@ -854,7 +862,7 @@ export interface SourceFileImportsList { * Calculates the resulting resolution mode for some reference in some file - this is generally the explicitly * provided resolution mode in the reference, unless one is not present, in which case it is the mode of the containing file. */ -export function getModeForFileReference(ref: FileReference | string, containingFileMode: ResolutionMode) { +export function getModeForFileReference(ref: FileReference | string, containingFileMode: ResolutionMode): ResolutionMode { return (isString(ref) ? containingFileMode : ref.resolutionMode) || containingFileMode; } @@ -881,7 +889,7 @@ export function getModeForResolutionAtIndex(file: SourceFileImportsList, index: } /** @internal */ -export function isExclusivelyTypeOnlyImportOrExport(decl: ImportDeclaration | ExportDeclaration | JSDocImportTag) { +export function isExclusivelyTypeOnlyImportOrExport(decl: ImportDeclaration | ExportDeclaration | JSDocImportTag): boolean { if (isExportDeclaration(decl)) { return decl.isTypeOnly; } @@ -929,7 +937,7 @@ export function isExclusivelyTypeOnlyImportOrExport(decl: ImportDeclaration | Ex * should be the options of the referenced project, not the referencing project. * @returns The final resolution mode of the import */ -export function getModeForUsageLocation(file: SourceFile, usage: StringLiteralLike, compilerOptions: CompilerOptions) { +export function getModeForUsageLocation(file: SourceFile, usage: StringLiteralLike, compilerOptions: CompilerOptions): ResolutionMode { return getModeForUsageLocationWorker(file, usage, compilerOptions); } @@ -982,7 +990,7 @@ function getEmitSyntaxForUsageLocationWorker(file: Pick void) { +export function getResolutionModeOverride(node: ImportAttributes | undefined, grammarErrorOnNode?: (node: Node, diagnostic: DiagnosticMessage) => void): ModuleKind.CommonJS | ModuleKind.ESNext | undefined { if (!node) return undefined; if (length(node.elements) !== 1) { grammarErrorOnNode?.( @@ -1182,13 +1190,13 @@ function forEachProjectReference( export const inferredTypesContainingFile = "__inferred type names__.ts"; /** @internal */ -export function getInferredLibraryNameResolveFrom(options: CompilerOptions, currentDirectory: string, libFileName: string) { +export function getInferredLibraryNameResolveFrom(options: CompilerOptions, currentDirectory: string, libFileName: string): string { const containingDirectory = options.configFilePath ? getDirectoryPath(options.configFilePath) : currentDirectory; return combinePaths(containingDirectory, `__lib_node_modules_lookup_${libFileName}__.ts`); } /** @internal */ -export function getLibraryNameFromLibFileName(libFileName: string) { +export function getLibraryNameFromLibFileName(libFileName: string): string { // Support resolving to lib.dom.d.ts -> @typescript/lib-dom, and // lib.dom.iterable.d.ts -> @typescript/lib-dom/iterable // lib.es2015.symbol.wellknown.d.ts -> @typescript/lib-es2015/symbol-wellknown @@ -1393,7 +1401,7 @@ export function getImpliedNodeFormatForFileWorker( packageJsonInfoCache: PackageJsonInfoCache | undefined, host: ModuleResolutionHost, options: CompilerOptions, -) { +): ModuleKind.CommonJS | ModuleKind.ESNext | Partial | undefined { const moduleResolution = getEmitModuleResolutionKind(options); const shouldLookupFromPackageJson = ModuleResolutionKind.Node16 <= moduleResolution && moduleResolution <= ModuleResolutionKind.NodeNext || pathContainsNodeModules(fileName); diff --git a/src/compiler/resolutionCache.ts b/src/compiler/resolutionCache.ts index cfe6b95555244..9cbad9a991fcc 100644 --- a/src/compiler/resolutionCache.ts +++ b/src/compiler/resolutionCache.ts @@ -304,7 +304,7 @@ function perceivedOsRootLengthForWatching(pathComponents: Readonly, length?: number) { +export function canWatchDirectoryOrFile(pathComponents: Readonly, length?: number): boolean { if (length === undefined) length = pathComponents.length; // Ignore "/", "c:/" // ignore "/user", "c:/users" or "c:/folderAtRoot" @@ -314,7 +314,7 @@ export function canWatchDirectoryOrFile(pathComponents: Readonly string | undefined) { +export function getRootDirectoryOfResolutionCache(rootDirForResolution: string, getCurrentDirectory: () => string | undefined): string { const normalized = getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory()); return !isDiskPathRoot(normalized) ? removeTrailingDirectorySeparator(normalized) : diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts index ce01171fcaafe..fb318bce41a91 100644 --- a/src/compiler/scanner.ts +++ b/src/compiler/scanner.ts @@ -384,7 +384,7 @@ function lookupInUnicodeMap(code: number, map: readonly number[]): boolean { } /** @internal */ -export function isUnicodeIdentifierStart(code: number, languageVersion: ScriptTarget | undefined) { +export function isUnicodeIdentifierStart(code: number, languageVersion: ScriptTarget | undefined): boolean { return languageVersion! >= ScriptTarget.ES2015 ? lookupInUnicodeMap(code, unicodeESNextIdentifierStart) : lookupInUnicodeMap(code, unicodeES5IdentifierStart); @@ -515,7 +515,7 @@ export function computeLineAndCharacterOfPosition(lineStarts: readonly number[], * @internal * We assume the first line starts at position 0 and 'position' is non-negative. */ -export function computeLineOfPosition(lineStarts: readonly number[], position: number, lowerBound?: number) { +export function computeLineOfPosition(lineStarts: readonly number[], position: number, lowerBound?: number): number { let lineNumber = binarySearch(lineStarts, position, identity, compareValues, lowerBound); if (lineNumber < 0) { // If the actual position was not found, @@ -532,7 +532,7 @@ export function computeLineOfPosition(lineStarts: readonly number[], position: n } /** @internal */ -export function getLinesBetweenPositions(sourceFile: SourceFileLike, pos1: number, pos2: number) { +export function getLinesBetweenPositions(sourceFile: SourceFileLike, pos1: number, pos2: number): number { if (pos1 === pos2) return 0; const lineStarts = getLineStarts(sourceFile); const lower = Math.min(pos1, pos2); @@ -939,11 +939,11 @@ export function forEachTrailingCommentRange(text: string, pos: number, cb: return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ true, cb, state!); } -export function reduceEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T, initial: U) { +export function reduceEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T, initial: U): U | undefined { return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ false, cb, state, initial); } -export function reduceEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T, initial: U) { +export function reduceEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T, initial: U): U | undefined { return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ true, cb, state, initial); } @@ -1017,7 +1017,7 @@ const enum ClassSetExpressionType { } // Creates a scanner over a (possibly unspecified) range of a piece of text. -export function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant = LanguageVariant.Standard, textInitial?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner { +export function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant: LanguageVariant = LanguageVariant.Standard, textInitial?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner { // Why var? It avoids TDZ checks in the runtime which can be costly. // See: https://github.com/microsoft/TypeScript/issues/52924 /* eslint-disable no-var */ @@ -4053,7 +4053,7 @@ function utf16EncodeAsStringFallback(codePoint: number) { const utf16EncodeAsStringWorker: (codePoint: number) => string = (String as any).fromCodePoint ? codePoint => (String as any).fromCodePoint(codePoint) : utf16EncodeAsStringFallback; /** @internal */ -export function utf16EncodeAsString(codePoint: number) { +export function utf16EncodeAsString(codePoint: number): string { return utf16EncodeAsStringWorker(codePoint); } diff --git a/src/compiler/semver.ts b/src/compiler/semver.ts index 2232d48b691cc..f9423d77f5232 100644 --- a/src/compiler/semver.ts +++ b/src/compiler/semver.ts @@ -44,7 +44,7 @@ const numericIdentifierRegExp = /^(?:0|[1-9]\d*)$/; * @internal */ export class Version { - static readonly zero = new Version(0, 0, 0, ["0"]); + static readonly zero: Version = new Version(0, 0, 0, ["0"]); readonly major: number; readonly minor: number; @@ -77,7 +77,7 @@ export class Version { this.build = buildArray; } - static tryParse(text: string) { + static tryParse(text: string): Version | undefined { const result = tryParseComponents(text); if (!result) return undefined; @@ -85,7 +85,7 @@ export class Version { return new Version(major, minor, patch, prerelease, build); } - compareTo(other: Version | undefined) { + compareTo(other: Version | undefined): Comparison { // https://semver.org/#spec-item-11 // > Precedence is determined by the first difference when comparing each of these // > identifiers from left to right as follows: Major, minor, and patch versions are @@ -106,7 +106,7 @@ export class Version { || comparePrereleaseIdentifiers(this.prerelease, other.prerelease); } - increment(field: "major" | "minor" | "patch") { + increment(field: "major" | "minor" | "patch"): Version { switch (field) { case "major": return new Version(this.major + 1, 0, 0); @@ -119,7 +119,7 @@ export class Version { } } - with(fields: { major?: number; minor?: number; patch?: number; prerelease?: string | readonly string[]; build?: string | readonly string[]; }) { + with(fields: { major?: number; minor?: number; patch?: number; prerelease?: string | readonly string[]; build?: string | readonly string[]; }): Version { const { major = this.major, minor = this.minor, @@ -130,7 +130,7 @@ export class Version { return new Version(major, minor, patch, prerelease, build); } - toString() { + toString(): string { let result = `${this.major}.${this.minor}.${this.patch}`; if (some(this.prerelease)) result += `-${this.prerelease.join(".")}`; if (some(this.build)) result += `+${this.build.join(".")}`; @@ -210,7 +210,7 @@ export class VersionRange { this._alternatives = spec ? Debug.checkDefined(parseRange(spec), "Invalid range spec.") : emptyArray; } - static tryParse(text: string) { + static tryParse(text: string): VersionRange | undefined { const sets = parseRange(text); if (sets) { const range = new VersionRange(""); @@ -224,12 +224,12 @@ export class VersionRange { * Tests whether a version matches the range. This is equivalent to `satisfies(version, range, { includePrerelease: true })`. * in `node-semver`. */ - test(version: Version | string) { + test(version: Version | string): boolean { if (typeof version === "string") version = new Version(version); return testDisjunction(version, this._alternatives); } - toString() { + toString(): string { return formatDisjunction(this._alternatives); } } diff --git a/src/compiler/sourcemap.ts b/src/compiler/sourcemap.ts index 9f3c5a05d4266..1ce989b250af7 100644 --- a/src/compiler/sourcemap.ts +++ b/src/compiler/sourcemap.ts @@ -360,12 +360,12 @@ export function createSourceMapGenerator(host: EmitHost, file: string, sourceRoo // Sometimes tools can see the following line as a source mapping url comment, so we mangle it a bit (the [M]) /** @internal */ -export const sourceMapCommentRegExpDontCareLineStart = /\/\/[@#] source[M]appingURL=(.+)\r?\n?$/; // eslint-disable-line regexp/no-useless-character-class +export const sourceMapCommentRegExpDontCareLineStart: RegExp = /\/\/[@#] source[M]appingURL=(.+)\r?\n?$/; // eslint-disable-line regexp/no-useless-character-class /** @internal */ -export const sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\r?\n?$/; // eslint-disable-line regexp/no-useless-character-class +export const sourceMapCommentRegExp: RegExp = /^\/\/[@#] source[M]appingURL=(.+)\r?\n?$/; // eslint-disable-line regexp/no-useless-character-class /** @internal */ -export const whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/; +export const whitespaceOrMapCommentRegExp: RegExp = /^\s*(\/\/[@#] .*)?$/; /** @internal */ export interface LineInfo { @@ -386,7 +386,7 @@ export function getLineInfo(text: string, lineStarts: readonly number[]): LineIn * * @internal */ -export function tryGetSourceMappingURL(lineInfo: LineInfo) { +export function tryGetSourceMappingURL(lineInfo: LineInfo): string | undefined { for (let index = lineInfo.getLineCount() - 1; index >= 0; index--) { const line = lineInfo.getLineText(index); const comment = sourceMapCommentRegExp.exec(line); @@ -419,7 +419,7 @@ function isRawSourceMap(x: any): x is RawSourceMap { /* eslint-enable no-restricted-syntax */ /** @internal */ -export function tryParseRawSourceMap(text: string) { +export function tryParseRawSourceMap(text: string): RawSourceMap | undefined { try { const parsed = JSON.parse(text); if (isRawSourceMap(parsed)) { @@ -616,7 +616,7 @@ export function decodeMappings(mappings: string): MappingsDecoder { } /** @internal */ -export function sameMapping(left: T, right: T) { +export function sameMapping(left: T, right: T): boolean { return left === right || left.generatedLine === right.generatedLine && left.generatedCharacter === right.generatedCharacter diff --git a/src/compiler/symbolWalker.ts b/src/compiler/symbolWalker.ts index 6942028d9af79..3f1181236f90a 100644 --- a/src/compiler/symbolWalker.ts +++ b/src/compiler/symbolWalker.ts @@ -38,7 +38,7 @@ export function createGetSymbolWalker( getConstraintOfTypeParameter: (typeParameter: TypeParameter) => Type | undefined, getFirstIdentifier: (node: EntityNameOrEntityNameExpression) => Identifier, getTypeArguments: (type: TypeReference) => readonly Type[], -) { +): (accept?: (symbol: Symbol) => boolean) => SymbolWalker { return getSymbolWalker; function getSymbolWalker(accept: (symbol: Symbol) => boolean = () => true): SymbolWalker { diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index a5b24bf854319..52a89099cf2b1 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -71,7 +71,7 @@ export function generateDjb2Hash(data: string): string { * * @internal */ -export function setStackTraceLimit() { +export function setStackTraceLimit(): void { if ((Error as any).stackTraceLimit < 100) { // Also tests that we won't set the property if it doesn't exist. (Error as any).stackTraceLimit = 100; } @@ -104,10 +104,10 @@ export type HostWatchFile = (fileName: string, callback: FileWatcherCallback, po export type HostWatchDirectory = (fileName: string, callback: DirectoryWatcherCallback, recursive: boolean, options: WatchOptions | undefined) => FileWatcher; /** @internal */ -export const missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time +export const missingFileModifiedTime: Date = new Date(0); // Any subsequent modification will occur after this time /** @internal */ -export function getModifiedTime(host: { getModifiedTime: NonNullable; }, fileName: string) { +export function getModifiedTime(host: { getModifiedTime: NonNullable; }, fileName: string): Date { return host.getModifiedTime(fileName) || missingFileModifiedTime; } @@ -128,7 +128,11 @@ function createPollingIntervalBasedLevels(levels: Levels) { const defaultChunkLevels: Levels = { Low: 32, Medium: 64, High: 256 }; let pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels); /** @internal */ -export let unchangedPollThresholds = createPollingIntervalBasedLevels(defaultChunkLevels); +export let unchangedPollThresholds: { + 250: number; + 500: number; + 2000: number; +} = createPollingIntervalBasedLevels(defaultChunkLevels); function setCustomPollingValues(system: System) { if (!system.getEnvironmentVariable) { @@ -550,7 +554,7 @@ function onWatchedFileStat(watchedFile: WatchedFile, modifiedTime: Date): boolea } /** @internal */ -export function getFileWatcherEventKind(oldTime: number, newTime: number) { +export function getFileWatcherEventKind(oldTime: number, newTime: number): FileWatcherEventKind { return oldTime === 0 ? FileWatcherEventKind.Created : newTime === 0 @@ -559,17 +563,17 @@ export function getFileWatcherEventKind(oldTime: number, newTime: number) { } /** @internal */ -export const ignoredPaths = ["/node_modules/.", "/.git", "/.#"]; +export const ignoredPaths: string[] = ["/node_modules/.", "/.git", "/.#"]; let curSysLog: (s: string) => void = noop; /** @internal */ -export function sysLog(s: string) { +export function sysLog(s: string): void { return curSysLog(s); } /** @internal */ -export function setSysLog(logger: typeof sysLog) { +export function setSysLog(logger: typeof sysLog): void { curSysLog = logger; } @@ -1375,7 +1379,7 @@ export function createSystemWatchFunctions({ * * @internal */ -export function patchWriteFileEnsuringDirectory(sys: System) { +export function patchWriteFileEnsuringDirectory(sys: System): void { // patch writefile to create folder before writing the file const originalWriteFile = sys.writeFile; sys.writeFile = (path, data, writeBom) => @@ -1997,7 +2001,7 @@ export let sys: System = (() => { })(); /** @internal @knipignore */ -export function setSys(s: System) { +export function setSys(s: System): void { sys = s; } diff --git a/src/compiler/tracing.ts b/src/compiler/tracing.ts index 94e9bd57c83b6..5d7138d1c22eb 100644 --- a/src/compiler/tracing.ts +++ b/src/compiler/tracing.ts @@ -55,7 +55,7 @@ export namespace tracingEnabled { } /** Starts tracing for the given project. */ - export function startTracing(tracingMode: Mode, traceDir: string, configFilePath?: string) { + export function startTracing(tracingMode: Mode, traceDir: string, configFilePath?: string): void { Debug.assert(!tracing, "Tracing already started"); if (fs === undefined) { @@ -105,7 +105,7 @@ export namespace tracingEnabled { } /** Stops tracing for the in-progress project and dumps the type catalog. */ - export function stopTracing() { + export function stopTracing(): void { Debug.assert(tracing, "Tracing is not in progress"); Debug.assert(!!typeCatalog.length === (mode !== "server")); // Have a type catalog iff not in server mode @@ -139,7 +139,7 @@ export namespace tracingEnabled { Session = "session", } - export function instant(phase: Phase, name: string, args?: Args) { + export function instant(phase: Phase, name: string, args?: Args): void { writeEvent("I", phase, name, args, `"s":"g"`); } @@ -151,18 +151,18 @@ export namespace tracingEnabled { * In the future we might implement an exit handler to dump unfinished events which would deprecate * these operations. */ - export function push(phase: Phase, name: string, args?: Args, separateBeginAndEnd = false) { + export function push(phase: Phase, name: string, args?: Args, separateBeginAndEnd = false): void { if (separateBeginAndEnd) { writeEvent("B", phase, name, args); } eventStack.push({ phase, name, args, time: 1000 * timestamp(), separateBeginAndEnd }); } - export function pop(results?: Args) { + export function pop(results?: Args): void { Debug.assert(eventStack.length > 0); writeStackEvent(eventStack.length - 1, 1000 * timestamp(), results); eventStack.length--; } - export function popAll() { + export function popAll(): void { const endTime = 1000 * timestamp(); for (let i = eventStack.length - 1; i >= 0; i--) { writeStackEvent(i, endTime); @@ -348,7 +348,7 @@ export namespace tracingEnabled { performance.measure("Dump types", "beginDumpTypes", "endDumpTypes"); } - export function dumpLegend() { + export function dumpLegend(): void { if (!legendPath) { return; } @@ -365,9 +365,9 @@ export namespace tracingEnabled { // define after tracingEnabled is initialized /** @internal */ -export const startTracing = tracingEnabled.startTracing; +export const startTracing: typeof tracingEnabled.startTracing = tracingEnabled.startTracing; /** @internal */ -export const dumpTracingLegend = tracingEnabled.dumpLegend; +export const dumpTracingLegend: typeof tracingEnabled.dumpLegend = tracingEnabled.dumpLegend; /** @internal */ export interface TracingNode { diff --git a/src/compiler/transformer.ts b/src/compiler/transformer.ts index bd181e5f3c028..0d499f3a08298 100644 --- a/src/compiler/transformer.ts +++ b/src/compiler/transformer.ts @@ -222,12 +222,12 @@ function wrapDeclarationTransformerFactory(transformer: TransformerFactory void) { +export function noEmitNotification(hint: EmitHint, node: Node, callback: (hint: EmitHint, node: Node) => void): void { callback(hint, node); } diff --git a/src/compiler/transformers/classThis.ts b/src/compiler/transformers/classThis.ts index e357c9b6e4f8b..86eb48346e50e 100644 --- a/src/compiler/transformers/classThis.ts +++ b/src/compiler/transformers/classThis.ts @@ -87,7 +87,7 @@ export function isClassThisAssignmentBlock(node: Node): node is ClassThisAssignm * `_classThis` (or similar) variable. * @internal */ -export function classHasClassThisAssignment(node: ClassLikeDeclaration) { +export function classHasClassThisAssignment(node: ClassLikeDeclaration): boolean { return !!node.emitNode?.classThis && some(node.members, isClassThisAssignmentBlock); } diff --git a/src/compiler/transformers/declarations.ts b/src/compiler/transformers/declarations.ts index b12c3acf84c3e..08683627cc944 100644 --- a/src/compiler/transformers/declarations.ts +++ b/src/compiler/transformers/declarations.ts @@ -253,7 +253,11 @@ const declarationEmitInternalNodeBuilderFlags = InternalNodeBuilderFlags.AllowUn * * @internal */ -export function transformDeclarations(context: TransformationContext) { +export function transformDeclarations(context: TransformationContext): { + (node: Bundle): Bundle; + (node: SourceFile): SourceFile; + (node: SourceFile | Bundle): SourceFile | Bundle; +} { const throwDiagnostic = () => Debug.fail("Diagnostic emitted without context"); let getSymbolAccessibilityDiagnostic: GetSymbolAccessibilityDiagnostic = throwDiagnostic; let needsDeclare = true; diff --git a/src/compiler/transformers/declarations/diagnostics.ts b/src/compiler/transformers/declarations/diagnostics.ts index d7a6c54f5eaf0..7e2978d9c59b8 100644 --- a/src/compiler/transformers/declarations/diagnostics.ts +++ b/src/compiler/transformers/declarations/diagnostics.ts @@ -161,7 +161,7 @@ export function canProduceDiagnostics(node: Node): node is DeclarationDiagnostic } /** @internal */ -export function createGetSymbolAccessibilityDiagnosticForNodeName(node: DeclarationDiagnosticProducing) { +export function createGetSymbolAccessibilityDiagnosticForNodeName(node: DeclarationDiagnosticProducing): (symbolAccessibilityResult: SymbolAccessibilityResult) => SymbolAccessibilityDiagnostic | undefined { if (isSetAccessor(node) || isGetAccessor(node)) { return getAccessorNameVisibilityError; } @@ -603,7 +603,7 @@ export function createGetSymbolAccessibilityDiagnosticForNode(node: DeclarationD } /** @internal */ -export function createGetIsolatedDeclarationErrors(resolver: EmitResolver) { +export function createGetIsolatedDeclarationErrors(resolver: EmitResolver): (node: Node) => DiagnosticWithLocation { const relatedSuggestionByDeclarationKind = { [SyntaxKind.ArrowFunction]: Diagnostics.Add_a_return_type_to_the_function_expression, [SyntaxKind.FunctionExpression]: Diagnostics.Add_a_return_type_to_the_function_expression, diff --git a/src/compiler/transformers/es2017.ts b/src/compiler/transformers/es2017.ts index 8947a94a079f4..3a80a84334eef 100644 --- a/src/compiler/transformers/es2017.ts +++ b/src/compiler/transformers/es2017.ts @@ -1056,7 +1056,7 @@ export function transformES2017(context: TransformationContext): (x: SourceFile * * @internal */ -export function createSuperAccessVariableStatement(factory: NodeFactory, resolver: EmitResolver, node: FunctionLikeDeclaration, names: Set<__String>) { +export function createSuperAccessVariableStatement(factory: NodeFactory, resolver: EmitResolver, node: FunctionLikeDeclaration, names: Set<__String>): VariableStatement { // Create a variable declaration with a getter/setter (if binding) definition for each name: // const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... }); const hasBinding = resolver.hasNodeCheckFlag(node, NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync); diff --git a/src/compiler/transformers/module/impliedNodeFormatDependent.ts b/src/compiler/transformers/module/impliedNodeFormatDependent.ts index 7a5bf9e210fcd..8a7ce9af79373 100644 --- a/src/compiler/transformers/module/impliedNodeFormatDependent.ts +++ b/src/compiler/transformers/module/impliedNodeFormatDependent.ts @@ -14,7 +14,7 @@ import { } from "../../_namespaces/ts.js"; /** @internal */ -export function transformImpliedNodeFormatDependentModule(context: TransformationContext) { +export function transformImpliedNodeFormatDependentModule(context: TransformationContext): (node: SourceFile | Bundle) => SourceFile | Bundle { const previousOnSubstituteNode = context.onSubstituteNode; const previousOnEmitNode = context.onEmitNode; diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index 036b8d60f9f27..4d0d900df6fd1 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -231,7 +231,7 @@ const enum ClassFacts { } /** @internal */ -export function transformTypeScript(context: TransformationContext) { +export function transformTypeScript(context: TransformationContext): (node: SourceFile | Bundle) => SourceFile | Bundle { const { factory, getEmitHelperFactory: emitHelpers, diff --git a/src/compiler/transformers/utilities.ts b/src/compiler/transformers/utilities.ts index fd1501e1d068d..bf59af6097718 100644 --- a/src/compiler/transformers/utilities.ts +++ b/src/compiler/transformers/utilities.ts @@ -96,7 +96,7 @@ import { } from "../_namespaces/ts.js"; /** @internal */ -export function getOriginalNodeId(node: Node) { +export function getOriginalNodeId(node: Node): number { node = getOriginalNode(node); return node ? getNodeId(node) : 0; } @@ -381,19 +381,19 @@ function multiMapSparseArrayAdd(map: V[][], key: number, value: V): V[] { export class IdentifierNameMap { private readonly _map = new Map(); - get size() { + get size(): number { return this._map.size; } - has(key: Identifier) { + has(key: Identifier): boolean { return this._map.has(IdentifierNameMap.toKey(key)); } - get(key: Identifier) { + get(key: Identifier): V | undefined { return this._map.get(IdentifierNameMap.toKey(key)); } - set(key: Identifier, value: V) { + set(key: Identifier, value: V): this { this._map.set(IdentifierNameMap.toKey(key), value); return this; } @@ -406,7 +406,7 @@ export class IdentifierNameMap { this._map.clear(); } - values() { + values(): IterableIterator { return this._map.values(); } @@ -460,7 +460,7 @@ class IdentifierNameMultiMap extends IdentifierNameMap { * * @internal */ -export function isSimpleCopiableExpression(expression: Expression) { +export function isSimpleCopiableExpression(expression: Expression): boolean { return isStringLiteralLike(expression) || expression.kind === SyntaxKind.NumericLiteral || isKeyword(expression.kind) || @@ -474,7 +474,7 @@ export function isSimpleCopiableExpression(expression: Expression) { * * @internal */ -export function isSimpleInlineableExpression(expression: Expression) { +export function isSimpleInlineableExpression(expression: Expression): boolean { return !isIdentifier(expression) && isSimpleCopiableExpression(expression); } @@ -560,7 +560,7 @@ function findSuperStatementIndexPathWorker(statements: NodeArray, sta * * @internal */ -export function findSuperStatementIndexPath(statements: NodeArray, start: number) { +export function findSuperStatementIndexPath(statements: NodeArray, start: number): number[] { const indices: number[] = []; findSuperStatementIndexPathWorker(statements, start, indices); return indices; @@ -821,7 +821,7 @@ export function newPrivateEnvironment(data: TData): PrivateEnviro export function getPrivateIdentifier( privateEnv: PrivateEnvironment | undefined, name: PrivateIdentifier, -) { +): TEntry | undefined { return isGeneratedPrivateIdentifier(name) ? privateEnv?.generatedIdentifiers?.get(getNodeForGeneratedName(name)) : privateEnv?.identifiers?.get(name.escapedText); @@ -832,7 +832,7 @@ export function setPrivateIdentifier( privateEnv: PrivateEnvironment, name: PrivateIdentifier, entry: TEntry, -) { +): void { if (isGeneratedPrivateIdentifier(name)) { privateEnv.generatedIdentifiers ??= new Map(); privateEnv.generatedIdentifiers.set(getNodeForGeneratedName(name), entry); @@ -851,7 +851,7 @@ export function accessPrivateIdentifier< >( env: LexicalEnvironment | undefined, name: PrivateIdentifier, -) { +): TPrivateEntry | undefined { return walkUpLexicalEnvironments(env, env => getPrivateIdentifier(env.privateEnv, name)); } @@ -860,6 +860,6 @@ function isSimpleParameter(node: ParameterDeclaration) { } /** @internal */ -export function isSimpleParameterList(nodes: NodeArray) { +export function isSimpleParameterList(nodes: NodeArray): boolean { return every(nodes, isSimpleParameter); } diff --git a/src/compiler/tsbuildPublic.ts b/src/compiler/tsbuildPublic.ts index 3230699eba3c0..efdcdb7502e23 100644 --- a/src/compiler/tsbuildPublic.ts +++ b/src/compiler/tsbuildPublic.ts @@ -301,13 +301,13 @@ function createSolutionBuilderHostBase(system: System, return host; } -export function createSolutionBuilderHost(system = sys, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportSolutionBuilderStatus?: DiagnosticReporter, reportErrorSummary?: ReportEmitErrorSummary) { +export function createSolutionBuilderHost(system: System = sys, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportSolutionBuilderStatus?: DiagnosticReporter, reportErrorSummary?: ReportEmitErrorSummary): SolutionBuilderHost { const host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus) as SolutionBuilderHost; host.reportErrorSummary = reportErrorSummary; return host; } -export function createSolutionBuilderWithWatchHost(system = sys, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportSolutionBuilderStatus?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter) { +export function createSolutionBuilderWithWatchHost(system: System = sys, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportSolutionBuilderStatus?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): SolutionBuilderWithWatchHost { const host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus) as SolutionBuilderWithWatchHost; const watchHost = createWatchHost(system, reportWatchStatus); copyProperties(host, watchHost); diff --git a/src/compiler/tsconfig.json b/src/compiler/tsconfig.json index cbbd3df0beb72..df37314573bac 100644 --- a/src/compiler/tsconfig.json +++ b/src/compiler/tsconfig.json @@ -1,7 +1,8 @@ { "extends": "../tsconfig-base", "compilerOptions": { - "types": ["node"] + "types": ["node"], + "isolatedDeclarations": true }, "references": [], diff --git a/src/compiler/types.ts b/src/compiler/types.ts index ec5aa60564eac..2fadf70ee42ed 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -7570,6 +7570,7 @@ export const enum ScriptKind { // NOTE: We must reevaluate the target for upcoming features when each successive TC39 edition is ratified in // June of each year. This includes changes to `LanguageFeatureMinimumTarget`, `ScriptTarget`, // transformers/esnext.ts, commandLineParser.ts, and the contents of each lib/esnext.*.d.ts file. +// IF UPDATING 'ScriptTarget', ALSO UPDATE 'LanguageFeatureMinimumTarget' (if needed) export const enum ScriptTarget { /** @deprecated */ ES3 = 0, @@ -8335,62 +8336,80 @@ export type EmitHelperUniqueNameCallback = (name: string) => string; * @internal */ export const enum LanguageFeatureMinimumTarget { + // These are copied from 'ScriptTarget' since under isolatedDeclarations, enums cannot have references to external symbols. + // Make sure these are updated alongside any changes to 'ScriptTarget'. + /**@deprecated */ + ES3 = 0, + ES5 = 1, + ES2015 = 2, + ES2016 = 3, + ES2017 = 4, + ES2018 = 5, + ES2019 = 6, + ES2020 = 7, + ES2021 = 8, + ES2022 = 9, + ES2023 = 10, + ESNext = 99, + JSON = 100, + Latest = ESNext, + // ES2015 Features - Classes = ScriptTarget.ES2015, - ForOf = ScriptTarget.ES2015, - Generators = ScriptTarget.ES2015, - Iteration = ScriptTarget.ES2015, - SpreadElements = ScriptTarget.ES2015, - RestElements = ScriptTarget.ES2015, - TaggedTemplates = ScriptTarget.ES2015, - DestructuringAssignment = ScriptTarget.ES2015, - BindingPatterns = ScriptTarget.ES2015, - ArrowFunctions = ScriptTarget.ES2015, - BlockScopedVariables = ScriptTarget.ES2015, - ObjectAssign = ScriptTarget.ES2015, - RegularExpressionFlagsUnicode = ScriptTarget.ES2015, - RegularExpressionFlagsSticky = ScriptTarget.ES2015, + Classes = ES2015, + ForOf = ES2015, + Generators = ES2015, + Iteration = ES2015, + SpreadElements = ES2015, + RestElements = ES2015, + TaggedTemplates = ES2015, + DestructuringAssignment = ES2015, + BindingPatterns = ES2015, + ArrowFunctions = ES2015, + BlockScopedVariables = ES2015, + ObjectAssign = ES2015, + RegularExpressionFlagsUnicode = ES2015, + RegularExpressionFlagsSticky = ES2015, // ES2016 Features - Exponentiation = ScriptTarget.ES2016, // `x ** y` + Exponentiation = ES2016, // `x ** y` // ES2017 Features - AsyncFunctions = ScriptTarget.ES2017, // `async function f() {}` + AsyncFunctions = ES2017, // `async function f() {}` // ES2018 Features - ForAwaitOf = ScriptTarget.ES2018, // `for await (const x of y)` - AsyncGenerators = ScriptTarget.ES2018, // `async function * f() { }` - AsyncIteration = ScriptTarget.ES2018, // `Symbol.asyncIterator` - ObjectSpreadRest = ScriptTarget.ES2018, // `{ ...obj }` - RegularExpressionFlagsDotAll = ScriptTarget.ES2018, + ForAwaitOf = ES2018, // `for await (const x of y)` + AsyncGenerators = ES2018, // `async function * f() { }` + AsyncIteration = ES2018, // `Symbol.asyncIterator` + ObjectSpreadRest = ES2018, // `{ ...obj }` + RegularExpressionFlagsDotAll = ES2018, // ES2019 Features - BindinglessCatch = ScriptTarget.ES2019, // `try { } catch { }` + BindinglessCatch = ES2019, // `try { } catch { }` // ES2020 Features - BigInt = ScriptTarget.ES2020, // `0n` - NullishCoalesce = ScriptTarget.ES2020, // `a ?? b` - OptionalChaining = ScriptTarget.ES2020, // `a?.b` + BigInt = ES2020, // `0n` + NullishCoalesce = ES2020, // `a ?? b` + OptionalChaining = ES2020, // `a?.b` // ES2021 Features - LogicalAssignment = ScriptTarget.ES2021, // `a ||= b`, `a &&= b`, `a ??= b` + LogicalAssignment = ES2021, // `a ||= b`, `a &&= b`, `a ??= b` // ES2022 Features - TopLevelAwait = ScriptTarget.ES2022, - ClassFields = ScriptTarget.ES2022, - PrivateNamesAndClassStaticBlocks = ScriptTarget.ES2022, // `class C { static {} #x = y, #m() {} }`, `#x in y` - RegularExpressionFlagsHasIndices = ScriptTarget.ES2022, + TopLevelAwait = ES2022, + ClassFields = ES2022, + PrivateNamesAndClassStaticBlocks = ES2022, // `class C { static {} #x = y, #m() {} }`, `#x in y` + RegularExpressionFlagsHasIndices = ES2022, // ES2023 Features - ShebangComments = ScriptTarget.ESNext, + ShebangComments = ESNext, // Upcoming Features // NOTE: We must reevaluate the target for upcoming features when each successive TC39 edition is ratified in // June of each year. This includes changes to `LanguageFeatureMinimumTarget`, `ScriptTarget`, // transformers/esnext.ts, commandLineParser.ts, and the contents of each lib/esnext.*.d.ts file. - UsingAndAwaitUsing = ScriptTarget.ESNext, // `using x = y`, `await using x = y` - ClassAndClassElementDecorators = ScriptTarget.ESNext, // `@dec class C {}`, `class C { @dec m() {} }` - RegularExpressionFlagsUnicodeSets = ScriptTarget.ESNext, + UsingAndAwaitUsing = ESNext, // `using x = y`, `await using x = y` + ClassAndClassElementDecorators = ESNext, // `@dec class C {}`, `class C { @dec m() {} }` + RegularExpressionFlagsUnicodeSets = ESNext, } // dprint-ignore @@ -10087,7 +10106,78 @@ export interface PragmaDefinition !isJsonEqual(getCompilerOptionValue(oldOptions, o), getCompilerOptionValue(newOptions, o))); } @@ -775,12 +775,12 @@ export function usingSingleLineStringWriter(action: (writer: EmitTextWriter) => } /** @internal */ -export function getFullWidth(node: Node) { +export function getFullWidth(node: Node): number { return node.end - node.pos; } /** @internal */ -export function projectReferenceIsEqualTo(oldRef: ProjectReference, newRef: ProjectReference) { +export function projectReferenceIsEqualTo(oldRef: ProjectReference, newRef: ProjectReference): boolean { return oldRef.path === newRef.path && !oldRef.prepend === !newRef.prepend && !oldRef.circular === !newRef.circular; @@ -801,17 +801,17 @@ export function moduleResolutionIsEqualTo(oldResolution: ResolvedModuleWithFaile } /** @internal */ -export function getResolvedModuleFromResolution(resolution: ResolvedModuleWithFailedLookupLocations) { +export function getResolvedModuleFromResolution(resolution: ResolvedModuleWithFailedLookupLocations): ResolvedModuleFull | undefined { return resolution.resolvedModule; } /** @internal */ -export function getResolvedTypeReferenceDirectiveFromResolution(resolution: ResolvedTypeReferenceDirectiveWithFailedLookupLocations) { +export function getResolvedTypeReferenceDirectiveFromResolution(resolution: ResolvedTypeReferenceDirectiveWithFailedLookupLocations): ResolvedTypeReferenceDirective | undefined { return resolution.resolvedTypeReferenceDirective; } /** @internal */ -export function createModuleNotFoundChain(sourceFile: SourceFile, host: TypeCheckerHost, moduleReference: string, mode: ResolutionMode, packageName: string) { +export function createModuleNotFoundChain(sourceFile: SourceFile, host: TypeCheckerHost, moduleReference: string, mode: ResolutionMode, packageName: string): DiagnosticMessageChain { const alternateResult = host.getResolvedModule(sourceFile, moduleReference, mode)?.alternateResult; const alternateResultMessage = alternateResult && (getEmitModuleResolutionKind(host.getCompilerOptions()) === ModuleResolutionKind.Node10 ? [Diagnostics.There_are_types_at_0_but_this_result_could_not_be_resolved_under_your_current_moduleResolution_setting_Consider_updating_to_node16_nodenext_or_bundler, [alternateResult]] as const @@ -850,7 +850,7 @@ export function createModuleNotFoundChain(sourceFile: SourceFile, host: TypeChec } /** @internal */ -export function createModeMismatchDetails(currentSourceFile: SourceFile) { +export function createModeMismatchDetails(currentSourceFile: SourceFile): DiagnosticMessageChain { const ext = tryGetExtensionFromPath(currentSourceFile.fileName); const scope = currentSourceFile.packageJsonScope; const targetExt = ext === Extension.Ts ? Extension.Mts : ext === Extension.Js ? Extension.Mjs : undefined; @@ -969,7 +969,7 @@ export function getSourceFileOfNode(node: Node | undefined): SourceFile | undefi } /** @internal */ -export function getSourceFileOfModule(module: Symbol) { +export function getSourceFileOfModule(module: Symbol): SourceFile | undefined { return getSourceFileOfNode(module.valueDeclaration || getNonAugmentationDeclaration(module)); } @@ -979,7 +979,7 @@ export function isPlainJsFile(file: SourceFile | undefined, checkJs: boolean | u } /** @internal */ -export function isStatementWithLocals(node: Node) { +export function isStatementWithLocals(node: Node): boolean { switch (node.kind) { case SyntaxKind.Block: case SyntaxKind.CaseBlock: @@ -1073,7 +1073,7 @@ export function nodeIsPresent(node: Node | undefined): boolean { * Tests whether `child` is a grammar error on `parent`. * @internal */ -export function isGrammarError(parent: Node, child: Node | NodeArray) { +export function isGrammarError(parent: Node, child: Node | NodeArray): boolean { if (isTypeParameterDeclaration(parent)) return child === parent.expression; if (isClassStaticBlockDeclaration(parent)) return child === parent.modifiers; if (isPropertySignature(parent)) return child === parent.initializer; @@ -1159,7 +1159,7 @@ export function insertStatementAfterCustomPrologue(to: T[], * * @internal */ -export function isRecognizedTripleSlashComment(text: string, commentPos: number, commentEnd: number) { +export function isRecognizedTripleSlashComment(text: string, commentPos: number, commentEnd: number): boolean { // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text // so that we don't end up computing comment string and doing match for all // comments if ( @@ -1180,7 +1180,7 @@ export function isRecognizedTripleSlashComment(text: string, commentPos: number, } /** @internal */ -export function isPinnedComment(text: string, start: number) { +export function isPinnedComment(text: string, start: number): boolean { return text.charCodeAt(start + 1) === CharacterCodes.asterisk && text.charCodeAt(start + 2) === CharacterCodes.exclamation; } @@ -1338,7 +1338,7 @@ function getPos(range: Node) { * * @internal */ -export function indexOfNode(nodeArray: readonly Node[], node: Node) { +export function indexOfNode(nodeArray: readonly Node[], node: Node): number { return binarySearch(nodeArray, node, getPos, compareValues); } @@ -1367,7 +1367,7 @@ export function getInternalEmitFlags(node: Node): InternalEmitFlags { export type ScriptTargetFeatures = ReadonlyMap>; /** @internal */ -export const getScriptTargetFeatures = /* @__PURE__ */ memoize((): ScriptTargetFeatures => +export const getScriptTargetFeatures: () => ScriptTargetFeatures = /* @__PURE__ */ memoize((): ScriptTargetFeatures => new Map(Object.entries({ Array: new Map(Object.entries({ es2015: [ @@ -1829,7 +1829,7 @@ export const enum GetLiteralTextFlags { } /** @internal */ -export function getLiteralText(node: LiteralLikeNode, sourceFile: SourceFile | undefined, flags: GetLiteralTextFlags) { +export function getLiteralText(node: LiteralLikeNode, sourceFile: SourceFile | undefined, flags: GetLiteralTextFlags): string { // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. if (sourceFile && canUseOriginalText(node, flags)) { @@ -1903,7 +1903,7 @@ function canUseOriginalText(node: LiteralLikeNode, flags: GetLiteralTextFlags): } /** @internal */ -export function getTextOfConstantValue(value: string | number) { +export function getTextOfConstantValue(value: string | number): string { return isString(value) ? `"${escapeString(value)}"` : "" + value; } @@ -1915,13 +1915,13 @@ export function makeIdentifierFromModuleName(moduleName: string): string { } /** @internal */ -export function isBlockOrCatchScoped(declaration: Declaration) { +export function isBlockOrCatchScoped(declaration: Declaration): boolean { return (getCombinedNodeFlags(declaration) & NodeFlags.BlockScoped) !== 0 || isCatchClauseVariableDeclarationOrBindingElement(declaration); } /** @internal */ -export function isCatchClauseVariableDeclarationOrBindingElement(declaration: Declaration) { +export function isCatchClauseVariableDeclarationOrBindingElement(declaration: Declaration): boolean { const node = getRootDeclaration(declaration); return node.kind === SyntaxKind.VariableDeclaration && node.parent.kind === SyntaxKind.CatchClause; } @@ -1983,7 +1983,7 @@ export function isExternalModuleAugmentation(node: Node): node is AmbientModuleD } /** @internal */ -export function isModuleAugmentationExternal(node: AmbientModuleDeclaration) { +export function isModuleAugmentationExternal(node: AmbientModuleDeclaration): boolean { // external module augmentation is a ambient module declaration that is either: // - defined in the top level scope and source file is an external module // - defined inside ambient module declaration located in the top level scope and source file not an external module @@ -1997,7 +1997,7 @@ export function isModuleAugmentationExternal(node: AmbientModuleDeclaration) { } /** @internal */ -export function getNonAugmentationDeclaration(symbol: Symbol) { +export function getNonAugmentationDeclaration(symbol: Symbol): Declaration | undefined { return symbol.declarations?.find(d => !isExternalModuleAugmentation(d) && !(isModuleDeclaration(d) && isGlobalScopeAugmentation(d))); } @@ -2006,7 +2006,7 @@ function isCommonJSContainingModuleKind(kind: ModuleKind) { } /** @internal */ -export function isEffectiveExternalModule(node: SourceFile, compilerOptions: CompilerOptions) { +export function isEffectiveExternalModule(node: SourceFile, compilerOptions: CompilerOptions): boolean { return isExternalModule(node) || (isCommonJSContainingModuleKind(getEmitModuleKind(compilerOptions)) && !!node.commonJsModuleIndicator); } @@ -2015,7 +2015,7 @@ export function isEffectiveExternalModule(node: SourceFile, compilerOptions: Com * * @internal */ -export function isEffectiveStrictModeSourceFile(node: SourceFile, compilerOptions: CompilerOptions) { +export function isEffectiveStrictModeSourceFile(node: SourceFile, compilerOptions: CompilerOptions): boolean { // We can only verify strict mode for JS/TS files switch (node.scriptKind) { case ScriptKind.JS: @@ -2046,7 +2046,7 @@ export function isEffectiveStrictModeSourceFile(node: SourceFile, compilerOption } /** @internal */ -export function isAmbientPropertyDeclaration(node: PropertyDeclaration) { +export function isAmbientPropertyDeclaration(node: PropertyDeclaration): boolean { return !!(node.flags & NodeFlags.Ambient) || hasSyntacticModifier(node, ModifierFlags.Ambient); } @@ -2198,7 +2198,7 @@ export function forEachEnclosingBlockScopeContainer(node: Node, cb: (container: // Computed property names will just be emitted as "[]", where is the source // text of the expression in the computed property. /** @internal */ -export function declarationNameToString(name: DeclarationName | QualifiedName | undefined) { +export function declarationNameToString(name: DeclarationName | QualifiedName | undefined): string { return !name || getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name); } @@ -2368,7 +2368,7 @@ export function getSpanOfTokenAtPosition(sourceFile: SourceFile, pos: number): T } /** @internal */ -export function scanTokenAtPosition(sourceFile: SourceFile, pos: number) { +export function scanTokenAtPosition(sourceFile: SourceFile, pos: number): SyntaxKind { const scanner = createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.languageVariant, sourceFile.text, /*onError*/ undefined, pos); scanner.scan(); return scanner.getToken(); @@ -2482,7 +2482,7 @@ export function getErrorSpanForNode(sourceFile: SourceFile, node: Node): TextSpa } /** @internal */ -export function isGlobalSourceFile(node: Node) { +export function isGlobalSourceFile(node: Node): boolean { return node.kind === SyntaxKind.SourceFile && !isExternalOrCommonJsModule(node as SourceFile); } @@ -2534,7 +2534,7 @@ export function isVarConst(node: VariableDeclaration | VariableDeclarationList): * Gets whether a bound `VariableDeclaration` or `VariableDeclarationList` is part of a `const`, `using` or `await using` declaration. * @internal */ -export function isVarConstLike(node: VariableDeclaration | VariableDeclarationList) { +export function isVarConstLike(node: VariableDeclaration | VariableDeclarationList): boolean { const blockScopeKind = getCombinedNodeFlags(node) & NodeFlags.BlockScoped; return blockScopeKind === NodeFlags.Const || blockScopeKind === NodeFlags.Using || @@ -2578,12 +2578,12 @@ export function isPrologueDirective(node: Node): node is PrologueDirective { } /** @internal */ -export function isCustomPrologue(node: Statement) { +export function isCustomPrologue(node: Statement): boolean { return !!(getEmitFlags(node) & EmitFlags.CustomPrologue); } /** @internal */ -export function isHoistedFunction(node: Statement) { +export function isHoistedFunction(node: Statement): boolean { return isCustomPrologue(node) && isFunctionDeclaration(node); } @@ -2594,19 +2594,19 @@ function isHoistedVariable(node: VariableDeclaration) { } /** @internal */ -export function isHoistedVariableStatement(node: Statement) { +export function isHoistedVariableStatement(node: Statement): boolean { return isCustomPrologue(node) && isVariableStatement(node) && every(node.declarationList.declarations, isHoistedVariable); } /** @internal */ -export function getLeadingCommentRangesOfNode(node: Node, sourceFileOfNode: SourceFile) { +export function getLeadingCommentRangesOfNode(node: Node, sourceFileOfNode: SourceFile): CommentRange[] | undefined { return node.kind !== SyntaxKind.JsxText ? getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined; } /** @internal */ -export function getJSDocCommentRanges(node: Node, text: string) { +export function getJSDocCommentRanges(node: Node, text: string): CommentRange[] | undefined { const commentRanges = (node.kind === SyntaxKind.Parameter || node.kind === SyntaxKind.TypeParameter || node.kind === SyntaxKind.FunctionExpression || @@ -2809,7 +2809,7 @@ export function forEachYieldExpression(body: Block, visitor: (expr: YieldExpress * * @internal */ -export function getRestParameterElementType(node: TypeNode | undefined) { +export function getRestParameterElementType(node: TypeNode | undefined): TypeNode | undefined { if (node && node.kind === SyntaxKind.ArrayType) { return (node as ArrayTypeNode).elementType; } @@ -2858,20 +2858,20 @@ export function isVariableLikeOrAccessor(node: Node): node is AccessorDeclaratio } /** @internal */ -export function isVariableDeclarationInVariableStatement(node: VariableDeclaration) { +export function isVariableDeclarationInVariableStatement(node: VariableDeclaration): boolean { return node.parent.kind === SyntaxKind.VariableDeclarationList && node.parent.parent.kind === SyntaxKind.VariableStatement; } /** @internal */ -export function isCommonJsExportedExpression(node: Node) { +export function isCommonJsExportedExpression(node: Node): boolean { if (!isInJSFile(node)) return false; return (isObjectLiteralExpression(node.parent) && isBinaryExpression(node.parent.parent) && getAssignmentDeclarationKind(node.parent.parent) === AssignmentDeclarationKind.ModuleExports) || isCommonJsExportPropertyAssignment(node.parent); } /** @internal */ -export function isCommonJsExportPropertyAssignment(node: Node) { +export function isCommonJsExportPropertyAssignment(node: Node): boolean { if (!isInJSFile(node)) return false; return (isBinaryExpression(node) && getAssignmentDeclarationKind(node) === AssignmentDeclarationKind.ExportsProperty); } @@ -2884,7 +2884,7 @@ export function isValidESSymbolDeclaration(node: Node): boolean { } /** @internal */ -export function introducesArgumentsExoticObject(node: Node) { +export function introducesArgumentsExoticObject(node: Node): boolean { switch (node.kind) { case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: @@ -2939,7 +2939,7 @@ export function isThisTypePredicate(predicate: TypePredicate): predicate is This } /** @internal */ -export function forEachPropertyAssignment(objectLiteral: ObjectLiteralExpression | undefined, key: string, callback: (property: PropertyAssignment) => T | undefined, key2?: string) { +export function forEachPropertyAssignment(objectLiteral: ObjectLiteralExpression | undefined, key: string, callback: (property: PropertyAssignment) => T | undefined, key2?: string): T | undefined { return forEach(objectLiteral?.properties, property => { if (!isPropertyAssignment(property)) return undefined; const propName = tryGetTextOfPropertyName(property.name); @@ -2974,7 +2974,7 @@ export function getTsConfigPropArrayElementValue(tsConfigSourceFile: TsConfigSou } /** @internal */ -export function forEachTsConfigPropArray(tsConfigSourceFile: TsConfigSourceFile | undefined, propKey: string, callback: (property: PropertyAssignment) => T | undefined) { +export function forEachTsConfigPropArray(tsConfigSourceFile: TsConfigSourceFile | undefined, propKey: string, callback: (property: PropertyAssignment) => T | undefined): T | undefined { return forEachPropertyAssignment(getTsConfigObjectLiteralExpression(tsConfigSourceFile), propKey, callback); } @@ -3135,7 +3135,7 @@ export function isThisContainerOrFunctionBlock(node: Node): boolean { } /** @internal */ -export function isInTopLevelContext(node: Node) { +export function isInTopLevelContext(node: Node): boolean { // The name of a class or function declaration is a BindingIdentifier in its surrounding scope. if (isIdentifier(node) && (isClassDeclaration(node.parent) || isFunctionDeclaration(node.parent)) && node.parent.name === node) { node = node.parent; @@ -3145,7 +3145,7 @@ export function isInTopLevelContext(node: Node) { } /** @internal */ -export function getNewTargetContainer(node: Node) { +export function getNewTargetContainer(node: Node): FunctionDeclaration | ConstructorDeclaration | FunctionExpression | undefined { const container = getThisContainer(node, /*includeArrowFunctions*/ false, /*includeClassComputedPropertyName*/ false); if (container) { switch (container.kind) { @@ -3468,7 +3468,7 @@ export function isEmptyStringLiteral(node: StringLiteral): boolean { } /** @internal */ -export function isJSXTagName(node: Node) { +export function isJSXTagName(node: Node): boolean { const { parent } = node; if ( parent.kind === SyntaxKind.JsxOpeningElement || @@ -3608,7 +3608,7 @@ export function isInExpressionContext(node: Node): boolean { } /** @internal */ -export function isPartOfTypeQuery(node: Node) { +export function isPartOfTypeQuery(node: Node): boolean { while (node.kind === SyntaxKind.QualifiedName || node.kind === SyntaxKind.Identifier) { node = node.parent; } @@ -3626,13 +3626,13 @@ export function isExternalModuleImportEqualsDeclaration(node: Node): node is Imp } /** @internal */ -export function getExternalModuleImportEqualsDeclarationExpression(node: Node) { +export function getExternalModuleImportEqualsDeclarationExpression(node: Node): Expression { Debug.assert(isExternalModuleImportEqualsDeclaration(node)); return ((node as ImportEqualsDeclaration).moduleReference as ExternalModuleReference).expression; } /** @internal */ -export function getExternalModuleRequireArgument(node: Node) { +export function getExternalModuleRequireArgument(node: Node): false | StringLiteral { return isVariableDeclarationInitializedToBareOrAccessedRequire(node) && (getLeftmostAccessExpression(node.initializer) as CallExpression).arguments[0] as StringLiteral; } @@ -3662,7 +3662,7 @@ export function isInJsonFile(node: Node | undefined): boolean { } /** @internal */ -export function isSourceFileNotJson(file: SourceFile) { +export function isSourceFileNotJson(file: SourceFile): boolean { return !isJsonSourceFile(file); } @@ -3672,7 +3672,7 @@ export function isInJSDoc(node: Node | undefined): boolean { } /** @internal */ -export function isJSDocIndexSignature(node: TypeReferenceNode | ExpressionWithTypeArguments) { +export function isJSDocIndexSignature(node: TypeReferenceNode | ExpressionWithTypeArguments): boolean | undefined { return isTypeReferenceNode(node) && isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && @@ -3746,7 +3746,7 @@ export function isRequireVariableStatement(node: Node): node is RequireVariableS } /** @internal */ -export function isSingleOrDoubleQuote(charCode: number) { +export function isSingleOrDoubleQuote(charCode: number): boolean { return charCode === CharacterCodes.singleQuote || charCode === CharacterCodes.doubleQuote; } @@ -3756,7 +3756,7 @@ export function isStringDoubleQuoted(str: StringLiteralLike, sourceFile: SourceF } /** @internal */ -export function isAssignmentDeclaration(decl: Declaration) { +export function isAssignmentDeclaration(decl: Declaration): boolean { return isBinaryExpression(decl) || isAccessExpression(decl) || isIdentifier(decl) || isCallExpression(decl); } @@ -3765,7 +3765,7 @@ export function isAssignmentDeclaration(decl: Declaration) { * * @internal */ -export function getEffectiveInitializer(node: HasExpressionInitializer) { +export function getEffectiveInitializer(node: HasExpressionInitializer): Expression | undefined { if ( isInJSFile(node) && node.initializer && isBinaryExpression(node.initializer) && @@ -3782,7 +3782,7 @@ export function getEffectiveInitializer(node: HasExpressionInitializer) { * * @internal */ -export function getDeclaredExpandoInitializer(node: HasExpressionInitializer) { +export function getDeclaredExpandoInitializer(node: HasExpressionInitializer): Expression | undefined { const init = getEffectiveInitializer(node); return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); } @@ -3863,7 +3863,7 @@ function getDefaultedExpandoInitializer(name: Expression, initializer: Expressio } /** @internal */ -export function isDefaultedExpandoInitializer(node: BinaryExpression) { +export function isDefaultedExpandoInitializer(node: BinaryExpression): boolean | undefined { const name = isVariableDeclaration(node.parent) ? node.parent.name : isBinaryExpression(node.parent) && node.parent.operatorToken.kind === SyntaxKind.EqualsToken ? node.parent.left : undefined; @@ -3928,12 +3928,12 @@ export function getRightMostAssignedExpression(node: Expression): Expression { } /** @internal */ -export function isExportsIdentifier(node: Node) { +export function isExportsIdentifier(node: Node): boolean { return isIdentifier(node) && node.escapedText === "exports"; } /** @internal */ -export function isModuleIdentifier(node: Node) { +export function isModuleIdentifier(node: Node): boolean { return isIdentifier(node) && node.escapedText === "module"; } @@ -4005,7 +4005,7 @@ export function isBindableStaticNameExpression(node: Node, excludeThisKeyword?: } /** @internal */ -export function getNameOrArgument(expr: PropertyAccessExpression | LiteralLikeElementAccessExpression) { +export function getNameOrArgument(expr: PropertyAccessExpression | LiteralLikeElementAccessExpression): MemberName | (Expression & (NumericLiteral | StringLiteralLike)) { if (isPropertyAccessExpression(expr)) { return expr.name; } @@ -4114,7 +4114,7 @@ export function getAssignmentDeclarationPropertyAccessKind(lhs: AccessExpression } /** @internal */ -export function getInitializerOfBinaryExpression(expr: BinaryExpression) { +export function getInitializerOfBinaryExpression(expr: BinaryExpression): Expression { while (isBinaryExpression(expr.right)) { expr = expr.right; } @@ -4155,7 +4155,7 @@ export function setValueDeclaration(symbol: Symbol, node: Declaration): void { } /** @internal */ -export function isFunctionSymbol(symbol: Symbol | undefined) { +export function isFunctionSymbol(symbol: Symbol | undefined): boolean | undefined { if (!symbol || !symbol.valueDeclaration) { return false; } @@ -4287,25 +4287,22 @@ export function forEachImportClauseDeclaration(node: ImportClause, action: (d } /** @internal */ -export function hasQuestionToken(node: Node) { - if (node) { - switch (node.kind) { - case SyntaxKind.Parameter: - case SyntaxKind.MethodDeclaration: - case SyntaxKind.MethodSignature: - case SyntaxKind.ShorthandPropertyAssignment: - case SyntaxKind.PropertyAssignment: - case SyntaxKind.PropertyDeclaration: - case SyntaxKind.PropertySignature: - return (node as ParameterDeclaration | MethodDeclaration | PropertyDeclaration).questionToken !== undefined; - } +export function hasQuestionToken(node: Node): boolean { + switch (node.kind) { + case SyntaxKind.Parameter: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.MethodSignature: + case SyntaxKind.ShorthandPropertyAssignment: + case SyntaxKind.PropertyAssignment: + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.PropertySignature: + return (node as ParameterDeclaration | MethodDeclaration | PropertyDeclaration).questionToken !== undefined; } - return false; } /** @internal */ -export function isJSDocConstructSignature(node: Node) { +export function isJSDocConstructSignature(node: Node): boolean { const param = isJSDocFunctionType(node) ? firstOrUndefined(node.parameters) : undefined; const name = tryCast(param && param.name, isIdentifier); return !!name && name.escapedText === "new"; @@ -4540,7 +4537,7 @@ function ownsJSDocTag(hostNode: Node, tag: JSDocTag) { } /** @internal */ -export function getNextJSDocCommentLocation(node: Node) { +export function getNextJSDocCommentLocation(node: Node): Node | undefined { const parent = node.parent; if ( parent.kind === SyntaxKind.PropertyAssignment || @@ -4597,7 +4594,7 @@ export function getParameterSymbolFromJSDoc(node: JSDocParameterTag): Symbol | u } /** @internal */ -export function getEffectiveContainerForJSDocTemplateTag(node: JSDocTemplateTag) { +export function getEffectiveContainerForJSDocTemplateTag(node: JSDocTemplateTag): SignatureDeclaration | JSDocTypedefTag | JSDocCallbackTag | JSDocEnumTag | undefined { if (isJSDoc(node.parent) && node.parent.tags) { // A @template tag belongs to any @typedef, @callback, or @enum tags in the same comment block, if they exist. const typeAlias = find(node.parent.tags, isJSDocTypeAlias); @@ -4839,12 +4836,12 @@ function walkUp(node: Node, kind: SyntaxKind) { } /** @internal */ -export function walkUpParenthesizedTypes(node: Node) { +export function walkUpParenthesizedTypes(node: Node): Node { return walkUp(node, SyntaxKind.ParenthesizedType); } /** @internal */ -export function walkUpParenthesizedExpressions(node: Node) { +export function walkUpParenthesizedExpressions(node: Node): Node { return walkUp(node, SyntaxKind.ParenthesizedExpression); } @@ -4942,7 +4939,7 @@ export function getDeclarationFromName(name: Node): Declaration | undefined { } /** @internal */ -export function isLiteralComputedPropertyDeclarationName(node: Node) { +export function isLiteralComputedPropertyDeclarationName(node: Node): boolean { return isStringOrNumericLiteralLike(node) && node.parent.kind === SyntaxKind.ComputedPropertyName && isDeclaration(node.parent.parent); @@ -5003,7 +5000,7 @@ export function getAliasDeclarationFromName(node: EntityName): Declaration | und } /** @internal */ -export function isAliasableExpression(e: Expression) { +export function isAliasableExpression(e: Expression): boolean { return isEntityNameExpression(e) || isClassExpression(e); } @@ -5025,7 +5022,7 @@ export function getPropertyAssignmentAliasLikeExpression(node: PropertyAssignmen } /** @internal */ -export function getEffectiveBaseTypeNode(node: ClassLikeDeclaration | InterfaceDeclaration) { +export function getEffectiveBaseTypeNode(node: ClassLikeDeclaration | InterfaceDeclaration): ExpressionWithTypeArguments | undefined { const baseType = getClassExtendsHeritageElement(node); if (baseType && isInJSFile(node)) { // Prefer an @augments tag because it may have type parameters. @@ -5038,7 +5035,7 @@ export function getEffectiveBaseTypeNode(node: ClassLikeDeclaration | InterfaceD } /** @internal */ -export function getClassExtendsHeritageElement(node: ClassLikeDeclaration | InterfaceDeclaration) { +export function getClassExtendsHeritageElement(node: ClassLikeDeclaration | InterfaceDeclaration): ExpressionWithTypeArguments | undefined { const heritageClause = getHeritageClause(node.heritageClauses, SyntaxKind.ExtendsKeyword); return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; } @@ -5066,13 +5063,13 @@ export function getAllSuperTypeNodes(node: Node): readonly TypeNode[] { } /** @internal */ -export function getInterfaceBaseTypeNodes(node: InterfaceDeclaration) { +export function getInterfaceBaseTypeNodes(node: InterfaceDeclaration): NodeArray | undefined { const heritageClause = getHeritageClause(node.heritageClauses, SyntaxKind.ExtendsKeyword); return heritageClause ? heritageClause.types : undefined; } /** @internal */ -export function getHeritageClause(clauses: NodeArray | undefined, kind: SyntaxKind) { +export function getHeritageClause(clauses: NodeArray | undefined, kind: SyntaxKind): HeritageClause | undefined { if (clauses) { for (const clause of clauses) { if (clause.token === kind) { @@ -5121,7 +5118,7 @@ export function isNonContextualKeyword(token: SyntaxKind): boolean { } /** @internal */ -export function isStringANonContextualKeyword(name: string) { +export function isStringANonContextualKeyword(name: string): boolean { const token = stringToToken(name); return token !== undefined && isNonContextualKeyword(token); } @@ -5148,7 +5145,7 @@ export const enum FunctionFlags { } /** @internal */ -export function getFunctionFlags(node: SignatureDeclaration | undefined) { +export function getFunctionFlags(node: SignatureDeclaration | undefined): FunctionFlags { if (!node) { return FunctionFlags.Invalid; } @@ -5414,7 +5411,7 @@ export function isNamedEvaluation(node: Node, cb?: (node: AnonymousFunctionDefin } /** @internal */ -export function isPushOrUnshiftIdentifier(node: Identifier) { +export function isPushOrUnshiftIdentifier(node: Identifier): boolean { return node.escapedText === "push" || node.escapedText === "unshift"; } @@ -5467,14 +5464,14 @@ export const enum Associativity { } /** @internal */ -export function getExpressionAssociativity(expression: Expression) { +export function getExpressionAssociativity(expression: Expression): Associativity { const operator = getOperator(expression); const hasArguments = expression.kind === SyntaxKind.NewExpression && (expression as NewExpression).arguments !== undefined; return getOperatorAssociativity(expression.kind, operator, hasArguments); } /** @internal */ -export function getOperatorAssociativity(kind: SyntaxKind, operator: SyntaxKind, hasArguments?: boolean) { +export function getOperatorAssociativity(kind: SyntaxKind, operator: SyntaxKind, hasArguments?: boolean): Associativity { switch (kind) { case SyntaxKind.NewExpression: return hasArguments ? Associativity.Left : Associativity.Right; @@ -5514,7 +5511,7 @@ export function getOperatorAssociativity(kind: SyntaxKind, operator: SyntaxKind, } /** @internal */ -export function getExpressionPrecedence(expression: Expression) { +export function getExpressionPrecedence(expression: Expression): OperatorPrecedence { const operator = getOperator(expression); const hasArguments = expression.kind === SyntaxKind.NewExpression && (expression as NewExpression).arguments !== undefined; return getOperatorPrecedence(expression.kind, operator, hasArguments); @@ -5726,7 +5723,7 @@ export const enum OperatorPrecedence { } /** @internal */ -export function getOperatorPrecedence(nodeKind: SyntaxKind, operatorKind: SyntaxKind, hasArguments?: boolean) { +export function getOperatorPrecedence(nodeKind: SyntaxKind, operatorKind: SyntaxKind, hasArguments?: boolean): OperatorPrecedence { switch (nodeKind) { case SyntaxKind.CommaListExpression: return OperatorPrecedence.Comma; @@ -5876,7 +5873,7 @@ export function getBinaryOperatorPrecedence(kind: SyntaxKind): OperatorPrecedenc } /** @internal */ -export function getSemanticJsxChildren(children: readonly JsxChild[]) { +export function getSemanticJsxChildren(children: readonly JsxChild[]): readonly JsxChild[] { return filter(children, i => { switch (i.kind) { case SyntaxKind.JsxExpression: @@ -6079,7 +6076,7 @@ function getJsxAttributeStringReplacement(c: string) { } /** @internal */ -export function escapeJsxAttributeString(s: string, quoteChar?: CharacterCodes.doubleQuote | CharacterCodes.singleQuote) { +export function escapeJsxAttributeString(s: string, quoteChar?: CharacterCodes.doubleQuote | CharacterCodes.singleQuote): string { const escapedCharsRegExp = quoteChar === CharacterCodes.singleQuote ? jsxSingleQuoteEscapedCharsRegExp : jsxDoubleQuoteEscapedCharsRegExp; return s.replace(escapedCharsRegExp, getJsxAttributeStringReplacement); @@ -6092,7 +6089,7 @@ export function escapeJsxAttributeString(s: string, quoteChar?: CharacterCodes.d * * @internal */ -export function stripQuotes(name: string) { +export function stripQuotes(name: string): string { const length = name.length; if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && isQuoteOrBacktick(name.charCodeAt(0))) { return name.substring(1, length - 1); @@ -6107,14 +6104,14 @@ function isQuoteOrBacktick(charCode: number) { } /** @internal */ -export function isIntrinsicJsxName(name: __String | string) { +export function isIntrinsicJsxName(name: __String | string): boolean { const ch = (name as string).charCodeAt(0); return (ch >= CharacterCodes.a && ch <= CharacterCodes.z) || (name as string).includes("-"); } const indentStrings: string[] = ["", " "]; /** @internal */ -export function getIndentString(level: number) { +export function getIndentString(level: number): string { // prepopulate cache const singleLevel = indentStrings[1]; for (let current = indentStrings.length; current <= level; current++) { @@ -6370,7 +6367,7 @@ export function getExternalModuleNameFromPath(host: ResolveModuleNameResolutionH } /** @internal */ -export function getOwnEmitOutputFilePath(fileName: string, host: EmitHost, extension: string) { +export function getOwnEmitOutputFilePath(fileName: string, host: EmitHost, extension: string): string { const compilerOptions = host.getCompilerOptions(); let emitOutputFilePathWithoutExtension: string; if (compilerOptions.outDir) { @@ -6384,7 +6381,7 @@ export function getOwnEmitOutputFilePath(fileName: string, host: EmitHost, exten } /** @internal */ -export function getDeclarationEmitOutputFilePath(fileName: string, host: EmitHost) { +export function getDeclarationEmitOutputFilePath(fileName: string, host: EmitHost): string { return getDeclarationEmitOutputFilePathWorker(fileName, host.getCompilerOptions(), host); } @@ -6400,7 +6397,7 @@ export function getDeclarationEmitOutputFilePathWorker(fileName: string, options } /** @internal */ -export function getDeclarationEmitExtensionForPath(path: string) { +export function getDeclarationEmitExtensionForPath(path: string): Extension.Dts | Extension.Dmts | Extension.Dcts | ".d.json.ts" { return fileExtensionIsOneOf(path, [Extension.Mjs, Extension.Mts]) ? Extension.Dmts : fileExtensionIsOneOf(path, [Extension.Cjs, Extension.Cts]) ? Extension.Dcts : fileExtensionIsOneOf(path, [Extension.Json]) ? `.d.json.ts` : // Drive-by redefinition of json declaration file output name so if it's ever enabled, it behaves well @@ -6412,7 +6409,7 @@ export function getDeclarationEmitExtensionForPath(path: string) { * * @internal */ -export function getPossibleOriginalInputExtensionForExtension(path: string) { +export function getPossibleOriginalInputExtensionForExtension(path: string): Extension[] { return fileExtensionIsOneOf(path, [Extension.Dmts, Extension.Mjs, Extension.Mts]) ? [Extension.Mts, Extension.Mjs] : fileExtensionIsOneOf(path, [Extension.Dcts, Extension.Cjs, Extension.Cts]) ? [Extension.Cts, Extension.Cjs] : fileExtensionIsOneOf(path, [`.d.json.ts`]) ? [Extension.Json] : @@ -6424,7 +6421,7 @@ export function getPossibleOriginalInputExtensionForExtension(path: string) { * * @internal */ -export function getPathsBasePath(options: CompilerOptions, host: { getCurrentDirectory?(): string; }) { +export function getPathsBasePath(options: CompilerOptions, host: { getCurrentDirectory?(): string; }): string | undefined { if (!options.paths) return undefined; return options.baseUrl ?? Debug.checkDefined(options.pathsBasePath || host.getCurrentDirectory?.(), "Encountered 'paths' without a 'baseUrl', config file, or host 'getCurrentDirectory'."); } @@ -6476,7 +6473,7 @@ export function getSourceFilesToEmit(host: EmitHost, targetSourceFile?: SourceFi * * @internal */ -export function sourceFileMayBeEmitted(sourceFile: SourceFile, host: SourceFileMayBeEmittedHost, forceDtsEmit?: boolean) { +export function sourceFileMayBeEmitted(sourceFile: SourceFile, host: SourceFileMayBeEmittedHost, forceDtsEmit?: boolean): boolean { const options = host.getCompilerOptions(); // Js files are emitted only if option is enabled if (options.noEmitForJsFiles && isSourceFileJS(sourceFile)) return false; @@ -6518,7 +6515,7 @@ function getSourceFilePathInNewDirWorker(fileName: string, newDirPath: string, c } /** @internal */ -export function writeFile(host: { writeFile: WriteFileCallback; }, diagnostics: DiagnosticCollection, fileName: string, text: string, writeByteOrderMark: boolean, sourceFiles?: readonly SourceFile[], data?: WriteFileCallbackData) { +export function writeFile(host: { writeFile: WriteFileCallback; }, diagnostics: DiagnosticCollection, fileName: string, text: string, writeByteOrderMark: boolean, sourceFiles?: readonly SourceFile[], data?: WriteFileCallbackData): void { host.writeFile( fileName, text, @@ -6564,7 +6561,7 @@ export function writeFileEnsuringDirectories( } /** @internal */ -export function getLineOfLocalPosition(sourceFile: SourceFile, pos: number) { +export function getLineOfLocalPosition(sourceFile: SourceFile, pos: number): number { const lineStarts = getLineStarts(sourceFile); return computeLineOfPosition(lineStarts, pos); } @@ -6768,7 +6765,7 @@ function emitNewLineBeforeLeadingCommentsOfPosition(lineMap: readonly number[], } /** @internal */ -export function emitNewLineBeforeLeadingCommentOfPosition(lineMap: readonly number[], writer: EmitTextWriter, pos: number, commentPos: number) { +export function emitNewLineBeforeLeadingCommentOfPosition(lineMap: readonly number[], writer: EmitTextWriter, pos: number, commentPos: number): void { // If the leading comments start on different line than the start of node, write new line if ( pos !== commentPos && @@ -6821,7 +6818,10 @@ function emitComments( * * @internal */ -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) { +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): { + nodePos: number; + detachedCommentEndPos: number; +} | undefined { let leadingComments: CommentRange[] | undefined; let currentDetachedCommentInfo: { nodePos: number; detachedCommentEndPos: number; } | undefined; if (removeComments) { @@ -6883,7 +6883,7 @@ export function emitDetachedComments(text: string, lineMap: readonly number[], w } /** @internal */ -export function writeCommentRange(text: string, lineMap: readonly number[], writer: EmitTextWriter, commentPos: number, commentEnd: number, newLine: string) { +export function writeCommentRange(text: string, lineMap: readonly number[], writer: EmitTextWriter, commentPos: number, commentEnd: number, newLine: string): void { if (text.charCodeAt(commentPos + 1) === CharacterCodes.asterisk) { const firstCommentLineAndCharacter = computeLineAndCharacterOfPosition(lineMap, commentPos); const lineCount = lineMap.length; @@ -6981,12 +6981,12 @@ function calculateIndent(text: string, pos: number, end: number) { } /** @internal */ -export function hasEffectiveModifiers(node: Node) { +export function hasEffectiveModifiers(node: Node): boolean { return getEffectiveModifierFlags(node) !== ModifierFlags.None; } /** @internal */ -export function hasSyntacticModifiers(node: Node) { +export function hasSyntacticModifiers(node: Node): boolean { return getSyntacticModifierFlags(node) !== ModifierFlags.None; } @@ -7001,7 +7001,7 @@ export function hasSyntacticModifier(node: Node, flags: ModifierFlags): boolean } /** @internal */ -export function isStatic(node: Node) { +export function isStatic(node: Node): boolean { // https://tc39.es/ecma262/#sec-static-semantics-isstatic return isClassElement(node) && hasStaticModifier(node) || isClassStaticBlockDeclaration(node); } @@ -7154,7 +7154,7 @@ export function getSyntacticModifierFlagsNoCache(node: Node): ModifierFlags { } /** @internal */ -export function modifiersToFlags(modifiers: readonly ModifierLike[] | undefined) { +export function modifiersToFlags(modifiers: readonly ModifierLike[] | undefined): ModifierFlags { let flags = ModifierFlags.None; if (modifiers) { for (const modifier of modifiers) { @@ -7369,20 +7369,20 @@ export function isPrototypeAccess(node: Node): node is BindableStaticAccessExpre } /** @internal */ -export function isRightSideOfQualifiedNameOrPropertyAccess(node: Node) { +export function isRightSideOfQualifiedNameOrPropertyAccess(node: Node): boolean { return (node.parent.kind === SyntaxKind.QualifiedName && (node.parent as QualifiedName).right === node) || (node.parent.kind === SyntaxKind.PropertyAccessExpression && (node.parent as PropertyAccessExpression).name === node) || (node.parent.kind === SyntaxKind.MetaProperty && (node.parent as MetaProperty).name === node); } /** @internal */ -export function isRightSideOfAccessExpression(node: Node) { +export function isRightSideOfAccessExpression(node: Node): boolean { return !!node.parent && (isPropertyAccessExpression(node.parent) && node.parent.name === node || isElementAccessExpression(node.parent) && node.parent.argumentExpression === node); } /** @internal */ -export function isRightSideOfQualifiedNameOrPropertyAccessOrJSDocMemberName(node: Node) { +export function isRightSideOfQualifiedNameOrPropertyAccessOrJSDocMemberName(node: Node): boolean { return isQualifiedName(node.parent) && node.parent.right === node || isPropertyAccessExpression(node.parent) && node.parent.name === node || isJSDocMemberName(node.parent) && node.parent.right === node; @@ -7393,7 +7393,7 @@ export function isInstanceOfExpression(node: Node): node is InstanceofExpression } /** @internal */ -export function isRightSideOfInstanceofExpression(node: Node) { +export function isRightSideOfInstanceofExpression(node: Node): boolean { return isInstanceOfExpression(node.parent) && node === node.parent.right; } @@ -7410,7 +7410,7 @@ export function isEmptyArrayLiteral(expression: Node): boolean { } /** @internal */ -export function getLocalSymbolForExportDefault(symbol: Symbol) { +export function getLocalSymbolForExportDefault(symbol: Symbol): Symbol | undefined { if (!isExportDefaultSymbol(symbol) || !symbol.declarations) return undefined; for (const decl of symbol.declarations) { if (decl.localSymbol) return decl.localSymbol; @@ -7601,7 +7601,7 @@ export function readJson(path: string, host: { readFile(fileName: string): strin } /** @internal */ -export function tryParseJson(text: string) { +export function tryParseJson(text: string): any { try { return JSON.parse(text); } @@ -7707,12 +7707,12 @@ export function createTokenRange(pos: number, token: SyntaxKind): TextRange { } /** @internal */ -export function rangeIsOnSingleLine(range: TextRange, sourceFile: SourceFile) { +export function rangeIsOnSingleLine(range: TextRange, sourceFile: SourceFile): boolean { return rangeStartIsOnSameLineAsRangeEnd(range, range, sourceFile); } /** @internal */ -export function rangeStartPositionsAreOnSameLine(range1: TextRange, range2: TextRange, sourceFile: SourceFile) { +export function rangeStartPositionsAreOnSameLine(range1: TextRange, range2: TextRange, sourceFile: SourceFile): boolean { return positionsAreOnSameLine( getStartPositionOfRange(range1, sourceFile, /*includeComments*/ false), getStartPositionOfRange(range2, sourceFile, /*includeComments*/ false), @@ -7721,28 +7721,28 @@ export function rangeStartPositionsAreOnSameLine(range1: TextRange, range2: Text } /** @internal */ -export function rangeEndPositionsAreOnSameLine(range1: TextRange, range2: TextRange, sourceFile: SourceFile) { +export function rangeEndPositionsAreOnSameLine(range1: TextRange, range2: TextRange, sourceFile: SourceFile): boolean { return positionsAreOnSameLine(range1.end, range2.end, sourceFile); } /** @internal @knipignore */ -export function rangeStartIsOnSameLineAsRangeEnd(range1: TextRange, range2: TextRange, sourceFile: SourceFile) { +export function rangeStartIsOnSameLineAsRangeEnd(range1: TextRange, range2: TextRange, sourceFile: SourceFile): boolean { return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile, /*includeComments*/ false), range2.end, sourceFile); } /** @internal */ -export function rangeEndIsOnSameLineAsRangeStart(range1: TextRange, range2: TextRange, sourceFile: SourceFile) { +export function rangeEndIsOnSameLineAsRangeStart(range1: TextRange, range2: TextRange, sourceFile: SourceFile): boolean { return positionsAreOnSameLine(range1.end, getStartPositionOfRange(range2, sourceFile, /*includeComments*/ false), sourceFile); } /** @internal */ -export function getLinesBetweenRangeEndAndRangeStart(range1: TextRange, range2: TextRange, sourceFile: SourceFile, includeSecondRangeComments: boolean) { +export function getLinesBetweenRangeEndAndRangeStart(range1: TextRange, range2: TextRange, sourceFile: SourceFile, includeSecondRangeComments: boolean): number { const range2Start = getStartPositionOfRange(range2, sourceFile, includeSecondRangeComments); return getLinesBetweenPositions(sourceFile, range1.end, range2Start); } /** @internal @knipignore */ -export function getLinesBetweenRangeEndPositions(range1: TextRange, range2: TextRange, sourceFile: SourceFile) { +export function getLinesBetweenRangeEndPositions(range1: TextRange, range2: TextRange, sourceFile: SourceFile): number { return getLinesBetweenPositions(sourceFile, range1.end, range2.end); } @@ -7752,24 +7752,24 @@ export function isNodeArrayMultiLine(list: NodeArray, sourceFile: SourceFi } /** @internal */ -export function positionsAreOnSameLine(pos1: number, pos2: number, sourceFile: SourceFile) { +export function positionsAreOnSameLine(pos1: number, pos2: number, sourceFile: SourceFile): boolean { return getLinesBetweenPositions(sourceFile, pos1, pos2) === 0; } /** @internal @knipignore */ -export function getStartPositionOfRange(range: TextRange, sourceFile: SourceFile, includeComments: boolean) { +export function getStartPositionOfRange(range: TextRange, sourceFile: SourceFile, includeComments: boolean): number { return positionIsSynthesized(range.pos) ? -1 : skipTrivia(sourceFile.text, range.pos, /*stopAfterLineBreak*/ false, includeComments); } /** @internal */ -export function getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(pos: number, stopPos: number, sourceFile: SourceFile, includeComments?: boolean) { +export function getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(pos: number, stopPos: number, sourceFile: SourceFile, includeComments?: boolean): number { const startPos = skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments); const prevPos = getPreviousNonWhitespacePosition(startPos, stopPos, sourceFile); return getLinesBetweenPositions(sourceFile, prevPos ?? stopPos, startPos); } /** @internal */ -export function getLinesBetweenPositionAndNextNonWhitespaceCharacter(pos: number, stopPos: number, sourceFile: SourceFile, includeComments?: boolean) { +export function getLinesBetweenPositionAndNextNonWhitespaceCharacter(pos: number, stopPos: number, sourceFile: SourceFile, includeComments?: boolean): number { const nextPos = skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments); return getLinesBetweenPositions(sourceFile, pos, Math.min(stopPos, nextPos)); } @@ -7788,7 +7788,7 @@ function getPreviousNonWhitespacePosition(pos: number, stopPos = 0, sourceFile: * * @internal */ -export function isDeclarationNameOfEnumOrNamespace(node: Identifier) { +export function isDeclarationNameOfEnumOrNamespace(node: Identifier): boolean { const parseNode = getParseTreeNode(node); if (parseNode) { switch (parseNode.parent.kind) { @@ -7801,7 +7801,7 @@ export function isDeclarationNameOfEnumOrNamespace(node: Identifier) { } /** @internal */ -export function getInitializedVariables(node: VariableDeclarationList) { +export function getInitializedVariables(node: VariableDeclarationList): readonly InitializedVariableDeclaration[] { return filter(node.declarations, isInitializedVariable); } @@ -7811,13 +7811,13 @@ export function isInitializedVariable(node: Node): node is InitializedVariableDe } /** @internal */ -export function isWatchSet(options: CompilerOptions) { +export function isWatchSet(options: CompilerOptions): boolean | undefined { // Firefox has Object.prototype.watch return options.watch && hasProperty(options, "watch"); } /** @internal */ -export function closeFileWatcher(watcher: FileWatcher) { +export function closeFileWatcher(watcher: FileWatcher): void { watcher.close(); } @@ -7850,7 +7850,7 @@ export function getDeclarationModifierFlagsFromSymbol(s: Symbol, isWrite = false } /** @internal */ -export function skipAlias(symbol: Symbol, checker: TypeChecker) { +export function skipAlias(symbol: Symbol, checker: TypeChecker): Symbol { return symbol.flags & SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol; } @@ -7864,12 +7864,12 @@ export function getCombinedLocalAndExportSymbolFlags(symbol: Symbol): SymbolFlag } /** @internal */ -export function isWriteOnlyAccess(node: Node) { +export function isWriteOnlyAccess(node: Node): boolean { return accessKind(node) === AccessKind.Write; } /** @internal */ -export function isWriteAccess(node: Node) { +export function isWriteAccess(node: Node): boolean { return accessKind(node) !== AccessKind.Read; } @@ -7954,7 +7954,7 @@ export function compareDataObjects(dst: any, src: any): boolean { * * @internal */ -export function clearMap(map: { forEach: Map["forEach"]; clear: Map["clear"]; }, onDeleteValue: (valueInMap: T, key: K) => void) { +export function clearMap(map: { forEach: Map["forEach"]; clear: Map["clear"]; }, onDeleteValue: (valueInMap: T, key: K) => void): void { // Remove all map.forEach(onDeleteValue); map.clear(); @@ -8146,7 +8146,7 @@ export function isAccessExpression(node: Node): node is AccessExpression { } /** @internal */ -export function getNameOfAccessExpression(node: AccessExpression) { +export function getNameOfAccessExpression(node: AccessExpression): Expression { if (node.kind === SyntaxKind.PropertyAccessExpression) { return node.name; } @@ -8206,7 +8206,7 @@ export function forEachNameInAccessChainWalkingLeft(name: MemberName | String } /** @internal */ -export function getLeftmostExpression(node: Expression, stopAtCallExpressions: boolean) { +export function getLeftmostExpression(node: Expression, stopAtCallExpressions: boolean): Expression { while (true) { switch (node.kind) { case SyntaxKind.PostfixUnaryExpression: @@ -8257,7 +8257,7 @@ export interface ObjectAllocator { getSourceMapSourceConstructor(): new (fileName: string, text: string, skipTrivia?: (pos: number) => number) => SourceMapSource; } -function Symbol(this: Symbol, flags: SymbolFlags, name: __String) { +function Symbol(this: Symbol, flags: SymbolFlags, name: __String): void { // Note: if modifying this, be sure to update SymbolObject in src/services/services.ts this.flags = flags; this.escapedName = name; @@ -8275,7 +8275,7 @@ function Symbol(this: Symbol, flags: SymbolFlags, name: __String) { (this as any).links = undefined; // used by TransientSymbol } -function Type(this: Type, checker: TypeChecker, flags: TypeFlags) { +function Type(this: Type, checker: TypeChecker, flags: TypeFlags): void { // Note: if modifying this, be sure to update TypeObject in src/services/services.ts this.flags = flags; if (Debug.isDebugging || tracing) { @@ -8283,7 +8283,7 @@ function Type(this: Type, checker: TypeChecker, flags: TypeFlags) { } } -function Signature(this: Signature, checker: TypeChecker, flags: SignatureFlags) { +function Signature(this: Signature, checker: TypeChecker, flags: SignatureFlags): void { // Note: if modifying this, be sure to update SignatureObject in src/services/services.ts this.flags = flags; if (Debug.isDebugging) { @@ -8291,7 +8291,7 @@ function Signature(this: Signature, checker: TypeChecker, flags: SignatureFlags) } } -function Node(this: Mutable, kind: SyntaxKind, pos: number, end: number) { +function Node(this: Mutable, kind: SyntaxKind, pos: number, end: number): void { // Note: if modifying this, be sure to update NodeObject in src/services/services.ts this.pos = pos; this.end = end; @@ -8305,7 +8305,7 @@ function Node(this: Mutable, kind: SyntaxKind, pos: number, end: number) { this.emitNode = undefined; } -function Token(this: Mutable, kind: SyntaxKind, pos: number, end: number) { +function Token(this: Mutable, kind: SyntaxKind, pos: number, end: number): void { // Note: if modifying this, be sure to update TokenOrIdentifierObject in src/services/services.ts this.pos = pos; this.end = end; @@ -8317,7 +8317,7 @@ function Token(this: Mutable, kind: SyntaxKind, pos: number, end: number) this.emitNode = undefined; } -function Identifier(this: Mutable, kind: SyntaxKind, pos: number, end: number) { +function Identifier(this: Mutable, kind: SyntaxKind, pos: number, end: number): void { // Note: if modifying this, be sure to update TokenOrIdentifierObject in src/services/services.ts this.pos = pos; this.end = end; @@ -8330,7 +8330,7 @@ function Identifier(this: Mutable, kind: SyntaxKind, pos: number, end: num this.emitNode = undefined; } -function SourceMapSource(this: SourceMapSource, fileName: string, text: string, skipTrivia?: (pos: number) => number) { +function SourceMapSource(this: SourceMapSource, fileName: string, text: string, skipTrivia?: (pos: number) => number): void { // Note: if modifying this, be sure to update SourceMapSourceObject in src/services/services.ts this.fileName = fileName; this.text = text; @@ -8357,13 +8357,13 @@ const objectAllocatorPatchers: ((objectAllocator: ObjectAllocator) => void)[] = * @internal * @knipignore */ -export function addObjectAllocatorPatcher(fn: (objectAllocator: ObjectAllocator) => void) { +export function addObjectAllocatorPatcher(fn: (objectAllocator: ObjectAllocator) => void): void { objectAllocatorPatchers.push(fn); fn(objectAllocator); } /** @internal */ -export function setObjectAllocator(alloc: ObjectAllocator) { +export function setObjectAllocator(alloc: ObjectAllocator): void { Object.assign(objectAllocator, alloc); forEach(objectAllocatorPatchers, fn => fn(objectAllocator)); } @@ -8376,21 +8376,21 @@ export function formatStringFromArgs(text: string, args: DiagnosticArguments): s let localizedDiagnosticMessages: MapLike | undefined; /** @internal */ -export function setLocalizedDiagnosticMessages(messages: MapLike | undefined) { +export function setLocalizedDiagnosticMessages(messages: MapLike | undefined): void { localizedDiagnosticMessages = messages; } /** @internal */ // If the localized messages json is unset, and if given function use it to set the json -export function maybeSetLocalizedDiagnosticMessages(getMessages: undefined | (() => MapLike | undefined)) { +export function maybeSetLocalizedDiagnosticMessages(getMessages: undefined | (() => MapLike | undefined)): void { if (!localizedDiagnosticMessages && getMessages) { localizedDiagnosticMessages = getMessages(); } } /** @internal */ -export function getLocaleSpecificMessage(message: DiagnosticMessage) { +export function getLocaleSpecificMessage(message: DiagnosticMessage): string { return localizedDiagnosticMessages && localizedDiagnosticMessages[message.key] || message.message; } @@ -8734,7 +8734,7 @@ function messageTextEqualityComparer(m1: string | DiagnosticMessageChain, m2: st } /** @internal */ -export function getLanguageVariant(scriptKind: ScriptKind) { +export function getLanguageVariant(scriptKind: ScriptKind): LanguageVariant { // .tsx and .jsx files are treated as jsx language variant. return scriptKind === ScriptKind.TSX || scriptKind === ScriptKind.JSX || scriptKind === ScriptKind.JS || scriptKind === ScriptKind.JSON ? LanguageVariant.JSX : LanguageVariant.Standard; } @@ -8800,7 +8800,7 @@ export function getSetExternalModuleIndicator(options: CompilerOptions): (file: * Returns true if an `import` and a `require` of the same module specifier * can resolve to a different file. */ -export function importSyntaxAffectsModuleResolution(options: CompilerOptions) { +export function importSyntaxAffectsModuleResolution(options: CompilerOptions): boolean { const moduleResolution = getEmitModuleResolutionKind(options); return ModuleResolutionKind.Node16 <= moduleResolution && moduleResolution <= ModuleResolutionKind.NodeNext || getResolvePackageJsonExports(options) @@ -8820,7 +8820,108 @@ function createComputedCompilerOptions) => boolean; + }; + allowSyntheticDefaultImports: { + dependencies: ("module" | "moduleResolution" | "target")[]; + computeValue: (compilerOptions: Pick) => boolean; + }; + alwaysStrict: { + dependencies: "strict"[]; + computeValue: (compilerOptions: Pick) => boolean; + }; + declaration: { + dependencies: "composite"[]; + computeValue: (compilerOptions: Pick) => boolean; + }; + declarationMap: { + dependencies: ("declaration" | "composite")[]; + computeValue: (compilerOptions: Pick) => boolean; + }; + isolatedModules: { + dependencies: "verbatimModuleSyntax"[]; + computeValue: (compilerOptions: Pick) => boolean; + }; + module: { + dependencies: "target"[]; + computeValue: (compilerOptions: Pick) => ModuleKind; + }; + moduleResolution: { + dependencies: ("module" | "target")[]; + computeValue: (compilerOptions: Pick) => ModuleResolutionKind; + }; + moduleDetection: { + dependencies: ("module" | "target")[]; + computeValue: (compilerOptions: Pick) => ModuleDetectionKind; + }; + noImplicitAny: { + dependencies: "strict"[]; + computeValue: (compilerOptions: Pick) => boolean; + }; + noImplicitThis: { + dependencies: "strict"[]; + computeValue: (compilerOptions: Pick) => boolean; + }; + preserveConstEnums: { + dependencies: ("isolatedModules" | "verbatimModuleSyntax")[]; + computeValue: (compilerOptions: Pick) => boolean; + }; + incremental: { + dependencies: "composite"[]; + computeValue: (compilerOptions: Pick) => boolean; + }; + resolvePackageJsonExports: { + dependencies: "moduleResolution"[]; + computeValue: (compilerOptions: Pick) => boolean; + }; + resolvePackageJsonImports: { + dependencies: ("moduleResolution" | "resolvePackageJsonExports")[]; + computeValue: (compilerOptions: Pick) => boolean; + }; + strictFunctionTypes: { + dependencies: "strict"[]; + computeValue: (compilerOptions: Pick) => boolean; + }; + strictBindCallApply: { + dependencies: "strict"[]; + computeValue: (compilerOptions: Pick) => boolean; + }; + strictNullChecks: { + dependencies: "strict"[]; + computeValue: (compilerOptions: Pick) => boolean; + }; + strictPropertyInitialization: { + dependencies: "strict"[]; + computeValue: (compilerOptions: Pick) => boolean; + }; + strictBuiltinIteratorReturn: { + dependencies: "strict"[]; + computeValue: (compilerOptions: Pick) => boolean; + }; + target: { + dependencies: "module"[]; + computeValue: (compilerOptions: Pick) => ScriptTarget; + }; + useUnknownInCatchVariables: { + dependencies: "strict"[]; + computeValue: (compilerOptions: Pick) => boolean; + }; + resolveJsonModule: { + dependencies: ("module" | "moduleResolution" | "target")[]; + computeValue: (compilerOptions: Pick) => boolean; + }; + esModuleInterop: { + dependencies: ("module" | "target")[]; + computeValue: (compilerOptions: Pick) => boolean; + }; + useDefineForClassFields: { + dependencies: ("module" | "target")[]; + computeValue: (compilerOptions: Pick) => boolean; + }; +} = createComputedCompilerOptions({ target: { dependencies: ["module"], computeValue: compilerOptions => { @@ -9047,45 +9148,45 @@ export const computedOptions = createComputedCompilerOptions({ }); /** @internal */ -export const getEmitScriptTarget = computedOptions.target.computeValue; +export const getEmitScriptTarget: (compilerOptions: Pick) => ScriptTarget = computedOptions.target.computeValue; /** @internal */ -export const getEmitModuleKind = computedOptions.module.computeValue; +export const getEmitModuleKind: (compilerOptions: Pick) => ModuleKind = computedOptions.module.computeValue; /** @internal */ -export const getEmitModuleResolutionKind = computedOptions.moduleResolution.computeValue; +export const getEmitModuleResolutionKind: (compilerOptions: Pick) => ModuleResolutionKind = computedOptions.moduleResolution.computeValue; /** @internal @knipignore */ -export const getEmitModuleDetectionKind = computedOptions.moduleDetection.computeValue; +export const getEmitModuleDetectionKind: (compilerOptions: Pick) => ModuleDetectionKind = computedOptions.moduleDetection.computeValue; /** @internal */ -export const getIsolatedModules = computedOptions.isolatedModules.computeValue; +export const getIsolatedModules: (compilerOptions: Pick) => boolean = computedOptions.isolatedModules.computeValue; /** @internal */ -export const getESModuleInterop = computedOptions.esModuleInterop.computeValue; +export const getESModuleInterop: (compilerOptions: Pick) => boolean = computedOptions.esModuleInterop.computeValue; /** @internal */ -export const getAllowSyntheticDefaultImports = computedOptions.allowSyntheticDefaultImports.computeValue; +export const getAllowSyntheticDefaultImports: (compilerOptions: Pick) => boolean = computedOptions.allowSyntheticDefaultImports.computeValue; /** @internal */ -export const getResolvePackageJsonExports = computedOptions.resolvePackageJsonExports.computeValue; +export const getResolvePackageJsonExports: (compilerOptions: Pick) => boolean = computedOptions.resolvePackageJsonExports.computeValue; /** @internal */ -export const getResolvePackageJsonImports = computedOptions.resolvePackageJsonImports.computeValue; +export const getResolvePackageJsonImports: (compilerOptions: Pick) => boolean = computedOptions.resolvePackageJsonImports.computeValue; /** @internal */ -export const getResolveJsonModule = computedOptions.resolveJsonModule.computeValue; +export const getResolveJsonModule: (compilerOptions: Pick) => boolean = computedOptions.resolveJsonModule.computeValue; /** @internal */ -export const getEmitDeclarations = computedOptions.declaration.computeValue; +export const getEmitDeclarations: (compilerOptions: Pick) => boolean = computedOptions.declaration.computeValue; /** @internal */ -export const shouldPreserveConstEnums = computedOptions.preserveConstEnums.computeValue; +export const shouldPreserveConstEnums: (compilerOptions: Pick) => boolean = computedOptions.preserveConstEnums.computeValue; /** @internal */ -export const isIncrementalCompilation = computedOptions.incremental.computeValue; +export const isIncrementalCompilation: (compilerOptions: Pick) => boolean = computedOptions.incremental.computeValue; /** @internal */ -export const getAreDeclarationMapsEnabled = computedOptions.declarationMap.computeValue; +export const getAreDeclarationMapsEnabled: (compilerOptions: Pick) => boolean = computedOptions.declarationMap.computeValue; /** @internal */ -export const getAllowJSCompilerOption = computedOptions.allowJs.computeValue; +export const getAllowJSCompilerOption: (compilerOptions: Pick) => boolean = computedOptions.allowJs.computeValue; /** @internal */ -export const getUseDefineForClassFields = computedOptions.useDefineForClassFields.computeValue; +export const getUseDefineForClassFields: (compilerOptions: Pick) => boolean = computedOptions.useDefineForClassFields.computeValue; /** @internal */ -export function emitModuleKindIsNonNodeESM(moduleKind: ModuleKind) { +export function emitModuleKindIsNonNodeESM(moduleKind: ModuleKind): boolean { return moduleKind >= ModuleKind.ES2015 && moduleKind <= ModuleKind.ESNext; } /** @internal */ -export function hasJsonModuleEmitEnabled(options: CompilerOptions) { +export function hasJsonModuleEmitEnabled(options: CompilerOptions): boolean { switch (getEmitModuleKind(options)) { case ModuleKind.None: case ModuleKind.System: @@ -9134,7 +9235,7 @@ export function getNameOfScriptTarget(scriptTarget: ScriptTarget): string | unde } /** @internal */ -export function getEmitStandardClassFields(compilerOptions: CompilerOptions) { +export function getEmitStandardClassFields(compilerOptions: CompilerOptions): boolean { return compilerOptions.useDefineForClassFields !== false && getEmitScriptTarget(compilerOptions) >= ScriptTarget.ES2022; } @@ -9185,7 +9286,7 @@ export function getJSXImplicitImportBase(compilerOptions: CompilerOptions, file? } /** @internal */ -export function getJSXRuntimeImport(base: string | undefined, options: CompilerOptions) { +export function getJSXRuntimeImport(base: string | undefined, options: CompilerOptions): string | undefined { return base ? `${base}/${options.jsx === JsxEmit.ReactJSXDev ? "jsx-dev-runtime" : "jsx-runtime"}` : undefined; } @@ -9352,7 +9453,7 @@ export function tryRemoveDirectoryPrefix(path: string, dirPath: string, getCanon const reservedCharacterPattern = /[^\w\s/]/g; /** @internal */ -export function regExpEscape(text: string) { +export function regExpEscape(text: string): string { return text.replace(reservedCharacterPattern, escapeRegExpCharacter); } @@ -9444,7 +9545,7 @@ export function isImplicitGlob(lastPathComponent: string): boolean { } /** @internal */ -export function getPatternFromSpec(spec: string, basePath: string, usage: "files" | "directories" | "exclude") { +export function getPatternFromSpec(spec: string, basePath: string, usage: "files" | "directories" | "exclude"): string | undefined { const pattern = spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); return pattern && `^(${pattern})${usage === "exclude" ? "($|/)" : "$"}`; } @@ -9900,7 +10001,7 @@ function getRequiresAtTopOfFile(sourceFile: SourceFile): readonly RequireOrImpor } /** @internal */ -export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions, extraFileExtensions?: readonly FileExtensionInfo[]) { +export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions, extraFileExtensions?: readonly FileExtensionInfo[]): boolean { if (!fileName) return false; const supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions); @@ -9918,7 +10019,7 @@ function numberOfDirectorySeparators(str: string) { } /** @internal */ -export function compareNumberOfDirectorySeparators(path1: string, path2: string) { +export function compareNumberOfDirectorySeparators(path1: string, path2: string): Comparison { return compareValues( numberOfDirectorySeparators(path1), numberOfDirectorySeparators(path2), @@ -9993,7 +10094,7 @@ export function extensionIsTS(ext: string): boolean { } /** @internal */ -export function resolutionExtensionIsTSOrJson(ext: string) { +export function resolutionExtensionIsTSOrJson(ext: string): boolean { return extensionIsTS(ext) || ext === Extension.Json; } @@ -10019,7 +10120,7 @@ export function tryGetExtensionFromPath(path: string): Extension | undefined { } /** @internal */ -export function isCheckJsEnabledForFile(sourceFile: SourceFile, compilerOptions: CompilerOptions) { +export function isCheckJsEnabledForFile(sourceFile: SourceFile, compilerOptions: CompilerOptions): boolean | undefined { return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; } @@ -10113,7 +10214,7 @@ export function skipTypeChecking( sourceFile: SourceFile, options: CompilerOptions, host: HostWithIsSourceOfProjectReferenceRedirect, -) { +): boolean { return skipTypeCheckingWorker(sourceFile, options, host, /*ignoreNoCheck*/ false); } @@ -10122,7 +10223,7 @@ export function skipTypeCheckingIgnoringNoCheck( sourceFile: SourceFile, options: CompilerOptions, host: HostWithIsSourceOfProjectReferenceRedirect, -) { +): boolean { return skipTypeCheckingWorker(sourceFile, options, host, /*ignoreNoCheck*/ true); } @@ -10143,7 +10244,7 @@ function skipTypeCheckingWorker( } /** @internal */ -export function canIncludeBindAndCheckDiagnostics(sourceFile: SourceFile, options: CompilerOptions) { +export function canIncludeBindAndCheckDiagnostics(sourceFile: SourceFile, options: CompilerOptions): boolean { if (!!sourceFile.checkJsDirective && sourceFile.checkJsDirective.enabled === false) return false; if ( sourceFile.scriptKind === ScriptKind.TS || @@ -10341,7 +10442,7 @@ export function isIdentifierTypeReference(node: Node): node is TypeReferenceNode } /** @internal */ -export function arrayIsHomogeneous(array: readonly T[], comparer: EqualityComparer = equateValues) { +export function arrayIsHomogeneous(array: readonly T[], comparer: EqualityComparer = equateValues): boolean { if (array.length < 2) return true; const first = array[0]; for (let i = 1, length = array.length; i < length; i++) { @@ -10356,7 +10457,7 @@ export function arrayIsHomogeneous(array: readonly T[], comparer: EqualityCom * * @internal */ -export function setTextRangePos(range: T, pos: number) { +export function setTextRangePos(range: T, pos: number): T { (range as TextRange).pos = pos; return range; } @@ -10366,7 +10467,7 @@ export function setTextRangePos(range: T, pos: numb * * @internal */ -export function setTextRangeEnd(range: T, end: number) { +export function setTextRangeEnd(range: T, end: number): T { (range as TextRange).end = end; return range; } @@ -10376,7 +10477,7 @@ export function setTextRangeEnd(range: T, end: numb * * @internal */ -export function setTextRangePosEnd(range: T, pos: number, end: number) { +export function setTextRangePosEnd(range: T, pos: number, end: number): T { return setTextRangeEnd(setTextRangePos(range, pos), end); } @@ -10386,7 +10487,7 @@ export function setTextRangePosEnd(range: T, pos: n * * @internal */ -export function setTextRangePosWidth(range: T, pos: number, width: number) { +export function setTextRangePosWidth(range: T, pos: number, width: number): T { return setTextRangePosEnd(range, pos, pos + width); } @@ -10469,7 +10570,7 @@ function isPackedElement(node: Expression) { * * @internal */ -export function isPackedArrayLiteral(node: Expression) { +export function isPackedArrayLiteral(node: Expression): boolean { return isArrayLiteralExpression(node) && every(node.elements, isPackedElement); } @@ -10516,7 +10617,7 @@ export function expressionResultIsUnused(node: Expression): boolean { } /** @internal */ -export function containsIgnoredPath(path: string) { +export function containsIgnoredPath(path: string): boolean { return some(ignoredPaths, p => path.includes(p)); } @@ -10592,7 +10693,7 @@ export function getContainingNodeArray(node: Node): NodeArray | undefined } /** @internal */ -export function hasContextSensitiveParameters(node: FunctionLikeDeclaration) { +export function hasContextSensitiveParameters(node: FunctionLikeDeclaration): boolean { // Functions with type parameters are not context sensitive. if (!node.typeParameters) { // Functions with any parameters that lack type annotations are context sensitive. @@ -10617,7 +10718,7 @@ export function isInfinityOrNaNString(name: string | __String): boolean { } /** @internal */ -export function isCatchClauseVariableDeclaration(node: Node) { +export function isCatchClauseVariableDeclaration(node: Node): boolean { return node.kind === SyntaxKind.VariableDeclaration && node.parent.kind === SyntaxKind.CatchClause; } @@ -10632,7 +10733,7 @@ export function escapeSnippetText(text: string): string { } /** @internal */ -export function isNumericLiteralName(name: string | __String) { +export function isNumericLiteralName(name: string | __String): boolean { // The intent of numeric names is that // - they are names with text in a numeric form, and that // - setting properties/indexing with them is always equivalent to doing so with the numeric literal 'numLit', @@ -10658,7 +10759,7 @@ export function isNumericLiteralName(name: string | __String) { } /** @internal */ -export function createPropertyNameNodeForIdentifierOrLiteral(name: string, target: ScriptTarget, singleQuote: boolean, stringNamed: boolean, isMethod: boolean) { +export function createPropertyNameNodeForIdentifierOrLiteral(name: string, target: ScriptTarget, singleQuote: boolean, stringNamed: boolean, isMethod: boolean): Identifier | StringLiteral | NumericLiteral { const isMethodNamedNew = isMethod && name === "new"; return !isMethodNamedNew && isIdentifierText(name, target) ? factory.createIdentifier(name) : !stringNamed && !isMethodNamedNew && isNumericLiteralName(name) && +name >= 0 ? factory.createNumericLiteral(+name) : @@ -10790,7 +10891,7 @@ export function hasTabstop(node: Node): boolean { } /** @internal */ -export function isJSDocOptionalParameter(node: ParameterDeclaration) { +export function isJSDocOptionalParameter(node: ParameterDeclaration): boolean { return isInJSFile(node) && ( // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType node.type && node.type.kind === SyntaxKind.JSDocOptionalType @@ -10827,12 +10928,12 @@ export function isJSDocSatisfiesExpression(node: Node): node is JSDocSatisfiesEx } /** @internal */ -export function getJSDocSatisfiesExpressionType(node: JSDocSatisfiesExpression) { +export function getJSDocSatisfiesExpressionType(node: JSDocSatisfiesExpression): TypeNode { return Debug.checkDefined(tryGetJSDocSatisfiesTypeNode(node)); } /** @internal */ -export function tryGetJSDocSatisfiesTypeNode(node: Node) { +export function tryGetJSDocSatisfiesTypeNode(node: Node): TypeNode | undefined { const tag = getJSDocSatisfiesTag(node); return tag && tag.typeExpression && tag.typeExpression.type; } @@ -10865,7 +10966,7 @@ export function getTextOfJsxNamespacedName(node: JsxNamespacedName) { } /** @internal */ -export function intrinsicTagNameToString(node: Identifier | JsxNamespacedName) { +export function intrinsicTagNameToString(node: Identifier | JsxNamespacedName): string { return isIdentifier(node) ? idText(node) : getTextOfJsxNamespacedName(node); } @@ -10897,7 +10998,7 @@ export function isExpandoPropertyDeclaration(declaration: Declaration | undefine } /** @internal */ -export function hasResolutionModeOverride(node: ImportTypeNode | ImportDeclaration | ExportDeclaration | JSDocImportTag | undefined) { +export function hasResolutionModeOverride(node: ImportTypeNode | ImportDeclaration | ExportDeclaration | JSDocImportTag | undefined): boolean { if (node === undefined) { return false; } @@ -10916,7 +11017,7 @@ export function replaceFirstStar(s: string, replacement: string): string { } /** @internal */ -export function getNameFromImportAttribute(node: ImportAttribute) { +export function getNameFromImportAttribute(node: ImportAttribute): __String { return isIdentifier(node.name) ? node.name.escapedText : escapeLeadingUnderscores(node.name.text); } @@ -11027,7 +11128,10 @@ export function evaluatorResult(value: T, } /** @internal */ -export function createEvaluator({ evaluateElementAccessExpression, evaluateEntityNameExpression }: EvaluationResolver) { +export function createEvaluator({ evaluateElementAccessExpression, evaluateEntityNameExpression }: EvaluationResolver): { + (expr: TemplateExpression, location?: Declaration): EvaluatorResult; + (expr: Expression, location?: Declaration): EvaluatorResult; +} { function evaluate(expr: TemplateExpression, location?: Declaration): EvaluatorResult; function evaluate(expr: Expression, location?: Declaration): EvaluatorResult; function evaluate(expr: Expression, location?: Declaration): EvaluatorResult { @@ -11157,7 +11261,7 @@ export function createEvaluator({ evaluateElementAccessExpression, evaluateEntit } /** @internal */ -export function isConstAssertion(location: Node) { +export function isConstAssertion(location: Node): boolean { return (isAssertionExpression(location) && isConstTypeReference(location.type)) || (isJSDocTypeTag(location) && isConstTypeReference(location.typeExpression)); } @@ -11211,7 +11315,14 @@ export function createNameResolver({ associatedDeclarationForContainingInitializerOrBindingName: ParameterDeclaration | BindingElement | undefined, withinDeferredContext: boolean, ) => void; -}) { +}): ( + location: Node | undefined, + nameArg: __String | Identifier, + meaning: SymbolFlags, + nameNotFoundMessage: DiagnosticMessage | undefined, + isUse: boolean, + excludeGlobals?: boolean, +) => Symbol | undefined { /* eslint-disable no-var */ var isolatedModulesLikeFlagName = compilerOptions.verbatimModuleSyntax ? "verbatimModuleSyntax" : "isolatedModules"; /* eslint-disable no-var */ @@ -11763,7 +11874,7 @@ export function isPrimitiveLiteralValue(node: Expression, includeBigInt = true): } /** @internal */ -export function unwrapParenthesizedExpression(o: Expression) { +export function unwrapParenthesizedExpression(o: Expression): Expression { while (o.kind === SyntaxKind.ParenthesizedExpression) { o = (o as ParenthesizedExpression).expression; } @@ -11857,13 +11968,13 @@ const unprefixedNodeCoreModulesList = [ ]; /** @internal */ -export const unprefixedNodeCoreModules = new Set(unprefixedNodeCoreModulesList); +export const unprefixedNodeCoreModules: Set = new Set(unprefixedNodeCoreModulesList); // await fetch('https://nodejs.org/docs/latest/api/all.json').then(r => r.text()).then(t => // new Set(t.match(/(?<=')node:.+?(?=')/g)) // .difference(new Set(require('module').builtinModules.map(x => `node:${x}`)))) /** @internal */ -export const exclusivelyPrefixedNodeCoreModules = new Set([ +export const exclusivelyPrefixedNodeCoreModules: Set = new Set([ "node:sea", "node:sqlite", "node:test", @@ -11871,7 +11982,7 @@ export const exclusivelyPrefixedNodeCoreModules = new Set([ ]); /** @internal */ -export const nodeCoreModules = new Set([ +export const nodeCoreModules: Set = new Set([ ...unprefixedNodeCoreModulesList, ...unprefixedNodeCoreModulesList.map(name => `node:${name}`), ...exclusivelyPrefixedNodeCoreModules, diff --git a/src/compiler/utilitiesPublic.ts b/src/compiler/utilitiesPublic.ts index 325f9739c5641..5b5ef0b54cbd4 100644 --- a/src/compiler/utilitiesPublic.ts +++ b/src/compiler/utilitiesPublic.ts @@ -330,15 +330,15 @@ export function getDefaultLibFileName(options: CompilerOptions): string { } } -export function textSpanEnd(span: TextSpan) { +export function textSpanEnd(span: TextSpan): number { return span.start + span.length; } -export function textSpanIsEmpty(span: TextSpan) { +export function textSpanIsEmpty(span: TextSpan): boolean { return span.length === 0; } -export function textSpanContainsPosition(span: TextSpan, position: number) { +export function textSpanContainsPosition(span: TextSpan, position: number): boolean { return position >= span.start && position < textSpanEnd(span); } @@ -348,21 +348,21 @@ export function textRangeContainsPositionInclusive(range: TextRange, position: n } // Returns true if 'span' contains 'other'. -export function textSpanContainsTextSpan(span: TextSpan, other: TextSpan) { +export function textSpanContainsTextSpan(span: TextSpan, other: TextSpan): boolean { return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span); } /** @internal */ -export function textSpanContainsTextRange(span: TextSpan, range: TextRange) { +export function textSpanContainsTextRange(span: TextSpan, range: TextRange): boolean { return range.pos >= span.start && range.end <= textSpanEnd(span); } /** @internal */ -export function textRangeContainsTextSpan(range: TextRange, span: TextSpan) { +export function textRangeContainsTextSpan(range: TextRange, span: TextSpan): boolean { return span.start >= range.pos && textSpanEnd(span) <= range.end; } -export function textSpanOverlapsWith(span: TextSpan, other: TextSpan) { +export function textSpanOverlapsWith(span: TextSpan, other: TextSpan): boolean { return textSpanOverlap(span, other) !== undefined; } @@ -439,15 +439,15 @@ export function createTextSpan(start: number, length: number): TextSpan { return { start, length }; } -export function createTextSpanFromBounds(start: number, end: number) { +export function createTextSpanFromBounds(start: number, end: number): TextSpan { return createTextSpan(start, end - start); } -export function textChangeRangeNewSpan(range: TextChangeRange) { +export function textChangeRangeNewSpan(range: TextChangeRange): TextSpan { return createTextSpan(range.span.start, range.newLength); } -export function textChangeRangeIsUnchanged(range: TextChangeRange) { +export function textChangeRangeIsUnchanged(range: TextChangeRange): boolean { return textSpanIsEmpty(range.span) && range.newLength === 0; } @@ -459,7 +459,7 @@ export function createTextChangeRange(span: TextSpan, newLength: number): TextCh return { span, newLength }; } -export const unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); +export const unchangedTextChangeRange: TextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); /** * Called to merge all the changes that occurred across several versions of a script snapshot @@ -669,7 +669,7 @@ function getNodeFlags(node: Node) { } /** @internal */ -export const supportedLocaleDirectories = ["cs", "de", "es", "fr", "it", "ja", "ko", "pl", "pt-br", "ru", "tr", "zh-cn", "zh-tw"]; +export const supportedLocaleDirectories: string[] = ["cs", "de", "es", "fr", "it", "ja", "ko", "pl", "pt-br", "ru", "tr", "zh-cn", "zh-tw"]; /** * Checks to see if the locale is in the appropriate format, @@ -679,7 +679,7 @@ export function validateLocaleAndSetLanguage( locale: string, sys: { getExecutingFilePath(): string; resolvePath(path: string): string; fileExists(fileName: string): boolean; readFile(fileName: string): string | undefined; }, errors?: Diagnostic[], -) { +): void { const lowerCaseLocale = locale.toLowerCase(); const matchResult = /^([a-z]+)(?:[_-]([a-z]+))?$/.exec(lowerCaseLocale); @@ -913,7 +913,7 @@ function getDeclarationIdentifier(node: Declaration | Expression): Identifier | } /** @internal */ -export function nodeHasName(statement: Node, name: Identifier) { +export function nodeHasName(statement: Node, name: Identifier): boolean { if (isNamedDeclaration(statement) && isIdentifier(statement.name) && idText(statement.name as Identifier) === idText(name)) { return true; } @@ -1276,7 +1276,7 @@ export function getAllJSDocTagsOfKind(node: Node, kind: SyntaxKind): readonly JS } /** Gets the text of a jsdoc comment, flattening links to their text. */ -export function getTextOfJSDocComment(comment?: string | NodeArray) { +export function getTextOfJSDocComment(comment?: string | NodeArray): string | undefined { return typeof comment === "string" ? comment : comment?.map(c => c.kind === SyntaxKind.JSDocText ? c.text : formatJSDocLink(c)).join(""); } @@ -1398,17 +1398,17 @@ export function isExpressionOfOptionalChainRoot(node: Node): node is Expression * * @internal */ -export function isOutermostOptionalChain(node: OptionalChain) { +export function isOutermostOptionalChain(node: OptionalChain): boolean { return !isOptionalChain(node.parent) // cases 1, 2, and 3 || isOptionalChainRoot(node.parent) // case 4 || node !== node.parent.expression; // case 5 } -export function isNullishCoalesce(node: Node) { +export function isNullishCoalesce(node: Node): boolean { return node.kind === SyntaxKind.BinaryExpression && (node as BinaryExpression).operatorToken.kind === SyntaxKind.QuestionQuestionToken; } -export function isConstTypeReference(node: Node) { +export function isConstTypeReference(node: Node): boolean { return isTypeReferenceNode(node) && isIdentifier(node.typeName) && node.typeName.escapedText === "const" && !node.typeArguments; } @@ -1444,7 +1444,7 @@ export function isJSDocPropertyLikeTag(node: Node): node is JSDocPropertyLikeTag // they may be used with transformations. /** @internal */ -export function isNodeKind(kind: SyntaxKind) { +export function isNodeKind(kind: SyntaxKind): boolean { return kind >= SyntaxKind.FirstNode; } @@ -1485,7 +1485,7 @@ export function isLiteralExpression(node: Node): node is LiteralExpression { } /** @internal */ -export function isLiteralExpressionOfObject(node: Node) { +export function isLiteralExpressionOfObject(node: Node): boolean { switch (node.kind) { case SyntaxKind.ObjectLiteralExpression: case SyntaxKind.ArrayLiteralExpression: @@ -1568,7 +1568,7 @@ export function isGeneratedPrivateIdentifier(node: Node): node is GeneratedPriva } /** @internal */ -export function isFileLevelReservedGeneratedIdentifier(node: GeneratedIdentifier) { +export function isFileLevelReservedGeneratedIdentifier(node: GeneratedIdentifier): boolean { const flags = node.emitNode.autoGenerate.flags; return !!(flags & GeneratedIdentifierFlags.FileLevel) && !!(flags & GeneratedIdentifierFlags.Optimistic) @@ -2111,17 +2111,17 @@ function isScopeMarker(node: Node) { } /** @internal */ -export function hasScopeMarker(statements: readonly Statement[]) { +export function hasScopeMarker(statements: readonly Statement[]): boolean { return some(statements, isScopeMarker); } /** @internal */ -export function needsScopeMarker(result: Statement) { +export function needsScopeMarker(result: Statement): boolean { return !isAnyImportOrReExport(result) && !isExportAssignment(result) && !hasSyntacticModifier(result, ModifierFlags.Export) && !isAmbientModule(result); } /** @internal */ -export function isExternalModuleIndicator(result: Statement) { +export function isExternalModuleIndicator(result: Statement): boolean { // Exported top-level member indicates moduleness return isAnyImportOrReExport(result) || isExportAssignment(result) || hasSyntacticModifier(result, ModifierFlags.Export); } @@ -2569,7 +2569,7 @@ export function isTypeReferenceType(node: Node): node is TypeReferenceType { const MAX_SMI_X86 = 0x3fff_ffff; /** @internal */ -export function guessIndentation(lines: string[]) { +export function guessIndentation(lines: string[]): number | undefined { let indentation = MAX_SMI_X86; for (const line of lines) { if (!line.length) { @@ -2614,7 +2614,7 @@ function hasInternalAnnotation(range: CommentRange, sourceFile: SourceFile) { return comment.includes("@internal"); } -export function isInternalDeclaration(node: Node, sourceFile?: SourceFile) { +export function isInternalDeclaration(node: Node, sourceFile?: SourceFile): boolean { sourceFile ??= getSourceFileOfNode(node); const parseTreeNode = getParseTreeNode(node); if (parseTreeNode && parseTreeNode.kind === SyntaxKind.Parameter) { diff --git a/src/compiler/visitorPublic.ts b/src/compiler/visitorPublic.ts index f3e71e026d9be..dbd49379e5750 100644 --- a/src/compiler/visitorPublic.ts +++ b/src/compiler/visitorPublic.ts @@ -379,7 +379,7 @@ function visitArrayWorker( * Starts a new lexical environment and visits a statement list, ending the lexical environment * and merging hoisted declarations upon completion. */ -export function visitLexicalEnvironment(statements: NodeArray, visitor: Visitor, context: TransformationContext, start?: number, ensureUseStrict?: boolean, nodesVisitor: NodesVisitor = visitNodes) { +export function visitLexicalEnvironment(statements: NodeArray, visitor: Visitor, context: TransformationContext, start?: number, ensureUseStrict?: boolean, nodesVisitor: NodesVisitor = visitNodes): NodeArray { context.startLexicalEnvironment(); statements = nodesVisitor(statements, visitor, isStatement, start); if (ensureUseStrict) statements = context.factory.ensureUseStrict(statements); @@ -561,7 +561,7 @@ export function visitIterationBody(body: Statement, visitor: Visitor, context: T * @param visitor The visitor to use when visiting expressions whose result will not be discarded at runtime. * @param discardVisitor The visitor to use when visiting expressions whose result will be discarded at runtime. Defaults to {@link visitor}. */ -export function visitCommaListElements(elements: NodeArray, visitor: Visitor, discardVisitor = visitor): NodeArray { +export function visitCommaListElements(elements: NodeArray, visitor: Visitor, discardVisitor: Visitor = visitor): NodeArray { if (discardVisitor === visitor || elements.length <= 1) { return visitNodes(elements, visitor, isExpression); } diff --git a/src/compiler/watch.ts b/src/compiler/watch.ts index 89c6f13b102c7..b8d21491a517d 100644 --- a/src/compiler/watch.ts +++ b/src/compiler/watch.ts @@ -173,7 +173,7 @@ function getPlainDiagnosticFollowingNewLines(diagnostic: Diagnostic, newLine: st * * @internal */ -export function getLocaleTimeString(system: System) { +export function getLocaleTimeString(system: System): string { return !system.now ? new Date().toLocaleTimeString() : // On some systems / builds of Node, there's a non-breaking space between the time and AM/PM. @@ -225,7 +225,7 @@ export function parseConfigFileWithSystem(configFileName: string, optionsToExten } /** @internal */ -export function getErrorCountForSummary(diagnostics: readonly Diagnostic[]) { +export function getErrorCountForSummary(diagnostics: readonly Diagnostic[]): number { return countWhere(diagnostics, diagnostic => diagnostic.category === DiagnosticCategory.Error); } @@ -256,7 +256,7 @@ export function getFilesInErrorForSummary(diagnostics: readonly Diagnostic[]): ( } /** @internal */ -export function getWatchErrorSummaryDiagnosticMessage(errorCount: number) { +export function getWatchErrorSummaryDiagnosticMessage(errorCount: number): DiagnosticMessage { return errorCount === 1 ? Diagnostics.Found_1_error_Watching_for_file_changes : Diagnostics.Found_0_errors_Watching_for_file_changes; @@ -277,7 +277,7 @@ export function getErrorSummaryText( filesInError: readonly (ReportFileInError | undefined)[], newLine: string, host: HasCurrentDirectory, -) { +): string { if (errorCount === 0) return ""; const nonNilFiles = filesInError.filter(fileInError => fileInError !== undefined); const distinctFileNamesWithLines = nonNilFiles.map(fileInError => `${fileInError.fileName}:${fileInError.line}`) @@ -347,7 +347,7 @@ function listFiles(program: Program | T, write: (s: st } /** @internal */ -export function explainFiles(program: Program, write: (s: string) => void) { +export function explainFiles(program: Program, write: (s: string) => void): void { const reasons = program.getFileIncludeReasons(); const relativeFileName = (fileName: string) => convertToRelativePath(fileName, program.getCurrentDirectory(), program.getCanonicalFileName); for (const file of program.getSourceFiles()) { @@ -412,7 +412,7 @@ export function explainIfFileIsRedirectAndImpliedFormat( } /** @internal */ -export function getMatchedFileSpec(program: Program, fileName: string) { +export function getMatchedFileSpec(program: Program, fileName: string): string | undefined { const configFile = program.getCompilerOptions().configFile; if (!configFile?.configFileSpecs?.validatedFilesSpec) return undefined; @@ -423,7 +423,7 @@ export function getMatchedFileSpec(program: Program, fileName: string) { } /** @internal */ -export function getMatchedIncludeSpec(program: Program, fileName: string) { +export function getMatchedIncludeSpec(program: Program, fileName: string): string | true | undefined { const configFile = program.getCompilerOptions().configFile; if (!configFile?.configFileSpecs?.validatedIncludeSpecs) return undefined; @@ -639,7 +639,7 @@ export function emitFilesAndReportErrorsAndGetExitStatus noopFileWatcher; +export const returnNoopFileWatcher = (): FileWatcher => noopFileWatcher; /** @internal */ -export function createWatchHost(system = sys, reportWatchStatus?: WatchStatusReporter): WatchHost { +export function createWatchHost(system: System = sys, reportWatchStatus?: WatchStatusReporter): WatchHost { const onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); return { onWatchStatusChange, @@ -741,7 +741,7 @@ export interface WatchFactoryWithLog extends WatchFactory(host: WatchFactoryHost & { trace?(s: string): void; }, options: { extendedDiagnostics?: boolean; diagnostics?: boolean; }) { +export function createWatchFactory(host: WatchFactoryHost & { trace?(s: string): void; }, options: { extendedDiagnostics?: boolean; diagnostics?: boolean; }): WatchFactoryWithLog { const watchLogLevel = host.trace ? options.extendedDiagnostics ? WatchLogLevel.Verbose : options.diagnostics ? WatchLogLevel.TriggerOnly : WatchLogLevel.None : WatchLogLevel.None; const writeLog: (s: string) => void = watchLogLevel !== WatchLogLevel.None ? (s => host.trace!(s)) : noop; const result = getWatchFactory(host, watchLogLevel, writeLog) as WatchFactoryWithLog; @@ -784,7 +784,7 @@ export function createCompilerHostFromProgramHost(host: ProgramHost, getCom } /** @internal */ -export function getSourceFileVersionAsHashFromText(host: Pick, text: string) { +export function getSourceFileVersionAsHashFromText(host: Pick, text: string): string { // If text can contain the sourceMapUrl ignore sourceMapUrl for calcualting hash if (text.match(sourceMapCommentRegExpDontCareLineStart)) { let lineEnd = text.length; @@ -823,7 +823,7 @@ export function getSourceFileVersionAsHashFromText(host: Pick { const result = originalGetSourceFile.call(compilerHost, ...args); @@ -982,7 +982,7 @@ export interface IncrementalCompilationOptions { system?: System; } /** @internal */ -export function performIncrementalCompilation(input: IncrementalCompilationOptions) { +export function performIncrementalCompilation(input: IncrementalCompilationOptions): ExitStatus.Success | ExitStatus.DiagnosticsPresent_OutputsSkipped | ExitStatus.DiagnosticsPresent_OutputsGenerated { const system = input.system || sys; const host = input.host || (input.host = createIncrementalCompilerHost(input.options, system)); const builderProgram = createIncrementalProgram(input); diff --git a/src/compiler/watchPublic.ts b/src/compiler/watchPublic.ts index 69147b946af34..c511ec228a64c 100644 --- a/src/compiler/watchPublic.ts +++ b/src/compiler/watchPublic.ts @@ -103,7 +103,7 @@ export interface ReadBuildProgramHost { /** @internal */ getBuildInfo?(fileName: string, configFilePath: string | undefined): BuildInfo | undefined; } -export function readBuilderProgram(compilerOptions: CompilerOptions, host: ReadBuildProgramHost) { +export function readBuilderProgram(compilerOptions: CompilerOptions, host: ReadBuildProgramHost): EmitAndSemanticDiagnosticsBuilderProgram | undefined { const buildInfoPath = getTsBuildInfoEmitOutputFilePath(compilerOptions); if (!buildInfoPath) return undefined; let buildInfo; @@ -120,7 +120,7 @@ export function readBuilderProgram(compilerOptions: CompilerOptions, host: ReadB return createBuilderProgramUsingIncrementalBuildInfo(buildInfo, buildInfoPath, host); } -export function createIncrementalCompilerHost(options: CompilerOptions, system = sys): CompilerHost { +export function createIncrementalCompilerHost(options: CompilerOptions, system: System = sys): CompilerHost { const host = createCompilerHostWorker(options, /*setParentNodes*/ undefined, system); host.createHash = maybeBind(system, system.createHash); host.storeSignatureInfo = system.storeSignatureInfo; diff --git a/src/compiler/watchUtilities.ts b/src/compiler/watchUtilities.ts index cbeceed07fd6e..82c9dbf32e28c 100644 --- a/src/compiler/watchUtilities.ts +++ b/src/compiler/watchUtilities.ts @@ -410,7 +410,7 @@ export function updateSharedExtendedConfigFileWatcher( extendedConfigFilesMap: Map>, createExtendedConfigFileWatch: (extendedConfigPath: string, extendedConfigFilePath: Path) => FileWatcher, toPath: (fileName: string) => Path, -) { +): void { const extendedConfigs = arrayToMap(options?.configFile?.extendedSourceFiles || emptyArray, toPath); // remove project from all unrelated watchers extendedConfigFilesMap.forEach((watcher, extendedConfigFilePath) => { @@ -449,7 +449,7 @@ export function updateSharedExtendedConfigFileWatcher( export function clearSharedExtendedConfigFileWatcher( projectPath: T, extendedConfigFilesMap: Map>, -) { +): void { extendedConfigFilesMap.forEach(watcher => { if (watcher.projects.delete(projectPath)) watcher.close(); }); @@ -464,7 +464,7 @@ export function cleanExtendedConfigCache( extendedConfigCache: Map, extendedConfigFilePath: Path, toPath: (fileName: string) => Path, -) { +): void { if (!extendedConfigCache.delete(extendedConfigFilePath)) return; extendedConfigCache.forEach(({ extendedResult }, key) => { if (extendedResult.extendedSourceFiles?.some(extendedFile => toPath(extendedFile) === extendedConfigFilePath)) { @@ -482,7 +482,7 @@ export function updateMissingFilePathsWatch( program: Program, missingFileWatches: Map, createMissingFileWatch: (missingFilePath: Path, missingFileName: string) => FileWatcher, -) { +): void { // Update the missing file paths watcher mutateMap( missingFileWatches, @@ -515,7 +515,7 @@ export function updateWatchingWildcardDirectories( existingWatchedForWildcards: Map>, wildcardDirectories: MapLike | undefined, watchDirectory: (directory: string, flags: WatchDirectoryFlags) => T, -) { +): void { if (wildcardDirectories) { mutateMap( existingWatchedForWildcards, @@ -665,7 +665,7 @@ export function isIgnoredFileFromWildCardWatching({ } /** @internal */ -export function isEmittedFileOfProgram(program: Program | undefined, file: string) { +export function isEmittedFileOfProgram(program: Program | undefined, file: string): boolean { if (!program) { return false; } @@ -842,6 +842,6 @@ export function getFallbackOptions(options: WatchOptions | undefined): WatchOpti } /** @internal */ -export function closeFileWatcherOf(objWithWatcher: T) { +export function closeFileWatcherOf(objWithWatcher: T): void { objWithWatcher.watcher.close(); } diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index 25a2b125a2150..6ecbc3076ec00 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -189,9 +189,9 @@ import { } from "./_namespaces/ts.server.js"; import * as protocol from "./protocol.js"; -export const maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; +export const maxProgramSizeForNonTsFiles: number = 20 * 1024 * 1024; /** @internal */ -export const maxFileSize = 4 * 1024 * 1024; +export const maxFileSize: number = 4 * 1024 * 1024; export const ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground"; export const ProjectLoadingStartEvent = "projectLoadingStart"; @@ -490,7 +490,7 @@ export function tryConvertScriptKindName(scriptKindName: protocol.ScriptKindName return isString(scriptKindName) ? convertScriptKindName(scriptKindName) : scriptKindName; } -export function convertScriptKindName(scriptKindName: protocol.ScriptKindName) { +export function convertScriptKindName(scriptKindName: protocol.ScriptKindName): ScriptKind.Unknown | ScriptKind.JS | ScriptKind.JSX | ScriptKind.TS | ScriptKind.TSX { switch (scriptKindName) { case "JS": return ScriptKind.JS; @@ -952,7 +952,7 @@ function isScriptInfoWatchedFromNodeModules(info: ScriptInfo) { * returns true if project updated with new program * @internal */ -export function updateProjectIfDirty(project: Project) { +export function updateProjectIfDirty(project: Project): boolean { project.invalidateResolutionsOfFailedLookupLocations(); return project.dirty && !project.updateGraph(); } @@ -1161,7 +1161,7 @@ export class ProjectService { * * @internal */ - readonly filenameToScriptInfo = new Map(); + readonly filenameToScriptInfo: Map = new Map(); private readonly nodeModulesWatchers = new Map(); /** * Contains all the deleted script info's version information so that @@ -1196,11 +1196,11 @@ export class ProjectService { */ readonly configuredProjects: Map = new Map(); /** @internal */ - readonly newInferredProjectName = createProjectNameFactoryWithCounter(makeInferredProjectName); + readonly newInferredProjectName: () => string = createProjectNameFactoryWithCounter(makeInferredProjectName); /** @internal */ - readonly newAutoImportProviderProjectName = createProjectNameFactoryWithCounter(makeAutoImportProviderProjectName); + readonly newAutoImportProviderProjectName: () => string = createProjectNameFactoryWithCounter(makeAutoImportProviderProjectName); /** @internal */ - readonly newAuxiliaryProjectName = createProjectNameFactoryWithCounter(makeAuxiliaryProjectName); + readonly newAuxiliaryProjectName: () => string = createProjectNameFactoryWithCounter(makeAuxiliaryProjectName); /** * Open files: with value being project root path, and key being Path of the file that is open */ @@ -1233,7 +1233,7 @@ export class ProjectService { * * @internal */ - readonly configFileExistenceInfoCache = new Map(); + readonly configFileExistenceInfoCache: Map = new Map(); /** @internal */ readonly throttledOperations: ThrottledOperations; private readonly hostConfiguration: HostConfiguration; @@ -1295,7 +1295,7 @@ export class ProjectService { private currentPluginEnablementPromise?: Promise; /** @internal */ baseline: (title?: string) => void = noop; - /** @internal */ verifyDocumentRegistry = noop; + /** @internal */ verifyDocumentRegistry: typeof noop = noop; /** @internal */ verifyProgram: (project: Project) => void = noop; /** @internal */ onProjectCreation: (project: Project) => void = noop; /** @internal */ canUseWatchEvents: boolean; @@ -1372,22 +1372,22 @@ export class ProjectService { opts.incrementalVerifier?.(this); } - toPath(fileName: string) { + toPath(fileName: string): Path { return toPath(fileName, this.currentDirectory, this.toCanonicalFileName); } /** @internal */ - getExecutingFilePath() { + getExecutingFilePath(): string { return this.getNormalizedAbsolutePath(this.host.getExecutingFilePath()); } /** @internal */ - getNormalizedAbsolutePath(fileName: string) { + getNormalizedAbsolutePath(fileName: string): string { return getNormalizedAbsolutePath(fileName, this.host.getCurrentDirectory()); } /** @internal */ - setDocument(key: DocumentRegistryBucketKeyWithMode, path: Path, sourceFile: SourceFile) { + setDocument(key: DocumentRegistryBucketKeyWithMode, path: Path, sourceFile: SourceFile): void { const info = Debug.checkDefined(this.getScriptInfoForPath(path)); info.cacheSourceFile = { key, sourceFile }; } @@ -1399,17 +1399,17 @@ export class ProjectService { } /** @internal */ - ensureInferredProjectsUpToDate_TestOnly() { + ensureInferredProjectsUpToDate_TestOnly(): void { this.ensureProjectStructuresUptoDate(); } /** @internal */ - getCompilerOptionsForInferredProjects() { + getCompilerOptionsForInferredProjects(): CompilerOptions | undefined { return this.compilerOptionsForInferredProjects; } /** @internal */ - onUpdateLanguageServiceStateForProject(project: Project, languageServiceEnabled: boolean) { + onUpdateLanguageServiceStateForProject(project: Project, languageServiceEnabled: boolean): void { if (!this.eventHandler) { return; } @@ -1473,12 +1473,12 @@ export class ProjectService { } /** @internal */ - watchTypingLocations(response: WatchTypingLocations) { + watchTypingLocations(response: WatchTypingLocations): void { this.findProject(response.projectName)?.watchTypingLocations(response.files); } /** @internal */ - delayEnsureProjectForOpenFiles() { + delayEnsureProjectForOpenFiles(): void { if (!this.openFiles.size) return; this.pendingEnsureProjectForOpenFiles = true; this.throttledOperations.schedule(ensureProjectForOpenFileSchedule, /*delay*/ 2500, () => { @@ -1511,12 +1511,12 @@ export class ProjectService { } /** @internal */ - hasPendingProjectUpdate(project: Project) { + hasPendingProjectUpdate(project: Project): boolean { return this.pendingProjectUpdates.has(project.getProjectName()); } /** @internal */ - sendProjectsUpdatedInBackgroundEvent() { + sendProjectsUpdatedInBackgroundEvent(): void { if (!this.eventHandler) { return; } @@ -1531,7 +1531,7 @@ export class ProjectService { } /** @internal */ - sendLargeFileReferencedEvent(file: string, fileSize: number) { + sendLargeFileReferencedEvent(file: string, fileSize: number): void { if (!this.eventHandler) { return; } @@ -1544,7 +1544,7 @@ export class ProjectService { } /** @internal */ - sendProjectLoadingStartEvent(project: ConfiguredProject, reason: string) { + sendProjectLoadingStartEvent(project: ConfiguredProject, reason: string): void { if (!this.eventHandler) { return; } @@ -1557,7 +1557,7 @@ export class ProjectService { } /** @internal */ - sendProjectLoadingFinishEvent(project: ConfiguredProject) { + sendProjectLoadingFinishEvent(project: ConfiguredProject): void { if (!this.eventHandler || !project.sendLoadingProjectFinish) { return; } @@ -1571,14 +1571,14 @@ export class ProjectService { } /** @internal */ - sendPerformanceEvent(kind: PerformanceEvent["kind"], durationMs: number) { + sendPerformanceEvent(kind: PerformanceEvent["kind"], durationMs: number): void { if (this.performanceEventHandler) { this.performanceEventHandler({ kind, durationMs }); } } /** @internal */ - delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project: Project) { + delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project: Project): void { this.delayUpdateProjectGraph(project); this.delayEnsureProjectForOpenFiles(); } @@ -1654,14 +1654,14 @@ export class ProjectService { } /** @internal */ - forEachProject(cb: (project: Project) => void) { + forEachProject(cb: (project: Project) => void): void { this.externalProjects.forEach(cb); this.configuredProjects.forEach(cb); this.inferredProjects.forEach(cb); } /** @internal */ - forEachEnabledProject(cb: (project: Project) => void) { + forEachEnabledProject(cb: (project: Project) => void): void { this.forEachProject(project => { if (!project.isOrphan() && project.languageServiceEnabled) { cb(project); @@ -1712,7 +1712,7 @@ export class ProjectService { (this.logErrorForScriptInfoNotFound(isString(fileNameOrScriptInfo) ? fileNameOrScriptInfo : fileNameOrScriptInfo.fileName), Errors.ThrowNoProject()); } - getScriptInfoEnsuringProjectsUptoDate(uncheckedFileName: string) { + getScriptInfoEnsuringProjectsUptoDate(uncheckedFileName: string): ScriptInfo | undefined { this.ensureProjectStructuresUptoDate(); return this.getScriptInfo(uncheckedFileName); } @@ -1739,7 +1739,7 @@ export class ProjectService { } } - getFormatCodeOptions(file: NormalizedPath) { + getFormatCodeOptions(file: NormalizedPath): FormatCodeSettings { const info = this.getScriptInfoForNormalizedPath(file); return info && info.getFormatCodeSettings() || this.hostConfiguration.formatCodeOptions; } @@ -2094,7 +2094,7 @@ export class ProjectService { } /** @internal */ - assignOrphanScriptInfoToInferredProject(info: ScriptInfo, projectRootPath: NormalizedPath | undefined) { + assignOrphanScriptInfoToInferredProject(info: ScriptInfo, projectRootPath: NormalizedPath | undefined): InferredProject { Debug.assert(info.isOrphan()); const project = this.getOrCreateInferredProjectForProjectRootPathIfEnabled(info, projectRootPath) || this.getOrCreateSingleInferredProjectIfEnabled() || @@ -2298,7 +2298,7 @@ export class ProjectService { } /** @internal */ - releaseParsedConfig(canonicalConfigFilePath: NormalizedPath, forProject: ConfiguredProject) { + releaseParsedConfig(canonicalConfigFilePath: NormalizedPath, forProject: ConfiguredProject): void { const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath)!; if (!configFileExistenceInfo.config?.projects.delete(forProject.canonicalConfigFilePath)) return; // If there are still projects watching this config file existence and config, there is nothing to do @@ -2336,7 +2336,7 @@ export class ProjectService { * so that we handle the watches and inferred project root data * @internal */ - stopWatchingConfigFilesForScriptInfo(info: ScriptInfo) { + stopWatchingConfigFilesForScriptInfo(info: ScriptInfo): void { if (this.serverMode !== LanguageServiceMode.Semantic) return; const isRootOfInferredProject = this.rootOfInferredProjects.delete(info); const isOpen = info.isScriptOpen(); @@ -2392,7 +2392,7 @@ export class ProjectService { * * @internal */ - startWatchingConfigFilesForInferredProjectRoot(info: ScriptInfo) { + startWatchingConfigFilesForInferredProjectRoot(info: ScriptInfo): void { if (this.serverMode !== LanguageServiceMode.Semantic) return; Debug.assert(info.isScriptOpen()); // Set this file as the root of inferred project @@ -2480,7 +2480,7 @@ export class ProjectService { } /** @internal */ - findDefaultConfiguredProject(info: ScriptInfo) { + findDefaultConfiguredProject(info: ScriptInfo): ConfiguredProject | undefined { return info.isScriptOpen() ? this.tryFindDefaultConfiguredProjectForOpenScriptInfo( info, @@ -2523,7 +2523,7 @@ export class ProjectService { * when findFromCacheOnly is true only looked up in cache instead of hitting disk to figure things out * @internal */ - getConfigFileNameForFile(info: OpenScriptInfoOrClosedOrConfigFileInfo, findFromCacheOnly: boolean) { + getConfigFileNameForFile(info: OpenScriptInfoOrClosedOrConfigFileInfo, findFromCacheOnly: boolean): NormalizedPath | undefined { // If we are using already cached values, look for values from pending update as well const fromCache = this.getConfigFileNameForFileFromCache(info, findFromCacheOnly); if (fromCache !== undefined) return fromCache || undefined; @@ -2682,7 +2682,7 @@ export class ProjectService { } /** @internal */ - createConfiguredProject(configFileName: NormalizedPath, reason: string) { + createConfiguredProject(configFileName: NormalizedPath, reason: string): ConfiguredProject { tracing?.instant(tracing.Phase.Session, "createConfiguredProject", { configFilePath: configFileName }); this.logger.info(`Creating configuration project ${configFileName}`); const canonicalConfigFilePath = asNormalizedPath(this.toCanonicalFileName(configFileName)); @@ -2868,7 +2868,7 @@ export class ProjectService { } /** @internal */ - watchWildcards(configFileName: NormalizedPath, { exists, config }: ConfigFileExistenceInfo, forProject: ConfiguredProject) { + watchWildcards(configFileName: NormalizedPath, { exists, config }: ConfigFileExistenceInfo, forProject: ConfiguredProject): void { config!.projects.set(forProject.canonicalConfigFilePath, true); if (exists) { if (config!.watchedDirectories && !config!.watchedDirectoriesStale) return; @@ -2889,7 +2889,7 @@ export class ProjectService { } /** @internal */ - stopWatchingWildCards(canonicalConfigFilePath: NormalizedPath, forProject: ConfiguredProject) { + stopWatchingWildCards(canonicalConfigFilePath: NormalizedPath, forProject: ConfiguredProject): void { const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath)!; if ( !configFileExistenceInfo.config || @@ -2995,7 +2995,7 @@ export class ProjectService { * * @internal */ - reloadFileNamesOfConfiguredProject(project: ConfiguredProject) { + reloadFileNamesOfConfiguredProject(project: ConfiguredProject): boolean { const fileNames = this.reloadFileNamesOfParsedConfig(project.getConfigFilePath(), this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath)!.config!); project.updateErrorOnNoInputFiles(fileNames); this.updateNonInferredProjectFiles(project, fileNames.concat(project.getExternalFiles(ProgramUpdateLevel.RootNamesAndUpdate)), fileNamePropertyReader); @@ -3019,7 +3019,7 @@ export class ProjectService { } /** @internal */ - setFileNamesOfAutpImportProviderOrAuxillaryProject(project: AutoImportProviderProject | AuxiliaryProject, fileNames: readonly string[]) { + setFileNamesOfAutpImportProviderOrAuxillaryProject(project: AutoImportProviderProject | AuxiliaryProject, fileNames: readonly string[]): void { this.updateNonInferredProjectFiles(project, fileNames, fileNamePropertyReader); } @@ -3028,7 +3028,7 @@ export class ProjectService { project: ConfiguredProject, reason: string, reloadedProjects: Set, - ) { + ): boolean { if (!tryAddToSet(reloadedProjects, project)) return false; this.clearSemanticCache(project); this.reloadConfiguredProject(project, reloadReason(reason)); @@ -3040,7 +3040,7 @@ export class ProjectService { * * @internal */ - reloadConfiguredProject(project: ConfiguredProject, reason: string) { + reloadConfiguredProject(project: ConfiguredProject, reason: string): void { project.isInitialLoadPending = returnFalse; project.pendingUpdateReason = undefined; project.pendingUpdateLevel = ProgramUpdateLevel.Update; @@ -3065,7 +3065,7 @@ export class ProjectService { } /** @internal */ - sendConfigFileDiagEvent(project: ConfiguredProject, triggerFile: NormalizedPath | undefined, force: boolean) { + sendConfigFileDiagEvent(project: ConfiguredProject, triggerFile: NormalizedPath | undefined, force: boolean): boolean { if (!this.eventHandler || this.suppressDiagnosticEvents) return false; const diagnostics = project.getLanguageService().getCompilerOptionsDiagnostics(); diagnostics.push(...project.getAllProjectErrors()); @@ -3188,7 +3188,7 @@ export class ProjectService { currentDirectory: string, hostToQueryFileExistsOn: DirectoryStructureHost, deferredDeleteOk: boolean, - ) { + ): ScriptInfo | undefined { return this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath( toNormalizedPath(uncheckedFileName), currentDirectory, @@ -3199,7 +3199,7 @@ export class ProjectService { ); } - getScriptInfo(uncheckedFileName: string) { + getScriptInfo(uncheckedFileName: string): ScriptInfo | undefined { return this.getScriptInfoForNormalizedPath(toNormalizedPath(uncheckedFileName)); } @@ -3447,7 +3447,7 @@ export class ProjectService { scriptKind?: ScriptKind, hasMixedContent?: boolean, hostToQueryFileExistsOn?: { fileExists(path: string): boolean; }, - ) { + ): ScriptInfo | undefined { return this.getOrCreateScriptInfoWorker( fileName, this.currentDirectory, @@ -3516,12 +3516,12 @@ export class ProjectService { /** * This gets the script info for the normalized path. If the path is not rooted disk path then the open script info with project root context is preferred */ - getScriptInfoForNormalizedPath(fileName: NormalizedPath) { + getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo | undefined { return !isRootedDiskPath(fileName) && this.openFilesWithNonRootedDiskPath.get(this.toCanonicalFileName(fileName)) || this.getScriptInfoForPath(normalizedPathToPath(fileName, this.currentDirectory, this.toCanonicalFileName)); } - getScriptInfoForPath(fileName: Path) { + getScriptInfoForPath(fileName: Path): ScriptInfo | undefined { const info = this.filenameToScriptInfo.get(fileName); return !info || !info.deferredDelete ? info : undefined; } @@ -3694,11 +3694,11 @@ export class ProjectService { } /** @internal */ - setPerformanceEventHandler(performanceEventHandler: PerformanceEventHandler) { + setPerformanceEventHandler(performanceEventHandler: PerformanceEventHandler): void { this.performanceEventHandler = performanceEventHandler; } - setHostConfiguration(args: protocol.ConfigureRequestArguments) { + setHostConfiguration(args: protocol.ConfigureRequestArguments): void { if (args.file) { const info = this.getScriptInfoForNormalizedPath(toNormalizedPath(args.file)); if (info) { @@ -3766,7 +3766,7 @@ export class ProjectService { } /** @internal */ - getWatchOptions(project: Project) { + getWatchOptions(project: Project): WatchOptions | undefined { return this.getWatchOptionsFromProjectWatchOptions(project.getWatchOptions(), project.getCurrentDirectory()); } @@ -3781,7 +3781,7 @@ export class ProjectService { projectOptions || hostWatchOptions; } - closeLog() { + closeLog(): void { this.logger.close(); } @@ -3817,7 +3817,7 @@ export class ProjectService { * This function rebuilds the project for every file opened by the client * This does not reload contents of open files from disk. But we could do that if needed */ - reloadProjects() { + reloadProjects(): void { this.logger.info("reload projects."); // If we want this to also reload open files from disk, we could do that, // but then we need to make sure we arent calling this function @@ -4315,7 +4315,7 @@ export class ProjectService { } /** @internal */ - loadAncestorProjectTree(forProjects?: ReadonlyCollection) { + loadAncestorProjectTree(forProjects?: ReadonlyCollection): void { forProjects ??= new Set( mapDefinedIterator(this.configuredProjects.entries(), ([key, project]) => !project.isInitialLoadPending() ? key : undefined), ); @@ -4722,7 +4722,7 @@ export class ProjectService { } /** @internal */ - applyChangesToFile(scriptInfo: ScriptInfo, changes: Iterable) { + applyChangesToFile(scriptInfo: ScriptInfo, changes: Iterable): void { for (const change of changes) { scriptInfo.editContent(change.span.start, change.span.start + change.span.length, change.newText); } @@ -4976,7 +4976,7 @@ export class ProjectService { } } - hasDeferredExtension() { + hasDeferredExtension(): boolean { for (const extension of this.hostConfiguration.extraFileExtensions!) { // TODO: GH#18217 if (extension.scriptKind === ScriptKind.Deferred) { return true; @@ -4990,7 +4990,7 @@ export class ProjectService { * Performs the initial steps of enabling a plugin by finding and instantiating the module for a plugin either asynchronously or synchronously * @internal */ - requestEnablePlugin(project: Project, pluginConfigEntry: PluginImport, searchPaths: string[]) { + requestEnablePlugin(project: Project, pluginConfigEntry: PluginImport, searchPaths: string[]): void { if (!this.host.importPlugin && !this.host.require) { this.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); return; @@ -5054,12 +5054,12 @@ export class ProjectService { } /** @internal */ - hasNewPluginEnablementRequests() { + hasNewPluginEnablementRequests(): boolean { return !!this.pendingPluginEnablements; } /** @internal */ - hasPendingPluginEnablements() { + hasPendingPluginEnablements(): boolean { return !!this.currentPluginEnablementPromise; } @@ -5068,7 +5068,7 @@ export class ProjectService { * * @internal */ - async waitForPendingPlugins() { + async waitForPendingPlugins(): Promise { while (this.currentPluginEnablementPromise) { await this.currentPluginEnablementPromise; } @@ -5079,7 +5079,7 @@ export class ProjectService { * * @internal */ - enableRequestedPlugins() { + enableRequestedPlugins(): void { if (this.pendingPluginEnablements) { void this.enableRequestedPluginsAsync(); } @@ -5136,7 +5136,7 @@ export class ProjectService { if (sendProjectsUpdatedInBackgroundEvent) this.sendProjectsUpdatedInBackgroundEvent(); } - configurePlugin(args: protocol.ConfigurePluginRequestArguments) { + configurePlugin(args: protocol.ConfigurePluginRequestArguments): void { // For any projects that already have the plugin loaded, configure the plugin this.forEachEnabledProject(project => project.onPluginConfigurationChanged(args.pluginName, args.configuration)); @@ -5247,7 +5247,7 @@ export class ProjectService { } /** @internal */ - getIncompleteCompletionsCache() { + getIncompleteCompletionsCache(): IncompleteCompletionsCache { return this.incompleteCompletionsCache ||= createIncompleteCompletionsCache(); } } diff --git a/src/server/project.ts b/src/server/project.ts index 187d2b146038f..19f9a79bef6d0 100644 --- a/src/server/project.ts +++ b/src/server/project.ts @@ -68,6 +68,7 @@ import { HasInvalidatedLibResolutions, HasInvalidatedResolutions, HostCancellationToken, + IncompleteCompletionsCache, inferredTypesContainingFile, InstallPackageOptions, IScriptSnapshot, @@ -85,6 +86,7 @@ import { memoize, ModuleResolutionCache, ModuleResolutionHost, + ModuleSpecifierCache, noop, noopFileWatcher, normalizePath, @@ -115,6 +117,7 @@ import { sortAndDeduplicate, SortedReadonlyArray, SourceFile, + SourceFileLike, SourceMapper, startsWith, StringLiteralLike, @@ -377,7 +380,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo * * @internal */ - cachedUnresolvedImportsPerFile = new Map(); + cachedUnresolvedImportsPerFile: Map = new Map(); /** @internal */ lastCachedUnresolvedImportsList: SortedReadonlyArray | undefined; @@ -465,12 +468,12 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo private readonly cancellationToken: ThrottledCancellationToken; - public isNonTsProject() { + public isNonTsProject(): boolean { updateProjectIfDirty(this); return allFilesAreJsOrDts(this); } - public isJsOnlyProject() { + public isJsOnlyProject(): boolean { updateProjectIfDirty(this); return hasOneOrMoreJsAndNoTsFiles(this); } @@ -554,7 +557,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo /** @internal */ protected typeAcquisition: TypeAcquisition | undefined; /** @internal */ - createHash = maybeBind(this.projectService.host, this.projectService.host.createHash); + createHash: ((data: string) => string) | undefined = maybeBind(this.projectService.host, this.projectService.host.createHash); /** @internal*/ preferNonRecursiveWatch: boolean | undefined; readonly jsDocParsingMode: JSDocParsingMode | undefined; @@ -643,7 +646,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo } /** @internal */ - getGlobalTypingsCacheLocation() { + getGlobalTypingsCacheLocation(): string | undefined { return this.getGlobalCache(); } @@ -663,20 +666,20 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo } // Method of LanguageServiceHost - getCompilationSettings() { + getCompilationSettings(): CompilerOptions { return this.compilerOptions; } // Method to support public API - getCompilerOptions() { + getCompilerOptions(): CompilerOptions { return this.getCompilationSettings(); } - getNewLine() { + getNewLine(): string { return this.projectService.host.newLine; } - getProjectVersion() { + getProjectVersion(): string { return this.projectStateVersion.toString(); } @@ -684,7 +687,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo return undefined; } - getScriptFileNames() { + getScriptFileNames(): string[] { if (!this.rootFilesMap.size) { return ts.emptyArray; } @@ -718,12 +721,12 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo return scriptInfo; } - getScriptKind(fileName: string) { + getScriptKind(fileName: string): ScriptKind { const info = this.projectService.getScriptInfoForPath(this.toPath(fileName)); return (info && info.scriptKind)!; // TODO: GH#18217 } - getScriptVersion(filename: string) { + getScriptVersion(filename: string): string { // Don't attach to the project if version is asked const info = this.projectService.getOrCreateScriptInfoNotOpenedByClient( @@ -750,12 +753,12 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo return this.currentDirectory; } - getDefaultLibFileName() { + getDefaultLibFileName(): string { const nodeModuleBinDir = getDirectoryPath(normalizePath(this.projectService.getExecutingFilePath())); return combinePaths(nodeModuleBinDir, getDefaultLibFileName(this.compilerOptions)); } - useCaseSensitiveFileNames() { + useCaseSensitiveFileNames(): boolean { return this.projectService.host.useCaseSensitiveFileNames; } @@ -820,12 +823,12 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo } /** @internal */ - toPath(fileName: string) { + toPath(fileName: string): Path { return toPath(fileName, this.currentDirectory, this.projectService.toCanonicalFileName); } /** @internal */ - watchDirectoryOfFailedLookupLocation(directory: string, cb: DirectoryWatcherCallback, flags: WatchDirectoryFlags) { + watchDirectoryOfFailedLookupLocation(directory: string, cb: DirectoryWatcherCallback, flags: WatchDirectoryFlags): FileWatcher { return this.projectService.watchFactory.watchDirectory( directory, cb, @@ -837,7 +840,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo } /** @internal */ - watchAffectingFileLocation(file: string, cb: FileWatcherCallback) { + watchAffectingFileLocation(file: string, cb: FileWatcherCallback): FileWatcher { return this.projectService.watchFactory.watchFile( file, cb, @@ -849,12 +852,12 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo } /** @internal */ - clearInvalidateResolutionOfFailedLookupTimer() { + clearInvalidateResolutionOfFailedLookupTimer(): boolean { return this.projectService.throttledOperations.cancel(`${this.getProjectName()}FailedLookupInvalidation`); } /** @internal */ - scheduleInvalidateResolutionsOfFailedLookupLocations() { + scheduleInvalidateResolutionsOfFailedLookupLocations(): void { this.projectService.throttledOperations.schedule(`${this.getProjectName()}FailedLookupInvalidation`, /*delay*/ 1000, () => { if (this.resolutionCache.invalidateResolutionsOfFailedLookupLocations()) { this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this); @@ -863,7 +866,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo } /** @internal */ - invalidateResolutionsOfFailedLookupLocations() { + invalidateResolutionsOfFailedLookupLocations(): void { if ( this.clearInvalidateResolutionOfFailedLookupTimer() && this.resolutionCache.invalidateResolutionsOfFailedLookupLocations() @@ -874,12 +877,12 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo } /** @internal */ - onInvalidatedResolution() { + onInvalidatedResolution(): void { this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this); } /** @internal */ - watchTypeRootsDirectory(directory: string, cb: DirectoryWatcherCallback, flags: WatchDirectoryFlags) { + watchTypeRootsDirectory(directory: string, cb: DirectoryWatcherCallback, flags: WatchDirectoryFlags): FileWatcher { return this.projectService.watchFactory.watchDirectory( directory, cb, @@ -891,38 +894,38 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo } /** @internal */ - hasChangedAutomaticTypeDirectiveNames() { + hasChangedAutomaticTypeDirectiveNames(): boolean { return this.resolutionCache.hasChangedAutomaticTypeDirectiveNames(); } /** @internal */ - onChangedAutomaticTypeDirectiveNames() { + onChangedAutomaticTypeDirectiveNames(): void { this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this); } /** @internal */ - getGlobalCache() { + getGlobalCache(): string | undefined { return this.getTypeAcquisition().enable ? this.projectService.typingsInstaller.globalTypingsCacheLocation : undefined; } /** @internal */ - globalCacheResolutionModuleName = JsTyping.nonRelativeModuleNameForTypingCache; + globalCacheResolutionModuleName: typeof JsTyping.nonRelativeModuleNameForTypingCache = JsTyping.nonRelativeModuleNameForTypingCache; /** @internal */ - fileIsOpen(filePath: Path) { + fileIsOpen(filePath: Path): boolean { return this.projectService.openFiles.has(filePath); } /** @internal */ - writeLog(s: string) { + writeLog(s: string): void { this.projectService.logger.info(s); } - log(s: string) { + log(s: string): void { this.writeLog(s); } - error(s: string) { + error(s: string): void { this.projectService.logger.msg(s, Msg.Err); } @@ -946,7 +949,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo return this.projectErrors || emptyArray; } - setProjectErrors(projectErrors: Diagnostic[] | undefined) { + setProjectErrors(projectErrors: Diagnostic[] | undefined): void { this.projectErrors = projectErrors; } @@ -963,7 +966,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo } /** @internal */ - clearSourceMapperCache() { + clearSourceMapperCache(): void { this.languageService.clearSourceMapperCache(); } @@ -973,12 +976,12 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo } /** @internal */ - getSourceFileLike(fileName: string) { + getSourceFileLike(fileName: string): SourceFileLike | undefined { return this.projectService.getSourceFileLike(fileName, this); } /** @internal */ - shouldEmitFile(scriptInfo: ScriptInfo | undefined) { + shouldEmitFile(scriptInfo: ScriptInfo | undefined): boolean | undefined { return scriptInfo && !scriptInfo.isDynamicOrHasMixedContent() && !this.program!.isSourceOfProjectReferenceRedirect(scriptInfo.path); @@ -1032,7 +1035,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo return { emitSkipped, diagnostics }; } - enableLanguageService() { + enableLanguageService(): void { if (this.languageServiceEnabled || this.projectService.serverMode === LanguageServiceMode.Syntactic) { return; } @@ -1042,7 +1045,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo } /** @internal */ - cleanupProgram() { + cleanupProgram(): void { if (this.program) { // Root files are always attached to the project irrespective of program for (const f of this.program.getSourceFiles()) { @@ -1053,7 +1056,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo } } - disableLanguageService(lastFileExceededProgramSize?: string) { + disableLanguageService(lastFileExceededProgramSize?: string): void { if (!this.languageServiceEnabled) { return; } @@ -1073,7 +1076,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo this.projectService.onUpdateLanguageServiceStateForProject(this, /*languageServiceEnabled*/ false); } - getProjectName() { + getProjectName(): string { return this.projectName; } @@ -1100,7 +1103,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo })); } - getSourceFile(path: Path) { + getSourceFile(path: Path): SourceFile | undefined { if (!this.program) { return undefined; } @@ -1113,7 +1116,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo return path === options.configFilePath ? options.configFile : this.getSourceFile(path); } - close() { + close(): void { if (this.typingsCache) this.projectService.typingsInstaller.onProjectClosed(this); this.typingsCache = undefined; this.closeWatchingTypingLocations(); @@ -1176,11 +1179,11 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo } } - isClosed() { + isClosed(): boolean { return this.rootFilesMap === undefined; } - hasRoots() { + hasRoots(): boolean { return !!this.rootFilesMap?.size; } @@ -1194,11 +1197,11 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo } /** @internal */ - getRootFilesMap() { + getRootFilesMap(): Map { return this.rootFilesMap; } - getRootScriptInfos() { + getRootScriptInfos(): ts.server.ScriptInfo[] { return arrayFrom(ts.mapDefinedIterator(this.rootFilesMap.values(), value => value.info)); } @@ -1218,7 +1221,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo return emptyArray; } - getFileNames(excludeFilesFromExternalLibraries?: boolean, excludeConfigFiles?: boolean) { + getFileNames(excludeFilesFromExternalLibraries?: boolean, excludeConfigFiles?: boolean): ts.server.NormalizedPath[] { if (!this.program) { return []; } @@ -1256,14 +1259,14 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo } /** @internal */ - getFileNamesWithRedirectInfo(includeProjectReferenceRedirectInfo: boolean) { + getFileNamesWithRedirectInfo(includeProjectReferenceRedirectInfo: boolean): ts.server.protocol.FileWithProjectReferenceRedirectInfo[] { return this.getFileNames().map((fileName): protocol.FileWithProjectReferenceRedirectInfo => ({ fileName, isSourceOfProjectReferenceRedirect: includeProjectReferenceRedirectInfo && this.isSourceOfProjectReferenceRedirect(fileName), })); } - hasConfigFile(configFilePath: NormalizedPath) { + hasConfigFile(configFilePath: NormalizedPath): boolean { if (this.program && this.languageServiceEnabled) { const configFile = this.program.getCompilerOptions().configFile; if (configFile) { @@ -1297,12 +1300,12 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo return false; } - isRoot(info: ScriptInfo) { + isRoot(info: ScriptInfo): boolean { return this.rootFilesMap?.get(info.path)?.info === info; } // add a root file to project - addRoot(info: ScriptInfo, fileName?: NormalizedPath) { + addRoot(info: ScriptInfo, fileName?: NormalizedPath): void { Debug.assert(!this.isRoot(info)); this.rootFilesMap.set(info.path, { fileName: fileName || info.fileName, info }); info.attachToProject(this); @@ -1311,13 +1314,13 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo } // add a root file that doesnt exist on host - addMissingFileRoot(fileName: NormalizedPath) { + addMissingFileRoot(fileName: NormalizedPath): void { const path = this.projectService.toPath(fileName); this.rootFilesMap.set(path, { fileName }); this.markAsDirty(); } - removeFile(info: ScriptInfo, fileExists: boolean, detachFromProject: boolean) { + removeFile(info: ScriptInfo, fileExists: boolean, detachFromProject: boolean): void { if (this.isRoot(info)) { this.removeRoot(info); } @@ -1337,12 +1340,12 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo this.markAsDirty(); } - registerFileUpdate(fileName: string) { + registerFileUpdate(fileName: string): void { (this.updatedFileNames || (this.updatedFileNames = new Set())).add(fileName); } /** @internal */ - markFileAsDirty(changedFile: Path) { + markFileAsDirty(changedFile: Path): void { this.markAsDirty(); if (this.exportMapCache && !this.exportMapCache.isEmpty()) { (this.changedFilesForExportMapCache ||= new Set()).add(changedFile); @@ -1350,7 +1353,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo } /** @internal */ - markAsDirty() { + markAsDirty(): void { if (!this.dirty) { this.projectStateVersion++; this.dirty = true; @@ -1358,24 +1361,24 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo } /** @internal */ - markAutoImportProviderAsDirty() { + markAutoImportProviderAsDirty(): void { if (!this.autoImportProviderHost) this.autoImportProviderHost = undefined; this.autoImportProviderHost?.markAsDirty(); } /** @internal */ - onAutoImportProviderSettingsChanged() { + onAutoImportProviderSettingsChanged(): void { this.markAutoImportProviderAsDirty(); } /** @internal */ - onPackageJsonChange() { + onPackageJsonChange(): void { this.moduleSpecifierCache.clear(); this.markAutoImportProviderAsDirty(); } /** @internal */ - onFileAddedOrRemoved(isSymlink: boolean | undefined) { + onFileAddedOrRemoved(isSymlink: boolean | undefined): void { this.hasAddedorRemovedFiles = true; if (isSymlink) { this.hasAddedOrRemovedSymlinks = true; @@ -1383,7 +1386,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo } /** @internal */ - onDiscoveredSymlink() { + onDiscoveredSymlink(): void { this.hasAddedOrRemovedSymlinks = true; } @@ -1393,7 +1396,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo _oldOptions: CompilerOptions, hasSourceFileByPath: boolean, newSourceFileByResolvedPath: SourceFile | undefined, - ) { + ): void { if ( !newSourceFileByResolvedPath || (oldSourceFile.resolvedPath === oldSourceFile.path && newSourceFileByResolvedPath.resolvedPath !== oldSourceFile.path) @@ -1409,7 +1412,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo updateFromProjectInProgress = false; /** @internal */ - updateFromProject() { + updateFromProject(): void { updateProjectIfDirty(this); } @@ -1468,7 +1471,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo } /** @internal */ - enqueueInstallTypingsForProject(forceRefresh: boolean) { + enqueueInstallTypingsForProject(forceRefresh: boolean): void { const typeAcquisition = this.getTypeAcquisition(); if (!typeAcquisition || !typeAcquisition.enable || this.projectService.typingsInstaller === nullTypingsInstaller) { @@ -1496,7 +1499,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo } /** @internal */ - updateTypingFiles(compilerOptions: CompilerOptions, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray, newTypings: string[]) { + updateTypingFiles(compilerOptions: CompilerOptions, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray, newTypings: string[]): void { this.typingsCache = { compilerOptions, typeAcquisition, @@ -1523,7 +1526,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo } /** @internal */ - watchTypingLocations(files: readonly string[] | undefined) { + watchTypingLocations(files: readonly string[] | undefined): void { if (!files) { this.typingWatchers!.isInvoked = false; return; @@ -1784,7 +1787,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo } /** @internal */ - sendPerformanceEvent(kind: PerformanceEvent["kind"], durationMs: number) { + sendPerformanceEvent(kind: PerformanceEvent["kind"], durationMs: number): void { this.projectService.sendPerformanceEvent(kind, durationMs); } @@ -1832,7 +1835,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo } /** @internal */ - addGeneratedFileWatch(generatedFile: string, sourceFile: string) { + addGeneratedFileWatch(generatedFile: string, sourceFile: string): void { if (this.compilerOptions.outFile) { // Single watcher if (!this.generatedFilesMap) { @@ -1897,11 +1900,11 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo return scriptInfo; } - getScriptInfo(uncheckedFileName: string) { + getScriptInfo(uncheckedFileName: string): ts.server.ScriptInfo | undefined { return this.projectService.getScriptInfo(uncheckedFileName); } - filesToString(writeProjectFileNames: boolean) { + filesToString(writeProjectFileNames: boolean): string { return this.filesToStringWorker(writeProjectFileNames, /*writeFileExplaination*/ true, /*writeFileVersionAndText*/ false); } @@ -1923,7 +1926,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo } /** @internal */ - print(writeProjectFileNames: boolean, writeFileExplaination: boolean, writeFileVersionAndText: boolean) { + print(writeProjectFileNames: boolean, writeFileExplaination: boolean, writeFileVersionAndText: boolean): void { this.writeLog(`Project '${this.projectName}' (${ProjectKind[this.projectKind]})`); this.writeLog(this.filesToStringWorker( writeProjectFileNames && this.projectService.logger.hasLevel(LogLevel.verbose), @@ -1937,7 +1940,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo this.noDtsResolutionProject?.print(/*writeProjectFileNames*/ false, /*writeFileExplaination*/ false, /*writeFileVersionAndText*/ false); } - setCompilerOptions(compilerOptions: CompilerOptions) { + setCompilerOptions(compilerOptions: CompilerOptions): void { if (compilerOptions) { compilerOptions.allowNonTsExtensions = true; const oldOptions = this.compilerOptions; @@ -1956,7 +1959,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo } /** @internal */ - setWatchOptions(watchOptions: WatchOptions | undefined) { + setWatchOptions(watchOptions: WatchOptions | undefined): void { this.watchOptions = watchOptions; } @@ -1971,7 +1974,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo } } - getTypeAcquisition() { + getTypeAcquisition(): TypeAcquisition { return this.typeAcquisition || {}; } @@ -2086,12 +2089,12 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo } /** @internal */ - isSourceOfProjectReferenceRedirect(fileName: string) { + isSourceOfProjectReferenceRedirect(fileName: string): boolean { return !!this.program && this.program.isSourceOfProjectReferenceRedirect(fileName); } /** @internal */ - protected getGlobalPluginSearchPaths() { + protected getGlobalPluginSearchPaths(): string[] { // Search any globally-specified probe paths, then our peer node_modules return [ ...this.projectService.pluginProbeLocations, @@ -2130,7 +2133,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo } /** @internal */ - enableProxy(pluginModuleFactory: PluginModuleFactory, configEntry: PluginImport) { + enableProxy(pluginModuleFactory: PluginModuleFactory, configEntry: PluginImport): void { try { if (typeof pluginModuleFactory !== "function") { this.projectService.logger.info(`Skipped loading plugin ${configEntry.name} because it did not expose a proper factory function`); @@ -2165,7 +2168,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo } /** @internal */ - onPluginConfigurationChanged(pluginName: string, configuration: any) { + onPluginConfigurationChanged(pluginName: string, configuration: any): void { this.plugins.filter(plugin => plugin.name === pluginName).forEach(plugin => { if (plugin.module.onConfigurationChanged) { plugin.module.onConfigurationChanged(configuration); @@ -2174,7 +2177,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo } /** Starts a new check for diagnostics. Call this if some file has updated that would cause diagnostics to be changed. */ - refreshDiagnostics() { + refreshDiagnostics(): void { this.projectService.sendProjectsUpdatedInBackgroundEvent(); } @@ -2195,22 +2198,22 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo } /** @internal */ - getPackageJsonCache() { + getPackageJsonCache(): ts.server.PackageJsonCache { return this.projectService.packageJsonCache; } /** @internal */ - getCachedExportInfoMap() { + getCachedExportInfoMap(): ExportInfoMap { return this.exportMapCache ||= createCacheableExportInfoMap(this); } /** @internal */ - clearCachedExportInfoMap() { + clearCachedExportInfoMap(): void { this.exportMapCache?.clear(); } /** @internal */ - getModuleSpecifierCache() { + getModuleSpecifierCache(): ModuleSpecifierCache { return this.moduleSpecifierCache; } @@ -2287,12 +2290,12 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo } /** @internal */ - watchNodeModulesForPackageJsonChanges(directoryPath: string) { + watchNodeModulesForPackageJsonChanges(directoryPath: string): FileWatcher { return this.projectService.watchPackageJsonsInNodeModules(directoryPath, this); } /** @internal */ - getIncompleteCompletionsCache() { + getIncompleteCompletionsCache(): IncompleteCompletionsCache { return this.projectService.getIncompleteCompletionsCache(); } @@ -2310,7 +2313,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo } /** @internal */ - runWithTemporaryFileUpdate(rootFile: string, updatedText: string, cb: (updatedProgram: Program, originalProgram: Program | undefined, updatedFile: SourceFile) => void) { + runWithTemporaryFileUpdate(rootFile: string, updatedText: string, cb: (updatedProgram: Program, originalProgram: Program | undefined, updatedFile: SourceFile) => void): void { const originalProgram = this.program; const rootSourceFile = Debug.checkDefined(this.program?.getSourceFile(rootFile), "Expected file to be part of program"); const originalText = Debug.checkDefined(rootSourceFile.getFullText()); @@ -2384,14 +2387,14 @@ function extractUnresolvedImportsFromSourceFile( export class InferredProject extends Project { private _isJsInferredProject = false; - toggleJsInferredProject(isJsInferredProject: boolean) { + toggleJsInferredProject(isJsInferredProject: boolean): void { if (isJsInferredProject !== this._isJsInferredProject) { this._isJsInferredProject = isJsInferredProject; this.setCompilerOptions(); } } - override setCompilerOptions(options?: CompilerOptions) { + override setCompilerOptions(options?: CompilerOptions): void { // Avoid manipulating the given options directly if (!options && !this.getCompilationSettings()) { return; @@ -2449,7 +2452,7 @@ export class InferredProject extends Project { this.enableGlobalPlugins(this.getCompilerOptions()); } - override addRoot(info: ScriptInfo) { + override addRoot(info: ScriptInfo): void { Debug.assert(info.isScriptOpen()); this.projectService.startWatchingConfigFilesForInferredProjectRoot(info); if (!this._isJsInferredProject && info.isJavaScript()) { @@ -2461,7 +2464,7 @@ export class InferredProject extends Project { super.addRoot(info); } - override removeRoot(info: ScriptInfo) { + override removeRoot(info: ScriptInfo): void { this.projectService.stopWatchingConfigFilesForScriptInfo(info); super.removeRoot(info); // Delay toggling to isJsInferredProject = false till we actually need it again @@ -2473,11 +2476,11 @@ export class InferredProject extends Project { } /** @internal */ - override isOrphan() { + override isOrphan(): boolean { return !this.hasRoots(); } - isProjectWithSingleRoot() { + isProjectWithSingleRoot(): boolean { // - when useSingleInferredProject is not set and projectRootPath is not set, // we can guarantee that this will be the only root // - other wise it has single root if it has single root script info @@ -2485,7 +2488,7 @@ export class InferredProject extends Project { this.getRootScriptInfos().length === 1; } - override close() { + override close(): void { forEach(this.getRootScriptInfos(), info => this.projectService.stopWatchingConfigFilesForScriptInfo(info)); super.close(); } @@ -2731,7 +2734,7 @@ export class AutoImportProviderProject extends Project { } /** @internal */ - isEmpty() { + isEmpty(): boolean { return !some(this.rootFileNames); } @@ -2740,7 +2743,7 @@ export class AutoImportProviderProject extends Project { return true; } - override updateGraph() { + override updateGraph(): boolean { let rootFileNames = this.rootFileNames; if (!rootFileNames) { rootFileNames = AutoImportProviderProject.getRootFileNames( @@ -2767,17 +2770,17 @@ export class AutoImportProviderProject extends Project { return; } - override hasRoots() { + override hasRoots(): boolean { return !!this.rootFileNames?.length; } /** @internal */ - override markAsDirty() { + override markAsDirty(): void { this.rootFileNames = undefined; super.markAsDirty(); } - override getScriptFileNames() { + override getScriptFileNames(): string[] { return this.rootFileNames || ts.emptyArray; } @@ -2799,22 +2802,22 @@ export class AutoImportProviderProject extends Project { throw new Error("AutoImportProviderProject cannot provide its own host; use `hostProject.getModuleResolutionHostForAutomImportProvider()` instead."); } - override getProjectReferences() { + override getProjectReferences(): readonly ProjectReference[] | undefined { return this.hostProject.getProjectReferences(); } /** @internal */ - override includePackageJsonAutoImports() { + override includePackageJsonAutoImports(): PackageJsonAutoImportPreference { return PackageJsonAutoImportPreference.Off; } /** @internal */ - override getSymlinkCache() { + override getSymlinkCache(): SymlinkCache { return this.hostProject.getSymlinkCache(); } /** @internal */ - override getModuleResolutionCache() { + override getModuleResolutionCache(): ModuleResolutionCache | undefined { return this.hostProject.getCurrentProgram()?.getModuleResolutionCache(); } } @@ -2831,7 +2834,7 @@ export class ConfiguredProject extends Project { pendingUpdateReason: string | undefined; /** @internal */ - openFileWatchTriggered = new Map(); + openFileWatchTriggered: Map = new Map(); /** @internal */ canConfigFileJsonReportNoInputFiles = false; @@ -2880,7 +2883,7 @@ export class ConfiguredProject extends Project { } /** @internal */ - setCompilerHost(host: CompilerHost) { + setCompilerHost(host: CompilerHost): void { this.compilerHost = host; } @@ -2890,12 +2893,12 @@ export class ConfiguredProject extends Project { } /** @internal */ - override useSourceOfProjectReferenceRedirect() { + override useSourceOfProjectReferenceRedirect(): boolean { return this.languageServiceEnabled; } /** @internal */ - override getParsedCommandLine(fileName: string) { + override getParsedCommandLine(fileName: string): ParsedCommandLine | undefined { const configFileName = asNormalizedPath(normalizePath(fileName)); const canonicalConfigFilePath = asNormalizedPath(this.projectService.toCanonicalFileName(configFileName)); // Ensure the config file existience info is cached @@ -2913,7 +2916,7 @@ export class ConfiguredProject extends Project { } /** @internal */ - onReleaseParsedCommandLine(fileName: string) { + onReleaseParsedCommandLine(fileName: string): void { this.releaseParsedConfig(asNormalizedPath(this.projectService.toCanonicalFileName(asNormalizedPath(normalizePath(fileName))))); } @@ -2974,7 +2977,7 @@ export class ConfiguredProject extends Project { return this.directoryStructureHost as CachedDirectoryStructureHost; } - getConfigFilePath() { + getConfigFilePath(): ts.server.NormalizedPath { return asNormalizedPath(this.getProjectName()); } @@ -2982,13 +2985,13 @@ export class ConfiguredProject extends Project { return this.projectReferences; } - updateReferences(refs: readonly ProjectReference[] | undefined) { + updateReferences(refs: readonly ProjectReference[] | undefined): void { this.projectReferences = refs; this.potentialProjectReferences = undefined; } /** @internal */ - setPotentialProjectReference(canonicalConfigPath: NormalizedPath) { + setPotentialProjectReference(canonicalConfigPath: NormalizedPath): void { Debug.assert(this.isInitialLoadPending()); (this.potentialProjectReferences || (this.potentialProjectReferences = new Set())).add(canonicalConfigPath); } @@ -3047,11 +3050,11 @@ export class ConfiguredProject extends Project { return this.projectErrors || emptyArray; } - override setProjectErrors(projectErrors: Diagnostic[]) { + override setProjectErrors(projectErrors: Diagnostic[]): void { this.projectErrors = projectErrors; } - override close() { + override close(): void { this.projectService.configFileExistenceInfoCache.forEach((_configFileExistenceInfo, canonicalConfigFilePath) => this.releaseParsedConfig(canonicalConfigFilePath)); this.projectErrors = undefined; this.openFileWatchTriggered.clear(); @@ -3060,13 +3063,13 @@ export class ConfiguredProject extends Project { } /** @internal */ - override markAsDirty() { + override markAsDirty(): void { if (this.deferredClose) return; super.markAsDirty(); } /** @internal */ - isSolution() { + isSolution(): boolean { return this.getRootFilesMap().size === 0 && !this.canConfigFileJsonReportNoInputFiles; } @@ -3076,12 +3079,12 @@ export class ConfiguredProject extends Project { return !!this.deferredClose; } - getEffectiveTypeRoots() { + getEffectiveTypeRoots(): string[] { return getEffectiveTypeRoots(this.getCompilationSettings(), this) || []; } /** @internal */ - updateErrorOnNoInputFiles(fileNames: string[]) { + updateErrorOnNoInputFiles(fileNames: string[]): void { updateErrorForNoInputFiles(fileNames, this.getConfigFilePath(), this.getCompilerOptions().configFile!.configFileSpecs!, this.projectErrors!, this.canConfigFileJsonReportNoInputFiles); } } @@ -3098,13 +3101,13 @@ export class ExternalProject extends Project { this.enableGlobalPlugins(this.getCompilerOptions()); } - override updateGraph() { + override updateGraph(): boolean { const result = super.updateGraph(); this.projectService.sendProjectTelemetry(this); return result; } - override getExcludedFiles() { + override getExcludedFiles(): readonly ts.server.NormalizedPath[] { return this.excludedFiles; } } diff --git a/src/server/scriptInfo.ts b/src/server/scriptInfo.ts index c974871f4d20c..afadbe12d50b7 100644 --- a/src/server/scriptInfo.ts +++ b/src/server/scriptInfo.ts @@ -100,13 +100,13 @@ export class TextStorage { this.version = initialVersion || 0; } - public getVersion() { + public getVersion(): string { return this.svc ? `SVC-${this.version}-${this.svc.getSnapshotVersion()}` : `Text-${this.version}`; } - public hasScriptVersionCache_TestOnly() { + public hasScriptVersionCache_TestOnly(): boolean { return this.svc !== undefined; } @@ -120,7 +120,7 @@ export class TextStorage { } /** Public for testing */ - public useText(newText: string) { + public useText(newText: string): void { this.svc = undefined; this.text = newText; this.textSnapshot = undefined; @@ -130,7 +130,7 @@ export class TextStorage { this.version++; } - public edit(start: number, end: number, newText: string) { + public edit(start: number, end: number, newText: string): void { this.switchToScriptVersionCache().edit(start, end - start, newText); this.ownFileText = false; this.text = undefined; @@ -174,7 +174,7 @@ export class TextStorage { * Reads the contents from tempFile(if supplied) or own file and sets it as contents * returns true if text changed */ - public reloadWithFileText(tempFileName?: string) { + public reloadWithFileText(tempFileName?: string): boolean { const { text: newText, fileSize } = tempFileName || !this.info.isDynamicOrHasMixedContent() ? this.getFileTextAndSize(tempFileName) : { text: "", fileSize: undefined }; @@ -196,13 +196,13 @@ export class TextStorage { * Schedule reload from the disk if its not already scheduled and its not own text * returns true when scheduling reload */ - public scheduleReloadIfNeeded() { + public scheduleReloadIfNeeded(): boolean { return !this.pendingReloadFromDisk && !this.ownFileText ? this.pendingReloadFromDisk = true : false; } - public delayReloadFromFileIntoText() { + public delayReloadFromFileIntoText(): void { this.pendingReloadFromDisk = true; } @@ -345,7 +345,7 @@ export class TextStorage { } } -export function isDynamicFileName(fileName: NormalizedPath) { +export function isDynamicFileName(fileName: NormalizedPath): boolean { return fileName[0] === "^" || ((fileName.includes("walkThroughSnippet:/") || fileName.includes("untitled:/")) && getBaseFileName(fileName)[0] === "^") || @@ -428,15 +428,15 @@ export class ScriptInfo { } /** @internal */ - public isDynamicOrHasMixedContent() { + public isDynamicOrHasMixedContent(): boolean { return this.hasMixedContent || this.isDynamic; } - public isScriptOpen() { + public isScriptOpen(): boolean { return this.textStorage.isOpen; } - public open(newText: string | undefined) { + public open(newText: string | undefined): void { this.textStorage.isOpen = true; if ( newText !== undefined && @@ -447,14 +447,14 @@ export class ScriptInfo { } } - public close(fileExists = true) { + public close(fileExists = true): void { this.textStorage.isOpen = false; if (fileExists && this.textStorage.scheduleReloadIfNeeded()) { this.markContainingProjectsAsDirty(); } } - public getSnapshot() { + public getSnapshot(): IScriptSnapshot { return this.textStorage.getSnapshot(); } @@ -510,7 +510,7 @@ export class ScriptInfo { return isNew; } - isAttached(project: Project) { + isAttached(project: Project): boolean { // unrolled for common cases switch (this.containingProjects.length) { case 0: @@ -524,7 +524,7 @@ export class ScriptInfo { } } - detachFromProject(project: Project) { + detachFromProject(project: Project): void { // unrolled for common cases switch (this.containingProjects.length) { case 0: @@ -554,7 +554,7 @@ export class ScriptInfo { } } - detachAllProjects() { + detachAllProjects(): void { for (const p of this.containingProjects) { if (isConfiguredProject(p)) { p.getCachedDirectoryStructureHost().addOrDeleteFile(this.fileName, this.path, FileWatcherEventKind.Deleted); @@ -572,7 +572,7 @@ export class ScriptInfo { clear(this.containingProjects); } - getDefaultProject() { + getDefaultProject(): Project { switch (this.containingProjects.length) { case 0: return Errors.ThrowNoProject(); @@ -654,18 +654,18 @@ export class ScriptInfo { return this.textStorage.getVersion(); } - saveTo(fileName: string) { + saveTo(fileName: string): void { this.host.writeFile(fileName, getSnapshotText(this.textStorage.getSnapshot())); } /** @internal */ - delayReloadNonMixedContentFile() { + delayReloadNonMixedContentFile(): void { Debug.assert(!this.isDynamicOrHasMixedContent()); this.textStorage.delayReloadFromFileIntoText(); this.markContainingProjectsAsDirty(); } - reloadFromFile(tempFileName?: NormalizedPath) { + reloadFromFile(tempFileName?: NormalizedPath): boolean { if (this.textStorage.reloadWithFileText(tempFileName)) { this.markContainingProjectsAsDirty(); return true; @@ -678,18 +678,18 @@ export class ScriptInfo { this.markContainingProjectsAsDirty(); } - markContainingProjectsAsDirty() { + markContainingProjectsAsDirty(): void { for (const p of this.containingProjects) { p.markFileAsDirty(this.path); } } - isOrphan() { + isOrphan(): boolean { return this.deferredDelete || !forEach(this.containingProjects, p => !p.isOrphan()); } /** @internal */ - isContainedByBackgroundProject() { + isContainedByBackgroundProject(): boolean { return some( this.containingProjects, isBackgroundProject, @@ -699,7 +699,7 @@ export class ScriptInfo { /** * @param line 1 based index */ - lineToTextSpan(line: number) { + lineToTextSpan(line: number): TextSpan { return this.textStorage.lineToTextSpan(line); } @@ -721,12 +721,12 @@ export class ScriptInfo { return location; } - public isJavaScript() { + public isJavaScript(): boolean { return this.scriptKind === ScriptKind.JS || this.scriptKind === ScriptKind.JSX; } /** @internal */ - closeSourceMapFileWatcher() { + closeSourceMapFileWatcher(): void { if (this.sourceMapFilePath && !isString(this.sourceMapFilePath)) { closeFileWatcherOf(this.sourceMapFilePath); this.sourceMapFilePath = undefined; diff --git a/src/server/scriptVersionCache.ts b/src/server/scriptVersionCache.ts index 306e310f23ee3..55a957928a1ae 100644 --- a/src/server/scriptVersionCache.ts +++ b/src/server/scriptVersionCache.ts @@ -287,7 +287,7 @@ export class ScriptVersionCache { } // REVIEW: can optimize by coalescing simple edits - edit(pos: number, deleteLen: number, insertedText?: string) { + edit(pos: number, deleteLen: number, insertedText?: string): void { this.changes.push(new TextChange(pos, deleteLen, insertedText)); if ( this.changes.length > ScriptVersionCache.changeNumberThreshold || @@ -345,7 +345,7 @@ export class ScriptVersionCache { return createTextSpan(absolutePosition, len); } - getTextChangesBetweenVersions(oldVersion: number, newVersion: number) { + getTextChangesBetweenVersions(oldVersion: number, newVersion: number): TextChangeRange | undefined { if (oldVersion < newVersion) { if (oldVersion >= this.minVersion) { const textChangeRanges: TextChangeRange[] = []; @@ -366,11 +366,11 @@ export class ScriptVersionCache { } } - getLineCount() { + getLineCount(): number { return this._getSnapshot().index.getLineCount(); } - static fromString(script: string) { + static fromString(script: string): ScriptVersionCache { const svc = new ScriptVersionCache(); const snap = new LineIndexSnapshot(0, svc, new LineIndex()); svc.versions[svc.currentVersion] = snap; @@ -423,7 +423,7 @@ export class LineIndex { return this.root.charOffsetToLineInfo(1, position); } - getLineCount() { + getLineCount(): number { return this.root.lineCount(); } @@ -438,7 +438,7 @@ export class LineIndex { } } - load(lines: string[]) { + load(lines: string[]): void { if (lines.length > 0) { const leaves: LineLeaf[] = []; for (let i = 0; i < lines.length; i++) { @@ -451,11 +451,11 @@ export class LineIndex { } } - walk(rangeStart: number, rangeLength: number, walkFns: LineIndexWalker) { + walk(rangeStart: number, rangeLength: number, walkFns: LineIndexWalker): void { this.root.walk(rangeStart, rangeLength, walkFns); } - getText(rangeStart: number, rangeLength: number) { + getText(rangeStart: number, rangeLength: number): string { let accum = ""; if ((rangeLength > 0) && (rangeStart < this.root.charCount())) { this.walk(rangeStart, rangeLength, { @@ -473,7 +473,7 @@ export class LineIndex { return this.root.charCount(); } - every(f: (ll: LineLeaf, s: number, len: number) => boolean, rangeStart: number, rangeEnd?: number) { + every(f: (ll: LineLeaf, s: number, len: number) => boolean, rangeStart: number, rangeEnd?: number): boolean { if (!rangeEnd) { rangeEnd = this.root.charCount(); } @@ -559,7 +559,10 @@ export class LineIndex { return this.buildTreeFromBottom(interiorNodes); } - static linesFromText(text: string) { + static linesFromText(text: string): { + lines: string[]; + lineMap: number[]; + } { const lineMap = computeLineStarts(text); if (lineMap.length === 0) { @@ -595,7 +598,7 @@ export class LineNode implements LineCollection { return false; } - updateCounts() { + updateCounts(): void { this.totalChars = 0; this.totalLines = 0; for (const child of this.children) { @@ -627,7 +630,7 @@ export class LineNode implements LineCollection { } } - walk(rangeStart: number, rangeLength: number, walkFns: LineIndexWalker) { + walk(rangeStart: number, rangeLength: number, walkFns: LineIndexWalker): void { // assume (rangeStart < this.totalChars) && (rangeLength <= this.totalChars) let childIndex = 0; let childCharCount = this.children[childIndex].charCount(); @@ -748,7 +751,7 @@ export class LineNode implements LineCollection { return splitNode; } - remove(child: LineCollection) { + remove(child: LineCollection): void { const childIndex = this.findChildIndex(child); const clen = this.children.length; if (childIndex < (clen - 1)) { @@ -765,7 +768,7 @@ export class LineNode implements LineCollection { return childIndex; } - insertAt(child: LineCollection, nodes: LineCollection[]) { + insertAt(child: LineCollection, nodes: LineCollection[]): LineNode[] { let childIndex = this.findChildIndex(child); const clen = this.children.length; const nodeCount = nodes.length; @@ -825,11 +828,11 @@ export class LineNode implements LineCollection { Debug.assert(this.children.length <= lineCollectionCapacity); } - charCount() { + charCount(): number { return this.totalChars; } - lineCount() { + lineCount(): number { return this.totalLines; } } @@ -843,11 +846,11 @@ export class LineLeaf implements LineCollection { return true; } - walk(rangeStart: number, rangeLength: number, walkFns: LineIndexWalker) { + walk(rangeStart: number, rangeLength: number, walkFns: LineIndexWalker): void { walkFns.leaf(rangeStart, rangeLength, this); } - charCount() { + charCount(): number { return this.text.length; } diff --git a/src/server/session.ts b/src/server/session.ts index fd0ed26586dc7..039c9d4238b7e 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -316,7 +316,7 @@ function allEditsBeforePos(edits: readonly TextChange[], pos: number): boolean { /** @deprecated use ts.server.protocol.CommandTypes */ export type CommandNames = protocol.CommandTypes; /** @deprecated use ts.server.protocol.CommandTypes */ -export const CommandNames = (protocol as any).CommandTypes; +export const CommandNames: CommandNames = (protocol as any).CommandTypes; export function formatMessage(msg: T, logger: Logger, byteLength: (s: string, encoding: BufferEncoding) => number, newLine: string): string { const verboseLogging = logger.hasLevel(LogLevel.verbose); @@ -1227,7 +1227,7 @@ export class Session implements EventSender { this.logger.msg(msg, Msg.Err); } - public send(msg: protocol.Message) { + public send(msg: protocol.Message): void { if (msg.type === "event" && !this.canUseEvents) { if (this.logger.hasLevel(LogLevel.verbose)) { this.logger.info(`Session does not support events: ignored event: ${stringifyIndented(msg)}`); @@ -1237,7 +1237,7 @@ export class Session implements EventSender { this.writeMessage(msg); } - protected writeMessage(msg: protocol.Message) { + protected writeMessage(msg: protocol.Message): void { const msgText = formatMessage(msg, this.logger, this.byteLength, this.host.newLine); this.host.write(msgText); } @@ -3289,12 +3289,12 @@ export class Session implements EventSender { return outgoingCalls.map(call => this.toProtocolCallHierarchyOutgoingCall(call, scriptInfo)); } - getCanonicalFileName(fileName: string) { + getCanonicalFileName(fileName: string): string { const name = this.host.useCaseSensitiveFileNames ? fileName : toFileNameLowerCase(fileName); return normalizePath(name); } - exit() {/*overridden*/} + exit(): void {/*overridden*/} private notRequired(request: protocol.Request | undefined): HandlerResponse { if (request) this.doOutput(/*info*/ undefined, request.command, request.seq, /*success*/ true, this.performanceData); @@ -3710,7 +3710,7 @@ export class Session implements EventSender { }, })); - public addProtocolHandler(command: string, handler: (request: protocol.Request) => HandlerResponse) { + public addProtocolHandler(command: string, handler: (request: protocol.Request) => HandlerResponse): void { if (this.handlers.has(command)) { throw new Error(`Protocol handler already exists for command "${command}"`); } @@ -3759,7 +3759,7 @@ export class Session implements EventSender { } } - public onMessage(message: TMessage) { + public onMessage(message: TMessage): void { this.gcTimer.scheduleCollect(); let start: [number, number] | undefined; const currentPerformanceData = this.performanceData; diff --git a/src/server/tsconfig.json b/src/server/tsconfig.json index 22a1de22f93b9..6011bf7acc184 100644 --- a/src/server/tsconfig.json +++ b/src/server/tsconfig.json @@ -3,7 +3,8 @@ "compilerOptions": { "types": [ "node" - ] + ], + "isolatedDeclarations": true }, "references": [ { "path": "../compiler" }, diff --git a/src/server/typingInstallerAdapter.ts b/src/server/typingInstallerAdapter.ts index 5f8e90b7f837d..f92b6bf2a8405 100644 --- a/src/server/typingInstallerAdapter.ts +++ b/src/server/typingInstallerAdapter.ts @@ -104,7 +104,7 @@ export abstract class TypingsInstallerAdapter implements ITypingsInstaller { return promise; } - attach(projectService: ProjectService) { + attach(projectService: ProjectService): void { this.projectService = projectService; this.installer = this.createInstallerProcess(); } @@ -131,7 +131,7 @@ export abstract class TypingsInstallerAdapter implements ITypingsInstaller { } } - handleMessage(response: TypesRegistryResponse | PackageInstalledResponse | SetTypings | InvalidateCachedTypings | BeginInstallTypes | EndInstallTypes | InitializationFailedResponse | server.WatchTypingLocations) { + handleMessage(response: TypesRegistryResponse | PackageInstalledResponse | SetTypings | InvalidateCachedTypings | BeginInstallTypes | EndInstallTypes | InitializationFailedResponse | server.WatchTypingLocations): void { if (this.logger.hasLevel(LogLevel.verbose)) { this.logger.info(`TIAdapter:: Received response:${stringifyIndented(response)}`); } @@ -234,7 +234,7 @@ export abstract class TypingsInstallerAdapter implements ITypingsInstaller { } } - scheduleRequest(request: DiscoverTypings) { + scheduleRequest(request: DiscoverTypings): void { if (this.logger.hasLevel(LogLevel.verbose)) { this.logger.info(`TIAdapter:: Scheduling request for: ${request.projectName}`); } diff --git a/src/server/utilities.ts b/src/server/utilities.ts index 5ea8cd876f3e7..5466d4c448d28 100644 --- a/src/server/utilities.ts +++ b/src/server/utilities.ts @@ -20,7 +20,7 @@ export class ThrottledOperations { * of the new one. (Note that the amount of time the canceled operation had been * waiting does not affect the amount of time that the new operation waits.) */ - public schedule(operationId: string, delay: number, cb: () => void) { + public schedule(operationId: string, delay: number, cb: () => void): void { const pendingTimeout = this.pendingTimeouts.get(operationId); if (pendingTimeout) { // another operation was already scheduled for this id - cancel it @@ -33,7 +33,7 @@ export class ThrottledOperations { } } - public cancel(operationId: string) { + public cancel(operationId: string): boolean { const pendingTimeout = this.pendingTimeouts.get(operationId); if (!pendingTimeout) return false; this.host.clearTimeout(pendingTimeout); @@ -55,7 +55,7 @@ export class GcTimer { constructor(private readonly host: ServerHost, private readonly delay: number, private readonly logger: Logger) { } - public scheduleCollect() { + public scheduleCollect(): void { if (!this.host.gc || this.timerId !== undefined) { // no global.gc or collection was already scheduled - skip this request return; diff --git a/src/server/utilitiesPublic.ts b/src/server/utilitiesPublic.ts index c0ce5dfea1295..2476292715de0 100644 --- a/src/server/utilitiesPublic.ts +++ b/src/server/utilitiesPublic.ts @@ -117,7 +117,7 @@ export interface ProjectOptions { configHasExcludeProperty: boolean; } -export function isInferredProjectName(name: string) { +export function isInferredProjectName(name: string): boolean { // POSIX defines /dev/null as a device - there should be no file with this prefix return /dev\/null\/inferredProject\d+\*/.test(name); } diff --git a/src/services/breakpoints.ts b/src/services/breakpoints.ts index 17d20da69ee92..b3e53fed929b5 100644 --- a/src/services/breakpoints.ts +++ b/src/services/breakpoints.ts @@ -77,7 +77,7 @@ import { * * @internal */ -export function spanInSourceFileAtLocation(sourceFile: SourceFile, position: number) { +export function spanInSourceFileAtLocation(sourceFile: SourceFile, position: number): TextSpan | undefined { // Cannot set breakpoint in dts file if (sourceFile.isDeclarationFile) { return undefined; diff --git a/src/services/codeFixProvider.ts b/src/services/codeFixProvider.ts index 686a96dea6c8e..7dbf939b4da05 100644 --- a/src/services/codeFixProvider.ts +++ b/src/services/codeFixProvider.ts @@ -29,7 +29,7 @@ const errorCodeToFixes = createMultiMap(); const fixIdToRegistration = new Map(); /** @internal */ -export function createCodeFixActionWithoutFixAll(fixName: string, changes: FileTextChanges[], description: DiagnosticOrDiagnosticAndArguments) { +export function createCodeFixActionWithoutFixAll(fixName: string, changes: FileTextChanges[], description: DiagnosticOrDiagnosticAndArguments): CodeFixAction { return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, /*fixId*/ undefined, /*fixAllDescription*/ undefined); } @@ -39,7 +39,7 @@ export function createCodeFixAction(fixName: string, changes: FileTextChanges[], } /** @internal */ -export function createCodeFixActionMaybeFixAll(fixName: string, changes: FileTextChanges[], description: DiagnosticOrDiagnosticAndArguments, fixId?: {}, fixAllDescription?: DiagnosticOrDiagnosticAndArguments, command?: CodeActionCommand) { +export function createCodeFixActionMaybeFixAll(fixName: string, changes: FileTextChanges[], description: DiagnosticOrDiagnosticAndArguments, fixId?: {}, fixAllDescription?: DiagnosticOrDiagnosticAndArguments, command?: CodeActionCommand): CodeFixAction { return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, fixId, fixAllDescription && diagnosticToString(fixAllDescription), command); } @@ -48,7 +48,7 @@ function createCodeFixActionWorker(fixName: string, description: string, changes } /** @internal */ -export function registerCodeFix(reg: CodeFixRegistration) { +export function registerCodeFix(reg: CodeFixRegistration): void { for (const error of reg.errorCodes) { errorCodeToFixesArray = undefined; errorCodeToFixes.add(String(error), reg); diff --git a/src/services/codefixes/helpers.ts b/src/services/codefixes/helpers.ts index 656f3dce112b7..553d5a32d3e1f 100644 --- a/src/services/codefixes/helpers.ts +++ b/src/services/codefixes/helpers.ts @@ -180,7 +180,7 @@ export function addNewNodeForMemberSymbol( importAdder: ImportAdder | undefined, addClassElement: (node: AddNode) => void, body: Block | undefined, - preserveOptional = PreserveOptionalFlags.All, + preserveOptional: PreserveOptionalFlags = PreserveOptionalFlags.All, isAmbient = false, ): void { const declarations = symbol.getDeclarations(); @@ -387,7 +387,7 @@ export function createSignatureDeclarationFromSignature( optional: boolean | undefined, enclosingDeclaration: Node | undefined, importAdder: ImportAdder | undefined, -) { +): FunctionDeclaration | MethodDeclaration | FunctionExpression | ArrowFunction | undefined { const program = context.program; const checker = program.getTypeChecker(); const scriptTarget = getEmitScriptTarget(program.getCompilerOptions()); @@ -850,7 +850,7 @@ export function setJsonCompilerOptionValues( changeTracker: textChanges.ChangeTracker, configFile: TsConfigSourceFile, options: [string, Expression][], -) { +): undefined { const tsconfigObjectLiteral = getTsConfigObjectLiteralExpression(configFile); if (!tsconfigObjectLiteral) return undefined; @@ -889,7 +889,7 @@ export function setJsonCompilerOptionValue( configFile: TsConfigSourceFile, optionName: string, optionValue: Expression, -) { +): void { setJsonCompilerOptionValues(changeTracker, configFile, [[optionName, optionValue]]); } @@ -908,7 +908,10 @@ function findJsonProperty(obj: ObjectLiteralExpression, name: string): PropertyA * * @internal */ -export function tryGetAutoImportableReferenceFromTypeNode(importTypeNode: TypeNode | undefined, scriptTarget: ScriptTarget) { +export function tryGetAutoImportableReferenceFromTypeNode(importTypeNode: TypeNode | undefined, scriptTarget: ScriptTarget): { + typeNode: TypeNode; + symbols: Symbol[]; +} | undefined { let symbols: Symbol[] | undefined; const typeNode = visitNode(importTypeNode, visit, isTypeNode); if (symbols && typeNode) { @@ -946,7 +949,7 @@ function replaceFirstIdentifierOfEntityName(name: EntityName, newIdentifier: Ide } /** @internal */ -export function importSymbols(importAdder: ImportAdder, symbols: readonly Symbol[]) { +export function importSymbols(importAdder: ImportAdder, symbols: readonly Symbol[]): void { symbols.forEach(s => importAdder.addImportFromExportedSymbol(s, /*isValidTypeOnlyUseSite*/ true)); } diff --git a/src/services/codefixes/importFixes.ts b/src/services/codefixes/importFixes.ts index 063ed6946eee4..05fb237ac7682 100644 --- a/src/services/codefixes/importFixes.ts +++ b/src/services/codefixes/importFixes.ts @@ -842,7 +842,7 @@ export function getImportCompletionAction( } /** @internal */ -export function getPromoteTypeOnlyCompletionAction(sourceFile: SourceFile, symbolToken: Identifier, program: Program, host: LanguageServiceHost, formatContext: formatting.FormatContext, preferences: UserPreferences) { +export function getPromoteTypeOnlyCompletionAction(sourceFile: SourceFile, symbolToken: Identifier, program: Program, host: LanguageServiceHost, formatContext: formatting.FormatContext, preferences: UserPreferences): CodeAction | undefined { const compilerOptions = program.getCompilerOptions(); const symbolName = single(getSymbolNamesToImport(sourceFile, program.getTypeChecker(), symbolToken, compilerOptions)); const fix = getTypeOnlyPromotionFix(sourceFile, symbolToken, symbolName, program); diff --git a/src/services/exportInfoMap.ts b/src/services/exportInfoMap.ts index 821e855e76a36..fba4fcc446ceb 100644 --- a/src/services/exportInfoMap.ts +++ b/src/services/exportInfoMap.ts @@ -442,7 +442,7 @@ export function forEachExternalModuleToImportFrom( preferences: UserPreferences, useAutoImportProvider: boolean, cb: (module: Symbol, moduleFile: SourceFile | undefined, program: Program, isFromPackageJson: boolean) => void, -) { +): void { const useCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames(host); const excludePatterns = preferences.autoImportFileExcludePatterns && getIsExcludedPatterns(preferences, useCaseSensitiveFileNames); @@ -507,7 +507,7 @@ function getIsExcluded(excludePatterns: readonly RegExp[], host: LanguageService } /** @internal */ -export function getIsFileExcluded(host: LanguageServiceHost, preferences: UserPreferences) { +export function getIsFileExcluded(host: LanguageServiceHost, preferences: UserPreferences): ({ fileName, path }: SourceFile) => boolean { if (!preferences.autoImportFileExcludePatterns) return () => false; return getIsExcluded(getIsExcludedPatterns(preferences, hostUsesCaseSensitiveFileNames(host)), host); } @@ -579,7 +579,10 @@ export function getExportInfoMap(importingFile: SourceFile | FutureSourceFile, h } /** @internal */ -export function getDefaultLikeExportInfo(moduleSymbol: Symbol, checker: TypeChecker) { +export function getDefaultLikeExportInfo(moduleSymbol: Symbol, checker: TypeChecker): { + symbol: Symbol; + exportKind: ExportKind; +} | undefined { const exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol); if (exportEquals !== moduleSymbol) return { symbol: exportEquals, exportKind: ExportKind.ExportEquals }; const defaultExport = checker.tryGetMemberInModuleExports(InternalSymbolName.Default, moduleSymbol); diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index 6e11dac1419fd..74aeb9c5be05c 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -1051,7 +1051,7 @@ export namespace Core { return mergeReferences(program, moduleReferences, references, moduleReferencesOfExportTarget); } - export function getAdjustedNode(node: Node, options: Options) { + export function getAdjustedNode(node: Node, options: Options): Node { if (options.use === FindReferencesUse.References) { node = getAdjustedReferenceLocation(node); } diff --git a/src/services/formatting/formatting.ts b/src/services/formatting/formatting.ts index 2dc19c021e302..e641b0f2b0434 100644 --- a/src/services/formatting/formatting.ts +++ b/src/services/formatting/formatting.ts @@ -1377,7 +1377,7 @@ export function getRangeOfEnclosingComment( sourceFile: SourceFile, position: number, precedingToken?: Node | null, // eslint-disable-line no-restricted-syntax - tokenAtPosition = getTokenAtPosition(sourceFile, position), + tokenAtPosition: Node = getTokenAtPosition(sourceFile, position), ): CommentRange | undefined { const jsdoc = findAncestor(tokenAtPosition, isJSDoc); if (jsdoc) tokenAtPosition = jsdoc.parent; diff --git a/src/services/formatting/formattingContext.ts b/src/services/formatting/formattingContext.ts index f41b7ee0ca283..ff73e9c578241 100644 --- a/src/services/formatting/formattingContext.ts +++ b/src/services/formatting/formattingContext.ts @@ -35,7 +35,7 @@ export class FormattingContext { constructor(public readonly sourceFile: SourceFileLike, public formattingRequestKind: FormattingRequestKind, public options: FormatCodeSettings) { } - public updateContext(currentRange: TextRangeWithKind, currentTokenParent: Node, nextRange: TextRangeWithKind, nextTokenParent: Node, commonParent: Node) { + public updateContext(currentRange: TextRangeWithKind, currentTokenParent: Node, nextRange: TextRangeWithKind, nextTokenParent: Node, commonParent: Node): void { this.currentTokenSpan = Debug.checkDefined(currentRange); this.currentTokenParent = Debug.checkDefined(currentTokenParent); this.nextTokenSpan = Debug.checkDefined(nextRange); @@ -76,7 +76,7 @@ export class FormattingContext { return this.tokensAreOnSameLine; } - public ContextNodeBlockIsOnOneLine() { + public ContextNodeBlockIsOnOneLine(): boolean { if (this.contextNodeBlockIsOnOneLine === undefined) { this.contextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.contextNode); } @@ -84,7 +84,7 @@ export class FormattingContext { return this.contextNodeBlockIsOnOneLine; } - public NextNodeBlockIsOnOneLine() { + public NextNodeBlockIsOnOneLine(): boolean { if (this.nextNodeBlockIsOnOneLine === undefined) { this.nextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.nextTokenParent); } diff --git a/src/services/formatting/smartIndenter.ts b/src/services/formatting/smartIndenter.ts index c2141602f1108..c6ed975a1a516 100644 --- a/src/services/formatting/smartIndenter.ts +++ b/src/services/formatting/smartIndenter.ts @@ -233,7 +233,7 @@ export namespace SmartIndenter { return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, /*indentationDelta*/ 0, sourceFile, /*isNextChild*/ false, options); } - export function getBaseIndentation(options: EditorSettings) { + export function getBaseIndentation(options: EditorSettings): number { return options.baseIndentSize || 0; } @@ -602,7 +602,10 @@ export namespace SmartIndenter { * value of 'character' for '$' is 3 * value of 'column' for '$' is 6 (assuming that tab size is 4) */ - export function findFirstNonWhitespaceCharacterAndColumn(startPos: number, endPos: number, sourceFile: SourceFileLike, options: EditorSettings) { + export function findFirstNonWhitespaceCharacterAndColumn(startPos: number, endPos: number, sourceFile: SourceFileLike, options: EditorSettings): { + column: number; + character: number; + } { let character = 0; let column = 0; for (let pos = startPos; pos < endPos; pos++) { diff --git a/src/services/jsDoc.ts b/src/services/jsDoc.ts index cbefd89bf8403..0f8cb859d6822 100644 --- a/src/services/jsDoc.ts +++ b/src/services/jsDoc.ts @@ -383,7 +383,7 @@ export function getJSDocTagNameCompletions(): CompletionEntry[] { } /** @internal */ -export const getJSDocTagNameCompletionDetails = getJSDocTagCompletionDetails; +export const getJSDocTagNameCompletionDetails: typeof getJSDocTagCompletionDetails = getJSDocTagCompletionDetails; /** @internal */ export function getJSDocTagCompletions(): CompletionEntry[] { diff --git a/src/services/organizeImports.ts b/src/services/organizeImports.ts index e7cc236947c84..1508ba7672d5e 100644 --- a/src/services/organizeImports.ts +++ b/src/services/organizeImports.ts @@ -914,19 +914,19 @@ export function getNamedImportSpecifierComparerWithDetection(importDecl: ImportD } /** @internal */ -export function getImportDeclarationInsertionIndex(sortedImports: readonly AnyImportOrRequireStatement[], newImport: AnyImportOrRequireStatement, comparer: Comparer) { +export function getImportDeclarationInsertionIndex(sortedImports: readonly AnyImportOrRequireStatement[], newImport: AnyImportOrRequireStatement, comparer: Comparer): number { const index = binarySearch(sortedImports, newImport, identity, (a, b) => compareImportsOrRequireStatements(a, b, comparer)); return index < 0 ? ~index : index; } /** @internal */ -export function getImportSpecifierInsertionIndex(sortedImports: readonly ImportSpecifier[], newImport: ImportSpecifier, comparer: Comparer) { +export function getImportSpecifierInsertionIndex(sortedImports: readonly ImportSpecifier[], newImport: ImportSpecifier, comparer: Comparer): number { const index = binarySearch(sortedImports, newImport, identity, comparer); return index < 0 ? ~index : index; } /** @internal */ -export function compareImportsOrRequireStatements(s1: AnyImportOrRequireStatement, s2: AnyImportOrRequireStatement, comparer: Comparer) { +export function compareImportsOrRequireStatements(s1: AnyImportOrRequireStatement, s2: AnyImportOrRequireStatement, comparer: Comparer): Comparison { return compareModuleSpecifiersWorker(getModuleSpecifierExpression(s1), getModuleSpecifierExpression(s2), comparer) || compareImportKind(s1, s2); } @@ -950,7 +950,7 @@ export function testCoalesceImports(importGroup: readonly ImportDeclaration[], i * @deprecated Only used for testing * @internal */ -export function testCoalesceExports(exportGroup: readonly ExportDeclaration[], ignoreCase: boolean, preferences?: UserPreferences) { +export function testCoalesceExports(exportGroup: readonly ExportDeclaration[], ignoreCase: boolean, preferences?: UserPreferences): readonly ExportDeclaration[] { const comparer = (s1: ExportSpecifier, s2: ExportSpecifier) => compareImportOrExportSpecifiers(s1, s2, getOrganizeImportsOrdinalStringComparer(ignoreCase), { organizeImportsTypeOrder: preferences?.organizeImportsTypeOrder ?? "last" }); return coalesceExportsWorker(exportGroup, comparer); } @@ -959,7 +959,7 @@ export function testCoalesceExports(exportGroup: readonly ExportDeclaration[], i * @deprecated Only used for testing * @internal */ -export function compareModuleSpecifiers(m1: Expression | undefined, m2: Expression | undefined, ignoreCase?: boolean) { +export function compareModuleSpecifiers(m1: Expression | undefined, m2: Expression | undefined, ignoreCase?: boolean): Comparison { const comparer = getOrganizeImportsOrdinalStringComparer(!!ignoreCase); return compareModuleSpecifiersWorker(m1, m2, comparer); } diff --git a/src/services/refactorProvider.ts b/src/services/refactorProvider.ts index 1b21149070931..b341d18124404 100644 --- a/src/services/refactorProvider.ts +++ b/src/services/refactorProvider.ts @@ -18,7 +18,7 @@ const refactors = new Map(); * * @internal */ -export function registerRefactor(name: string, refactor: Refactor) { +export function registerRefactor(name: string, refactor: Refactor): void { refactors.set(name, refactor); } diff --git a/src/services/refactors/convertImport.ts b/src/services/refactors/convertImport.ts index b0071598b3bb7..1b21d2d5beb02 100644 --- a/src/services/refactors/convertImport.ts +++ b/src/services/refactors/convertImport.ts @@ -210,7 +210,7 @@ function getLeftOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName: P } /** @internal */ -export function doChangeNamedToNamespaceOrDefault(sourceFile: SourceFile, program: Program, changes: textChanges.ChangeTracker, toConvert: NamedImports, shouldUseDefault = getShouldUseDefault(program, toConvert.parent)): void { +export function doChangeNamedToNamespaceOrDefault(sourceFile: SourceFile, program: Program, changes: textChanges.ChangeTracker, toConvert: NamedImports, shouldUseDefault: boolean = getShouldUseDefault(program, toConvert.parent)): void { const checker = program.getTypeChecker(); const importDecl = toConvert.parent.parent; const { moduleSpecifier } = importDecl; diff --git a/src/services/refactors/extractSymbol.ts b/src/services/refactors/extractSymbol.ts index 423922f691323..2d59e42c433d6 100644 --- a/src/services/refactors/extractSymbol.ts +++ b/src/services/refactors/extractSymbol.ts @@ -387,17 +387,17 @@ export namespace Messages { export const cannotExtractRangeContainingConditionalReturnStatement: DiagnosticMessage = createMessage("Cannot extract range containing conditional return statement."); export const cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange: DiagnosticMessage = createMessage("Cannot extract range containing labeled break or continue with target outside of the range."); export const cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators: DiagnosticMessage = createMessage("Cannot extract range containing writes to references located outside of the target range in generators."); - export const typeWillNotBeVisibleInTheNewScope = createMessage("Type will not visible in the new scope."); - export const functionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope."); - export const cannotExtractIdentifier = createMessage("Select more than a single identifier."); - export const cannotExtractExportedEntity = createMessage("Cannot extract exported declaration"); - export const cannotWriteInExpression = createMessage("Cannot write back side-effects when extracting an expression"); - export const cannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor"); - export const cannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts"); - export const cannotAccessVariablesFromNestedScopes = createMessage("Cannot access variables from nested scopes"); - export const cannotExtractToJSClass = createMessage("Cannot extract constant to a class scope in JS"); - export const cannotExtractToExpressionArrowFunction = createMessage("Cannot extract constant to an arrow function without a block"); - export const cannotExtractFunctionsContainingThisToMethod = createMessage("Cannot extract functions containing this to method"); + export const typeWillNotBeVisibleInTheNewScope: DiagnosticMessage = createMessage("Type will not visible in the new scope."); + export const functionWillNotBeVisibleInTheNewScope: DiagnosticMessage = createMessage("Function will not visible in the new scope."); + export const cannotExtractIdentifier: DiagnosticMessage = createMessage("Select more than a single identifier."); + export const cannotExtractExportedEntity: DiagnosticMessage = createMessage("Cannot extract exported declaration"); + export const cannotWriteInExpression: DiagnosticMessage = createMessage("Cannot write back side-effects when extracting an expression"); + export const cannotExtractReadonlyPropertyInitializerOutsideConstructor: DiagnosticMessage = createMessage("Cannot move initialization of read-only class property outside of the constructor"); + export const cannotExtractAmbientBlock: DiagnosticMessage = createMessage("Cannot extract code from ambient contexts"); + export const cannotAccessVariablesFromNestedScopes: DiagnosticMessage = createMessage("Cannot access variables from nested scopes"); + export const cannotExtractToJSClass: DiagnosticMessage = createMessage("Cannot extract constant to a class scope in JS"); + export const cannotExtractToExpressionArrowFunction: DiagnosticMessage = createMessage("Cannot extract constant to an arrow function without a block"); + export const cannotExtractFunctionsContainingThisToMethod: DiagnosticMessage = createMessage("Cannot extract functions containing this to method"); } /** @internal */ diff --git a/src/services/refactors/helpers.ts b/src/services/refactors/helpers.ts index 459979c3ef0dc..38fc8b965f4b9 100644 --- a/src/services/refactors/helpers.ts +++ b/src/services/refactors/helpers.ts @@ -55,7 +55,7 @@ export function refactorKindBeginsWith(known: string, requested: string | undefi * * @internal */ -export function getIdentifierForNode(node: Node, scope: FunctionLikeDeclaration | SourceFile | ModuleBlock | ClassLikeDeclaration, checker: TypeChecker, file: SourceFile) { +export function getIdentifierForNode(node: Node, scope: FunctionLikeDeclaration | SourceFile | ModuleBlock | ClassLikeDeclaration, checker: TypeChecker, file: SourceFile): string { return isPropertyAccessExpression(node) && !isClassLike(scope) && !checker.resolveName(node.name.text, node, SymbolFlags.Value, /*excludeGlobals*/ false) && !isPrivateIdentifier(node.name) && !identifierToKeywordKind(node.name) ? node.name.text : getUniqueName(isClassLike(scope) ? "newProperty" : "newLocal", file); @@ -69,7 +69,7 @@ export function addTargetFileImports( checker: TypeChecker, program: Program, importAdder: codefix.ImportAdder, -) { +): void { /** * Recomputing the imports is preferred with importAdder because it manages multiple import additions for a file and writes then to a ChangeTracker, * but sometimes it fails because of unresolved imports from files, or when a source file is not available for the target file (in this case when creating a new file). diff --git a/src/services/refactors/moveToFile.ts b/src/services/refactors/moveToFile.ts index 85c040013edcb..c1e102fc9c8bf 100644 --- a/src/services/refactors/moveToFile.ts +++ b/src/services/refactors/moveToFile.ts @@ -246,7 +246,7 @@ export function getNewStatementsAndRemoveFromOldFile( preferences: UserPreferences, importAdderForNewFile: codefix.ImportAdder, importAdderForOldFile: codefix.ImportAdder, -) { +): void { const checker = program.getTypeChecker(); const prologueDirectives = takeWhile(oldFile.statements, isPrologueDirective); @@ -311,7 +311,7 @@ function deleteUnusedOldImports(oldFile: SourceFile, toMove: readonly Statement[ } /** @internal */ -export function addExportsInOldFile(oldFile: SourceFile, targetFileImportsFromOldFile: Map, changes: textChanges.ChangeTracker, useEsModuleSyntax: boolean) { +export function addExportsInOldFile(oldFile: SourceFile, targetFileImportsFromOldFile: Map, changes: textChanges.ChangeTracker, useEsModuleSyntax: boolean): void { const markSeenTop = nodeSeenTracker(); // Needed because multiple declarations may appear in `const x = 0, y = 1;`. targetFileImportsFromOldFile.forEach((_, symbol) => { if (!symbol.declarations) { @@ -512,7 +512,7 @@ export function addImportsForMovedSymbols( targetFileName: string, importAdder: codefix.ImportAdder, program: Program, -) { +): void { for (const [symbol, isValidTypeOnlyUseSite] of symbols) { const symbolName = getNameForExportedSymbol(symbol, getEmitScriptTarget(program.getCompilerOptions())); const exportKind = symbol.name === "default" && symbol.parent ? ExportKind.Default : ExportKind.Named; @@ -840,7 +840,7 @@ export function getStatementsToMove(context: RefactorContext): ToMove | undefine } /** @internal */ -export function containsJsx(statements: readonly Statement[] | undefined) { +export function containsJsx(statements: readonly Statement[] | undefined): Statement | undefined { return find(statements, statement => !!(statement.transformFlags & TransformFlags.ContainsJsx)); } @@ -1121,7 +1121,7 @@ function getOverloadRangeToMove(sourceFile: SourceFile, statement: Statement) { } /** @internal */ -export function getExistingLocals(sourceFile: SourceFile, statements: readonly Statement[], checker: TypeChecker) { +export function getExistingLocals(sourceFile: SourceFile, statements: readonly Statement[], checker: TypeChecker): Set { const existingLocals = new Set(); for (const moduleSpecifier of sourceFile.imports) { const declaration = importFromModuleSpecifier(moduleSpecifier); diff --git a/src/services/services.ts b/src/services/services.ts index 5bccc5fc677b9..b60559284da17 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -1363,7 +1363,7 @@ function isCamelCase(s: string) { return !s.length || s.charAt(0) === s.charAt(0).toLowerCase(); } -export function displayPartsToString(displayParts: SymbolDisplayPart[] | undefined) { +export function displayPartsToString(displayParts: SymbolDisplayPart[] | undefined): string { if (displayParts) { return map(displayParts, displayPart => displayPart.text).join(""); } @@ -1379,7 +1379,7 @@ export function getDefaultCompilerOptions(): CompilerOptions { }; } -export function getSupportedCodeFixes() { +export function getSupportedCodeFixes(): readonly string[] { return codefix.getSupportedErrorCodes(); } diff --git a/src/services/sourcemaps.ts b/src/services/sourcemaps.ts index a8c168eb320aa..5613d2011102b 100644 --- a/src/services/sourcemaps.ts +++ b/src/services/sourcemaps.ts @@ -183,7 +183,7 @@ export function getDocumentPositionMapper( generatedFileName: string, generatedFileLineInfo: LineInfo, readMapFile: ReadMapFile, -) { +): DocumentPositionMapper | undefined { let mapFileName = tryGetSourceMappingURL(generatedFileLineInfo); if (mapFileName) { const match = base64UrlRegExp.exec(mapFileName); diff --git a/src/services/stringCompletions.ts b/src/services/stringCompletions.ts index 667cdf24ca8aa..21eb75ea71572 100644 --- a/src/services/stringCompletions.ts +++ b/src/services/stringCompletions.ts @@ -298,7 +298,7 @@ function convertStringLiteralCompletions( } /** @internal */ -export function getStringLiteralCompletionDetails(name: string, sourceFile: SourceFile, position: number, contextToken: Node | undefined, program: Program, host: LanguageServiceHost, cancellationToken: CancellationToken, preferences: UserPreferences) { +export function getStringLiteralCompletionDetails(name: string, sourceFile: SourceFile, position: number, contextToken: Node | undefined, program: Program, host: LanguageServiceHost, cancellationToken: CancellationToken, preferences: UserPreferences): CompletionEntryDetails | undefined { if (!contextToken || !isStringLiteralLike(contextToken)) return undefined; const completions = getStringLiteralCompletionEntries(sourceFile, contextToken, position, program, host, preferences); return completions && stringLiteralCompletionDetails(name, contextToken, completions, sourceFile, program.getTypeChecker(), cancellationToken); diff --git a/src/services/symbolDisplay.ts b/src/services/symbolDisplay.ts index 5ba8170b17b32..adcd705ff59c0 100644 --- a/src/services/symbolDisplay.ts +++ b/src/services/symbolDisplay.ts @@ -866,7 +866,7 @@ function getSymbolDisplayPartsDocumentationAndSymbolKindWorker(typeChecker: Type // TODO(drosen): Currently completion entry details passes the SemanticMeaning.All instead of using semanticMeaning of location /** @internal */ -export function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker: TypeChecker, symbol: Symbol, sourceFile: SourceFile, enclosingDeclaration: Node | undefined, location: Node, semanticMeaning = getMeaningFromLocation(location), alias?: Symbol): SymbolDisplayPartsDocumentationAndSymbolKind { +export function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker: TypeChecker, symbol: Symbol, sourceFile: SourceFile, enclosingDeclaration: Node | undefined, location: Node, semanticMeaning: SemanticMeaning = getMeaningFromLocation(location), alias?: Symbol): SymbolDisplayPartsDocumentationAndSymbolKind { return getSymbolDisplayPartsDocumentationAndSymbolKindWorker(typeChecker, symbol, sourceFile, enclosingDeclaration, location, /*type*/ undefined, semanticMeaning, alias); } diff --git a/src/services/textChanges.ts b/src/services/textChanges.ts index b02caba811bc0..e73da8490b683 100644 --- a/src/services/textChanges.ts +++ b/src/services/textChanges.ts @@ -509,7 +509,7 @@ export class ChangeTracker { /** Public for tests only. Other callers should use `ChangeTracker.with`. */ constructor(private readonly newLineCharacter: string, private readonly formatContext: formatting.FormatContext) {} - public pushRaw(sourceFile: SourceFile, change: FileTextChanges) { + public pushRaw(sourceFile: SourceFile, change: FileTextChanges): void { Debug.assertEqual(sourceFile.fileName, change.fileName); for (const c of change.textChanges) { this.changes.push({ @@ -534,7 +534,7 @@ export class ChangeTracker { this.deleteRange(sourceFile, getAdjustedRange(sourceFile, node, node, options)); } - public deleteNodes(sourceFile: SourceFile, nodes: readonly Node[], options: ConfigurableStartEnd = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }, hasTrailingComment: boolean): void { + public deleteNodes(sourceFile: SourceFile, nodes: readonly Node[], options: ConfigurableStartEnd | undefined = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }, hasTrailingComment: boolean): void { // When deleting multiple nodes we need to track if the end position is including multiline trailing comments. for (const node of nodes) { const pos = getAdjustedStartPosition(sourceFile, node, options, hasTrailingComment); @@ -724,7 +724,7 @@ export class ChangeTracker { factory.createNodeArray(intersperse(comments, factory.createJSDocText("\n"))); } - public replaceJSDocComment(sourceFile: SourceFile, node: HasJSDoc, tags: readonly JSDocTag[]) { + public replaceJSDocComment(sourceFile: SourceFile, node: HasJSDoc, tags: readonly JSDocTag[]): void { this.insertJsdocCommentBefore(sourceFile, updateJSDocHost(node), factory.createJSDocComment(this.createJSDocText(sourceFile, node), factory.createNodeArray(tags))); } @@ -1011,7 +1011,7 @@ export class ChangeTracker { this.insertText(sourceFile, node.getStart(sourceFile), "export "); } - public insertImportSpecifierAtIndex(sourceFile: SourceFile, importSpecifier: ImportSpecifier, namedImports: NamedImports, index: number) { + public insertImportSpecifierAtIndex(sourceFile: SourceFile, importSpecifier: ImportSpecifier, namedImports: NamedImports, index: number): void { const prevSpecifier = namedImports.elements[index - 1]; if (prevSpecifier) { this.insertNodeInListAfter(sourceFile, prevSpecifier, importSpecifier); @@ -1031,7 +1031,7 @@ export class ChangeTracker { * i.e. arguments in arguments lists, parameters in parameter lists etc. * Note that separators are part of the node in statements and class elements. */ - public insertNodeInListAfter(sourceFile: SourceFile, after: Node, newNode: Node, containingList = formatting.SmartIndenter.getContainingList(after, sourceFile)): void { + public insertNodeInListAfter(sourceFile: SourceFile, after: Node, newNode: Node, containingList: NodeArray | undefined = formatting.SmartIndenter.getContainingList(after, sourceFile)): void { if (!containingList) { Debug.fail("node is not a list element"); return; @@ -1121,7 +1121,7 @@ export class ChangeTracker { } } - public parenthesizeExpression(sourceFile: SourceFile, expression: Expression) { + public parenthesizeExpression(sourceFile: SourceFile, expression: Expression): void { this.replaceRange(sourceFile, rangeOfNode(expression), factory.createParenthesizedExpression(expression)); } @@ -1659,7 +1659,7 @@ function getInsertionPositionAtSourceFileTop(sourceFile: SourceFile): number { } /** @internal */ -export function isValidLocationToAddComment(sourceFile: SourceFile, position: number) { +export function isValidLocationToAddComment(sourceFile: SourceFile, position: number): boolean { return !isInComment(sourceFile, position) && !isInString(sourceFile, position) && !isInTemplateString(sourceFile, position) && !isInJSXText(sourceFile, position); } diff --git a/src/services/tsconfig.json b/src/services/tsconfig.json index 42c124fdd8156..54f2511346b40 100644 --- a/src/services/tsconfig.json +++ b/src/services/tsconfig.json @@ -1,6 +1,7 @@ { "extends": "../tsconfig-base", "compilerOptions": { + "isolatedDeclarations": true }, "references": [ { "path": "../compiler" }, diff --git a/src/services/types.ts b/src/services/types.ts index 10befea4c5386..30e4ee715d2af 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -1232,7 +1232,7 @@ export function getDefaultFormatCodeSettings(newLineCharacter?: string): FormatC } /** @internal */ -export const testFormatSettings = getDefaultFormatCodeSettings("\n"); +export const testFormatSettings: FormatCodeSettings = getDefaultFormatCodeSettings("\n"); export interface DefinitionInfo extends DocumentSpan { kind: ScriptElementKind; diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 0cabbecaa4c8b..231d766a43197 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -525,7 +525,7 @@ function getMeaningFromRightHandSideOfImportEquals(node: Node): SemanticMeaning } /** @internal */ -export function isInRightSideOfInternalImportEqualsDeclaration(node: Node) { +export function isInRightSideOfInternalImportEqualsDeclaration(node: Node): boolean { while (node.parent.kind === SyntaxKind.QualifiedName) { node = node.parent; } @@ -645,7 +645,7 @@ function isCalleeWorker token.getStart(sourceFile); } /** @internal */ -export function isInJSXText(sourceFile: SourceFile, position: number) { +export function isInJSXText(sourceFile: SourceFile, position: number): boolean { const token = getTokenAtPosition(sourceFile, position); if (isJsxText(token)) { return true; @@ -1967,7 +1967,7 @@ export function isInsideJsxElement(sourceFile: SourceFile, position: number): bo } /** @internal */ -export function findPrecedingMatchingToken(token: Node, matchingTokenKind: SyntaxKind.OpenBraceToken | SyntaxKind.OpenParenToken | SyntaxKind.OpenBracketToken, sourceFile: SourceFile) { +export function findPrecedingMatchingToken(token: Node, matchingTokenKind: SyntaxKind.OpenBraceToken | SyntaxKind.OpenParenToken | SyntaxKind.OpenBracketToken, sourceFile: SourceFile): Node | undefined { const closeTokenText = tokenToString(token.kind)!; const matchingTokenText = tokenToString(matchingTokenKind); const tokenFullStart = token.getFullStart(); @@ -2171,7 +2171,7 @@ function nodeHasTokens(n: Node, sourceFile: SourceFileLike): boolean { } /** @internal */ -export function getNodeModifiers(node: Node, excludeFlags = ModifierFlags.None): string { +export function getNodeModifiers(node: Node, excludeFlags: ModifierFlags = ModifierFlags.None): string { const result: string[] = []; const flags = isDeclaration(node) ? getCombinedNodeFlagsAlwaysIncludeJSDoc(node) & ~excludeFlags @@ -2225,7 +2225,7 @@ function areIntersectedTypesAvoidingStringReduction(checker: TypeChecker, t1: Ty } /** @internal */ -export function isStringAndEmptyAnonymousObjectIntersection(type: Type) { +export function isStringAndEmptyAnonymousObjectIntersection(type: Type): boolean { if (!type.isIntersection()) { return false; } @@ -2242,7 +2242,7 @@ export function isInsideTemplateLiteral(node: TemplateLiteralToken, position: nu } /** @internal */ -export function isAccessibilityModifier(kind: SyntaxKind) { +export function isAccessibilityModifier(kind: SyntaxKind): boolean { switch (kind) { case SyntaxKind.PublicKeyword: case SyntaxKind.PrivateKeyword: @@ -2261,7 +2261,7 @@ export function cloneCompilerOptions(options: CompilerOptions): CompilerOptions } /** @internal */ -export function isArrayLiteralOrObjectLiteralDestructuringPattern(node: Node) { +export function isArrayLiteralOrObjectLiteralDestructuringPattern(node: Node): boolean { if ( node.kind === SyntaxKind.ArrayLiteralExpression || node.kind === SyntaxKind.ObjectLiteralExpression @@ -2313,7 +2313,7 @@ function isInReferenceCommentWorker(sourceFile: SourceFile, position: number, sh } /** @internal */ -export function getReplacementSpanForContextToken(contextToken: Node | undefined, position: number) { +export function getReplacementSpanForContextToken(contextToken: Node | undefined, position: number): TextSpan | undefined { if (!contextToken) return undefined; switch (contextToken.kind) { @@ -2331,7 +2331,7 @@ export function createTextSpanFromNode(node: Node, sourceFile?: SourceFile, endN } /** @internal */ -export function createTextSpanFromStringLiteralLikeContent(node: StringLiteralLike, position: number) { +export function createTextSpanFromStringLiteralLikeContent(node: StringLiteralLike, position: number): TextSpan | undefined { let replacementEnd = node.getEnd() - 1; if (node.isUnterminated) { // we return no replacement range only if unterminated string is empty @@ -2400,7 +2400,7 @@ function isTypeKeywordToken(node: Node): node is Token { } /** @internal */ -export function isTypeKeywordTokenOrIdentifier(node: Node) { +export function isTypeKeywordTokenOrIdentifier(node: Node): boolean { return isTypeKeywordToken(node) || isIdentifier(node) && node.text === "type"; } @@ -2772,7 +2772,7 @@ export function getMappedContextSpan(documentSpan: DocumentSpan, sourceMapper: S // Display-part writer helpers // #region /** @internal */ -export function isFirstDeclarationOfSymbolParameter(symbol: Symbol) { +export function isFirstDeclarationOfSymbolParameter(symbol: Symbol): boolean { const declaration = symbol.declarations ? firstOrUndefined(symbol.declarations) : undefined; return !!findAncestor(declaration, n => isParameter(n) ? true : isBindingElement(n) || isObjectBindingPattern(n) || isArrayBindingPattern(n) ? false : "quit"); } @@ -2903,37 +2903,37 @@ export function displayPart(text: string, kind: SymbolDisplayPartKind): SymbolDi } /** @internal */ -export function spacePart() { +export function spacePart(): SymbolDisplayPart { return displayPart(" ", SymbolDisplayPartKind.space); } /** @internal */ -export function keywordPart(kind: SyntaxKind) { +export function keywordPart(kind: SyntaxKind): SymbolDisplayPart { return displayPart(tokenToString(kind)!, SymbolDisplayPartKind.keyword); } /** @internal */ -export function punctuationPart(kind: SyntaxKind) { +export function punctuationPart(kind: SyntaxKind): SymbolDisplayPart { return displayPart(tokenToString(kind)!, SymbolDisplayPartKind.punctuation); } /** @internal */ -export function operatorPart(kind: SyntaxKind) { +export function operatorPart(kind: SyntaxKind): SymbolDisplayPart { return displayPart(tokenToString(kind)!, SymbolDisplayPartKind.operator); } /** @internal */ -export function parameterNamePart(text: string) { +export function parameterNamePart(text: string): SymbolDisplayPart { return displayPart(text, SymbolDisplayPartKind.parameterName); } /** @internal */ -export function propertyNamePart(text: string) { +export function propertyNamePart(text: string): SymbolDisplayPart { return displayPart(text, SymbolDisplayPartKind.propertyName); } /** @internal */ -export function textOrKeywordPart(text: string) { +export function textOrKeywordPart(text: string): SymbolDisplayPart { const kind = stringToToken(text); return kind === undefined ? textPart(text) @@ -2941,17 +2941,17 @@ export function textOrKeywordPart(text: string) { } /** @internal */ -export function textPart(text: string) { +export function textPart(text: string): SymbolDisplayPart { return displayPart(text, SymbolDisplayPartKind.text); } /** @internal */ -export function typeAliasNamePart(text: string) { +export function typeAliasNamePart(text: string): SymbolDisplayPart { return displayPart(text, SymbolDisplayPartKind.aliasName); } /** @internal */ -export function typeParameterNamePart(text: string) { +export function typeParameterNamePart(text: string): SymbolDisplayPart { return displayPart(text, SymbolDisplayPartKind.typeParameterName); } @@ -3040,14 +3040,14 @@ const lineFeed = "\n"; * * @internal */ -export function getNewLineOrDefaultFromHost(host: FormattingHost, formatSettings: FormatCodeSettings | undefined) { +export function getNewLineOrDefaultFromHost(host: FormattingHost, formatSettings: FormatCodeSettings | undefined): string { return formatSettings?.newLineCharacter || host.getNewLine?.() || lineFeed; } /** @internal */ -export function lineBreakPart() { +export function lineBreakPart(): SymbolDisplayPart { return displayPart("\n", SymbolDisplayPartKind.lineBreak); } @@ -3115,12 +3115,12 @@ function isAliasSymbol(symbol: Symbol): boolean { } /** @internal */ -export function getUniqueSymbolId(symbol: Symbol, checker: TypeChecker) { +export function getUniqueSymbolId(symbol: Symbol, checker: TypeChecker): number { return getSymbolId(skipAlias(symbol, checker)); } /** @internal */ -export function getFirstNonSpaceCharacterPosition(text: string, position: number) { +export function getFirstNonSpaceCharacterPosition(text: string, position: number): number { while (isWhiteSpaceLike(text.charCodeAt(position))) { position += 1; } @@ -3128,7 +3128,7 @@ export function getFirstNonSpaceCharacterPosition(text: string, position: number } /** @internal */ -export function getPrecedingNonSpaceCharacterPosition(text: string, position: number) { +export function getPrecedingNonSpaceCharacterPosition(text: string, position: number): number { while (position > -1 && isWhiteSpaceSingleLine(text.charCodeAt(position))) { position -= 1; } @@ -3219,7 +3219,7 @@ export function getSynthesizedDeepClonesWithReplacements( * * @internal */ -export function suppressLeadingAndTrailingTrivia(node: Node) { +export function suppressLeadingAndTrailingTrivia(node: Node): void { suppressLeadingTrivia(node); suppressTrailingTrivia(node); } @@ -3229,7 +3229,7 @@ export function suppressLeadingAndTrailingTrivia(node: Node) { * * @internal */ -export function suppressLeadingTrivia(node: Node) { +export function suppressLeadingTrivia(node: Node): void { addEmitFlagsRecursively(node, EmitFlags.NoLeadingComments, getFirstChild); } @@ -3238,12 +3238,12 @@ export function suppressLeadingTrivia(node: Node) { * * @internal @knipignore */ -export function suppressTrailingTrivia(node: Node) { +export function suppressTrailingTrivia(node: Node): void { addEmitFlagsRecursively(node, EmitFlags.NoTrailingComments, getLastChild); } /** @internal */ -export function copyComments(sourceNode: Node, targetNode: Node) { +export function copyComments(sourceNode: Node, targetNode: Node): void { const sourceFile = sourceNode.getSourceFile(); const text = sourceFile.text; if (hasLeadingLineBreak(sourceNode, text)) { @@ -3317,12 +3317,12 @@ export function getRenameLocation(edits: readonly FileTextChanges[], renameFilen } /** @internal */ -export function copyLeadingComments(sourceNode: Node, targetNode: Node, sourceFile: SourceFile, commentKind?: CommentKind, hasTrailingNewLine?: boolean) { +export function copyLeadingComments(sourceNode: Node, targetNode: Node, sourceFile: SourceFile, commentKind?: CommentKind, hasTrailingNewLine?: boolean): void { forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, addSyntheticLeadingComment)); } /** @internal */ -export function copyTrailingComments(sourceNode: Node, targetNode: Node, sourceFile: SourceFile, commentKind?: CommentKind, hasTrailingNewLine?: boolean) { +export function copyTrailingComments(sourceNode: Node, targetNode: Node, sourceFile: SourceFile, commentKind?: CommentKind, hasTrailingNewLine?: boolean): void { forEachTrailingCommentRange(sourceFile.text, sourceNode.end, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, addSyntheticTrailingComment)); } @@ -3335,7 +3335,7 @@ export function copyTrailingComments(sourceNode: Node, targetNode: Node, sourceF * * @internal */ -export function copyTrailingAsLeadingComments(sourceNode: Node, targetNode: Node, sourceFile: SourceFile, commentKind?: CommentKind, hasTrailingNewLine?: boolean) { +export function copyTrailingAsLeadingComments(sourceNode: Node, targetNode: Node, sourceFile: SourceFile, commentKind?: CommentKind, hasTrailingNewLine?: boolean): void { forEachTrailingCommentRange(sourceFile.text, sourceNode.pos, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, addSyntheticLeadingComment)); } @@ -3999,7 +3999,7 @@ export function firstOrOnly(valueOrArray: T | readonly T[]): T { * instead, which searches for names of re-exported defaults/namespaces in target files. * @internal */ -export function getNameForExportedSymbol(symbol: Symbol, scriptTarget: ScriptTarget | undefined, preferCapitalized?: boolean) { +export function getNameForExportedSymbol(symbol: Symbol, scriptTarget: ScriptTarget | undefined, preferCapitalized?: boolean): string { if (symbol.escapedName === InternalSymbolName.ExportEquals || symbol.escapedName === InternalSymbolName.Default) { // Names for default exports: // - export default foo => foo @@ -4102,7 +4102,7 @@ export function moduleSpecifierToValidIdentifier(moduleSpecifier: string, target * * @internal */ -export function stringContainsAt(haystack: string, needle: string, startIndex: number) { +export function stringContainsAt(haystack: string, needle: string, startIndex: number): boolean { const needleLength = needle.length; if (needleLength + startIndex > haystack.length) { return false; @@ -4119,7 +4119,7 @@ export function startsWithUnderscore(name: string): boolean { } /** @internal */ -export function isDeprecatedDeclaration(decl: Declaration) { +export function isDeprecatedDeclaration(decl: Declaration): boolean { return !!(getCombinedNodeFlagsAlwaysIncludeJSDoc(decl) & ModifierFlags.Deprecated); } @@ -4168,12 +4168,12 @@ export function getFormatCodeSettingsForWriting({ options }: formatting.FormatCo } /** @internal */ -export function jsxModeNeedsExplicitImport(jsx: JsxEmit | undefined) { +export function jsxModeNeedsExplicitImport(jsx: JsxEmit | undefined): jsx is JsxEmit.React | JsxEmit.ReactNative { return jsx === JsxEmit.React || jsx === JsxEmit.ReactNative; } /** @internal */ -export function isSourceFileFromLibrary(program: Program, node: SourceFile) { +export function isSourceFileFromLibrary(program: Program, node: SourceFile): boolean { return program.isSourceFileFromExternalLibrary(node) || program.isSourceFileDefaultLibrary(node); } @@ -4249,7 +4249,7 @@ export function newCaseClauseTracker(checker: TypeChecker, clauses: readonly (Ca } /** @internal */ -export function fileShouldUseJavaScriptRequire(file: SourceFile | string, program: Program, host: LanguageServiceHost, preferRequire?: boolean) { +export function fileShouldUseJavaScriptRequire(file: SourceFile | string, program: Program, host: LanguageServiceHost, preferRequire?: boolean): boolean | undefined { const fileName = typeof file === "string" ? file : file.fileName; if (!hasJSFileExtension(fileName)) { return false; diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index 211120bc58196..7e7a5f3609e7f 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -2842,14 +2842,14 @@ declare namespace ts { readonly jsDocParsingMode: JSDocParsingMode | undefined; isKnownTypesPackageName(name: string): boolean; installPackage(options: InstallPackageOptions): Promise; - getCompilationSettings(): ts.CompilerOptions; - getCompilerOptions(): ts.CompilerOptions; + getCompilationSettings(): CompilerOptions; + getCompilerOptions(): CompilerOptions; getNewLine(): string; getProjectVersion(): string; getProjectReferences(): readonly ProjectReference[] | undefined; getScriptFileNames(): string[]; private getOrCreateScriptInfoAndAttachToProject; - getScriptKind(fileName: string): ts.ScriptKind; + getScriptKind(fileName: string): ScriptKind; getScriptVersion(filename: string): string; getScriptSnapshot(filename: string): IScriptSnapshot | undefined; getCancellationToken(): HostCancellationToken; @@ -2885,7 +2885,7 @@ declare namespace ts { getProjectName(): string; protected removeLocalTypingsFromTypeAcquisition(newTypeAcquisition: TypeAcquisition): TypeAcquisition; getExternalFiles(updateLevel?: ProgramUpdateLevel): SortedReadonlyArray; - getSourceFile(path: Path): ts.SourceFile | undefined; + getSourceFile(path: Path): SourceFile | undefined; close(): void; private detachScriptInfoIfNotRoot; isClosed(): boolean; @@ -2924,7 +2924,7 @@ declare namespace ts { private filesToStringWorker; setCompilerOptions(compilerOptions: CompilerOptions): void; setTypeAcquisition(newTypeAcquisition: TypeAcquisition | undefined): void; - getTypeAcquisition(): ts.TypeAcquisition; + getTypeAcquisition(): TypeAcquisition; protected removeRoot(info: ScriptInfo): void; protected enableGlobalPlugins(options: CompilerOptions): void; protected enablePlugin(pluginConfigEntry: PluginImport, searchPaths: string[]): void; @@ -2958,7 +2958,7 @@ declare namespace ts { getScriptFileNames(): string[]; getLanguageService(): never; getHostForAutoImportProvider(): never; - getProjectReferences(): readonly ts.ProjectReference[] | undefined; + getProjectReferences(): readonly ProjectReference[] | undefined; } /** * If a file is opened, the server will look for a tsconfig (or jsconfig) @@ -3375,7 +3375,7 @@ declare namespace ts { /** @deprecated use ts.server.protocol.CommandTypes */ type CommandNames = protocol.CommandTypes; /** @deprecated use ts.server.protocol.CommandTypes */ - const CommandNames: any; + const CommandNames: CommandNames; type Event = (body: T, eventName: string) => void; interface EventSender { event: Event;