Merge pull request #32239 from andrewbranch/enhancement/missing-await-errors

Improve error messages for potentially missing 'await'
This commit is contained in:
Andrew Branch
2019-07-09 16:28:54 -07:00
committed by GitHub
9 changed files with 607 additions and 44 deletions
+125 -41
View File
@@ -932,6 +932,19 @@ namespace ts {
addErrorOrSuggestion(isError, "message" in message ? createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) : createDiagnosticForNodeFromMessageChain(location, message));
}
function errorAndMaybeSuggestAwait(
location: Node,
maybeMissingAwait: boolean,
message: DiagnosticMessage,
arg0?: string | number | undefined, arg1?: string | number | undefined, arg2?: string | number | undefined, arg3?: string | number | undefined): Diagnostic {
const diagnostic = error(location, message, arg0, arg1, arg2, arg3);
if (maybeMissingAwait) {
const related = createDiagnosticForNode(location, Diagnostics.Did_you_forget_to_use_await);
addRelatedInfo(diagnostic, related);
}
return diagnostic;
}
function createSymbol(flags: SymbolFlags, name: __String, checkFlags?: CheckFlags) {
symbolCount++;
const symbol = <TransientSymbol>(new Symbol(flags | SymbolFlags.Transient, name));
@@ -21426,6 +21439,7 @@ namespace ts {
const checkArgType = checkMode & CheckMode.SkipContextSensitive ? getRegularTypeOfObjectLiteral(argType) : argType;
if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage, containingMessageChain, errorOutputContainer)) {
Debug.assert(!reportErrors || !!errorOutputContainer.errors, "parameter should have errors when reporting errors");
maybeAddMissingAwaitInfo(arg, checkArgType, paramType);
return errorOutputContainer.errors || [];
}
}
@@ -21435,10 +21449,24 @@ namespace ts {
const errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined;
if (!checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage, /*containingMessageChain*/ undefined, errorOutputContainer)) {
Debug.assert(!reportErrors || !!errorOutputContainer.errors, "rest parameter should have errors when reporting errors");
maybeAddMissingAwaitInfo(errorNode, spreadType, restType);
return errorOutputContainer.errors || [];
}
}
return undefined;
function maybeAddMissingAwaitInfo(errorNode: Node | undefined, source: Type, target: Type) {
if (errorNode && reportErrors && errorOutputContainer.errors && errorOutputContainer.errors.length) {
// Bail if target is Promise-like---something else is wrong
if (getAwaitedTypeOfPromise(target)) {
return;
}
const awaitedTypeOfSource = getAwaitedTypeOfPromise(source);
if (awaitedTypeOfSource && isTypeRelatedTo(awaitedTypeOfSource, target, relation)) {
addRelatedInfo(errorOutputContainer.errors[0], createDiagnosticForNode(errorNode, Diagnostics.Did_you_forget_to_use_await));
}
}
}
}
/**
@@ -22340,9 +22368,11 @@ namespace ts {
return true;
}
function invocationErrorDetails(apparentType: Type, kind: SignatureKind): DiagnosticMessageChain {
function invocationErrorDetails(apparentType: Type, kind: SignatureKind): { messageChain: DiagnosticMessageChain, relatedMessage: DiagnosticMessage | undefined } {
let errorInfo: DiagnosticMessageChain | undefined;
const isCall = kind === SignatureKind.Call;
const awaitedType = getAwaitedType(apparentType);
const maybeMissingAwait = awaitedType && getSignaturesOfType(awaitedType, kind).length > 0;
if (apparentType.flags & TypeFlags.Union) {
const types = (apparentType as UnionType).types;
let hasSignatures = false;
@@ -22407,15 +22437,20 @@ namespace ts {
typeToString(apparentType)
);
}
return chainDiagnosticMessages(
errorInfo,
isCall ?
Diagnostics.This_expression_is_not_callable :
Diagnostics.This_expression_is_not_constructable
);
return {
messageChain: chainDiagnosticMessages(
errorInfo,
isCall ? Diagnostics.This_expression_is_not_callable : Diagnostics.This_expression_is_not_constructable
),
relatedMessage: maybeMissingAwait ? Diagnostics.Did_you_forget_to_use_await : undefined,
};
}
function invocationError(errorTarget: Node, apparentType: Type, kind: SignatureKind, relatedInformation?: DiagnosticRelatedInformation) {
const diagnostic = createDiagnosticForNodeFromMessageChain(errorTarget, invocationErrorDetails(apparentType, kind));
const { messageChain, relatedMessage: relatedInfo } = invocationErrorDetails(apparentType, kind);
const diagnostic = createDiagnosticForNodeFromMessageChain(errorTarget, messageChain);
if (relatedInfo) {
addRelatedInfo(diagnostic, createDiagnosticForNode(errorTarget, relatedInfo));
}
if (isCallExpression(errorTarget.parent)) {
const { start, length } = getDiagnosticSpanForCallNode(errorTarget.parent, /* doNotIncludeArguments */ true);
diagnostic.start = start;
@@ -22515,9 +22550,12 @@ namespace ts {
const headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);
if (!callSignatures.length) {
let errorInfo = invocationErrorDetails(apparentType, SignatureKind.Call);
errorInfo = chainDiagnosticMessages(errorInfo, headMessage);
const diag = createDiagnosticForNodeFromMessageChain(node.expression, errorInfo);
const errorDetails = invocationErrorDetails(apparentType, SignatureKind.Call);
const messageChain = chainDiagnosticMessages(errorDetails.messageChain, headMessage);
const diag = createDiagnosticForNodeFromMessageChain(node.expression, messageChain);
if (errorDetails.relatedMessage) {
addRelatedInfo(diag, createDiagnosticForNode(node.expression, errorDetails.relatedMessage));
}
diagnostics.add(diag);
invocationErrorRecovery(apparentType, SignatureKind.Call, diag);
return resolveErrorCall(node);
@@ -23677,7 +23715,11 @@ namespace ts {
function checkArithmeticOperandType(operand: Node, type: Type, diagnostic: DiagnosticMessage): boolean {
if (!isTypeAssignableTo(type, numberOrBigIntType)) {
error(operand, diagnostic);
const awaitedType = getAwaitedType(type);
errorAndMaybeSuggestAwait(
operand,
!!awaitedType && isTypeAssignableTo(awaitedType, numberOrBigIntType),
diagnostic);
return false;
}
return true;
@@ -24295,7 +24337,7 @@ namespace ts {
) {
resultType = numberType;
}
// At least one is assignable to bigint, so both should be only assignable to bigint
// At least one is assignable to bigint, so check that both are
else if (isTypeAssignableToKind(leftType, TypeFlags.BigIntLike) && isTypeAssignableToKind(rightType, TypeFlags.BigIntLike)) {
switch (operator) {
case SyntaxKind.GreaterThanGreaterThanGreaterThanToken:
@@ -24304,8 +24346,9 @@ namespace ts {
}
resultType = bigintType;
}
// Exactly one of leftType/rightType is assignable to bigint
else {
reportOperatorError();
reportOperatorError((awaitedLeft, awaitedRight) => isTypeAssignableToKind(awaitedLeft, TypeFlags.BigIntLike) && isTypeAssignableToKind(awaitedRight, TypeFlags.BigIntLike));
resultType = errorType;
}
if (leftOk && rightOk) {
@@ -24350,7 +24393,14 @@ namespace ts {
}
if (!resultType) {
reportOperatorError();
// Types that have a reasonably good chance of being a valid operand type.
// If both types have an awaited type of one of these, we’ll assume the user
// might be missing an await without doing an exhaustive check that inserting
// await(s) will actually be a completely valid binary expression.
const closeEnoughKind = TypeFlags.NumberLike | TypeFlags.BigIntLike | TypeFlags.StringLike | TypeFlags.AnyOrUnknown;
reportOperatorError((awaitedLeft, awaitedRight) =>
isTypeAssignableToKind(awaitedLeft, closeEnoughKind) &&
isTypeAssignableToKind(awaitedRight, closeEnoughKind));
return anyType;
}
@@ -24365,21 +24415,18 @@ namespace ts {
if (checkForDisallowedESSymbolOperand(operator)) {
leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left));
rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right));
if (!(isTypeComparableTo(leftType, rightType) || isTypeComparableTo(rightType, leftType) ||
(isTypeAssignableTo(leftType, numberOrBigIntType) && isTypeAssignableTo(rightType, numberOrBigIntType))
)) {
reportOperatorError();
}
reportOperatorErrorUnless((left, right) =>
isTypeComparableTo(left, right) || isTypeComparableTo(right, left) || (
isTypeAssignableTo(left, numberOrBigIntType) && isTypeAssignableTo(right, numberOrBigIntType)));
}
return booleanType;
case SyntaxKind.EqualsEqualsToken:
case SyntaxKind.ExclamationEqualsToken:
case SyntaxKind.EqualsEqualsEqualsToken:
case SyntaxKind.ExclamationEqualsEqualsToken:
if (!isTypeEqualityComparableTo(leftType, rightType) && !isTypeEqualityComparableTo(rightType, leftType)) {
reportOperatorError();
}
reportOperatorErrorUnless((left, right) => isTypeEqualityComparableTo(left, right) || isTypeEqualityComparableTo(right, left));
return booleanType;
case SyntaxKind.InstanceOfKeyword:
return checkInstanceOfExpression(left, right, leftType, rightType);
case SyntaxKind.InKeyword:
@@ -24506,12 +24553,33 @@ namespace ts {
}
}
function reportOperatorError() {
const [leftStr, rightStr] = getTypeNamesForErrorDisplay(leftType, rightType);
/**
* Returns true if an error is reported
*/
function reportOperatorErrorUnless(typesAreCompatible: (left: Type, right: Type) => boolean): boolean {
if (!typesAreCompatible(leftType, rightType)) {
reportOperatorError(typesAreCompatible);
return true;
}
return false;
}
function reportOperatorError(awaitedTypesAreCompatible?: (left: Type, right: Type) => boolean) {
let wouldWorkWithAwait = false;
const errNode = errorNode || operatorToken;
if (!tryGiveBetterPrimaryError(errNode, leftStr, rightStr)) {
error(
const [leftStr, rightStr] = getTypeNamesForErrorDisplay(leftType, rightType);
if (awaitedTypesAreCompatible) {
const awaitedLeftType = getAwaitedType(leftType);
const awaitedRightType = getAwaitedType(rightType);
wouldWorkWithAwait = !(awaitedLeftType === leftType && awaitedRightType === rightType)
&& !!(awaitedLeftType && awaitedRightType)
&& awaitedTypesAreCompatible(awaitedLeftType, awaitedRightType);
}
if (!tryGiveBetterPrimaryError(errNode, wouldWorkWithAwait, leftStr, rightStr)) {
errorAndMaybeSuggestAwait(
errNode,
wouldWorkWithAwait,
Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2,
tokenToString(operatorToken.kind),
leftStr,
@@ -24520,15 +24588,26 @@ namespace ts {
}
}
function tryGiveBetterPrimaryError(errNode: Node, leftStr: string, rightStr: string) {
function tryGiveBetterPrimaryError(errNode: Node, maybeMissingAwait: boolean, leftStr: string, rightStr: string) {
let typeName: string | undefined;
switch (operatorToken.kind) {
case SyntaxKind.EqualsEqualsEqualsToken:
case SyntaxKind.EqualsEqualsToken:
return error(errNode, Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "false", leftStr, rightStr);
typeName = "false";
break;
case SyntaxKind.ExclamationEqualsEqualsToken:
case SyntaxKind.ExclamationEqualsToken:
return error(errNode, Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "true", leftStr, rightStr);
}
typeName = "true";
}
if (typeName) {
return errorAndMaybeSuggestAwait(
errNode,
maybeMissingAwait,
Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap,
typeName, leftStr, rightStr);
}
return undefined;
}
}
@@ -27879,18 +27958,22 @@ namespace ts {
// number and string input is allowed, we want to say that number is not an
// array type or a string type.
const yieldType = getIterationTypeOfIterable(use, IterationTypeKind.Yield, inputType, /*errorNode*/ undefined);
const diagnostic = !(use & IterationUse.AllowsStringInputFlag) || hasStringConstituent
const [defaultDiagnostic, maybeMissingAwait]: [DiagnosticMessage, boolean] = !(use & IterationUse.AllowsStringInputFlag) || hasStringConstituent
? downlevelIteration
? Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator
? [Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true]
: yieldType
? Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators
: Diagnostics.Type_0_is_not_an_array_type
? [Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false]
: [Diagnostics.Type_0_is_not_an_array_type, true]
: downlevelIteration
? Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator
? [Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true]
: yieldType
? Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators
: Diagnostics.Type_0_is_not_an_array_type_or_a_string_type;
error(errorNode, diagnostic, typeToString(arrayType));
? [Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false]
: [Diagnostics.Type_0_is_not_an_array_type_or_a_string_type, true];
errorAndMaybeSuggestAwait(
errorNode,
maybeMissingAwait && !!getAwaitedTypeOfPromise(arrayType),
defaultDiagnostic,
typeToString(arrayType));
}
return hasStringConstituent ? stringType : undefined;
}
@@ -28189,9 +28272,10 @@ namespace ts {
}
function reportTypeNotIterableError(errorNode: Node, type: Type, allowAsyncIterables: boolean): void {
error(errorNode, allowAsyncIterables
const message = allowAsyncIterables
? Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator
: Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator, typeToString(type));
: Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator;
errorAndMaybeSuggestAwait(errorNode, !!getAwaitedTypeOfPromise(type), message, typeToString(type));
}
/**
+4
View File
@@ -2693,6 +2693,10 @@
"category": "Error",
"code": 2772
},
"Did you forget to use 'await'?": {
"category": "Error",
"code": 2773
},
"Import declaration '{0}' is using private name '{1}'.": {
"category": "Error",