mirror of
https://github.com/microsoft/TypeScript.git
synced 2025-11-18 17:21:48 +00:00
Switch Debug.assertX functions to use asserts conditions (#36995)
* Switch Debug.assertX functions to use asserts conditions * Replace assert functions with ts.noop when assertion level too low
This commit is contained in:
@@ -409,7 +409,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function getDisplayName(node: Declaration): string {
|
||||
return isNamedDeclaration(node) ? declarationNameToString(node.name) : unescapeLeadingUnderscores(Debug.assertDefined(getDeclarationName(node)));
|
||||
return isNamedDeclaration(node) ? declarationNameToString(node.name) : unescapeLeadingUnderscores(Debug.checkDefined(getDeclarationName(node)));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+24
-24
@@ -366,7 +366,7 @@ namespace ts {
|
||||
|
||||
// With --out or --outFile all outputs go into single file
|
||||
// so operations are performed directly on program, return program
|
||||
const program = Debug.assertDefined(state.program);
|
||||
const program = Debug.checkDefined(state.program);
|
||||
const compilerOptions = program.getCompilerOptions();
|
||||
if (compilerOptions.outFile || compilerOptions.out) {
|
||||
Debug.assert(!state.semanticDiagnosticsPerFile);
|
||||
@@ -393,10 +393,10 @@ namespace ts {
|
||||
if (affectedFilesPendingEmit) {
|
||||
const seenEmittedFiles = state.seenEmittedFiles || (state.seenEmittedFiles = createMap());
|
||||
for (let i = state.affectedFilesPendingEmitIndex!; i < affectedFilesPendingEmit.length; i++) {
|
||||
const affectedFile = Debug.assertDefined(state.program).getSourceFileByPath(affectedFilesPendingEmit[i]);
|
||||
const affectedFile = Debug.checkDefined(state.program).getSourceFileByPath(affectedFilesPendingEmit[i]);
|
||||
if (affectedFile) {
|
||||
const seenKind = seenEmittedFiles.get(affectedFile.resolvedPath);
|
||||
const emitKind = Debug.assertDefined(Debug.assertDefined(state.affectedFilesPendingEmitKind).get(affectedFile.resolvedPath));
|
||||
const emitKind = Debug.checkDefined(Debug.checkDefined(state.affectedFilesPendingEmitKind).get(affectedFile.resolvedPath));
|
||||
if (seenKind === undefined || seenKind < emitKind) {
|
||||
// emit this file
|
||||
state.affectedFilesPendingEmitIndex = i;
|
||||
@@ -422,7 +422,7 @@ namespace ts {
|
||||
if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles) {
|
||||
if (!state.cleanedDiagnosticsOfLibFiles) {
|
||||
state.cleanedDiagnosticsOfLibFiles = true;
|
||||
const program = Debug.assertDefined(state.program);
|
||||
const program = Debug.checkDefined(state.program);
|
||||
const options = program.getCompilerOptions();
|
||||
forEach(program.getSourceFiles(), f =>
|
||||
program.isSourceFileDefaultLibrary(f) &&
|
||||
@@ -446,7 +446,7 @@ namespace ts {
|
||||
removeSemanticDiagnosticsOf(state, path);
|
||||
|
||||
if (!state.changedFilesSet.has(path)) {
|
||||
const program = Debug.assertDefined(state.program);
|
||||
const program = Debug.checkDefined(state.program);
|
||||
const sourceFile = program.getSourceFileByPath(path);
|
||||
if (sourceFile) {
|
||||
// Even though the js emit doesnt change and we are already handling dts emit and semantic diagnostics
|
||||
@@ -457,7 +457,7 @@ namespace ts {
|
||||
state,
|
||||
program,
|
||||
sourceFile,
|
||||
Debug.assertDefined(state.currentAffectedFilesSignatures),
|
||||
Debug.checkDefined(state.currentAffectedFilesSignatures),
|
||||
cancellationToken,
|
||||
computeHash,
|
||||
state.currentAffectedFilesExportedModulesMap
|
||||
@@ -486,8 +486,8 @@ namespace ts {
|
||||
}
|
||||
|
||||
function isChangedSignagure(state: BuilderProgramState, path: Path) {
|
||||
const newSignature = Debug.assertDefined(state.currentAffectedFilesSignatures).get(path);
|
||||
const oldSignagure = Debug.assertDefined(state.fileInfos.get(path)).signature;
|
||||
const newSignature = Debug.checkDefined(state.currentAffectedFilesSignatures).get(path);
|
||||
const oldSignagure = Debug.checkDefined(state.fileInfos.get(path)).signature;
|
||||
return newSignature !== oldSignagure;
|
||||
}
|
||||
|
||||
@@ -515,7 +515,7 @@ namespace ts {
|
||||
seenFileNamesMap.set(currentPath, true);
|
||||
const result = fn(state, currentPath);
|
||||
if (result && isChangedSignagure(state, currentPath)) {
|
||||
const currentSourceFile = Debug.assertDefined(state.program).getSourceFileByPath(currentPath)!;
|
||||
const currentSourceFile = Debug.checkDefined(state.program).getSourceFileByPath(currentPath)!;
|
||||
queue.push(...BuilderState.getReferencedByPaths(state, currentSourceFile.resolvedPath));
|
||||
}
|
||||
}
|
||||
@@ -526,7 +526,7 @@ namespace ts {
|
||||
const seenFileAndExportsOfFile = createMap<true>();
|
||||
// Go through exported modules from cache first
|
||||
// If exported modules has path, all files referencing file exported from are affected
|
||||
if (forEachEntry(state.currentAffectedFilesExportedModulesMap!, (exportedModules, exportedFromPath) =>
|
||||
if (forEachEntry(state.currentAffectedFilesExportedModulesMap, (exportedModules, exportedFromPath) =>
|
||||
exportedModules &&
|
||||
exportedModules.has(affectedFile.resolvedPath) &&
|
||||
forEachFilesReferencingPath(state, exportedFromPath as Path, seenFileAndExportsOfFile, fn)
|
||||
@@ -567,7 +567,7 @@ namespace ts {
|
||||
Debug.assert(!!state.currentAffectedFilesExportedModulesMap);
|
||||
// Go through exported modules from cache first
|
||||
// If exported modules has path, all files referencing file exported from are affected
|
||||
if (forEachEntry(state.currentAffectedFilesExportedModulesMap!, (exportedModules, exportedFromPath) =>
|
||||
if (forEachEntry(state.currentAffectedFilesExportedModulesMap, (exportedModules, exportedFromPath) =>
|
||||
exportedModules &&
|
||||
exportedModules.has(filePath) &&
|
||||
forEachFileAndExportsOfFile(state, exportedFromPath as Path, seenFileAndExportsOfFile, fn)
|
||||
@@ -655,7 +655,7 @@ namespace ts {
|
||||
function getSemanticDiagnosticsOfFile(state: BuilderProgramState, sourceFile: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[] {
|
||||
return concatenate(
|
||||
getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken),
|
||||
Debug.assertDefined(state.program).getProgramDiagnostics(sourceFile)
|
||||
Debug.checkDefined(state.program).getProgramDiagnostics(sourceFile)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -674,7 +674,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
// Diagnostics werent cached, get them from program, and cache the result
|
||||
const diagnostics = Debug.assertDefined(state.program).getBindAndCheckDiagnostics(sourceFile, cancellationToken);
|
||||
const diagnostics = Debug.checkDefined(state.program).getBindAndCheckDiagnostics(sourceFile, cancellationToken);
|
||||
if (state.semanticDiagnosticsPerFile) {
|
||||
state.semanticDiagnosticsPerFile.set(path, diagnostics);
|
||||
}
|
||||
@@ -695,7 +695,7 @@ namespace ts {
|
||||
*/
|
||||
function getProgramBuildInfo(state: Readonly<ReusableBuilderProgramState>, getCanonicalFileName: GetCanonicalFileName): ProgramBuildInfo | undefined {
|
||||
if (state.compilerOptions.outFile || state.compilerOptions.out) return undefined;
|
||||
const currentDirectory = Debug.assertDefined(state.program).getCurrentDirectory();
|
||||
const currentDirectory = Debug.checkDefined(state.program).getCurrentDirectory();
|
||||
const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(getTsBuildInfoEmitOutputFilePath(state.compilerOptions)!, currentDirectory));
|
||||
const fileInfos: MapLike<BuilderState.FileInfo> = {};
|
||||
state.fileInfos.forEach((value, key) => {
|
||||
@@ -891,10 +891,10 @@ namespace ts {
|
||||
backupState = cloneBuilderProgramState(state);
|
||||
};
|
||||
builderProgram.restoreState = () => {
|
||||
state = Debug.assertDefined(backupState);
|
||||
state = Debug.checkDefined(backupState);
|
||||
backupState = undefined;
|
||||
};
|
||||
builderProgram.getAllDependencies = sourceFile => BuilderState.getAllDependencies(state, Debug.assertDefined(state.program), sourceFile);
|
||||
builderProgram.getAllDependencies = sourceFile => BuilderState.getAllDependencies(state, Debug.checkDefined(state.program), sourceFile);
|
||||
builderProgram.getSemanticDiagnostics = getSemanticDiagnostics;
|
||||
builderProgram.emit = emit;
|
||||
builderProgram.releaseProgram = () => {
|
||||
@@ -932,7 +932,7 @@ namespace ts {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const affected = Debug.assertDefined(state.program);
|
||||
const affected = Debug.checkDefined(state.program);
|
||||
return toAffectedFileEmitResult(
|
||||
state,
|
||||
// When whole program is affected, do emit only once (eg when --out or --outFile is specified)
|
||||
@@ -948,7 +948,7 @@ namespace ts {
|
||||
isPendingEmitFile = true;
|
||||
}
|
||||
else {
|
||||
const program = Debug.assertDefined(state.program);
|
||||
const program = Debug.checkDefined(state.program);
|
||||
if (state.programEmitComplete) return undefined;
|
||||
affected = program;
|
||||
}
|
||||
@@ -958,7 +958,7 @@ namespace ts {
|
||||
state,
|
||||
// When whole program is affected, do emit only once (eg when --out or --outFile is specified)
|
||||
// Otherwise just affected file
|
||||
Debug.assertDefined(state.program).emit(
|
||||
Debug.checkDefined(state.program).emit(
|
||||
affected === state.program ? undefined : affected as SourceFile,
|
||||
writeFile || maybeBind(host, host.writeFile),
|
||||
cancellationToken,
|
||||
@@ -1009,7 +1009,7 @@ namespace ts {
|
||||
};
|
||||
}
|
||||
}
|
||||
return Debug.assertDefined(state.program).emit(targetSourceFile, writeFile || maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles, customTransformers);
|
||||
return Debug.checkDefined(state.program).emit(targetSourceFile, writeFile || maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles, customTransformers);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1062,11 +1062,11 @@ namespace ts {
|
||||
*/
|
||||
function getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[] {
|
||||
assertSourceFileOkWithoutNextAffectedCall(state, sourceFile);
|
||||
const compilerOptions = Debug.assertDefined(state.program).getCompilerOptions();
|
||||
const compilerOptions = Debug.checkDefined(state.program).getCompilerOptions();
|
||||
if (compilerOptions.outFile || compilerOptions.out) {
|
||||
Debug.assert(!state.semanticDiagnosticsPerFile);
|
||||
// We dont need to cache the diagnostics just return them from program
|
||||
return Debug.assertDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken);
|
||||
return Debug.checkDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken);
|
||||
}
|
||||
|
||||
if (sourceFile) {
|
||||
@@ -1080,7 +1080,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
let diagnostics: Diagnostic[] | undefined;
|
||||
for (const sourceFile of Debug.assertDefined(state.program).getSourceFiles()) {
|
||||
for (const sourceFile of Debug.checkDefined(state.program).getSourceFiles()) {
|
||||
diagnostics = addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken));
|
||||
}
|
||||
return diagnostics || emptyArray;
|
||||
@@ -1193,7 +1193,7 @@ namespace ts {
|
||||
};
|
||||
|
||||
function getProgram() {
|
||||
return Debug.assertDefined(state.program);
|
||||
return Debug.checkDefined(state.program);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -210,7 +210,7 @@ namespace ts {
|
||||
|
||||
// Create the reference map, and set the file infos
|
||||
for (const sourceFile of newProgram.getSourceFiles()) {
|
||||
const version = Debug.assertDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set");
|
||||
const version = Debug.checkDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set");
|
||||
const oldInfo = useOldState ? oldState!.fileInfos.get(sourceFile.resolvedPath) : undefined;
|
||||
if (referencedMap) {
|
||||
const newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName);
|
||||
|
||||
+18
-18
@@ -4823,7 +4823,7 @@ namespace ts {
|
||||
let chain: Symbol[];
|
||||
const isTypeParameter = symbol.flags & SymbolFlags.TypeParameter;
|
||||
if (!isTypeParameter && (context.enclosingDeclaration || context.flags & NodeBuilderFlags.UseFullyQualifiedType) && !(context.flags & NodeBuilderFlags.DoNotIncludeSymbolChain)) {
|
||||
chain = Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true));
|
||||
chain = Debug.checkDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true));
|
||||
Debug.assert(chain && chain.length > 0);
|
||||
}
|
||||
else {
|
||||
@@ -5607,9 +5607,9 @@ namespace ts {
|
||||
|
||||
function includePrivateSymbol(symbol: Symbol) {
|
||||
if (some(symbol.declarations, isParameterDeclaration)) return;
|
||||
Debug.assertDefined(deferredPrivates);
|
||||
Debug.assertIsDefined(deferredPrivates);
|
||||
getUnusedName(unescapeLeadingUnderscores(symbol.escapedName), symbol); // Call to cache unique name for symbol
|
||||
deferredPrivates!.set("" + getSymbolId(symbol), symbol);
|
||||
deferredPrivates.set("" + getSymbolId(symbol), symbol);
|
||||
}
|
||||
|
||||
function isExportingScope(enclosingDeclaration: Node) {
|
||||
@@ -5882,12 +5882,12 @@ namespace ts {
|
||||
const symbolProps = getPropertiesOfType(classType);
|
||||
const publicSymbolProps = filter(symbolProps, s => {
|
||||
const valueDecl = s.valueDeclaration;
|
||||
Debug.assertDefined(valueDecl);
|
||||
Debug.assertIsDefined(valueDecl);
|
||||
return !(isNamedDeclaration(valueDecl) && isPrivateIdentifier(valueDecl.name));
|
||||
});
|
||||
const hasPrivateIdentifier = some(symbolProps, s => {
|
||||
const valueDecl = s.valueDeclaration;
|
||||
Debug.assertDefined(valueDecl);
|
||||
Debug.assertIsDefined(valueDecl);
|
||||
return isNamedDeclaration(valueDecl) && isPrivateIdentifier(valueDecl.name);
|
||||
});
|
||||
// Boil down all private properties into a single one.
|
||||
@@ -7864,8 +7864,8 @@ namespace ts {
|
||||
}
|
||||
else {
|
||||
Debug.assert(!!getter, "there must exist a getter as we are current checking either setter or getter in this function");
|
||||
if (!isPrivateWithinAmbient(getter!)) {
|
||||
errorOrSuggestion(noImplicitAny, getter!, Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol));
|
||||
if (!isPrivateWithinAmbient(getter)) {
|
||||
errorOrSuggestion(noImplicitAny, getter, Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol));
|
||||
}
|
||||
}
|
||||
return anyType;
|
||||
@@ -7991,9 +7991,9 @@ namespace ts {
|
||||
function getTypeOfSymbolWithDeferredType(symbol: Symbol) {
|
||||
const links = getSymbolLinks(symbol);
|
||||
if (!links.type) {
|
||||
Debug.assertDefined(links.deferralParent);
|
||||
Debug.assertDefined(links.deferralConstituents);
|
||||
links.type = links.deferralParent!.flags & TypeFlags.Union ? getUnionType(links.deferralConstituents!) : getIntersectionType(links.deferralConstituents!);
|
||||
Debug.assertIsDefined(links.deferralParent);
|
||||
Debug.assertIsDefined(links.deferralConstituents);
|
||||
links.type = links.deferralParent.flags & TypeFlags.Union ? getUnionType(links.deferralConstituents) : getIntersectionType(links.deferralConstituents);
|
||||
}
|
||||
return links.type;
|
||||
}
|
||||
@@ -8440,7 +8440,7 @@ namespace ts {
|
||||
return errorType;
|
||||
}
|
||||
|
||||
const declaration = Debug.assertDefined(find(symbol.declarations, isTypeAlias), "Type alias symbol with no valid declaration found");
|
||||
const declaration = Debug.checkDefined(find(symbol.declarations, isTypeAlias), "Type alias symbol with no valid declaration found");
|
||||
const typeNode = isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type;
|
||||
// If typeNode is missing, we will error in checkJSDocTypedefTag.
|
||||
let type = typeNode ? getTypeFromTypeNode(typeNode) : errorType;
|
||||
@@ -16129,11 +16129,11 @@ namespace ts {
|
||||
if (getCheckFlags(targetProp) & CheckFlags.DeferredType && !getSymbolLinks(targetProp).type) {
|
||||
// Rather than resolving (and normalizing) the type, relate constituent-by-constituent without performing normalization or seconadary passes
|
||||
const links = getSymbolLinks(targetProp);
|
||||
Debug.assertDefined(links.deferralParent);
|
||||
Debug.assertDefined(links.deferralConstituents);
|
||||
const unionParent = !!(links.deferralParent!.flags & TypeFlags.Union);
|
||||
Debug.assertIsDefined(links.deferralParent);
|
||||
Debug.assertIsDefined(links.deferralConstituents);
|
||||
const unionParent = !!(links.deferralParent.flags & TypeFlags.Union);
|
||||
let result = unionParent ? Ternary.False : Ternary.True;
|
||||
const targetTypes = links.deferralConstituents!;
|
||||
const targetTypes = links.deferralConstituents;
|
||||
for (const targetType of targetTypes) {
|
||||
const related = isRelatedTo(source, targetType, /*reportErrors*/ false, /*headMessage*/ undefined, unionParent ? 0 : IntersectionState.Target);
|
||||
if (!unionParent) {
|
||||
@@ -23469,7 +23469,7 @@ namespace ts {
|
||||
right,
|
||||
Diagnostics.Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier,
|
||||
diagName,
|
||||
diagnosticName(typeClass!.name || anon)
|
||||
diagnosticName(typeClass.name || anon)
|
||||
);
|
||||
return true;
|
||||
}
|
||||
@@ -34557,7 +34557,7 @@ namespace ts {
|
||||
return isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal, ignoreErrors) : undefined;
|
||||
|
||||
case SyntaxKind.ExportKeyword:
|
||||
return isExportAssignment(node.parent) ? Debug.assertDefined(node.parent.symbol) : undefined;
|
||||
return isExportAssignment(node.parent) ? Debug.checkDefined(node.parent.symbol) : undefined;
|
||||
|
||||
default:
|
||||
return undefined;
|
||||
@@ -36524,7 +36524,7 @@ namespace ts {
|
||||
if (accessor.type) {
|
||||
return grammarErrorOnNode(accessor.name, Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation);
|
||||
}
|
||||
const parameter = Debug.assertDefined(getSetAccessorValueParameter(accessor), "Return value does not match parameter count assertion.");
|
||||
const parameter = Debug.checkDefined(getSetAccessorValueParameter(accessor), "Return value does not match parameter count assertion.");
|
||||
if (parameter.dotDotDotToken) {
|
||||
return grammarErrorOnNode(parameter.dotDotDotToken, Diagnostics.A_set_accessor_cannot_have_rest_parameter);
|
||||
}
|
||||
|
||||
+182
-92
@@ -1,47 +1,52 @@
|
||||
/* @internal */
|
||||
namespace ts {
|
||||
export namespace Debug {
|
||||
/* eslint-disable prefer-const */
|
||||
export let currentAssertionLevel = AssertionLevel.None;
|
||||
let currentAssertionLevel = AssertionLevel.None;
|
||||
|
||||
// eslint-disable-next-line prefer-const
|
||||
export let isDebugging = false;
|
||||
/* eslint-enable prefer-const */
|
||||
|
||||
type AssertionKeys = MatchingKeys<typeof Debug, AnyFunction>;
|
||||
|
||||
const assertionCache: Partial<Record<AssertionKeys, { level: AssertionLevel, assertion: AnyFunction }>> = {};
|
||||
|
||||
export function getAssertionLevel() {
|
||||
return currentAssertionLevel;
|
||||
}
|
||||
|
||||
export function setAssertionLevel(level: AssertionLevel) {
|
||||
const prevAssertionLevel = currentAssertionLevel;
|
||||
currentAssertionLevel = level;
|
||||
|
||||
if (level > prevAssertionLevel) {
|
||||
// restore assertion functions for the current assertion level (see `shouldAssertFunction`).
|
||||
for (const key of getOwnKeys(assertionCache) as AssertionKeys[]) {
|
||||
const cachedFunc = assertionCache[key];
|
||||
if (cachedFunc !== undefined && Debug[key] !== cachedFunc.assertion && level >= cachedFunc.level) {
|
||||
(Debug as any)[key] = cachedFunc;
|
||||
assertionCache[key] = undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function shouldAssert(level: AssertionLevel): boolean {
|
||||
return currentAssertionLevel >= level;
|
||||
}
|
||||
|
||||
export function assert(expression: boolean, message?: string, verboseDebugInfo?: string | (() => string), stackCrawlMark?: AnyFunction): void {
|
||||
if (!expression) {
|
||||
if (verboseDebugInfo) {
|
||||
message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo());
|
||||
}
|
||||
fail(message ? "False expression: " + message : "False expression.", stackCrawlMark || assert);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertEqual<T>(a: T, b: T, msg?: string, msg2?: string): void {
|
||||
if (a !== b) {
|
||||
const message = msg ? msg2 ? `${msg} ${msg2}` : msg : "";
|
||||
fail(`Expected ${a} === ${b}. ${message}`);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertLessThan(a: number, b: number, msg?: string): void {
|
||||
if (a >= b) {
|
||||
fail(`Expected ${a} < ${b}. ${msg || ""}`);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertLessThanOrEqual(a: number, b: number): void {
|
||||
if (a > b) {
|
||||
fail(`Expected ${a} <= ${b}`);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertGreaterThanOrEqual(a: number, b: number): void {
|
||||
if (a < b) {
|
||||
fail(`Expected ${a} >= ${b}`);
|
||||
/**
|
||||
* Tests whether an assertion function should be executed. If it shouldn't, it is cached and replaced with `ts.noop`.
|
||||
* Replaced assertion functions are restored when `Debug.setAssertionLevel` is set to a high enough level.
|
||||
* @param level The minimum assertion level required.
|
||||
* @param name The name of the current assertion function.
|
||||
*/
|
||||
function shouldAssertFunction<K extends AssertionKeys>(level: AssertionLevel, name: K): boolean {
|
||||
if (!shouldAssert(level)) {
|
||||
assertionCache[name] = { level, assertion: Debug[name] };
|
||||
(Debug as any)[name] = noop;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function fail(message?: string, stackCrawlMark?: AnyFunction): never {
|
||||
@@ -53,24 +58,163 @@ namespace ts {
|
||||
throw e;
|
||||
}
|
||||
|
||||
export function assertDefined<T>(value: T | null | undefined, message?: string): T {
|
||||
export function failBadSyntaxKind(node: Node, message?: string, stackCrawlMark?: AnyFunction): never {
|
||||
return fail(
|
||||
`${message || "Unexpected node."}\r\nNode ${formatSyntaxKind(node.kind)} was unexpected.`,
|
||||
stackCrawlMark || failBadSyntaxKind);
|
||||
}
|
||||
|
||||
export function assert(expression: boolean, message?: string, verboseDebugInfo?: string | (() => string), stackCrawlMark?: AnyFunction): asserts expression {
|
||||
if (!expression) {
|
||||
message = message ? `False expression: ${message}` : "False expression.";
|
||||
if (verboseDebugInfo) {
|
||||
message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo());
|
||||
}
|
||||
fail(message, stackCrawlMark || assert);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertEqual<T>(a: T, b: T, msg?: string, msg2?: string, stackCrawlMark?: AnyFunction): void {
|
||||
if (a !== b) {
|
||||
const message = msg ? msg2 ? `${msg} ${msg2}` : msg : "";
|
||||
fail(`Expected ${a} === ${b}. ${message}`, stackCrawlMark || assertEqual);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertLessThan(a: number, b: number, msg?: string, stackCrawlMark?: AnyFunction): void {
|
||||
if (a >= b) {
|
||||
fail(`Expected ${a} < ${b}. ${msg || ""}`, stackCrawlMark || assertLessThan);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertLessThanOrEqual(a: number, b: number, stackCrawlMark?: AnyFunction): void {
|
||||
if (a > b) {
|
||||
fail(`Expected ${a} <= ${b}`, stackCrawlMark || assertLessThanOrEqual);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertGreaterThanOrEqual(a: number, b: number, stackCrawlMark?: AnyFunction): void {
|
||||
if (a < b) {
|
||||
fail(`Expected ${a} >= ${b}`, stackCrawlMark || assertGreaterThanOrEqual);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertIsDefined<T>(value: T, message?: string, stackCrawlMark?: AnyFunction): asserts value is NonNullable<T> {
|
||||
// eslint-disable-next-line no-null/no-null
|
||||
if (value === undefined || value === null) return fail(message);
|
||||
if (value === undefined || value === null) {
|
||||
fail(message, stackCrawlMark || assertIsDefined);
|
||||
}
|
||||
}
|
||||
|
||||
export function checkDefined<T>(value: T | null | undefined, message?: string, stackCrawlMark?: AnyFunction): T {
|
||||
assertIsDefined(value, message, stackCrawlMark || checkDefined);
|
||||
return value;
|
||||
}
|
||||
|
||||
export function assertEachDefined<T, A extends readonly T[]>(value: A, message?: string): A {
|
||||
/**
|
||||
* @deprecated Use `checkDefined` to check whether a value is defined inline. Use `assertIsDefined` to check whether
|
||||
* a value is defined at the statement level.
|
||||
*/
|
||||
export const assertDefined = checkDefined;
|
||||
|
||||
export function assertEachIsDefined<T extends Node>(value: NodeArray<T>, message?: string, stackCrawlMark?: AnyFunction): asserts value is NodeArray<T>;
|
||||
export function assertEachIsDefined<T>(value: readonly T[], message?: string, stackCrawlMark?: AnyFunction): asserts value is readonly NonNullable<T>[];
|
||||
export function assertEachIsDefined<T>(value: readonly T[], message?: string, stackCrawlMark?: AnyFunction) {
|
||||
for (const v of value) {
|
||||
assertDefined(v, message);
|
||||
assertIsDefined(v, message, stackCrawlMark || assertEachIsDefined);
|
||||
}
|
||||
}
|
||||
|
||||
export function checkEachDefined<T, A extends readonly T[]>(value: A, message?: string, stackCrawlMark?: AnyFunction): A {
|
||||
assertEachIsDefined(value, message, stackCrawlMark || checkEachDefined);
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use `checkEachDefined` to check whether the elements of an array are defined inline. Use `assertEachIsDefined` to check whether
|
||||
* the elements of an array are defined at the statement level.
|
||||
*/
|
||||
export const assertEachDefined = checkEachDefined;
|
||||
|
||||
export function assertNever(member: never, message = "Illegal value:", stackCrawlMark?: AnyFunction): never {
|
||||
const detail = typeof member === "object" && hasProperty(member, "kind") && hasProperty(member, "pos") && formatSyntaxKind ? "SyntaxKind: " + formatSyntaxKind((member as Node).kind) : JSON.stringify(member);
|
||||
return fail(`${message} ${detail}`, stackCrawlMark || assertNever);
|
||||
}
|
||||
|
||||
export function assertEachNode<T extends Node, U extends T>(nodes: NodeArray<T>, test: (node: T) => node is U, message?: string, stackCrawlMark?: AnyFunction): asserts nodes is NodeArray<U>;
|
||||
export function assertEachNode<T extends Node, U extends T>(nodes: readonly T[], test: (node: T) => node is U, message?: string, stackCrawlMark?: AnyFunction): asserts nodes is readonly U[];
|
||||
export function assertEachNode(nodes: readonly Node[], test: (node: Node) => boolean, message?: string, stackCrawlMark?: AnyFunction): void;
|
||||
export function assertEachNode(nodes: readonly Node[], test: (node: Node) => boolean, message?: string, stackCrawlMark?: AnyFunction) {
|
||||
if (shouldAssertFunction(AssertionLevel.Normal, "assertEachNode")) {
|
||||
assert(
|
||||
test === undefined || every(nodes, test),
|
||||
message || "Unexpected node.",
|
||||
() => `Node array did not pass test '${getFunctionName(test)}'.`,
|
||||
stackCrawlMark || assertEachNode);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertNode<T extends Node, U extends T>(node: T | undefined, test: (node: T) => node is U, message?: string, stackCrawlMark?: AnyFunction): asserts node is U;
|
||||
export function assertNode(node: Node | undefined, test: ((node: Node) => boolean) | undefined, message?: string, stackCrawlMark?: AnyFunction): void;
|
||||
export function assertNode(node: Node | undefined, test: ((node: Node) => boolean) | undefined, message?: string, stackCrawlMark?: AnyFunction) {
|
||||
if (shouldAssertFunction(AssertionLevel.Normal, "assertNode")) {
|
||||
assert(
|
||||
node !== undefined && (test === undefined || test(node)),
|
||||
message || "Unexpected node.",
|
||||
() => `Node ${formatSyntaxKind(node!.kind)} did not pass test '${getFunctionName(test!)}'.`,
|
||||
stackCrawlMark || assertNode);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertNotNode<T extends Node, U extends T>(node: T | undefined, test: (node: T) => node is U, message?: string, stackCrawlMark?: AnyFunction): asserts node is Exclude<T, U>;
|
||||
export function assertNotNode(node: Node | undefined, test: ((node: Node) => boolean) | undefined, message?: string, stackCrawlMark?: AnyFunction): void;
|
||||
export function assertNotNode(node: Node | undefined, test: ((node: Node) => boolean) | undefined, message?: string, stackCrawlMark?: AnyFunction) {
|
||||
if (shouldAssertFunction(AssertionLevel.Normal, "assertNotNode")) {
|
||||
assert(
|
||||
node === undefined || test === undefined || !test(node),
|
||||
message || "Unexpected node.",
|
||||
() => `Node ${formatSyntaxKind(node!.kind)} should not have passed test '${getFunctionName(test!)}'.`,
|
||||
stackCrawlMark || assertNotNode);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertOptionalNode<T extends Node, U extends T>(node: T, test: (node: T) => node is U, message?: string, stackCrawlMark?: AnyFunction): asserts node is U;
|
||||
export function assertOptionalNode<T extends Node, U extends T>(node: T | undefined, test: (node: T) => node is U, message?: string, stackCrawlMark?: AnyFunction): asserts node is U | undefined;
|
||||
export function assertOptionalNode(node: Node | undefined, test: ((node: Node) => boolean) | undefined, message?: string, stackCrawlMark?: AnyFunction): void;
|
||||
export function assertOptionalNode(node: Node | undefined, test: ((node: Node) => boolean) | undefined, message?: string, stackCrawlMark?: AnyFunction) {
|
||||
if (shouldAssertFunction(AssertionLevel.Normal, "assertOptionalNode")) {
|
||||
assert(
|
||||
test === undefined || node === undefined || test(node),
|
||||
message || "Unexpected node.",
|
||||
() => `Node ${formatSyntaxKind(node!.kind)} did not pass test '${getFunctionName(test!)}'.`,
|
||||
stackCrawlMark || assertOptionalNode);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertOptionalToken<T extends Node, K extends SyntaxKind>(node: T, kind: K, message?: string, stackCrawlMark?: AnyFunction): asserts node is Extract<T, { readonly kind: K }>;
|
||||
export function assertOptionalToken<T extends Node, K extends SyntaxKind>(node: T | undefined, kind: K, message?: string, stackCrawlMark?: AnyFunction): asserts node is Extract<T, { readonly kind: K }> | undefined;
|
||||
export function assertOptionalToken(node: Node | undefined, kind: SyntaxKind | undefined, message?: string, stackCrawlMark?: AnyFunction): void;
|
||||
export function assertOptionalToken(node: Node | undefined, kind: SyntaxKind | undefined, message?: string, stackCrawlMark?: AnyFunction) {
|
||||
if (shouldAssertFunction(AssertionLevel.Normal, "assertOptionalToken")) {
|
||||
assert(
|
||||
kind === undefined || node === undefined || node.kind === kind,
|
||||
message || "Unexpected node.",
|
||||
() => `Node ${formatSyntaxKind(node!.kind)} was not a '${formatSyntaxKind(kind)}' token.`,
|
||||
stackCrawlMark || assertOptionalToken);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertMissingNode(node: Node | undefined, message?: string, stackCrawlMark?: AnyFunction): asserts node is undefined;
|
||||
export function assertMissingNode(node: Node | undefined, message?: string, stackCrawlMark?: AnyFunction) {
|
||||
if (shouldAssertFunction(AssertionLevel.Normal, "assertMissingNode")) {
|
||||
assert(
|
||||
node === undefined,
|
||||
message || "Unexpected node.",
|
||||
() => `Node ${formatSyntaxKind(node!.kind)} was unexpected'.`,
|
||||
stackCrawlMark || assertMissingNode);
|
||||
}
|
||||
}
|
||||
|
||||
export function getFunctionName(func: AnyFunction) {
|
||||
if (typeof func !== "function") {
|
||||
return "";
|
||||
@@ -167,60 +311,6 @@ namespace ts {
|
||||
return formatEnum(flags, (<any>ts).ObjectFlags, /*isFlags*/ true);
|
||||
}
|
||||
|
||||
export function failBadSyntaxKind(node: Node, message?: string): never {
|
||||
return fail(
|
||||
`${message || "Unexpected node."}\r\nNode ${formatSyntaxKind(node.kind)} was unexpected.`,
|
||||
failBadSyntaxKind);
|
||||
}
|
||||
|
||||
export const assertEachNode = shouldAssert(AssertionLevel.Normal)
|
||||
? (nodes: Node[], test: (node: Node) => boolean, message?: string): void => assert(
|
||||
test === undefined || every(nodes, test),
|
||||
message || "Unexpected node.",
|
||||
() => `Node array did not pass test '${getFunctionName(test)}'.`,
|
||||
assertEachNode)
|
||||
: noop;
|
||||
|
||||
export const assertNode = shouldAssert(AssertionLevel.Normal)
|
||||
? (node: Node | undefined, test: ((node: Node | undefined) => boolean) | undefined, message?: string): void => assert(
|
||||
test === undefined || test(node),
|
||||
message || "Unexpected node.",
|
||||
() => `Node ${formatSyntaxKind(node!.kind)} did not pass test '${getFunctionName(test!)}'.`,
|
||||
assertNode)
|
||||
: noop;
|
||||
|
||||
export const assertNotNode = shouldAssert(AssertionLevel.Normal)
|
||||
? (node: Node | undefined, test: ((node: Node | undefined) => boolean) | undefined, message?: string): void => assert(
|
||||
test === undefined || !test(node),
|
||||
message || "Unexpected node.",
|
||||
() => `Node ${formatSyntaxKind(node!.kind)} should not have passed test '${getFunctionName(test!)}'.`,
|
||||
assertNode)
|
||||
: noop;
|
||||
|
||||
export const assertOptionalNode = shouldAssert(AssertionLevel.Normal)
|
||||
? (node: Node, test: (node: Node) => boolean, message?: string): void => assert(
|
||||
test === undefined || node === undefined || test(node),
|
||||
message || "Unexpected node.",
|
||||
() => `Node ${formatSyntaxKind(node.kind)} did not pass test '${getFunctionName(test)}'.`,
|
||||
assertOptionalNode)
|
||||
: noop;
|
||||
|
||||
export const assertOptionalToken = shouldAssert(AssertionLevel.Normal)
|
||||
? (node: Node, kind: SyntaxKind, message?: string): void => assert(
|
||||
kind === undefined || node === undefined || node.kind === kind,
|
||||
message || "Unexpected node.",
|
||||
() => `Node ${formatSyntaxKind(node.kind)} was not a '${formatSyntaxKind(kind)}' token.`,
|
||||
assertOptionalToken)
|
||||
: noop;
|
||||
|
||||
export const assertMissingNode = shouldAssert(AssertionLevel.Normal)
|
||||
? (node: Node, message?: string): void => assert(
|
||||
node === undefined,
|
||||
message || "Unexpected node.",
|
||||
() => `Node ${formatSyntaxKind(node.kind)} was unexpected'.`,
|
||||
assertMissingNode)
|
||||
: noop;
|
||||
|
||||
let isDebugInfoEnabled = false;
|
||||
|
||||
interface ExtendedDebugModule {
|
||||
|
||||
@@ -131,7 +131,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function rootDirOfOptions(configFile: ParsedCommandLine) {
|
||||
return configFile.options.rootDir || getDirectoryPath(Debug.assertDefined(configFile.options.configFilePath));
|
||||
return configFile.options.rootDir || getDirectoryPath(Debug.checkDefined(configFile.options.configFilePath));
|
||||
}
|
||||
|
||||
function getOutputPathWithoutChangingExt(inputFileName: string, configFile: ParsedCommandLine, ignoreCase: boolean, outputDir: string | undefined) {
|
||||
@@ -163,7 +163,7 @@ namespace ts {
|
||||
Extension.Jsx :
|
||||
Extension.Js
|
||||
);
|
||||
return !isJsonFile || comparePaths(inputFileName, outputFileName, Debug.assertDefined(configFile.options.configFilePath), ignoreCase) !== Comparison.EqualTo ?
|
||||
return !isJsonFile || comparePaths(inputFileName, outputFileName, Debug.checkDefined(configFile.options.configFilePath), ignoreCase) !== Comparison.EqualTo ?
|
||||
outputFileName :
|
||||
undefined;
|
||||
}
|
||||
@@ -239,7 +239,7 @@ namespace ts {
|
||||
export function getFirstProjectOutput(configFile: ParsedCommandLine, ignoreCase: boolean): string {
|
||||
if (configFile.options.outFile || configFile.options.out) {
|
||||
const { jsFilePath } = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false);
|
||||
return Debug.assertDefined(jsFilePath, `project ${configFile.options.configFilePath} expected to have at least one output`);
|
||||
return Debug.checkDefined(jsFilePath, `project ${configFile.options.configFilePath} expected to have at least one output`);
|
||||
}
|
||||
|
||||
for (const inputFileName of configFile.fileNames) {
|
||||
@@ -587,7 +587,7 @@ namespace ts {
|
||||
return `data:application/json;base64,${base64SourceMapText}`;
|
||||
}
|
||||
|
||||
const sourceMapFile = getBaseFileName(normalizeSlashes(Debug.assertDefined(sourceMapFilePath)));
|
||||
const sourceMapFile = getBaseFileName(normalizeSlashes(Debug.checkDefined(sourceMapFilePath)));
|
||||
if (mapOptions.mapRoot) {
|
||||
let sourceMapDir = normalizeSlashes(mapOptions.mapRoot);
|
||||
if (sourceFile) {
|
||||
@@ -690,7 +690,7 @@ namespace ts {
|
||||
sourceFile.statements = createNodeArray();
|
||||
return sourceFile;
|
||||
});
|
||||
const jsBundle = Debug.assertDefined(bundle.js);
|
||||
const jsBundle = Debug.checkDefined(bundle.js);
|
||||
forEach(jsBundle.sources && jsBundle.sources.prologues, prologueInfo => {
|
||||
const sourceFile = sourceFiles[prologueInfo.file];
|
||||
sourceFile.text = prologueInfo.text;
|
||||
@@ -713,9 +713,9 @@ namespace ts {
|
||||
customTransformers?: CustomTransformers
|
||||
): EmitUsingBuildInfoResult {
|
||||
const { buildInfoPath, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath } = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ false);
|
||||
const buildInfoText = host.readFile(Debug.assertDefined(buildInfoPath));
|
||||
const buildInfoText = host.readFile(Debug.checkDefined(buildInfoPath));
|
||||
if (!buildInfoText) return buildInfoPath!;
|
||||
const jsFileText = host.readFile(Debug.assertDefined(jsFilePath));
|
||||
const jsFileText = host.readFile(Debug.checkDefined(jsFilePath));
|
||||
if (!jsFileText) return jsFilePath!;
|
||||
const sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath);
|
||||
// error if no source map or for now if inline sourcemap
|
||||
@@ -848,7 +848,7 @@ namespace ts {
|
||||
let write = writeBase;
|
||||
let isOwnFileEmit: boolean;
|
||||
const bundleFileInfo = printerOptions.writeBundleFileInfo ? { sections: [] } as BundleFileInfo : undefined;
|
||||
const relativeToBuildInfo = bundleFileInfo ? Debug.assertDefined(printerOptions.relativeToBuildInfo) : undefined;
|
||||
const relativeToBuildInfo = bundleFileInfo ? Debug.checkDefined(printerOptions.relativeToBuildInfo) : undefined;
|
||||
const recordInternalSection = printerOptions.recordInternalSection;
|
||||
let sourceFileTextPos = 0;
|
||||
let sourceFileTextKind: BundleFileTextLikeKind = BundleFileSectionKind.Text;
|
||||
@@ -3784,7 +3784,7 @@ namespace ts {
|
||||
else {
|
||||
for (const prepend of sourceFileOrBundle.prepends) {
|
||||
Debug.assertNode(prepend, isUnparsedSource);
|
||||
if (emitShebangIfNeeded(prepend as UnparsedSource)) {
|
||||
if (emitShebangIfNeeded(prepend)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1829,7 +1829,7 @@ namespace ts {
|
||||
if (isBindingElement(element)) {
|
||||
if (element.dotDotDotToken) {
|
||||
Debug.assertNode(element.name, isIdentifier);
|
||||
return setOriginalNode(setTextRange(createSpread(<Identifier>element.name), element), element);
|
||||
return setOriginalNode(setTextRange(createSpread(element.name), element), element);
|
||||
}
|
||||
const expression = convertToAssignmentElementTarget(element.name);
|
||||
return element.initializer
|
||||
@@ -1850,14 +1850,14 @@ namespace ts {
|
||||
if (isBindingElement(element)) {
|
||||
if (element.dotDotDotToken) {
|
||||
Debug.assertNode(element.name, isIdentifier);
|
||||
return setOriginalNode(setTextRange(createSpreadAssignment(<Identifier>element.name), element), element);
|
||||
return setOriginalNode(setTextRange(createSpreadAssignment(element.name), element), element);
|
||||
}
|
||||
if (element.propertyName) {
|
||||
const expression = convertToAssignmentElementTarget(element.name);
|
||||
return setOriginalNode(setTextRange(createPropertyAssignment(element.propertyName, element.initializer ? createAssignment(expression, element.initializer) : expression), element), element);
|
||||
}
|
||||
Debug.assertNode(element.name, isIdentifier);
|
||||
return setOriginalNode(setTextRange(createShorthandPropertyAssignment(<Identifier>element.name, element.initializer), element), element);
|
||||
return setOriginalNode(setTextRange(createShorthandPropertyAssignment(element.name, element.initializer), element), element);
|
||||
}
|
||||
Debug.assertNode(element, isObjectLiteralElementLike);
|
||||
return <ObjectLiteralElementLike>element;
|
||||
|
||||
@@ -2975,10 +2975,10 @@ namespace ts {
|
||||
if (textOrInputFiles.buildInfo && textOrInputFiles.buildInfo.bundle) {
|
||||
node.oldFileOfCurrentEmit = textOrInputFiles.oldFileOfCurrentEmit;
|
||||
Debug.assert(mapTextOrStripInternal === undefined || typeof mapTextOrStripInternal === "boolean");
|
||||
stripInternal = mapTextOrStripInternal as boolean | undefined;
|
||||
stripInternal = mapTextOrStripInternal;
|
||||
bundleFileInfo = mapPathOrType === "js" ? textOrInputFiles.buildInfo.bundle.js : textOrInputFiles.buildInfo.bundle.dts;
|
||||
if (node.oldFileOfCurrentEmit) {
|
||||
parseOldFileOfCurrentEmit(node, Debug.assertDefined(bundleFileInfo));
|
||||
parseOldFileOfCurrentEmit(node, Debug.checkDefined(bundleFileInfo));
|
||||
return node;
|
||||
}
|
||||
}
|
||||
@@ -3197,13 +3197,13 @@ namespace ts {
|
||||
};
|
||||
node.javascriptPath = declarationTextOrJavascriptPath;
|
||||
node.javascriptMapPath = javascriptMapPath;
|
||||
node.declarationPath = Debug.assertDefined(javascriptMapTextOrDeclarationPath);
|
||||
node.declarationPath = Debug.checkDefined(javascriptMapTextOrDeclarationPath);
|
||||
node.declarationMapPath = declarationMapPath;
|
||||
node.buildInfoPath = declarationMapTextOrBuildInfoPath;
|
||||
Object.defineProperties(node, {
|
||||
javascriptText: { get() { return definedTextGetter(declarationTextOrJavascriptPath); } },
|
||||
javascriptMapText: { get() { return textGetter(javascriptMapPath); } }, // TODO:: if there is inline sourceMap in jsFile, use that
|
||||
declarationText: { get() { return definedTextGetter(Debug.assertDefined(javascriptMapTextOrDeclarationPath)); } },
|
||||
declarationText: { get() { return definedTextGetter(Debug.checkDefined(javascriptMapTextOrDeclarationPath)); } },
|
||||
declarationMapText: { get() { return textGetter(declarationMapPath); } }, // TODO:: if there is inline sourceMap in dtsFile, use that
|
||||
buildInfo: { get() { return getAndCacheBuildInfo(() => textGetter(declarationMapTextOrBuildInfoPath)); } }
|
||||
});
|
||||
|
||||
@@ -6234,7 +6234,7 @@ namespace ts {
|
||||
const tok = token();
|
||||
Debug.assert(tok === SyntaxKind.ExtendsKeyword || tok === SyntaxKind.ImplementsKeyword); // isListElement() should ensure this.
|
||||
const node = <HeritageClause>createNode(SyntaxKind.HeritageClause);
|
||||
node.token = tok as SyntaxKind.ExtendsKeyword | SyntaxKind.ImplementsKeyword;
|
||||
node.token = tok;
|
||||
nextToken();
|
||||
node.types = parseDelimitedList(ParsingContext.HeritageClauseElement, parseExpressionWithTypeArguments);
|
||||
return finishNode(node);
|
||||
|
||||
+11
-11
@@ -757,7 +757,7 @@ namespace ts {
|
||||
let resolveModuleNamesWorker: (moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference) => ResolvedModuleFull[];
|
||||
const hasInvalidatedResolution = host.hasInvalidatedResolution || returnFalse;
|
||||
if (host.resolveModuleNames) {
|
||||
resolveModuleNamesWorker = (moduleNames, containingFile, reusedNames, redirectedReference) => host.resolveModuleNames!(Debug.assertEachDefined(moduleNames), containingFile, reusedNames, redirectedReference, options).map(resolved => {
|
||||
resolveModuleNamesWorker = (moduleNames, containingFile, reusedNames, redirectedReference) => host.resolveModuleNames!(Debug.checkEachDefined(moduleNames), containingFile, reusedNames, redirectedReference, options).map(resolved => {
|
||||
// An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName.
|
||||
if (!resolved || (resolved as ResolvedModuleFull).extension !== undefined) {
|
||||
return resolved as ResolvedModuleFull;
|
||||
@@ -770,16 +770,16 @@ namespace ts {
|
||||
else {
|
||||
moduleResolutionCache = createModuleResolutionCache(currentDirectory, x => host.getCanonicalFileName(x), options);
|
||||
const loader = (moduleName: string, containingFile: string, redirectedReference: ResolvedProjectReference | undefined) => resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule!; // TODO: GH#18217
|
||||
resolveModuleNamesWorker = (moduleNames, containingFile, _reusedNames, redirectedReference) => loadWithLocalCache<ResolvedModuleFull>(Debug.assertEachDefined(moduleNames), containingFile, redirectedReference, loader);
|
||||
resolveModuleNamesWorker = (moduleNames, containingFile, _reusedNames, redirectedReference) => loadWithLocalCache<ResolvedModuleFull>(Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader);
|
||||
}
|
||||
|
||||
let resolveTypeReferenceDirectiveNamesWorker: (typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference) => (ResolvedTypeReferenceDirective | undefined)[];
|
||||
if (host.resolveTypeReferenceDirectives) {
|
||||
resolveTypeReferenceDirectiveNamesWorker = (typeDirectiveNames, containingFile, redirectedReference) => host.resolveTypeReferenceDirectives!(Debug.assertEachDefined(typeDirectiveNames), containingFile, redirectedReference, options);
|
||||
resolveTypeReferenceDirectiveNamesWorker = (typeDirectiveNames, containingFile, redirectedReference) => host.resolveTypeReferenceDirectives!(Debug.checkEachDefined(typeDirectiveNames), containingFile, redirectedReference, options);
|
||||
}
|
||||
else {
|
||||
const loader = (typesRef: string, containingFile: string, redirectedReference: ResolvedProjectReference | undefined) => resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective!; // TODO: GH#18217
|
||||
resolveTypeReferenceDirectiveNamesWorker = (typeReferenceDirectiveNames, containingFile, redirectedReference) => loadWithLocalCache<ResolvedTypeReferenceDirective>(Debug.assertEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader);
|
||||
resolveTypeReferenceDirectiveNamesWorker = (typeReferenceDirectiveNames, containingFile, redirectedReference) => loadWithLocalCache<ResolvedTypeReferenceDirective>(Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader);
|
||||
}
|
||||
|
||||
// Map from a stringified PackageId to the source file with that id.
|
||||
@@ -1843,19 +1843,19 @@ namespace ts {
|
||||
break;
|
||||
case SyntaxKind.InterfaceDeclaration:
|
||||
const interfaceKeyword = tokenToString(SyntaxKind.InterfaceKeyword);
|
||||
Debug.assertDefined(interfaceKeyword);
|
||||
Debug.assertIsDefined(interfaceKeyword);
|
||||
diagnostics.push(createDiagnosticForNode(node, Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, interfaceKeyword));
|
||||
return;
|
||||
case SyntaxKind.ModuleDeclaration:
|
||||
const moduleKeyword = node.flags & NodeFlags.Namespace ? tokenToString(SyntaxKind.NamespaceKeyword) : tokenToString(SyntaxKind.ModuleKeyword);
|
||||
Debug.assertDefined(moduleKeyword);
|
||||
Debug.assertIsDefined(moduleKeyword);
|
||||
diagnostics.push(createDiagnosticForNode(node, Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, moduleKeyword));
|
||||
return;
|
||||
case SyntaxKind.TypeAliasDeclaration:
|
||||
diagnostics.push(createDiagnosticForNode(node, Diagnostics.Type_aliases_can_only_be_used_in_TypeScript_files));
|
||||
return;
|
||||
case SyntaxKind.EnumDeclaration:
|
||||
const enumKeyword = Debug.assertDefined(tokenToString(SyntaxKind.EnumKeyword));
|
||||
const enumKeyword = Debug.checkDefined(tokenToString(SyntaxKind.EnumKeyword));
|
||||
diagnostics.push(createDiagnosticForNode(node, Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, enumKeyword));
|
||||
return;
|
||||
case SyntaxKind.NonNullExpression:
|
||||
@@ -2906,7 +2906,7 @@ namespace ts {
|
||||
projectReferenceRedirects.set(sourceFilePath, false);
|
||||
return undefined;
|
||||
}
|
||||
sourceFile = Debug.assertDefined(commandLine.options.configFile);
|
||||
sourceFile = Debug.checkDefined(commandLine.options.configFile);
|
||||
Debug.assert(!sourceFile.path || sourceFile.path === sourceFilePath);
|
||||
addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined);
|
||||
}
|
||||
@@ -3207,7 +3207,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function createFileDiagnosticAtReference(refPathToReportErrorOn: ts.RefFile, message: DiagnosticMessage, ...args: (string | number | undefined)[]) {
|
||||
const refFile = Debug.assertDefined(getSourceFileByPath(refPathToReportErrorOn.file));
|
||||
const refFile = Debug.checkDefined(getSourceFileByPath(refPathToReportErrorOn.file));
|
||||
const { kind, index } = refPathToReportErrorOn;
|
||||
let pos: number, end: number;
|
||||
switch (kind) {
|
||||
@@ -3473,8 +3473,8 @@ namespace ts {
|
||||
return {
|
||||
fileExists: f => directoryStructureHost.fileExists(f),
|
||||
readDirectory(root, extensions, excludes, includes, depth) {
|
||||
Debug.assertDefined(directoryStructureHost.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'");
|
||||
return directoryStructureHost.readDirectory!(root, extensions, excludes, includes, depth);
|
||||
Debug.assertIsDefined(directoryStructureHost.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'");
|
||||
return directoryStructureHost.readDirectory(root, extensions, excludes, includes, depth);
|
||||
},
|
||||
readFile: f => directoryStructureHost.readFile(f),
|
||||
useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(),
|
||||
|
||||
@@ -294,7 +294,7 @@ namespace ts {
|
||||
// create different collection of failed lookup locations for second pass
|
||||
// if it will fail and we've already found something during the first pass - we don't want to pollute its results
|
||||
const { resolvedModule, failedLookupLocations } = loadModuleFromGlobalCache(
|
||||
Debug.assertDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName),
|
||||
Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName),
|
||||
resolutionHost.projectName,
|
||||
compilerOptions,
|
||||
host,
|
||||
|
||||
@@ -42,7 +42,7 @@ namespace ts {
|
||||
constructor(major: number, minor?: number, patch?: number, prerelease?: string, build?: string);
|
||||
constructor(major: number | string, minor = 0, patch = 0, prerelease = "", build = "") {
|
||||
if (typeof major === "string") {
|
||||
const result = Debug.assertDefined(tryParseComponents(major), "Invalid version");
|
||||
const result = Debug.checkDefined(tryParseComponents(major), "Invalid version");
|
||||
({ major, minor, patch, prerelease, build } = result);
|
||||
}
|
||||
|
||||
@@ -171,7 +171,7 @@ namespace ts {
|
||||
private _alternatives: readonly (readonly Comparator[])[];
|
||||
|
||||
constructor(spec: string) {
|
||||
this._alternatives = spec ? Debug.assertDefined(parseRange(spec), "Invalid range spec.") : emptyArray;
|
||||
this._alternatives = spec ? Debug.checkDefined(parseRange(spec), "Invalid range spec.") : emptyArray;
|
||||
}
|
||||
|
||||
static tryParse(text: string) {
|
||||
|
||||
+6
-6
@@ -398,7 +398,7 @@ namespace ts {
|
||||
|
||||
return {
|
||||
close: () => {
|
||||
const watcher = Debug.assertDefined(cache.get(path));
|
||||
const watcher = Debug.checkDefined(cache.get(path));
|
||||
callbacksCache.remove(path, callback);
|
||||
watcher.refCount--;
|
||||
if (watcher.refCount) return;
|
||||
@@ -525,7 +525,7 @@ namespace ts {
|
||||
return {
|
||||
dirName,
|
||||
close: () => {
|
||||
const directoryWatcher = Debug.assertDefined(cache.get(dirPath));
|
||||
const directoryWatcher = Debug.checkDefined(cache.get(dirPath));
|
||||
if (callbackToAdd) callbackCache.remove(dirPath, callbackToAdd);
|
||||
directoryWatcher.refCount--;
|
||||
|
||||
@@ -772,7 +772,7 @@ namespace ts {
|
||||
|
||||
function watchFile(fileName: string, callback: FileWatcherCallback, pollingInterval: PollingInterval, options: WatchOptions | undefined): FileWatcher {
|
||||
options = updateOptionsForWatchFile(options, useNonPollingWatchers);
|
||||
const watchFileKind = Debug.assertDefined(options.watchFile);
|
||||
const watchFileKind = Debug.checkDefined(options.watchFile);
|
||||
switch (watchFileKind) {
|
||||
case WatchFileKind.FixedPollingInterval:
|
||||
return pollingWatchFile(fileName, callback, PollingInterval.Low, /*options*/ undefined);
|
||||
@@ -874,7 +874,7 @@ namespace ts {
|
||||
function nonRecursiveWatchDirectory(directoryName: string, callback: DirectoryWatcherCallback, recursive: boolean, options: WatchOptions | undefined): FileWatcher {
|
||||
Debug.assert(!recursive);
|
||||
options = updateOptionsForWatchDirectory(options);
|
||||
const watchDirectoryKind = Debug.assertDefined(options.watchDirectory);
|
||||
const watchDirectoryKind = Debug.checkDefined(options.watchDirectory);
|
||||
switch (watchDirectoryKind) {
|
||||
case WatchDirectoryKind.FixedPollingInterval:
|
||||
return pollingWatchFile(
|
||||
@@ -1727,9 +1727,9 @@ namespace ts {
|
||||
|
||||
if (sys && sys.getEnvironmentVariable) {
|
||||
setCustomPollingValues(sys);
|
||||
Debug.currentAssertionLevel = /^development$/i.test(sys.getEnvironmentVariable("NODE_ENV"))
|
||||
Debug.setAssertionLevel(/^development$/i.test(sys.getEnvironmentVariable("NODE_ENV"))
|
||||
? AssertionLevel.Normal
|
||||
: AssertionLevel.None;
|
||||
: AssertionLevel.None);
|
||||
}
|
||||
if (sys && sys.debugMode) {
|
||||
Debug.isDebugging = true;
|
||||
|
||||
@@ -518,7 +518,7 @@ namespace ts {
|
||||
|
||||
if (some(staticProperties) || some(pendingExpressions)) {
|
||||
if (isDecoratedClassDeclaration) {
|
||||
Debug.assertDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration.");
|
||||
Debug.assertIsDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration.");
|
||||
|
||||
// Write any pending expressions from elided or moved computed property names
|
||||
if (pendingStatements && pendingExpressions && some(pendingExpressions)) {
|
||||
|
||||
@@ -252,7 +252,7 @@ namespace ts {
|
||||
value = inlineExpressions(append(pendingExpressions, value));
|
||||
pendingExpressions = undefined;
|
||||
}
|
||||
pendingDeclarations.push({ pendingExpressions, name: <BindingName>target, value, location, original });
|
||||
pendingDeclarations.push({ pendingExpressions, name: target, value, location, original });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1879,7 +1879,7 @@ namespace ts {
|
||||
// being emitted for the end position only.
|
||||
statementsLocation = moveRangeEnd(body, -1);
|
||||
|
||||
const equalsGreaterThanToken = (<ArrowFunction>node).equalsGreaterThanToken;
|
||||
const equalsGreaterThanToken = node.equalsGreaterThanToken;
|
||||
if (!nodeIsSynthesized(equalsGreaterThanToken) && !nodeIsSynthesized(body)) {
|
||||
if (rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) {
|
||||
singleLine = true;
|
||||
@@ -3431,12 +3431,12 @@ namespace ts {
|
||||
const ancestorFacts = enterSubtree(HierarchyFacts.BlockScopeExcludes, HierarchyFacts.BlockScopeIncludes);
|
||||
let updated: CatchClause;
|
||||
Debug.assert(!!node.variableDeclaration, "Catch clause variable should always be present when downleveling ES2015.");
|
||||
if (isBindingPattern(node.variableDeclaration!.name)) {
|
||||
if (isBindingPattern(node.variableDeclaration.name)) {
|
||||
const temp = createTempVariable(/*recordTempVariable*/ undefined);
|
||||
const newVariableDeclaration = createVariableDeclaration(temp);
|
||||
setTextRange(newVariableDeclaration, node.variableDeclaration);
|
||||
const vars = flattenDestructuringBinding(
|
||||
node.variableDeclaration!,
|
||||
node.variableDeclaration,
|
||||
visitor,
|
||||
context,
|
||||
FlattenLevel.All,
|
||||
|
||||
@@ -1989,7 +1989,7 @@ namespace ts {
|
||||
*/
|
||||
function markLabel(label: Label): void {
|
||||
Debug.assert(labelOffsets !== undefined, "No labels were defined.");
|
||||
labelOffsets![label] = operations ? operations.length : 0;
|
||||
labelOffsets[label] = operations ? operations.length : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -637,7 +637,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function visitExportDeclaration(node: ExportDeclaration): VisitResult<Statement> {
|
||||
Debug.assertDefined(node);
|
||||
Debug.assertIsDefined(node);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
|
||||
@@ -2514,7 +2514,7 @@ namespace ts {
|
||||
|
||||
function declaredNameInScope(node: FunctionDeclaration | ClassDeclaration | ModuleDeclaration | EnumDeclaration): __String {
|
||||
Debug.assertNode(node.name, isIdentifier);
|
||||
return (node.name as Identifier).escapedText;
|
||||
return node.name.escapedText;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2870,7 +2870,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
// Elide the export declaration if all of its named exports are elided.
|
||||
const exportClause = visitNode(node.exportClause, visitNamedExportBindings, isNamedImportBindings);
|
||||
const exportClause = visitNode(node.exportClause, visitNamedExportBindings, isNamedExportBindings);
|
||||
return exportClause
|
||||
? updateExportDeclaration(
|
||||
node,
|
||||
|
||||
@@ -294,7 +294,7 @@ namespace ts {
|
||||
if (!compilerHost.resolveModuleNames) {
|
||||
const loader = (moduleName: string, containingFile: string, redirectedReference: ResolvedProjectReference | undefined) => resolveModuleName(moduleName, containingFile, state.projectCompilerOptions, compilerHost, moduleResolutionCache, redirectedReference).resolvedModule!;
|
||||
compilerHost.resolveModuleNames = (moduleNames, containingFile, _reusedNames, redirectedReference) =>
|
||||
loadWithLocalCache<ResolvedModuleFull>(Debug.assertEachDefined(moduleNames), containingFile, redirectedReference, loader);
|
||||
loadWithLocalCache<ResolvedModuleFull>(Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader);
|
||||
}
|
||||
|
||||
const { watchFile, watchFilePath, watchDirectory, writeLog } = createWatchFactory<ResolvedConfigFileName>(hostWithWatch, options);
|
||||
@@ -871,13 +871,13 @@ namespace ts {
|
||||
}
|
||||
|
||||
function getSyntaxDiagnostics(cancellationToken?: CancellationToken) {
|
||||
Debug.assertDefined(program);
|
||||
Debug.assertIsDefined(program);
|
||||
handleDiagnostics(
|
||||
[
|
||||
...program!.getConfigFileParsingDiagnostics(),
|
||||
...program!.getOptionsDiagnostics(cancellationToken),
|
||||
...program!.getGlobalDiagnostics(cancellationToken),
|
||||
...program!.getSyntacticDiagnostics(/*sourceFile*/ undefined, cancellationToken)
|
||||
...program.getConfigFileParsingDiagnostics(),
|
||||
...program.getOptionsDiagnostics(cancellationToken),
|
||||
...program.getGlobalDiagnostics(cancellationToken),
|
||||
...program.getSyntacticDiagnostics(/*sourceFile*/ undefined, cancellationToken)
|
||||
],
|
||||
BuildResultFlags.SyntaxErrors,
|
||||
"Syntactic"
|
||||
@@ -886,22 +886,22 @@ namespace ts {
|
||||
|
||||
function getSemanticDiagnostics(cancellationToken?: CancellationToken) {
|
||||
handleDiagnostics(
|
||||
Debug.assertDefined(program).getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken),
|
||||
Debug.checkDefined(program).getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken),
|
||||
BuildResultFlags.TypeErrors,
|
||||
"Semantic"
|
||||
);
|
||||
}
|
||||
|
||||
function emit(writeFileCallback?: WriteFileCallback, cancellationToken?: CancellationToken, customTransformers?: CustomTransformers): EmitResult {
|
||||
Debug.assertDefined(program);
|
||||
Debug.assertIsDefined(program);
|
||||
Debug.assert(step === Step.Emit);
|
||||
// Before emitting lets backup state, so we can revert it back if there are declaration errors to handle emit and declaration errors correctly
|
||||
program!.backupState();
|
||||
program.backupState();
|
||||
let declDiagnostics: Diagnostic[] | undefined;
|
||||
const reportDeclarationDiagnostics = (d: Diagnostic) => (declDiagnostics || (declDiagnostics = [])).push(d);
|
||||
const outputFiles: OutputFile[] = [];
|
||||
const { emitResult } = emitFilesAndReportErrors(
|
||||
program!,
|
||||
program,
|
||||
reportDeclarationDiagnostics,
|
||||
/*writeFileName*/ undefined,
|
||||
/*reportSummary*/ undefined,
|
||||
@@ -912,7 +912,7 @@ namespace ts {
|
||||
);
|
||||
// Don't emit .d.ts if there are decl file errors
|
||||
if (declDiagnostics) {
|
||||
program!.restoreState();
|
||||
program.restoreState();
|
||||
buildResult = buildErrors(
|
||||
state,
|
||||
projectPath,
|
||||
@@ -1095,12 +1095,12 @@ namespace ts {
|
||||
break;
|
||||
|
||||
case Step.BuildInvalidatedProjectOfBundle:
|
||||
Debug.assertDefined(invalidatedProjectOfBundle).done(cancellationToken);
|
||||
Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken);
|
||||
step = Step.Done;
|
||||
break;
|
||||
|
||||
case Step.QueueReferencingProjects:
|
||||
queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, Debug.assertDefined(buildResult));
|
||||
queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, Debug.checkDefined(buildResult));
|
||||
step++;
|
||||
break;
|
||||
|
||||
|
||||
@@ -2463,7 +2463,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
export function getJSDocHost(node: Node): HasJSDoc {
|
||||
return Debug.assertDefined(findAncestor(node.parent, isJSDoc)).parent;
|
||||
return Debug.checkDefined(findAncestor(node.parent, isJSDoc)).parent;
|
||||
}
|
||||
|
||||
export function getTypeParameterFromJsDoc(node: TypeParameterDeclaration & { parent: JSDocTemplateTag }): TypeParameterDeclaration | undefined {
|
||||
@@ -5129,7 +5129,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
export function formatStringFromArgs(text: string, args: ArrayLike<string | number>, baseIndex = 0): string {
|
||||
return text.replace(/{(\d+)}/g, (_match, index: string) => "" + Debug.assertDefined(args[+index + baseIndex]));
|
||||
return text.replace(/{(\d+)}/g, (_match, index: string) => "" + Debug.checkDefined(args[+index + baseIndex]));
|
||||
}
|
||||
|
||||
export let localizedDiagnosticMessages: MapLike<string> | undefined;
|
||||
|
||||
@@ -105,7 +105,7 @@ namespace ts {
|
||||
|
||||
// Visit each original node.
|
||||
for (let i = 0; i < count; i++) {
|
||||
const node = nodes[i + start];
|
||||
const node: T = nodes[i + start];
|
||||
aggregateTransformFlags(node);
|
||||
const visited = node !== undefined ? visitor(node) : undefined;
|
||||
if (updated !== undefined || visited === undefined || visited !== node) {
|
||||
|
||||
@@ -291,7 +291,7 @@ namespace ts.server {
|
||||
|
||||
const request = this.processRequest<protocol.DefinitionRequest>(CommandNames.DefinitionAndBoundSpan, args);
|
||||
const response = this.processResponse<protocol.DefinitionInfoAndBoundSpanResponse>(request);
|
||||
const body = Debug.assertDefined(response.body); // TODO: GH#18217
|
||||
const body = Debug.checkDefined(response.body); // TODO: GH#18217
|
||||
|
||||
return {
|
||||
definitions: body.definitions.map(entry => ({
|
||||
@@ -385,7 +385,7 @@ namespace ts.server {
|
||||
start: entry.start,
|
||||
length: entry.length,
|
||||
messageText: entry.message,
|
||||
category: Debug.assertDefined(category, "convertDiagnostic: category should not be undefined"),
|
||||
category: Debug.checkDefined(category, "convertDiagnostic: category should not be undefined"),
|
||||
code: entry.code,
|
||||
reportsUnnecessary: entry.reportsUnnecessary,
|
||||
};
|
||||
|
||||
@@ -381,7 +381,7 @@ namespace FourSlash {
|
||||
}
|
||||
|
||||
private getFileContent(fileName: string): string {
|
||||
return ts.Debug.assertDefined(this.tryGetFileContent(fileName));
|
||||
return ts.Debug.checkDefined(this.tryGetFileContent(fileName));
|
||||
}
|
||||
private tryGetFileContent(fileName: string): string | undefined {
|
||||
const script = this.languageServiceAdapterHost.getScriptInfo(fileName);
|
||||
@@ -1716,7 +1716,7 @@ namespace FourSlash {
|
||||
resultString += Harness.IO.newLine();
|
||||
}
|
||||
|
||||
Harness.Baseline.runBaseline(ts.Debug.assertDefined(this.testData.globalOptions[MetadataOptionNames.baselineFile]), resultString);
|
||||
Harness.Baseline.runBaseline(ts.Debug.checkDefined(this.testData.globalOptions[MetadataOptionNames.baselineFile]), resultString);
|
||||
}
|
||||
|
||||
private flattenChainedMessage(diag: ts.DiagnosticMessageChain, indent = " ") {
|
||||
@@ -2630,7 +2630,7 @@ namespace FourSlash {
|
||||
const fixWithId = ts.find(this.getCodeFixes(this.activeFile.fileName), a => a.fixId === fixId);
|
||||
ts.Debug.assert(fixWithId !== undefined, "No available code fix has the expected id. Fix All is not available if there is only one potentially fixable diagnostic present.", () =>
|
||||
`Expected '${fixId}'. Available actions:\n${ts.mapDefined(this.getCodeFixes(this.activeFile.fileName), a => `${a.fixName} (${a.fixId || "no fix id"})`).join("\n")}`);
|
||||
ts.Debug.assertEqual(fixWithId!.fixAllDescription, fixAllDescription);
|
||||
ts.Debug.assertEqual(fixWithId.fixAllDescription, fixAllDescription);
|
||||
|
||||
const { changes, commands } = this.languageService.getCombinedCodeFix({ type: "file", fileName: this.activeFile.fileName }, fixId, this.formatCodeSettings, ts.emptyOptions);
|
||||
assert.deepEqual<readonly {}[] | undefined>(commands, expectedCommands);
|
||||
|
||||
@@ -897,7 +897,7 @@ namespace FourSlashInterface {
|
||||
const res: ExpectedCompletionEntryObject[] = [];
|
||||
for (let i = ts.SyntaxKind.FirstKeyword; i <= ts.SyntaxKind.LastKeyword; i++) {
|
||||
res.push({
|
||||
name: ts.Debug.assertDefined(ts.tokenToString(i)),
|
||||
name: ts.Debug.checkDefined(ts.tokenToString(i)),
|
||||
kind: "keyword",
|
||||
sortText: SortText.GlobalsOrKeywords
|
||||
});
|
||||
|
||||
@@ -691,7 +691,7 @@ namespace ts.server {
|
||||
|
||||
/*@internal*/
|
||||
setDocument(key: DocumentRegistryBucketKey, path: Path, sourceFile: SourceFile) {
|
||||
const info = Debug.assertDefined(this.getScriptInfoForPath(path));
|
||||
const info = Debug.checkDefined(this.getScriptInfoForPath(path));
|
||||
info.cacheSourceFile = { key, sourceFile };
|
||||
}
|
||||
|
||||
@@ -1110,7 +1110,7 @@ namespace ts.server {
|
||||
// don't trigger callback on open, existing files
|
||||
if (project.fileIsOpen(fileOrDirectoryPath)) {
|
||||
if (project.pendingReload !== ConfigFileProgramReloadLevel.Full) {
|
||||
const info = Debug.assertDefined(this.getScriptInfoForPath(fileOrDirectoryPath));
|
||||
const info = Debug.checkDefined(this.getScriptInfoForPath(fileOrDirectoryPath));
|
||||
if (info.isAttached(project)) {
|
||||
project.openFileWatchTriggered.set(fileOrDirectoryPath, true);
|
||||
}
|
||||
@@ -1642,7 +1642,7 @@ namespace ts.server {
|
||||
|
||||
Debug.assert(!isOpenScriptInfo(info) || this.openFiles.has(info.path));
|
||||
const projectRootPath = this.openFiles.get(info.path);
|
||||
const scriptInfo = Debug.assertDefined(this.getScriptInfo(info.path));
|
||||
const scriptInfo = Debug.checkDefined(this.getScriptInfo(info.path));
|
||||
if (scriptInfo.isDynamic) return undefined;
|
||||
|
||||
let searchPath = asNormalizedPath(getDirectoryPath(info.fileName));
|
||||
@@ -1996,7 +1996,7 @@ namespace ts.server {
|
||||
else {
|
||||
const scriptKind = propertyReader.getScriptKind(f, this.hostConfiguration.extraFileExtensions);
|
||||
const hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions);
|
||||
const scriptInfo = Debug.assertDefined(this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(
|
||||
const scriptInfo = Debug.checkDefined(this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(
|
||||
fileName,
|
||||
project.currentDirectory,
|
||||
scriptKind,
|
||||
|
||||
@@ -758,7 +758,7 @@ namespace ts.server {
|
||||
return map(this.program!.getSourceFiles(), sourceFile => {
|
||||
const scriptInfo = this.projectService.getScriptInfoForPath(sourceFile.resolvedPath);
|
||||
Debug.assert(!!scriptInfo, "getScriptInfo", () => `scriptInfo for a file '${sourceFile.fileName}' Path: '${sourceFile.path}' / '${sourceFile.resolvedPath}' is missing.`);
|
||||
return scriptInfo!;
|
||||
return scriptInfo;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2011,7 +2011,7 @@ namespace ts.server {
|
||||
break;
|
||||
case ConfigFileProgramReloadLevel.Full:
|
||||
this.openFileWatchTriggered.clear();
|
||||
const reason = Debug.assertDefined(this.pendingReloadReason);
|
||||
const reason = Debug.checkDefined(this.pendingReloadReason);
|
||||
this.pendingReloadReason = undefined;
|
||||
this.projectService.reloadConfiguredProject(this, reason);
|
||||
result = true;
|
||||
|
||||
@@ -443,7 +443,7 @@ namespace ts.server {
|
||||
}
|
||||
|
||||
while (toDo && toDo.length) {
|
||||
toDo = callbackProjectAndLocation(Debug.assertDefined(toDo.pop()), projectService, toDo, seenProjects, cb);
|
||||
toDo = callbackProjectAndLocation(Debug.checkDefined(toDo.pop()), projectService, toDo, seenProjects, cb);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1071,7 +1071,7 @@ namespace ts.server {
|
||||
private getDefinitionAndBoundSpan(args: protocol.FileLocationRequestArgs, simplifiedResult: boolean): protocol.DefinitionInfoAndBoundSpan | DefinitionInfoAndBoundSpan {
|
||||
const { file, project } = this.getFileAndProject(args);
|
||||
const position = this.getPositionInFile(args, file);
|
||||
const scriptInfo = Debug.assertDefined(project.getScriptInfo(file));
|
||||
const scriptInfo = Debug.checkDefined(project.getScriptInfo(file));
|
||||
|
||||
const unmappedDefinitionAndBoundSpan = project.getLanguageService().getDefinitionAndBoundSpan(file, position);
|
||||
|
||||
@@ -1335,7 +1335,7 @@ namespace ts.server {
|
||||
if (!simplifiedResult) return locations;
|
||||
|
||||
const defaultProject = this.getDefaultProject(args);
|
||||
const renameInfo: protocol.RenameInfo = this.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position, { allowRenameOfImportPath: this.getPreferences(file).allowRenameOfImportPath }), Debug.assertDefined(this.projectService.getScriptInfo(file)));
|
||||
const renameInfo: protocol.RenameInfo = this.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position, { allowRenameOfImportPath: this.getPreferences(file).allowRenameOfImportPath }), Debug.checkDefined(this.projectService.getScriptInfo(file)));
|
||||
return { info: renameInfo, locs: this.toSpanGroups(locations) };
|
||||
}
|
||||
|
||||
@@ -1355,7 +1355,7 @@ namespace ts.server {
|
||||
for (const { fileName, textSpan, contextSpan, originalContextSpan: _2, originalTextSpan: _, originalFileName: _1, ...prefixSuffixText } of locations) {
|
||||
let group = map.get(fileName);
|
||||
if (!group) map.set(fileName, group = { file: fileName, locs: [] });
|
||||
const scriptInfo = Debug.assertDefined(this.projectService.getScriptInfo(fileName));
|
||||
const scriptInfo = Debug.checkDefined(this.projectService.getScriptInfo(fileName));
|
||||
group.locs.push({ ...toProtocolTextSpanWithContext(textSpan, contextSpan, scriptInfo), ...prefixSuffixText });
|
||||
}
|
||||
return arrayFrom(map.values());
|
||||
@@ -1382,7 +1382,7 @@ namespace ts.server {
|
||||
const symbolName = nameSpan ? scriptInfo.getSnapshot().getText(nameSpan.start, textSpanEnd(nameSpan)) : "";
|
||||
const refs: readonly protocol.ReferencesResponseItem[] = flatMap(references, referencedSymbol =>
|
||||
referencedSymbol.references.map(({ fileName, textSpan, contextSpan, isWriteAccess, isDefinition }): protocol.ReferencesResponseItem => {
|
||||
const scriptInfo = Debug.assertDefined(this.projectService.getScriptInfo(fileName));
|
||||
const scriptInfo = Debug.checkDefined(this.projectService.getScriptInfo(fileName));
|
||||
const span = toProtocolTextSpanWithContext(textSpan, contextSpan, scriptInfo);
|
||||
const lineSpan = scriptInfo.lineToTextSpan(span.start.line - 1);
|
||||
const lineText = scriptInfo.getSnapshot().getText(lineSpan.start, textSpanEnd(lineSpan)).replace(/\r|\n/g, "");
|
||||
@@ -1918,7 +1918,7 @@ namespace ts.server {
|
||||
const { startPosition, endPosition } = this.getStartAndEndPosition(args, scriptInfo);
|
||||
textRange = { pos: startPosition, end: endPosition };
|
||||
}
|
||||
return Debug.assertDefined(position === undefined ? textRange : position);
|
||||
return Debug.checkDefined(position === undefined ? textRange : position);
|
||||
|
||||
function getPosition(loc: protocol.FileLocationRequestArgs) {
|
||||
return loc.position !== undefined ? loc.position : scriptInfo.lineOffsetToPosition(loc.line, loc.offset);
|
||||
@@ -2145,7 +2145,7 @@ namespace ts.server {
|
||||
private getSmartSelectionRange(args: protocol.SelectionRangeRequestArgs, simplifiedResult: boolean) {
|
||||
const { locations } = args;
|
||||
const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args);
|
||||
const scriptInfo = Debug.assertDefined(this.projectService.getScriptInfo(file));
|
||||
const scriptInfo = Debug.checkDefined(this.projectService.getScriptInfo(file));
|
||||
|
||||
return map(locations, location => {
|
||||
const pos = this.getPosition(location, scriptInfo);
|
||||
@@ -2290,7 +2290,7 @@ namespace ts.server {
|
||||
request.arguments.changedFiles && mapIterator(arrayIterator(request.arguments.changedFiles), file => ({
|
||||
fileName: file.fileName,
|
||||
changes: mapDefinedIterator(arrayReverseIterator(file.textChanges), change => {
|
||||
const scriptInfo = Debug.assertDefined(this.projectService.getScriptInfo(file.fileName));
|
||||
const scriptInfo = Debug.checkDefined(this.projectService.getScriptInfo(file.fileName));
|
||||
const start = scriptInfo.lineOffsetToPosition(change.start.line, change.start.offset);
|
||||
const end = scriptInfo.lineOffsetToPosition(change.end.line, change.end.offset);
|
||||
return start >= 0 ? { span: { start, length: end - start }, newText: change.newText } : undefined;
|
||||
|
||||
@@ -536,7 +536,7 @@ namespace ts.BreakpointResolver {
|
||||
|
||||
function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node: DestructuringPattern): TextSpan | undefined {
|
||||
Debug.assert(node.kind !== SyntaxKind.ArrayBindingPattern && node.kind !== SyntaxKind.ObjectBindingPattern);
|
||||
const elements: NodeArray<Expression | ObjectLiteralElement> = node.kind === SyntaxKind.ArrayLiteralExpression ? node.elements : (node as ObjectLiteralExpression).properties;
|
||||
const elements: NodeArray<Expression | ObjectLiteralElement> = node.kind === SyntaxKind.ArrayLiteralExpression ? node.elements : node.properties;
|
||||
|
||||
const firstBindingElement = forEach(elements,
|
||||
element => element.kind !== SyntaxKind.OmittedExpression ? element : undefined);
|
||||
|
||||
@@ -78,7 +78,7 @@ namespace ts.CallHierarchy {
|
||||
if (isSourceFile(node)) return node;
|
||||
if (isNamedDeclaration(node)) return node.name;
|
||||
if (isConstNamedExpression(node)) return node.parent.name;
|
||||
return Debug.assertDefined(node.modifiers && find(node.modifiers, isDefaultModifier));
|
||||
return Debug.checkDefined(node.modifiers && find(node.modifiers, isDefaultModifier));
|
||||
}
|
||||
|
||||
function isDefaultModifier(node: Node) {
|
||||
@@ -105,7 +105,7 @@ namespace ts.CallHierarchy {
|
||||
}
|
||||
|
||||
const declName = isConstNamedExpression(node) ? node.parent.name :
|
||||
Debug.assertDefined(getNameOfDeclaration(node), "Expected call hierarchy item to have a name");
|
||||
Debug.checkDefined(getNameOfDeclaration(node), "Expected call hierarchy item to have a name");
|
||||
|
||||
let text =
|
||||
isIdentifier(declName) ? idText(declName) :
|
||||
|
||||
@@ -14,7 +14,7 @@ namespace ts.codefix {
|
||||
|
||||
function makeChange(changeTracker: textChanges.ChangeTracker, sourceFile: SourceFile, pos: number) {
|
||||
const token = getTokenAtPosition(sourceFile, pos);
|
||||
const assertion = Debug.assertDefined(findAncestor(token, (n): n is AsExpression | TypeAssertion => isAsExpression(n) || isTypeAssertion(n)), "Expected to find an assertion expression");
|
||||
const assertion = Debug.checkDefined(findAncestor(token, (n): n is AsExpression | TypeAssertion => isAsExpression(n) || isTypeAssertion(n)), "Expected to find an assertion expression");
|
||||
const replacement = isAsExpression(assertion)
|
||||
? createAsExpression(assertion.expression, createKeywordTypeNode(SyntaxKind.UnknownKeyword))
|
||||
: createTypeAssertion(createKeywordTypeNode(SyntaxKind.UnknownKeyword), assertion.expression);
|
||||
|
||||
@@ -60,7 +60,7 @@ namespace ts.codefix {
|
||||
}
|
||||
}
|
||||
else {
|
||||
const jsdocType = Debug.assertDefined(getJSDocType(decl), "A JSDocType for this declaration should exist"); // If not defined, shouldn't have been an error to fix
|
||||
const jsdocType = Debug.checkDefined(getJSDocType(decl), "A JSDocType for this declaration should exist"); // If not defined, shouldn't have been an error to fix
|
||||
Debug.assert(!decl.type, "The JSDocType decl should have a type"); // If defined, shouldn't have been an error to fix.
|
||||
changes.tryInsertTypeAnnotation(sourceFile, decl, transformJSDocType(jsdocType));
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ namespace ts.codefix {
|
||||
});
|
||||
|
||||
function getClass(sourceFile: SourceFile, pos: number): ClassLikeDeclaration {
|
||||
return Debug.assertDefined(getContainingClass(getTokenAtPosition(sourceFile, pos)), "There should be a containing class");
|
||||
return Debug.checkDefined(getContainingClass(getTokenAtPosition(sourceFile, pos)), "There should be a containing class");
|
||||
}
|
||||
|
||||
function symbolPointsToNonPrivateMember(symbol: Symbol) {
|
||||
|
||||
@@ -18,7 +18,7 @@ namespace ts.codefix {
|
||||
function getNode(sourceFile: SourceFile, pos: number): ConstructorDeclaration {
|
||||
const token = getTokenAtPosition(sourceFile, pos);
|
||||
Debug.assert(isConstructorDeclaration(token.parent), "token should be at the constructor declaration");
|
||||
return token.parent as ConstructorDeclaration;
|
||||
return token.parent;
|
||||
}
|
||||
|
||||
function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, ctr: ConstructorDeclaration) {
|
||||
|
||||
@@ -32,24 +32,24 @@ namespace ts.codefix {
|
||||
// this.speling = 1;
|
||||
// ^^^^^^^
|
||||
const node = getTokenAtPosition(sourceFile, pos);
|
||||
const parent = node.parent;
|
||||
const checker = context.program.getTypeChecker();
|
||||
|
||||
let suggestedSymbol: Symbol | undefined;
|
||||
if (isPropertyAccessExpression(node.parent) && node.parent.name === node) {
|
||||
if (isPropertyAccessExpression(parent) && parent.name === node) {
|
||||
Debug.assert(isIdentifierOrPrivateIdentifier(node), "Expected an identifier for spelling (property access)");
|
||||
let containingType = checker.getTypeAtLocation(node.parent.expression);
|
||||
if (node.parent.flags & NodeFlags.OptionalChain) {
|
||||
let containingType = checker.getTypeAtLocation(parent.expression);
|
||||
if (parent.flags & NodeFlags.OptionalChain) {
|
||||
containingType = checker.getNonNullableType(containingType);
|
||||
}
|
||||
const name = node as Identifier | PrivateIdentifier;
|
||||
suggestedSymbol = checker.getSuggestedSymbolForNonexistentProperty(name, containingType);
|
||||
suggestedSymbol = checker.getSuggestedSymbolForNonexistentProperty(node, containingType);
|
||||
}
|
||||
else if (isImportSpecifier(node.parent) && node.parent.name === node) {
|
||||
Debug.assert(node.kind === SyntaxKind.Identifier, "Expected an identifier for spelling (import)");
|
||||
else if (isImportSpecifier(parent) && parent.name === node) {
|
||||
Debug.assertNode(node, isIdentifier, "Expected an identifier for spelling (import)");
|
||||
const importDeclaration = findAncestor(node, isImportDeclaration)!;
|
||||
const resolvedSourceFile = getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration);
|
||||
if (resolvedSourceFile && resolvedSourceFile.symbol) {
|
||||
suggestedSymbol = checker.getSuggestedSymbolForNonexistentModule(node as Identifier, resolvedSourceFile.symbol);
|
||||
suggestedSymbol = checker.getSuggestedSymbolForNonexistentModule(node, resolvedSourceFile.symbol);
|
||||
}
|
||||
}
|
||||
else {
|
||||
|
||||
@@ -49,7 +49,7 @@ namespace ts.codefix {
|
||||
|
||||
if (isBlock(statement.parent)) {
|
||||
const end = start + length;
|
||||
const lastStatement = Debug.assertDefined(lastWhere(sliceAfter(statement.parent.statements, statement), s => s.pos < end), "Some statement should be last");
|
||||
const lastStatement = Debug.checkDefined(lastWhere(sliceAfter(statement.parent.statements, statement), s => s.pos < end), "Some statement should be last");
|
||||
changes.deleteNodeRange(sourceFile, statement, lastStatement);
|
||||
}
|
||||
else {
|
||||
|
||||
@@ -117,7 +117,7 @@ namespace ts.codefix {
|
||||
}
|
||||
|
||||
function deleteTypeParameters(changes: textChanges.ChangeTracker, sourceFile: SourceFile, token: Node): void {
|
||||
changes.delete(sourceFile, Debug.assertDefined(cast(token.parent, isDeclarationWithTypeParameterChildren).typeParameters, "The type parameter to delete should exist"));
|
||||
changes.delete(sourceFile, Debug.checkDefined(cast(token.parent, isDeclarationWithTypeParameterChildren).typeParameters, "The type parameter to delete should exist"));
|
||||
}
|
||||
|
||||
// Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing.
|
||||
|
||||
@@ -55,7 +55,7 @@ namespace ts.codefix {
|
||||
}
|
||||
|
||||
function addImportFromExportedSymbol(exportedSymbol: Symbol, usageIsTypeOnly?: boolean) {
|
||||
const moduleSymbol = Debug.assertDefined(exportedSymbol.parent);
|
||||
const moduleSymbol = Debug.checkDefined(exportedSymbol.parent);
|
||||
const symbolName = getNameForExportedSymbol(exportedSymbol, getEmitScriptTarget(compilerOptions));
|
||||
const checker = program.getTypeChecker();
|
||||
const symbol = checker.getMergedSymbol(skipAlias(exportedSymbol, checker));
|
||||
@@ -339,7 +339,7 @@ namespace ts.codefix {
|
||||
.map((moduleSpecifier): FixAddNewImport | FixUseImportType =>
|
||||
// `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types.
|
||||
exportedSymbolIsTypeOnly && isJs
|
||||
? { kind: ImportFixKind.ImportType, moduleSpecifier, position: Debug.assertDefined(position, "position should be defined") }
|
||||
? { kind: ImportFixKind.ImportType, moduleSpecifier, position: Debug.checkDefined(position, "position should be defined") }
|
||||
: { kind: ImportFixKind.AddNew, moduleSpecifier, importKind, typeOnly: preferTypeOnlyImport }));
|
||||
|
||||
// Sort by presence in package.json, then shortest paths first
|
||||
@@ -542,7 +542,7 @@ namespace ts.codefix {
|
||||
|
||||
if (defaultExport.flags & SymbolFlags.Alias) {
|
||||
const aliased = checker.getImmediateAliasedSymbol(defaultExport);
|
||||
return aliased && getDefaultExportInfoWorker(aliased, Debug.assertDefined(aliased.parent, "Alias targets of default exports must have a parent"), checker, compilerOptions);
|
||||
return aliased && getDefaultExportInfoWorker(aliased, Debug.checkDefined(aliased.parent, "Alias targets of default exports must have a parent"), checker, compilerOptions);
|
||||
}
|
||||
|
||||
if (defaultExport.escapedName !== InternalSymbolName.Default &&
|
||||
@@ -620,7 +620,7 @@ namespace ts.codefix {
|
||||
changes.replaceNode(sourceFile, clause.namedBindings, namedImports);
|
||||
}
|
||||
else {
|
||||
changes.insertNodeAfter(sourceFile, Debug.assertDefined(clause.name, "Import clause must have either named imports or a default import"), namedImports);
|
||||
changes.insertNodeAfter(sourceFile, Debug.checkDefined(clause.name, "Import clause must have either named imports or a default import"), namedImports);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1031,7 +1031,7 @@ namespace ts.codefix {
|
||||
usage.properties.forEach((propUsage, name) => {
|
||||
const genericPropertyType = checker.getTypeOfPropertyOfType(generic, name as string);
|
||||
Debug.assert(!!genericPropertyType, "generic should have all the properties of its reference.");
|
||||
types.push(...inferTypeParameters(genericPropertyType!, combineFromUsage(propUsage), singleTypeParameter));
|
||||
types.push(...inferTypeParameters(genericPropertyType, combineFromUsage(propUsage), singleTypeParameter));
|
||||
});
|
||||
return builtinConstructors[type.symbol.escapedName as string](combineTypes(types));
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ namespace ts.codefix {
|
||||
if (!importDeclaration) {
|
||||
return;
|
||||
}
|
||||
const importClause = Debug.assertDefined(importDeclaration.importClause);
|
||||
const importClause = Debug.checkDefined(importDeclaration.importClause);
|
||||
changes.replaceNode(context.sourceFile, importDeclaration, updateImportDeclaration(
|
||||
importDeclaration,
|
||||
importDeclaration.decorators,
|
||||
|
||||
@@ -1020,7 +1020,8 @@ namespace ts.Completions {
|
||||
getTypeScriptMemberSymbols();
|
||||
}
|
||||
else if (isRightOfOpenTag) {
|
||||
const tagSymbols = Debug.assertEachDefined(typeChecker.getJsxIntrinsicTagNamesAt(location), "getJsxIntrinsicTagNames() should all be defined");
|
||||
const tagSymbols = typeChecker.getJsxIntrinsicTagNamesAt(location);
|
||||
Debug.assertEachIsDefined(tagSymbols, "getJsxIntrinsicTagNames() should all be defined");
|
||||
tryGetGlobalSymbols();
|
||||
symbols = tagSymbols.concat(symbols);
|
||||
completionKind = CompletionKind.MemberLike;
|
||||
@@ -1103,7 +1104,8 @@ namespace ts.Completions {
|
||||
|
||||
if (symbol.flags & (SymbolFlags.Module | SymbolFlags.Enum)) {
|
||||
// Extract module or enum members
|
||||
const exportedSymbols = Debug.assertEachDefined(typeChecker.getExportsOfModule(symbol), "getExportsOfModule() should all be defined");
|
||||
const exportedSymbols = typeChecker.getExportsOfModule(symbol);
|
||||
Debug.assertEachIsDefined(exportedSymbols, "getExportsOfModule() should all be defined");
|
||||
const isValidValueAccess = (symbol: Symbol) => typeChecker.isValidPropertyAccess(isImportType ? <ImportTypeNode>node : <PropertyAccessExpression>(node.parent), symbol.name);
|
||||
const isValidTypeAccess = (symbol: Symbol) => symbolCanBeReferencedAtTypeLocation(symbol);
|
||||
const isValidAccess: (symbol: Symbol) => boolean =
|
||||
@@ -1335,7 +1337,8 @@ namespace ts.Completions {
|
||||
|
||||
const symbolMeanings = (isTypeOnly ? SymbolFlags.None : SymbolFlags.Value) | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias;
|
||||
|
||||
symbols = Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined");
|
||||
symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings);
|
||||
Debug.assertEachIsDefined(symbols, "getSymbolsInScope() should all be defined");
|
||||
for (const symbol of symbols) {
|
||||
if (!typeChecker.isArgumentsSymbol(symbol) &&
|
||||
!some(symbol.declarations, d => d.getSourceFile() === sourceFile)) {
|
||||
@@ -1848,7 +1851,7 @@ namespace ts.Completions {
|
||||
|
||||
if (typeMembers && typeMembers.length > 0) {
|
||||
// Add filtered items to the completion list
|
||||
symbols = filterObjectMembersList(typeMembers, Debug.assertDefined(existingMembers));
|
||||
symbols = filterObjectMembersList(typeMembers, Debug.checkDefined(existingMembers));
|
||||
}
|
||||
setSortTextToOptionalMember();
|
||||
|
||||
@@ -2585,8 +2588,8 @@ namespace ts.Completions {
|
||||
*/
|
||||
function getPropertiesForCompletion(type: Type, checker: TypeChecker): Symbol[] {
|
||||
return type.isUnion()
|
||||
? Debug.assertEachDefined(checker.getAllPossiblePropertiesOfTypes(type.types), "getAllPossiblePropertiesOfTypes() should all be defined")
|
||||
: Debug.assertEachDefined(type.getApparentProperties(), "getApparentProperties() should all be defined");
|
||||
? Debug.checkEachDefined(checker.getAllPossiblePropertiesOfTypes(type.types), "getAllPossiblePropertiesOfTypes() should all be defined")
|
||||
: Debug.checkEachDefined(type.getApparentProperties(), "getApparentProperties() should all be defined");
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -230,7 +230,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey): void {
|
||||
const bucket = Debug.assertDefined(buckets.get(key));
|
||||
const bucket = Debug.checkDefined(buckets.get(key));
|
||||
const entry = bucket.get(path)!;
|
||||
entry.languageServiceRefCount--;
|
||||
|
||||
|
||||
@@ -723,7 +723,7 @@ namespace ts.FindAllReferences {
|
||||
if (sourceFilesSet.has(sourceFile.fileName)) {
|
||||
// At `module.exports = ...`, reference node is `module`
|
||||
const node = isBinaryExpression(decl) && isPropertyAccessExpression(decl.left) ? decl.left.expression :
|
||||
isExportAssignment(decl) ? Debug.assertDefined(findChildOfKind(decl, SyntaxKind.ExportKeyword, sourceFile)) :
|
||||
isExportAssignment(decl) ? Debug.checkDefined(findChildOfKind(decl, SyntaxKind.ExportKeyword, sourceFile)) :
|
||||
getNameOfDeclaration(decl) || decl;
|
||||
references.push(nodeEntry(node));
|
||||
}
|
||||
@@ -801,7 +801,7 @@ namespace ts.FindAllReferences {
|
||||
}
|
||||
else if (node && node.kind === SyntaxKind.DefaultKeyword) {
|
||||
addReference(node, symbol, state);
|
||||
searchForImportsOfExport(node, symbol, { exportingModuleSymbol: Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: ExportKind.Default }, state);
|
||||
searchForImportsOfExport(node, symbol, { exportingModuleSymbol: Debug.checkDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: ExportKind.Default }, state);
|
||||
}
|
||||
else {
|
||||
const search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, options.use === FindReferencesUse.Rename, !!options.providePrefixAndSuffixTextForRename, !!options.implementations) : [symbol] });
|
||||
@@ -1194,7 +1194,7 @@ namespace ts.FindAllReferences {
|
||||
export function eachSignatureCall(signature: SignatureDeclaration, sourceFiles: readonly SourceFile[], checker: TypeChecker, cb: (call: CallExpression) => void): void {
|
||||
if (!signature.name || !isIdentifier(signature.name)) return;
|
||||
|
||||
const symbol = Debug.assertDefined(checker.getSymbolAtLocation(signature.name));
|
||||
const symbol = Debug.checkDefined(checker.getSymbolAtLocation(signature.name));
|
||||
|
||||
for (const sourceFile of sourceFiles) {
|
||||
for (const name of getPossibleSymbolReferenceNodes(sourceFile, symbol.name)) {
|
||||
@@ -1410,7 +1410,7 @@ namespace ts.FindAllReferences {
|
||||
}
|
||||
|
||||
if (addReferencesHere && state.options.use !== FindReferencesUse.Rename && state.markSeenReExportRHS(name)) {
|
||||
addReference(name, Debug.assertDefined(exportSpecifier.symbol), state);
|
||||
addReference(name, Debug.checkDefined(exportSpecifier.symbol), state);
|
||||
}
|
||||
}
|
||||
else {
|
||||
@@ -1424,7 +1424,7 @@ namespace ts.FindAllReferences {
|
||||
const isDefaultExport = referenceLocation.originalKeywordKind === SyntaxKind.DefaultKeyword
|
||||
|| exportSpecifier.name.originalKeywordKind === SyntaxKind.DefaultKeyword;
|
||||
const exportKind = isDefaultExport ? ExportKind.Default : ExportKind.Named;
|
||||
const exportSymbol = Debug.assertDefined(exportSpecifier.symbol);
|
||||
const exportSymbol = Debug.checkDefined(exportSpecifier.symbol);
|
||||
const exportInfo = getExportInfo(exportSymbol, exportKind, state.checker);
|
||||
if (exportInfo) {
|
||||
searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state);
|
||||
|
||||
@@ -26,11 +26,11 @@ namespace ts.formatting {
|
||||
}
|
||||
|
||||
public updateContext(currentRange: TextRangeWithKind, currentTokenParent: Node, nextRange: TextRangeWithKind, nextTokenParent: Node, commonParent: Node) {
|
||||
this.currentTokenSpan = Debug.assertDefined(currentRange);
|
||||
this.currentTokenParent = Debug.assertDefined(currentTokenParent);
|
||||
this.nextTokenSpan = Debug.assertDefined(nextRange);
|
||||
this.nextTokenParent = Debug.assertDefined(nextTokenParent);
|
||||
this.contextNode = Debug.assertDefined(commonParent);
|
||||
this.currentTokenSpan = Debug.checkDefined(currentRange);
|
||||
this.currentTokenParent = Debug.checkDefined(currentTokenParent);
|
||||
this.nextTokenSpan = Debug.checkDefined(nextRange);
|
||||
this.nextTokenParent = Debug.checkDefined(nextTokenParent);
|
||||
this.contextNode = Debug.checkDefined(commonParent);
|
||||
|
||||
// drop cached results
|
||||
this.contextNodeAllOnSameLine = undefined;
|
||||
|
||||
@@ -63,8 +63,8 @@ namespace ts {
|
||||
const includes = mapDefined(property.initializer.elements, e => isStringLiteral(e) ? e.text : undefined);
|
||||
const matchers = getFileMatcherPatterns(configDir, /*excludes*/ [], includes, useCaseSensitiveFileNames, currentDirectory);
|
||||
// If there isn't some include for this, add a new one.
|
||||
if (getRegexFromPattern(Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(oldFileOrDirPath) &&
|
||||
!getRegexFromPattern(Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath)) {
|
||||
if (getRegexFromPattern(Debug.checkDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(oldFileOrDirPath) &&
|
||||
!getRegexFromPattern(Debug.checkDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath)) {
|
||||
changeTracker.insertNodeAfter(configFile, last(property.initializer.elements), createStringLiteral(relativePath(newFileOrDirPath)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -499,7 +499,7 @@ namespace ts.FindAllReferences {
|
||||
|
||||
function getExportAssignmentExport(ex: ExportAssignment): ExportedSymbol {
|
||||
// Get the symbol for the `export =` node; its parent is the module it's the export of.
|
||||
const exportingModuleSymbol = Debug.assertDefined(ex.symbol.parent, "Expected export symbol to have a parent");
|
||||
const exportingModuleSymbol = Debug.checkDefined(ex.symbol.parent, "Expected export symbol to have a parent");
|
||||
const exportKind = ex.isExportEquals ? ExportKind.ExportEquals : ExportKind.Default;
|
||||
return { kind: ImportExport.Export, symbol, exportInfo: { exportingModuleSymbol, exportKind } };
|
||||
}
|
||||
@@ -563,18 +563,18 @@ namespace ts.FindAllReferences {
|
||||
|
||||
function getExportEqualsLocalSymbol(importedSymbol: Symbol, checker: TypeChecker): Symbol {
|
||||
if (importedSymbol.flags & SymbolFlags.Alias) {
|
||||
return Debug.assertDefined(checker.getImmediateAliasedSymbol(importedSymbol));
|
||||
return Debug.checkDefined(checker.getImmediateAliasedSymbol(importedSymbol));
|
||||
}
|
||||
|
||||
const decl = importedSymbol.valueDeclaration;
|
||||
if (isExportAssignment(decl)) { // `export = class {}`
|
||||
return Debug.assertDefined(decl.expression.symbol);
|
||||
return Debug.checkDefined(decl.expression.symbol);
|
||||
}
|
||||
else if (isBinaryExpression(decl)) { // `module.exports = class {}`
|
||||
return Debug.assertDefined(decl.right.symbol);
|
||||
return Debug.checkDefined(decl.right.symbol);
|
||||
}
|
||||
else if (isSourceFile(decl)) { // json module
|
||||
return Debug.assertDefined(decl.symbol);
|
||||
return Debug.checkDefined(decl.symbol);
|
||||
}
|
||||
return Debug.fail();
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ namespace ts.refactor {
|
||||
},
|
||||
getEditsForAction(context, actionName): RefactorEditInfo {
|
||||
Debug.assert(actionName === actionNameDefaultToNamed || actionName === actionNameNamedToDefault, "Unexpected action name");
|
||||
const edits = textChanges.ChangeTracker.with(context, t => doChange(context.file, context.program, Debug.assertDefined(getInfo(context), "context must have info"), t, context.cancellationToken));
|
||||
const edits = textChanges.ChangeTracker.with(context, t => doChange(context.file, context.program, Debug.checkDefined(getInfo(context), "context must have info"), t, context.cancellationToken));
|
||||
return { edits, renameFilename: undefined, renameLocation: undefined };
|
||||
},
|
||||
});
|
||||
@@ -78,10 +78,10 @@ namespace ts.refactor {
|
||||
|
||||
function changeExport(exportingSourceFile: SourceFile, { wasDefault, exportNode, exportName }: Info, changes: textChanges.ChangeTracker, checker: TypeChecker): void {
|
||||
if (wasDefault) {
|
||||
changes.delete(exportingSourceFile, Debug.assertDefined(findModifier(exportNode, SyntaxKind.DefaultKeyword), "Should find a default keyword in modifier list"));
|
||||
changes.delete(exportingSourceFile, Debug.checkDefined(findModifier(exportNode, SyntaxKind.DefaultKeyword), "Should find a default keyword in modifier list"));
|
||||
}
|
||||
else {
|
||||
const exportKeyword = Debug.assertDefined(findModifier(exportNode, SyntaxKind.ExportKeyword), "Should find an export keyword in modifier list");
|
||||
const exportKeyword = Debug.checkDefined(findModifier(exportNode, SyntaxKind.ExportKeyword), "Should find an export keyword in modifier list");
|
||||
switch (exportNode.kind) {
|
||||
case SyntaxKind.FunctionDeclaration:
|
||||
case SyntaxKind.ClassDeclaration:
|
||||
@@ -92,7 +92,7 @@ namespace ts.refactor {
|
||||
// If 'x' isn't used in this file, `export const x = 0;` --> `export default 0;`
|
||||
if (!FindAllReferences.Core.isSymbolReferencedInFile(exportName, checker, exportingSourceFile)) {
|
||||
// We checked in `getInfo` that an initializer exists.
|
||||
changes.replaceNode(exportingSourceFile, exportNode, createExportDefault(Debug.assertDefined(first(exportNode.declarationList.declarations).initializer, "Initializer was previously known to be present")));
|
||||
changes.replaceNode(exportingSourceFile, exportNode, createExportDefault(Debug.checkDefined(first(exportNode.declarationList.declarations).initializer, "Initializer was previously known to be present")));
|
||||
break;
|
||||
}
|
||||
// falls through
|
||||
@@ -111,7 +111,7 @@ namespace ts.refactor {
|
||||
|
||||
function changeImports(program: Program, { wasDefault, exportName, exportingModuleSymbol }: Info, changes: textChanges.ChangeTracker, cancellationToken: CancellationToken | undefined): void {
|
||||
const checker = program.getTypeChecker();
|
||||
const exportSymbol = Debug.assertDefined(checker.getSymbolAtLocation(exportName), "Export name should resolve to a symbol");
|
||||
const exportSymbol = Debug.checkDefined(checker.getSymbolAtLocation(exportName), "Export name should resolve to a symbol");
|
||||
FindAllReferences.Core.eachExportReference(program.getSourceFiles(), checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName.text, wasDefault, ref => {
|
||||
const importingSourceFile = ref.getSourceFile();
|
||||
if (wasDefault) {
|
||||
|
||||
@@ -13,7 +13,7 @@ namespace ts.refactor {
|
||||
},
|
||||
getEditsForAction(context, actionName): RefactorEditInfo {
|
||||
Debug.assert(actionName === actionNameNamespaceToNamed || actionName === actionNameNamedToNamespace, "Unexpected action name");
|
||||
const edits = textChanges.ChangeTracker.with(context, t => doChange(context.file, context.program, t, Debug.assertDefined(getImportToConvert(context), "Context must provide an import to convert")));
|
||||
const edits = textChanges.ChangeTracker.with(context, t => doChange(context.file, context.program, t, Debug.checkDefined(getImportToConvert(context), "Context must provide an import to convert")));
|
||||
return { edits, renameFilename: undefined, renameLocation: undefined };
|
||||
}
|
||||
});
|
||||
|
||||
@@ -523,7 +523,7 @@ namespace ts.refactor.convertParamsToDestructuredObject {
|
||||
if (classDeclaration.name) return [classDeclaration.name];
|
||||
// If the class declaration doesn't have a name, it should have a default modifier.
|
||||
// We validated this in `isValidFunctionDeclaration` through `hasNameOrDefault`
|
||||
const defaultModifier = Debug.assertDefined(
|
||||
const defaultModifier = Debug.checkDefined(
|
||||
findModifier(classDeclaration, SyntaxKind.DefaultKeyword),
|
||||
"Nameless class declaration should be a default export");
|
||||
return [defaultModifier];
|
||||
@@ -542,14 +542,14 @@ namespace ts.refactor.convertParamsToDestructuredObject {
|
||||
if (functionDeclaration.name) return [functionDeclaration.name];
|
||||
// If the function declaration doesn't have a name, it should have a default modifier.
|
||||
// We validated this in `isValidFunctionDeclaration` through `hasNameOrDefault`
|
||||
const defaultModifier = Debug.assertDefined(
|
||||
const defaultModifier = Debug.checkDefined(
|
||||
findModifier(functionDeclaration, SyntaxKind.DefaultKeyword),
|
||||
"Nameless function declaration should be a default export");
|
||||
return [defaultModifier];
|
||||
case SyntaxKind.MethodDeclaration:
|
||||
return [functionDeclaration.name];
|
||||
case SyntaxKind.Constructor:
|
||||
const ctrKeyword = Debug.assertDefined(
|
||||
const ctrKeyword = Debug.checkDefined(
|
||||
findChildOfKind(functionDeclaration, SyntaxKind.ConstructorKeyword, functionDeclaration.getSourceFile()),
|
||||
"Constructor declaration should have constructor keyword");
|
||||
if (functionDeclaration.parent.kind === SyntaxKind.ClassExpression) {
|
||||
|
||||
@@ -1382,7 +1382,7 @@ namespace ts.refactor.extractSymbol {
|
||||
}
|
||||
|
||||
// There must be at least one statement since we started in one.
|
||||
return Debug.assertDefined(prevStatement, "prevStatement failed to get set");
|
||||
return Debug.checkDefined(prevStatement, "prevStatement failed to get set");
|
||||
}
|
||||
|
||||
Debug.assert(curr !== scope, "Didn't encounter a block-like before encountering scope");
|
||||
|
||||
@@ -23,7 +23,7 @@ namespace ts.refactor {
|
||||
},
|
||||
getEditsForAction(context, actionName): RefactorEditInfo {
|
||||
const { file } = context;
|
||||
const info = Debug.assertDefined(getRangeToExtract(context), "Expected to find a range to extract");
|
||||
const info = Debug.checkDefined(getRangeToExtract(context), "Expected to find a range to extract");
|
||||
|
||||
const name = getUniqueName("NewType", file);
|
||||
const edits = textChanges.ChangeTracker.with(context, changes => {
|
||||
@@ -68,7 +68,7 @@ namespace ts.refactor {
|
||||
if (!selection || !isTypeNode(selection)) return undefined;
|
||||
|
||||
const checker = context.program.getTypeChecker();
|
||||
const firstStatement = Debug.assertDefined(findAncestor(selection, isStatement), "Should find a statement");
|
||||
const firstStatement = Debug.checkDefined(findAncestor(selection, isStatement), "Should find a statement");
|
||||
const typeParameters = collectTypeParameters(checker, selection, firstStatement, file);
|
||||
if (!typeParameters) return undefined;
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ namespace ts.refactor {
|
||||
},
|
||||
getEditsForAction(context, actionName): RefactorEditInfo {
|
||||
Debug.assert(actionName === refactorName, "Wrong refactor invoked");
|
||||
const statements = Debug.assertDefined(getStatementsToMove(context));
|
||||
const statements = Debug.checkDefined(getStatementsToMove(context));
|
||||
const edits = textChanges.ChangeTracker.with(context, t => doChange(context.file, context.program, statements, t, context.host, context.preferences));
|
||||
return { edits, renameFilename: undefined, renameLocation: undefined };
|
||||
}
|
||||
@@ -310,7 +310,7 @@ namespace ts.refactor {
|
||||
return flatMap(toMove, statement => {
|
||||
if (isTopLevelDeclarationStatement(statement) &&
|
||||
!isExported(sourceFile, statement, useEs6Exports) &&
|
||||
forEachTopLevelDeclaration(statement, d => needExport.has(Debug.assertDefined(d.symbol)))) {
|
||||
forEachTopLevelDeclaration(statement, d => needExport.has(Debug.checkDefined(d.symbol)))) {
|
||||
const exports = addExport(statement, useEs6Exports);
|
||||
if (exports) return exports;
|
||||
}
|
||||
@@ -472,7 +472,7 @@ namespace ts.refactor {
|
||||
|
||||
for (const statement of toMove) {
|
||||
forEachTopLevelDeclaration(statement, decl => {
|
||||
movedSymbols.add(Debug.assertDefined(isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol, "Need a symbol here"));
|
||||
movedSymbols.add(Debug.checkDefined(isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol, "Need a symbol here"));
|
||||
});
|
||||
}
|
||||
for (const statement of toMove) {
|
||||
|
||||
@@ -1261,7 +1261,7 @@ namespace ts {
|
||||
return host.getDirectories ? host.getDirectories(path) : [];
|
||||
},
|
||||
readDirectory(path, extensions, exclude, include, depth) {
|
||||
Debug.assertDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'");
|
||||
Debug.checkDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'");
|
||||
return host.readDirectory!(path, extensions, exclude, include, depth);
|
||||
},
|
||||
onReleaseOldSourceFile,
|
||||
|
||||
@@ -144,7 +144,7 @@ namespace ts.SmartSelectionRange {
|
||||
// few keystrokes.
|
||||
if (isMappedTypeNode(node)) {
|
||||
const [openBraceToken, ...children] = node.getChildren();
|
||||
const closeBraceToken = Debug.assertDefined(children.pop());
|
||||
const closeBraceToken = Debug.checkDefined(children.pop());
|
||||
Debug.assertEqual(openBraceToken.kind, SyntaxKind.OpenBraceToken);
|
||||
Debug.assertEqual(closeBraceToken.kind, SyntaxKind.CloseBraceToken);
|
||||
// Group `-/+readonly` and `-/+?`
|
||||
|
||||
@@ -1315,7 +1315,7 @@ namespace ts.textChanges {
|
||||
// Delete named imports while preserving the default import
|
||||
// import d|, * as ns| from './file'
|
||||
// import d|, { a }| from './file'
|
||||
const previousToken = Debug.assertDefined(getTokenAtPosition(sourceFile, node.pos - 1));
|
||||
const previousToken = Debug.checkDefined(getTokenAtPosition(sourceFile, node.pos - 1));
|
||||
changes.deleteRange(sourceFile, { pos: previousToken.getStart(sourceFile), end: node.end });
|
||||
}
|
||||
else {
|
||||
@@ -1371,7 +1371,7 @@ namespace ts.textChanges {
|
||||
}
|
||||
|
||||
function deleteNodeInList(changes: ChangeTracker, deletedNodesInLists: NodeSet<Node>, sourceFile: SourceFile, node: Node): void {
|
||||
const containingList = Debug.assertDefined(formatting.SmartIndenter.getContainingList(node, sourceFile));
|
||||
const containingList = Debug.checkDefined(formatting.SmartIndenter.getContainingList(node, sourceFile));
|
||||
const index = indexOfNode(containingList, node);
|
||||
Debug.assert(index !== -1);
|
||||
if (containingList.length === 1) {
|
||||
|
||||
@@ -2749,7 +2749,7 @@ namespace ts {
|
||||
if (symbol.escapedName === InternalSymbolName.ExportEquals || symbol.escapedName === InternalSymbolName.Default) {
|
||||
// Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase.
|
||||
return firstDefined(symbol.declarations, d => isExportAssignment(d) && isIdentifier(d.expression) ? d.expression.text : undefined)
|
||||
|| codefix.moduleSymbolToValidIdentifier(Debug.assertDefined(symbol.parent), scriptTarget);
|
||||
|| codefix.moduleSymbolToValidIdentifier(Debug.checkDefined(symbol.parent), scriptTarget);
|
||||
}
|
||||
return symbol.name;
|
||||
}
|
||||
|
||||
@@ -101,7 +101,7 @@ namespace ts {
|
||||
return transformSourceFile(`let a!: () => void`, [
|
||||
context => file => visitNode(file, function visitor(node: Node): VisitResult<Node> {
|
||||
if (node.kind === SyntaxKind.VoidKeyword) {
|
||||
return createIdentifier("undefined");
|
||||
return createKeywordTypeNode(SyntaxKind.UndefinedKeyword);
|
||||
}
|
||||
return visitEachChild(node, visitor, context);
|
||||
})
|
||||
|
||||
@@ -419,7 +419,7 @@ namespace ts.tscWatch {
|
||||
}
|
||||
|
||||
export function replaceFileText(sys: WatchedSystem, file: string, searchValue: string | RegExp, replaceValue: string) {
|
||||
const content = Debug.assertDefined(sys.readFile(file));
|
||||
const content = Debug.checkDefined(sys.readFile(file));
|
||||
sys.writeFile(file, content.replace(searchValue, replaceValue));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,7 +114,7 @@ namespace ts.projectSystem {
|
||||
|
||||
function verifyConfiguredProject(host: TestServerHost, projectService: TestProjectService, orphanInferredProject?: boolean) {
|
||||
projectService.checkNumberOfProjects({ configuredProjects: 1, inferredProjects: orphanInferredProject ? 1 : 0 });
|
||||
const project = Debug.assertDefined(projectService.configuredProjects.get(tsconfig.path));
|
||||
const project = Debug.checkDefined(projectService.configuredProjects.get(tsconfig.path));
|
||||
|
||||
if (orphanInferredProject) {
|
||||
const inferredProject = projectService.inferredProjects[0];
|
||||
|
||||
@@ -26,9 +26,9 @@ namespace ts.projectSystem {
|
||||
|
||||
function checkDeclarationFiles(file: File, session: TestSession, expectedFiles: readonly File[]): void {
|
||||
openFilesForSession([file], session);
|
||||
const project = Debug.assertDefined(session.getProjectService().getDefaultProjectForFile(file.path as server.NormalizedPath, /*ensureProject*/ false));
|
||||
const project = Debug.checkDefined(session.getProjectService().getDefaultProjectForFile(file.path as server.NormalizedPath, /*ensureProject*/ false));
|
||||
const program = project.getCurrentProgram()!;
|
||||
const output = getFileEmitOutput(program, Debug.assertDefined(program.getSourceFile(file.path)), /*emitOnlyDtsFiles*/ true);
|
||||
const output = getFileEmitOutput(program, Debug.checkDefined(program.getSourceFile(file.path)), /*emitOnlyDtsFiles*/ true);
|
||||
closeFilesForSession([file], session);
|
||||
|
||||
Debug.assert(!output.emitSkipped);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
namespace ts.projectSystem {
|
||||
export function verifyDynamic(service: server.ProjectService, path: string) {
|
||||
const info = Debug.assertDefined(service.filenameToScriptInfo.get(path), `Expected ${path} in :: ${JSON.stringify(arrayFrom(service.filenameToScriptInfo.entries(), ([key, f]) => ({ key, fileName: f.fileName, path: f.path })))}`);
|
||||
const info = Debug.checkDefined(service.filenameToScriptInfo.get(path), `Expected ${path} in :: ${JSON.stringify(arrayFrom(service.filenameToScriptInfo.entries(), ([key, f]) => ({ key, fileName: f.fileName, path: f.path })))}`);
|
||||
assert.isTrue(info.isDynamic);
|
||||
}
|
||||
|
||||
@@ -191,7 +191,7 @@ var x = 10;`
|
||||
catch (e) {
|
||||
assert.strictEqual(
|
||||
e.message.replace(/\r?\n/, "\n"),
|
||||
`Debug Failure. False expression: \nVerbose Debug Information: {"fileName":"^walkThroughSnippet:/Users/UserName/projects/someProject/out/someFile#1.js","currentDirectory":"/user/username/projects/myproject","hostCurrentDirectory":"/","openKeys":[]}\nDynamic files must always be opened with service's current directory or service should support inferred project per projectRootPath.`
|
||||
`Debug Failure. False expression.\nVerbose Debug Information: {"fileName":"^walkThroughSnippet:/Users/UserName/projects/someProject/out/someFile#1.js","currentDirectory":"/user/username/projects/myproject","hostCurrentDirectory":"/","openKeys":[]}\nDynamic files must always be opened with service's current directory or service should support inferred project per projectRootPath.`
|
||||
);
|
||||
}
|
||||
const file2Path = file.path.replace("#1", "#2");
|
||||
|
||||
@@ -241,7 +241,7 @@ namespace ts.projectSystem {
|
||||
}
|
||||
return true;
|
||||
});
|
||||
return Debug.assertDefined(eventData);
|
||||
return Debug.checkDefined(eventData);
|
||||
}
|
||||
|
||||
hasZeroEvent<T extends server.ProjectServiceEvent>(eventName: T["eventName"]) {
|
||||
|
||||
@@ -1291,7 +1291,7 @@ namespace ts.projectSystem {
|
||||
verifyFile2InfoIsOrphan();
|
||||
|
||||
function verifyFile2InfoIsOrphan() {
|
||||
const info = Debug.assertDefined(service.getScriptInfoForPath(file2.path as Path));
|
||||
const info = Debug.checkDefined(service.getScriptInfoForPath(file2.path as Path));
|
||||
assert.equal(info.containingProjects.length, 0);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -918,7 +918,7 @@ export const x = 10;`
|
||||
const service = createProjectService(host);
|
||||
service.openClientFile(file1.path);
|
||||
checkNumberOfProjects(service, { configuredProjects: 1 });
|
||||
const project = Debug.assertDefined(service.configuredProjects.get(config.path));
|
||||
const project = Debug.checkDefined(service.configuredProjects.get(config.path));
|
||||
checkProjectActualFiles(project, files.map(f => f.path));
|
||||
host.checkTimeoutQueueLength(0);
|
||||
|
||||
|
||||
@@ -45,7 +45,7 @@ namespace ts.projectSystem {
|
||||
const projectService = createProjectService(host);
|
||||
projectService.openClientFile(index.path);
|
||||
|
||||
const project = Debug.assertDefined(projectService.configuredProjects.get(configFile.path));
|
||||
const project = Debug.checkDefined(projectService.configuredProjects.get(configFile.path));
|
||||
verifyProjectAndCompletions();
|
||||
|
||||
// Add file2
|
||||
@@ -168,7 +168,7 @@ namespace ts.projectSystem {
|
||||
const projectService = createProjectService(host);
|
||||
projectService.openClientFile(index.path);
|
||||
|
||||
const project = Debug.assertDefined(projectService.configuredProjects.get(configFile.path));
|
||||
const project = Debug.checkDefined(projectService.configuredProjects.get(configFile.path));
|
||||
verifyProject();
|
||||
|
||||
const nodeModulesIgnoredFileFromIgnoreDirectory: File = {
|
||||
|
||||
Reference in New Issue
Block a user