Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Infer type predicates from function bodies using control flow analysis #57465

Merged
merged 43 commits into from
Mar 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
43 commits
Select commit Hold shift + click to select a range
0c24ccc
Infer type predicates from function bodies
danvk Feb 20, 2024
e2684f1
Run formatter
danvk Feb 21, 2024
101df93
Add secondary subtype check and tests
danvk Feb 21, 2024
d0e385e
add union type test to baselines
danvk Feb 21, 2024
a72b1f1
add prisma circularity test with failing baseline
danvk Feb 23, 2024
ef2d465
Various fixes for circularity issue
danvk Feb 23, 2024
9336052
circularity test is fixed
danvk Feb 23, 2024
41f624d
revert back to CheckMode.TypeOnly
danvk Feb 23, 2024
52df115
Add test case for a predicate that throws
danvk Feb 23, 2024
3ab6fae
Drop isTriviallyNonBoolean, switch to simpler test, check for assertions
danvk Feb 26, 2024
9591231
Use unescapeLeadingUnderscores
danvk Feb 29, 2024
9a8c0a1
tests are fixed
danvk Feb 29, 2024
a4ff6b4
Always bind flow nodes to return statements + other fixes
ahejlsberg Mar 1, 2024
869422f
Accept new baselines
ahejlsberg Mar 1, 2024
adbdc7d
Merge branch 'suggested-changes-57465' into infer-type-predicate-16069
danvk Mar 1, 2024
0dec9c6
simplify
danvk Mar 1, 2024
703253a
Delay expensive functionHasImplicitReturn call
ahejlsberg Mar 2, 2024
c7f1c3d
Avoid creating closures
ahejlsberg Mar 2, 2024
25743a3
Add fallback isTypeAssignableTo check to test for equivalence
danvk Mar 2, 2024
4e79d76
try caching the antecedent
danvk Mar 3, 2024
a5725d2
revert fallback assignability check
danvk Mar 3, 2024
3323573
Revert "try caching the antecedent"
danvk Mar 4, 2024
76a5abd
Merge commit 'c7f1c3d309' into infer-type-predicate-16069
danvk Mar 4, 2024
5ec6f1f
accept baselines
danvk Mar 13, 2024
3491c78
ignore rest parameters & update baseline
danvk Mar 13, 2024
c4ee1f0
switch to getParameterCount
danvk Mar 13, 2024
4e934fa
Revert "switch to getParameterCount"
danvk Mar 14, 2024
37951ca
Revert "ignore rest parameters & update baseline"
danvk Mar 14, 2024
cabed97
Revert "accept baselines"
danvk Mar 14, 2024
6a88111
try setting @declaration: true
danvk Mar 14, 2024
151d026
accept baselines
danvk Mar 14, 2024
0b6a24a
Merge branch 'main' into test-fix-expt-16069
danvk Mar 14, 2024
0f31362
accept baseline
danvk Mar 14, 2024
2354072
Add rest parameter test and accept baselines
danvk Mar 13, 2024
f63105c
ignore rest parameters & update baseline
danvk Mar 13, 2024
eea3994
switch to getParameterCount
danvk Mar 13, 2024
e474bfc
accept baseline
danvk Mar 14, 2024
a6a734c
emit inferred type predicates in createReturnTypeOfSignatureDeclaration
danvk Mar 14, 2024
f5a9404
accept baselines
danvk Mar 14, 2024
784e2a3
correct isDate / flakyIsDate pair
danvk Mar 14, 2024
33826df
handle asserts predicates as well
danvk Mar 14, 2024
f002b28
Pass flags for type predicate emit
danvk Mar 14, 2024
50803a0
Factor out nodeBuilder.typePredicateToTypePredicateNode
danvk Mar 15, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/compiler/binder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1094,7 +1094,7 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void {
inAssignmentPattern = saveInAssignmentPattern;
return;
}
if (node.kind >= SyntaxKind.FirstStatement && node.kind <= SyntaxKind.LastStatement && !options.allowUnreachableCode) {
if (node.kind >= SyntaxKind.FirstStatement && node.kind <= SyntaxKind.LastStatement && (!options.allowUnreachableCode || node.kind === SyntaxKind.ReturnStatement)) {
(node as HasFlowNode).flowNode = currentFlow;
}
switch (node.kind) {
Expand Down
115 changes: 99 additions & 16 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6456,6 +6456,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
function createNodeBuilder() {
return {
typeToTypeNode: (type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags, tracker?: SymbolTracker) => withContext(enclosingDeclaration, flags, tracker, context => typeToTypeNodeHelper(type, context)),
typePredicateToTypePredicateNode: (typePredicate: TypePredicate, enclosingDeclaration?: Node, flags?: NodeBuilderFlags, tracker?: SymbolTracker) => withContext(enclosingDeclaration, flags, tracker, context => typePredicateToTypePredicateNodeHelper(typePredicate, context)),
indexInfoToIndexSignatureDeclaration: (indexInfo: IndexInfo, enclosingDeclaration?: Node, flags?: NodeBuilderFlags, tracker?: SymbolTracker) => withContext(enclosingDeclaration, flags, tracker, context => indexInfoToIndexSignatureDeclarationHelper(indexInfo, context, /*typeNode*/ undefined)),
signatureToSignatureDeclaration: (signature: Signature, kind: SignatureDeclaration["kind"], enclosingDeclaration?: Node, flags?: NodeBuilderFlags, tracker?: SymbolTracker) => withContext(enclosingDeclaration, flags, tracker, context => signatureToSignatureDeclarationHelper(signature, kind, context)),
symbolToEntityName: (symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags, tracker?: SymbolTracker) => withContext(enclosingDeclaration, flags, tracker, context => symbolToName(symbol, context, meaning, /*expectsIdentifier*/ false)),
Expand Down Expand Up @@ -7704,14 +7705,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
let returnTypeNode: TypeNode | undefined;
const typePredicate = getTypePredicateOfSignature(signature);
if (typePredicate) {
const assertsModifier = typePredicate.kind === TypePredicateKind.AssertsThis || typePredicate.kind === TypePredicateKind.AssertsIdentifier ?
factory.createToken(SyntaxKind.AssertsKeyword) :
undefined;
const parameterName = typePredicate.kind === TypePredicateKind.Identifier || typePredicate.kind === TypePredicateKind.AssertsIdentifier ?
setEmitFlags(factory.createIdentifier(typePredicate.parameterName), EmitFlags.NoAsciiEscaping) :
factory.createThisTypeNode();
const typeNode = typePredicate.type && typeToTypeNodeHelper(typePredicate.type, context);
returnTypeNode = factory.createTypePredicateNode(assertsModifier, parameterName, typeNode);
returnTypeNode = typePredicateToTypePredicateNodeHelper(typePredicate, context);
}
else {
const returnType = getReturnTypeOfSignature(signature);
Expand Down Expand Up @@ -7790,6 +7784,17 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
return typeParameterToDeclarationWithConstraint(type, context, constraintNode);
}

function typePredicateToTypePredicateNodeHelper(typePredicate: TypePredicate, context: NodeBuilderContext): TypePredicateNode {
const assertsModifier = typePredicate.kind === TypePredicateKind.AssertsThis || typePredicate.kind === TypePredicateKind.AssertsIdentifier ?
factory.createToken(SyntaxKind.AssertsKeyword) :
undefined;
const parameterName = typePredicate.kind === TypePredicateKind.Identifier || typePredicate.kind === TypePredicateKind.AssertsIdentifier ?
setEmitFlags(factory.createIdentifier(typePredicate.parameterName), EmitFlags.NoAsciiEscaping) :
factory.createThisTypeNode();
const typeNode = typePredicate.type && typeToTypeNodeHelper(typePredicate.type, context);
return factory.createTypePredicateNode(assertsModifier, parameterName, typeNode);
}

function getEffectiveParameterDeclaration(parameterSymbol: Symbol): ParameterDeclaration | JSDocParameterTag | undefined {
const parameterDeclaration: ParameterDeclaration | JSDocParameterTag | undefined = getDeclarationOfKind<ParameterDeclaration>(parameterSymbol, SyntaxKind.Parameter);
if (parameterDeclaration) {
Expand Down Expand Up @@ -10309,11 +10314,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
return writer ? typePredicateToStringWorker(writer).getText() : usingSingleLineStringWriter(typePredicateToStringWorker);

function typePredicateToStringWorker(writer: EmitTextWriter) {
const predicate = factory.createTypePredicateNode(
typePredicate.kind === TypePredicateKind.AssertsThis || typePredicate.kind === TypePredicateKind.AssertsIdentifier ? factory.createToken(SyntaxKind.AssertsKeyword) : undefined,
typePredicate.kind === TypePredicateKind.Identifier || typePredicate.kind === TypePredicateKind.AssertsIdentifier ? factory.createIdentifier(typePredicate.parameterName) : factory.createThisTypeNode(),
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Slight change here: previously this did not call setEmitFlags(factory.createIdentifier(typePredicate.parameterName), EmitFlags.NoAsciiEscaping) here but now it does via nodeBuilder.typePredicateToTypePredicateNode. I wasn't sure if this difference was intentional. Making these consistent doesn't break any tests, but I can model the difference if we want to keep it.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AFAIK NoAsciiEscaping doesn't do anything for things that aren't string literals, so I'm honestly not sure why it's here.

typePredicate.type && nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | NodeBuilderFlags.IgnoreErrors | NodeBuilderFlags.WriteTypeParametersInQualifiedName)!, // TODO: GH#18217
);
const nodeBuilderFlags = toNodeBuilderFlags(flags) | NodeBuilderFlags.IgnoreErrors | NodeBuilderFlags.WriteTypeParametersInQualifiedName;
const predicate = nodeBuilder.typePredicateToTypePredicateNode(typePredicate, enclosingDeclaration, nodeBuilderFlags)!; // TODO: GH#18217
const printer = createPrinterWithRemoveComments();
const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration);
printer.writeNode(EmitHint.Unspecified, predicate, /*sourceFile*/ sourceFile, writer);
Expand Down Expand Up @@ -15476,9 +15478,19 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
jsdocPredicate = getTypePredicateOfSignature(jsdocSignature);
}
}
signature.resolvedTypePredicate = type && isTypePredicateNode(type) ?
createTypePredicateFromTypePredicateNode(type, signature) :
jsdocPredicate || noTypePredicate;
if (type || jsdocPredicate) {
signature.resolvedTypePredicate = type && isTypePredicateNode(type) ?
createTypePredicateFromTypePredicateNode(type, signature) :
jsdocPredicate || noTypePredicate;
}
else if (signature.declaration && isFunctionLikeDeclaration(signature.declaration) && (!signature.resolvedReturnType || signature.resolvedReturnType.flags & TypeFlags.Boolean) && getParameterCount(signature) > 0) {
const { declaration } = signature;
signature.resolvedTypePredicate = noTypePredicate; // avoid infinite loop
signature.resolvedTypePredicate = getTypePredicateFromBody(declaration) || noTypePredicate;
}
else {
signature.resolvedTypePredicate = noTypePredicate;
}
}
Debug.assert(!!signature.resolvedTypePredicate);
}
Expand Down Expand Up @@ -37439,6 +37451,72 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
}
}

