Skip to content

feat: dependent contextual inference #51511

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

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
90 changes: 90 additions & 0 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28417,6 +28417,96 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
}

function checkObjectLiteral(node: ObjectLiteralExpression, checkMode?: CheckMode): Type {
const contextualType = getContextualType(node, /*contextFlags*/ undefined);
const isContextualTypeDependent =
Copy link
Contributor

Choose a reason for hiding this comment

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

Have you tried using couldContainTypeVariables? A comment for this function mentions this:

    // Return true if the given type could possibly reference a type parameter for which
    // we perform type inference (i.e. a type parameter of a generic function). We cache
    // results for union and intersection types for performance reasons.

It sounds like maybe you could reuse it

Copy link
Author

Choose a reason for hiding this comment

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

No because here we don't want to check if X has any type parameter, we want to check if X has a T type parameter. So using isContextualTypeDependent = couldContainTypeVariable(contextualType.immediateConstraint) would make it true for even T extends F<U> (U being some other type parameter) when it should have been false (as it's not T extends F<T>).

Copy link
Contributor

Choose a reason for hiding this comment

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

Right, but then perhaps that function could be extended with an optional argument, and this way you could limit the results to be based on the specific type param.

Copy link
Author

@devanshj devanshj Dec 5, 2022

Choose a reason for hiding this comment

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

I thought about that but I think that's quite non-trivial because it's implemented keeping in mind that we're checking against any type parameter... So for example caching is a big part of this, right now because we're checking for any type parameter the cache is implemented simply as a CouldContainTypeVariables flag, but if we want to cache for couldContainTypeVariables(type, typeParameters) or even couldContainTypeVariable(type, typeParameter) it would require a lot of ceremony.

Edit: I think you could implement couldContainTypeVariable(type, typeParameter)'s cache by simply memoizing via ids of the arguments, so it's not much of a ceremony, but I'm not convinced I want to change this already existing abstraction for my use-case. Might reconsider in future.

Copy link
Author

@devanshj devanshj Jan 4, 2023

Choose a reason for hiding this comment

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

Btw I realised the implementation is seriouly true to it's name "couldContainTypeVariable" and not "containsTypeVariable". This function doesn't definitively checks if the type as a type parameter, it just kinda bets, for example if it's an anonymous object type it just bets it has a type parameter and doesn't check furthur inside it. So if it returns true that means the type either has a type parameter or doesn't have a type parameter, but if it return false then it the type definately doesn't have a type parameter. So one can write bailouts like if (!couldContainTypeVariable(type)) return can gain some optimization and still not give bad results.

So there's no way I can use this function here as I want a definitive result. And extending it's implementation to give a definitive result might not be trivial and definitately more complex and slow than the ast check I'm doing here.

Fun fact: While working on #52088 I overlooked the "could" in it's name knowing perfectly what it means and relied on it which produced bad results, finally when I looked at the implementation I saw that it really takes the "could" in it's name seriously :P

node.parent.kind === SyntaxKind.CallExpression &&
contextualType &&
(contextualType.flags & TypeFlags.TypeParameter) &&
contextualType.immediateBaseConstraint &&
!!forEachChildRecursively(
(contextualType.symbol.declarations![0] as TypeParameterDeclaration).constraint!,
node => {
if (
node.kind === SyntaxKind.TypeReference &&
(node as TypeReferenceNode).typeName.kind === SyntaxKind.Identifier &&
((node as TypeReferenceNode).typeName as Identifier).escapedText ===
(contextualType.symbol.declarations![0] as TypeParameterDeclaration).name.escapedText
Comment on lines +28432 to +28433
Copy link
Author

Choose a reason for hiding this comment

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

This is probably a brittle way of writing this (unless I'm mistaken) but I don't know any other way that works. I would have used symbols but it seems that they aren't declared at this point.

) {
return true;
}
}
);

if (!isContextualTypeDependent) {
return checkObjectLiteralNonDependently(node, checkMode);
}

diagnostics.isStaging = true;
suggestionDiagnostics.isStaging = true;
let valueType = checkObjectLiteralNonDependently(node, checkMode);
let previousValueType = undefined as Type | undefined;
let passes = 0;
while(true) {
if (previousValueType && isTypeIdenticalTo(valueType, previousValueType)) {
commitDiagnostics();
return valueType;
}
if (passes >= 3) {
commitDiagnostics();
error(node, Diagnostics.Dependent_contextual_inference_requires_too_many_passes_and_possibly_infinite);
return valueType;
}

const newContextualType = cloneTypeParameter(contextualType as TypeParameter);
newContextualType.immediateBaseConstraint =
instantiateType(
contextualType.immediateBaseConstraint,
createTypeMapper([contextualType], [valueType])
);
if (newContextualType.immediateBaseConstraint!.flags & TypeFlags.StructuredType) {
newContextualType.immediateBaseConstraint = resolveStructuredTypeMembers(newContextualType.immediateBaseConstraint as StructuredType);
}

forEachChildRecursively(node, node => {
const nodeLinks = getNodeLinks(node);
nodeLinks.flags &= ~NodeCheckFlags.TypeChecked;
nodeLinks.flags &= ~NodeCheckFlags.ContextChecked;
nodeLinks.resolvedType = undefined;
nodeLinks.resolvedEnumType = undefined;
nodeLinks.resolvedSignature = undefined;
nodeLinks.resolvedSymbol = undefined;
nodeLinks.resolvedIndexInfo = undefined;
nodeLinks.contextFreeType = undefined;

if (node.symbol) {
const symbolLinks = getSymbolLinks(node.symbol);
symbolLinks.type = undefined;
symbolLinks.typeParameters = undefined;
}
});


node.contextualType = newContextualType;
revertDiagnostics();
previousValueType = valueType;
valueType = checkObjectLiteralNonDependently(node);
passes++;
}

function commitDiagnostics() {
diagnostics.commitStaged();
suggestionDiagnostics.commitStaged();
diagnostics.isStaging = false;
suggestionDiagnostics.isStaging = false;
}

function revertDiagnostics() {
diagnostics.revertStaged();
suggestionDiagnostics.revertStaged();
}
}

function checkObjectLiteralNonDependently(node: ObjectLiteralExpression, checkMode?: CheckMode): Type {
const inDestructuringPattern = isAssignmentTarget(node);
// Grammar checking
checkGrammarObjectLiteralExpression(node, inDestructuringPattern);
Expand Down
4 changes: 4 additions & 0 deletions src/compiler/diagnosticMessages.json
Original file line number Diff line number Diff line change
Expand Up @@ -7392,6 +7392,10 @@
"category": "Message",
"code": 95175
},
"Dependent contextual inference requires too many passes and possibly infinite": {
"category": "Error",
"code": 95176
},

