Compare commits

...

4 commits

Author SHA1 Message Date
rbuckton 7c7712e024 baselines, diff fallback 2017-01-07 15:09:33 -08:00
Ron Buckton 3c7741fe20 Add PromisesClause 2017-01-06 20:13:05 -08:00
Ron Buckton 4af87e1efc WIP promises type 2017-01-06 16:47:26 -08:00
Ron Buckton 46622740b2 Clean up promised type checking 2017-01-06 13:07:02 -08:00
14 changed files with 487 additions and 225 deletions

View file

@ -726,7 +726,7 @@ compileFile(
// Appending exports at the end of the server library
var tsserverLibraryDefinitionFileContents =
fs.readFileSync(tsserverLibraryDefinitionFile).toString() +
fs.readFileSync(tsserverLibraryDefinitionFile).toString() +
"\r\nexport = ts;" +
"\r\nexport as namespace ts;";
@ -851,24 +851,36 @@ var refTest262Baseline = path.join(internalTests, "baselines/test262/reference")
desc("Builds the test infrastructure using the built compiler");
task("tests", ["local", run].concat(libraryTargets));
function exec(cmd, completeHandler, errorHandler) {
function exec(cmd, completeHandler, errorHandler, opts) {
var stdio = opts && opts.stdio || {};
if (typeof stdio === "string") stdio = { stdout: stdio, stderr: stdio };
if (!stdio.stdout) stdio.stdout = "inherit";
if (!stdio.stderr) stdio.stderr = "inherit";
var stdout = "";
var stderr = "";
var ex = jake.createExec([cmd], { windowsVerbatimArguments: true });
// Add listeners for output and error
ex.addListener("stdout", function (output) {
process.stdout.write(output);
stdout += output;
if (stdio.stdout === "inherit") {
process.stdout.write(output);
}
});
ex.addListener("stderr", function (error) {
process.stderr.write(error);
stderr += error;
if (stdio.stderr === "inherit") {
process.stderr.write(error);
}
});
ex.addListener("cmdEnd", function () {
if (completeHandler) {
completeHandler();
completeHandler(stdout, stderr);
}
complete();
});
ex.addListener("error", function (e, status) {
if (errorHandler) {
errorHandler(e, status);
errorHandler(e, status, stdout, stderr);
} else {
fail("Process exited with code " + status);
}
@ -1070,27 +1082,61 @@ task("runtests-browser", ["tests", "browserify", builtLocalDirectory, servicesFi
exec(cmd);
}, { async: true });
function getDiffTool() {
function getDiffTool(cb) {
var program = process.env['DIFF'];
if (!program) {
if (program) return cb(program);
return exec("git config diff.tool", onGetDiffTool, onError, { stdio: "redirect" });
function onGetDiffTool(stdout) {
if (stdout) stdout = stdout.trim();
if (stdout) return exec("git config difftool." + stdout + ".cmd", onGetDifftoolCmd, onError, { stdio: "redirect" });
return onError();
}
function onGetDifftoolCmd(stdout) {
if (stdout) stdout = stdout.trim();
if (stdout) return cb(stdout.trim());
return onError();
}
function onError() {
fail("Add the 'DIFF' environment variable to the path of the program you want to use.");
}
return program;
}
function formatDiffTool(toolPath, leftPath, rightPath) {
return /\$(local|remote)/i.test(toolPath)
? toolPath.replace(/(\$local)|(\$remote)/gi, function (_, left, right) { return left ? leftPath : rightPath; })
: '"' + toolPath + '" "' + leftPath + '" "' + rightPath + '"';
}
function parseCommand(text) {
var re = /"([^"]*)"|[^"\s]+/g, args = [], m;
while (m = re.exec(text)) args.push(m[1] || m[0]);
return { cmd: args.shift(), args: args };
}
// Baseline Diff
desc("Diffs the compiler baselines using the diff tool specified by the 'DIFF' environment variable");
task('diff', function () {
var cmd = '"' + getDiffTool() + '" ' + refBaseline + ' ' + localBaseline;
console.log(cmd);
exec(cmd);
getDiffTool(function (tool) {
var cmd = formatDiffTool(tool, refBaseline, localBaseline);
console.log(cmd);
var opts = parseCommand(cmd);
child_process.spawn(opts.cmd, opts.args, { detached: true }).unref();
complete();
});
}, { async: true });
desc("Diffs the RWC baselines using the diff tool specified by the 'DIFF' environment variable");
task('diff-rwc', function () {
var cmd = '"' + getDiffTool() + '" ' + refRwcBaseline + ' ' + localRwcBaseline;
console.log(cmd);
exec(cmd);
getDiffTool(function (tool) {
var cmd = formatDiffTool(tool, refRwcBaseline, localRwcBaseline);
console.log(cmd);
var opts = parseCommand(cmd);
child_process.spawn(opts.cmd, opts.args, { detached: true }).unref();
complete();
});
}, { async: true });
desc("Builds the test sources and automation in debug mode");

View file

@ -256,6 +256,8 @@ namespace ts {
return "__index";
case SyntaxKind.ExportDeclaration:
return "__export";
case SyntaxKind.PromisesClause:
return "__promises";
case SyntaxKind.ExportAssignment:
return (<ExportAssignment>node).isExportEquals ? "export=" : "default";
case SyntaxKind.BinaryExpression:
@ -1944,6 +1946,7 @@ namespace ts {
case SyntaxKind.TypePredicate:
return checkTypePredicate(node as TypePredicateNode);
case SyntaxKind.TypeParameter:
case SyntaxKind.PromisesClause:
return declareSymbolAndAddToSymbolTable(<Declaration>node, SymbolFlags.TypeParameter, SymbolFlags.TypeParameterExcludes);
case SyntaxKind.Parameter:
return bindParameter(<ParameterDeclaration>node);
@ -3105,6 +3108,7 @@ namespace ts {
case SyntaxKind.AsExpression:
case SyntaxKind.NonNullExpression:
case SyntaxKind.ReadonlyKeyword:
case SyntaxKind.PromisesClause:
// These nodes are TypeScript syntax.
transformFlags |= TransformFlags.AssertTypeScript;
break;

View file

@ -1723,19 +1723,20 @@ namespace ts {
return result || emptyArray;
}
function setStructuredTypeMembers(type: StructuredType, members: SymbolTable, callSignatures: Signature[], constructSignatures: Signature[], stringIndexInfo: IndexInfo, numberIndexInfo: IndexInfo): ResolvedType {
function setStructuredTypeMembers(type: StructuredType, members: SymbolTable, callSignatures: Signature[], constructSignatures: Signature[], stringIndexInfo: IndexInfo, numberIndexInfo: IndexInfo, promisesClause: Symbol | undefined): ResolvedType {
(<ResolvedType>type).members = members;
(<ResolvedType>type).properties = getNamedMembers(members);
(<ResolvedType>type).callSignatures = callSignatures;
(<ResolvedType>type).constructSignatures = constructSignatures;
if (stringIndexInfo) (<ResolvedType>type).stringIndexInfo = stringIndexInfo;
if (numberIndexInfo) (<ResolvedType>type).numberIndexInfo = numberIndexInfo;
if (promisesClause) (<ResolvedType>type).promisesClause = promisesClause;
return <ResolvedType>type;
}
function createAnonymousType(symbol: Symbol, members: SymbolTable, callSignatures: Signature[], constructSignatures: Signature[], stringIndexInfo: IndexInfo, numberIndexInfo: IndexInfo): ResolvedType {
return setStructuredTypeMembers(createObjectType(ObjectFlags.Anonymous, symbol),
members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo, /*promisesClause*/ undefined);
}
function forEachSymbolTableInScope<T>(enclosingDeclaration: Node, callback: (symbolTable: SymbolTable) => T): T {
@ -3702,9 +3703,24 @@ namespace ts {
if (symbol.flags & SymbolFlags.Alias) {
return getTypeOfAlias(symbol);
}
if (symbol.flags & SymbolFlags.TypeParameter && symbol.name === "__promises") {
return getTypeOfPromisesClause(symbol);
}
return unknownType;
}
function getTypeOfPromisesClause(symbol: Symbol): Type {
const declaration = <PromisesClause | undefined>getDeclarationOfKind(symbol, SyntaxKind.PromisesClause);
return declaration ? getTypeFromTypeNode(declaration.type) : unknownType;
}
function isReferenceToType(type: Type, target: Type) {
return type !== undefined
&& target !== undefined
&& (getObjectFlags(type) & ObjectFlags.Reference) !== 0
&& (<TypeReference>type).target === target;
}
function getTargetType(type: Type): Type {
return getObjectFlags(type) & ObjectFlags.Reference ? (<TypeReference>type).target : type;
}
@ -4287,6 +4303,7 @@ namespace ts {
(<InterfaceTypeWithDeclaredMembers>type).declaredConstructSignatures = getSignaturesOfSymbol(symbol.members["__new"]);
(<InterfaceTypeWithDeclaredMembers>type).declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, IndexKind.String);
(<InterfaceTypeWithDeclaredMembers>type).declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, IndexKind.Number);
(<InterfaceTypeWithDeclaredMembers>type).declaredPromisesClause = symbol.members["__promises"];
}
return <InterfaceTypeWithDeclaredMembers>type;
}
@ -4306,6 +4323,7 @@ namespace ts {
let constructSignatures: Signature[];
let stringIndexInfo: IndexInfo;
let numberIndexInfo: IndexInfo;
let promisesClause: Symbol;
if (rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) {
mapper = identityMapper;
members = source.symbol ? source.symbol.members : createSymbolTable(source.declaredProperties);
@ -4313,6 +4331,7 @@ namespace ts {
constructSignatures = source.declaredConstructSignatures;
stringIndexInfo = source.declaredStringIndexInfo;
numberIndexInfo = source.declaredNumberIndexInfo;
promisesClause = source.declaredPromisesClause;
}
else {
mapper = createTypeMapper(typeParameters, typeArguments);
@ -4321,6 +4340,7 @@ namespace ts {
constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper);
stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper);
numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper);
promisesClause = source.declaredPromisesClause && instantiateSymbol(source.declaredPromisesClause, mapper);
}
const baseTypes = getBaseTypes(source);
if (baseTypes.length) {
@ -4335,9 +4355,10 @@ namespace ts {
constructSignatures = concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, SignatureKind.Construct));
stringIndexInfo = stringIndexInfo || getIndexInfoOfType(instantiatedBaseType, IndexKind.String);
numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, IndexKind.Number);
promisesClause = promisesClause || getPromisesClauseOfType(instantiatedBaseType);
}
}
setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo, promisesClause);
}
function resolveClassOrInterfaceMembers(type: InterfaceType): void {
@ -4484,7 +4505,7 @@ namespace ts {
const constructSignatures = getUnionSignatures(type.types, SignatureKind.Construct);
const stringIndexInfo = getUnionIndexInfo(type.types, IndexKind.String);
const numberIndexInfo = getUnionIndexInfo(type.types, IndexKind.Number);
setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo, /*promisesClause*/ undefined);
}
function intersectTypes(type1: Type, type2: Type): Type {
@ -4514,7 +4535,7 @@ namespace ts {
stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, IndexKind.String));
numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, IndexKind.Number));
}
setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo, /*promisesClause*/ undefined);
}
/**
@ -4528,7 +4549,9 @@ namespace ts {
const constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, SignatureKind.Construct), type.mapper);
const stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, IndexKind.String), type.mapper);
const numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, IndexKind.Number), type.mapper);
setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
const promisesClause = getPromisesClauseOfType(type.target);
const instantiatedPromisesClause = promisesClause && instantiateSymbol(promisesClause, type.mapper);
setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo, instantiatedPromisesClause);
}
else if (symbol.flags & SymbolFlags.TypeLiteral) {
const members = symbol.members;
@ -4536,7 +4559,8 @@ namespace ts {
const constructSignatures = getSignaturesOfSymbol(members["__new"]);
const stringIndexInfo = getIndexInfoOfSymbol(symbol, IndexKind.String);
const numberIndexInfo = getIndexInfoOfSymbol(symbol, IndexKind.Number);
setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
const promisesClause = members["__promises"];
setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo, promisesClause);
}
else {
// Combinations of function, class, enum and module
@ -4558,7 +4582,7 @@ namespace ts {
}
}
const numberIndexInfo = symbol.flags & SymbolFlags.Enum ? enumNumberIndexInfo : undefined;
setStructuredTypeMembers(type, members, emptyArray, constructSignatures, undefined, numberIndexInfo);
setStructuredTypeMembers(type, members, emptyArray, constructSignatures, undefined, numberIndexInfo, /*promisesClause*/ undefined);
// We resolve the members before computing the signatures because a signature may use
// typeof with a qualified name expression that circularly references the type we are
// in the process of resolving (see issue #6072). The temporarily empty signature list
@ -4574,7 +4598,7 @@ namespace ts {
const members: SymbolTable = createMap<Symbol>();
let stringIndexInfo: IndexInfo;
// Resolve upfront such that recursive references see an empty object type.
setStructuredTypeMembers(type, emptySymbols, emptyArray, emptyArray, undefined, undefined);
setStructuredTypeMembers(type, emptySymbols, emptyArray, emptyArray, undefined, undefined, undefined);
// In { [P in K]: T }, we refer to P as the type parameter type, K as the constraint type,
// and T as the template type.
const typeParameter = getTypeParameterFromMappedType(type);
@ -4598,7 +4622,7 @@ namespace ts {
const iterationType = keyType.flags & TypeFlags.Index ? getIndexType(getApparentType((<IndexType>keyType).type)) : keyType;
forEachType(iterationType, addMemberForKeyType);
}
setStructuredTypeMembers(type, members, emptyArray, emptyArray, stringIndexInfo, undefined);
setStructuredTypeMembers(type, members, emptyArray, emptyArray, stringIndexInfo, undefined, undefined);
function addMemberForKeyType(t: Type) {
// Create a mapper from T to the current iteration type constituent. Then, if the
@ -4953,6 +4977,17 @@ namespace ts {
return undefined;
}
function getPromisesClauseOfStructuredType(type: Type): Symbol | undefined {
if (type.flags & TypeFlags.StructuredType) {
const resolved = resolveStructuredTypeMembers(<ObjectType>type);
return resolved.promisesClause;
}
}
function getPromisesClauseOfType(type: Type): Symbol | undefined {
return getPromisesClauseOfStructuredType(getApparentType(type));
}
function getTypeParametersFromJSDocTemplate(declaration: SignatureDeclaration): TypeParameter[] {
if (declaration.flags & NodeFlags.JavaScriptFile) {
const templateTag = getJSDocTemplateTag(declaration);
@ -7733,15 +7768,18 @@ namespace ts {
result = mappedTypeRelatedTo(source, target, reportErrors);
}
else {
result = propertiesRelatedTo(source, target, reportErrors);
result = promisesClausesRelatedTo(source, target, reportErrors);
if (result) {
result &= signaturesRelatedTo(source, target, SignatureKind.Call, reportErrors);
result = propertiesRelatedTo(source, target, reportErrors);
if (result) {
result &= signaturesRelatedTo(source, target, SignatureKind.Construct, reportErrors);
result &= signaturesRelatedTo(source, target, SignatureKind.Call, reportErrors);
if (result) {
result &= indexTypesRelatedTo(source, originalSource, target, IndexKind.String, reportErrors);
result &= signaturesRelatedTo(source, target, SignatureKind.Construct, reportErrors);
if (result) {
result &= indexTypesRelatedTo(source, originalSource, target, IndexKind.Number, reportErrors);
result &= indexTypesRelatedTo(source, originalSource, target, IndexKind.String, reportErrors);
if (result) {
result &= indexTypesRelatedTo(source, originalSource, target, IndexKind.Number, reportErrors);
}
}
}
}
@ -7795,6 +7833,22 @@ namespace ts {
return Ternary.False;
}
function promisesClausesRelatedTo(source: Type, target: Type, reportErrors: boolean): Ternary {
// const sourceClause = getPromisesClauseOfType(source);
const sourceClause = resolveStructuredTypeMembers(<ObjectType>source).promisesClause;
const sourceType = sourceClause && getTypeOfSymbol(sourceClause);
// const targetClause = getPromisesClauseOfType(target);
const targetClause = resolveStructuredTypeMembers(<ObjectType>target).promisesClause;
const targetType = targetClause && getTypeOfSymbol(targetClause);
if (!sourceType && !targetType) {
return Ternary.Maybe;
}
if (!sourceType || !targetType) {
return Ternary.False;
}
return isRelatedTo(sourceType, targetType, reportErrors);
}
function propertiesRelatedTo(source: Type, target: Type, reportErrors: boolean): Ternary {
if (relation === identityRelation) {
return propertiesIdenticalTo(source, target);
@ -11000,22 +11054,14 @@ namespace ts {
return undefined;
}
function getContextualTypeForReturnExpression(node: Expression): Type {
function getContextualTypeForReturnExpression(node: Expression): Type | undefined {
const func = getContainingFunction(node);
if (isAsyncFunctionLike(func)) {
const contextualReturnType = getContextualReturnType(func);
if (contextualReturnType) {
return getPromisedType(contextualReturnType);
}
return undefined;
}
if (func && !func.asteriskToken) {
return getContextualReturnType(func);
const contextualReturnType = getContextualReturnType(func);
return isAsyncFunctionLike(func)
? contextualReturnType && getAwaitedTypeOfPromise(contextualReturnType)
: contextualReturnType;
}
return undefined;
}
@ -13922,6 +13968,10 @@ namespace ts {
pos < signature.parameters.length ? getTypeOfParameter(signature.parameters[pos]) : anyType;
}
function getTypeOfFirstParameterOfSignature(signature: Signature) {
return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType;
}
function assignContextualParameterTypes(signature: Signature, context: Signature, mapper: TypeMapper) {
const len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0);
if (isInferentialContext(mapper)) {
@ -14032,7 +14082,7 @@ namespace ts {
const globalPromiseType = getGlobalPromiseType();
if (globalPromiseType !== emptyGenericType) {
// if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type
promisedType = getAwaitedType(promisedType);
promisedType = getAwaitedType(promisedType) || emptyObjectType;
return createTypeReference(<GenericType>globalPromiseType, [promisedType]);
}
@ -14064,7 +14114,7 @@ namespace ts {
// Promise/A+ compatible implementation will always assimilate any foreign promise, so the
// return type of the body should be unwrapped to its awaited type, which we will wrap in
// the native Promise<T> type later in this function.
type = checkAwaitedType(type, func, Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member);
type = checkAwaitedType(type, /*errorNode*/ func);
}
}
else {
@ -14178,7 +14228,7 @@ namespace ts {
// Promise/A+ compatible implementation will always assimilate any foreign promise, so the
// return type of the body should be unwrapped to its awaited type, which should be wrapped in
// the native Promise<T> type by the caller.
type = checkAwaitedType(type, func, Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member);
type = checkAwaitedType(type, /*errorNode*/ func);
}
if (type.flags & TypeFlags.Never) {
hasReturnOfTypeNever = true;
@ -14351,7 +14401,7 @@ namespace ts {
const exprType = checkExpression(<Expression>node.body);
if (returnOrPromisedType) {
if (isAsync) {
const awaitedType = checkAwaitedType(exprType, node.body, Diagnostics.Expression_body_for_async_arrow_function_does_not_have_a_valid_callable_then_member);
const awaitedType = checkAwaitedType(exprType, /*errorNode*/ node.body);
checkTypeAssignableTo(awaitedType, returnOrPromisedType, node.body);
}
else {
@ -16346,22 +16396,46 @@ namespace ts {
}
}
function checkNonThenableType(type: Type, location?: Node, message?: DiagnosticMessage): Type {
type = getWidenedType(type);
const apparentType = getApparentType(type);
if ((apparentType.flags & (TypeFlags.Any | TypeFlags.Never)) === 0 && isTypeAssignableTo(type, getGlobalThenableType())) {
if (location) {
if (!message) {
message = Diagnostics.Operand_for_await_does_not_have_a_valid_callable_then_member;
}
// function getPromisesClauseConstraint(type: Type): Type | undefined {
// if (isTypeAny(type) || !type.symbol) {
// return undefined;
// }
error(location, message);
}
// const typeAsPromise = <PromiseOrAwaitableType>type;
// if (typeAsPromise.promisesClauseConstraintType) {
// return typeAsPromise.promisesClauseConstraintType;
// }
return unknownType;
// for (const decl of type.symbol.declarations) {
// if (decl.kind === SyntaxKind.ClassDeclaration || decl.kind === SyntaxKind)
// }
// }
function getAwaitedTypeOfPromise(type: Type, errorNode?: Node): Type | undefined {
const promisedType = getPromisedTypeOfPromise(type, errorNode);
return promisedType && getAwaitedType(promisedType, errorNode);
}
/**
* Determines whether a type has a callable 'then' method.
*/
function isThenableType(type: Type) {
//
// {
// then( // thenFunction
// ): any;
// }
//
// TODO(rbuckton): Verify whether we need to call getApparentType. See checkNonThenableType in master
const thenFunction = getTypeOfPropertyOfType(type, "then");
const thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, SignatureKind.Call) : emptyArray;
if (thenSignatures.length > 0) {
return true;
}
return type;
return false;
}
/**
@ -16369,7 +16443,7 @@ namespace ts {
* @param type The type of the promise.
* @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback.
*/
function getPromisedType(promise: Type): Type {
function getPromisedTypeOfPromise(promise: Type, errorNode?: Node): Type {
//
// { // promise
// then( // thenFunction
@ -16384,25 +16458,25 @@ namespace ts {
return undefined;
}
if (getObjectFlags(promise) & ObjectFlags.Reference) {
if ((<GenericType>promise).target === tryGetGlobalPromiseType()
|| (<GenericType>promise).target === getGlobalPromiseLikeType()) {
return (<GenericType>promise).typeArguments[0];
}
const typeAsPromise = <PromiseOrAwaitableType>promise;
if (typeAsPromise.promisedTypeOfPromise) {
return typeAsPromise.promisedTypeOfPromise;
}
const globalPromiseLikeType = getInstantiatedGlobalPromiseLikeType();
if (globalPromiseLikeType === emptyObjectType || !isTypeAssignableTo(promise, globalPromiseLikeType)) {
return undefined;
if (isReferenceToType(promise, getGlobalPromiseType())) {
return typeAsPromise.promisedTypeOfPromise = (<GenericType>promise).typeArguments[0];
}
const thenFunction = getTypeOfPropertyOfType(promise, "then");
if (!thenFunction || isTypeAny(thenFunction)) {
if (isTypeAny(thenFunction)) {
return undefined;
}
const thenSignatures = getSignaturesOfType(thenFunction, SignatureKind.Call);
const thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, SignatureKind.Call) : emptyArray;
if (thenSignatures.length === 0) {
if (errorNode) {
error(errorNode, Diagnostics.A_promise_must_have_a_then_method);
}
return undefined;
}
@ -16413,14 +16487,23 @@ namespace ts {
const onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, SignatureKind.Call);
if (onfulfilledParameterSignatures.length === 0) {
if (errorNode) {
error(errorNode, Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback);
}
return undefined;
}
return getUnionType(map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), /*subtypeReduction*/ true);
return typeAsPromise.promisedTypeOfPromise = getUnionType(map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), /*subtypeReduction*/ true);
}
function getTypeOfFirstParameterOfSignature(signature: Signature) {
return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType;
function getCallableType(type: Type): Type {
if (some(getSignaturesOfType(type, SignatureKind.Call))) {
return type;
}
if (type.flags & TypeFlags.Union) {
return getUnionType(map((<UnionType>type).types, getCallableType), /*subtypeReduction*/ true);
}
return neverType;
}
/**
@ -16430,96 +16513,111 @@ namespace ts {
* Promise-like type; otherwise, it is the type of the expression. This is used to reflect
* The runtime behavior of the `await` keyword.
*/
function getAwaitedType(type: Type) {
return checkAwaitedType(type, /*location*/ undefined, /*message*/ undefined);
function checkAwaitedType(type: Type, errorNode: Node): Type {
return getAwaitedType(type, errorNode) || unknownType;
}
function checkAwaitedType(type: Type, location?: Node, message?: DiagnosticMessage) {
return checkAwaitedTypeWorker(type);
function checkAwaitedTypeWorker(type: Type): Type {
if (type.flags & TypeFlags.Union) {
const types: Type[] = [];
for (const constituentType of (<UnionType>type).types) {
types.push(checkAwaitedTypeWorker(constituentType));
}
return getUnionType(types, /*subtypeReduction*/ true);
}
else {
const promisedType = getPromisedType(type);
if (promisedType === undefined) {
// The type was not a PromiseLike, so it could not be unwrapped any further.
// As long as the type does not have a callable "then" property, it is
// safe to return the type; otherwise, an error will have been reported in
// the call to checkNonThenableType and we will return unknownType.
//
// An example of a non-promise "thenable" might be:
//
// await { then(): void {} }
//
// The "thenable" does not match the minimal definition for a PromiseLike. When
// a Promise/A+-compatible or ES6 promise tries to adopt this value, the promise
// will never settle. We treat this as an error to help flag an early indicator
// of a runtime problem. If the user wants to return this value from an async
// function, they would need to wrap it in some other value. If they want it to
// be treated as a promise, they can cast to <any>.
return checkNonThenableType(type, location, message);
}
else {
if (type.id === promisedType.id || indexOf(awaitedTypeStack, promisedType.id) >= 0) {
// We have a bad actor in the form of a promise whose promised type is
// the same promise type, or a mutually recursive promise. Return the
// unknown type as we cannot guess the shape. If this were the actual
// case in the JavaScript, this Promise would never resolve.
//
// An example of a bad actor with a singly-recursive promise type might
// be:
//
// interface BadPromise {
// then(
// onfulfilled: (value: BadPromise) => any,
// onrejected: (error: any) => any): BadPromise;
// }
//
// The above interface will pass the PromiseLike check, and return a
// promised type of `BadPromise`. Since this is a self reference, we
// don't want to keep recursing ad infinitum.
//
// An example of a bad actor in the form of a mutually-recursive
// promise type might be:
//
// interface BadPromiseA {
// then(
// onfulfilled: (value: BadPromiseB) => any,
// onrejected: (error: any) => any): BadPromiseB;
// }
//
// interface BadPromiseB {
// then(
// onfulfilled: (value: BadPromiseA) => any,
// onrejected: (error: any) => any): BadPromiseA;
// }
//
if (location) {
error(
location,
Diagnostics._0_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method,
symbolToString(type.symbol));
}
return unknownType;
}
// Keep track of the type we're about to unwrap to avoid bad recursive promise types.
// See the comments above for more information.
awaitedTypeStack.push(type.id);
const awaitedType = checkAwaitedTypeWorker(promisedType);
awaitedTypeStack.pop();
return awaitedType;
}
}
function getAwaitedType(type: Type, errorNode?: Node): Type | undefined {
const typeAsAwaitable = <PromiseOrAwaitableType>type;
if (typeAsAwaitable.awaitedTypeOfType) {
return typeAsAwaitable.awaitedTypeOfType;
}
if (isTypeAny(type)) {
return typeAsAwaitable.awaitedTypeOfType = type;
}
if (type.flags & TypeFlags.Union) {
let types: Type[];
for (const constituentType of (<UnionType>type).types) {
types = append(types, getAwaitedType(constituentType, errorNode));
}
if (!types) {
return undefined;
}
return typeAsAwaitable.awaitedTypeOfType = getUnionType(types, /*subtypeReduction*/ true);
}
const promisedType = getPromisedTypeOfPromise(type);
if (promisedType) {
if (type.id === promisedType.id || indexOf(awaitedTypeStack, promisedType.id) >= 0) {
// Verify that we don't have a bad actor in the form of a promise whose
// promised type is the same as the promise type, or a mutually recursive
// promise. If so, we returnundefined as we cannot guess the shape. If this
// were the actual case in the JavaScript, this Promise would never resolve.
//
// An example of a bad actor with a singly-recursive promise type might
// be:
//
// interface BadPromise {
// then(
// onfulfilled: (value: BadPromise) => any,
// onrejected: (error: any) => any): BadPromise;
// }
// The above interface will pass the PromiseLike check, and return a
// promised type of `BadPromise`. Since this is a self reference, we
// don't want to keep recursing ad infinitum.
//
// An example of a bad actor in the form of a mutually-recursive
// promise type might be:
//
// interface BadPromiseA {
// then(
// onfulfilled: (value: BadPromiseB) => any,
// onrejected: (error: any) => any): BadPromiseB;
// }
//
// interface BadPromiseB {
// then(
// onfulfilled: (value: BadPromiseA) => any,
// onrejected: (error: any) => any): BadPromiseA;
// }
//
if (errorNode) {
error(errorNode, Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method);
}
return undefined;
}
// Keep track of the type we're about to unwrap to avoid bad recursive promise types.
// See the comments above for more information.
awaitedTypeStack.push(type.id);
const awaitedType = getAwaitedType(promisedType, errorNode);
awaitedTypeStack.pop();
if (!awaitedType) {
return undefined;
}
return typeAsAwaitable.awaitedTypeOfType = awaitedType;
}
// The type was not a promise, so it could not be unwrapped any further.
// As long as the type does not have a callable "then" property, it is
// safe to return the type; otherwise, an error will be reported in
// the call to getNonThenableType and we will return undefined.
//
// An example of a non-promise "thenable" might be:
//
// await { then(): void {} }
//
// The "thenable" does not match the minimal definition for a promise. When
// a Promise/A+-compatible or ES6 promise tries to adopt this value, the promise
// will never settle. We treat this as an error to help flag an early indicator
// of a runtime problem. If the user wants to return this value from an async
// function, they would need to wrap it in some other value. If they want it to
// be treated as a promise, they can cast to <any>.
const widenedType = getWidenedType(type);
if (isThenableType(widenedType)) {
if (errorNode) {
error(errorNode, Diagnostics.Type_used_as_operand_to_await_or_the_return_type_of_an_async_function_must_not_contain_a_callable_then_member_if_it_is_not_a_promise);
}
return undefined;
}
return typeAsAwaitable.awaitedTypeOfType = widenedType;
}
/**
@ -16620,7 +16718,7 @@ namespace ts {
}
// Get and return the awaited type of the return type.
return checkAwaitedType(returnType, node, Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type);
return checkAwaitedType(returnType, node);
}
/** Check a decorator */
@ -17864,7 +17962,7 @@ namespace ts {
}
function isUnwrappedReturnTypeVoidOrAny(func: FunctionLikeDeclaration, returnType: Type): boolean {
const unwrappedReturnType = isAsyncFunctionLike(func) ? getPromisedType(returnType) : returnType;
const unwrappedReturnType = isAsyncFunctionLike(func) ? getPromisedTypeOfPromise(returnType) : returnType;
return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, TypeFlags.Void | TypeFlags.Any);
}
@ -17904,8 +18002,8 @@ namespace ts {
}
else if (func.type || isGetAccessorWithAnnotatedSetAccessor(func)) {
if (isAsyncFunctionLike(func)) {
const promisedType = getPromisedType(returnType);
const awaitedType = checkAwaitedType(exprType, node.expression || node, Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member);
const promisedType = getPromisedTypeOfPromise(returnType);
const awaitedType = checkAwaitedType(exprType, node.expression || node);
if (promisedType) {
// If the function has a return type, but promisedType is
// undefined, an error will be reported in checkAsyncFunctionReturnType
@ -18182,11 +18280,12 @@ namespace ts {
}
/** Check that type parameter lists are identical across multiple declarations */
function checkTypeParameterListsIdentical(node: ClassLikeDeclaration | InterfaceDeclaration, symbol: Symbol) {
function checkTypeParameterListsAndPromisesTypesIdentical(node: ClassLikeDeclaration | InterfaceDeclaration, symbol: Symbol) {
if (symbol.declarations.length === 1) {
return;
}
let firstDecl: ClassLikeDeclaration | InterfaceDeclaration;
let firstPromisesType: Type;
for (const declaration of symbol.declarations) {
if (declaration.kind === SyntaxKind.ClassDeclaration || declaration.kind === SyntaxKind.InterfaceDeclaration) {
if (!firstDecl) {
@ -18195,6 +18294,17 @@ namespace ts {
else if (!areTypeParametersIdentical(firstDecl.typeParameters, node.typeParameters)) {
error(node.name, Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, node.name.text);
}
const promisesClause = (<ClassLikeDeclaration | InterfaceDeclaration>declaration).promisesClause;
const promisesType = promisesClause && getTypeFromTypeNode(promisesClause.type);
if (!firstPromisesType) {
firstPromisesType = promisesType;
}
else {
if (promisesType && !isTypeIdenticalTo(firstPromisesType, promisesType)) {
error(node.name, Diagnostics.Any_declarations_of_0_that_promise_a_type_must_promise_the_same_type, node.name.text);
}
}
}
}
}
@ -18236,7 +18346,7 @@ namespace ts {
const type = <InterfaceType>getDeclaredTypeOfSymbol(symbol);
const typeWithThis = getTypeWithThisArgument(type);
const staticType = <ObjectType>getTypeOfSymbol(symbol);
checkTypeParameterListsIdentical(node, symbol);
checkTypeParameterListsAndPromisesTypesIdentical(node, symbol);
checkClassForDuplicateDeclarations(node);
const baseTypeNode = getClassExtendsHeritageClauseElement(node);
@ -18307,6 +18417,22 @@ namespace ts {
}
}
const promisesClause = node.promisesClause;
if (promisesClause) {
if (produceDiagnostics) {
const t = getTypeFromTypeNode(promisesClause.type);
if (t !== unknownType) {
const promisedType = getPromisedTypeOfPromise(type);
if (!promisedType) {
error(node.name || node, Diagnostics.Class_or_interface_0_incorrectly_promises_type_1_A_compatible_then_signature_could_not_be_found, typeToString(type), typeToString(t));
}
else {
checkTypeAssignableTo(t, promisedType, node.name || node, Diagnostics.Class_or_interface_promises_type_0_which_is_not_compatible_with_the_type_1_used_by_the_fulfillment_callbacks_of_its_then_members);
}
}
}
}
if (produceDiagnostics) {
checkIndexConstraints(type);
checkTypeForDuplicateIndexSignatures(node);
@ -18506,13 +18632,14 @@ namespace ts {
// Grammar checking
checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarInterfaceDeclaration(node);
const promisesClause = node.promisesClause;
checkTypeParameters(node.typeParameters);
if (produceDiagnostics) {
checkTypeNameIsReserved(node.name, Diagnostics.Interface_name_cannot_be_0);
checkExportsOnMergedDeclarations(node);
const symbol = getSymbolOfNode(node);
checkTypeParameterListsIdentical(node, symbol);
checkTypeParameterListsAndPromisesTypesIdentical(node, symbol);
// Only check this symbol once
const firstInterfaceDecl = <InterfaceDeclaration>getDeclarationOfKind(symbol, SyntaxKind.InterfaceDeclaration);
@ -18526,6 +18653,19 @@ namespace ts {
}
checkIndexConstraints(type);
}
if (promisesClause) {
const promisesType = getTypeFromTypeNode(promisesClause.type);
if (promisesType !== unknownType) {
const promisedType = getPromisedTypeOfPromise(type);
if (!promisedType) {
error(node.name || node, Diagnostics.Class_or_interface_0_incorrectly_promises_type_1_A_compatible_then_signature_could_not_be_found, typeToString(type), typeToString(promisesType));
}
else {
checkTypeAssignableTo(promisesType, promisedType, node.name || node, Diagnostics.Class_or_interface_promises_type_0_which_is_not_compatible_with_the_type_1_used_by_the_fulfillment_callbacks_of_its_then_members);
}
}
}
}
checkObjectTypeForDuplicateDeclarations(node);
}
@ -21311,28 +21451,26 @@ namespace ts {
if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && node.heritageClauses) {
for (const heritageClause of node.heritageClauses) {
if (heritageClause.token === SyntaxKind.ExtendsKeyword) {
if (seenExtendsClause) {
return grammarErrorOnFirstToken(heritageClause, Diagnostics.extends_clause_already_seen);
}
switch (heritageClause.token) {
case SyntaxKind.ExtendsKeyword:
if (seenExtendsClause) {
return grammarErrorOnFirstToken(heritageClause, Diagnostics._0_clause_already_seen, "extends");
}
if (seenImplementsClause) {
return grammarErrorOnFirstToken(heritageClause, Diagnostics._0_clause_must_precede_1_clause, "extends", "implements");
}
if (heritageClause.types.length > 1) {
return grammarErrorOnFirstToken(heritageClause.types[1], Diagnostics.Classes_can_only_extend_a_single_class);
}
seenExtendsClause = true;
break;
if (seenImplementsClause) {
return grammarErrorOnFirstToken(heritageClause, Diagnostics.extends_clause_must_precede_implements_clause);
}
if (heritageClause.types.length > 1) {
return grammarErrorOnFirstToken(heritageClause.types[1], Diagnostics.Classes_can_only_extend_a_single_class);
}
seenExtendsClause = true;
}
else {
Debug.assert(heritageClause.token === SyntaxKind.ImplementsKeyword);
if (seenImplementsClause) {
return grammarErrorOnFirstToken(heritageClause, Diagnostics.implements_clause_already_seen);
}
seenImplementsClause = true;
case SyntaxKind.ImplementsKeyword:
if (seenImplementsClause) {
return grammarErrorOnFirstToken(heritageClause, Diagnostics._0_clause_already_seen, "implements");
}
seenImplementsClause = true;
break;
}
// Grammar checking heritageClause inside class declaration
@ -21346,16 +21484,15 @@ namespace ts {
if (node.heritageClauses) {
for (const heritageClause of node.heritageClauses) {
if (heritageClause.token === SyntaxKind.ExtendsKeyword) {
if (seenExtendsClause) {
return grammarErrorOnFirstToken(heritageClause, Diagnostics.extends_clause_already_seen);
}
seenExtendsClause = true;
}
else {
Debug.assert(heritageClause.token === SyntaxKind.ImplementsKeyword);
return grammarErrorOnFirstToken(heritageClause, Diagnostics.Interface_declaration_cannot_have_implements_clause);
switch (heritageClause.token) {
case SyntaxKind.ExtendsKeyword:
if (seenExtendsClause) {
return grammarErrorOnFirstToken(heritageClause, Diagnostics._0_clause_already_seen, "extends");
}
seenExtendsClause = true;
break;
case SyntaxKind.ImplementsKeyword:
return grammarErrorOnFirstToken(heritageClause, Diagnostics.Interface_declaration_cannot_have_implements_clause);
}
// Grammar checking heritageClause inside class declaration

View file

@ -175,15 +175,15 @@
"category": "Error",
"code": 1057
},
"Operand for 'await' does not have a valid callable 'then' member.": {
"Type used as operand to 'await' or the return type of an async function must not contain a callable 'then' member if it is not a promise.": {
"category": "Error",
"code": 1058
},
"Return expression in async function does not have a valid callable 'then' member.": {
"A promise must have a 'then' method.": {
"category": "Error",
"code": 1059
},
"Expression body for async arrow function does not have a valid callable 'then' member.": {
"The first parameter of the 'then' method of a promise must be a callback.": {
"category": "Error",
"code": 1060
},
@ -191,7 +191,7 @@
"category": "Error",
"code": 1061
},
"{0} is referenced directly or indirectly in the fulfillment callback of its own 'then' method.": {
"Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method.": {
"category": "Error",
"code": 1062
},
@ -511,11 +511,11 @@
"category": "Error",
"code": 1171
},
"'extends' clause already seen.": {
"'{0}' clause already seen.": {
"category": "Error",
"code": 1172
},
"'extends' clause must precede 'implements' clause.": {
"'{0}' clause must precede '{1}' clause.": {
"category": "Error",
"code": 1173
},
@ -523,7 +523,7 @@
"category": "Error",
"code": 1174
},
"'implements' clause already seen.": {
"Classes and interfaces can only promise a single type.": {
"category": "Error",
"code": 1175
},
@ -1323,6 +1323,10 @@
"category": "Error",
"code": 2420
},
"Class or interface '{0}' incorrectly promises type '{1}'. A compatible 'then()' signature could not be found.": {
"category": "Error",
"code": 2421
},
"A class may only implement another class or interface.": {
"category": "Error",
"code": 2422
@ -1351,6 +1355,10 @@
"category": "Error",
"code": 2428
},
"Class or interface promises type '{0}' which is not compatible with the type '{1}' used by the fulfillment callbacks of its 'then()' members.": {
"category": "Error",
"code": 2429
},
"Interface '{0}' incorrectly extends interface '{1}'.": {
"category": "Error",
"code": 2430
@ -1427,6 +1435,10 @@
"category": "Error",
"code": 2448
},
"Any declarations of '{0}' that promise a type must promise the same type.": {
"category": "Error",
"code": 2449
},
"Cannot redeclare block-scoped variable '{0}'.": {
"category": "Error",
"code": 2451
@ -1627,6 +1639,10 @@
"category": "Error",
"code": 2503
},
"A class or interface can only promise an identifier/qualified-name with optional type arguments.": {
"category": "Error",
"code": 2504
},
"A generator cannot have a 'void' type annotation.": {
"category": "Error",
"code": 2505

View file

@ -1333,7 +1333,7 @@ namespace ts {
// Clauses
export function createHeritageClause(token: SyntaxKind, types: ExpressionWithTypeArguments[], location?: TextRange) {
export function createHeritageClause(token: SyntaxKind.ExtendsKeyword | SyntaxKind.ImplementsKeyword, types: ExpressionWithTypeArguments[], location?: TextRange) {
const node = <HeritageClause>createNode(SyntaxKind.HeritageClause, location);
node.token = token;
node.types = createNodeArray(types);
@ -1347,6 +1347,19 @@ namespace ts {
return node;
}
export function createPromisesClause(type: TypeNode, location?: TextRange) {
const node = <PromisesClause>createNode(SyntaxKind.PromisesClause, location);
node.type = type;
return node;
}
export function updatePromisesClause(node: PromisesClause, type: TypeNode) {
if (node.type !== type) {
return updateNode(createPromisesClause(type, node), node);
}
return node;
}
export function createCaseClause(expression: Expression, statements: Statement[], location?: TextRange) {
const node = <CaseClause>createNode(SyntaxKind.CaseClause, location);
node.expression = parenthesizeExpressionForList(expression);

View file

@ -284,13 +284,15 @@ namespace ts {
visitNode(cbNode, (<ClassLikeDeclaration>node).name) ||
visitNodes(cbNodes, (<ClassLikeDeclaration>node).typeParameters) ||
visitNodes(cbNodes, (<ClassLikeDeclaration>node).heritageClauses) ||
visitNode(cbNode, (<ClassLikeDeclaration>node).promisesClause) ||
visitNodes(cbNodes, (<ClassLikeDeclaration>node).members);
case SyntaxKind.InterfaceDeclaration:
return visitNodes(cbNodes, node.decorators) ||
visitNodes(cbNodes, node.modifiers) ||
visitNode(cbNode, (<InterfaceDeclaration>node).name) ||
visitNodes(cbNodes, (<InterfaceDeclaration>node).typeParameters) ||
visitNodes(cbNodes, (<ClassDeclaration>node).heritageClauses) ||
visitNodes(cbNodes, (<InterfaceDeclaration>node).heritageClauses) ||
visitNode(cbNode, (<InterfaceDeclaration>node).promisesClause) ||
visitNodes(cbNodes, (<InterfaceDeclaration>node).members);
case SyntaxKind.TypeAliasDeclaration:
return visitNodes(cbNodes, node.decorators) ||
@ -353,6 +355,8 @@ namespace ts {
return visitNode(cbNode, (<ComputedPropertyName>node).expression);
case SyntaxKind.HeritageClause:
return visitNodes(cbNodes, (<HeritageClause>node).types);
case SyntaxKind.PromisesClause:
return visitNode(cbNode, (<PromisesClause>node).type);
case SyntaxKind.ExpressionWithTypeArguments:
return visitNode(cbNode, (<ExpressionWithTypeArguments>node).expression) ||
visitNodes(cbNodes, (<ExpressionWithTypeArguments>node).typeArguments);
@ -5371,6 +5375,7 @@ namespace ts {
node.name = parseNameOfClassDeclarationOrExpression();
node.typeParameters = parseTypeParameters();
node.heritageClauses = parseHeritageClauses();
node.promisesClause = parsePromisesClause();
if (parseExpected(SyntaxKind.OpenBraceToken)) {
// ClassTail[Yield,Await] : (Modified) See 14.5
@ -5412,9 +5417,10 @@ namespace ts {
}
function parseHeritageClause() {
if (token() === SyntaxKind.ExtendsKeyword || token() === SyntaxKind.ImplementsKeyword) {
const keyword = token();
if (keyword === SyntaxKind.ExtendsKeyword || keyword === SyntaxKind.ImplementsKeyword) {
const node = <HeritageClause>createNode(SyntaxKind.HeritageClause);
node.token = token();
node.token = keyword;
nextToken();
node.types = parseDelimitedList(ParsingContext.HeritageClauseElement, parseExpressionWithTypeArguments);
return finishNode(node);
@ -5434,7 +5440,22 @@ namespace ts {
}
function isHeritageClause(): boolean {
return token() === SyntaxKind.ExtendsKeyword || token() === SyntaxKind.ImplementsKeyword;
switch (token()) {
case SyntaxKind.ExtendsKeyword:
case SyntaxKind.ImplementsKeyword:
return true;
}
return false;
}
function parsePromisesClause(): PromisesClause {
if (token() === SyntaxKind.PromisesKeyword) {
const node = <PromisesClause>createNode(SyntaxKind.PromisesClause);
nextToken();
node.type = parseType();
return finishNode(node);
}
return undefined;
}
function parseClassMembers() {
@ -5449,6 +5470,7 @@ namespace ts {
node.name = parseIdentifier();
node.typeParameters = parseTypeParameters();
node.heritageClauses = parseHeritageClauses();
node.promisesClause = parsePromisesClause();
node.members = parseObjectTypeMembers();
return addJSDocComment(finishNode(node));
}

View file

@ -101,6 +101,7 @@ namespace ts {
"package": SyntaxKind.PackageKeyword,
"private": SyntaxKind.PrivateKeyword,
"protected": SyntaxKind.ProtectedKeyword,
"promises": SyntaxKind.PromisesKeyword,
"public": SyntaxKind.PublicKeyword,
"readonly": SyntaxKind.ReadonlyKeyword,
"require": SyntaxKind.RequireKeyword,

View file

@ -172,6 +172,7 @@ namespace ts {
ModuleKeyword,
NamespaceKeyword,
NeverKeyword,
PromisesKeyword,
ReadonlyKeyword,
RequireKeyword,
NumberKeyword,
@ -317,6 +318,7 @@ namespace ts {
CaseClause,
DefaultClause,
HeritageClause,
PromisesClause,
CatchClause,
// Property assignments
@ -1693,6 +1695,7 @@ namespace ts {
name?: Identifier;
typeParameters?: NodeArray<TypeParameterDeclaration>;
heritageClauses?: NodeArray<HeritageClause>;
promisesClause?: PromisesClause;
members: NodeArray<ClassElement>;
}
@ -1721,15 +1724,21 @@ namespace ts {
name: Identifier;
typeParameters?: NodeArray<TypeParameterDeclaration>;
heritageClauses?: NodeArray<HeritageClause>;
promisesClause?: PromisesClause;
members: NodeArray<TypeElement>;
}
export interface HeritageClause extends Node {
kind: SyntaxKind.HeritageClause;
token: SyntaxKind;
token: SyntaxKind.ExtendsKeyword | SyntaxKind.ImplementsKeyword;
types?: NodeArray<ExpressionWithTypeArguments>;
}
export interface PromisesClause extends Declaration {
kind: SyntaxKind.PromisesClause;
type: TypeNode;
}
export interface TypeAliasDeclaration extends DeclarationStatement {
kind: SyntaxKind.TypeAliasDeclaration;
name: Identifier;
@ -2889,6 +2898,7 @@ namespace ts {
declaredConstructSignatures: Signature[]; // Declared construct signatures
declaredStringIndexInfo: IndexInfo; // Declared string indexing info
declaredNumberIndexInfo: IndexInfo; // Declared numeric indexing info
declaredPromisesClause?: Symbol; // Declared promises clause
}
/**
@ -2959,6 +2969,7 @@ namespace ts {
constructSignatures: Signature[]; // Construct signatures of type
stringIndexInfo?: IndexInfo; // String indexing info
numberIndexInfo?: IndexInfo; // Numeric indexing info
promisesClause?: Symbol; // Promises clause
}
/* @internal */
@ -2976,6 +2987,14 @@ namespace ts {
iteratorElementType?: Type;
}
/* @internal */
export interface PromiseOrAwaitableType extends ObjectType, UnionType {
promiseTypeOfPromiseConstructor?: Type;
promisedTypeOfPromise?: Type;
awaitedTypeOfType?: Type;
promisesClauseConstraintType?: Type;
}
export interface TypeVariable extends Type {
/* @internal */
resolvedApparentType: Type;

View file

@ -1156,6 +1156,10 @@ namespace ts {
return updateHeritageClause(<HeritageClause>node,
visitNodes((<HeritageClause>node).types, visitor, isExpressionWithTypeArguments));
case SyntaxKind.PromisesClause:
return updatePromisesClause(<PromisesClause>node,
visitNode((<PromisesClause>node).type, visitor, isTypeNode));
case SyntaxKind.CatchClause:
return updateCatchClause(<CatchClause>node,
visitNode((<CatchClause>node).variableDeclaration, visitor, isVariableDeclaration),

View file

@ -8,8 +8,8 @@ tests/cases/conformance/async/es5/functionDeclarations/asyncFunctionDeclaration1
Types of property 'then' are incompatible.
Type '() => void' is not assignable to type '{ (onfulfilled?: (value: any) => any, onrejected?: (reason: any) => any): PromiseLike<any>; <TResult>(onfulfilled: (value: any) => any, onrejected: (reason: any) => TResult | PromiseLike<TResult>): PromiseLike<any>; <TResult>(onfulfilled: (value: any) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>): PromiseLike<TResult>; <TResult1, TResult2>(onfulfilled: (value: any) => TResult1 | PromiseLike<TResult1>, onrejected: (reason: any) => TResult2 | PromiseLike<TResult2>): PromiseLike<TResult1 | TResult2>; }'.
Type 'void' is not assignable to type 'PromiseLike<any>'.
tests/cases/conformance/async/es5/functionDeclarations/asyncFunctionDeclaration15_es5.ts(17,16): error TS1059: Return expression in async function does not have a valid callable 'then' member.
tests/cases/conformance/async/es5/functionDeclarations/asyncFunctionDeclaration15_es5.ts(23,25): error TS1058: Operand for 'await' does not have a valid callable 'then' member.
tests/cases/conformance/async/es5/functionDeclarations/asyncFunctionDeclaration15_es5.ts(17,16): error TS1058: Type used as operand to 'await' or the return type of an async function must not contain a callable 'then' member if it is not a promise.
tests/cases/conformance/async/es5/functionDeclarations/asyncFunctionDeclaration15_es5.ts(23,25): error TS1058: Type used as operand to 'await' or the return type of an async function must not contain a callable 'then' member if it is not a promise.
==== tests/cases/conformance/async/es5/functionDeclarations/asyncFunctionDeclaration15_es5.ts (8 errors) ====
@ -47,7 +47,7 @@ tests/cases/conformance/async/es5/functionDeclarations/asyncFunctionDeclaration1
async function fn12() { return obj; } // valid: Promise<{ then: string; }>
async function fn13() { return thenable; } // error
~~~~
!!! error TS1059: Return expression in async function does not have a valid callable 'then' member.
!!! error TS1058: Type used as operand to 'await' or the return type of an async function must not contain a callable 'then' member if it is not a promise.
async function fn14() { await 1; } // valid: Promise<void>
async function fn15() { await null; } // valid: Promise<void>
async function fn16() { await undefined; } // valid: Promise<void>
@ -55,5 +55,5 @@ tests/cases/conformance/async/es5/functionDeclarations/asyncFunctionDeclaration1
async function fn18() { await obj; } // valid: Promise<void>
async function fn19() { await thenable; } // error
~~~~~~~~~~~~~~
!!! error TS1058: Operand for 'await' does not have a valid callable 'then' member.
!!! error TS1058: Type used as operand to 'await' or the return type of an async function must not contain a callable 'then' member if it is not a promise.

View file

@ -3,8 +3,8 @@ tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration1
tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration15_es6.ts(8,23): error TS1064: The return type of an async function or method must be the global Promise<T> type.
tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration15_es6.ts(9,23): error TS1064: The return type of an async function or method must be the global Promise<T> type.
tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration15_es6.ts(10,23): error TS1064: The return type of an async function or method must be the global Promise<T> type.
tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration15_es6.ts(17,16): error TS1059: Return expression in async function does not have a valid callable 'then' member.
tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration15_es6.ts(23,25): error TS1058: Operand for 'await' does not have a valid callable 'then' member.
tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration15_es6.ts(17,16): error TS1058: Type used as operand to 'await' or the return type of an async function must not contain a callable 'then' member if it is not a promise.
tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration15_es6.ts(23,25): error TS1058: Type used as operand to 'await' or the return type of an async function must not contain a callable 'then' member if it is not a promise.
==== tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration15_es6.ts (7 errors) ====
@ -36,7 +36,7 @@ tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration1
async function fn12() { return obj; } // valid: Promise<{ then: string; }>
async function fn13() { return thenable; } // error
~~~~
!!! error TS1059: Return expression in async function does not have a valid callable 'then' member.
!!! error TS1058: Type used as operand to 'await' or the return type of an async function must not contain a callable 'then' member if it is not a promise.
async function fn14() { await 1; } // valid: Promise<void>
async function fn15() { await null; } // valid: Promise<void>
async function fn16() { await undefined; } // valid: Promise<void>
@ -44,5 +44,5 @@ tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration1
async function fn18() { await obj; } // valid: Promise<void>
async function fn19() { await thenable; } // error
~~~~~~~~~~~~~~
!!! error TS1058: Operand for 'await' does not have a valid callable 'then' member.
!!! error TS1058: Type used as operand to 'await' or the return type of an async function must not contain a callable 'then' member if it is not a promise.

View file

@ -1,4 +1,4 @@
tests/cases/compiler/implementsClauseAlreadySeen.ts(4,22): error TS1175: 'implements' clause already seen.
tests/cases/compiler/implementsClauseAlreadySeen.ts(4,22): error TS1172: 'implements' clause already seen.
==== tests/cases/compiler/implementsClauseAlreadySeen.ts (1 errors) ====
@ -7,6 +7,6 @@ tests/cases/compiler/implementsClauseAlreadySeen.ts(4,22): error TS1175: 'implem
}
class D implements C implements C {
~~~~~~~~~~
!!! error TS1175: 'implements' clause already seen.
!!! error TS1172: 'implements' clause already seen.
baz() { }
}

View file

@ -1,5 +1,5 @@
tests/cases/conformance/parser/ecmascript5/ClassDeclarations/parserClassDeclaration2.ts(1,20): error TS2304: Cannot find name 'A'.
tests/cases/conformance/parser/ecmascript5/ClassDeclarations/parserClassDeclaration2.ts(1,22): error TS1175: 'implements' clause already seen.
tests/cases/conformance/parser/ecmascript5/ClassDeclarations/parserClassDeclaration2.ts(1,22): error TS1172: 'implements' clause already seen.
==== tests/cases/conformance/parser/ecmascript5/ClassDeclarations/parserClassDeclaration2.ts (2 errors) ====
@ -7,5 +7,5 @@ tests/cases/conformance/parser/ecmascript5/ClassDeclarations/parserClassDeclarat
~
!!! error TS2304: Cannot find name 'A'.
~~~~~~~~~~
!!! error TS1175: 'implements' clause already seen.
!!! error TS1172: 'implements' clause already seen.
}

View file

@ -1,6 +1,6 @@
tests/cases/conformance/parser/ecmascript5/ClassDeclarations/parserClassDeclaration5.ts(1,17): error TS2304: Cannot find name 'A'.
tests/cases/conformance/parser/ecmascript5/ClassDeclarations/parserClassDeclaration5.ts(1,30): error TS2304: Cannot find name 'B'.
tests/cases/conformance/parser/ecmascript5/ClassDeclarations/parserClassDeclaration5.ts(1,32): error TS1175: 'implements' clause already seen.
tests/cases/conformance/parser/ecmascript5/ClassDeclarations/parserClassDeclaration5.ts(1,32): error TS1172: 'implements' clause already seen.
==== tests/cases/conformance/parser/ecmascript5/ClassDeclarations/parserClassDeclaration5.ts (3 errors) ====
@ -10,5 +10,5 @@ tests/cases/conformance/parser/ecmascript5/ClassDeclarations/parserClassDeclarat
~
!!! error TS2304: Cannot find name 'B'.
~~~~~~~~~~
!!! error TS1175: 'implements' clause already seen.
!!! error TS1172: 'implements' clause already seen.
}