function getTypePredicateFromBody(func: FunctionLikeDeclaration): TypePredicate | undefined {
switch (func.kind) {
case SyntaxKind.Constructor:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
danvk marked this conversation as resolved.
Show resolved Hide resolved
return undefined;
}
const functionFlags = getFunctionFlags(func);
if (functionFlags !== FunctionFlags.Normal) return undefined;

// Only attempt to infer a type predicate if there's exactly one return.
let singleReturn: Expression | undefined;
if (func.body && func.body.kind !== SyntaxKind.Block) {
singleReturn = func.body; // arrow function
}
else {
const bailedEarly = forEachReturnStatement(func.body as Block, returnStatement => {
danvk marked this conversation as resolved.
Show resolved Hide resolved
if (singleReturn || !returnStatement.expression) return true;
singleReturn = returnStatement.expression;
});
if (bailedEarly || !singleReturn || functionHasImplicitReturn(func)) return undefined;
}
danvk marked this conversation as resolved.
Show resolved Hide resolved
return checkIfExpressionRefinesAnyParameter(func, singleReturn);
}

function checkIfExpressionRefinesAnyParameter(func: FunctionLikeDeclaration, expr: Expression): TypePredicate | undefined {
expr = skipParentheses(expr, /*excludeJSDocTypeAssertions*/ true);
danvk marked this conversation as resolved.
Show resolved Hide resolved
const returnType = checkExpressionCached(expr);
if (!(returnType.flags & TypeFlags.Boolean)) return undefined;

return forEach(func.parameters, (param, i) => {
const initType = getTypeOfSymbol(param.symbol);
if (!initType || initType.flags & TypeFlags.Boolean || !isIdentifier(param.name) || isSymbolAssigned(param.symbol) || isRestParameter(param)) {
// Refining "x: boolean" to "x is true" or "x is false" isn't useful.
return;
}
const trueType = checkIfExpressionRefinesParameter(func, expr, param, initType);
if (trueType) {
return createTypePredicate(TypePredicateKind.Identifier, unescapeLeadingUnderscores(param.name.escapedText), i, trueType);
}
});
}

