Enable `--isolatedDeclarations` on TS codebase (#59635)

Co-authored-by: Sheetal Nandi <shkamat@microsoft.com>
Co-authored-by: Andrew Branch <andrew@wheream.io>
This commit is contained in:
Isabel Duan 2024-09-15 18:10:52 -07:00 коммит произвёл GitHub
Родитель 89e004f632
Коммит 52eaa7b02f
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: B5690EEEBB952194
136 изменённых файлов: 1947 добавлений и 1614 удалений

Просмотреть файл

@ -118,6 +118,7 @@ export default tseslint.config(
"@typescript-eslint/ban-ts-comment": "off",
"@typescript-eslint/class-literal-property-style": "off",
"@typescript-eslint/consistent-indexed-object-style": "off",
"@typescript-eslint/consistent-generic-constructors": "off",
"@typescript-eslint/no-duplicate-enum-values": "off",
"@typescript-eslint/no-empty-function": "off",
"@typescript-eslint/no-namespace": "off",

Просмотреть файл

@ -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}) as DiagnosticMessage,`);
});
result.push("};");

Просмотреть файл

@ -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");

Просмотреть файл

@ -8,6 +8,7 @@ import {
BuilderProgramHost,
BuilderState,
BuildInfo,
BuildInfoFileVersionMap,
CancellationToken,
CommandLineOption,
compareStringsCaseSensitive,
@ -277,7 +278,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 +734,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 +1624,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 +2396,7 @@ export function getBuildInfoFileVersionMap(
program: IncrementalBuildInfo,
buildInfoPath: string,
host: Pick<ReadBuildProgramHost, "useCaseSensitiveFileNames" | "getCurrentDirectory">,
) {
): BuildInfoFileVersionMap {
const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames());
const fileInfos = new Map<Path, string>();
@ -2440,7 +2441,7 @@ export function getNonIncrementalBuildInfoRoots(
buildInfo: BuildInfo,
buildInfoPath: string,
host: Pick<ReadBuildProgramHost, "useCaseSensitiveFileNames" | "getCurrentDirectory">,
) {
): Path[] | undefined {
if (!isNonIncrementalBuildInfo(buildInfo)) return undefined;
const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames());

Просмотреть файл

@ -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<BuilderState>, referencedFilePath: Path) {
export function getReferencedByPaths(state: Readonly<BuilderState>, referencedFilePath: Path): Path[] {
const keys = state.referencedMap!.getKeys(referencedFilePath);
return keys ? arrayFrom(keys.keys()) : [];
}

Просмотреть файл

@ -1450,7 +1450,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);
@ -52709,7 +52709,7 @@ function getIterationTypesKeyFromIterationTypeKind(typeKind: IterationTypeKind)
}
/** @internal */
export function signatureHasRestParameter(s: Signature) {
export function signatureHasRestParameter(s: Signature): boolean {
return !!(s.flags & SignatureFlags.HasRestParameter);
}

Просмотреть файл

@ -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<string, string> = 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<string, string> = new Map(libEntries);
// Watch related options
@ -1800,7 +1800,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);
}
@ -1835,6 +1835,14 @@ export interface OptionsBase {
[option: string]: CompilerOptionsValue | TsConfigSourceFile | undefined;
}
/** @internal */
export interface BaseParsedCommandLine {
options: OptionsBase;
watchOptions: WatchOptions | undefined;
fileNames: string[];
errors: Diagnostic[];
}
/** @internal */
export interface ParseCommandLineWorkerDiagnostics extends DidYouMeanOptionsDiagnostics {
getOptionsNameMap: () => OptionsNameMap;
@ -1875,7 +1883,7 @@ export function parseCommandLineWorker(
diagnostics: ParseCommandLineWorkerDiagnostics,
commandLine: readonly string[],
readFile?: (path: string) => string | undefined,
) {
): BaseParsedCommandLine {
const options = {} as OptionsBase;
let watchOptions: WatchOptions | undefined;
const fileNames: string[] = [];
@ -2602,11 +2610,11 @@ export function convertToTSConfig(configParseResult: ParsedCommandLine, configFi
const providedKeys = new Set(optionMap.keys());
const impliedCompilerOptions: Record<string, CompilerOptionsValue> = {};
for (const option in computedOptions) {
if (!providedKeys.has(option) && some(computedOptions[option as keyof typeof computedOptions].dependencies, dep => providedKeys.has(dep))) {
const implied = computedOptions[option as keyof typeof computedOptions].computeValue(configParseResult.options);
const defaultValue = computedOptions[option as keyof typeof computedOptions].computeValue({});
if (!providedKeys.has(option) && some(computedOptions[option].dependencies, dep => providedKeys.has(dep))) {
const implied = computedOptions[option].computeValue(configParseResult.options);
const defaultValue = computedOptions[option].computeValue({});
if (implied !== defaultValue) {
impliedCompilerOptions[option] = computedOptions[option as keyof typeof computedOptions].computeValue(configParseResult.options);
impliedCompilerOptions[option] = computedOptions[option].computeValue(configParseResult.options);
}
}
}
@ -2866,7 +2874,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;
@ -2927,7 +2935,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 });
}
@ -3243,12 +3251,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));
@ -3943,7 +3951,7 @@ export function matchesExclude(
excludeSpecs: readonly string[] | undefined,
useCaseSensitiveFileNames: boolean,
currentDirectory: string,
) {
): boolean {
return matchesExcludeWorker(
pathToCheck,
filter(excludeSpecs, spec => !invalidDotDotAfterRecursiveWildcard(spec)),

Просмотреть файл

@ -329,7 +329,7 @@ export function map<T, U>(array: readonly T[] | undefined, f: (x: T, i: number)
}
/** @internal */
export function* mapIterator<T, U>(iter: Iterable<T>, mapFn: (x: T) => U) {
export function* mapIterator<T, U>(iter: Iterable<T>, mapFn: (x: T) => U): Generator<U, void, unknown> {
for (const x of iter) {
yield mapFn(x);
}
@ -434,7 +434,7 @@ export function flatMapToMutable<T, U>(array: readonly T[] | undefined, mapfn: (
}
/** @internal */
export function* flatMapIterator<T, U>(iter: Iterable<T>, mapfn: (x: T) => readonly U[] | Iterable<U> | undefined) {
export function* flatMapIterator<T, U>(iter: Iterable<T>, mapfn: (x: T) => readonly U[] | Iterable<U> | undefined): Generator<U, void, any> {
for (const x of iter) {
const iter2 = mapfn(x);
if (!iter2) continue;
@ -505,7 +505,8 @@ export function mapDefined<T, U>(array: readonly T[] | undefined, mapFn: (x: T,
}
/** @internal */
export function* mapDefinedIterator<T, U>(iter: Iterable<T>, mapFn: (x: T) => U | undefined) {
// eslint-disable-next-line no-restricted-syntax
export function* mapDefinedIterator<T, U>(iter: Iterable<T>, mapFn: (x: T) => U | undefined): Generator<U & ({} | null), void, unknown> {
for (const x of iter) {
const value = mapFn(x);
if (value !== undefined) {
@ -515,7 +516,7 @@ export function* mapDefinedIterator<T, U>(iter: Iterable<T>, mapFn: (x: T) => U
}
/** @internal */
export function getOrUpdate<K, V>(map: Map<K, V>, key: K, callback: () => V) {
export function getOrUpdate<K, V>(map: Map<K, V>, key: K, callback: () => V): V {
if (map.has(key)) {
return map.get(key)!;
}
@ -525,7 +526,7 @@ export function getOrUpdate<K, V>(map: Map<K, V>, key: K, callback: () => V) {
}
/** @internal */
export function tryAddToSet<T>(set: Set<T>, value: T) {
export function tryAddToSet<T>(set: Set<T>, value: T): boolean {
if (!set.has(value)) {
set.add(value);
return true;
@ -534,7 +535,7 @@ export function tryAddToSet<T>(set: Set<T>, value: T) {
}
/** @internal */
export function* singleIterator<T>(value: T) {
export function* singleIterator<T>(value: T): Generator<T, void, unknown> {
yield value;
}
@ -1039,14 +1040,14 @@ export function toSorted<T>(array: readonly T[], comparer?: Comparer<T>): Sorted
}
/** @internal */
export function* arrayReverseIterator<T>(array: readonly T[]) {
export function* arrayReverseIterator<T>(array: readonly T[]): Generator<T, void, unknown> {
for (let i = array.length - 1; i >= 0; i--) {
yield array[i];
}
}
/** @internal */
export function rangeEquals<T>(array1: readonly T[], array2: readonly T[], pos: number, end: number) {
export function rangeEquals<T>(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<T, U>(iterator: Iterable<T>, map?: (t: T) => U): (T |
}
/** @internal */
export function assign<T extends object>(t: T, ...args: (T | undefined)[]) {
export function assign<T extends object>(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 extends object>(t: T, ...args: (T | undefined)[]) {
*
* @internal
*/
export function equalOwnProperties<T>(left: MapLike<T> | undefined, right: MapLike<T> | undefined, equalityComparer: EqualityComparer<T> = equateValues) {
export function equalOwnProperties<T>(left: MapLike<T> | undefined, right: MapLike<T> | undefined, equalityComparer: EqualityComparer<T> = equateValues): boolean {
if (left === right) return true;
if (!left || !right) return false;
for (const key in left) {
@ -1509,7 +1510,7 @@ export function extend<T1, T2>(first: T1, second: T2): T1 & T2 {
}
/** @internal */
export function copyProperties<T1 extends T2, T2>(first: T1, second: T2) {
export function copyProperties<T1 extends T2, T2>(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<T>(x: T) {
export function identity<T>(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<T>(a: T, b: T) {
export function equateValues<T>(a: T, b: T): boolean {
return a === b;
}
@ -1947,7 +1948,7 @@ export function equateValues<T>(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<T>(items: readonly T[], compare: Comparer<T>): 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<string> | 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<T>(array: T[], index: number): void {
*
* @internal
*/
export function unorderedRemoveItem<T>(array: T[], item: T) {
export function unorderedRemoveItem<T>(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<T>(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: T | undefined): T[] | undefined {
}
/** @internal */
export function enumerateInsertsAndDeletes<T, U>(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<T, U>(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<T, U>(newItems: readonly T[], oldItem
}
/** @internal */
export function cartesianProduct<T>(arrays: readonly T[][]) {
export function cartesianProduct<T>(arrays: readonly T[][]): T[][] {
const result: T[][] = [];
cartesianProductWorker(arrays, result, /*outer*/ undefined, 0);
return result;

Просмотреть файл

@ -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<Record<AssertionKeys, { level: AssertionLevel; assertion: AnyFunction; }>> = {};
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<T>(value: unknown): asserts value is T;
export function type(_value: unknown) {}
export function getFunctionName(func: AnyFunction) {
export function getFunctionName(func: AnyFunction): string {
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<Node>) {
export function attachNodeArrayDebugInfo(array: NodeArray<Node>): 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) {

Просмотреть файл

@ -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<T>(
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<T>(
}
}
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,17 @@ 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 +727,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 +1118,7 @@ export function emitFiles(
}
/** @internal */
export function getBuildInfoText(buildInfo: BuildInfo) {
export function getBuildInfoText(buildInfo: BuildInfo): string {
return JSON.stringify(buildInfo);
}
@ -1174,16 +1179,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.

Просмотреть файл

@ -729,7 +729,7 @@ function executeCommandLineWorker(
}
/** Returns true if commandline is --build and needs to be parsed useing parseBuildCommand */
export function isBuildCommand(commandLineArgs: readonly string[]) {
export function isBuildCommand(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 === tscBuildOption.name || firstOption === tscBuildOption.shortName;

Просмотреть файл

@ -55,6 +55,7 @@ import {
PropertySignature,
SetAccessorDeclaration,
SignatureDeclaration,
SyntacticNodeBuilder,
SyntacticTypeNodeBuilderContext,
SyntacticTypeNodeBuilderResolver,
SyntaxKind,
@ -66,7 +67,10 @@ import {
} from "./_namespaces/ts.js";
/** @internal */
export function createSyntacticTypeNodeBuilder(options: CompilerOptions, resolver: SyntacticTypeNodeBuilderResolver) {
export function createSyntacticTypeNodeBuilder(
options: CompilerOptions,
resolver: SyntacticTypeNodeBuilderResolver,
): SyntacticNodeBuilder {
const strictNullChecks = getStrictOptionValue(options, "strictNullChecks");
return {

Просмотреть файл

@ -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;

Просмотреть файл

@ -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<T extends Node>(node: T): T {
/**
* Sets flags that control emit behavior of a node.
*/
export function setEmitFlags<T extends Node>(node: T, emitFlags: EmitFlags) {
export function setEmitFlags<T extends Node>(node: T, emitFlags: EmitFlags): T {
getOrCreateEmitNode(node).flags = emitFlags;
return node;
}
@ -99,7 +99,7 @@ export function setEmitFlags<T extends Node>(node: T, emitFlags: EmitFlags) {
*
* @internal
*/
export function addEmitFlags<T extends Node>(node: T, emitFlags: EmitFlags) {
export function addEmitFlags<T extends Node>(node: T, emitFlags: EmitFlags): T {
const emitNode = getOrCreateEmitNode(node);
emitNode.flags = emitNode.flags | emitFlags;
return node;
@ -110,7 +110,7 @@ export function addEmitFlags<T extends Node>(node: T, emitFlags: EmitFlags) {
*
* @internal
*/
export function setInternalEmitFlags<T extends Node>(node: T, emitFlags: InternalEmitFlags) {
export function setInternalEmitFlags<T extends Node>(node: T, emitFlags: InternalEmitFlags): T {
getOrCreateEmitNode(node).internalFlags = emitFlags;
return node;
}
@ -120,7 +120,7 @@ export function setInternalEmitFlags<T extends Node>(node: T, emitFlags: Interna
*
* @internal
*/
export function addInternalEmitFlags<T extends Node>(node: T, emitFlags: InternalEmitFlags) {
export function addInternalEmitFlags<T extends Node>(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<T extends Node>(node: T, range: SourceMapRange | undefined) {
export function setSourceMapRange<T extends Node>(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<T extends Node>(node: T, token: SyntaxKind, range: SourceMapRange | undefined) {
export function setTokenSourceMapRange<T extends Node>(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<T extends Node>(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<T extends Node>(node: T, newLine: boolean) {
export function setStartsOnNewLine<T extends Node>(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<T extends Node>(node: T, range: TextRange) {
export function setCommentRange<T extends Node>(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<T extends Node>(node: T, comments: SynthesizedComment[] | undefined) {
export function setSyntheticLeadingComments<T extends Node>(node: T, comments: SynthesizedComment[] | undefined): T {
getOrCreateEmitNode(node).leadingComments = comments;
return node;
}
export function addSyntheticLeadingComment<T extends Node>(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean) {
export function addSyntheticLeadingComment<T extends Node>(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean): T {
return setSyntheticLeadingComments(node, append<SynthesizedComment>(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<T extends Node>(node: T, comments: SynthesizedComment[] | undefined) {
export function setSyntheticTrailingComments<T extends Node>(node: T, comments: SynthesizedComment[] | undefined): T {
getOrCreateEmitNode(node).trailingComments = comments;
return node;
}
export function addSyntheticTrailingComment<T extends Node>(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean) {
export function addSyntheticTrailingComment<T extends Node>(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean): T {
return setSyntheticTrailingComments(node, append<SynthesizedComment>(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<T extends Node>(node: T): TypeNode | undefined {
}
/** @internal */
export function setIdentifierTypeArguments<T extends Identifier>(node: T, typeArguments: NodeArray<TypeNode | TypeParameterDeclaration> | undefined) {
export function setIdentifierTypeArguments<T extends Identifier>(node: T, typeArguments: NodeArray<TypeNode | TypeParameterDeclaration> | undefined): T {
getOrCreateEmitNode(node).identifierTypeArguments = typeArguments;
return node;
}
@ -359,7 +359,7 @@ export function getIdentifierTypeArguments(node: Identifier): NodeArray<TypeNode
}
/** @internal */
export function setIdentifierAutoGenerate<T extends Identifier | PrivateIdentifier>(node: T, autoGenerate: AutoGenerateInfo | undefined) {
export function setIdentifierAutoGenerate<T extends Identifier | PrivateIdentifier>(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<T extends Identifier | PrivateIdentifier>(node: T, value: ImportSpecifier | undefined) {
export function setIdentifierGeneratedImportReference<T extends Identifier | PrivateIdentifier>(node: T, value: ImportSpecifier | undefined): T {
getOrCreateEmitNode(node).generatedImportReference = value;
return node;
}

Просмотреть файл

@ -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);

Просмотреть файл

@ -477,7 +477,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);
}
@ -7396,7 +7396,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;

Просмотреть файл

@ -180,7 +180,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);
}
@ -513,7 +513,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");
@ -547,7 +553,7 @@ export function expandPreOrPostfixIncrementOrDecrementExpression(factory: NodeFa
*
* @internal
*/
export function isInternalName(node: Identifier) {
export function isInternalName(node: Identifier): boolean {
return (getEmitFlags(node) & EmitFlags.InternalName) !== 0;
}
@ -556,7 +562,7 @@ export function isInternalName(node: Identifier) {
*
* @internal
*/
export function isLocalName(node: Identifier) {
export function isLocalName(node: Identifier): boolean {
return (getEmitFlags(node) & EmitFlags.LocalName) !== 0;
}
@ -566,7 +572,7 @@ export function isLocalName(node: Identifier) {
*
* @internal
*/
export function isExportName(node: Identifier) {
export function isExportName(node: Identifier): boolean {
return (getEmitFlags(node) & EmitFlags.ExportName) !== 0;
}
@ -590,7 +596,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)
@ -622,7 +628,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)) {
@ -658,7 +664,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;
@ -673,21 +679,21 @@ export function startOnNewLine<T extends Node>(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 | ImportEqualsDeclaration | undefined {
if (compilerOptions.importHelpers && isEffectiveExternalModule(sourceFile, compilerOptions)) {
const moduleKind = getEmitModuleKind(compilerOptions);
const impliedModuleKind = getImpliedNodeFormatForEmitWorker(sourceFile, compilerOptions);
@ -803,7 +809,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)
@ -1081,7 +1087,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) {
@ -1507,7 +1513,7 @@ export function elideNodes<T extends Node>(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;
@ -1600,7 +1606,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,
@ -1714,7 +1720,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;

Просмотреть файл

@ -297,7 +297,7 @@ function initializeResolutionField<T>(value: T[]): T[] | undefined {
return value.length ? value : undefined;
}
/** @internal */
export function updateResolutionField<T>(to: T[] | undefined, value: T[] | undefined) {
export function updateResolutionField<T>(to: T[] | undefined, value: T[] | undefined): T[] | undefined {
if (!value?.length) return to;
if (!to?.length) return value;
to.push(...value);
@ -454,7 +454,7 @@ function readPackageJsonTypesVersionPaths(jsonContent: PackageJson, state: Modul
let typeScriptVersion: Version | undefined;
/** @internal */
export function getPackageJsonTypesVersionsPaths(typesVersions: MapLike<MapLike<string[]>>) {
export function getPackageJsonTypesVersionsPaths(typesVersions: MapLike<MapLike<string[]>>): VersionPaths | undefined {
if (!typeScriptVersion) typeScriptVersion = new Version(version);
for (const key in typesVersions) {
@ -748,7 +748,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) {
@ -952,7 +952,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}`;
}
@ -1383,7 +1383,7 @@ export function createTypeReferenceDirectiveResolutionCache(
}
/** @internal */
export function getOptionsForLibraryResolution(options: CompilerOptions) {
export function getOptionsForLibraryResolution(options: CompilerOptions): CompilerOptions {
return { moduleResolution: ModuleResolutionKind.Node10, traceResolution: options.traceResolution };
}
@ -2556,7 +2556,7 @@ export function parsePackageName(moduleName: string): { packageName: string; res
}
/** @internal */
export function allKeysStartWithDot(obj: MapLike<unknown>) {
export function allKeysStartWithDot(obj: MapLike<unknown>): boolean {
return every(getOwnKeys(obj), k => startsWith(k, "."));
}
@ -2677,18 +2677,18 @@ 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): Comparison {
const aPatternIndex = a.indexOf("*");
const bPatternIndex = b.indexOf("*");
const baseLenA = aPatternIndex === -1 ? a.length : aPatternIndex + 1;
const baseLenB = bPatternIndex === -1 ? b.length : bPatternIndex + 1;
if (baseLenA > baseLenB) return -1;
if (baseLenB > baseLenA) return 1;
if (aPatternIndex === -1) return 1;
if (bPatternIndex === -1) return -1;
if (a.length > b.length) return -1;
if (b.length > a.length) return 1;
return 0;
if (baseLenA > baseLenB) return Comparison.LessThan;
if (baseLenB > baseLenA) return Comparison.GreaterThan;
if (aPatternIndex === -1) return Comparison.GreaterThan;
if (bPatternIndex === -1) return Comparison.LessThan;
if (a.length > b.length) return Comparison.LessThan;
if (b.length > a.length) return Comparison.GreaterThan;
return Comparison.EqualTo;
}
function loadModuleFromImportsOrExports(extensions: Extensions, state: ModuleResolutionState, cache: ModuleResolutionCache | undefined, redirectedReference: ResolvedProjectReference | undefined, moduleName: string, lookupTable: object, scope: PackageJsonInfo, isImports: boolean): SearchResult<Resolved> | undefined {
@ -2965,7 +2965,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));
@ -3332,8 +3332,8 @@ 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) {
return !!compilerOptions.allowImportingTsExtensions || fromFileName && isDeclarationFileName(fromFileName);
export function shouldAllowImportingTsExtension(compilerOptions: CompilerOptions, fromFileName?: string): boolean {
return !!compilerOptions.allowImportingTsExtensions || !!fromFileName && isDeclarationFileName(fromFileName);
}
/**

Просмотреть файл

@ -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;
@ -1412,7 +1412,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);

Просмотреть файл

@ -458,14 +458,14 @@ function visitNodes<T>(cbNode: (node: Node) => T, cbNodes: ((node: NodeArray<Nod
}
/** @internal */
export function isJSDocLikeText(text: string, start: number) {
export function isJSDocLikeText(text: string, start: number): boolean {
return text.charCodeAt(start + 1) === CharacterCodes.asterisk &&
text.charCodeAt(start + 2) === CharacterCodes.asterisk &&
text.charCodeAt(start + 3) !== CharacterCodes.slash;
}
/** @internal */
export function isFileProbablyExternalModule(sourceFile: SourceFile) {
export function isFileProbablyExternalModule(sourceFile: SourceFile): Node | undefined {
// Try to use the first top-level import/export when available, then
// fall back to looking for an 'import.meta' somewhere in the tree if necessary.
return forEach(sourceFile.statements, isAnExternalModuleIndicatorNode) ||
@ -1404,7 +1404,13 @@ export function updateSourceFile(sourceFile: SourceFile, newText: string, textCh
}
/** @internal */
export function parseIsolatedJSDocComment(content: string, start?: number, length?: number) {
export interface JsDocWithDiagnostics {
jsDoc: JSDoc;
diagnostics: Diagnostic[];
}
/** @internal */
export function parseIsolatedJSDocComment(content: string, start?: number, length?: number): JsDocWithDiagnostics | undefined {
const result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length);
if (result && result.jsDoc) {
// because the jsDocComment was parsed out of the source file, it might
@ -1417,7 +1423,10 @@ export function parseIsolatedJSDocComment(content: string, start?: number, lengt
/** @internal */
// Exposed only for testing.
export function parseJSDocTypeExpressionForTests(content: string, start?: number, length?: number) {
export function parseJSDocTypeExpressionForTests(content: string, start?: number, length?: number): {
jsDocTypeExpression: JSDocTypeExpression;
diagnostics: Diagnostic[];
} | undefined {
return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length);
}

Просмотреть файл

@ -47,7 +47,7 @@ export function isAnyDirectorySeparator(charCode: number): boolean {
*
* @internal
*/
export function isUrl(path: string) {
export function isUrl(path: string): boolean {
return getEncodedRootLength(path) < 0;
}
@ -57,7 +57,7 @@ export function isUrl(path: string) {
*
* @internal
*/
export function isRootedDiskPath(path: string) {
export function isRootedDiskPath(path: string): boolean {
return getEncodedRootLength(path) > 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<T extends string>(pathComponents: readonly T[], length?: number) {
export function getPathFromPathComponents<T extends string>(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<T, P extends string>(directory: P, call
}
/** @internal */
export function isNodeModulesDirectory(dirPath: Path) {
export function isNodeModulesDirectory(dirPath: Path): boolean {
return endsWith(dirPath, "/node_modules");
}

Просмотреть файл

@ -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<string, number>();
*
* @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();

Просмотреть файл

@ -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;

Просмотреть файл

@ -516,12 +516,23 @@ export interface CompilerHostLikeForCache {
writeFile?: WriteFileCallback;
}
/** @internal */
export interface CompilerHostLikeWithCache {
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;
}
/** @internal */
export function changeCompilerHostLikeToUseCache(
host: CompilerHostLikeForCache,
toPath: (fileName: string) => Path,
getSourceFile?: CompilerHost["getSourceFile"],
) {
): CompilerHostLikeWithCache {
const originalReadFile = host.readFile;
const originalFileExists = host.fileExists;
const originalDirectoryExists = host.directoryExists;
@ -704,7 +715,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 +774,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 +865,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 +892,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 +940,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 +993,7 @@ function getEmitSyntaxForUsageLocationWorker(file: Pick<SourceFile, "fileName" |
}
/** @internal */
export function getResolutionModeOverride(node: ImportAttributes | undefined, grammarErrorOnNode?: (node: Node, diagnostic: DiagnosticMessage) => void) {
export function getResolutionModeOverride(node: ImportAttributes | undefined, grammarErrorOnNode?: (node: Node, diagnostic: DiagnosticMessage) => void): ResolutionMode | undefined {
if (!node) return undefined;
if (length(node.elements) !== 1) {
grammarErrorOnNode?.(
@ -1182,13 +1193,13 @@ function forEachProjectReference<T>(
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 +1404,7 @@ export function getImpliedNodeFormatForFileWorker(
packageJsonInfoCache: PackageJsonInfoCache | undefined,
host: ModuleResolutionHost,
options: CompilerOptions,
) {
): ResolutionMode | Partial<CreateSourceFileOptions> | undefined {
const moduleResolution = getEmitModuleResolutionKind(options);
const shouldLookupFromPackageJson = ModuleResolutionKind.Node16 <= moduleResolution && moduleResolution <= ModuleResolutionKind.NodeNext
|| pathContainsNodeModules(fileName);

Просмотреть файл

@ -303,7 +303,7 @@ function perceivedOsRootLengthForWatching(pathComponents: Readonly<PathPathCompo
*
* @internal
*/
export function canWatchDirectoryOrFile(pathComponents: Readonly<PathPathComponents>, length?: number) {
export function canWatchDirectoryOrFile(pathComponents: Readonly<PathPathComponents>, length?: number): boolean {
if (length === undefined) length = pathComponents.length;
// Ignore "/", "c:/"
// ignore "/user", "c:/users" or "c:/folderAtRoot"
@ -313,12 +313,12 @@ export function canWatchDirectoryOrFile(pathComponents: Readonly<PathPathCompone
}
/** @internal */
export function canWatchDirectoryOrFilePath(path: Path) {
export function canWatchDirectoryOrFilePath(path: Path): boolean {
return canWatchDirectoryOrFile(getPathComponents(path));
}
/** @internal */
export function canWatchAtTypes(atTypes: Path) {
export function canWatchAtTypes(atTypes: Path): boolean {
// Otherwise can watch directory only if we can watch the parent directory of node_modules/@types
return canWatchAffectedPackageJsonOrNodeModulesOfAtTypes(getDirectoryPath(atTypes));
}
@ -336,7 +336,7 @@ function canWatchAffectedPackageJsonOrNodeModulesOfAtTypes(fileOrDirPath: Path)
}
/** @internal */
export function canWatchAffectingLocation(filePath: Path) {
export function canWatchAffectingLocation(filePath: Path): boolean {
return canWatchAffectedPackageJsonOrNodeModulesOfAtTypes(filePath);
}
@ -491,7 +491,7 @@ export function getDirectoryToWatchFailedLookupLocationFromTypeRoot(
}
/** @internal */
export function getRootDirectoryOfResolutionCache(rootDirForResolution: string, getCurrentDirectory: () => string | undefined) {
export function getRootDirectoryOfResolutionCache(rootDirForResolution: string, getCurrentDirectory: () => string | undefined): string {
const normalized = getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory());
return !isDiskPathRoot(normalized) ?
removeTrailingDirectorySeparator(normalized) :

Просмотреть файл

@ -21,6 +21,7 @@ import {
KeywordSyntaxKind,
LanguageFeatureMinimumTarget,
LanguageVariant,
LanugageFeatures,
LineAndCharacter,
MapLike,
parsePseudoBigInt,
@ -295,7 +296,7 @@ const charCodeToRegExpFlag = new Map<CharacterCodes, RegularExpressionFlags>([
[CharacterCodes.y, RegularExpressionFlags.Sticky],
]);
const regExpFlagToFirstAvailableLanguageVersion = new Map<RegularExpressionFlags, LanguageFeatureMinimumTarget>([
const regExpFlagToFirstAvailableLanguageVersion = new Map<RegularExpressionFlags, typeof LanguageFeatureMinimumTarget[LanugageFeatures]>([
[RegularExpressionFlags.HasIndices, LanguageFeatureMinimumTarget.RegularExpressionFlagsHasIndices],
[RegularExpressionFlags.DotAll, LanguageFeatureMinimumTarget.RegularExpressionFlagsDotAll],
[RegularExpressionFlags.Unicode, LanguageFeatureMinimumTarget.RegularExpressionFlagsUnicode],
@ -384,7 +385,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 +516,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 +533,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 +940,11 @@ export function forEachTrailingCommentRange<T, U>(text: string, pos: number, cb:
return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ true, cb, state!);
}
export function reduceEachLeadingCommentRange<T, U>(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T, initial: U) {
export function reduceEachLeadingCommentRange<T, U>(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<T, U>(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T, initial: U) {
export function reduceEachTrailingCommentRange<T, U>(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 +1018,15 @@ 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 */
@ -3599,7 +3608,7 @@ export function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean
}
function checkRegularExpressionFlagAvailability(flag: RegularExpressionFlags, size: number) {
const availableFrom = regExpFlagToFirstAvailableLanguageVersion.get(flag) as ScriptTarget | undefined;
const availableFrom = regExpFlagToFirstAvailableLanguageVersion.get(flag);
if (availableFrom && languageVersion < availableFrom) {
error(Diagnostics.This_regular_expression_flag_is_only_available_when_targeting_0_or_later, pos, size, getNameOfScriptTarget(availableFrom));
}
@ -4053,7 +4062,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);
}

Просмотреть файл

@ -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);
}
}

Просмотреть файл

@ -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<T extends Mapping>(left: T, right: T) {
export function sameMapping<T extends Mapping>(left: T, right: T): boolean {
return left === right
|| left.generatedLine === right.generatedLine
&& left.generatedCharacter === right.generatedCharacter

Просмотреть файл

@ -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 {

Просмотреть файл

@ -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<System["getModifiedTime"]>; }, fileName: string) {
export function getModifiedTime(host: { getModifiedTime: NonNullable<System["getModifiedTime"]>; }, fileName: string): Date {
return host.getModifiedTime(fileName) || missingFileModifiedTime;
}
@ -128,7 +128,7 @@ 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: { [K in PollingInterval]: number; } = createPollingIntervalBasedLevels(defaultChunkLevels);
function setCustomPollingValues(system: System) {
if (!system.getEnvironmentVariable) {
@ -550,7 +550,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 +559,17 @@ export function getFileWatcherEventKind(oldTime: number, newTime: number) {
}
/** @internal */
export const ignoredPaths = ["/node_modules/.", "/.git", "/.#"];
export const ignoredPaths: readonly 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 +1375,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 +1997,7 @@ export let sys: System = (() => {
})();
/** @internal @knipignore */
export function setSys(s: System) {
export function setSys(s: System): void {
sys = s;
}

Просмотреть файл

@ -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 {

Просмотреть файл

@ -222,12 +222,12 @@ function wrapDeclarationTransformerFactory(transformer: TransformerFactory<Bundl
}
/** @internal */
export function noEmitSubstitution(_hint: EmitHint, node: Node) {
export function noEmitSubstitution(_hint: EmitHint, node: Node): Node {
return node;
}
/** @internal */
export function noEmitNotification(hint: EmitHint, node: Node, callback: (hint: EmitHint, node: Node) => void) {
export function noEmitNotification(hint: EmitHint, node: Node, callback: (hint: EmitHint, node: Node) => void): void {
callback(hint, node);
}

Просмотреть файл

@ -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);
}

Просмотреть файл

@ -196,6 +196,7 @@ import {
SymbolTracker,
SyntaxKind,
TransformationContext,
Transformer,
transformNodes,
tryCast,
TypeAliasDeclaration,
@ -253,7 +254,7 @@ const declarationEmitInternalNodeBuilderFlags = InternalNodeBuilderFlags.AllowUn
*
* @internal
*/
export function transformDeclarations(context: TransformationContext) {
export function transformDeclarations(context: TransformationContext): Transformer<SourceFile | Bundle> {
const throwDiagnostic = () => Debug.fail("Diagnostic emitted without context");
let getSymbolAccessibilityDiagnostic: GetSymbolAccessibilityDiagnostic = throwDiagnostic;
let needsDeclare = true;
@ -436,10 +437,7 @@ export function transformDeclarations(context: TransformationContext) {
return result;
}
function transformRoot(node: Bundle): Bundle;
function transformRoot(node: SourceFile): SourceFile;
function transformRoot(node: SourceFile | Bundle): SourceFile | Bundle;
function transformRoot(node: SourceFile | Bundle) {
function transformRoot(node: SourceFile | Bundle): SourceFile | Bundle {
if (node.kind === SyntaxKind.SourceFile && node.isDeclarationFile) {
return node;
}

Просмотреть файл

@ -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,

Просмотреть файл

@ -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);

Просмотреть файл

@ -10,11 +10,12 @@ import {
SyntaxKind,
TransformationContext,
transformECMAScriptModule,
Transformer,
transformModule,
} from "../../_namespaces/ts.js";
/** @internal */
export function transformImpliedNodeFormatDependentModule(context: TransformationContext) {
export function transformImpliedNodeFormatDependentModule(context: TransformationContext): Transformer<SourceFile | Bundle> {
const previousOnSubstituteNode = context.onSubstituteNode;
const previousOnEmitNode = context.onEmitNode;

Просмотреть файл

@ -190,6 +190,7 @@ import {
takeWhile,
TextRange,
TransformationContext,
Transformer,
TransformFlags,
VariableDeclaration,
VariableStatement,
@ -231,7 +232,7 @@ const enum ClassFacts {
}
/** @internal */
export function transformTypeScript(context: TransformationContext) {
export function transformTypeScript(context: TransformationContext): Transformer<SourceFile | Bundle> {
const {
factory,
getEmitHelperFactory: emitHelpers,

Просмотреть файл

@ -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<V>(map: V[][], key: number, value: V): V[] {
export class IdentifierNameMap<V> {
private readonly _map = new Map<string, V>();
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<V> {
this._map.clear();
}
values() {
values(): MapIterator<V> {
return this._map.values();
}
@ -460,7 +460,7 @@ class IdentifierNameMultiMap<V> extends IdentifierNameMap<V[]> {
*
* @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<Statement>, sta
*
* @internal
*/
export function findSuperStatementIndexPath(statements: NodeArray<Statement>, start: number) {
export function findSuperStatementIndexPath(statements: NodeArray<Statement>, start: number): number[] {
const indices: number[] = [];
findSuperStatementIndexPathWorker(statements, start, indices);
return indices;
@ -821,7 +821,7 @@ export function newPrivateEnvironment<TData, TEntry>(data: TData): PrivateEnviro
export function getPrivateIdentifier<TData, TEntry>(
privateEnv: PrivateEnvironment<TData, TEntry> | 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<TData, TEntry>(
privateEnv: PrivateEnvironment<TData, TEntry>,
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<TEnvData, TPrivateEnvData, TPrivateEntry> | 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<ParameterDeclaration>) {
export function isSimpleParameterList(nodes: NodeArray<ParameterDeclaration>): boolean {
return every(nodes, isSimpleParameter);
}

Просмотреть файл

@ -4,6 +4,7 @@ import {
assertType,
BuilderProgram,
BuildInfo,
BuildInfoFileVersionMap,
CancellationToken,
canJsonReportNoInputFiles,
changeCompilerHostLikeToUseCache,
@ -301,13 +302,25 @@ function createSolutionBuilderHostBase<T extends BuilderProgram>(system: System,
return host;
}
export function createSolutionBuilderHost<T extends BuilderProgram = EmitAndSemanticDiagnosticsBuilderProgram>(system = sys, createProgram?: CreateProgram<T>, reportDiagnostic?: DiagnosticReporter, reportSolutionBuilderStatus?: DiagnosticReporter, reportErrorSummary?: ReportEmitErrorSummary) {
export function createSolutionBuilderHost<T extends BuilderProgram = EmitAndSemanticDiagnosticsBuilderProgram>(
system: System = sys,
createProgram?: CreateProgram<T>,
reportDiagnostic?: DiagnosticReporter,
reportSolutionBuilderStatus?: DiagnosticReporter,
reportErrorSummary?: ReportEmitErrorSummary,
): SolutionBuilderHost<T> {
const host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus) as SolutionBuilderHost<T>;
host.reportErrorSummary = reportErrorSummary;
return host;
}
export function createSolutionBuilderWithWatchHost<T extends BuilderProgram = EmitAndSemanticDiagnosticsBuilderProgram>(system = sys, createProgram?: CreateProgram<T>, reportDiagnostic?: DiagnosticReporter, reportSolutionBuilderStatus?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter) {
export function createSolutionBuilderWithWatchHost<T extends BuilderProgram = EmitAndSemanticDiagnosticsBuilderProgram>(
system: System = sys,
createProgram?: CreateProgram<T>,
reportDiagnostic?: DiagnosticReporter,
reportSolutionBuilderStatus?: DiagnosticReporter,
reportWatchStatus?: WatchStatusReporter,
): SolutionBuilderWithWatchHost<T> {
const host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus) as SolutionBuilderWithWatchHost<T>;
const watchHost = createWatchHost(system, reportWatchStatus);
copyProperties(host, watchHost);
@ -1601,7 +1614,7 @@ function getUpToDateStatusWorker<T extends BuilderProgram>(state: SolutionBuilde
/** True if input file has changed timestamp but text is not changed, we can then do only timestamp updates on output to make it look up-to-date later */
let pseudoInputUpToDate = false;
const seenRoots = new Set<Path>();
let buildInfoVersionMap: ReturnType<typeof getBuildInfoFileVersionMap> | undefined;
let buildInfoVersionMap: BuildInfoFileVersionMap | undefined;
// Get timestamps of input files
for (const inputFile of project.fileNames) {
const inputTime = getModifiedTime(state, inputFile);

Просмотреть файл

@ -8334,69 +8334,98 @@ export type EmitHelper = ScopedEmitHelper | UnscopedEmitHelper;
export type EmitHelperUniqueNameCallback = (name: string) => string;
/** @internal */
export type LanugageFeatures =
// ES2015 Features
| "Classes"
| "ForOf"
| "Generators"
| "Iteration"
| "SpreadElements"
| "RestElements"
| "TaggedTemplates"
| "DestructuringAssignment"
| "BindingPatterns"
| "ArrowFunctions"
| "BlockScopedVariables"
| "ObjectAssign"
| "RegularExpressionFlagsUnicode"
| "RegularExpressionFlagsSticky"
// ES2016 Features
| "Exponentiation" // `x ** y`
// ES2017 Features
| "AsyncFunctions" // `async function f() {}`
// ES2018 Features
| "ForAwaitOf" // `for await (const x of y)`
| "AsyncGenerators" // `async function * f() { }`
| "AsyncIteration" // `Symbol.asyncIterator`
| "ObjectSpreadRest" // `{ ...obj }`
| "RegularExpressionFlagsDotAll"
// ES2019 Features
| "BindinglessCatch" // `try { } catch { }`
// ES2020 Features
| "BigInt" // `0n`
| "NullishCoalesce" // `a ?? b`
| "OptionalChaining" // `a?.b`
// ES2021 Features
| "LogicalAssignment" // `a ||= b`| `a &&= b`| `a ??= b`
// ES2022 Features
| "TopLevelAwait"
| "ClassFields"
| "PrivateNamesAndClassStaticBlocks" // `class C { static {} #x = y| #m() {} }`| `#x in y`
| "RegularExpressionFlagsHasIndices"
// ES2023 Features
| "ShebangComments"
// 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"
| "ClassAndClassElementDecorators" // `using x = y`, `await using x = y`
| "RegularExpressionFlagsUnicodeSets" // `@dec class C {}`, `class C { @dec m() {} }`
;
/**
* Indicates the minimum `ScriptTarget` (inclusive) after which a specific language feature is no longer transpiled.
*
* @internal
*/
export const enum LanguageFeatureMinimumTarget {
// 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,
// ES2016 Features
Exponentiation = ScriptTarget.ES2016, // `x ** y`
// ES2017 Features
AsyncFunctions = ScriptTarget.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,
// ES2019 Features
BindinglessCatch = ScriptTarget.ES2019, // `try { } catch { }`
// ES2020 Features
BigInt = ScriptTarget.ES2020, // `0n`
NullishCoalesce = ScriptTarget.ES2020, // `a ?? b`
OptionalChaining = ScriptTarget.ES2020, // `a?.b`
// ES2021 Features
LogicalAssignment = ScriptTarget.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,
// ES2023 Features
ShebangComments = ScriptTarget.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,
}
export const LanguageFeatureMinimumTarget: Record<LanugageFeatures, ScriptTarget> = {
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,
Exponentiation: ScriptTarget.ES2016,
AsyncFunctions: ScriptTarget.ES2017,
ForAwaitOf: ScriptTarget.ES2018,
AsyncGenerators: ScriptTarget.ES2018,
AsyncIteration: ScriptTarget.ES2018,
ObjectSpreadRest: ScriptTarget.ES2018,
RegularExpressionFlagsDotAll: ScriptTarget.ES2018,
BindinglessCatch: ScriptTarget.ES2019,
BigInt: ScriptTarget.ES2020,
NullishCoalesce: ScriptTarget.ES2020,
OptionalChaining: ScriptTarget.ES2020,
LogicalAssignment: ScriptTarget.ES2021,
TopLevelAwait: ScriptTarget.ES2022,
ClassFields: ScriptTarget.ES2022,
PrivateNamesAndClassStaticBlocks: ScriptTarget.ES2022,
RegularExpressionFlagsHasIndices: ScriptTarget.ES2022,
ShebangComments: ScriptTarget.ESNext,
UsingAndAwaitUsing: ScriptTarget.ESNext,
ClassAndClassElementDecorators: ScriptTarget.ESNext,
RegularExpressionFlagsUnicodeSets: ScriptTarget.ESNext,
};
// dprint-ignore
/**
@ -9664,6 +9693,12 @@ export interface BuildInfo {
version: string;
}
/** @internal */
export interface BuildInfoFileVersionMap {
fileInfos: Map<Path, string>;
roots: Map<Path, Path | undefined>;
}
export interface PrintHandlers {
/**
* A hook used by the Printer when generating unique names to avoid collisions with
@ -10093,7 +10128,7 @@ export interface PragmaDefinition<T1 extends string = string, T2 extends string
// While not strictly a type, this is here because `PragmaMap` needs to be here to be used with `SourceFile`, and we don't
// fancy effectively defining it twice, once in value-space and once in type-space
/** @internal */
export const commentPragmas = {
export const commentPragmas: ConcretePragmaSpecs = {
"reference": {
args: [
{ name: "types", optional: true, captureSpan: true },
@ -10189,7 +10224,78 @@ export type PragmaArgumentType<KPrag extends keyof ConcretePragmaSpecs> = Concre
: never;
/** @internal */
export type ConcretePragmaSpecs = typeof commentPragmas;
export interface ConcretePragmaSpecs {
readonly "reference": {
readonly args: readonly [{
readonly name: "types";
readonly optional: true;
readonly captureSpan: true;
}, {
readonly name: "lib";
readonly optional: true;
readonly captureSpan: true;
}, {
readonly name: "path";
readonly optional: true;
readonly captureSpan: true;
}, {
readonly name: "no-default-lib";
readonly optional: true;
}, {
readonly name: "resolution-mode";
readonly optional: true;
}, {
readonly name: "preserve";
readonly optional: true;
}];
readonly kind: PragmaKindFlags.TripleSlashXML;
};
readonly "amd-dependency": {
readonly args: readonly [{
readonly name: "path";
}, {
readonly name: "name";
readonly optional: true;
}];
readonly kind: PragmaKindFlags.TripleSlashXML;
};
readonly "amd-module": {
readonly args: readonly [{
readonly name: "name";
}];
readonly kind: PragmaKindFlags.TripleSlashXML;
};
readonly "ts-check": {
readonly kind: PragmaKindFlags.SingleLine;
};
readonly "ts-nocheck": {
readonly kind: PragmaKindFlags.SingleLine;
};
readonly "jsx": {
readonly args: readonly [{
readonly name: "factory";
}];
readonly kind: PragmaKindFlags.MultiLine;
};
readonly "jsxfrag": {
readonly args: readonly [{
readonly name: "factory";
}];
readonly kind: PragmaKindFlags.MultiLine;
};
readonly "jsximportsource": {
readonly args: readonly [{
readonly name: "factory";
}];
readonly kind: PragmaKindFlags.MultiLine;
};
readonly "jsxruntime": {
readonly args: readonly [{
readonly name: "factory";
}];
readonly kind: PragmaKindFlags.MultiLine;
};
}
/** @internal */
export type PragmaPseudoMap = { [K in keyof ConcretePragmaSpecs]: { arguments: PragmaArgumentType<K>; range: CommentRange; }; };
@ -10410,3 +10516,11 @@ export interface SyntacticTypeNodeBuilderResolver {
requiresAddingImplicitUndefined(parameter: ParameterDeclaration | JSDocParameterTag, enclosingDeclaration: Node | undefined): boolean;
isDefinitelyReferenceToGlobalSymbolObject(node: Node): boolean;
}
/** @internal */
export interface SyntacticNodeBuilder {
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;
}

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -304,7 +304,7 @@ export function sortAndDeduplicateDiagnostics<T extends Diagnostic>(diagnostics:
}
/** @internal */
export const targetToLibMap = new Map<ScriptTarget, string>([
export const targetToLibMap: Map<ScriptTarget, string> = new Map([
[ScriptTarget.ESNext, "lib.esnext.full.d.ts"],
[ScriptTarget.ES2023, "lib.es2023.full.d.ts"],
[ScriptTarget.ES2022, "lib.es2022.full.d.ts"],
@ -336,15 +336,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);
}
@ -354,21 +354,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;
}
@ -445,15 +445,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;
}
@ -465,7 +465,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
@ -675,7 +675,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 = ["cs", "de", "es", "fr", "it", "ja", "ko", "pl", "pt-br", "ru", "tr", "zh-cn", "zh-tw"] as const;
/**
* Checks to see if the locale is in the appropriate format,
@ -685,7 +685,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);
@ -919,7 +919,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;
}
@ -1282,7 +1282,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<JSDocComment>) {
export function getTextOfJSDocComment(comment?: string | NodeArray<JSDocComment>): string | undefined {
return typeof comment === "string" ? comment
: comment?.map(c => c.kind === SyntaxKind.JSDocText ? c.text : formatJSDocLink(c)).join("");
}
@ -1404,17 +1404,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;
}
@ -1450,7 +1450,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;
}
@ -1491,7 +1491,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:
@ -1574,7 +1574,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)
@ -2118,17 +2118,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);
}
@ -2576,7 +2576,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) {
@ -2621,7 +2621,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) {

Просмотреть файл

@ -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<Statement>, visitor: Visitor, context: TransformationContext, start?: number, ensureUseStrict?: boolean, nodesVisitor: NodesVisitor = visitNodes) {
export function visitLexicalEnvironment(statements: NodeArray<Statement>, visitor: Visitor, context: TransformationContext, start?: number, ensureUseStrict?: boolean, nodesVisitor: NodesVisitor = visitNodes): NodeArray<Statement> {
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<Expression>, visitor: Visitor, discardVisitor = visitor): NodeArray<Expression> {
export function visitCommaListElements(elements: NodeArray<Expression>, visitor: Visitor, discardVisitor: Visitor = visitor): NodeArray<Expression> {
if (discardVisitor === visitor || elements.length <= 1) {
return visitNodes(elements, visitor, isExpression);
}

Просмотреть файл

@ -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<T extends BuilderProgram>(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<T extends BuilderProgra
cancellationToken?: CancellationToken,
emitOnlyDtsFiles?: boolean,
customTransformers?: CustomTransformers,
) {
): ExitStatus {
const { emitResult, diagnostics } = emitFilesAndReportErrors(
program,
reportDiagnostic,
@ -666,10 +666,10 @@ export function emitFilesAndReportErrorsAndGetExitStatus<T extends BuilderProgra
/** @internal */
export const noopFileWatcher: FileWatcher = { close: noop };
/** @internal */
export const returnNoopFileWatcher = () => 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<X, Y = undefined> extends WatchFactory<X, Y
}
/** @internal */
export function createWatchFactory<Y = undefined>(host: WatchFactoryHost & { trace?(s: string): void; }, options: { extendedDiagnostics?: boolean; diagnostics?: boolean; }) {
export function createWatchFactory<Y = undefined>(host: WatchFactoryHost & { trace?(s: string): void; }, options: { extendedDiagnostics?: boolean; diagnostics?: boolean; }): WatchFactoryWithLog<WatchType, Y> {
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<WatchType, Y>(host, watchLogLevel, writeLog) as WatchFactoryWithLog<WatchType, Y>;
@ -784,7 +784,7 @@ export function createCompilerHostFromProgramHost(host: ProgramHost<any>, getCom
}
/** @internal */
export function getSourceFileVersionAsHashFromText(host: Pick<CompilerHost, "createHash">, text: string) {
export function getSourceFileVersionAsHashFromText(host: Pick<CompilerHost, "createHash">, 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<CompilerHost, "cre
}
/** @internal */
export function setGetSourceFileAsHashVersioned(compilerHost: CompilerHost) {
export function setGetSourceFileAsHashVersioned(compilerHost: CompilerHost): void {
const originalGetSourceFile = compilerHost.getSourceFile;
compilerHost.getSourceFile = (...args) => {
const result = originalGetSourceFile.call(compilerHost, ...args);
@ -981,8 +981,9 @@ export interface IncrementalCompilationOptions {
afterProgramEmitAndDiagnostics?(program: EmitAndSemanticDiagnosticsBuilderProgram): void;
system?: System;
}
/** @internal */
export function performIncrementalCompilation(input: IncrementalCompilationOptions) {
export function performIncrementalCompilation(input: IncrementalCompilationOptions): ExitStatus {
const system = input.system || sys;
const host = input.host || (input.host = createIncrementalCompilerHost(input.options, system));
const builderProgram = createIncrementalProgram(input);

Просмотреть файл

@ -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;

Просмотреть файл

@ -410,7 +410,7 @@ export function updateSharedExtendedConfigFileWatcher<T>(
extendedConfigFilesMap: Map<Path, SharedExtendedConfigFileWatcher<T>>,
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<T>(
export function clearSharedExtendedConfigFileWatcher<T>(
projectPath: T,
extendedConfigFilesMap: Map<Path, SharedExtendedConfigFileWatcher<T>>,
) {
): void {
extendedConfigFilesMap.forEach(watcher => {
if (watcher.projects.delete(projectPath)) watcher.close();
});
@ -464,7 +464,7 @@ export function cleanExtendedConfigCache(
extendedConfigCache: Map<string, ExtendedConfigCacheEntry>,
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<Path, FileWatcher>,
createMissingFileWatch: (missingFilePath: Path, missingFileName: string) => FileWatcher,
) {
): void {
// Update the missing file paths watcher
mutateMap(
missingFileWatches,
@ -515,7 +515,7 @@ export function updateWatchingWildcardDirectories<T extends FileWatcher>(
existingWatchedForWildcards: Map<string, WildcardDirectoryWatcher<T>>,
wildcardDirectories: MapLike<WatchDirectoryFlags> | 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<T extends { watcher: FileWatcher; }>(objWithWatcher: T) {
export function closeFileWatcherOf<T extends { watcher: FileWatcher; }>(objWithWatcher: T): void {
objWithWatcher.watcher.close();
}

Просмотреть файл

@ -9,7 +9,7 @@ import {
export let enableDeprecationWarnings = true;
export function setEnableDeprecationWarnings(value: boolean) {
export function setEnableDeprecationWarnings(value: boolean): void {
enableDeprecationWarnings = value;
}

Просмотреть файл

@ -40,6 +40,7 @@ import {
JSDocTagInfo,
LanguageService,
LanguageServiceHost,
LineAndCharacter,
map,
mapOneOrMany,
NavigateToItem,
@ -203,7 +204,7 @@ export class SessionClient implements LanguageService {
}
/** @internal */
configure(preferences: UserPreferences) {
configure(preferences: UserPreferences): void {
this.preferences = preferences;
const args: protocol.ConfigureRequestArguments = { preferences };
const request = this.processRequest(protocol.CommandTypes.Configure, args);
@ -211,14 +212,14 @@ export class SessionClient implements LanguageService {
}
/** @internal */
setFormattingOptions(formatOptions: FormatCodeSettings) {
setFormattingOptions(formatOptions: FormatCodeSettings): void {
const args: protocol.ConfigureRequestArguments = { formatOptions };
const request = this.processRequest(protocol.CommandTypes.Configure, args);
this.processResponse(request, /*expectEmptyBody*/ true);
}
/** @internal */
setCompilerOptionsForInferredProjects(options: protocol.CompilerOptions) {
setCompilerOptionsForInferredProjects(options: protocol.CompilerOptions): void {
const args: protocol.SetCompilerOptionsForInferredProjectsArgs = { options };
const request = this.processRequest(protocol.CommandTypes.CompilerOptionsForInferredProjects, args);
this.processResponse(request, /*expectEmptyBody*/ false);
@ -247,7 +248,7 @@ export class SessionClient implements LanguageService {
this.processResponse(request, /*expectEmptyBody*/ true);
}
toLineColumnOffset(fileName: string, position: number) {
toLineColumnOffset(fileName: string, position: number): LineAndCharacter {
const { line, offset } = this.positionToOneBasedLineOffset(fileName, position);
return { line, character: offset };
}
@ -580,7 +581,7 @@ export class SessionClient implements LanguageService {
return renameInfo;
}
getSmartSelectionRange() {
getSmartSelectionRange(): never {
return notImplemented();
}
@ -766,9 +767,9 @@ export class SessionClient implements LanguageService {
({ fixName, description, changes: this.convertChanges(changes, file), commands: commands as CodeActionCommand[], fixId, fixAllDescription }));
}
getCombinedCodeFix = notImplemented;
getCombinedCodeFix: typeof notImplemented = notImplemented;
applyCodeActionCommand = notImplemented;
applyCodeActionCommand: typeof notImplemented = notImplemented;
provideInlayHints(file: string, span: TextSpan): InlayHint[] {
const { start, length } = span;
@ -796,7 +797,7 @@ export class SessionClient implements LanguageService {
});
}
mapCode = notImplemented;
mapCode: typeof notImplemented = notImplemented;
private createFileLocationOrRangeRequestArgs(positionOrRange: number | TextRange, fileName: string): protocol.FileLocationOrRangeRequestArgs {
return typeof positionOrRange === "number"
@ -902,7 +903,7 @@ export class SessionClient implements LanguageService {
return notImplemented();
}
getEditsForFileRename() {
getEditsForFileRename(): never {
return notImplemented();
}
@ -992,7 +993,7 @@ export class SessionClient implements LanguageService {
};
}
provideCallHierarchyIncomingCalls(fileName: string, position: number) {
provideCallHierarchyIncomingCalls(fileName: string, position: number): CallHierarchyIncomingCall[] {
const args = this.createFileLocationRequestArgs(fileName, position);
const request = this.processRequest<protocol.ProvideCallHierarchyIncomingCallsRequest>(protocol.CommandTypes.ProvideCallHierarchyIncomingCalls, args);
const response = this.processResponse<protocol.ProvideCallHierarchyIncomingCallsResponse>(request);
@ -1006,7 +1007,7 @@ export class SessionClient implements LanguageService {
};
}
provideCallHierarchyOutgoingCalls(fileName: string, position: number) {
provideCallHierarchyOutgoingCalls(fileName: string, position: number): CallHierarchyOutgoingCall[] {
const args = this.createFileLocationRequestArgs(fileName, position);
const request = this.processRequest<protocol.ProvideCallHierarchyOutgoingCallsRequest>(protocol.CommandTypes.ProvideCallHierarchyOutgoingCalls, args);
const response = this.processResponse<protocol.ProvideCallHierarchyOutgoingCallsResponse>(request);

Просмотреть файл

@ -23,11 +23,11 @@ export class SortedMap<K, V> {
}
}
public get size() {
public get size(): number {
return this._keys.length;
}
public get comparer() {
public get comparer(): (a: K, b: K) => number {
return this._comparer;
}
@ -35,11 +35,11 @@ export class SortedMap<K, V> {
return "SortedMap";
}
public has(key: K) {
public has(key: K): boolean {
return ts.binarySearch(this._keys, key, ts.identity, this._comparer) >= 0;
}
public get(key: K) {
public get(key: K): V | undefined {
const index = ts.binarySearch(this._keys, key, ts.identity, this._comparer);
return index >= 0 ? this._values[index] : undefined;
}
@ -49,7 +49,7 @@ export class SortedMap<K, V> {
return index >= 0 ? [this._keys[index], this._values[index]] : undefined;
}
public set(key: K, value: V) {
public set(key: K, value: V): this {
const index = ts.binarySearch(this._keys, key, ts.identity, this._comparer);
if (index >= 0) {
this._values[index] = value;
@ -64,7 +64,7 @@ export class SortedMap<K, V> {
return this;
}
public delete(key: K) {
public delete(key: K): boolean {
const index = ts.binarySearch(this._keys, key, ts.identity, this._comparer);
if (index >= 0) {
this.writePreamble();
@ -77,7 +77,7 @@ export class SortedMap<K, V> {
return false;
}
public clear() {
public clear(): void {
if (this.size > 0) {
this.writePreamble();
this._keys.length = 0;
@ -87,7 +87,7 @@ export class SortedMap<K, V> {
}
}
public forEach(callback: (value: V, key: K, collection: this) => void, thisArg?: any) {
public forEach(callback: (value: V, key: K, collection: this) => void, thisArg?: any): void {
const keys = this._keys;
const values = this._values;
const indices = this.getIterationOrder();
@ -112,7 +112,7 @@ export class SortedMap<K, V> {
}
}
public *keys() {
public *keys(): Generator<K, undefined, unknown> {
const keys = this._keys;
const indices = this.getIterationOrder();
const version = this._version;
@ -135,7 +135,7 @@ export class SortedMap<K, V> {
return undefined;
}
public *values() {
public *values(): Generator<V, undefined, unknown> {
const values = this._values;
const indices = this.getIterationOrder();
const version = this._version;
@ -158,7 +158,7 @@ export class SortedMap<K, V> {
return undefined;
}
public *entries() {
public *entries(): Generator<[K, V], undefined, unknown> {
const keys = this._keys;
const values = this._values;
const indices = this.getIterationOrder();
@ -184,7 +184,7 @@ export class SortedMap<K, V> {
return undefined;
}
public [Symbol.iterator]() {
public [Symbol.iterator](): Generator<[K, V], undefined, unknown> {
return this.entries();
}
@ -255,7 +255,7 @@ export class Metadata {
return this._size;
}
public get parent() {
public get parent(): Metadata | undefined {
return this._parent;
}
@ -292,7 +292,7 @@ export class Metadata {
this._version++;
}
public forEach(callback: (value: any, key: string, map: this) => void) {
public forEach(callback: (value: any, key: string, map: this) => void): void {
for (const key in this._map) {
callback(this._map[key], Metadata._unescapeKey(key), this);
}

Просмотреть файл

@ -225,7 +225,7 @@ export class CompilationResult {
return vpath.changeExtension(path, ext);
}
public getNumberOfJsFiles(includeJson: boolean) {
public getNumberOfJsFiles(includeJson: boolean): number {
if (includeJson) {
return this.js.size;
}

Просмотреть файл

@ -22,7 +22,7 @@ export class TextDocument {
return this._lineStarts || (this._lineStarts = ts.computeLineStarts(this.text));
}
public static fromTestFile(file: Harness.Compiler.TestFile) {
public static fromTestFile(file: Harness.Compiler.TestFile): TextDocument {
return new TextDocument(
file.unitName,
file.content,
@ -31,7 +31,7 @@ export class TextDocument {
);
}
public asTestFile() {
public asTestFile(): Harness.Compiler.TestFile {
return this._testFile || (this._testFile = {
unitName: this.file,
content: this.text,
@ -140,7 +140,7 @@ export class SourceMap {
this.mappings = mappings;
}
public static getUrl(text: string) {
public static getUrl(text: string): string | undefined {
let match: RegExpExecArray | null; // eslint-disable-line no-restricted-syntax
let lastMatch: RegExpExecArray | undefined;
while (match = SourceMap._sourceMappingURLRegExp.exec(text)) {
@ -149,7 +149,7 @@ export class SourceMap {
return lastMatch ? lastMatch[1] : undefined;
}
public static fromUrl(url: string) {
public static fromUrl(url: string): SourceMap | undefined {
const match = SourceMap._dataURLRegExp.exec(url);
return match ? new SourceMap(/*mapFile*/ undefined, ts.sys.base64decode!(match[1])) : undefined;
}

Просмотреть файл

@ -33,7 +33,7 @@ for (const symbolName of symbolNames) {
}
}
export function evaluateTypeScript(source: string | { files: vfs.FileSet; rootFiles: string[]; main: string; }, options?: ts.CompilerOptions, globals?: Record<string, any>) {
export function evaluateTypeScript(source: string | { files: vfs.FileSet; rootFiles: string[]; main: string; }, options?: ts.CompilerOptions, globals?: Record<string, any>): any {
if (typeof source === "string") source = { files: { [sourceFile]: source }, rootFiles: [sourceFile], main: sourceFile };
const fs = vfs.createFromFileSystem(Harness.IO, /*ignoreCase*/ false, { files: source.files });
const compilerOptions: ts.CompilerOptions = {
@ -62,7 +62,7 @@ export function evaluateTypeScript(source: string | { files: vfs.FileSet; rootFi
return loader.import(output.file);
}
export function evaluateJavaScript(sourceText: string, globals?: Record<string, any>, sourceFile = sourceFileJs) {
export function evaluateJavaScript(sourceText: string, globals?: Record<string, any>, sourceFile: string = sourceFileJs): any {
globals = { Symbol: FakeSymbol, ...globals };
const fs = new vfs.FileSystem(/*ignoreCase*/ false, { files: { [sourceFile]: sourceText } });
return new CommonJsLoader(fs, globals).import(sourceFile);

Просмотреть файл

@ -41,19 +41,19 @@ export class System implements ts.System {
}
private testTerminalWidth = Number.parseInt(this.getEnvironmentVariable("TS_TEST_TERMINAL_WIDTH"));
getWidthOfTerminal = Number.isNaN(this.testTerminalWidth) ? undefined : () => this.testTerminalWidth;
getWidthOfTerminal: (() => number) | undefined = Number.isNaN(this.testTerminalWidth) ? undefined : () => this.testTerminalWidth;
// Pretty output
writeOutputIsTTY() {
return true;
}
public write(message: string) {
public write(message: string): void {
if (ts.Debug.isDebugging) console.log(message);
this.output.push(message);
}
public readFile(path: string) {
public readFile(path: string): string | undefined {
try {
const content = this.vfs.readFileSync(path, "utf8");
return content === undefined ? undefined : Utils.removeByteOrderMark(content);
@ -68,16 +68,16 @@ export class System implements ts.System {
this.vfs.writeFileSync(path, writeByteOrderMark ? Utils.addUTF8ByteOrderMark(data) : data);
}
public deleteFile(path: string) {
public deleteFile(path: string): void {
this.vfs.unlinkSync(path);
}
public fileExists(path: string) {
public fileExists(path: string): boolean {
const stats = this._getStats(path);
return stats ? stats.isFile() : false;
}
public directoryExists(path: string) {
public directoryExists(path: string): boolean {
const stats = this._getStats(path);
return stats ? stats.isDirectory() : false;
}
@ -86,11 +86,11 @@ export class System implements ts.System {
this.vfs.mkdirpSync(path);
}
public getCurrentDirectory() {
public getCurrentDirectory(): string {
return this.vfs.cwd();
}
public getDirectories(path: string) {
public getDirectories(path: string): string[] {
const result: string[] = [];
try {
for (const file of this.vfs.readdirSync(path)) {
@ -128,31 +128,31 @@ export class System implements ts.System {
return { files, directories };
}
public exit(exitCode?: number) {
public exit(exitCode?: number): void {
this.exitCode = exitCode;
throw processExitSentinel;
}
public getFileSize(path: string) {
public getFileSize(path: string): number {
const stats = this._getStats(path);
return stats && stats.isFile() ? stats.size : 0;
}
public resolvePath(path: string) {
public resolvePath(path: string): string {
return vpath.resolve(this.vfs.cwd(), path);
}
public getExecutingFilePath() {
public getExecutingFilePath(): string {
if (this._executingFilePath === undefined) return ts.notImplemented();
return this._executingFilePath;
}
public getModifiedTime(path: string) {
public getModifiedTime(path: string): Date {
const stats = this._getStats(path);
return stats ? stats.mtime : undefined!; // TODO: GH#18217
}
public setModifiedTime(path: string, time: Date) {
public setModifiedTime(path: string, time: Date): void {
try {
this.vfs.utimesSync(path, time, time);
}
@ -163,7 +163,7 @@ export class System implements ts.System {
return `${ts.generateDjb2Hash(data)}-${data}`;
}
public realpath(path: string) {
public realpath(path: string): string {
try {
return this.vfs.realpathSync(path);
}
@ -185,7 +185,7 @@ export class System implements ts.System {
}
}
now() {
now(): Date {
return new Date(this.vfs.time());
}
}
@ -201,11 +201,11 @@ export class ParseConfigHost implements ts.ParseConfigHost {
this.sys = sys;
}
public get vfs() {
public get vfs(): vfs.FileSystem {
return this.sys.vfs;
}
public get useCaseSensitiveFileNames() {
public get useCaseSensitiveFileNames(): boolean {
return this.sys.useCaseSensitiveFileNames;
}
@ -247,7 +247,7 @@ export class CompilerHost implements ts.CompilerHost {
public readonly outputs: documents.TextDocument[] = [];
private readonly _outputsMap: collections.SortedMap<string, number>;
public readonly traces: string[] = [];
public readonly shouldAssertInvariants = !Harness.lightMode;
public readonly shouldAssertInvariants: boolean = !Harness.lightMode;
public readonly jsDocParsingMode: ts.JSDocParsingMode | undefined;
private _setParentNodes: boolean;
@ -255,7 +255,7 @@ export class CompilerHost implements ts.CompilerHost {
private _parseConfigHost: ParseConfigHost | undefined;
private _newLine: string;
constructor(sys: System | vfs.FileSystem, options = ts.getDefaultCompilerOptions(), setParentNodes = false, jsDocParsingMode?: ts.JSDocParsingMode) {
constructor(sys: System | vfs.FileSystem, options: ts.CompilerOptions = ts.getDefaultCompilerOptions(), setParentNodes = false, jsDocParsingMode?: ts.JSDocParsingMode) {
if (sys instanceof vfs.FileSystem) sys = new System(sys);
this.sys = sys;
this.defaultLibLocation = sys.vfs.meta.get("defaultLibLocation") || "";
@ -266,11 +266,11 @@ export class CompilerHost implements ts.CompilerHost {
this.jsDocParsingMode = jsDocParsingMode;
}
public get vfs() {
public get vfs(): vfs.FileSystem {
return this.sys.vfs;
}
public get parseConfigHost() {
public get parseConfigHost(): ParseConfigHost {
return this._parseConfigHost || (this._parseConfigHost = new ParseConfigHost(this.sys));
}
@ -290,7 +290,7 @@ export class CompilerHost implements ts.CompilerHost {
return this.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
}
public deleteFile(fileName: string) {
public deleteFile(fileName: string): void {
this.sys.deleteFile(fileName);
}
@ -302,11 +302,11 @@ export class CompilerHost implements ts.CompilerHost {
return this.sys.directoryExists(directoryName);
}
public getModifiedTime(fileName: string) {
public getModifiedTime(fileName: string): Date {
return this.sys.getModifiedTime(fileName);
}
public setModifiedTime(fileName: string, time: Date) {
public setModifiedTime(fileName: string, time: Date): void {
return this.sys.setModifiedTime(fileName, time);
}
@ -322,7 +322,7 @@ export class CompilerHost implements ts.CompilerHost {
return this.sys.readFile(path);
}
public writeFile(fileName: string, content: string, writeByteOrderMark: boolean) {
public writeFile(fileName: string, content: string, writeByteOrderMark: boolean): void {
if (writeByteOrderMark) content = Utils.addUTF8ByteOrderMark(content);
this.sys.writeFile(fileName, content);

Просмотреть файл

@ -178,7 +178,7 @@ export class TestCancellationToken implements ts.HostCancellationToken {
}
}
export function verifyOperationIsCancelled(f: () => void) {
export function verifyOperationIsCancelled(f: () => void): void {
try {
f();
}
@ -533,7 +533,7 @@ export class TestState {
else this.baselineFromTest.push({ command, actual, ext });
}
baselineTest() {
baselineTest(): void {
if (this.baselineFromTest) {
Harness.Baseline.runBaseline(
this.getBaselineFileNameForContainingTestFile(this.baselineFromTest[0].ext),
@ -542,7 +542,7 @@ export class TestState {
}
}
baselineTsserverLog() {
baselineTsserverLog(): void {
if (this.logger) {
Harness.Baseline.runBaseline(
`tsserver/fourslashServer/${ts.getBaseFileName(this.originalInputFileName).replace(".ts", ".js")}`,
@ -560,7 +560,7 @@ export class TestState {
}
// Entry points from fourslash.ts
public goToMarker(name: string | Marker = "") {
public goToMarker(name: string | Marker = ""): void {
const marker = ts.isString(name) ? this.getMarkerByName(name) : name;
if (this.activeFile.fileName !== marker.fileName) {
this.openFile(marker.fileName);
@ -581,7 +581,7 @@ export class TestState {
this.goToRangeStart(markerOrRange);
}
public goToEachMarker(markers: readonly Marker[], action: (marker: Marker, index: number) => void) {
public goToEachMarker(markers: readonly Marker[], action: (marker: Marker, index: number) => void): void {
assert(markers.length);
for (let i = 0; i < markers.length; i++) {
this.goToMarker(markers[i]);
@ -589,7 +589,7 @@ export class TestState {
}
}
public goToEachRange(action: (range: Range) => void) {
public goToEachRange(action: (range: Range) => void): void {
const ranges = this.getRanges();
assert(ranges.length);
for (const range of ranges) {
@ -606,7 +606,7 @@ export class TestState {
})!;
}
public goToPosition(positionOrLineAndCharacter: number | ts.LineAndCharacter) {
public goToPosition(positionOrLineAndCharacter: number | ts.LineAndCharacter): void {
const pos = typeof positionOrLineAndCharacter === "number"
? positionOrLineAndCharacter
: this.languageServiceAdapterHost.lineAndCharacterToPosition(this.activeFile.fileName, positionOrLineAndCharacter);
@ -614,7 +614,7 @@ export class TestState {
this.selectionEnd = -1;
}
public select(startMarker: string, endMarker: string) {
public select(startMarker: string, endMarker: string): void {
const start = this.getMarkerByName(startMarker), end = this.getMarkerByName(endMarker);
ts.Debug.assert(start.fileName === end.fileName);
if (this.activeFile.fileName !== start.fileName) {
@ -624,7 +624,7 @@ export class TestState {
this.selectionEnd = end.position;
}
public selectAllInFile(fileName: string) {
public selectAllInFile(fileName: string): void {
this.openFile(fileName);
this.goToPosition(0);
this.selectionEnd = this.activeFile.content.length;
@ -635,13 +635,13 @@ export class TestState {
this.selectionEnd = range.end;
}
public selectLine(index: number) {
public selectLine(index: number): void {
const lineStart = this.languageServiceAdapterHost.lineAndCharacterToPosition(this.activeFile.fileName, { line: index, character: 0 });
const lineEnd = lineStart + this.getLineContent(index).length;
this.selectRange({ fileName: this.activeFile.fileName, pos: lineStart, end: lineEnd });
}
public moveCaretRight(count = 1) {
public moveCaretRight(count = 1): void {
this.currentCaretPosition += count;
this.currentCaretPosition = Math.min(this.currentCaretPosition, this.getFileContent(this.activeFile.fileName).length);
this.selectionEnd = -1;
@ -656,7 +656,7 @@ export class TestState {
this.languageServiceAdapterHost.openFile(fileToOpen.fileName, content, scriptKindName);
}
public verifyErrorExistsBetweenMarkers(startMarkerName: string, endMarkerName: string, shouldExist: boolean) {
public verifyErrorExistsBetweenMarkers(startMarkerName: string, endMarkerName: string, shouldExist: boolean): void {
const startMarker = this.getMarkerByName(startMarkerName);
const endMarker = this.getMarkerByName(endMarkerName);
const predicate = (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number | undefined) => ((errorMinChar === startPos) && (errorLimChar === endPos)) ? true : false;
@ -669,7 +669,7 @@ export class TestState {
}
}
public verifyOrganizeImports(newContent: string, mode?: ts.OrganizeImportsMode, preferences?: ts.UserPreferences) {
public verifyOrganizeImports(newContent: string, mode?: ts.OrganizeImportsMode, preferences?: ts.UserPreferences): void {
const changes = this.languageService.organizeImports({ fileName: this.activeFile.fileName, type: "file", mode }, this.formatCodeSettings, preferences);
this.applyChanges(changes);
this.verifyFileContent(this.activeFile.fileName, newContent);
@ -710,7 +710,7 @@ export class TestState {
});
}
public verifyErrorExistsAfterMarker(markerName: string, shouldExist: boolean, after: boolean) {
public verifyErrorExistsAfterMarker(markerName: string, shouldExist: boolean, after: boolean): void {
const marker: Marker = this.getMarkerByName(markerName);
let predicate: (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number | undefined) => boolean;
@ -772,7 +772,7 @@ export class TestState {
return "global";
}
public verifyNoErrors() {
public verifyNoErrors(): void {
ts.forEachKey(this.inputFiles, fileName => {
if (
!ts.isAnySupportedFileExtension(fileName)
@ -791,7 +791,7 @@ export class TestState {
});
}
public verifyErrorExistsAtRange(range: Range, code: number, expectedMessage?: string) {
public verifyErrorExistsAtRange(range: Range, code: number, expectedMessage?: string): void {
const span = ts.createTextSpanFromRange(range);
const hasMatchingError = ts.some(
this.getDiagnostics(range.fileName),
@ -807,7 +807,7 @@ export class TestState {
}
}
public verifyNumberOfErrorsInCurrentFile(expected: number) {
public verifyNumberOfErrorsInCurrentFile(expected: number): void {
const errors = this.getDiagnostics(this.activeFile.fileName);
const actual = errors.length;
@ -819,7 +819,7 @@ export class TestState {
}
}
public verifyEval(expr: string, value: any) {
public verifyEval(expr: string, value: any): void {
const emit = this.languageService.getEmitOutput(this.activeFile.fileName);
if (emit.outputFiles.length !== 1) {
throw new Error("Expected exactly one output from emit of " + this.activeFile.fileName);
@ -899,7 +899,7 @@ export class TestState {
public baselineGoToDefinition(
markerOrRange: MarkerOrNameOrRange[] | undefined,
rangeText: string[] | undefined,
) {
): void {
this.baselineEachMarkerOrRange("goToDefinition", markerOrRange, rangeText, markerOrRange =>
this.baselineGoToDefs(
"/*GOTO DEF*/",
@ -911,7 +911,7 @@ export class TestState {
public baselineGetDefinitionAtPosition(
markerOrRange: MarkerOrNameOrRange[] | undefined,
rangeText: string[] | undefined,
) {
): void {
this.baselineEachMarkerOrRange("getDefinitionAtPosition", markerOrRange, rangeText, markerOrRange =>
this.baselineGoToDefs(
"/*GOTO DEF POS*/",
@ -923,7 +923,7 @@ export class TestState {
public baselineGoToSourceDefinition(
markerOrRange: MarkerOrNameOrRange[] | undefined,
rangeText: string[] | undefined,
) {
): void {
if (this.testType !== FourSlashTestType.Server) {
this.raiseError("goToSourceDefinition may only be used in fourslash/server tests.");
}
@ -940,7 +940,7 @@ export class TestState {
public baselineGoToType(
markerOrRange: MarkerOrNameOrRange[] | undefined,
rangeText: string[] | undefined,
) {
): void {
this.baselineEachMarkerOrRange("goToType", markerOrRange, rangeText, markerOrRange =>
this.baselineGoToDefs(
"/*GOTO TYPE*/",
@ -952,7 +952,7 @@ export class TestState {
public baselineGoToImplementation(
markerOrRange: MarkerOrNameOrRange[] | undefined,
rangeText: string[] | undefined,
) {
): void {
this.baselineEachMarkerOrRange("goToImplementation", markerOrRange, rangeText, markerOrRange =>
this.baselineGoToDefs(
"/*GOTO IMPL*/",
@ -1016,7 +1016,7 @@ export class TestState {
this.baseline("Inlay Hints", annotations.join("\n\n"));
}
public verifyCompletions(options: FourSlashInterface.VerifyCompletionsOptions) {
public verifyCompletions(options: FourSlashInterface.VerifyCompletionsOptions): FourSlashInterface.CompletionsResult | undefined {
if (options.marker === undefined) {
return this.verifyCompletionsWorker(options);
}
@ -1410,7 +1410,7 @@ export class TestState {
public baselineFindAllReferences(
markerOrRange: MarkerOrNameOrRange[] | undefined,
rangeText: string[] | undefined,
) {
): void {
this.baselineEachMarkerOrRange("findAllReferences", markerOrRange, rangeText, markerOrRange => {
this.goToMarkerOrNameOrRange(markerOrRange);
const references = this.findReferencesAtCaret();
@ -1460,7 +1460,7 @@ export class TestState {
});
}
public baselineGetFileReferences(fileNames: string[]) {
public baselineGetFileReferences(fileNames: string[]): void {
this.baselineArray("getFileReferences", fileNames, fileName => {
const references = this.languageService.getFileReferences(fileName);
return `// fileName: ${fileName}\n\n` + this.getBaselineForDocumentSpansWithFileContents(
@ -1838,7 +1838,7 @@ export class TestState {
return this.languageService.findReferences(this.activeFile.fileName, this.currentCaretPosition);
}
public getSyntacticDiagnostics(expected: readonly FourSlashInterface.Diagnostic[]) {
public getSyntacticDiagnostics(expected: readonly FourSlashInterface.Diagnostic[]): void {
const diagnostics = this.languageService.getSyntacticDiagnostics(this.activeFile.fileName);
this.testDiagnostics(expected, diagnostics, "error");
}
@ -1847,7 +1847,7 @@ export class TestState {
return this.languageService.getSemanticDiagnostics(this.activeFile.fileName);
}
public verifySemanticDiagnostics(expected: readonly FourSlashInterface.Diagnostic[]) {
public verifySemanticDiagnostics(expected: readonly FourSlashInterface.Diagnostic[]): void {
const diagnostics = this.getSemanticDiagnostics();
this.testDiagnostics(expected, diagnostics, "error");
}
@ -1860,7 +1860,7 @@ export class TestState {
ranges: ts.TextRange[],
expectedDiagnostics: readonly FourSlashInterface.Diagnostic[] | undefined,
expectedRanges: ts.TextRange[] | undefined,
) {
): void {
const diagnosticsResult = this.languageService.getRegionSemanticDiagnostics(this.activeFile.fileName, ranges);
if (diagnosticsResult && expectedDiagnostics) {
this.testDiagnostics(expectedDiagnostics, diagnosticsResult.diagnostics, "error");
@ -1903,14 +1903,14 @@ export class TestState {
);
}
public verifyQuickInfoAt(markerName: string | Range, expectedText: string, expectedDocumentation?: string, expectedTags?: { name: string; text: string; }[]) {
public verifyQuickInfoAt(markerName: string | Range, expectedText: string, expectedDocumentation?: string, expectedTags?: { name: string; text: string; }[]): void {
if (typeof markerName === "string") this.goToMarker(markerName);
else this.goToRangeStart(markerName);
this.verifyQuickInfoString(expectedText, expectedDocumentation, expectedTags);
}
public verifyQuickInfos(namesAndTexts: { [name: string]: string | [string, string]; }) {
public verifyQuickInfos(namesAndTexts: { [name: string]: string | [string, string]; }): void {
for (const name in namesAndTexts) {
if (ts.hasProperty(namesAndTexts, name)) {
const text = namesAndTexts[name];
@ -1926,7 +1926,7 @@ export class TestState {
}
}
public verifyQuickInfoString(expectedText: string, expectedDocumentation?: string, expectedTags?: { name: string; text: string; }[]) {
public verifyQuickInfoString(expectedText: string, expectedDocumentation?: string, expectedTags?: { name: string; text: string; }[]): void {
if (expectedDocumentation === "") {
throw new Error("Use 'undefined' instead of empty string for `expectedDocumentation`");
}
@ -1951,7 +1951,7 @@ export class TestState {
}
}
public verifyQuickInfoDisplayParts(kind: string, kindModifiers: string, textSpan: TextSpan, displayParts: ts.SymbolDisplayPart[], documentation: ts.SymbolDisplayPart[], tags: ts.JSDocTagInfo[] | undefined) {
public verifyQuickInfoDisplayParts(kind: string, kindModifiers: string, textSpan: TextSpan, displayParts: ts.SymbolDisplayPart[], documentation: ts.SymbolDisplayPart[], tags: ts.JSDocTagInfo[] | undefined): void {
const actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition)!;
assert.equal(actualQuickInfo.kind, kind, this.messageAtLastKnownMarker("QuickInfo kind"));
assert.equal(actualQuickInfo.kindModifiers, kindModifiers, this.messageAtLastKnownMarker("QuickInfo kindModifiers"));
@ -1974,7 +1974,7 @@ export class TestState {
markerOrRange: ArrayOrSingle<MarkerOrNameOrRange> | undefined,
rangeText: ArrayOrSingle<string> | undefined,
options: FourSlashInterface.RenameOptions | undefined,
) {
): void {
this.baselineEachMarkerOrRangeArrayOrSingle("findRenameLocations", markerOrRange, rangeText, markerOrRange => {
const { fileName, position } = ts.isString(markerOrRange) ?
this.getMarkerByName(markerOrRange) :
@ -2019,7 +2019,7 @@ export class TestState {
});
}
public verifyQuickInfoExists(negative: boolean) {
public verifyQuickInfoExists(negative: boolean): void {
const actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition);
if (negative) {
if (actualQuickInfo) {
@ -2033,7 +2033,7 @@ export class TestState {
}
}
public verifySignatureHelpPresence(expectPresent: boolean, triggerReason: ts.SignatureHelpTriggerReason | undefined, markers: readonly (string | Marker)[]) {
public verifySignatureHelpPresence(expectPresent: boolean, triggerReason: ts.SignatureHelpTriggerReason | undefined, markers: readonly (string | Marker)[]): void {
if (markers.length) {
for (const marker of markers) {
this.goToMarker(marker);
@ -2052,7 +2052,7 @@ export class TestState {
}
}
public verifySignatureHelp(optionses: readonly FourSlashInterface.VerifySignatureHelpOptions[]) {
public verifySignatureHelp(optionses: readonly FourSlashInterface.VerifySignatureHelpOptions[]): void {
for (const options of optionses) {
if (options.marker === undefined) {
this.verifySignatureHelpWorker(options);
@ -2179,7 +2179,7 @@ export class TestState {
}
}
public verifyRenameInfoFailed(message?: string, preferences?: ts.UserPreferences) {
public verifyRenameInfoFailed(message?: string, preferences?: ts.UserPreferences): void {
const allowRenameOfImportPath = preferences?.allowRenameOfImportPath === undefined ? true : preferences.allowRenameOfImportPath;
const renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition, { ...preferences, allowRenameOfImportPath });
if (renameInfo.canRename) {
@ -2330,11 +2330,11 @@ export class TestState {
return resultString;
}
public getBreakpointStatementLocation(pos: number) {
public getBreakpointStatementLocation(pos: number): ts.TextSpan | undefined {
return this.languageService.getBreakpointStatementAtPosition(this.activeFile.fileName, pos);
}
public baselineCurrentFileBreakpointLocations() {
public baselineCurrentFileBreakpointLocations(): void {
this.baseline("breakpoints", this.baselineCurrentFileLocations(pos => this.getBreakpointStatementLocation(pos)!));
}
@ -2413,7 +2413,7 @@ export class TestState {
return result;
}
public baselineSyntacticDiagnostics() {
public baselineSyntacticDiagnostics(): void {
const files = this.getCompilerTestFiles();
const result = this.getSyntacticDiagnosticBaselineText(files);
this.baseline("Syntax Diagnostics", result);
@ -2426,7 +2426,7 @@ export class TestState {
}));
}
public baselineSyntacticAndSemanticDiagnostics() {
public baselineSyntacticAndSemanticDiagnostics(): void {
const files = ts.filter(this.getCompilerTestFiles(), f => !ts.endsWith(f.unitName, ".json"));
const result = this.getSyntacticDiagnosticBaselineText(files)
+ Harness.IO.newLine()
@ -2451,7 +2451,7 @@ export class TestState {
return result;
}
public baselineQuickInfo() {
public baselineQuickInfo(): void {
const result = ts.arrayFrom(this.testData.markerPositions.entries(), ([name, marker]) => ({
marker: { ...marker, name },
item: this.languageService.getQuickInfoAtPosition(marker.fileName, marker.position),
@ -2469,7 +2469,7 @@ export class TestState {
this.baseline("QuickInfo", annotations + "\n\n" + stringify(result));
}
public baselineSignatureHelp() {
public baselineSignatureHelp(): void {
const result = ts.arrayFrom(this.testData.markerPositions.entries(), ([name, marker]) => ({
marker: { ...marker, name },
item: this.languageService.getSignatureHelpItems(marker.fileName, marker.position, /*options*/ undefined),
@ -2503,7 +2503,7 @@ export class TestState {
this.baseline("SignatureHelp", annotations + "\n\n" + stringify(result));
}
public baselineCompletions(preferences?: ts.UserPreferences) {
public baselineCompletions(preferences?: ts.UserPreferences): void {
const result = ts.arrayFrom(this.testData.markerPositions.entries(), ([name, marker]) => {
this.goToMarker(marker);
const completions = this.getCompletionListAtCaret(preferences);
@ -2610,7 +2610,7 @@ export class TestState {
.join("\n\n");
}
public baselineSmartSelection() {
public baselineSmartSelection(): void {
const n = "\n";
const markers = this.getMarkers();
const fileContent = this.activeFile.content;
@ -2642,25 +2642,25 @@ export class TestState {
this.baseline("Smart Selection", text);
}
public printBreakpointLocation(pos: number) {
public printBreakpointLocation(pos: number): void {
Harness.IO.log("\n**Pos: " + pos + " " + this.spanInfoToString(this.getBreakpointStatementLocation(pos)!, " "));
}
public printBreakpointAtCurrentLocation() {
public printBreakpointAtCurrentLocation(): void {
this.printBreakpointLocation(this.currentCaretPosition);
}
public printCurrentParameterHelp() {
public printCurrentParameterHelp(): void {
const help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition, /*options*/ undefined);
Harness.IO.log(stringify(help));
}
public printCurrentQuickInfo() {
public printCurrentQuickInfo(): void {
const quickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition)!;
Harness.IO.log("Quick Info: " + quickInfo.displayParts!.map(part => part.text).join(""));
}
public printErrorList() {
public printErrorList(): void {
const syntacticErrors = this.languageService.getSyntacticDiagnostics(this.activeFile.fileName);
const semanticErrors = this.languageService.getSemanticDiagnostics(this.activeFile.fileName);
const errorList = ts.concatenate(syntacticErrors, semanticErrors);
@ -2677,7 +2677,7 @@ export class TestState {
}
}
public printCurrentFileState(showWhitespace: boolean, makeCaretVisible: boolean) {
public printCurrentFileState(showWhitespace: boolean, makeCaretVisible: boolean): void {
for (const file of this.testData.files) {
const active = this.activeFile === file;
Harness.IO.log(`=== Script (${file.fileName}) ${(active ? "(active, cursor at |)" : "")} ===`);
@ -2692,7 +2692,7 @@ export class TestState {
}
}
public printCurrentSignatureHelp() {
public printCurrentSignatureHelp(): void {
const help = this.getSignatureHelp(ts.emptyOptions)!;
Harness.IO.log(stringify(help.items[help.selectedItemIndex]));
}
@ -2708,7 +2708,7 @@ export class TestState {
});
}
public printCompletionListMembers(preferences: ts.UserPreferences | undefined) {
public printCompletionListMembers(preferences: ts.UserPreferences | undefined): void {
const completions = this.getCompletionListAtCaret(preferences);
this.printMembersOrCompletions(completions);
}
@ -2725,11 +2725,11 @@ export class TestState {
Harness.IO.log(formattedEntries.join("\n"));
}
public printContext() {
public printContext(): void {
ts.forEach(this.languageServiceAdapterHost.getFilenames(), Harness.IO.log);
}
public deleteChar(count = 1) {
public deleteChar(count = 1): void {
let offset = this.currentCaretPosition;
const ch = "";
@ -2754,12 +2754,12 @@ export class TestState {
this.checkPostEditInvariants();
}
public replace(start: number, length: number, text: string) {
public replace(start: number, length: number, text: string): void {
this.editScriptAndUpdateMarkers(this.activeFile.fileName, start, start + length, text);
this.checkPostEditInvariants();
}
public deleteLineRange(startIndex: number, endIndexInclusive: number) {
public deleteLineRange(startIndex: number, endIndexInclusive: number): void {
const startPos = this.languageServiceAdapterHost.lineAndCharacterToPosition(this.activeFile.fileName, { line: startIndex, character: 0 });
const endPos = this.languageServiceAdapterHost.lineAndCharacterToPosition(this.activeFile.fileName, { line: endIndexInclusive + 1, character: 0 });
this.replace(startPos, endPos - startPos, "");
@ -2769,7 +2769,7 @@ export class TestState {
return { fileName: this.activeFile.fileName, position: this.currentCaretPosition };
}
public deleteCharBehindMarker(count = 1) {
public deleteCharBehindMarker(count = 1): void {
let offset = this.currentCaretPosition;
const ch = "";
const checkCadence = (count >> 2) + 1;
@ -2790,7 +2790,7 @@ export class TestState {
}
// Enters lines of text at the current caret position
public type(text: string, highFidelity = false) {
public type(text: string, highFidelity = false): void {
let offset = this.currentCaretPosition;
const prevChar = " ";
const checkCadence = (text.length >> 2) + 1;
@ -2840,7 +2840,7 @@ export class TestState {
}
// Enters text as if the user had pasted it
public paste(text: string) {
public paste(text: string): void {
const start = this.currentCaretPosition;
this.editScriptAndUpdateMarkers(this.activeFile.fileName, this.currentCaretPosition, this.currentCaretPosition, text);
this.checkPostEditInvariants();
@ -2937,17 +2937,17 @@ export class TestState {
return oldFormatCodeOptions;
}
public formatDocument() {
public formatDocument(): void {
const edits = this.languageService.getFormattingEditsForDocument(this.activeFile.fileName, this.formatCodeSettings);
this.applyEdits(this.activeFile.fileName, edits);
}
public formatSelection(start: number, end: number) {
public formatSelection(start: number, end: number): void {
const edits = this.languageService.getFormattingEditsForRange(this.activeFile.fileName, start, end, this.formatCodeSettings);
this.applyEdits(this.activeFile.fileName, edits);
}
public formatOnType(pos: number, key: string) {
public formatOnType(pos: number, key: string): void {
const edits = this.languageService.getFormattingEditsAfterKeystroke(this.activeFile.fileName, pos, key, this.formatCodeSettings);
this.applyEdits(this.activeFile.fileName, edits);
}
@ -2976,16 +2976,16 @@ export class TestState {
return text.replace(/\s/g, "");
}
public goToBOF() {
public goToBOF(): void {
this.goToPosition(0);
}
public goToEOF() {
public goToEOF(): void {
const len = this.getFileContent(this.activeFile.fileName).length;
this.goToPosition(len);
}
public goToRangeStart({ fileName, pos }: Range) {
public goToRangeStart({ fileName, pos }: Range): void {
this.openFile(fileName);
this.goToPosition(pos);
}
@ -3003,7 +3003,7 @@ export class TestState {
return this.testData.ranges;
}
public getRangesInFile(fileName = this.activeFile.fileName) {
public getRangesInFile(fileName: string = this.activeFile.fileName): Range[] {
return this.getRanges().filter(r => r.fileName === fileName);
}
@ -3022,7 +3022,7 @@ export class TestState {
return this.getFileContent(fileName).slice(pos, end);
}
public verifyCaretAtMarker(markerName = "") {
public verifyCaretAtMarker(markerName = ""): void {
const pos = this.getMarkerByName(markerName);
if (pos.fileName !== this.activeFile.fileName) {
throw new Error(`verifyCaretAtMarker failed - expected to be in file "${pos.fileName}", but was in file "${this.activeFile.fileName}"`);
@ -3039,7 +3039,7 @@ export class TestState {
return this.languageService.getIndentationAtPosition(fileName, position, formatOptions);
}
public verifyIndentationAtCurrentPosition(numberOfSpaces: number, indentStyle: ts.IndentStyle = ts.IndentStyle.Smart, baseIndentSize = 0) {
public verifyIndentationAtCurrentPosition(numberOfSpaces: number, indentStyle: ts.IndentStyle = ts.IndentStyle.Smart, baseIndentSize = 0): void {
const actual = this.getIndentation(this.activeFile.fileName, this.currentCaretPosition, indentStyle, baseIndentSize);
const lineCol = this.getLineColStringAtPosition(this.currentCaretPosition);
if (actual !== numberOfSpaces) {
@ -3047,7 +3047,7 @@ export class TestState {
}
}
public verifyIndentationAtPosition(fileName: string, position: number, numberOfSpaces: number, indentStyle: ts.IndentStyle = ts.IndentStyle.Smart, baseIndentSize = 0) {
public verifyIndentationAtPosition(fileName: string, position: number, numberOfSpaces: number, indentStyle: ts.IndentStyle = ts.IndentStyle.Smart, baseIndentSize = 0): void {
const actual = this.getIndentation(fileName, position, indentStyle, baseIndentSize);
const lineCol = this.getLineColStringAtPosition(position);
if (actual !== numberOfSpaces) {
@ -3055,14 +3055,14 @@ export class TestState {
}
}
public verifyCurrentLineContent(text: string) {
public verifyCurrentLineContent(text: string): void {
const actual = this.getCurrentLineContent();
if (actual !== text) {
throw new Error("verifyCurrentLineContent\n" + displayExpectedAndActualString(text, actual, /*quoted*/ true));
}
}
public verifyCurrentFileContent(text: string) {
public verifyCurrentFileContent(text: string): void {
this.verifyFileContent(this.activeFile.fileName, text);
}
@ -3080,14 +3080,14 @@ export class TestState {
this.verifyFileContent(fileName, before);
}
public verifyTextAtCaretIs(text: string) {
public verifyTextAtCaretIs(text: string): void {
const actual = this.getFileContent(this.activeFile.fileName).substring(this.currentCaretPosition, this.currentCaretPosition + text.length);
if (actual !== text) {
throw new Error("verifyTextAtCaretIs\n" + displayExpectedAndActualString(text, actual, /*quoted*/ true));
}
}
public verifyCurrentNameOrDottedNameSpanText(text: string) {
public verifyCurrentNameOrDottedNameSpanText(text: string): undefined {
const span = this.languageService.getNameOrDottedNameSpan(this.activeFile.fileName, this.currentCaretPosition, this.currentCaretPosition);
if (!span) {
return this.raiseError("verifyCurrentNameOrDottedNameSpanText\n" + displayExpectedAndActualString('"' + text + '"', "undefined"));
@ -3103,14 +3103,14 @@ export class TestState {
return this.languageService.getNameOrDottedNameSpan(this.activeFile.fileName, pos, pos);
}
public baselineCurrentFileNameOrDottedNameSpans() {
public baselineCurrentFileNameOrDottedNameSpans(): void {
this.baseline(
"NameOrDottedNameSpans",
this.baselineCurrentFileLocations(pos => this.getNameOrDottedNameSpan(pos)!),
);
}
public printNameOrDottedNameSpans(pos: number) {
public printNameOrDottedNameSpans(pos: number): void {
Harness.IO.log(this.spanInfoToString(this.getNameOrDottedNameSpan(pos)!, "**"));
}
@ -3211,7 +3211,7 @@ export class TestState {
}
}
public verifyProjectInfo(expected: string[]) {
public verifyProjectInfo(expected: string[]): void {
if (this.testType === FourSlashTestType.Server) {
const actual = (this.languageService as ts.server.SessionClient).getProjectInfo(
this.activeFile.fileName,
@ -3226,7 +3226,7 @@ export class TestState {
}
}
public replaceWithSemanticClassifications(format: ts.SemanticClassificationFormat.TwentyTwenty) {
public replaceWithSemanticClassifications(format: ts.SemanticClassificationFormat.TwentyTwenty): void {
const actual = this.languageService.getSemanticClassifications(this.activeFile.fileName, ts.createTextSpan(0, this.activeFile.content.length), format);
const replacement = [`const c2 = classification("2020");`, `verify.semanticClassificationsAre("2020",`];
for (const a of actual) {
@ -3245,32 +3245,32 @@ export class TestState {
// fs.writeFileSync(testfilePath, newfile);
}
public verifyEncodedSyntacticClassificationsLength(expected: number) {
public verifyEncodedSyntacticClassificationsLength(expected: number): void {
const actual = this.languageService.getEncodedSyntacticClassifications(this.activeFile.fileName, ts.createTextSpan(0, this.activeFile.content.length));
if (actual.spans.length !== expected) {
this.raiseError(`encodedSyntacticClassificationsLength failed - expected total spans to be ${expected} got ${actual.spans.length}`);
}
}
public verifyEncodedSemanticClassificationsLength(format: ts.SemanticClassificationFormat, expected: number) {
public verifyEncodedSemanticClassificationsLength(format: ts.SemanticClassificationFormat, expected: number): void {
const actual = this.languageService.getEncodedSemanticClassifications(this.activeFile.fileName, ts.createTextSpan(0, this.activeFile.content.length), format);
if (actual.spans.length !== expected) {
this.raiseError(`encodedSemanticClassificationsLength failed - expected total spans to be ${expected} got ${actual.spans.length}`);
}
}
public verifySemanticClassifications(format: ts.SemanticClassificationFormat, expected: { classificationType: string | number; text?: string; }[]) {
public verifySemanticClassifications(format: ts.SemanticClassificationFormat, expected: { classificationType: string | number; text?: string; }[]): void {
const actual = this.languageService.getSemanticClassifications(this.activeFile.fileName, ts.createTextSpan(0, this.activeFile.content.length), format);
this.verifyClassifications(expected, actual, this.activeFile.content);
}
public verifySyntacticClassifications(expected: { classificationType: string; text: string; }[]) {
public verifySyntacticClassifications(expected: { classificationType: string; text: string; }[]): void {
const actual = this.languageService.getSyntacticClassifications(this.activeFile.fileName, ts.createTextSpan(0, this.activeFile.content.length));
this.verifyClassifications(expected, actual, this.activeFile.content);
}
public printOutliningSpans() {
public printOutliningSpans(): void {
const spans = this.languageService.getOutliningSpans(this.activeFile.fileName);
Harness.IO.log(`Outlining spans (${spans.length} items)\nResults:`);
Harness.IO.log(stringify(spans));
@ -3292,7 +3292,7 @@ export class TestState {
Harness.IO.log(`\nMockup:\n${annotated}`);
}
public verifyOutliningSpans(spans: Range[], kind?: "comment" | "region" | "code" | "imports") {
public verifyOutliningSpans(spans: Range[], kind?: "comment" | "region" | "code" | "imports"): void {
const actual = this.languageService.getOutliningSpans(this.activeFile.fileName);
const filterActual = ts.filter(actual, f => kind === undefined ? true : f.kind === kind);
@ -3310,7 +3310,7 @@ export class TestState {
});
}
public verifyOutliningHintSpans(spans: Range[]) {
public verifyOutliningHintSpans(spans: Range[]): void {
const actual = this.languageService.getOutliningSpans(this.activeFile.fileName);
if (actual.length !== spans.length) {
@ -3324,7 +3324,7 @@ export class TestState {
});
}
public verifyTodoComments(descriptors: string[], spans: Range[]) {
public verifyTodoComments(descriptors: string[], spans: Range[]): void {
const actual = this.languageService.getTodoComments(this.activeFile.fileName, descriptors.map(d => ({ text: d, priority: 0 })));
if (actual.length !== spans.length) {
@ -3346,7 +3346,7 @@ export class TestState {
* @param errorCode The error code that generated the code action.
* @param index The nth (0-index-based) codeaction available generated by errorCode.
*/
public getAndApplyCodeActions(errorCode?: number, index?: number) {
public getAndApplyCodeActions(errorCode?: number, index?: number): void {
const fileName = this.activeFile.fileName;
const fixes = this.getCodeFixes(fileName, errorCode);
if (index === undefined) {
@ -3364,7 +3364,7 @@ export class TestState {
this.applyChanges(fixes[index].changes);
}
public applyCodeActionFromCompletion(markerName: string | undefined, options: FourSlashInterface.VerifyCompletionActionOptions) {
public applyCodeActionFromCompletion(markerName: string | undefined, options: FourSlashInterface.VerifyCompletionActionOptions): undefined {
if (markerName !== undefined) {
this.goToMarker(markerName);
}
@ -3392,7 +3392,7 @@ export class TestState {
this.verifyNewContentAfterChange(options, ts.flatMap(codeActions, a => a.changes.map(c => c.fileName)));
}
public verifyRangeIs(expectedText: string, includeWhiteSpace?: boolean) {
public verifyRangeIs(expectedText: string, includeWhiteSpace?: boolean): void {
this.verifyTextMatches(this.rangeText(this.getOnlyRange()), !!includeWhiteSpace, expectedText);
}
@ -3416,7 +3416,7 @@ export class TestState {
* (ie: [|...|]) in the file after applying the codefix sole codefix
* in the source file.
*/
public verifyRangeAfterCodeFix(expectedText: string, includeWhiteSpace?: boolean, errorCode?: number, index?: number) {
public verifyRangeAfterCodeFix(expectedText: string, includeWhiteSpace?: boolean, errorCode?: number, index?: number): void {
this.getAndApplyCodeActions(errorCode, index);
this.verifyRangeIs(expectedText, includeWhiteSpace);
}
@ -3435,7 +3435,7 @@ export class TestState {
this.verifyNewContent({ newFileContent }, changes);
}
public verifyCodeFix(options: FourSlashInterface.VerifyCodeFixOptions) {
public verifyCodeFix(options: FourSlashInterface.VerifyCodeFixOptions): void {
const fileName = this.activeFile.fileName;
const actions = this.getCodeFixes(fileName, options.errorCode, options.preferences);
let index = options.index;
@ -3562,7 +3562,7 @@ export class TestState {
}
}
public verifyImportFixAtPosition(expectedTextArray: string[], errorCode: number | undefined, preferences: ts.UserPreferences | undefined) {
public verifyImportFixAtPosition(expectedTextArray: string[], errorCode: number | undefined, preferences: ts.UserPreferences | undefined): void {
const { fileName } = this.activeFile;
const ranges = this.getRanges().filter(r => r.fileName === fileName);
if (ranges.length > 1) {
@ -3612,7 +3612,7 @@ export class TestState {
});
}
public verifyImportFixModuleSpecifiers(markerName: string, moduleSpecifiers: string[], preferences?: ts.UserPreferences) {
public verifyImportFixModuleSpecifiers(markerName: string, moduleSpecifiers: string[], preferences?: ts.UserPreferences): void {
const marker = this.getMarkerByName(markerName);
const codeFixes = this.getCodeFixes(marker.fileName, ts.Diagnostics.Cannot_find_name_0.code, {
includeCompletionsForModuleExports: true,
@ -3635,7 +3635,7 @@ export class TestState {
this.verifyNewContent({ newFileContent: options.newFileContents }, editInfo.edits);
}
public verifyDocCommentTemplate(expected: ts.TextInsertion | undefined, options?: ts.DocCommentTemplateOptions) {
public verifyDocCommentTemplate(expected: ts.TextInsertion | undefined, options?: ts.DocCommentTemplateOptions): void {
const name = "verifyDocCommentTemplate";
const actual = this.languageService.getDocCommentTemplateAtPosition(this.activeFile.fileName, this.currentCaretPosition, options || { generateReturnInDocTemplate: true }, this.formatCodeSettings)!;
@ -3661,7 +3661,7 @@ export class TestState {
}
}
public verifyBraceCompletionAtPosition(negative: boolean, openingBrace: string) {
public verifyBraceCompletionAtPosition(negative: boolean, openingBrace: string): void {
const openBraceMap = new Map(Object.entries<ts.CharacterCodes>({
"(": ts.CharacterCodes.openParen,
"{": ts.CharacterCodes.openBrace,
@ -3690,7 +3690,7 @@ export class TestState {
}
}
public baselineAutoImports(markerName: string, fullNamesForCodeFix?: string[], preferences?: ts.UserPreferences) {
public baselineAutoImports(markerName: string, fullNamesForCodeFix?: string[], preferences?: ts.UserPreferences): void {
const marker = this.getMarkerByName(markerName);
const completionPreferences = {
includeCompletionsForModuleExports: true,
@ -3844,7 +3844,7 @@ export class TestState {
}
}
public verifyMatchingBracePosition(bracePosition: number, expectedMatchPosition: number) {
public verifyMatchingBracePosition(bracePosition: number, expectedMatchPosition: number): void {
const actual = this.languageService.getBraceMatchingAtPosition(this.activeFile.fileName, bracePosition);
if (actual.length !== 2) {
@ -3867,7 +3867,7 @@ export class TestState {
}
}
public verifyNoMatchingBracePosition(bracePosition: number) {
public verifyNoMatchingBracePosition(bracePosition: number): void {
const actual = this.languageService.getBraceMatchingAtPosition(this.activeFile.fileName, bracePosition);
if (actual.length !== 0) {
@ -3875,7 +3875,7 @@ export class TestState {
}
}
public verifySpanOfEnclosingComment(negative: boolean, onlyMultiLineDiverges?: boolean) {
public verifySpanOfEnclosingComment(negative: boolean, onlyMultiLineDiverges?: boolean): void {
const expected = !negative;
const position = this.currentCaretPosition;
const fileName = this.activeFile.fileName;
@ -3913,11 +3913,11 @@ export class TestState {
}
}
public verifyNavigationBar(json: any, options: { checkSpans?: boolean; } | undefined) {
public verifyNavigationBar(json: any, options: { checkSpans?: boolean; } | undefined): void {
this.verifyNavigationTreeOrBar(json, this.languageService.getNavigationBarItems(this.activeFile.fileName), "Bar", options);
}
public verifyNavigationTree(json: any, options: { checkSpans?: boolean; } | undefined) {
public verifyNavigationTree(json: any, options: { checkSpans?: boolean; } | undefined): void {
this.verifyNavigationTreeOrBar(json, this.languageService.getNavigationTree(this.activeFile.fileName), "Tree", options);
}
@ -3944,7 +3944,7 @@ export class TestState {
}
}
public printNavigationItems(searchValue: string) {
public printNavigationItems(searchValue: string): void {
const items = this.languageService.getNavigateToItems(searchValue);
Harness.IO.log(`NavigationItems list (${items.length} items)`);
for (const item of items) {
@ -3952,7 +3952,7 @@ export class TestState {
}
}
public printNavigationBar() {
public printNavigationBar(): void {
const items = this.languageService.getNavigationBarItems(this.activeFile.fileName);
Harness.IO.log(`Navigation bar (${items.length} items)`);
for (const item of items) {
@ -3969,7 +3969,7 @@ export class TestState {
markerOrRange: ArrayOrSingle<MarkerOrNameOrRange> | undefined,
rangeText: ArrayOrSingle<string> | undefined,
options: FourSlashInterface.VerifyDocumentHighlightsOptions | undefined,
) {
): void {
this.baselineEachMarkerOrRangeArrayOrSingle(
"documentHighlights",
markerOrRange,
@ -4015,7 +4015,7 @@ export class TestState {
}
}
public verifyCodeFixAllAvailable(negative: boolean, fixName: string) {
public verifyCodeFixAllAvailable(negative: boolean, fixName: string): void {
const availableFixes = this.getCodeFixes(this.activeFile.fileName);
const hasFix = availableFixes.some(fix => fix.fixName === fixName && fix.fixId);
if (negative && hasFix) {
@ -4035,7 +4035,7 @@ export class TestState {
}
}
public verifyApplicableRefactorAvailableAtMarker(negative: boolean, markerName: string) {
public verifyApplicableRefactorAvailableAtMarker(negative: boolean, markerName: string): void {
const isAvailable = this.getApplicableRefactors(this.getMarkerByName(markerName)).length > 0;
if (negative && isAvailable) {
this.raiseError(`verifyApplicableRefactorAvailableAtMarker failed - expected no refactor at marker ${markerName} but found some.`);
@ -4052,7 +4052,7 @@ export class TestState {
};
}
public verifyRefactorAvailable(negative: boolean, triggerReason: ts.RefactorTriggerReason, name: string, actionName?: string, actionDescription?: string, kind?: string, preferences = ts.emptyOptions, includeInteractiveActions?: boolean) {
public verifyRefactorAvailable(negative: boolean, triggerReason: ts.RefactorTriggerReason, name: string, actionName?: string, actionDescription?: string, kind?: string, preferences: {} = ts.emptyOptions, includeInteractiveActions?: boolean): void {
let refactors = this.getApplicableRefactorsAtSelection(triggerReason, kind, preferences, includeInteractiveActions);
refactors = refactors.filter(r => r.name === name);
@ -4083,7 +4083,7 @@ export class TestState {
}
}
public verifyRefactorKindsAvailable(kind: string, expected: string[], preferences = ts.emptyOptions) {
public verifyRefactorKindsAvailable(kind: string, expected: string[], preferences: {} = ts.emptyOptions): void {
const refactors = this.getApplicableRefactorsAtSelection("invoked", kind, preferences);
const availableKinds = ts.flatMap(refactors, refactor => refactor.actions).map(action => action.kind);
assert.deepEqual(availableKinds.slice().sort(), expected.slice().sort(), `Expected kinds to be equal`);
@ -4093,7 +4093,7 @@ export class TestState {
assert.deepEqual(unique(this.getApplicableRefactorsAtSelection(), r => r.name), names);
}
public verifyApplicableRefactorAvailableForRange(negative: boolean) {
public verifyApplicableRefactorAvailableForRange(negative: boolean): void {
const ranges = this.getRanges();
if (!(ranges && ranges.length === 1)) {
throw new Error("Exactly one refactor range is allowed per test.");
@ -4108,7 +4108,7 @@ export class TestState {
}
}
public applyRefactor({ refactorName, actionName, actionDescription, newContent: newContentWithRenameMarker, triggerReason }: FourSlashInterface.ApplyRefactorOptions) {
public applyRefactor({ refactorName, actionName, actionDescription, newContent: newContentWithRenameMarker, triggerReason }: FourSlashInterface.ApplyRefactorOptions): void {
const range = this.getSelection();
const refactors = this.getApplicableRefactorsAtSelection(triggerReason);
const refactorsWithName = refactors.filter(r => r.name === refactorName);
@ -4169,7 +4169,7 @@ export class TestState {
}
}
public noMoveToNewFile() {
public noMoveToNewFile(): void {
const ranges = this.getRanges();
assert(ranges.length);
for (const range of ranges) {
@ -4239,7 +4239,7 @@ export class TestState {
refactorNameToApply: string,
actionName: string,
formattingOptions?: ts.FormatCodeSettings,
) {
): void {
formattingOptions = formattingOptions || this.formatCodeSettings;
const marker = this.getMarkerByName(markerName);
@ -4262,7 +4262,7 @@ export class TestState {
}
}
public printAvailableCodeFixes() {
public printAvailableCodeFixes(): void {
const codeFixes = this.getCodeFixes(this.activeFile.fileName);
Harness.IO.log(stringify(codeFixes));
}
@ -4392,7 +4392,7 @@ export class TestState {
return text;
}
public baselineCallHierarchy() {
public baselineCallHierarchy(): void {
const callHierarchyItem = this.languageService.prepareCallHierarchy(this.activeFile.fileName, this.currentCaretPosition);
const text = callHierarchyItem ? ts.mapOneOrMany(callHierarchyItem, item => this.formatCallHierarchy(item), result => result.join("")) : "none";
this.baseline("Call Hierarchy", text, ".callHierarchy.txt");
@ -4484,7 +4484,7 @@ export class TestState {
return `line ${(pos.line + 1)}, col ${pos.character}`;
}
public getMarkerByName(markerName: string) {
public getMarkerByName(markerName: string): Marker {
const markerPos = this.testData.markerPositions.get(markerName);
if (markerPos === undefined) {
throw new Error(`Unknown marker "${markerName}" Available markers: ${this.getMarkerNames().map(m => '"' + m + '"').join(", ")}`);
@ -4532,7 +4532,7 @@ export class TestState {
(this.languageService as ts.server.SessionClient).configurePlugin(pluginName, configuration);
}
public setCompilerOptionsForInferredProjects(options: ts.server.protocol.CompilerOptions) {
public setCompilerOptionsForInferredProjects(options: ts.server.protocol.CompilerOptions): void {
ts.Debug.assert(this.testType === FourSlashTestType.Server);
(this.languageService as ts.server.SessionClient).setCompilerOptionsForInferredProjects(options);
}
@ -4675,7 +4675,7 @@ export interface FourSlashServerLogBaseliner {
baseline?: () => void;
}
export function runFourSlashTest(basePath: string, testType: FourSlashTestType, fileName: string, serverLogBaseliner?: FourSlashServerLogBaseliner) {
export function runFourSlashTest(basePath: string, testType: FourSlashTestType, fileName: string, serverLogBaseliner?: FourSlashServerLogBaseliner): void {
const content = Harness.IO.readFile(fileName)!;
runFourSlashTestContent(basePath, testType, content, fileName, serverLogBaseliner);
}

Просмотреть файл

@ -17,7 +17,7 @@ export class Test {
return this.state.getMarkerByName(name);
}
public markerName(m: FourSlash.Marker) {
public markerName(m: FourSlash.Marker): string {
return this.state.markerName(m);
}
@ -83,7 +83,7 @@ export class GoTo {
// Moves the caret to the specified marker,
// or the anonymous marker ('/**/') if no name
// is given
public marker(name?: string | FourSlash.Marker) {
public marker(name?: string | FourSlash.Marker): void {
this.state.goToMarker(name);
}
@ -94,19 +94,19 @@ export class GoTo {
this.state.goToEachMarker(markers, typeof a === "function" ? a : b!);
}
public rangeStart(range: FourSlash.Range) {
public rangeStart(range: FourSlash.Range): void {
this.state.goToRangeStart(range);
}
public eachRange(action: (range: FourSlash.Range) => void) {
public eachRange(action: (range: FourSlash.Range) => void): void {
this.state.goToEachRange(action);
}
public bof() {
public bof(): void {
this.state.goToBOF();
}
public eof() {
public eof(): void {
this.state.goToEOF();
}
@ -124,11 +124,11 @@ export class GoTo {
this.state.openFile(indexOrName, content, scriptKindName);
}
public select(startMarker: string, endMarker: string) {
public select(startMarker: string, endMarker: string): void {
this.state.select(startMarker, endMarker);
}
public selectAllInFile(fileName: string) {
public selectAllInFile(fileName: string): void {
this.state.selectAllInFile(fileName);
}
@ -146,7 +146,7 @@ export class VerifyNegatable {
}
}
public assertHasRanges(ranges: FourSlash.Range[]) {
public assertHasRanges(ranges: FourSlash.Range[]): void {
assert(ranges.length !== 0, "Array of ranges is expected to be non-empty");
}
@ -166,23 +166,23 @@ export class VerifyNegatable {
this.state.verifySignatureHelp(options);
}
public errorExistsBetweenMarkers(startMarker: string, endMarker: string) {
public errorExistsBetweenMarkers(startMarker: string, endMarker: string): void {
this.state.verifyErrorExistsBetweenMarkers(startMarker, endMarker, !this.negative);
}
public errorExistsAfterMarker(markerName = "") {
public errorExistsAfterMarker(markerName = ""): void {
this.state.verifyErrorExistsAfterMarker(markerName, !this.negative, /*after*/ true);
}
public errorExistsBeforeMarker(markerName = "") {
public errorExistsBeforeMarker(markerName = ""): void {
this.state.verifyErrorExistsAfterMarker(markerName, !this.negative, /*after*/ false);
}
public quickInfoExists() {
public quickInfoExists(): void {
this.state.verifyQuickInfoExists(this.negative);
}
public isValidBraceCompletionAtPosition(openingBrace: string) {
public isValidBraceCompletionAtPosition(openingBrace: string): void {
this.state.verifyBraceCompletionAtPosition(this.negative, openingBrace);
}
@ -198,27 +198,27 @@ export class VerifyNegatable {
this.state.baselineLinkedEditing();
}
public isInCommentAtPosition(onlyMultiLineDiverges?: boolean) {
public isInCommentAtPosition(onlyMultiLineDiverges?: boolean): void {
this.state.verifySpanOfEnclosingComment(this.negative, onlyMultiLineDiverges);
}
public codeFix(options: VerifyCodeFixOptions) {
public codeFix(options: VerifyCodeFixOptions): void {
this.state.verifyCodeFix(options);
}
public codeFixAvailable(options?: VerifyCodeFixAvailableOptions[]) {
public codeFixAvailable(options?: VerifyCodeFixAvailableOptions[]): void {
this.state.verifyCodeFixAvailable(this.negative, options);
}
public codeFixAllAvailable(fixName: string) {
public codeFixAllAvailable(fixName: string): void {
this.state.verifyCodeFixAllAvailable(this.negative, fixName);
}
public applicableRefactorAvailableAtMarker(markerName: string) {
public applicableRefactorAvailableAtMarker(markerName: string): void {
this.state.verifyApplicableRefactorAvailableAtMarker(this.negative, markerName);
}
public applicableRefactorAvailableForRange() {
public applicableRefactorAvailableForRange(): void {
this.state.verifyApplicableRefactorAvailableForRange(this.negative);
}
@ -226,31 +226,31 @@ export class VerifyNegatable {
this.state.verifyRefactorsAvailable(names);
}
public refactorAvailable(name: string, actionName?: string, actionDescription?: string, kind?: string, preferences = ts.emptyOptions, includeInteractiveActions?: boolean) {
public refactorAvailable(name: string, actionName?: string, actionDescription?: string, kind?: string, preferences: {} = ts.emptyOptions, includeInteractiveActions?: boolean): void {
this.state.verifyRefactorAvailable(this.negative, "implicit", name, actionName, actionDescription, kind, preferences, includeInteractiveActions);
}
public refactorAvailableForTriggerReason(triggerReason: ts.RefactorTriggerReason, name: string, actionName?: string, actionDescription?: string, kind?: string, preferences = ts.emptyOptions, includeInteractiveActions?: boolean) {
public refactorAvailableForTriggerReason(triggerReason: ts.RefactorTriggerReason, name: string, actionName?: string, actionDescription?: string, kind?: string, preferences: {} = ts.emptyOptions, includeInteractiveActions?: boolean): void {
this.state.verifyRefactorAvailable(this.negative, triggerReason, name, actionName, actionDescription, kind, preferences, includeInteractiveActions);
}
public refactorKindAvailable(kind: string, expected: string[], preferences = ts.emptyOptions) {
public refactorKindAvailable(kind: string, expected: string[], preferences: {} = ts.emptyOptions): void {
this.state.verifyRefactorKindsAvailable(kind, expected, preferences);
}
public toggleLineComment(newFileContent: string) {
public toggleLineComment(newFileContent: string): void {
this.state.toggleLineComment(newFileContent);
}
public toggleMultilineComment(newFileContent: string) {
public toggleMultilineComment(newFileContent: string): void {
this.state.toggleMultilineComment(newFileContent);
}
public commentSelection(newFileContent: string) {
public commentSelection(newFileContent: string): void {
this.state.commentSelection(newFileContent);
}
public uncommentSelection(newFileContent: string) {
public uncommentSelection(newFileContent: string): void {
this.state.uncommentSelection(newFileContent);
}
@ -259,12 +259,22 @@ export class VerifyNegatable {
}
}
export interface CompletionsResult {
andApplyCodeAction: (options: {
name: string;
source: string;
description: string;
newFileContent?: string;
newRangeContent?: string;
}) => void;
}
export class Verify extends VerifyNegatable {
constructor(state: FourSlash.TestState) {
super(state);
}
public completions(...optionsArray: VerifyCompletionsOptions[]) {
public completions(...optionsArray: VerifyCompletionsOptions[]): CompletionsResult | undefined {
if (optionsArray.length === 1) {
return this.state.verifyCompletions(optionsArray[0]);
}
@ -278,35 +288,35 @@ export class Verify extends VerifyNegatable {
};
}
public baselineInlayHints(span: ts.TextSpan, preference?: ts.UserPreferences) {
public baselineInlayHints(span: ts.TextSpan, preference?: ts.UserPreferences): void {
this.state.baselineInlayHints(span, preference);
}
public quickInfoIs(expectedText: string, expectedDocumentation?: string, expectedTags?: { name: string; text: string; }[]) {
public quickInfoIs(expectedText: string, expectedDocumentation?: string, expectedTags?: { name: string; text: string; }[]): void {
this.state.verifyQuickInfoString(expectedText, expectedDocumentation, expectedTags);
}
public quickInfoAt(markerName: string | FourSlash.Range, expectedText: string, expectedDocumentation?: string, expectedTags?: { name: string; text: string; }[]) {
public quickInfoAt(markerName: string | FourSlash.Range, expectedText: string, expectedDocumentation?: string, expectedTags?: { name: string; text: string; }[]): void {
this.state.verifyQuickInfoAt(markerName, expectedText, expectedDocumentation, expectedTags);
}
public quickInfos(namesAndTexts: { [name: string]: string; }) {
public quickInfos(namesAndTexts: { [name: string]: string; }): void {
this.state.verifyQuickInfos(namesAndTexts);
}
public caretAtMarker(markerName?: string) {
public caretAtMarker(markerName?: string): void {
this.state.verifyCaretAtMarker(markerName);
}
public indentationIs(numberOfSpaces: number) {
public indentationIs(numberOfSpaces: number): void {
this.state.verifyIndentationAtCurrentPosition(numberOfSpaces);
}
public indentationAtPositionIs(fileName: string, position: number, numberOfSpaces: number, indentStyle = ts.IndentStyle.Smart, baseIndentSize = 0) {
public indentationAtPositionIs(fileName: string, position: number, numberOfSpaces: number, indentStyle: ts.IndentStyle = ts.IndentStyle.Smart, baseIndentSize = 0): void {
this.state.verifyIndentationAtPosition(fileName, position, numberOfSpaces, indentStyle, baseIndentSize);
}
public textAtCaretIs(text: string) {
public textAtCaretIs(text: string): void {
this.state.verifyTextAtCaretIs(text);
}
@ -315,15 +325,15 @@ export class Verify extends VerifyNegatable {
* the emitted output, then compares (using ===) the result of that expression
* to 'value'. Do not use this function with external modules as it is not supported.
*/
public eval(expr: string, value: any) {
public eval(expr: string, value: any): void {
this.state.verifyEval(expr, value);
}
public currentLineContentIs(text: string) {
public currentLineContentIs(text: string): void {
this.state.verifyCurrentLineContent(text);
}
public currentFileContentIs(text: string) {
public currentFileContentIs(text: string): void {
this.state.verifyCurrentFileContent(text);
}
@ -339,95 +349,95 @@ export class Verify extends VerifyNegatable {
this.state.verifyGetEmitOutputContentsForCurrentFile(expected);
}
public symbolAtLocation(startRange: FourSlash.Range, ...declarationRanges: FourSlash.Range[]) {
public symbolAtLocation(startRange: FourSlash.Range, ...declarationRanges: FourSlash.Range[]): void {
this.state.verifySymbolAtLocation(startRange, declarationRanges);
}
public typeOfSymbolAtLocation(range: FourSlash.Range, symbol: ts.Symbol, expected: string) {
public typeOfSymbolAtLocation(range: FourSlash.Range, symbol: ts.Symbol, expected: string): void {
this.state.verifyTypeOfSymbolAtLocation(range, symbol, expected);
}
public typeAtLocation(range: FourSlash.Range, expected: string) {
public typeAtLocation(range: FourSlash.Range, expected: string): void {
this.state.verifyTypeAtLocation(range, expected);
}
public baselineFindAllReferences(...markerOrRange: FourSlash.MarkerOrNameOrRange[]) {
public baselineFindAllReferences(...markerOrRange: FourSlash.MarkerOrNameOrRange[]): void {
this.state.baselineFindAllReferences(markerOrRange, /*rangeText*/ undefined);
}
public baselineFindAllReferencesAtRangesWithText(...rangeText: string[]) {
public baselineFindAllReferencesAtRangesWithText(...rangeText: string[]): void {
this.state.baselineFindAllReferences(/*markerOrRange*/ undefined, rangeText);
}
public baselineGetFileReferences(...fileName: string[]) {
public baselineGetFileReferences(...fileName: string[]): void {
this.state.baselineGetFileReferences(fileName);
}
public baselineGoToDefinition(...markerOrRange: FourSlash.MarkerOrNameOrRange[]) {
public baselineGoToDefinition(...markerOrRange: FourSlash.MarkerOrNameOrRange[]): void {
this.state.baselineGoToDefinition(markerOrRange, /*rangeText*/ undefined);
}
public baselineGoToDefinitionAtRangesWithText(...rangeText: string[]) {
public baselineGoToDefinitionAtRangesWithText(...rangeText: string[]): void {
this.state.baselineGoToDefinition(/*markerOrRange*/ undefined, rangeText);
}
public baselineGetDefinitionAtPosition(...markerOrRange: FourSlash.MarkerOrNameOrRange[]) {
public baselineGetDefinitionAtPosition(...markerOrRange: FourSlash.MarkerOrNameOrRange[]): void {
this.state.baselineGetDefinitionAtPosition(markerOrRange, /*rangeText*/ undefined);
}
public baselineGetDefinitionAtRangesWithText(...rangeText: string[]) {
public baselineGetDefinitionAtRangesWithText(...rangeText: string[]): void {
this.state.baselineGetDefinitionAtPosition(/*markerOrRange*/ undefined, rangeText);
}
public baselineGoToSourceDefinition(...markerOrRange: FourSlash.MarkerOrNameOrRange[]) {
public baselineGoToSourceDefinition(...markerOrRange: FourSlash.MarkerOrNameOrRange[]): void {
this.state.baselineGoToSourceDefinition(markerOrRange, /*rangeText*/ undefined);
}
public baselineGoToSourceDefinitionAtRangesWithText(...rangeText: string[]) {
public baselineGoToSourceDefinitionAtRangesWithText(...rangeText: string[]): void {
this.state.baselineGoToSourceDefinition(/*markerOrRange*/ undefined, rangeText);
}
public baselineGoToType(...markerOrRange: FourSlash.MarkerOrNameOrRange[]) {
public baselineGoToType(...markerOrRange: FourSlash.MarkerOrNameOrRange[]): void {
this.state.baselineGoToType(markerOrRange, /*rangeText*/ undefined);
}
public baselineGoToTypeAtRangesWithText(...rangeText: string[]) {
public baselineGoToTypeAtRangesWithText(...rangeText: string[]): void {
this.state.baselineGoToType(/*markerOrRange*/ undefined, rangeText);
}
public baselineGoToImplementation(...markerOrRange: FourSlash.MarkerOrNameOrRange[]) {
public baselineGoToImplementation(...markerOrRange: FourSlash.MarkerOrNameOrRange[]): void {
this.state.baselineGoToImplementation(markerOrRange, /*rangeText*/ undefined);
}
public baselineGoToImplementationAtRangesWithText(...rangeText: string[]) {
public baselineGoToImplementationAtRangesWithText(...rangeText: string[]): void {
this.state.baselineGoToImplementation(/*markerOrRange*/ undefined, rangeText);
}
public baselineDocumentHighlights(markerOrRange?: ArrayOrSingle<FourSlash.MarkerOrNameOrRange>, options?: VerifyDocumentHighlightsOptions) {
public baselineDocumentHighlights(markerOrRange?: ArrayOrSingle<FourSlash.MarkerOrNameOrRange>, options?: VerifyDocumentHighlightsOptions): void {
this.state.baselineDocumentHighlights(markerOrRange, /*rangeText*/ undefined, options);
}
public baselineDocumentHighlightsAtRangesWithText(rangeText?: ArrayOrSingle<string>, options?: VerifyDocumentHighlightsOptions) {
public baselineDocumentHighlightsAtRangesWithText(rangeText?: ArrayOrSingle<string>, options?: VerifyDocumentHighlightsOptions): void {
this.state.baselineDocumentHighlights(/*markerOrRange*/ undefined, rangeText, options);
}
public noErrors() {
public noErrors(): void {
this.state.verifyNoErrors();
}
public errorExistsAtRange(range: FourSlash.Range, code: number, message?: string) {
public errorExistsAtRange(range: FourSlash.Range, code: number, message?: string): void {
this.state.verifyErrorExistsAtRange(range, code, message);
}
public numberOfErrorsInCurrentFile(expected: number) {
public numberOfErrorsInCurrentFile(expected: number): void {
this.state.verifyNumberOfErrorsInCurrentFile(expected);
}
public baselineCurrentFileBreakpointLocations() {
public baselineCurrentFileBreakpointLocations(): void {
this.state.baselineCurrentFileBreakpointLocations();
}
public baselineCurrentFileNameOrDottedNameSpans() {
public baselineCurrentFileNameOrDottedNameSpans(): void {
this.state.baselineCurrentFileNameOrDottedNameSpans();
}
@ -435,64 +445,64 @@ export class Verify extends VerifyNegatable {
this.state.verifyGetEmitOutput(expectedOutputFiles);
}
public baselineGetEmitOutput() {
public baselineGetEmitOutput(): void {
this.state.baselineGetEmitOutput();
}
public baselineQuickInfo() {
public baselineQuickInfo(): void {
this.state.baselineQuickInfo();
}
public baselineSignatureHelp() {
public baselineSignatureHelp(): void {
this.state.baselineSignatureHelp();
}
public baselineCompletions(preferences?: ts.UserPreferences) {
public baselineCompletions(preferences?: ts.UserPreferences): void {
this.state.baselineCompletions(preferences);
}
public baselineSmartSelection() {
public baselineSmartSelection(): void {
this.state.baselineSmartSelection();
}
public baselineSyntacticDiagnostics() {
public baselineSyntacticDiagnostics(): void {
this.state.baselineSyntacticDiagnostics();
}
public baselineSyntacticAndSemanticDiagnostics() {
public baselineSyntacticAndSemanticDiagnostics(): void {
this.state.baselineSyntacticAndSemanticDiagnostics();
}
public nameOrDottedNameSpanTextIs(text: string) {
public nameOrDottedNameSpanTextIs(text: string): void {
this.state.verifyCurrentNameOrDottedNameSpanText(text);
}
public outliningSpansInCurrentFile(spans: FourSlash.Range[], kind?: "comment" | "region" | "code" | "imports") {
public outliningSpansInCurrentFile(spans: FourSlash.Range[], kind?: "comment" | "region" | "code" | "imports"): void {
this.state.verifyOutliningSpans(spans, kind);
}
public outliningHintSpansInCurrentFile(spans: FourSlash.Range[]) {
public outliningHintSpansInCurrentFile(spans: FourSlash.Range[]): void {
this.state.verifyOutliningHintSpans(spans);
}
public todoCommentsInCurrentFile(descriptors: string[]) {
public todoCommentsInCurrentFile(descriptors: string[]): void {
this.state.verifyTodoComments(descriptors, this.state.getRanges());
}
public matchingBracePositionInCurrentFile(bracePosition: number, expectedMatchPosition: number) {
public matchingBracePositionInCurrentFile(bracePosition: number, expectedMatchPosition: number): void {
this.state.verifyMatchingBracePosition(bracePosition, expectedMatchPosition);
}
public noMatchingBracePositionInCurrentFile(bracePosition: number) {
public noMatchingBracePositionInCurrentFile(bracePosition: number): void {
this.state.verifyNoMatchingBracePosition(bracePosition);
}
public docCommentTemplateAt(marker: string | FourSlash.Marker, expectedOffset: number, expectedText: string, options?: ts.DocCommentTemplateOptions) {
public docCommentTemplateAt(marker: string | FourSlash.Marker, expectedOffset: number, expectedText: string, options?: ts.DocCommentTemplateOptions): void {
this.state.goToMarker(marker);
this.state.verifyDocCommentTemplate({ newText: expectedText.replace(/\r?\n/g, ts.testFormatSettings.newLineCharacter!), caretOffset: expectedOffset }, options);
}
public noDocCommentTemplateAt(marker: string | FourSlash.Marker) {
public noDocCommentTemplateAt(marker: string | FourSlash.Marker): void {
this.state.goToMarker(marker);
this.state.verifyDocCommentTemplate(/*expected*/ undefined);
}
@ -525,19 +535,19 @@ export class Verify extends VerifyNegatable {
this.state.verifyImportFixAtPosition(expectedTextArray, errorCode, preferences);
}
public importFixModuleSpecifiers(marker: string, moduleSpecifiers: string[], preferences?: ts.UserPreferences) {
public importFixModuleSpecifiers(marker: string, moduleSpecifiers: string[], preferences?: ts.UserPreferences): void {
this.state.verifyImportFixModuleSpecifiers(marker, moduleSpecifiers, preferences);
}
public baselineAutoImports(marker: string, fullNamesForCodeFix?: string[], options?: ts.UserPreferences) {
public baselineAutoImports(marker: string, fullNamesForCodeFix?: string[], options?: ts.UserPreferences): void {
this.state.baselineAutoImports(marker, fullNamesForCodeFix, options);
}
public navigationBar(json: any, options?: { checkSpans?: boolean; }) {
public navigationBar(json: any, options?: { checkSpans?: boolean; }): void {
this.state.verifyNavigationBar(json, options);
}
public navigationTree(json: any, options?: { checkSpans?: boolean; }) {
public navigationTree(json: any, options?: { checkSpans?: boolean; }): void {
this.state.verifyNavigationTree(json, options);
}
@ -548,26 +558,26 @@ export class Verify extends VerifyNegatable {
/**
* This method *requires* a contiguous, complete, and ordered stream of classifications for a file.
*/
public syntacticClassificationsAre(...classifications: { classificationType: string; text: string; }[]) {
public syntacticClassificationsAre(...classifications: { classificationType: string; text: string; }[]): void {
this.state.verifySyntacticClassifications(classifications);
}
public encodedSyntacticClassificationsLength(length: number) {
public encodedSyntacticClassificationsLength(length: number): void {
this.state.verifyEncodedSyntacticClassificationsLength(length);
}
public encodedSemanticClassificationsLength(format: ts.SemanticClassificationFormat, length: number) {
public encodedSemanticClassificationsLength(format: ts.SemanticClassificationFormat, length: number): void {
this.state.verifyEncodedSemanticClassificationsLength(format, length);
}
/**
* This method *requires* an ordered stream of classifications for a file, and spans are highly recommended.
*/
public semanticClassificationsAre(format: ts.SemanticClassificationFormat, ...classifications: Classification[]) {
public semanticClassificationsAre(format: ts.SemanticClassificationFormat, ...classifications: Classification[]): void {
this.state.verifySemanticClassifications(format, classifications);
}
public replaceWithSemanticClassifications(format: ts.SemanticClassificationFormat.TwentyTwenty) {
public replaceWithSemanticClassifications(format: ts.SemanticClassificationFormat.TwentyTwenty): void {
this.state.replaceWithSemanticClassifications(format);
}
@ -579,31 +589,31 @@ export class Verify extends VerifyNegatable {
fileToRename?: string,
expectedRange?: FourSlash.Range,
preferences?: ts.UserPreferences,
) {
): void {
this.state.verifyRenameInfoSucceeded(displayName, fullDisplayName, kind, kindModifiers, fileToRename, expectedRange, preferences);
}
public renameInfoFailed(message?: string, preferences?: ts.UserPreferences) {
public renameInfoFailed(message?: string, preferences?: ts.UserPreferences): void {
this.state.verifyRenameInfoFailed(message, preferences);
}
public baselineRename(markerOrRange?: ArrayOrSingle<FourSlash.MarkerOrNameOrRange>, options?: RenameOptions) {
public baselineRename(markerOrRange?: ArrayOrSingle<FourSlash.MarkerOrNameOrRange>, options?: RenameOptions): void {
this.state.baselineRename(markerOrRange, /*rangeText*/ undefined, options);
}
public baselineRenameAtRangesWithText(rangeText?: ArrayOrSingle<string>, options?: RenameOptions) {
public baselineRenameAtRangesWithText(rangeText?: ArrayOrSingle<string>, options?: RenameOptions): void {
this.state.baselineRename(/*markerOrRange*/ undefined, rangeText, options);
}
public verifyQuickInfoDisplayParts(kind: string, kindModifiers: string, textSpan: FourSlash.TextSpan, displayParts: ts.SymbolDisplayPart[], documentation: ts.SymbolDisplayPart[], tags: ts.JSDocTagInfo[]) {
public verifyQuickInfoDisplayParts(kind: string, kindModifiers: string, textSpan: FourSlash.TextSpan, displayParts: ts.SymbolDisplayPart[], documentation: ts.SymbolDisplayPart[], tags: ts.JSDocTagInfo[]): void {
this.state.verifyQuickInfoDisplayParts(kind, kindModifiers, textSpan, displayParts, documentation, tags);
}
public getSyntacticDiagnostics(expected: readonly Diagnostic[]) {
public getSyntacticDiagnostics(expected: readonly Diagnostic[]): void {
this.state.getSyntacticDiagnostics(expected);
}
public getSemanticDiagnostics(expected: readonly Diagnostic[]) {
public getSemanticDiagnostics(expected: readonly Diagnostic[]): void {
this.state.verifySemanticDiagnostics(expected);
}
@ -611,23 +621,23 @@ export class Verify extends VerifyNegatable {
ranges: ts.TextRange[],
expectedDiagnostics: readonly Diagnostic[],
expectedRanges: ts.TextRange[] | undefined,
) {
): void {
this.state.getRegionSemanticDiagnostics(ranges, expectedDiagnostics, expectedRanges);
}
public getSuggestionDiagnostics(expected: readonly Diagnostic[]) {
public getSuggestionDiagnostics(expected: readonly Diagnostic[]): void {
this.state.getSuggestionDiagnostics(expected);
}
public ProjectInfo(expected: string[]) {
public ProjectInfo(expected: string[]): void {
this.state.verifyProjectInfo(expected);
}
public getEditsForFileRename(options: GetEditsForFileRenameOptions) {
public getEditsForFileRename(options: GetEditsForFileRenameOptions): void {
this.state.getEditsForFileRename(options);
}
public baselineCallHierarchy() {
public baselineCallHierarchy(): void {
this.state.baselineCallHierarchy();
}
@ -655,70 +665,70 @@ export class Verify extends VerifyNegatable {
export class Edit {
constructor(private state: FourSlash.TestState) {
}
public caretPosition() {
public caretPosition(): FourSlash.Marker {
return this.state.caretPosition();
}
public backspace(count?: number) {
public backspace(count?: number): void {
this.state.deleteCharBehindMarker(count);
}
public deleteAtCaret(times?: number) {
public deleteAtCaret(times?: number): void {
this.state.deleteChar(times);
}
public replace(start: number, length: number, text: string) {
public replace(start: number, length: number, text: string): void {
this.state.replace(start, length, text);
}
public paste(text: string) {
public paste(text: string): void {
this.state.paste(text);
}
public insert(text: string) {
public insert(text: string): void {
this.insertLines(text);
}
public insertLine(text: string) {
public insertLine(text: string): void {
this.insertLines(text + "\n");
}
public insertLines(...lines: string[]) {
public insertLines(...lines: string[]): void {
this.state.type(lines.join("\n"));
}
public deleteLine(index: number) {
public deleteLine(index: number): void {
this.deleteLineRange(index, index);
}
public deleteLineRange(startIndex: number, endIndexInclusive: number) {
public deleteLineRange(startIndex: number, endIndexInclusive: number): void {
this.state.deleteLineRange(startIndex, endIndexInclusive);
}
public replaceLine(index: number, text: string) {
public replaceLine(index: number, text: string): void {
this.state.selectLine(index);
this.state.type(text);
}
public moveRight(count?: number) {
public moveRight(count?: number): void {
this.state.moveCaretRight(count);
}
public moveLeft(count?: number) {
public moveLeft(count?: number): void {
if (typeof count === "undefined") {
count = 1;
}
this.state.moveCaretRight(count * -1);
}
public enableFormatting() {
public enableFormatting(): void {
this.state.enableFormatting = true;
}
public disableFormatting() {
public disableFormatting(): void {
this.state.enableFormatting = false;
}
public applyRefactor(options: ApplyRefactorOptions) {
public applyRefactor(options: ApplyRefactorOptions): void {
this.state.applyRefactor(options);
}
}
@ -727,66 +737,66 @@ export class Debug {
constructor(private state: FourSlash.TestState) {
}
public printCurrentParameterHelp() {
public printCurrentParameterHelp(): void {
this.state.printCurrentParameterHelp();
}
public printCurrentFileState() {
public printCurrentFileState(): void {
this.state.printCurrentFileState(/*showWhitespace*/ false, /*makeCaretVisible*/ true);
}
public printCurrentFileStateWithWhitespace() {
public printCurrentFileStateWithWhitespace(): void {
this.state.printCurrentFileState(/*showWhitespace*/ true, /*makeCaretVisible*/ true);
}
public printCurrentFileStateWithoutCaret() {
public printCurrentFileStateWithoutCaret(): void {
this.state.printCurrentFileState(/*showWhitespace*/ false, /*makeCaretVisible*/ false);
}
public printCurrentQuickInfo() {
public printCurrentQuickInfo(): void {
this.state.printCurrentQuickInfo();
}
public printCurrentSignatureHelp() {
public printCurrentSignatureHelp(): void {
this.state.printCurrentSignatureHelp();
}
public printCompletionListMembers(options: ts.UserPreferences | undefined) {
public printCompletionListMembers(options: ts.UserPreferences | undefined): void {
this.state.printCompletionListMembers(options);
}
public printAvailableCodeFixes() {
public printAvailableCodeFixes(): void {
this.state.printAvailableCodeFixes();
}
public printBreakpointLocation(pos: number) {
public printBreakpointLocation(pos: number): void {
this.state.printBreakpointLocation(pos);
}
public printBreakpointAtCurrentLocation() {
public printBreakpointAtCurrentLocation(): void {
this.state.printBreakpointAtCurrentLocation();
}
public printNameOrDottedNameSpans(pos: number) {
public printNameOrDottedNameSpans(pos: number): void {
this.state.printNameOrDottedNameSpans(pos);
}
public printErrorList() {
public printErrorList(): void {
this.state.printErrorList();
}
public printNavigationItems(searchValue = ".*") {
public printNavigationItems(searchValue = ".*"): void {
this.state.printNavigationItems(searchValue);
}
public printNavigationBar() {
public printNavigationBar(): void {
this.state.printNavigationBar();
}
public printContext() {
public printContext(): void {
this.state.printContext();
}
public printOutliningSpans() {
public printOutliningSpans(): void {
this.state.printOutliningSpans();
}
}
@ -795,7 +805,7 @@ export class Format {
constructor(private state: FourSlash.TestState) {
}
public document() {
public document(): void {
this.state.formatDocument();
}
@ -803,15 +813,15 @@ export class Format {
return this.state.copyFormatOptions();
}
public setFormatOptions(options: ts.FormatCodeOptions) {
public setFormatOptions(options: ts.FormatCodeOptions): ts.FormatCodeSettings {
return this.state.setFormatOptions(options);
}
public selection(startMarker: string, endMarker: string) {
public selection(startMarker: string, endMarker: string): void {
this.state.formatSelection(this.state.getMarkerByName(startMarker).position, this.state.getMarkerByName(endMarker).position);
}
public onType(posMarker: string, key: string) {
public onType(posMarker: string, key: string): void {
this.state.formatOnType(this.state.getMarkerByName(posMarker).position, key);
}
@ -824,11 +834,11 @@ export class Cancellation {
constructor(private state: FourSlash.TestState) {
}
public resetCancelled() {
public resetCancelled(): void {
this.state.resetCancelled();
}
public setCancelled(numberOfCalls = 0) {
public setCancelled(numberOfCalls = 0): void {
this.state.setCancelled(numberOfCalls);
}
}
@ -848,7 +858,59 @@ interface ModernClassification {
type Classification = OlderClassification | ModernClassification;
export function classification(format: ts.SemanticClassificationFormat) {
export function classification(format: ts.SemanticClassificationFormat): {
semanticToken: (identifier: string, text: string, _position: number) => Classification;
comment?: undefined;
identifier?: undefined;
keyword?: undefined;
numericLiteral?: undefined;
operator?: undefined;
stringLiteral?: undefined;
whiteSpace?: undefined;
text?: undefined;
punctuation?: undefined;
docCommentTagName?: undefined;
className?: undefined;
enumName?: undefined;
interfaceName?: undefined;
moduleName?: undefined;
typeParameterName?: undefined;
parameterName?: undefined;
typeAliasName?: undefined;
jsxOpenTagName?: undefined;
jsxCloseTagName?: undefined;
jsxSelfClosingTagName?: undefined;
jsxAttribute?: undefined;
jsxText?: undefined;
jsxAttributeStringLiteralValue?: undefined;
getClassification?: undefined;
} | {
comment: (text: string, position?: number) => Classification;
identifier: (text: string, position?: number) => Classification;
keyword: (text: string, position?: number) => Classification;
numericLiteral: (text: string, position?: number) => Classification;
operator: (text: string, position?: number) => Classification;
stringLiteral: (text: string, position?: number) => Classification;
whiteSpace: (text: string, position?: number) => Classification;
text: (text: string, position?: number) => Classification;
punctuation: (text: string, position?: number) => Classification;
docCommentTagName: (text: string, position?: number) => Classification;
className: (text: string, position?: number) => Classification;
enumName: (text: string, position?: number) => Classification;
interfaceName: (text: string, position?: number) => Classification;
moduleName: (text: string, position?: number) => Classification;
typeParameterName: (text: string, position?: number) => Classification;
parameterName: (text: string, position?: number) => Classification;
typeAliasName: (text: string, position?: number) => Classification;
jsxOpenTagName: (text: string, position?: number) => Classification;
jsxCloseTagName: (text: string, position?: number) => Classification;
jsxSelfClosingTagName: (text: string, position?: number) => Classification;
jsxAttribute: (text: string, position?: number) => Classification;
jsxText: (text: string, position?: number) => Classification;
jsxAttributeStringLiteralValue: (text: string, position?: number) => Classification;
getClassification: (classificationType: ts.ClassificationTypeNames, text: string, position?: number) => Classification;
semanticToken?: undefined;
} {
function semanticToken(identifier: string, text: string, _position: number): Classification {
return {
classificationType: identifier,
@ -1137,7 +1199,7 @@ export namespace Completion {
return Object.assign(sorted([...providedByHarness, ...providedByTest]), { plusFunctionName: functionName, plusArgument: providedByTest });
}
export function typeKeywordsPlus(plus: readonly ExpectedCompletionEntry[]) {
export function typeKeywordsPlus(plus: readonly ExpectedCompletionEntry[]): ExpectedExactCompletionsPlus {
return combineExpectedCompletionEntries("typeKeywordsPlus", typeKeywords, plus);
}
@ -1268,8 +1330,8 @@ export namespace Completion {
kind: "module",
sortText: SortText.GlobalsOrKeywords,
};
export const globalTypes = globalTypesPlus([]);
export function globalTypesPlus(plus: readonly ExpectedCompletionEntry[]) {
export const globalTypes: ExpectedExactCompletionsPlus = globalTypesPlus([]);
export function globalTypesPlus(plus: readonly ExpectedCompletionEntry[]): ExpectedExactCompletionsPlus {
return combineExpectedCompletionEntries(
"globalTypesPlus",
[globalThisEntry, ...globalTypeDecls, ...typeKeywords],
@ -1332,7 +1394,7 @@ export namespace Completion {
"static",
].map(keywordEntry);
export const classElementInJsKeywords = getInJsKeywords(classElementKeywords);
export const classElementInJsKeywords: readonly ExpectedCompletionEntryObject[] = getInJsKeywords(classElementKeywords);
export const constructorParameterKeywords: readonly ExpectedCompletionEntryObject[] = ["override", "private", "protected", "public", "readonly"].map((name): ExpectedCompletionEntryObject => ({
name,
@ -1350,7 +1412,7 @@ export namespace Completion {
propertyEntry("caller"),
].sort(compareExpectedCompletionEntries);
export function functionMembersPlus(plus: readonly ExpectedCompletionEntryObject[]) {
export function functionMembersPlus(plus: readonly ExpectedCompletionEntryObject[]): ExpectedExactCompletionsPlus {
return combineExpectedCompletionEntries("functionMembersPlus", functionMembers, plus);
}
@ -1383,7 +1445,7 @@ export namespace Completion {
propertyEntry("prototype"),
].sort(compareExpectedCompletionEntries);
export function functionMembersWithPrototypePlus(plus: readonly ExpectedCompletionEntryObject[]) {
export function functionMembersWithPrototypePlus(plus: readonly ExpectedCompletionEntryObject[]): ExpectedCompletionEntryObject[] {
return [...functionMembersWithPrototype, ...plus].sort(compareExpectedCompletionEntries);
}
@ -1472,7 +1534,7 @@ export namespace Completion {
}
});
export const statementInJsKeywords = getInJsKeywords(statementKeywords);
export const statementInJsKeywords: readonly ExpectedCompletionEntryObject[] = getInJsKeywords(statementKeywords);
export const globalsVars: readonly ExpectedCompletionEntryObject[] = [
varEntry("Array"),
@ -1675,7 +1737,7 @@ export namespace Completion {
"yield",
].map(keywordEntry);
export const globalInJsKeywords = getInJsKeywords(globalKeywords);
export const globalInJsKeywords: readonly ExpectedCompletionEntryObject[] = getInJsKeywords(globalKeywords);
export const insideMethodKeywords: readonly ExpectedCompletionEntryObject[] = [
"as",
@ -1727,7 +1789,7 @@ export namespace Completion {
"yield",
].map(keywordEntry);
export const insideMethodInJsKeywords = getInJsKeywords(insideMethodKeywords);
export const insideMethodInJsKeywords: readonly ExpectedCompletionEntryObject[] = getInJsKeywords(insideMethodKeywords);
export const globals: readonly ExpectedCompletionEntryObject[] = [
globalThisEntry,
@ -1743,7 +1805,7 @@ export namespace Completion {
...globalInJsKeywords,
].sort(compareExpectedCompletionEntries);
export function globalsPlus(plus: readonly ExpectedCompletionEntry[], options?: { noLib?: boolean; }) {
export function globalsPlus(plus: readonly ExpectedCompletionEntry[], options?: { noLib?: boolean; }): ExpectedExactCompletionsPlus {
return combineExpectedCompletionEntries("globalsPlus", [
globalThisEntry,
...options?.noLib ? [] : globalsVars,
@ -1752,7 +1814,7 @@ export namespace Completion {
], plus);
}
export function globalsInJsPlus(plus: readonly ExpectedCompletionEntry[], options?: { noLib?: boolean; }) {
export function globalsInJsPlus(plus: readonly ExpectedCompletionEntry[], options?: { noLib?: boolean; }): ExpectedExactCompletionsPlus {
return combineExpectedCompletionEntries("globalsInJsPlus", [
globalThisEntry,
...options?.noLib ? [] : globalsVars,

Просмотреть файл

@ -44,7 +44,7 @@ export interface IO {
}
export let IO: IO;
export function setHarnessIO(io: IO) {
export function setHarnessIO(io: IO): void {
IO = io;
}
@ -173,7 +173,7 @@ export type SourceMapEmitterCallback = (
export let userSpecifiedRoot = "";
export let lightMode = false;
/* eslint-enable prefer-const */
export function setLightMode(flag: boolean) {
export function setLightMode(flag: boolean): void {
lightMode = flag;
}
@ -186,23 +186,23 @@ export namespace Compiler {
public lines: string[] = [];
public currentLine: string = undefined!;
public Write(str: string) {
public Write(str: string): void {
// out of memory usage concerns avoid using + or += if we're going to do any manipulation of this string later
this.currentLine = [this.currentLine || "", str].join("");
}
public WriteLine(str: string) {
public WriteLine(str: string): void {
// out of memory usage concerns avoid using + or += if we're going to do any manipulation of this string later
this.lines.push([this.currentLine || "", str].join(""));
this.currentLine = undefined!;
}
public Close() {
public Close(): void {
if (this.currentLine !== undefined) this.lines.push(this.currentLine);
this.currentLine = undefined!;
}
public reset() {
public reset(): void {
this.lines = [];
this.currentLine = undefined!;
}
@ -212,7 +212,7 @@ export namespace Compiler {
fileName: string,
sourceText: string,
languageVersionOrOptions: ts.ScriptTarget | ts.CreateSourceFileOptions,
) {
): ts.SourceFile {
// We'll only assert invariants outside of light mode.
const shouldAssertInvariants = !lightMode;
@ -235,7 +235,7 @@ export namespace Compiler {
// Cache of lib files from "built/local"
export let libFileNameSourceFileMap: Map<string, ts.SourceFile> | undefined;
export function getDefaultLibrarySourceFile(fileName = defaultLibFileName): ts.SourceFile | undefined {
export function getDefaultLibrarySourceFile(fileName: string = defaultLibFileName): ts.SourceFile | undefined {
if (!isDefaultLibraryFile(fileName)) {
return undefined;
}
@ -519,7 +519,11 @@ export namespace Compiler {
}
}
export function compileDeclarationFiles(context: DeclarationCompilationContext | undefined, symlinks: vfs.FileSet | undefined) {
export function compileDeclarationFiles(context: DeclarationCompilationContext | undefined, symlinks: vfs.FileSet | undefined): {
declInputFiles: TestFile[];
declOtherFiles: TestFile[];
declResult: CompileFilesResult;
} | undefined {
if (!context) {
return;
}
@ -528,12 +532,12 @@ export namespace Compiler {
return { declInputFiles, declOtherFiles, declResult: output };
}
export function minimalDiagnosticsToString(diagnostics: readonly ts.Diagnostic[], pretty?: boolean) {
export function minimalDiagnosticsToString(diagnostics: readonly ts.Diagnostic[], pretty?: boolean): string {
const host = { getCanonicalFileName, getCurrentDirectory: () => "", getNewLine: () => IO.newLine() };
return (pretty ? ts.formatDiagnosticsWithColorAndContext : ts.formatDiagnostics)(diagnostics, host);
}
export function getErrorBaseline(inputFiles: readonly TestFile[], diagnostics: readonly ts.Diagnostic[], pretty?: boolean) {
export function getErrorBaseline(inputFiles: readonly TestFile[], diagnostics: readonly ts.Diagnostic[], pretty?: boolean): string {
let outputLines = "";
const gen = iterateErrorBaseline(inputFiles, diagnostics, { pretty });
for (const value of gen) {
@ -708,11 +712,21 @@ export namespace Compiler {
assert.equal(totalErrorsReportedInNonLibraryNonTsconfigFiles + numLibraryDiagnostics + numTsconfigDiagnostics, diagnostics.length, "total number of errors");
}
export function doErrorBaseline(baselinePath: string, inputFiles: readonly TestFile[], errors: readonly ts.Diagnostic[], pretty?: boolean) {
export function doErrorBaseline(baselinePath: string, inputFiles: readonly TestFile[], errors: readonly ts.Diagnostic[], pretty?: boolean): void {
Baseline.runBaseline(baselinePath.replace(/\.tsx?$/, ".errors.txt"), !errors || (errors.length === 0) ? null : getErrorBaseline(inputFiles, errors, pretty)); // eslint-disable-line no-restricted-syntax
}
export function doTypeAndSymbolBaseline(baselinePath: string, header: string, program: ts.Program, allFiles: { unitName: string; content: string; }[], opts?: Baseline.BaselineOptions, multifile?: boolean, skipTypeBaselines?: boolean, skipSymbolBaselines?: boolean, hasErrorBaseline?: boolean) {
export function doTypeAndSymbolBaseline(
baselinePath: string,
header: string,
program: ts.Program,
allFiles: { unitName: string; content: string; }[],
opts?: Baseline.BaselineOptions,
multifile?: boolean,
skipTypeBaselines?: boolean,
skipSymbolBaselines?: boolean,
hasErrorBaseline?: boolean,
): void {
// The full walker simulates the types that you would get from doing a full
// compile. The pull walker simulates the types you get when you just do
// a type query for a random node (like how the LS would do it). Most of the
@ -903,7 +917,7 @@ export namespace Compiler {
}
}
export function doSourcemapBaseline(baselinePath: string, options: ts.CompilerOptions, result: compiler.CompilationResult, harnessSettings: TestCaseParser.CompilerSettings) {
export function doSourcemapBaseline(baselinePath: string, options: ts.CompilerOptions, result: compiler.CompilationResult, harnessSettings: TestCaseParser.CompilerSettings): void {
const declMaps = ts.getAreDeclarationMapsEnabled(options);
if (options.inlineSourceMap) {
if (result.maps.size > 0 && !declMaps) {
@ -949,7 +963,16 @@ export namespace Compiler {
return "\n//// https://sokra.github.io/source-map-visualization" + hash + "\n";
}
export function doJsEmitBaseline(baselinePath: string, header: string, options: ts.CompilerOptions, result: CompileFilesResult, tsConfigFiles: readonly TestFile[], toBeCompiled: readonly TestFile[], otherFiles: readonly TestFile[], harnessSettings: TestCaseParser.CompilerSettings) {
export function doJsEmitBaseline(
baselinePath: string,
header: string,
options: ts.CompilerOptions,
result: CompileFilesResult,
tsConfigFiles: readonly TestFile[],
toBeCompiled: readonly TestFile[],
otherFiles: readonly TestFile[],
harnessSettings: TestCaseParser.CompilerSettings,
): void {
if (!options.noEmit && !options.emitDeclarationOnly && result.js.size === 0 && result.diagnostics.length === 0) {
throw new Error("Expected at least one js file to be emitted or at least one error to be created.");
}
@ -1081,7 +1104,7 @@ export namespace Compiler {
return resultName;
}
export function sanitizeTestFilePath(name: string) {
export function sanitizeTestFilePath(name: string): string {
const path = ts.toPath(ts.normalizeSlashes(name.replace(/[\^<>:"|?*%]/g, "_")).replace(/\.\.\//g, "__dotdot/"), "", Utils.canonicalizeForHarness);
if (ts.startsWith(path, "/")) {
return path.substring(1);
@ -1221,7 +1244,7 @@ export function getFileBasedTestConfigurations(settings: TestCaseParser.Compiler
/**
* Compute a description for this configuration based on its entries
*/
export function getFileBasedTestConfigurationDescription(configuration: FileBasedTestConfiguration) {
export function getFileBasedTestConfigurationDescription(configuration: FileBasedTestConfiguration): string {
let name = "";
if (configuration) {
const keys = Object.keys(configuration).sort();
@ -1252,7 +1275,7 @@ export namespace TestCaseParser {
const optionRegex = /^\/{2}\s*@(\w+)\s*:\s*([^\r\n]*)/gm; // multiple matches on multiple lines
const linkRegex = /^\/{2}\s*@link\s*:\s*([^\r\n]*)\s*->\s*([^\r\n]*)/gm; // multiple matches on multiple lines
export function parseSymlinkFromTest(line: string, symlinks: vfs.FileSet | undefined, absoluteRootDir?: string) {
export function parseSymlinkFromTest(line: string, symlinks: vfs.FileSet | undefined, absoluteRootDir?: string): vfs.FileSet | undefined {
const linkMetaData = linkRegex.exec(line);
linkRegex.lastIndex = 0;
if (!linkMetaData) return undefined;
@ -1282,7 +1305,7 @@ export namespace TestCaseParser {
}
/** Given a test file containing // @FileName directives, return an array of named units of code to be added to an existing compiler instance */
export function makeUnitsFromTest(code: string, fileName: string, settings = extractCompilerSettings(code)): TestCaseContent {
export function makeUnitsFromTest(code: string, fileName: string, settings: CompilerSettings = extractCompilerSettings(code)): TestCaseContent {
// List of all the subfiles we've parsed out
const testUnitData: TestUnitData[] = [];
@ -1427,7 +1450,7 @@ export namespace Baseline {
PrintDiff?: true;
}
export function localPath(fileName: string, baselineFolder?: string, subfolder?: string) {
export function localPath(fileName: string, baselineFolder?: string, subfolder?: string): string {
if (baselineFolder === undefined) {
return baselinePath(fileName, "local", "tests/baselines", subfolder);
}

Просмотреть файл

@ -113,7 +113,7 @@ class ScriptSnapshot implements ts.IScriptSnapshot {
}
class DefaultHostCancellationToken implements ts.HostCancellationToken {
public static readonly instance = new DefaultHostCancellationToken();
public static readonly instance: DefaultHostCancellationToken = new DefaultHostCancellationToken();
public isCancellationRequested() {
return false;
@ -129,16 +129,16 @@ export interface LanguageServiceAdapter {
}
export abstract class LanguageServiceAdapterHost {
public readonly sys = new fakes.System(new vfs.FileSystem(/*ignoreCase*/ true, { cwd: virtualFileSystemRoot }));
public readonly sys: fakes.System = new fakes.System(new vfs.FileSystem(/*ignoreCase*/ true, { cwd: virtualFileSystemRoot }));
public typesRegistry: Map<string, void> | undefined;
private scriptInfos: collections.SortedMap<string, ScriptInfo>;
public jsDocParsingMode: ts.JSDocParsingMode | undefined;
constructor(protected cancellationToken = DefaultHostCancellationToken.instance, protected settings = ts.getDefaultCompilerOptions()) {
constructor(protected cancellationToken: DefaultHostCancellationToken = DefaultHostCancellationToken.instance, protected settings: ts.CompilerOptions = ts.getDefaultCompilerOptions()) {
this.scriptInfos = new collections.SortedMap({ comparer: this.vfs.stringComparer, sort: "insertion" });
}
public get vfs() {
public get vfs(): vfs.FileSystem {
return this.sys.vfs;
}
@ -185,7 +185,7 @@ export abstract class LanguageServiceAdapterHost {
}
}
public directoryExists(path: string) {
public directoryExists(path: string): boolean {
return this.vfs.statSync(path).isDirectory();
}
@ -214,7 +214,7 @@ export abstract class LanguageServiceAdapterHost {
});
}
public editScript(fileName: string, start: number, end: number, newText: string) {
public editScript(fileName: string, start: number, end: number, newText: string): void {
const script = this.getScriptInfo(fileName);
if (script) {
script.editContent(start, end, newText);
@ -244,7 +244,7 @@ export abstract class LanguageServiceAdapterHost {
return ts.computePositionOfLineAndCharacter(script.getLineMap(), lineAndCharacter.line, lineAndCharacter.character);
}
useCaseSensitiveFileNames() {
useCaseSensitiveFileNames(): boolean {
return !this.vfs.ignoreCase;
}
}
@ -257,17 +257,17 @@ class NativeLanguageServiceHost extends LanguageServiceAdapterHost implements ts
return !!this.typesRegistry && this.typesRegistry.has(name);
}
getGlobalTypingsCacheLocation() {
getGlobalTypingsCacheLocation(): string {
return harnessTypingInstallerCacheLocation;
}
installPackage = ts.notImplemented;
installPackage: typeof ts.notImplemented = ts.notImplemented;
getCompilationSettings() {
getCompilationSettings(): ts.CompilerOptions {
return this.settings;
}
getCancellationToken() {
getCancellationToken(): DefaultHostCancellationToken {
return this.cancellationToken;
}
@ -325,14 +325,14 @@ class NativeLanguageServiceHost extends LanguageServiceAdapterHost implements ts
return 0;
}
log = ts.noop;
trace = ts.noop;
error = ts.noop;
log: typeof ts.noop = ts.noop;
trace: typeof ts.noop = ts.noop;
error: typeof ts.noop = ts.noop;
}
export class NativeLanguageServiceAdapter implements LanguageServiceAdapter {
private host: NativeLanguageServiceHost;
getLogger = ts.returnUndefined;
getLogger: typeof ts.returnUndefined = ts.returnUndefined;
constructor(cancellationToken?: ts.HostCancellationToken, options?: ts.CompilerOptions) {
this.host = new NativeLanguageServiceHost(cancellationToken, options);
}
@ -367,10 +367,10 @@ class SessionClientHost extends NativeLanguageServiceHost implements ts.server.S
return harnessSessionCurrentDirectory;
}
onMessage = ts.noop;
writeMessage = ts.noop;
onMessage: typeof ts.noop = ts.noop;
writeMessage: typeof ts.noop = ts.noop;
setClient(client: ts.server.SessionClient) {
setClient(client: ts.server.SessionClient): void {
this.client = client;
}
@ -379,7 +379,7 @@ class SessionClientHost extends NativeLanguageServiceHost implements ts.server.S
this.client.openFile(fileName, content, scriptKindName);
}
override editScript(fileName: string, start: number, end: number, newText: string) {
override editScript(fileName: string, start: number, end: number, newText: string): void {
const changeArgs = this.client.createChangeFileRequestArgs(fileName, start, end, newText);
super.editScript(fileName, start, end, newText);
this.client.changeFile(fileName, changeArgs);
@ -675,10 +675,10 @@ export class ServerLanguageServiceAdapter implements LanguageServiceAdapter {
this.client = client;
this.host = clientHost;
}
getLogger() {
getLogger(): LoggerWithInMemoryLogs {
return this.logger;
}
getHost() {
getHost(): SessionClientHost {
return this.host;
}
getLanguageService(): ts.LanguageService {
@ -690,7 +690,7 @@ export class ServerLanguageServiceAdapter implements LanguageServiceAdapter {
getPreProcessedFileInfo(): ts.PreProcessedFileInfo {
throw new Error("getPreProcessedFileInfo is not available using the server interface.");
}
assertTextConsistent(fileName: string) {
assertTextConsistent(fileName: string): void {
const serverText = this.server.getText(fileName);
const clientText = this.host.readFile(fileName);
ts.Debug.assert(

Просмотреть файл

@ -6,7 +6,7 @@ export function encodeString(s: string): string {
return Buffer.from(s).toString("utf8");
}
export function evalFile(fileContents: string, fileName: string, nodeContext?: any) {
export function evalFile(fileContents: string, fileName: string, nodeContext?: any): void {
if (nodeContext) {
vm.runInNewContext(fileContents, nodeContext, fileName);
}
@ -16,7 +16,7 @@ export function evalFile(fileContents: string, fileName: string, nodeContext?: a
}
/** Splits the given string on \r\n, or on only \n if that fails, or on only \r if *that* fails. */
export function splitContentByNewlines(content: string) {
export function splitContentByNewlines(content: string): string[] {
// Split up the input file by line
// Note: IE JS engine incorrectly handles consecutive delimiters here when using RegExp split, so
// we have to use string-based splitting instead and try to figure out the delimiting chars
@ -32,7 +32,7 @@ export function splitContentByNewlines(content: string) {
}
/** Reads a file under /tests */
export function readTestFile(path: string) {
export function readTestFile(path: string): string | undefined {
if (!path.includes("tests")) {
path = "tests/" + path;
}
@ -64,9 +64,9 @@ export function memoize<T extends ts.AnyFunction>(f: T, memoKey: (...anything: a
} as any);
}
export const canonicalizeForHarness = ts.createGetCanonicalFileName(/*useCaseSensitiveFileNames*/ false); // This is done so tests work on windows _and_ linux
export const canonicalizeForHarness: ts.GetCanonicalFileName = ts.createGetCanonicalFileName(/*useCaseSensitiveFileNames*/ false); // This is done so tests work on windows _and_ linux
export function assertInvariants(node: ts.Node | undefined, parent: ts.Node | undefined) {
export function assertInvariants(node: ts.Node | undefined, parent: ts.Node | undefined): void {
const queue: [ts.Node | undefined, ts.Node | undefined][] = [[node, parent]];
for (const [node, parent] of queue) {
assertInvariantsWorker(node, parent);
@ -149,7 +149,13 @@ function isNodeOrArray(a: any): boolean {
return a !== undefined && typeof a.pos === "number";
}
export function convertDiagnostics(diagnostics: readonly ts.Diagnostic[]) {
export function convertDiagnostics(diagnostics: readonly ts.Diagnostic[]): {
start: number | undefined;
length: number | undefined;
messageText: string;
category: string;
code: number;
}[] {
return diagnostics.map(convertDiagnostic);
}
@ -247,7 +253,7 @@ export function sourceFileToJSON(file: ts.Node): string {
}
}
export function assertDiagnosticsEquals(array1: readonly ts.Diagnostic[], array2: readonly ts.Diagnostic[]) {
export function assertDiagnosticsEquals(array1: readonly ts.Diagnostic[], array2: readonly ts.Diagnostic[]): void {
if (array1 === array2) {
return;
}
@ -273,7 +279,7 @@ export function assertDiagnosticsEquals(array1: readonly ts.Diagnostic[], array2
}
}
export function assertStructuralEquals(node1: ts.Node, node2: ts.Node) {
export function assertStructuralEquals(node1: ts.Node, node2: ts.Node): void {
if (node1 === node2) {
return;
}
@ -330,7 +336,7 @@ function findChildName(parent: any, child: any) {
const maxHarnessFrames = 1;
export function filterStack(error: Error, stackTraceLimit = Infinity) {
export function filterStack(error: Error, stackTraceLimit: number = Infinity): Error {
const stack = (error as any).stack as string;
if (stack) {
const lines = stack.split(/\r\n?|\n/);

Просмотреть файл

@ -1,6 +1,6 @@
import * as ts from "./_namespaces/ts.js";
export function reportDocumentRegistryStats(documentRegistry: ts.DocumentRegistry) {
export function reportDocumentRegistryStats(documentRegistry: ts.DocumentRegistry): string[] {
const str: string[] = [];
documentRegistry.getBuckets().forEach((bucketEntries, key) => {
str.push(` Key:: ${key}`);
@ -193,7 +193,7 @@ function getProgramStructure(program: ts.Program | undefined) {
return baseline.join("\n");
}
export function verifyProgramStructure(expectedProgram: ts.Program, actualProgram: ts.Program, projectName: string) {
export function verifyProgramStructure(expectedProgram: ts.Program, actualProgram: ts.Program, projectName: string): void {
const actual = getProgramStructure(actualProgram);
const expected = getProgramStructure(expectedProgram);
ts.Debug.assert(actual === expected, `Program verification:: ${projectName}`);
@ -204,7 +204,7 @@ export function verifyResolutionCache(
actualProgram: ts.Program,
resolutionHostCacheHost: ts.ResolutionCacheHost,
projectName: string,
) {
): void {
const currentDirectory = resolutionHostCacheHost.getCurrentDirectory!();
const expected = ts.createResolutionCache(resolutionHostCacheHost, actual.rootDirForResolution, /*logChangesWhenResolvingModule*/ false);
expected.startCachingPerDirectoryResolution();
@ -645,7 +645,7 @@ export interface IncrementalVerifierCallbacks {
afterVerification?(dataFromBefore: any): void;
}
export function incrementalVerifier(service: ts.server.ProjectService) {
export function incrementalVerifier(service: ts.server.ProjectService): void {
service.verifyDocumentRegistry = withIncrementalVerifierCallbacks(service, verifyDocumentRegistry);
service.verifyProgram = withIncrementalVerifierCallbacks(service, verifyProgram);
service.onProjectCreation = onProjectCreation;

Просмотреть файл

@ -67,7 +67,7 @@ enum Diff {
type StatePropertyLog = string | string[];
type StateItemLog = [string, StatePropertyLog[]];
export function patchServiceForStateBaseline(service: ProjectService) {
export function patchServiceForStateBaseline(service: ProjectService): void {
if (!service.logger.isTestLogger || !service.logger.hasLevel(LogLevel.verbose)) return;
if (service.baseline !== noop) return; // Already patched

Просмотреть файл

@ -12,10 +12,10 @@ export let shards = 1;
export let shardId = 1;
// The following have setters as while they're read here in the harness, they're only set in the runner
export function setShards(count: number) {
export function setShards(count: number): void {
shards = count;
}
export function setShardId(id: number) {
export function setShardId(id: number): void {
shardId = id;
}
@ -24,7 +24,7 @@ export abstract class RunnerBase {
public tests: string[] = [];
/** Add a source file to the runner's list of tests that need to be initialized with initializeTests */
public addTest(fileName: string) {
public addTest(fileName: string): void {
this.tests.push(fileName);
}
@ -53,7 +53,7 @@ export abstract class RunnerBase {
public abstract initializeTests(): void;
/** Replaces instances of full paths with fileNames only */
static removeFullPaths(path: string) {
static removeFullPaths(path: string): string {
// If its a full path (starts with "C:" or "/") replace with just the filename
let fixedPath = /^(?:\w:|\/)/.test(path) ? ts.getBaseFileName(path) : path;

Просмотреть файл

@ -277,7 +277,7 @@ namespace SourceMapSpanWriter {
}
}
export function getSourceMapRecord(sourceMapDataList: readonly ts.SourceMapEmitResult[], program: ts.Program, jsFiles: readonly documents.TextDocument[], declarationFiles: readonly documents.TextDocument[]) {
export function getSourceMapRecord(sourceMapDataList: readonly ts.SourceMapEmitResult[], program: ts.Program, jsFiles: readonly documents.TextDocument[], declarationFiles: readonly documents.TextDocument[]): string {
const sourceMapRecorder = new Compiler.WriterAggregator();
for (let i = 0; i < sourceMapDataList.length; i++) {
@ -324,7 +324,7 @@ export function getSourceMapRecord(sourceMapDataList: readonly ts.SourceMapEmitR
return sourceMapRecorder.lines.join("\r\n");
}
export function getSourceMapRecordWithSystem(sys: ts.System, sourceMapFile: string) {
export function getSourceMapRecordWithSystem(sys: ts.System, sourceMapFile: string): string {
const sourceMapRecorder = new Compiler.WriterAggregator();
let prevSourceFile: documents.TextDocument | undefined;
const files = new Map<string, documents.TextDocument>();

Просмотреть файл

@ -21,14 +21,14 @@ const replaceTypesVersionsMessage = createDiagnosticMessageReplacer(
([entry, , moduleName], compilerVersion) => [entry, compilerVersion, moduleName],
);
export function sanitizeTraceResolutionLogEntry(text: string) {
export function sanitizeTraceResolutionLogEntry(text: string): string {
return text && replaceTypesVersionsMessage(text, "3.1.0-dev");
}
/**
* Removes leading indentation from a template literal string.
*/
export function dedent(array: TemplateStringsArray, ...args: any[]) {
export function dedent(array: TemplateStringsArray, ...args: any[]): string {
let text = array[0];
for (let i = 0; i < args.length; i++) {
text += args[i];
@ -97,11 +97,11 @@ export function removeByteOrderMark(text: string): string {
return length ? text.slice(length) : text;
}
export function addUTF8ByteOrderMark(text: string) {
export function addUTF8ByteOrderMark(text: string): string {
return getByteOrderMarkLength(text) === 0 ? "\u00EF\u00BB\u00BF" + text : text;
}
export function theory<T extends any[]>(name: string, cb: (...args: T) => void, data: T[]) {
export function theory<T extends any[]>(name: string, cb: (...args: T) => void, data: T[]): void {
for (const entry of data) {
it(`${name}(${entry.map(formatTheoryDatum).join(", ")})`, () => cb(...entry));
}

Просмотреть файл

@ -111,14 +111,14 @@ export class FileSystem {
/**
* Gets a value indicating whether the file system is read-only.
*/
public get isReadonly() {
public get isReadonly(): boolean {
return Object.isFrozen(this);
}
/**
* Makes the file system read-only.
*/
public makeReadonly() {
public makeReadonly(): this {
Object.freeze(this);
return this;
}
@ -126,7 +126,7 @@ export class FileSystem {
/**
* Gets the file system shadowed by this file system.
*/
public get shadowRoot() {
public get shadowRoot(): FileSystem | undefined {
return this._shadowRoot;
}
@ -135,7 +135,7 @@ export class FileSystem {
* generating file system patches using `.diff()` from one snapshot to the next. Performs
* no action if this file system is read-only.
*/
public snapshot() {
public snapshot(): void {
if (this.isReadonly) return;
const fs = new FileSystem(this.ignoreCase, { time: this._time });
fs._lazy = this._lazy;
@ -153,7 +153,7 @@ export class FileSystem {
* original, allowing multiple copies of the same core file system without multiple copies
* of the same data.
*/
public shadow(ignoreCase = this.ignoreCase) {
public shadow(ignoreCase: boolean = this.ignoreCase): FileSystem {
if (!this.isReadonly) throw new Error("Cannot shadow a mutable file system.");
if (ignoreCase && !this.ignoreCase) throw new Error("Cannot create a case-insensitive file system from a case-sensitive one.");
const fs = new FileSystem(ignoreCase, { time: this._time });
@ -201,7 +201,7 @@ export class FileSystem {
*
* @link - http://pubs.opengroup.org/onlinepubs/9699919799/functions/getcwd.html
*/
public cwd() {
public cwd(): string {
if (!this._cwd) throw new Error("The current working directory has not been set.");
const { node } = this._walk(this._cwd);
if (!node) throw createIOError("ENOENT");
@ -214,7 +214,7 @@ export class FileSystem {
*
* @link http://pubs.opengroup.org/onlinepubs/9699919799/functions/chdir.html
*/
public chdir(path: string) {
public chdir(path: string): void {
if (this.isReadonly) throw createIOError("EPERM");
path = this._resolve(path);
const { node } = this._walk(path);
@ -226,7 +226,7 @@ export class FileSystem {
/**
* Pushes the current directory onto the directory stack and changes the current working directory to the supplied path.
*/
public pushd(path?: string) {
public pushd(path?: string): void {
if (this.isReadonly) throw createIOError("EPERM");
if (path) path = this._resolve(path);
if (this._cwd) {
@ -241,7 +241,7 @@ export class FileSystem {
/**
* Pops the previous directory from the location stack and changes the current directory to that directory.
*/
public popd() {
public popd(): void {
if (this.isReadonly) throw createIOError("EPERM");
const path = this._dirStack && this._dirStack.pop();
if (path) {
@ -252,7 +252,7 @@ export class FileSystem {
/**
* Update the file system with a set of files.
*/
public apply(files: FileSet) {
public apply(files: FileSet): void {
this._applyFiles(files, this._cwd);
}
@ -262,7 +262,7 @@ export class FileSystem {
* @param axis The axis along which to traverse.
* @param traversal The traversal scheme to use.
*/
public scanSync(path: string, axis: Axis, traversal: Traversal) {
public scanSync(path: string, axis: Axis, traversal: Traversal): string[] {
path = this._resolve(path);
const results: string[] = [];
this._scan(path, this._stat(this._walk(path)), axis, traversal, /*noFollow*/ false, results);
@ -275,7 +275,7 @@ export class FileSystem {
* @param axis The axis along which to traverse.
* @param traversal The traversal scheme to use.
*/
public lscanSync(path: string, axis: Axis, traversal: Traversal) {
public lscanSync(path: string, axis: Axis, traversal: Traversal): string[] {
path = this._resolve(path);
const results: string[] = [];
this._scan(path, this._stat(this._walk(path, /*noFollow*/ true)), axis, traversal, /*noFollow*/ true, results);
@ -321,7 +321,7 @@ export class FileSystem {
* @param target The path in this virtual file system.
* @param resolver An object used to resolve files in `source`.
*/
public mountSync(source: string, target: string, resolver: FileSystemResolver) {
public mountSync(source: string, target: string, resolver: FileSystemResolver): void {
if (this.isReadonly) throw createIOError("EROFS");
source = vpath.validate(source, vpath.ValidationFlags.Absolute);
@ -339,7 +339,7 @@ export class FileSystem {
/**
* Recursively remove all files and directories underneath the provided path.
*/
public rimrafSync(path: string) {
public rimrafSync(path: string): void {
try {
const stats = this.lstatSync(path);
if (stats.isFile() || stats.isSymbolicLink()) {
@ -361,7 +361,7 @@ export class FileSystem {
/**
* Make a directory and all of its parent paths (if they don't exist).
*/
public mkdirpSync(path: string) {
public mkdirpSync(path: string): void {
path = this._resolve(path);
const result = this._walk(path, /*noFollow*/ true, (error, result) => {
if (error.code === "ENOENT") {
@ -410,7 +410,7 @@ export class FileSystem {
/**
* Determines whether a path exists.
*/
public existsSync(path: string) {
public existsSync(path: string): boolean {
const result = this._walk(this._resolve(path), /*noFollow*/ true, () => "stop");
return result !== undefined && result.node !== undefined;
}
@ -422,7 +422,7 @@ export class FileSystem {
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public statSync(path: string) {
public statSync(path: string): Stats {
return this._stat(this._walk(this._resolve(path)));
}
@ -431,7 +431,7 @@ export class FileSystem {
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public utimesSync(path: string, atime: Date, mtime: Date) {
public utimesSync(path: string, atime: Date, mtime: Date): void {
if (this.isReadonly) throw createIOError("EROFS");
if (!isFinite(+atime) || !isFinite(+mtime)) throw createIOError("EINVAL");
@ -451,7 +451,7 @@ export class FileSystem {
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public lstatSync(path: string) {
public lstatSync(path: string): Stats {
return this._stat(this._walk(this._resolve(path), /*noFollow*/ true));
}
@ -481,7 +481,7 @@ export class FileSystem {
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public readdirSync(path: string) {
public readdirSync(path: string): string[] {
const { node } = this._walk(this._resolve(path));
if (!node) throw createIOError("ENOENT");
if (!isDirectory(node)) throw createIOError("ENOTDIR");
@ -495,7 +495,7 @@ export class FileSystem {
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public mkdirSync(path: string) {
public mkdirSync(path: string): void {
if (this.isReadonly) throw createIOError("EROFS");
this._mkdir(this._walk(this._resolve(path), /*noFollow*/ true));
@ -515,7 +515,7 @@ export class FileSystem {
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public rmdirSync(path: string) {
public rmdirSync(path: string): void {
if (this.isReadonly) throw createIOError("EROFS");
path = this._resolve(path);
@ -534,7 +534,7 @@ export class FileSystem {
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public linkSync(oldpath: string, newpath: string) {
public linkSync(oldpath: string, newpath: string): void {
if (this.isReadonly) throw createIOError("EROFS");
const { node } = this._walk(this._resolve(oldpath));
@ -555,7 +555,7 @@ export class FileSystem {
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public unlinkSync(path: string) {
public unlinkSync(path: string): void {
if (this.isReadonly) throw createIOError("EROFS");
const { parent, links, node, basename } = this._walk(this._resolve(path), /*noFollow*/ true);
@ -573,7 +573,7 @@ export class FileSystem {
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public renameSync(oldpath: string, newpath: string) {
public renameSync(oldpath: string, newpath: string): void {
if (this.isReadonly) throw createIOError("EROFS");
const { parent: oldParent, links: oldParentLinks, node, basename: oldBasename } = this._walk(this._resolve(oldpath), /*noFollow*/ true);
@ -607,7 +607,7 @@ export class FileSystem {
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public symlinkSync(target: string, linkpath: string) {
public symlinkSync(target: string, linkpath: string): void {
if (this.isReadonly) throw createIOError("EROFS");
const { parent, links, node: existingNode, basename } = this._walk(this._resolve(linkpath), /*noFollow*/ true);
@ -627,7 +627,7 @@ export class FileSystem {
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public realpathSync(path: string) {
public realpathSync(path: string): string {
const { realpath } = this._walk(this._resolve(path));
return realpath;
}
@ -666,7 +666,7 @@ export class FileSystem {
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
// eslint-disable-next-line no-restricted-syntax
public writeFileSync(path: string, data: string | Buffer, encoding: string | null = null) {
public writeFileSync(path: string, data: string | Buffer, encoding: string | null = null): void {
if (this.isReadonly) throw createIOError("EROFS");
const { parent, links, node: existingNode, basename } = this._walk(this._resolve(path), /*noFollow*/ false);
@ -694,7 +694,7 @@ export class FileSystem {
* Generates a `FileSet` patch containing all the entries in this `FileSystem` that are not in `base`.
* @param base The base file system. If not provided, this file system's `shadowRoot` is used (if present).
*/
public diff(base?: FileSystem | undefined, options: DiffOptions = {}) {
public diff(base?: FileSystem | undefined, options: DiffOptions = {}): FileSet | undefined {
if (!base && !options.baseIsNotShadowRoot) base = this.shadowRoot;
const differences: FileSet = {};
const hasDifferences = base ?
@ -707,7 +707,7 @@ export class FileSystem {
/**
* Generates a `FileSet` patch containing all the entries in `changed` that are not in `base`.
*/
public static diff(changed: FileSystem, base: FileSystem, options: DiffOptions = {}) {
public static diff(changed: FileSystem, base: FileSystem, options: DiffOptions = {}): FileSet | undefined {
const differences: FileSet = {};
return FileSystem.rootDiff(differences, changed, base, options) ?
differences :
@ -1253,7 +1253,7 @@ export function createResolver(host: FileSystemResolverHost): FileSystemResolver
*
* Unless overridden, `/.src` will be the current working directory for the virtual file system.
*/
export function createFromFileSystem(host: FileSystemResolverHost, ignoreCase: boolean, { documents, files, cwd, time, meta }: FileSystemCreateOptions = {}) {
export function createFromFileSystem(host: FileSystemResolverHost, ignoreCase: boolean, { documents, files, cwd, time, meta }: FileSystemCreateOptions = {}): FileSystem {
const fs = getBuiltLocal(host, ignoreCase).shadow();
if (meta) {
for (const key of Object.keys(meta)) {
@ -1331,30 +1331,31 @@ export class Stats {
this.birthtime = new Date(this.birthtimeMs);
}
public isFile() {
public isFile(): boolean {
return (this.mode & S_IFMT) === S_IFREG;
}
public isDirectory() {
public isDirectory(): boolean {
return (this.mode & S_IFMT) === S_IFDIR;
}
public isSymbolicLink() {
public isSymbolicLink(): boolean {
return (this.mode & S_IFMT) === S_IFLNK;
}
public isBlockDevice() {
public isBlockDevice(): boolean {
return (this.mode & S_IFMT) === S_IFBLK;
}
public isCharacterDevice() {
public isCharacterDevice(): boolean {
return (this.mode & S_IFMT) === S_IFCHR;
}
public isFIFO() {
public isFIFO(): boolean {
return (this.mode & S_IFMT) === S_IFIFO;
}
public isSocket() {
public isSocket(): boolean {
return (this.mode & S_IFMT) === S_IFSOCK;
}
}
export const IOErrorMessages = Object.freeze({
// IOErrorMessages is defined like this to reduce duplication for --isolatedDeclarations
const TemplateIOErrorMessages = {
EACCES: "access denied",
EIO: "an I/O error occurred",
ENOENT: "no such file or directory",
@ -1367,9 +1368,10 @@ export const IOErrorMessages = Object.freeze({
ENOTEMPTY: "directory not empty",
EPERM: "operation not permitted",
EROFS: "file system is read-only",
});
} as const;
export const IOErrorMessages: typeof TemplateIOErrorMessages = Object.freeze(TemplateIOErrorMessages);
export function createIOError(code: keyof typeof IOErrorMessages, details = "") {
export function createIOError(code: keyof typeof IOErrorMessages, details = ""): NodeJS.ErrnoException {
const err: NodeJS.ErrnoException = new Error(`${code}: ${IOErrorMessages[code]} ${details}`);
err.code = code;
if (Error.captureStackTrace) Error.captureStackTrace(err, createIOError);

Просмотреть файл

@ -102,32 +102,32 @@ function validateComponents(components: string[], flags: ValidationFlags, hasTra
return true;
}
export function validate(path: string, flags: ValidationFlags = ValidationFlags.RelativeOrAbsolute) {
export function validate(path: string, flags: ValidationFlags = ValidationFlags.RelativeOrAbsolute): string {
const components = parse(path);
const trailing = hasTrailingSeparator(path);
if (!validateComponents(components, flags, trailing)) throw vfs.createIOError("ENOENT");
return components.length > 1 && trailing ? format(reduce(components)) + sep : format(reduce(components));
}
export function isDeclaration(path: string) {
export function isDeclaration(path: string): boolean {
return ts.isDeclarationFileName(path);
}
export function isSourceMap(path: string) {
export function isSourceMap(path: string): boolean {
return extname(path, ".map", /*ignoreCase*/ false).length > 0;
}
const javaScriptSourceMapExtensions: readonly string[] = [".js.map", ".jsx.map"];
export function isJavaScriptSourceMap(path: string) {
export function isJavaScriptSourceMap(path: string): boolean {
return extname(path, javaScriptSourceMapExtensions, /*ignoreCase*/ false).length > 0;
}
export function isJson(path: string) {
export function isJson(path: string): boolean {
return extname(path, ".json", /*ignoreCase*/ false).length > 0;
}
export function isDefaultLibrary(path: string) {
export function isDefaultLibrary(path: string): boolean {
return isDeclaration(path)
&& basename(path).startsWith("lib.");
}

Просмотреть файл

@ -14,7 +14,7 @@ import {
System,
} from "./_namespaces/ts.js";
export function ensureWatchablePath(path: string, locationType: string) {
export function ensureWatchablePath(path: string, locationType: string): void {
Debug.assert(
canWatchDirectoryOrFilePath(path as Path),
`Not a watchable location: ${locationType} like "/home/src/workspaces/project" or refer canWatchDirectoryOrFile for more allowed locations`,
@ -195,7 +195,7 @@ export function createWatchUtils<PollingWatcherData, FsWatcherData>(
}
}
export function serializeMultiMap<T>(baseline: string[], caption: string, multiMap: MultiMap<string, T>, serialized: Map<string, T[]> | undefined) {
export function serializeMultiMap<T>(baseline: string[], caption: string, multiMap: MultiMap<string, T>, serialized: Map<string, T[]> | undefined): Map<string, T[]> | undefined {
let hasChange = diffMap(baseline, caption, multiMap, serialized, /*deleted*/ false);
hasChange = diffMap(baseline, caption, serialized, multiMap, /*deleted*/ true) || hasChange;
if (hasChange) {

Просмотреть файл

@ -57,13 +57,13 @@ export interface CachedTyping {
}
/** @internal */
export function isTypingUpToDate(cachedTyping: CachedTyping, availableTypingVersions: MapLike<string>) {
export function isTypingUpToDate(cachedTyping: CachedTyping, availableTypingVersions: MapLike<string>): boolean {
const availableVersion = new Version(getProperty(availableTypingVersions, `ts${versionMajorMinor}`) || getProperty(availableTypingVersions, "latest")!);
return availableVersion.compareTo(cachedTyping.version) <= 0;
}
/** @internal */
export function nonRelativeModuleNameForTypingCache(moduleName: string) {
export function nonRelativeModuleNameForTypingCache(moduleName: string): string {
return nodeCoreModules.has(moduleName) ? "node" : moduleName;
}

Просмотреть файл

@ -45,7 +45,7 @@ export namespace Arguments {
}
/** @internal */
export function hasArgument(argumentName: string) {
export function hasArgument(argumentName: string): boolean {
return sys.args.includes(argumentName);
}

Просмотреть файл

@ -188,9 +188,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";
@ -489,7 +489,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 {
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<Path, ScriptInfo>();
readonly filenameToScriptInfo: Map<Path, ScriptInfo> = new Map();
private readonly nodeModulesWatchers = new Map<Path, NodeModulesWatcher>();
/**
* Contains all the deleted script info's version information so that
@ -1194,17 +1194,17 @@ export class ProjectService {
/**
* projects specified by a tsconfig.json file
*/
readonly configuredProjects: Map<string, ConfiguredProject> = new Map<string, ConfiguredProject>();
readonly configuredProjects: Map<string, ConfiguredProject> = 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
*/
readonly openFiles: Map<Path, NormalizedPath | undefined> = new Map<Path, NormalizedPath | undefined>();
readonly openFiles: Map<Path, NormalizedPath | undefined> = new Map();
/** Config files looked up and cached config files for open script info */
private readonly configFileForOpenFiles = new Map<Path, ConfigFileName>();
/** Set of open script infos that are root of inferred project */
@ -1233,7 +1233,7 @@ export class ProjectService {
*
* @internal
*/
readonly configFileExistenceInfoCache = new Map<NormalizedPath, ConfigFileExistenceInfo>();
readonly configFileExistenceInfoCache: Map<NormalizedPath, ConfigFileExistenceInfo> = new Map();
/** @internal */ readonly throttledOperations: ThrottledOperations;
private readonly hostConfiguration: HostConfiguration;
@ -1295,7 +1295,7 @@ export class ProjectService {
private currentPluginEnablementPromise?: Promise<void>;
/** @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;
@ -1381,22 +1381,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 };
}
@ -1408,17 +1408,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;
}
@ -1482,12 +1482,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, () => {
@ -1520,12 +1520,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;
}
@ -1540,7 +1540,7 @@ export class ProjectService {
}
/** @internal */
sendLargeFileReferencedEvent(file: string, fileSize: number) {
sendLargeFileReferencedEvent(file: string, fileSize: number): void {
if (!this.eventHandler) {
return;
}
@ -1553,7 +1553,7 @@ export class ProjectService {
}
/** @internal */
sendProjectLoadingStartEvent(project: ConfiguredProject, reason: string) {
sendProjectLoadingStartEvent(project: ConfiguredProject, reason: string): void {
if (!this.eventHandler) {
return;
}
@ -1566,7 +1566,7 @@ export class ProjectService {
}
/** @internal */
sendProjectLoadingFinishEvent(project: ConfiguredProject) {
sendProjectLoadingFinishEvent(project: ConfiguredProject): void {
if (!this.eventHandler || !project.sendLoadingProjectFinish) {
return;
}
@ -1580,14 +1580,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();
}
@ -1663,14 +1663,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);
@ -1721,7 +1721,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);
}
@ -1748,7 +1748,7 @@ export class ProjectService {
}
}
getFormatCodeOptions(file: NormalizedPath) {
getFormatCodeOptions(file: NormalizedPath): FormatCodeSettings {
const info = this.getScriptInfoForNormalizedPath(file);
return info && info.getFormatCodeSettings() || this.hostConfiguration.formatCodeOptions;
}
@ -2103,7 +2103,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() ||
@ -2307,7 +2307,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
@ -2345,7 +2345,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();
@ -2401,7 +2401,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
@ -2489,7 +2489,7 @@ export class ProjectService {
}
/** @internal */
findDefaultConfiguredProject(info: ScriptInfo) {
findDefaultConfiguredProject(info: ScriptInfo): ConfiguredProject | undefined {
return info.isScriptOpen() ?
this.tryFindDefaultConfiguredProjectForOpenScriptInfo(
info,
@ -2532,7 +2532,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;
@ -2690,7 +2690,7 @@ export class ProjectService {
}
/** @internal */
createConfiguredProject(configFileName: NormalizedPath, reason: string) {
createConfiguredProject(configFileName: NormalizedPath, reason: string): ConfiguredProject {
tracing?.instant(tracing.Phase.Session, "createConfiguredProject", { configFilePath: configFileName });
const canonicalConfigFilePath = asNormalizedPath(this.toCanonicalFileName(configFileName));
let configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath);
@ -2874,7 +2874,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;
@ -2895,7 +2895,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 ||
@ -3001,7 +3001,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);
@ -3028,7 +3028,7 @@ export class ProjectService {
setFileNamesOfAutoImportProviderOrAuxillaryProject(
project: AutoImportProviderProject | AuxiliaryProject,
fileNames: readonly string[],
) {
): void {
this.updateNonInferredProjectFiles(project, fileNames, fileNamePropertyReader);
}
@ -3037,7 +3037,7 @@ export class ProjectService {
project: ConfiguredProject,
reason: string,
reloadedProjects: Set<ConfiguredProject>,
) {
): boolean {
if (!tryAddToSet(reloadedProjects, project)) return false;
this.clearSemanticCache(project);
this.reloadConfiguredProject(project, reloadReason(reason));
@ -3049,7 +3049,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;
@ -3074,7 +3074,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());
@ -3216,7 +3216,7 @@ export class ProjectService {
currentDirectory: string,
hostToQueryFileExistsOn: DirectoryStructureHost,
deferredDeleteOk: boolean,
) {
): ScriptInfo | undefined {
return this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(
toNormalizedPath(uncheckedFileName),
currentDirectory,
@ -3227,7 +3227,7 @@ export class ProjectService {
);
}
getScriptInfo(uncheckedFileName: string) {
getScriptInfo(uncheckedFileName: string): ScriptInfo | undefined {
return this.getScriptInfoForNormalizedPath(toNormalizedPath(uncheckedFileName));
}
@ -3475,7 +3475,7 @@ export class ProjectService {
scriptKind?: ScriptKind,
hasMixedContent?: boolean,
hostToQueryFileExistsOn?: { fileExists(path: string): boolean; },
) {
): ScriptInfo | undefined {
return this.getOrCreateScriptInfoWorker(
fileName,
this.currentDirectory,
@ -3544,12 +3544,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;
}
@ -3722,11 +3722,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) {
@ -3794,7 +3794,7 @@ export class ProjectService {
}
/** @internal */
getWatchOptions(project: Project) {
getWatchOptions(project: Project): WatchOptions | undefined {
return this.getWatchOptionsFromProjectWatchOptions(project.getWatchOptions(), project.getCurrentDirectory());
}
@ -3809,7 +3809,7 @@ export class ProjectService {
projectOptions || hostWatchOptions;
}
closeLog() {
closeLog(): void {
this.logger.close();
}
@ -3845,7 +3845,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
@ -4343,7 +4343,7 @@ export class ProjectService {
}
/** @internal */
loadAncestorProjectTree(forProjects?: ReadonlyCollection<string>) {
loadAncestorProjectTree(forProjects?: ReadonlyCollection<string>): void {
forProjects ??= new Set(
mapDefinedIterator(this.configuredProjects.entries(), ([key, project]) => !project.isInitialLoadPending() ? key : undefined),
);
@ -4750,7 +4750,7 @@ export class ProjectService {
}
/** @internal */
applyChangesToFile(scriptInfo: ScriptInfo, changes: Iterable<TextChange>) {
applyChangesToFile(scriptInfo: ScriptInfo, changes: Iterable<TextChange>): void {
for (const change of changes) {
scriptInfo.editContent(change.span.start, change.span.start + change.span.length, change.newText);
}
@ -5004,7 +5004,7 @@ export class ProjectService {
}
}
hasDeferredExtension() {
hasDeferredExtension(): boolean {
for (const extension of this.hostConfiguration.extraFileExtensions!) { // TODO: GH#18217
if (extension.scriptKind === ScriptKind.Deferred) {
return true;
@ -5018,7 +5018,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;
@ -5082,12 +5082,12 @@ export class ProjectService {
}
/** @internal */
hasNewPluginEnablementRequests() {
hasNewPluginEnablementRequests(): boolean {
return !!this.pendingPluginEnablements;
}
/** @internal */
hasPendingPluginEnablements() {
hasPendingPluginEnablements(): boolean {
return !!this.currentPluginEnablementPromise;
}
@ -5096,7 +5096,7 @@ export class ProjectService {
*
* @internal
*/
async waitForPendingPlugins() {
async waitForPendingPlugins(): Promise<void> {
while (this.currentPluginEnablementPromise) {
await this.currentPluginEnablementPromise;
}
@ -5107,7 +5107,7 @@ export class ProjectService {
*
* @internal
*/
enableRequestedPlugins() {
enableRequestedPlugins(): void {
if (this.pendingPluginEnablements) {
void this.enableRequestedPluginsAsync();
}
@ -5164,7 +5164,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));
@ -5283,7 +5283,7 @@ export class ProjectService {
}
/** @internal */
getIncompleteCompletionsCache() {
getIncompleteCompletionsCache(): IncompleteCompletionsCache {
return this.incompleteCompletionsCache ||= createIncompleteCompletionsCache();
}
}

Просмотреть файл

@ -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,
@ -146,6 +149,7 @@ import {
Msg,
NormalizedPath,
nullTypingsInstaller,
PackageJsonCache,
PackageJsonWatcher,
ProjectOptions,
ProjectService,
@ -378,7 +382,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
*
* @internal
*/
cachedUnresolvedImportsPerFile = new Map<Path, readonly string[]>();
cachedUnresolvedImportsPerFile: Map<Path, readonly string[]> = new Map();
/** @internal */
lastCachedUnresolvedImportsList: SortedReadonlyArray<string> | undefined;
@ -466,12 +470,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);
}
@ -555,7 +559,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;
@ -648,7 +652,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
}
/** @internal */
getGlobalTypingsCacheLocation() {
getGlobalTypingsCacheLocation(): string | undefined {
return this.getTypeAcquisition().enable ? this.projectService.typingsInstaller.globalTypingsCacheLocation : undefined;
}
@ -668,20 +672,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();
}
@ -689,7 +693,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
return undefined;
}
getScriptFileNames() {
getScriptFileNames(): string[] {
if (!this.rootFilesMap.size) {
return ts.emptyArray;
}
@ -723,12 +727,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(
@ -755,12 +759,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;
}
@ -825,12 +829,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,
@ -842,7 +846,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,
@ -854,12 +858,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);
@ -868,7 +872,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
}
/** @internal */
invalidateResolutionsOfFailedLookupLocations() {
invalidateResolutionsOfFailedLookupLocations(): void {
if (
this.clearInvalidateResolutionOfFailedLookupTimer() &&
this.resolutionCache.invalidateResolutionsOfFailedLookupLocations()
@ -879,12 +883,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,
@ -896,33 +900,33 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
}
/** @internal */
hasChangedAutomaticTypeDirectiveNames() {
hasChangedAutomaticTypeDirectiveNames(): boolean {
return this.resolutionCache.hasChangedAutomaticTypeDirectiveNames();
}
/** @internal */
onChangedAutomaticTypeDirectiveNames() {
onChangedAutomaticTypeDirectiveNames(): void {
this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this);
}
/** @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 +950,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 +967,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
}
/** @internal */
clearSourceMapperCache() {
clearSourceMapperCache(): void {
this.languageService.clearSourceMapperCache();
}
@ -973,12 +977,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 +1036,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 +1046,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 +1057,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
}
}
disableLanguageService(lastFileExceededProgramSize?: string) {
disableLanguageService(lastFileExceededProgramSize?: string): void {
if (!this.languageServiceEnabled) {
return;
}
@ -1073,7 +1077,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
this.projectService.onUpdateLanguageServiceStateForProject(this, /*languageServiceEnabled*/ false);
}
getProjectName() {
getProjectName(): string {
return this.projectName;
}
@ -1100,7 +1104,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
}));
}
getSourceFile(path: Path) {
getSourceFile(path: Path): SourceFile | undefined {
if (!this.program) {
return undefined;
}
@ -1113,7 +1117,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 +1180,11 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
}
}
isClosed() {
isClosed(): boolean {
return this.rootFilesMap === undefined;
}
hasRoots() {
hasRoots(): boolean {
return !!this.rootFilesMap?.size;
}
@ -1194,11 +1198,11 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
}
/** @internal */
getRootFilesMap() {
getRootFilesMap(): Map<Path, ProjectRootFile> {
return this.rootFilesMap;
}
getRootScriptInfos() {
getRootScriptInfos(): ScriptInfo[] {
return arrayFrom(ts.mapDefinedIterator(this.rootFilesMap.values(), value => value.info));
}
@ -1218,7 +1222,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
return emptyArray;
}
getFileNames(excludeFilesFromExternalLibraries?: boolean, excludeConfigFiles?: boolean) {
getFileNames(excludeFilesFromExternalLibraries?: boolean, excludeConfigFiles?: boolean): NormalizedPath[] {
if (!this.program) {
return [];
}
@ -1256,14 +1260,14 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
}
/** @internal */
getFileNamesWithRedirectInfo(includeProjectReferenceRedirectInfo: boolean) {
getFileNamesWithRedirectInfo(includeProjectReferenceRedirectInfo: boolean): 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 +1301,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 +1315,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 +1341,12 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
this.markAsDirty();
}
registerFileUpdate(fileName: string) {
registerFileUpdate(fileName: string): void {
(this.updatedFileNames || (this.updatedFileNames = new Set<string>())).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 +1354,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
}
/** @internal */
markAsDirty() {
markAsDirty(): void {
if (!this.dirty) {
this.projectStateVersion++;
this.dirty = true;
@ -1358,24 +1362,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 +1387,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
}
/** @internal */
onDiscoveredSymlink() {
onDiscoveredSymlink(): void {
this.hasAddedOrRemovedSymlinks = true;
}
@ -1393,7 +1397,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 +1413,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
updateFromProjectInProgress = false;
/** @internal */
updateFromProject() {
updateFromProject(): void {
updateProjectIfDirty(this);
}
@ -1468,7 +1472,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 +1500,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
}
/** @internal */
updateTypingFiles(compilerOptions: CompilerOptions, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray<string>, newTypings: string[]) {
updateTypingFiles(compilerOptions: CompilerOptions, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray<string>, newTypings: string[]): void {
this.typingsCache = {
compilerOptions,
typeAcquisition,
@ -1523,7 +1527,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;
@ -1789,7 +1793,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);
}
@ -1837,7 +1841,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) {
@ -1902,11 +1906,11 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
return scriptInfo;
}
getScriptInfo(uncheckedFileName: string) {
getScriptInfo(uncheckedFileName: string): ScriptInfo | undefined {
return this.projectService.getScriptInfo(uncheckedFileName);
}
filesToString(writeProjectFileNames: boolean) {
filesToString(writeProjectFileNames: boolean): string {
return this.filesToStringWorker(writeProjectFileNames, /*writeFileExplaination*/ true, /*writeFileVersionAndText*/ false);
}
@ -1928,7 +1932,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),
@ -1942,7 +1946,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;
@ -1961,7 +1965,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
}
/** @internal */
setWatchOptions(watchOptions: WatchOptions | undefined) {
setWatchOptions(watchOptions: WatchOptions | undefined): void {
this.watchOptions = watchOptions;
}
@ -1976,7 +1980,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
}
}
getTypeAcquisition() {
getTypeAcquisition(): TypeAcquisition {
return this.typeAcquisition || {};
}
@ -2023,8 +2027,8 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
info => info.isSourceOfProjectReferenceRedirect,
);
const added: Map<string, boolean> = new Map<string, boolean>();
const removed: Map<string, boolean> = new Map<string, boolean>();
const added: Map<string, boolean> = new Map();
const removed: Map<string, boolean> = new Map();
const updated: string[] = updatedFileNames ? arrayFrom(updatedFileNames.keys()) : [];
const updatedRedirects: protocol.FileWithProjectReferenceRedirectInfo[] = [];
@ -2091,12 +2095,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,
@ -2135,7 +2139,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`);
@ -2170,7 +2174,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);
@ -2179,7 +2183,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();
}
@ -2200,22 +2204,22 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
}
/** @internal */
getPackageJsonCache() {
getPackageJsonCache(): 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;
}
@ -2296,12 +2300,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();
}
@ -2320,7 +2324,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());
@ -2336,7 +2340,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo
}
/** @internal */
getCompilerOptionsForNoDtsResolutionProject() {
getCompilerOptionsForNoDtsResolutionProject(): CompilerOptions {
return {
...this.getCompilerOptions(),
noDtsResolution: true,
@ -2395,14 +2399,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;
@ -2457,7 +2461,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()) {
@ -2469,7 +2473,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
@ -2481,11 +2485,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
@ -2493,7 +2497,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();
}
@ -2764,7 +2768,7 @@ export class AutoImportProviderProject extends Project {
}
/** @internal */
isEmpty() {
isEmpty(): boolean {
return !some(this.rootFileNames);
}
@ -2773,7 +2777,7 @@ export class AutoImportProviderProject extends Project {
return true;
}
override updateGraph() {
override updateGraph(): boolean {
let rootFileNames = this.rootFileNames;
if (!rootFileNames) {
rootFileNames = AutoImportProviderProject.getRootFileNames(
@ -2800,17 +2804,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;
}
@ -2832,22 +2836,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();
}
}
@ -2864,7 +2868,7 @@ export class ConfiguredProject extends Project {
pendingUpdateReason: string | undefined;
/** @internal */
openFileWatchTriggered = new Map<string, ProgramUpdateLevel>();
openFileWatchTriggered: Map<string, ProgramUpdateLevel> = new Map();
/** @internal */
canConfigFileJsonReportNoInputFiles = false;
@ -2923,7 +2927,7 @@ export class ConfiguredProject extends Project {
}
/** @internal */
setCompilerHost(host: CompilerHost) {
setCompilerHost(host: CompilerHost): void {
this.compilerHost = host;
}
@ -2933,12 +2937,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
@ -2956,7 +2960,7 @@ export class ConfiguredProject extends Project {
}
/** @internal */
onReleaseParsedCommandLine(fileName: string) {
onReleaseParsedCommandLine(fileName: string): void {
this.releaseParsedConfig(asNormalizedPath(this.projectService.toCanonicalFileName(asNormalizedPath(normalizePath(fileName)))));
}
@ -3017,7 +3021,7 @@ export class ConfiguredProject extends Project {
return this.directoryStructureHost as CachedDirectoryStructureHost;
}
getConfigFilePath() {
getConfigFilePath(): NormalizedPath {
return asNormalizedPath(this.getProjectName());
}
@ -3025,13 +3029,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);
}
@ -3090,11 +3094,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();
@ -3103,13 +3107,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;
}
@ -3119,12 +3123,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);
}
}
@ -3160,13 +3164,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 NormalizedPath[] {
return this.excludedFiles;
}
}

Просмотреть файл

@ -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;

Просмотреть файл

@ -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;
}

Просмотреть файл

@ -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: any = (protocol as any).CommandTypes;
export function formatMessage<T extends protocol.Message>(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<TMessage = string> 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<TMessage = string> 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<TMessage = string> 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<TMessage = string> 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<TMessage = string> implements EventSender {
}
}
public onMessage(message: TMessage) {
public onMessage(message: TMessage): void {
this.gcTimer.scheduleCollect();
let start: [number, number] | undefined;
const currentPerformanceData = this.performanceData;

Просмотреть файл

@ -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}`);
}

Просмотреть файл

@ -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;

Просмотреть файл

@ -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);
}

Просмотреть файл

@ -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;

Просмотреть файл

@ -29,7 +29,7 @@ const errorCodeToFixes = createMultiMap<string, CodeFixRegistration>();
const fixIdToRegistration = new Map<string, CodeFixRegistration>();
/** @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);

Просмотреть файл

@ -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));
}

Просмотреть файл

@ -857,7 +857,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);

Просмотреть файл

@ -458,7 +458,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);
@ -527,7 +527,7 @@ function getIsExcluded(excludePatterns: readonly RegExp[], host: LanguageService
}
/** @internal */
export function getIsFileExcluded(host: LanguageServiceHost, preferences: UserPreferences) {
export function getIsFileExcluded(host: LanguageServiceHost, preferences: UserPreferences): (sourceFile: SourceFile) => boolean {
if (!preferences.autoImportFileExcludePatterns) return () => false;
return getIsExcluded(getIsExcludedPatterns(preferences, hostUsesCaseSensitiveFileNames(host)), host);
}
@ -599,7 +599,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);

Просмотреть файл

@ -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);
}

Просмотреть файл

@ -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;

Просмотреть файл

@ -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);
}

Просмотреть файл

@ -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++) {

Просмотреть файл

@ -383,7 +383,7 @@ export function getJSDocTagNameCompletions(): CompletionEntry[] {
}
/** @internal */
export const getJSDocTagNameCompletionDetails = getJSDocTagCompletionDetails;
export const getJSDocTagNameCompletionDetails: typeof getJSDocTagCompletionDetails = getJSDocTagCompletionDetails;
/** @internal */
export function getJSDocTagCompletions(): CompletionEntry[] {

Просмотреть файл

@ -914,19 +914,19 @@ export function getNamedImportSpecifierComparerWithDetection(importDecl: ImportD
}
/** @internal */
export function getImportDeclarationInsertionIndex(sortedImports: readonly AnyImportOrRequireStatement[], newImport: AnyImportOrRequireStatement, comparer: Comparer<string>) {
export function getImportDeclarationInsertionIndex(sortedImports: readonly AnyImportOrRequireStatement[], newImport: AnyImportOrRequireStatement, comparer: Comparer<string>): 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<ImportSpecifier>) {
export function getImportSpecifierInsertionIndex(sortedImports: readonly ImportSpecifier[], newImport: ImportSpecifier, comparer: Comparer<ImportSpecifier>): number {
const index = binarySearch(sortedImports, newImport, identity, comparer);
return index < 0 ? ~index : index;
}
/** @internal */
export function compareImportsOrRequireStatements(s1: AnyImportOrRequireStatement, s2: AnyImportOrRequireStatement, comparer: Comparer<string>) {
export function compareImportsOrRequireStatements(s1: AnyImportOrRequireStatement, s2: AnyImportOrRequireStatement, comparer: Comparer<string>): 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);
}

Просмотреть файл

@ -18,7 +18,7 @@ const refactors = new Map<string, Refactor>();
*
* @internal
*/
export function registerRefactor(name: string, refactor: Refactor) {
export function registerRefactor(name: string, refactor: Refactor): void {
refactors.set(name, refactor);
}

Просмотреть файл

@ -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;

Просмотреть файл

@ -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 */

Просмотреть файл

@ -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).

Просмотреть файл

@ -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<Symbol, boolean>, changes: textChanges.ChangeTracker, useEsModuleSyntax: boolean) {
export function addExportsInOldFile(oldFile: SourceFile, targetFileImportsFromOldFile: Map<Symbol, boolean>, 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<Symbol> {
const existingLocals = new Set<Symbol>();
for (const moduleSpecifier of sourceFile.imports) {
const declaration = importFromModuleSpecifier(moduleSpecifier);

Просмотреть файл

@ -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();
}

Просмотреть файл

@ -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);

Просмотреть файл

@ -298,7 +298,16 @@ 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);

Просмотреть файл

@ -866,7 +866,15 @@ 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);
}

Просмотреть файл

@ -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<Node> | 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);
}

Просмотреть файл

@ -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;

Просмотреть файл

@ -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<T extends CallExpression | NewExpression | TaggedTemplat
}
/** @internal */
export function climbPastPropertyAccess(node: Node) {
export function climbPastPropertyAccess(node: Node): Node {
return isRightSideOfPropertyAccess(node) ? node.parent : node;
}
@ -694,22 +694,22 @@ export function isTagName(node: Node): boolean {
}
/** @internal */
export function isRightSideOfQualifiedName(node: Node) {
export function isRightSideOfQualifiedName(node: Node): boolean {
return tryCast(node.parent, isQualifiedName)?.right === node;
}
/** @internal */
export function isRightSideOfPropertyAccess(node: Node) {
export function isRightSideOfPropertyAccess(node: Node): boolean {
return tryCast(node.parent, isPropertyAccessExpression)?.name === node;
}
/** @internal */
export function isArgumentExpressionOfElementAccess(node: Node) {
export function isArgumentExpressionOfElementAccess(node: Node): boolean {
return tryCast(node.parent, isElementAccessExpression)?.argumentExpression === node;
}
/** @internal */
export function isNameOfModuleDeclaration(node: Node) {
export function isNameOfModuleDeclaration(node: Node): boolean {
return tryCast(node.parent, isModuleDeclaration)?.name === node;
}
@ -743,7 +743,7 @@ export function isLiteralNameOfPropertyDeclarationOrIndexAccess(node: StringLite
}
/** @internal */
export function isExpressionOfExternalModuleImportEqualsDeclaration(node: Node) {
export function isExpressionOfExternalModuleImportEqualsDeclaration(node: Node): boolean {
return isExternalModuleImportEqualsDeclaration(node.parent.parent) &&
getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node;
}
@ -933,7 +933,7 @@ export function rangeContainsPosition(r: TextRange, pos: number): boolean {
}
/** @internal */
export function rangeContainsPositionExclusive(r: TextRange, pos: number) {
export function rangeContainsPositionExclusive(r: TextRange, pos: number): boolean {
return r.pos < pos && pos < r.end;
}
@ -948,17 +948,17 @@ export function rangeContainsStartEnd(range: TextRange, start: number, end: numb
}
/** @internal */
export function rangeOverlapsWithStartEnd(r1: TextRange, start: number, end: number) {
export function rangeOverlapsWithStartEnd(r1: TextRange, start: number, end: number): boolean {
return startEndOverlapsWithStartEnd(r1.pos, r1.end, start, end);
}
/** @internal */
export function nodeOverlapsWithStartEnd(node: Node, sourceFile: SourceFile, start: number, end: number) {
export function nodeOverlapsWithStartEnd(node: Node, sourceFile: SourceFile, start: number, end: number): boolean {
return startEndOverlapsWithStartEnd(node.getStart(sourceFile), node.end, start, end);
}
/** @internal */
export function startEndOverlapsWithStartEnd(start1: number, end1: number, start2: number, end2: number) {
export function startEndOverlapsWithStartEnd(start1: number, end1: number, start2: number, end2: number): boolean {
const start = Math.max(start1, start2);
const end = Math.min(end1, end2);
return start < end;
@ -1849,7 +1849,7 @@ function findRightmostChildNodeWithTokens(children: readonly Node[], exclusiveSt
}
/** @internal */
export function isInString(sourceFile: SourceFile, position: number, previousToken = findPrecedingToken(position, sourceFile)): boolean {
export function isInString(sourceFile: SourceFile, position: number, previousToken: Node | undefined = findPrecedingToken(position, sourceFile)): boolean {
if (previousToken && isStringTextContainingNode(previousToken)) {
const start = previousToken.getStart(sourceFile);
const end = previousToken.getEnd();
@ -1873,7 +1873,7 @@ export function isInString(sourceFile: SourceFile, position: number, previousTok
/**
* @internal
*/
export function isInsideJsxElementOrAttribute(sourceFile: SourceFile, position: number) {
export function isInsideJsxElementOrAttribute(sourceFile: SourceFile, position: number): boolean {
const token = getTokenAtPosition(sourceFile, position);
if (!token) {
@ -1914,13 +1914,13 @@ function isWhiteSpaceOnlyJsxText(node: Node): boolean {
}
/** @internal */
export function isInTemplateString(sourceFile: SourceFile, position: number) {
export function isInTemplateString(sourceFile: SourceFile, position: number): boolean {
const token = getTokenAtPosition(sourceFile, position);
return isTemplateLiteralKind(token.kind) && position > 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<SyntaxKind.TypeKeyword> {
}
/** @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<T extends Node>(
*
* @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));
}
@ -4008,7 +4008,7 @@ export function firstOrOnly<T>(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
@ -4111,7 +4111,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;
@ -4128,7 +4128,7 @@ export function startsWithUnderscore(name: string): boolean {
}
/** @internal */
export function isDeprecatedDeclaration(decl: Declaration) {
export function isDeprecatedDeclaration(decl: Declaration): boolean {
return !!(getCombinedNodeFlagsAlwaysIncludeJSDoc(decl) & ModifierFlags.Deprecated);
}
@ -4177,12 +4177,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);
}
@ -4258,7 +4258,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;

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше