Skip to content

Add an early bail when structurally comparing similar types #42726

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
wants to merge 3 commits into from
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
68 changes: 68 additions & 0 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17773,6 +17773,13 @@ namespace ts {
return result;
}

function getInstanceOfAliasOrReferenceWithMarker(input: Type, typeArguments: readonly Type[]) {
const s = input.aliasSymbol && !(getObjectFlags(input) & ObjectFlags.Reference) ? getTypeAliasInstantiation(input.aliasSymbol, typeArguments) : createTypeReference((<TypeReference>input).target, typeArguments);
if (s.aliasSymbol) s.aliasTypeArgumentsContainsMarker = true;
if (getObjectFlags(s) & ObjectFlags.Reference) (<TypeReference>s).objectFlags |= ObjectFlags.MarkerType;
return s;
}

function structuredTypeRelatedToWorker(source: Type, target: Type, reportErrors: boolean, intersectionState: IntersectionState): Ternary {
if (intersectionState & IntersectionState.PropertyCheck) {
return propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, IntersectionState.None);
Expand Down Expand Up @@ -17861,6 +17868,67 @@ namespace ts {
}
}

// If a more _general_ version of the source and target are being compared, consider them related with assumptions
// eg, if { x: Q } and { x: Q, y: A } are being compared and we're about to look at { x: Q' } and { x: Q', y: A } where Q'
// is some specialization or subtype of Q
// This is difficult to detect generally, so we scan for prior comparisons of the same instantiated type, and match up matching
// type arguments into sets to create a canonicalization based on those matches
if (relation !== identityRelation && ((source.aliasSymbol && !source.aliasTypeArgumentsContainsMarker && length(source.aliasTypeArguments)) || (getObjectFlags(source) & ObjectFlags.Reference && !!getTypeArguments(<TypeReference>source).length && !(getObjectFlags(source) & ObjectFlags.MarkerType))) &&
((target.aliasSymbol && !target.aliasTypeArgumentsContainsMarker && length(target.aliasTypeArguments)) || (getObjectFlags(target) & ObjectFlags.Reference && !!getTypeArguments(<TypeReference>target).length && !(getObjectFlags(target) & ObjectFlags.MarkerType)))) {
if (source.aliasSymbol || target.aliasSymbol || (<TypeReference>source).target !== (<TypeReference>target).target) { // ensure like symbols are just handled by standard variance analysis
const sourceTypeArguments = getObjectFlags(source) & ObjectFlags.Reference ? getTypeArguments(<TypeReference>source) : source.aliasTypeArguments!;
const sourceHasMarker = some(sourceTypeArguments, a => a === markerOtherType);
const targetTypeArguments = getObjectFlags(target) & ObjectFlags.Reference ? getTypeArguments(<TypeReference>target) : target.aliasTypeArguments!;
const targetHasMarker = some(targetTypeArguments, a => a === markerOtherType);
// We're using `markerOtherType` as an existential, so we can't use it again if it's already in use,
// as we'd get spurious equivalencies - we'd need to use a second existential type, and once we're doing
// that we lose a lot of the benefit of canonicalizing back to a single-existential comparison, since then
// we'd need to manufacture new type identities for every new existential we make
// The above checks don't catch all cases this can occur, as they can only detect when the containing type
// was flagged during construction as containing a marker; however if a marker enters a type through instantiation
// we need to catch that here.
// We only do this when there's a handful of possible ways to match the type parameters up, as otherwise we manufacture
// an inordinate quantity of types just to calculate their IDs!
if (!sourceHasMarker && !targetHasMarker && sourceTypeArguments.length * targetTypeArguments.length < 10) {
const originalKey = getRelationKey(source, target, intersectionState, relation);
for (let i = 0; i < sourceTypeArguments.length; i++) {
for (let j = 0; j < targetTypeArguments.length; j++) {
if ((!(sourceTypeArguments[i].flags & TypeFlags.TypeParameter) && !isTypeAny(sourceTypeArguments[i]) && sourceTypeArguments[i] === targetTypeArguments[j]) ||
// Similarly, if we're comparing X<Q> to Z<any>, X<Q> is assignable to Z<any> trivially if X<?> is assignable to Z<?>
(!(sourceTypeArguments[i].flags & TypeFlags.TypeParameter) && isTypeAny(targetTypeArguments[j])) ||
// Again, but for `X<any>` vs `Z<Q>`
(isTypeAny(sourceTypeArguments[i]) && !(targetTypeArguments[j].flags & TypeFlags.TypeParameter)) ||
// Likewise, if we're comparing X<U> to Z<U> and are already comparing X<T> to Z<T>, we can assume it to be true
!!(sourceTypeArguments[i].flags & TypeFlags.TypeParameter) && sourceTypeArguments[i] === targetTypeArguments[j]) {
const sourceClone = sourceTypeArguments.slice();
sourceClone[i] = markerOtherType;
const s = getInstanceOfAliasOrReferenceWithMarker(source, sourceClone);
const targetClone = targetTypeArguments.slice();
targetClone[j] = markerOtherType;
const t = getInstanceOfAliasOrReferenceWithMarker(target, targetClone);
// If the marker-instantiated form looks "the same" as the type we already have (eg,
// because we replace unconstrained generics with unconstrained generics), skip the check
// since we'll otherwise deliver a spurious `Maybe` result from the key _just_ set upon
// entry into `recursiveTypeRelatedTo`
const existentialKey = getRelationKey(s, t, intersectionState, relation);
if (existentialKey !== originalKey) {
// We don't actually trigger the comparison, since we'd rather not do an extra comparison
// if we haven't already started that more general comparison; instead we just look for the
// key in the maybeKeys stack
for (let i = 0; i < maybeCount; i++) {
// If source and target are already being compared, consider them related with assumptions
if (existentialKey === maybeKeys[i]) {
return Ternary.Maybe;
}
}
}
}
}
}
}
}
}