function checkIfExpressionRefinesParameter(func: FunctionLikeDeclaration, expr: Expression, param: ParameterDeclaration, initType: Type): Type | undefined {
const antecedent = (expr as Expression & { flowNode?: FlowNode; }).flowNode ||
expr.parent.kind === SyntaxKind.ReturnStatement && (expr.parent as ReturnStatement).flowNode ||
{ flags: FlowFlags.Start };
const trueCondition: FlowCondition = {
flags: FlowFlags.TrueCondition,
node: expr,
antecedent,
};

const trueType = getFlowTypeOfReference(param.name, initType, initType, func, trueCondition);
if (trueType === initType) return undefined;

// "x is T" means that x is T if and only if it returns true. If it returns false then x is not T.
// This means that if the function is called with an argument of type trueType, there can't be anything left in the `else` branch. It must reduce to `never`.
const falseCondition: FlowCondition = {
...trueCondition,
flags: FlowFlags.FalseCondition,
};
const falseSubtype = getFlowTypeOfReference(param.name, trueType, trueType, func, falseCondition);
return falseSubtype.flags & TypeFlags.Never ? trueType : undefined;
}

/**
* TypeScript Specification 1.0 (6.3) - July 2014
* An explicitly typed function whose return type isn't the Void type,
Expand Down Expand Up @@ -48500,6 +48578,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
return factory.createToken(SyntaxKind.AnyKeyword) as KeywordTypeNode;
}
const signature = getSignatureFromDeclaration(signatureDeclaration);
const typePredicate = getTypePredicateOfSignature(signature);
if (typePredicate) {
// Inferred type predicates
return nodeBuilder.typePredicateToTypePredicateNode(typePredicate, enclosingDeclaration, flags | NodeBuilderFlags.MultilineObjectLiterals, tracker);
}
danvk marked this conversation as resolved.
Show resolved Hide resolved
return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | NodeBuilderFlags.MultilineObjectLiterals, tracker);
}

Expand Down
40 changes: 40 additions & 0 deletions tests/baselines/reference/circularConstructorWithReturn.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
//// [tests/cases/compiler/circularConstructorWithReturn.ts] ////

//// [circularConstructorWithReturn.ts]
// This should not be a circularity error. See
// https://github.com/microsoft/TypeScript/pull/57465#issuecomment-1960271216
export type Client = ReturnType<typeof getPrismaClient> extends new () => infer T ? T : never

export function getPrismaClient(options?: any) {
class PrismaClient {
self: Client;
constructor(options?: any) {
return (this.self = applyModelsAndClientExtensions(this));
}
}

return PrismaClient
}

export function applyModelsAndClientExtensions(client: Client) {
return client;
}


//// [circularConstructorWithReturn.js]
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getPrismaClient = getPrismaClient;
exports.applyModelsAndClientExtensions = applyModelsAndClientExtensions;
function getPrismaClient(options) {
var PrismaClient = /** @class */ (function () {
function PrismaClient(options) {
return (this.self = applyModelsAndClientExtensions(this));
}
return PrismaClient;
}());
return PrismaClient;
}
function applyModelsAndClientExtensions(client) {
return client;
}
48 changes: 48 additions & 0 deletions tests/baselines/reference/circularConstructorWithReturn.symbols
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
//// [tests/cases/compiler/circularConstructorWithReturn.ts] ////

