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 29 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
82 changes: 79 additions & 3 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15458,9 +15458,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)) {
const { declaration } = signature;
danvk marked this conversation as resolved.
Show resolved Hide resolved
signature.resolvedTypePredicate = noTypePredicate; // avoid infinite loop
signature.resolvedTypePredicate = getTypePredicateFromBody(declaration) || noTypePredicate;
}
else {
signature.resolvedTypePredicate = noTypePredicate;
}
}
Debug.assert(!!signature.resolvedTypePredicate);
}
Expand Down Expand Up @@ -37389,6 +37399,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:
return undefined;
}
const functionFlags = getFunctionFlags(func);
if (functionFlags !== FunctionFlags.Normal || func.parameters.length === 0) return undefined;
danvk marked this conversation as resolved.
Show resolved Hide resolved

// 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 => {
if (singleReturn || !returnStatement.expression) return true;
singleReturn = returnStatement.expression;
});
if (bailedEarly || !singleReturn || functionHasImplicitReturn(func)) return undefined;
}
return checkIfExpressionRefinesAnyParameter(func, singleReturn);
}

danvk marked this conversation as resolved.
Show resolved Hide resolved
function checkIfExpressionRefinesAnyParameter(func: FunctionLikeDeclaration, expr: Expression): TypePredicate | undefined {
expr = skipParentheses(expr, /*excludeJSDocTypeAssertions*/ true);
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)) {
// 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);
}
});
danvk marked this conversation as resolved.
Show resolved Hide resolved
}

function checkIfExpressionRefinesParameter(func: FunctionLikeDeclaration, expr: Expression, param: ParameterDeclaration, initType: Type): Type | undefined {
const antecedent = (expr as Expression & { flowNode?: FlowNode; }).flowNode ||
danvk marked this conversation as resolved.
Show resolved Hide resolved
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.
danvk marked this conversation as resolved.
Show resolved Hide resolved
// 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,
danvk marked this conversation as resolved.
Show resolved Hide resolved
Expand Down
41 changes: 41 additions & 0 deletions tests/baselines/reference/circularConstructorWithReturn.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
//// [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.applyModelsAndClientExtensions = exports.getPrismaClient = void 0;
function getPrismaClient(options) {
var PrismaClient = /** @class */ (function () {
function PrismaClient(options) {
return (this.self = applyModelsAndClientExtensions(this));
}
return PrismaClient;
}());
return PrismaClient;
}
exports.getPrismaClient = getPrismaClient;
function applyModelsAndClientExtensions(client) {
return client;
}
exports.applyModelsAndClientExtensions = applyModelsAndClientExtensions;
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