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

Experimental variant on #57465 with two optimizations #57660

Closed
wants to merge 29 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 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
8edd119
implement the never bailout
danvk Mar 5, 2024
9479ed8
attempt to implement === fast path
danvk Mar 5, 2024
f833865
add === test and baselines
danvk Mar 5, 2024
51a8970
make at most two calls to getFTOR for big unions
danvk Mar 6, 2024
348509a
comments, format
danvk Mar 6, 2024
fd8db07
getTypeOfExpression -> checkExpressionCached
danvk Mar 6, 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
129 changes: 126 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;
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,119 @@ 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;

// 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);
}

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);
}
});
}

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,
};

if (isBinaryExpression(expr)) {
// fast path for x => x === y and other similar patterns
// This can only be a type predicate if y is a unit type (e.g. null) but it can be quite expensive to determine that via the usual code path.
const { operatorToken } = expr;
const operator = operatorToken.kind;
let target;
switch (operator) {
case SyntaxKind.EqualsEqualsToken:
case SyntaxKind.ExclamationEqualsToken:
case SyntaxKind.EqualsEqualsEqualsToken:
case SyntaxKind.ExclamationEqualsEqualsToken:
const { left, right } = expr;
if (isMatchingReference(param.name, left)) {
target = right;
}
else if (isMatchingReference(param.name, right)) {
target = left;
}
}
if (target) {
const targetType = checkExpressionCached(target);
if (!isUnitType(targetType)) {
return undefined;
}
}
}

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,
};

if ((trueType.flags & TypeFlags.Union) && (trueType as UnionType).types.length >= 20) {
// For large unions, try the false check on just the first ten.
// If this is non-never then we can skip checking the remaining constituents.
const unionType = trueType as UnionType;
const head: UnionType = { ...unionType, types: unionType.types.slice(0, 10) };
const falseSubTypeHead = getFlowTypeOfReference(param.name, head, head, func, falseCondition);
if (!(falseSubTypeHead.flags & TypeFlags.Never)) {
return undefined;
}
const rest: UnionType = { ...unionType, types: unionType.types.slice(10) };
const falseSubTypeRest = getFlowTypeOfReference(param.name, rest, rest, func, falseCondition);
if (!(falseSubTypeRest.flags & TypeFlags.Never)) {
return undefined;
}
return trueType;
}
else {
const falseSubtype = getFlowTypeOfReference(param.name, trueType, trueType, func, falseCondition);
const isNever = !!(falseSubtype.flags & TypeFlags.Never);
return isNever ? trueType : undefined;
}
}

/**
* TypeScript Specification 1.0 (6.3) - July 2014
* An explicitly typed function whose return type isn't the Void type,
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