=== circularConstructorWithReturn.ts ===
// This should not be a circularity error. See
// https://github.com/microsoft/TypeScript/pull/57465#issuecomment-1960271216
export type Client = ReturnType<typeof getPrismaClient> extends new () => infer T ? T : never
>Client : Symbol(Client, Decl(circularConstructorWithReturn.ts, 0, 0))
>ReturnType : Symbol(ReturnType, Decl(lib.es5.d.ts, --, --))
>getPrismaClient : Symbol(getPrismaClient, Decl(circularConstructorWithReturn.ts, 2, 93))
>T : Symbol(T, Decl(circularConstructorWithReturn.ts, 2, 79))
>T : Symbol(T, Decl(circularConstructorWithReturn.ts, 2, 79))

export function getPrismaClient(options?: any) {
>getPrismaClient : Symbol(getPrismaClient, Decl(circularConstructorWithReturn.ts, 2, 93))
>options : Symbol(options, Decl(circularConstructorWithReturn.ts, 4, 32))

class PrismaClient {
>PrismaClient : Symbol(PrismaClient, Decl(circularConstructorWithReturn.ts, 4, 48))

self: Client;
>self : Symbol(PrismaClient.self, Decl(circularConstructorWithReturn.ts, 5, 22))
>Client : Symbol(Client, Decl(circularConstructorWithReturn.ts, 0, 0))

constructor(options?: any) {
>options : Symbol(options, Decl(circularConstructorWithReturn.ts, 7, 16))

return (this.self = applyModelsAndClientExtensions(this));
>this.self : Symbol(PrismaClient.self, Decl(circularConstructorWithReturn.ts, 5, 22))
>this : Symbol(PrismaClient, Decl(circularConstructorWithReturn.ts, 4, 48))
>self : Symbol(PrismaClient.self, Decl(circularConstructorWithReturn.ts, 5, 22))
>applyModelsAndClientExtensions : Symbol(applyModelsAndClientExtensions, Decl(circularConstructorWithReturn.ts, 13, 1))
>this : Symbol(PrismaClient, Decl(circularConstructorWithReturn.ts, 4, 48))
}
}

return PrismaClient
>PrismaClient : Symbol(PrismaClient, Decl(circularConstructorWithReturn.ts, 4, 48))
}

