Skip to content
Draft
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
1 change: 1 addition & 0 deletions packages/typescript/enums/objectFlags.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,5 @@ export declare enum ObjectFlags {
IsNeverIntersectionComputed = 1 << 25,
IsNeverIntersection = 1 << 26,
IsConstrainedTypeVariable = 1 << 27,
ConditionalForConstraint = 1 << 30,
}
1 change: 1 addition & 0 deletions packages/typescript/enums/objectFlags.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,5 @@ export var ObjectFlags;
ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 33554432] = "IsNeverIntersectionComputed";
ObjectFlags[ObjectFlags["IsNeverIntersection"] = 67108864] = "IsNeverIntersection";
ObjectFlags[ObjectFlags["IsConstrainedTypeVariable"] = 134217728] = "IsConstrainedTypeVariable";
ObjectFlags[ObjectFlags["ConditionalForConstraint"] = 1073741824] = "ConditionalForConstraint";
})(ObjectFlags || (ObjectFlags = {}));
1 change: 1 addition & 0 deletions tsc/internal/api/enum_values_generated.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

420 changes: 391 additions & 29 deletions tsc/internal/checker/checker.go

Large diffs are not rendered by default.

26 changes: 25 additions & 1 deletion tsc/internal/checker/inference.go
Original file line number Diff line number Diff line change
Expand Up @@ -1243,6 +1243,28 @@ func (c *Checker) isTypeCloselyMatchedBy(s *Type, t *Type) bool {

// Create an object with properties named in the string literal type. Every property has type `any`.
func (c *Checker) createEmptyObjectTypeFromStringLiteral(t *Type) *Type {
// The result is determined by the string literals in t and whether t
// includes string, so it is interned by those.
var b keyBuilder
for _, u := range t.Distributed() {
if u.flags&TypeFlagsStringLiteral != 0 {
b.writeString(getStringLiteralValue(u))
b.writeByte(0)
if u.symbol != nil {
b.writeByte(1)
b.writeSymbol(u.symbol)
} else {
b.writeByte(0)
}
}
}
if t.flags&TypeFlagsString != 0 {
b.writeByte(2)
}
key := b.hash()
if cached := c.emptyObjectTypesFromStringLiterals[key]; cached != nil {
return cached
}
members := ast.NewSymbolTable()
for _, t := range t.Distributed() {
if t.flags&TypeFlagsStringLiteral == 0 {
Expand All @@ -1261,7 +1283,9 @@ func (c *Checker) createEmptyObjectTypeFromStringLiteral(t *Type) *Type {
if t.flags&TypeFlagsString != 0 {
indexInfos = []*IndexInfo{c.newIndexInfo(c.stringType, c.emptyObjectType, false /*isReadonly*/, nil, nil)}
}
return c.newAnonymousType(nil, members, nil, nil, indexInfos)
result := c.newAnonymousType(nil, members, nil, nil, indexInfos)
c.emptyObjectTypesFromStringLiterals[key] = result
return result
}

func (c *Checker) newInferenceContext(typeParameters []*Type, signature *Signature, flags InferenceFlags, compareTypes TypeComparer) *InferenceContext {
Expand Down
8 changes: 8 additions & 0 deletions tsc/internal/checker/pseudotypenodebuilder.go
Original file line number Diff line number Diff line change
Expand Up @@ -699,6 +699,14 @@ func (b *NodeBuilderImpl) pseudoTypeToType(t *pseudochecker.PseudoType) *Type {
return b.ch.getReturnTypeOfSignature(b.ch.getSignatureFromDeclaration(node))
}
ty := b.ch.getWidenedType(b.ch.getRegularTypeOfExpression(node))
if ast.IsPropertyAssignment(node.Parent) {
// pseudoTypeToNode serializes the type of the property's symbol, which is
// not widened in the context of its containing object literal.
declared := b.ch.getWidenedLiteralType(b.ch.getTypeOfSymbol(b.ch.getSymbolOfDeclaration(node.Parent)))
if declared != ty {
return nil
}
}
return ty
case pseudochecker.PseudoTypeKindNoResult:
return nil // TODO: extract type selection logic from `serializeTypeForDeclaration`, not needed for current usecases but needed if completeness becomes required
Expand Down
172 changes: 165 additions & 7 deletions tsc/internal/checker/relater.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/microsoft/TypeScript/tsc/internal/binder"
"github.com/microsoft/TypeScript/tsc/internal/collections"
"github.com/microsoft/TypeScript/tsc/internal/core"
"github.com/microsoft/TypeScript/tsc/internal/debug"
"github.com/microsoft/TypeScript/tsc/internal/diagnostics"
"github.com/microsoft/TypeScript/tsc/internal/jsnum"
"github.com/microsoft/TypeScript/tsc/internal/stringutil"
Expand Down Expand Up @@ -71,8 +72,11 @@ const (
RelationComparisonResultReportsUnmeasurable RelationComparisonResult = 1 << 3
RelationComparisonResultReportsUnreliable RelationComparisonResult = 1 << 4
RelationComparisonResultComplexityOverflow RelationComparisonResult = 1 << 5
RelationComparisonResultReportsMask = RelationComparisonResultReportsUnmeasurable | RelationComparisonResultReportsUnreliable
RelationComparisonResultOverflow = RelationComparisonResultComplexityOverflow
// Set while relating when a return type still being resolved was read as any. Results computed under that
// assumption are not cached; this flag is never recorded in a relation.
RelationComparisonResultAssumesResolvingReturnType RelationComparisonResult = 1 << 6
RelationComparisonResultReportsMask = RelationComparisonResultReportsUnmeasurable | RelationComparisonResultReportsUnreliable
RelationComparisonResultOverflow = RelationComparisonResultComplexityOverflow
)

type DiagnosticAndArguments struct {
Expand Down Expand Up @@ -371,7 +375,9 @@ func (c *Checker) checkTypeRelatedToEx(
r.relation = relation
r.errorNode = errorNode
r.relationCount = (16_000_000 - relation.size()) / 8
saveAssumesResolvingReturnType := c.reliabilityFlags & RelationComparisonResultAssumesResolvingReturnType
result := r.isRelatedToEx(source, target, RecursionFlagsBoth, errorNode != nil /*reportErrors*/, headMessage, IntersectionStateNone)
c.reliabilityFlags = c.reliabilityFlags&^RelationComparisonResultAssumesResolvingReturnType | saveAssumesResolvingReturnType
if r.overflow {
// Record this relation as having failed such that we don't attempt the overflowing operation again.
id, _ := getRelationKey(source, target, IntersectionStateNone, relation == c.identityRelation, false /*ignoreConstraints*/)
Expand Down Expand Up @@ -779,25 +785,169 @@ func (c *Checker) isDeeplyNestedType(t *Type, stack []*Type, maxDepth int) bool
} else {
identity := getRecursionIdentityFromTarget(target)
count := 0
lastTypeId := TypeId(0)
var previous *Type
for _, t := range stack {
if hasMatchingRecursionIdentity(t, identity) {
// We only count occurrences with a higher type id than the previous occurrence, since higher
// type ids are an indicator of newer instantiations caused by recursion.
if t.id >= lastTypeId {
if previous == nil || c.isDeeperOccurrence(t, previous) {
count++
if count >= maxDepth {
return true
}
}
lastTypeId = t.id
previous = t
}
}
}
}
return false
}

// isDeeperOccurrence reports whether t, an occurrence of a recursion identity
// nested within the occurrence previous, counts as another level of nesting.
// Instantiations caused by recursion are built from the previous occurrence or
// its parts and so have a higher generation, whereas nested type arguments and
// the types of nested members have a lower one. However, evaluating a
// conditional type, an indexed access, or a constraint can step to a type
// built from fewer layers than the one it was evaluated from, so a lower
// generation occurrence of such a type counts unless it is one of the types
// previous was built from. A copy of an intersection or union with the same
// constituents as previous, such as one without its alias, is the same level
// of nesting. Two such types that both have aliases are different levels, as
// the alias type arguments can keep growing while the constituents stay the
// same, such as `type HasDefault<T> = T & { hasDefault: true }` applied to
// `this` again and again.
func (c *Checker) isDeeperOccurrence(t *Type, previous *Type) bool {
generation, previousGeneration := c.typeGeneration(t), c.typeGeneration(previous)
switch {
case generation > previousGeneration:
return true
case generation == previousGeneration:
return t == previous || t.flags&TypeFlagsUnionOrIntersection == 0 ||
t.flags&TypeFlagsUnionOrIntersection != previous.flags&TypeFlagsUnionOrIntersection ||
!slices.Equal(t.Types(), previous.Types()) ||
t.alias != nil && previous.alias != nil
}
return t.flags&TypeFlagsInstantiable != 0 && !c.isBuiltFrom(previous, t)
}

// isBuiltFrom reports whether t was instantiated, transitively, from s, as
// visitTypeSources visits the types a type was instantiated from. Since a type
// has a higher generation than the types it was built from, only those of a
// higher generation than s are searched.
func (c *Checker) isBuiltFrom(t *Type, s *Type) bool {
target := c.typeGeneration(s)
var visited collections.Set[*Type]
var visit func(t *Type) bool
visit = func(t *Type) bool {
if t == s {
return true
}
if t == nil || c.typeGeneration(t) <= target || visited.Has(t) {
return false
}
visited.Add(t)
found := false
c.visitTypeSources(t, func(u *Type) {
found = found || visit(u)
})
return found
}
return visit(t)
}

// visitTypeSources calls f with each type t was instantiated from, as far as
// they are known without computing them. Object literals are built from the
// types of their properties, except for those resolved lazily, such as
// accessors.
func (c *Checker) visitTypeSources(t *Type, f func(*Type)) {
switch {
case t.flags&TypeFlagsObject != 0:
if t.objectFlags&ObjectFlagsReference != 0 && t.AsTypeReference().node == nil {
for _, a := range t.AsTypeReference().resolvedTypeArguments {
f(a)
}
} else if m := t.AsObjectType().mapper; m != nil {
c.visitMapperTargets(m, f)
} else if t.symbol != nil && t.symbol.Flags()&ast.SymbolFlagsObjectLiteral != 0 {
for prop := range t.AsStructuredType().members.Values() {
if prop.Flags()&ast.SymbolFlagsTransient == 0 || prop.CheckFlags()&(ast.CheckFlagsInstantiated|ast.CheckFlagsMapped|ast.CheckFlagsReverseMapped|ast.CheckFlagsDeferredType) != 0 {
continue
}
if propType := c.peekTypeOfObjectLiteralMember(prop); propType != nil {
f(propType)
}
}
}
case t.flags&TypeFlagsConditional != 0:
if m := t.AsConditionalType().mapper; m != nil {
c.visitMapperTargets(m, f)
}
case t.flags&TypeFlagsIndexedAccess != 0:
d := t.AsIndexedAccessType()
f(d.objectType)
f(d.indexType)
case t.flags&TypeFlagsUnionOrIntersection != 0, t.flags&TypeFlagsTemplateLiteral != 0:
for _, u := range t.Types() {
f(u)
}
case t.flags&TypeFlagsIndex != 0, t.flags&TypeFlagsStringMapping != 0:
f(t.Target())
case t.flags&TypeFlagsSubstitution != 0:
d := t.AsSubstitutionType()
f(d.baseType)
f(d.constraint)
}
}

// visitMapperTargets calls f with each type m maps to, as far as they are
// known without computing them.
func (c *Checker) visitMapperTargets(m *TypeMapper, f func(*Type)) {
switch m.kind {
case TypeMapperKindSimple:
f(castTypeMapper[SimpleTypeMapper](m, TypeMapperKindSimple).target)
case TypeMapperKindArray:
for _, t := range castTypeMapper[ArrayTypeMapper](m, TypeMapperKindArray).targets {
f(t)
}
case TypeMapperKindArrayToSingle:
f(castTypeMapper[ArrayToSingleTypeMapper](m, TypeMapperKindArrayToSingle).target)
case TypeMapperKindMerged:
d := castTypeMapper[MergedTypeMapper](m, TypeMapperKindMerged)
c.visitMapperTargets(d.m1, f)
c.visitMapperTargets(d.m2, f)
case TypeMapperKindComposite:
d := castTypeMapper[CompositeTypeMapper](m, TypeMapperKindComposite)
c.visitMapperTargets(d.m1, f)
c.visitMapperTargets(d.m2, f)
}
}

const (
maxTypeGeneration = 1<<16 - 3
typeGenerationInProgress = 1<<16 - 1
)

// typeGeneration returns one more than the highest generation of the types t
// was instantiated from, as visitTypeSources visits them, or zero if it was not
// instantiated from any. A type is created after the types it is instantiated
// from, so this orders types by creation where the order follows from their
// structure, and unlike type ids does not depend on the order in which
// unrelated types were created.
func (c *Checker) typeGeneration(t *Type) int {
debug.Assert(t.generation != typeGenerationInProgress, "types are only built from existing types")
if t.generation != 0 {
return int(t.generation) - 1
}
t.generation = typeGenerationInProgress
generation := 0
c.visitTypeSources(t, func(s *Type) {
generation = max(generation, c.typeGeneration(s)+1)
})
generation = min(generation, maxTypeGeneration)
t.generation = uint16(generation + 1)
return generation
}

func hasMatchingRecursionIdentity(t *Type, identity RecursionId) bool {
target := getRecursionIdentityTarget(t)
if target.flags&TypeFlagsIntersection != 0 {
Expand Down Expand Up @@ -3201,6 +3351,14 @@ func (r *Relater) recursiveTypeRelatedTo(source *Type, target *Type, reportError
r.targetStack = r.targetStack[:len(r.targetStack)-1]
}
r.expandingFlags = saveExpandingFlags
if propagatingVarianceFlags&RelationComparisonResultAssumesResolvingReturnType != 0 {
// The result holds only while a return type it read is being resolved, so it is not cached. Comparisons
// still in progress below this one have the same dependence.
if result == TernaryFalse || result == TernaryTrue || (len(r.sourceStack) == 0 && len(r.targetStack) == 0) {
r.resetMaybeStack(maybeStart, propagatingVarianceFlags, false)
}
return result
}
if result != TernaryFalse {
if result == TernaryTrue || (len(r.sourceStack) == 0 && len(r.targetStack) == 0) {
if result == TernaryTrue || result == TernaryMaybe {
Expand Down
4 changes: 4 additions & 0 deletions tsc/internal/checker/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -737,6 +737,8 @@ const (
ObjectFlagsIsNeverIntersectionComputed = 1 << 25 // IsNeverLike flag has been computed
ObjectFlagsIsNeverIntersection = 1 << 26 // Intersection reduces to never
ObjectFlagsIsConstrainedTypeVariable = 1 << 27 // T & C, where T's constraint and C are primitives, object, or {}
// Flags that require TypeFlags.Conditional
ObjectFlagsConditionalForConstraint = 1 << 30 // Deferred conditional type made for a constraint
)

// TypeAlias
Expand Down Expand Up @@ -795,6 +797,7 @@ type Type struct {
objectFlags ObjectFlags
id TypeId
kind typeKind `customlint:"protected"`
generation uint16 // see Checker.typeGeneration; zero until computed
symbol *ast.Symbol
alias *TypeAlias
checker *Checker
Expand Down Expand Up @@ -1510,6 +1513,7 @@ type TypeParameter struct {
isDistributed bool
resolvedDefaultType *Type
distributedType *Type
origin *Type // The type parameter a restrictive type parameter was made from, or the tuple target of a tuple element type parameter
}

func (t *TypeParameter) IsThisType() bool { return t.isThisType }
Expand Down
15 changes: 10 additions & 5 deletions tsc/internal/checker/types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package checker

import (
"encoding/binary"
"math"
"runtime"
"slices"
"strconv"
Expand Down Expand Up @@ -177,11 +178,15 @@ func BenchmarkTypeListKey(b *testing.B) {

func newCompositeTestChecker() (*Checker, []*Type) {
c := &Checker{
strictNullChecks: true,
unionTypes: make(map[CacheHashKey]*Type),
unionOfUnionTypes: make(map[UnionOfUnionKey]*Type),
intersectionTypes: make(map[CacheHashKey]*Type),
subtypeReductionCache: make(map[CacheHashKey][]*Type),
strictNullChecks: true,
unionTypes: make(map[CacheHashKey]*Type),
unionOfUnionTypes: make(map[UnionOfUnionKey]*Type),
intersectionTypes: make(map[CacheHashKey]*Type),
intersectionContentTypes: make(map[CacheHashKey]*Type),
subtypeReductionCache: make(map[CacheHashKey][]*Type),
// The synthetic types of these tests are distinguished only by the
// order they are created in, as types created with a checker are.
builtinTypeCount: math.MaxUint32,
}
c.compareSymbols = c.compareSymbolsWorker
c.neverType = c.newIntrinsicType(TypeFlagsNever, "never")
Expand Down
Loading
Loading