"No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer.": {
"category": "Error",
Expand Down
4 changes: 4 additions & 0 deletions src/compiler/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9135,6 +9135,10 @@ export interface DiagnosticCollection {
// Otherwise, returns all the diagnostics (global and file associated) in this collection.
getDiagnostics(): Diagnostic[];
getDiagnostics(fileName: string): DiagnosticWithLocation[];

isStaging: boolean;
commitStaged(): void;
revertStaged(): void;
}

// SyntaxKind.SyntaxList
Expand Down
25 changes: 25 additions & 0 deletions src/compiler/utilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4397,11 +4397,19 @@ export function createDiagnosticCollection(): DiagnosticCollection {
const fileDiagnostics = new Map<string, SortedArray<DiagnosticWithLocation>>();
let hasReadNonFileDiagnostics = false;

let isStaging = false;
const stagingDiagnostics = [] as Diagnostic[];


return {
add,
lookup,
getGlobalDiagnostics,
getDiagnostics,
get isStaging() { return isStaging; },
set isStaging(v) { isStaging = v; },
commitStaged,
revertStaged,
};

function lookup(diagnostic: Diagnostic): Diagnostic | undefined {
Expand All @@ -4423,6 +4431,10 @@ export function createDiagnosticCollection(): DiagnosticCollection {
}

function add(diagnostic: Diagnostic): void {
if (isStaging) {
stagingDiagnostics.push(diagnostic);
return;
}
let diagnostics: SortedArray<Diagnostic> | undefined;
if (diagnostic.file) {
diagnostics = fileDiagnostics.get(diagnostic.file.fileName);
Expand Down Expand Up @@ -4464,6 +4476,19 @@ export function createDiagnosticCollection(): DiagnosticCollection {
fileDiags.unshift(...nonFileDiagnostics);
return fileDiags;
}

function commitStaged() {
const savedIsStaging = isStaging;
isStaging = false;
for (const diagnostic of stagingDiagnostics) {
add(diagnostic);
}
isStaging = savedIsStaging;
}

function revertStaged() {
stagingDiagnostics.length = 0;
}
}

const templateSubstitutionRegExp = /\$\{/g;
Expand Down
20 changes: 20 additions & 0 deletions tests/baselines/reference/dependentContextualInference1.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
//// [dependentContextualInference1.ts]
declare const f:
<T extends F<T>>(t: T) => T

type F<T> =
{ a: unknown
, b: (a: T["a" & keyof T]) => unknown
}

f({
a: "hello",
b: x => x.toUpperCase()
})


//// [dependentContextualInference1.js]
f({
a: "hello",
b: function (x) { return x.toUpperCase(); }
});
41 changes: 41 additions & 0 deletions tests/baselines/reference/dependentContextualInference1.symbols
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
=== tests/cases/compiler/dependentContextualInference1.ts ===
declare const f:
>f : Symbol(f, Decl(dependentContextualInference1.ts, 0, 13))

<T extends F<T>>(t: T) => T
>T : Symbol(T, Decl(dependentContextualInference1.ts, 1, 3))
>F : Symbol(F, Decl(dependentContextualInference1.ts, 1, 29))
>T : Symbol(T, Decl(dependentContextualInference1.ts, 1, 3))
>t : Symbol(t, Decl(dependentContextualInference1.ts, 1, 19))
>T : Symbol(T, Decl(dependentContextualInference1.ts, 1, 3))
>T : Symbol(T, Decl(dependentContextualInference1.ts, 1, 3))

type F<T> =
>F : Symbol(F, Decl(dependentContextualInference1.ts, 1, 29))
>T : Symbol(T, Decl(dependentContextualInference1.ts, 3, 7))

{ a: unknown
>a : Symbol(a, Decl(dependentContextualInference1.ts, 4, 3))

, b: (a: T["a" & keyof T]) => unknown
>b : Symbol(b, Decl(dependentContextualInference1.ts, 5, 3))
>a : Symbol(a, Decl(dependentContextualInference1.ts, 5, 8))
>T : Symbol(T, Decl(dependentContextualInference1.ts, 3, 7))
>T : Symbol(T, Decl(dependentContextualInference1.ts, 3, 7))
}

f({
>f : Symbol(f, Decl(dependentContextualInference1.ts, 0, 13))

a: "hello",
>a : Symbol(a, Decl(dependentContextualInference1.ts, 8, 3))

b: x => x.toUpperCase()
>b : Symbol(b, Decl(dependentContextualInference1.ts, 9, 13))
>x : Symbol(x, Decl(dependentContextualInference1.ts, 10, 4))
>x.toUpperCase : Symbol(String.toUpperCase, Decl(lib.es5.d.ts, --, --))
>x : Symbol(x, Decl(dependentContextualInference1.ts, 10, 4))
>toUpperCase : Symbol(String.toUpperCase, Decl(lib.es5.d.ts, --, --))

})

38 changes: 38 additions & 0 deletions tests/baselines/reference/dependentContextualInference1.types
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
=== tests/cases/compiler/dependentContextualInference1.ts ===
declare const f:
>f : <T extends F<T>>(t: T) => T

<T extends F<T>>(t: T) => T
>t : T

type F<T> =
>F : F<T>

{ a: unknown
>a : unknown

, b: (a: T["a" & keyof T]) => unknown
>b : (a: T["a" & keyof T]) => unknown
>a : T["a" & keyof T]
}

f({
>f({ a: "hello", b: x => x.toUpperCase()}) : { a: string; b: (x: string) => string; }
>f : <T extends F<T>>(t: T) => T
>{ a: "hello", b: x => x.toUpperCase()} : { a: string; b: (x: string) => string; }

a: "hello",
>a : string
>"hello" : "hello"

b: x => x.toUpperCase()
>b : (x: string) => string
>x => x.toUpperCase() : (x: string) => string
>x : string
>x.toUpperCase() : string
>x.toUpperCase : () => string
>x : string
>toUpperCase : () => string

})

26 changes: 26 additions & 0 deletions tests/baselines/reference/dependentContextualInference2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
//// [dependentContextualInference2.ts]
declare const m: <T extends M<T>>(m: T) => T
type M<Self> =
{ a?: number
, b?: number
, c?: number
, d?: number
, k?: Exclude<keyof Self, "k" | "t">
, t?: (k: Exclude<keyof Self, "k" | "t">) => void
}

m({
a: 1,
b: 2,
k: "a",
t: k => {}
})


//// [dependentContextualInference2.js]
m({
a: 1,
b: 2,
k: "a",
t: function (k) { }
});
56 changes: 56 additions & 0 deletions tests/baselines/reference/dependentContextualInference2.symbols
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
=== tests/cases/compiler/dependentContextualInference2.ts ===
declare const m: <T extends M<T>>(m: T) => T
>m : Symbol(m, Decl(dependentContextualInference2.ts, 0, 13))
>T : Symbol(T, Decl(dependentContextualInference2.ts, 0, 18))
>M : Symbol(M, Decl(dependentContextualInference2.ts, 0, 44))
>T : Symbol(T, Decl(dependentContextualInference2.ts, 0, 18))
>m : Symbol(m, Decl(dependentContextualInference2.ts, 0, 34))
>T : Symbol(T, Decl(dependentContextualInference2.ts, 0, 18))
>T : Symbol(T, Decl(dependentContextualInference2.ts, 0, 18))

type M<Self> =
>M : Symbol(M, Decl(dependentContextualInference2.ts, 0, 44))
>Self : Symbol(Self, Decl(dependentContextualInference2.ts, 1, 7))

{ a?: number
>a : Symbol(a, Decl(dependentContextualInference2.ts, 2, 3))

, b?: number
>b : Symbol(b, Decl(dependentContextualInference2.ts, 3, 3))

, c?: number
>c : Symbol(c, Decl(dependentContextualInference2.ts, 4, 3))

, d?: number
>d : Symbol(d, Decl(dependentContextualInference2.ts, 5, 3))

, k?: Exclude<keyof Self, "k" | "t">
>k : Symbol(k, Decl(dependentContextualInference2.ts, 6, 3))
>Exclude : Symbol(Exclude, Decl(lib.es5.d.ts, --, --))
>Self : Symbol(Self, Decl(dependentContextualInference2.ts, 1, 7))

, t?: (k: Exclude<keyof Self, "k" | "t">) => void
>t : Symbol(t, Decl(dependentContextualInference2.ts, 7, 3))
>k : Symbol(k, Decl(dependentContextualInference2.ts, 7, 9))
>Exclude : Symbol(Exclude, Decl(lib.es5.d.ts, --, --))
>Self : Symbol(Self, Decl(dependentContextualInference2.ts, 1, 7))
}

m({
>m : Symbol(m, Decl(dependentContextualInference2.ts, 0, 13))

a: 1,
>a : Symbol(a, Decl(dependentContextualInference2.ts, 10, 3))

b: 2,
>b : Symbol(b, Decl(dependentContextualInference2.ts, 11, 7))

k: "a",
>k : Symbol(k, Decl(dependentContextualInference2.ts, 12, 7))

t: k => {}
>t : Symbol(t, Decl(dependentContextualInference2.ts, 13, 9))
>k : Symbol(k, Decl(dependentContextualInference2.ts, 14, 4))

})

Loading