export function applyModelsAndClientExtensions(client: Client) {
>applyModelsAndClientExtensions : Symbol(applyModelsAndClientExtensions, Decl(circularConstructorWithReturn.ts, 13, 1))
>client : Symbol(client, Decl(circularConstructorWithReturn.ts, 15, 47))
>Client : Symbol(Client, Decl(circularConstructorWithReturn.ts, 0, 0))

return client;
>client : Symbol(client, Decl(circularConstructorWithReturn.ts, 15, 47))
}

46 changes: 46 additions & 0 deletions tests/baselines/reference/circularConstructorWithReturn.types
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
//// [tests/cases/compiler/circularConstructorWithReturn.ts] ////

=== circularConstructorWithReturn.ts ===
// This should not be a circularity error. See
// https://github.com/microsoft/TypeScript/pull/57465#issuecomment-1960271216
export type Client = ReturnType<typeof getPrismaClient> extends new () => infer T ? T : never
>Client : PrismaClient
>getPrismaClient : (options?: any) => typeof PrismaClient

export function getPrismaClient(options?: any) {
>getPrismaClient : (options?: any) => typeof PrismaClient
>options : any

class PrismaClient {
>PrismaClient : PrismaClient

self: Client;
>self : PrismaClient

constructor(options?: any) {
>options : any

return (this.self = applyModelsAndClientExtensions(this));
>(this.self = applyModelsAndClientExtensions(this)) : PrismaClient
>this.self = applyModelsAndClientExtensions(this) : PrismaClient
>this.self : PrismaClient
>this : this
>self : PrismaClient
>applyModelsAndClientExtensions(this) : PrismaClient
>applyModelsAndClientExtensions : (client: PrismaClient) => PrismaClient
>this : this
}
}

return PrismaClient
>PrismaClient : typeof PrismaClient
}

export function applyModelsAndClientExtensions(client: Client) {
>applyModelsAndClientExtensions : (client: Client) => PrismaClient
>client : PrismaClient

return client;
>client : PrismaClient
}

Loading
Loading