// For a generic type T and a type U that is assignable to T, [...U] is assignable to T, U is assignable to readonly [...T],
// and U is assignable to [...T] when U is constrained to a mutable array or tuple type.
if (isSingleElementGenericTupleType(source) && !source.target.readonly && (result = isRelatedTo(getTypeArguments(source)[0], target)) ||
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
//// [performanceComparisonOfStructurallyIdenticalInterfacesWithGenericSignatures.ts]
export declare type ThenArg<T> = T extends any ? any : T extends PromiseLike<infer U> ? U : T;

export interface InterfaceA<T> {
filter(callback: (newValue: T, oldValue: T) => boolean): InterfaceA<T>;
map<D>(callback: (value: T) => D): InterfaceA<D>;
await<R extends ThenArg<T>>(): InterfaceA<R>;
awaitLatest<R extends ThenArg<T>>(): InterfaceA<R>;
awaitOrdered<R extends ThenArg<T>>(): InterfaceA<R>;
awaitOrdered2<R extends ThenArg<T>>(): InterfaceA<R>;
awaitOrdered3<R extends ThenArg<T>>(): InterfaceA<R>;
awaitOrdered4<R extends ThenArg<T>>(): InterfaceA<R>;
awaitOrdered5<R extends ThenArg<T>>(): InterfaceA<R>;
awaitOrdered6<R extends ThenArg<T>>(): InterfaceA<R>;
awaitOrdered7<R extends ThenArg<T>>(): InterfaceA<R>;
awaitOrdered8<R extends ThenArg<T>>(): InterfaceA<R>;
awaitOrdered9<R extends ThenArg<T>>(): InterfaceA<R>;
}

export interface InterfaceB<T> extends InterfaceA<T> {
map<D>(callback: (value: T) => D): InterfaceB<D>;
await<R extends ThenArg<T>>(): InterfaceB<R>;
awaitLatest<R extends ThenArg<T>>(): InterfaceB<R>;
awaitOrdered<R extends ThenArg<T>>(): InterfaceB<R>;
awaitOrdered2<R extends ThenArg<T>>(): InterfaceB<R>;
awaitOrdered3<R extends ThenArg<T>>(): InterfaceB<R>;
awaitOrdered4<R extends ThenArg<T>>(): InterfaceB<R>;
awaitOrdered5<R extends ThenArg<T>>(): InterfaceB<R>;
awaitOrdered6<R extends ThenArg<T>>(): InterfaceB<R>;
awaitOrdered7<R extends ThenArg<T>>(): InterfaceB<R>;
awaitOrdered8<R extends ThenArg<T>>(): InterfaceB<R>;
awaitOrdered9<R extends ThenArg<T>>(): InterfaceB<R>;
}

export class A<T> implements InterfaceB<T> {
public filter(callback: (newValue: T, oldValue: T) => boolean): B<T> {
return undefined as any;
}

public map<D>(callback: (value: T) => D): B<D> {
return undefined as any;
}

public await<R extends ThenArg<T>>(): B<R> {
return undefined as any;
}

public awaitOrdered<R extends ThenArg<T>>(): B<R> {
return undefined as any;
}

public awaitOrdered2<R extends ThenArg<T>>(): B<R> {
return undefined as any;
}

public awaitOrdered3<R extends ThenArg<T>>(): B<R> {
return undefined as any;
}

public awaitOrdered4<R extends ThenArg<T>>(): B<R> {
return undefined as any;
}

public awaitOrdered5<R extends ThenArg<T>>(): B<R> {
return undefined as any;
}

public awaitOrdered6<R extends ThenArg<T>>(): B<R> {
return undefined as any;
}

public awaitOrdered7<R extends ThenArg<T>>(): B<R> {
return undefined as any;
}

public awaitOrdered8<R extends ThenArg<T>>(): B<R> {
return undefined as any;
}

public awaitOrdered9<R extends ThenArg<T>>(): B<R> {
return undefined as any;
}

public awaitLatest<R extends ThenArg<T>>(): B<R> {
return undefined as any;
}
}

export class B<T> extends A<T> { }

//// [performanceComparisonOfStructurallyIdenticalInterfacesWithGenericSignatures.js]
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
exports.__esModule = true;
exports.B = exports.A = void 0;
var A = /** @class */ (function () {
function A() {
}
A.prototype.filter = function (callback) {
return undefined;
};
A.prototype.map = function (callback) {
return undefined;
};
A.prototype.await = function () {
return undefined;
};
A.prototype.awaitOrdered = function () {
return undefined;
};
A.prototype.awaitOrdered2 = function () {
return undefined;
};
A.prototype.awaitOrdered3 = function () {
return undefined;
};
A.prototype.awaitOrdered4 = function () {
return undefined;
};
A.prototype.awaitOrdered5 = function () {
return undefined;
};
A.prototype.awaitOrdered6 = function () {
return undefined;
};
A.prototype.awaitOrdered7 = function () {
return undefined;
};
A.prototype.awaitOrdered8 = function () {
return undefined;
};
A.prototype.awaitOrdered9 = function () {
return undefined;
};
A.prototype.awaitLatest = function () {
return undefined;
};
return A;
}());
exports.A = A;
var B = /** @class */ (function (_super) {
__extends(B, _super);
function B() {
return _super !== null && _super.apply(this, arguments) || this;
}
return B;
}(A));
exports.B = B;
Loading