Skip to content

Add this expandos #860

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

Merged
merged 11 commits into from
May 15, 2025
Merged
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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
59 changes: 43 additions & 16 deletions internal/ast/utilities.go
Original file line number Diff line number Diff line change
Expand Up @@ -1353,8 +1353,10 @@ func GetNonAssignedNameOfDeclaration(declaration *Node) *Node {
// !!!
switch declaration.Kind {
case KindBinaryExpression:
if IsFunctionPropertyAssignment(declaration) {
return GetElementOrPropertyAccessArgumentExpressionOrName(declaration.AsBinaryExpression().Left)
bin := declaration.AsBinaryExpression()
kind := GetAssignmentDeclarationKind(bin)
if kind == JSDeclarationKindProperty || kind == JSDeclarationKindThisProperty {
return GetElementOrPropertyAccessArgumentExpressionOrName(bin.Left)
}
return nil
case KindExportAssignment, KindJSExportAssignment:
Expand Down Expand Up @@ -1400,21 +1402,46 @@ func getAssignedName(node *Node) *Node {
return nil
}

func IsFunctionPropertyAssignment(node *Node) bool {
if node.Kind == KindBinaryExpression {
expr := node.AsBinaryExpression()
if expr.OperatorToken.Kind == KindEqualsToken {
switch expr.Left.Kind {
case KindPropertyAccessExpression:
// F.id = expr
return IsIdentifier(expr.Left.Expression()) && IsIdentifier(expr.Left.Name())
case KindElementAccessExpression:
// F[xxx] = expr
return IsIdentifier(expr.Left.Expression())
}
}
type JSDeclarationKind int

const (
JSDeclarationKindNone JSDeclarationKind = iota
/// module.exports = expr
JSDeclarationKindModuleExports
/// exports.name = expr
/// module.exports.name = expr
JSDeclarationKindExportsProperty
/// className.prototype.name = expr
JSDeclarationKindPrototypeProperty
/// this.name = expr
JSDeclarationKindThisProperty
/// F.name = expr, F[name] = expr
JSDeclarationKindProperty
)

func GetAssignmentDeclarationKind(bin *BinaryExpression) JSDeclarationKind {
if bin.OperatorToken.Kind != KindEqualsToken || !IsAccessExpression(bin.Left) {
return JSDeclarationKindNone
}
return false
if IsModuleExportsAccessExpression(bin.Left) {
return JSDeclarationKindModuleExports
} else if (IsModuleExportsAccessExpression(bin.Left.Expression()) || IsExportsIdentifier(bin.Left.Expression())) &&
hasJSBindableName(bin.Left) {
return JSDeclarationKindExportsProperty
}
if bin.Left.Expression().Kind == KindThisKeyword {
return JSDeclarationKindThisProperty
}
if bin.Left.Kind == KindPropertyAccessExpression && IsIdentifier(bin.Left.Expression()) && hasJSBindableName(bin.Left) ||
bin.Left.Kind == KindElementAccessExpression && IsIdentifier(bin.Left.Expression()) {
return JSDeclarationKindProperty
}
return JSDeclarationKindNone
}

func hasJSBindableName(node *Node) bool {
name := GetElementOrPropertyAccessArgumentExpressionOrName(node)
return IsIdentifier(name) || IsStringLiteralLike(name)
}

/**
Expand Down
40 changes: 39 additions & 1 deletion internal/binder/binder.go
Original file line number Diff line number Diff line change
Expand Up @@ -622,8 +622,11 @@ func (b *Binder) bind(node *ast.Node) bool {
setFlowNode(node, b.currentFlow)
}
case ast.KindBinaryExpression:
if ast.IsFunctionPropertyAssignment(node) {
switch ast.GetAssignmentDeclarationKind(node.AsBinaryExpression()) {
case ast.JSDeclarationKindProperty:
b.bindFunctionPropertyAssignment(node)
case ast.JSDeclarationKindThisProperty:
b.bindThisPropertyAssignment(node)
}
b.checkStrictModeBinaryExpression(node)
case ast.KindCatchClause:
Expand Down Expand Up @@ -1042,6 +1045,41 @@ func (b *Binder) bindFunctionPropertyAssignment(node *ast.Node) {
}
}

func (b *Binder) bindThisPropertyAssignment(node *ast.Node) {
if !ast.IsInJSFile(node) {
return
}
bin := node.AsBinaryExpression()
if ast.IsPropertyAccessExpression(bin.Left) && ast.IsPrivateIdentifier(bin.Left.AsPropertyAccessExpression().Name()) {
return
}
thisContainer := ast.GetThisContainer(node /*includeArrowFunctions*/, false /*includeClassComputedPropertyName*/, false)
switch thisContainer.Kind {
case ast.KindFunctionDeclaration, ast.KindFunctionExpression:
// !!! constructor functions
case ast.KindConstructor, ast.KindPropertyDeclaration, ast.KindMethodDeclaration, ast.KindGetAccessor, ast.KindSetAccessor, ast.KindClassStaticBlockDeclaration:
// this.property assignment in class member -- bind to the containing class
containingClass := thisContainer.Parent
classSymbol := containingClass.Symbol()
var symbolTable ast.SymbolTable
if ast.IsStatic(thisContainer) {
symbolTable = ast.GetExports(containingClass.Symbol())
} else {
symbolTable = ast.GetMembers(containingClass.Symbol())
}
if ast.HasDynamicName(node) {
b.declareSymbolEx(symbolTable, containingClass.Symbol(), node, ast.SymbolFlagsProperty, ast.SymbolFlagsNone, true /*isReplaceableByMethod*/, true /*isComputedName*/)
addLateBoundAssignmentDeclarationToSymbol(node, classSymbol)
} else {
b.declareSymbolEx(symbolTable, containingClass.Symbol(), node, ast.SymbolFlagsProperty|ast.SymbolFlagsAssignment, ast.SymbolFlagsNone, true /*isReplaceableByMethod*/, false /*isComputedName*/)
}
case ast.KindSourceFile, ast.KindModuleDeclaration:
// top-level this.property as assignment to globals is no longer supported
default:
panic("Unhandled case in bindThisPropertyAssignment: " + thisContainer.Kind.String())
}
}

func (b *Binder) bindEnumDeclaration(node *ast.Node) {
if ast.IsEnumConst(node) {
b.bindBlockScopedDeclaration(node, ast.SymbolFlagsConstEnum, ast.SymbolFlagsConstEnumExcludes)
Expand Down
172 changes: 138 additions & 34 deletions internal/checker/checker.go
Original file line number Diff line number Diff line change
Expand Up @@ -581,6 +581,8 @@ type Checker struct {
templateLiteralTypes map[string]*Type
stringMappingTypes map[StringMappingKey]*Type
uniqueESSymbolTypes map[*ast.Symbol]*Type
thisExpandoKinds map[*ast.Symbol]thisAssignmentDeclarationKind
thisExpandoLocations map[*ast.Symbol]*ast.Node
subtypeReductionCache map[string][]*Type
cachedTypes map[CachedTypeKey]*Type
cachedSignatures map[CachedSignatureKey]*Signature
Expand Down Expand Up @@ -866,6 +868,8 @@ func NewChecker(program Program) *Checker {
c.templateLiteralTypes = make(map[string]*Type)
c.stringMappingTypes = make(map[StringMappingKey]*Type)
c.uniqueESSymbolTypes = make(map[*ast.Symbol]*Type)
c.thisExpandoKinds = make(map[*ast.Symbol]thisAssignmentDeclarationKind)
c.thisExpandoLocations = make(map[*ast.Symbol]*ast.Node)
c.subtypeReductionCache = make(map[string][]*Type)
c.cachedTypes = make(map[CachedTypeKey]*Type)
c.cachedSignatures = make(map[CachedSignatureKey]*Signature)
Expand Down Expand Up @@ -10809,9 +10813,9 @@ func (c *Checker) getFlowTypeOfProperty(reference *ast.Node, prop *ast.Symbol) *
func (c *Checker) getTypeOfPropertyInBaseClass(property *ast.Symbol) *Type {
classType := c.getDeclaringClass(property)
if classType != nil {
baseClassType := c.getBaseTypes(classType)[0]
if baseClassType != nil {
return c.getTypeOfPropertyOfType(baseClassType, property.Name)
baseClassTypes := c.getBaseTypes(classType)
if len(baseClassTypes) > 0 {
return c.getTypeOfPropertyOfType(baseClassTypes[0], property.Name)
}
}
return nil
Expand Down Expand Up @@ -16710,14 +16714,101 @@ func (c *Checker) getTypeOfPrototypeProperty(prototype *ast.Symbol) *Type {
return classType
}

type thisAssignmentDeclarationKind int32

const (
thisAssignmentDeclarationNone thisAssignmentDeclarationKind = iota // not (all) this.property assignments
thisAssignmentDeclarationTyped // typed; use the type annotation
thisAssignmentDeclarationConstructor // at least one in the constructor; use control flow
thisAssignmentDeclarationMethod // methods only; look in base first, and if not found, union all declaration types plus undefined
)

func (c *Checker) getWidenedTypeForAssignmentDeclaration(symbol *ast.Symbol) *Type {
var types []*Type
var t *Type
kind, location := c.isConstructorDeclaredThisProperty(symbol)
if kind == thisAssignmentDeclarationTyped {
if location == nil {
panic("location should not be nil when this assignment has a type.")
}
t = c.getTypeFromTypeNode(location)
} else if kind == thisAssignmentDeclarationConstructor {
if location == nil {
panic("constructor should not be nil when this assignment is in a constructor.")
}
t = c.getFlowTypeInConstructor(symbol, location)
} else if kind == thisAssignmentDeclarationMethod {
t = c.getTypeOfPropertyInBaseClass(symbol)
}
if t == nil {
var types []*Type
for _, declaration := range symbol.Declarations {
if ast.IsBinaryExpression(declaration) {
types = core.AppendIfUnique(types, c.checkExpressionForMutableLocation(declaration.AsBinaryExpression().Right, CheckModeNormal))
}
}
if kind == thisAssignmentDeclarationMethod && len(types) > 0 {
if c.strictNullChecks {
types = core.AppendIfUnique(types, c.undefinedOrMissingType)
}
}
t = c.getWidenedType(c.getUnionType(types))
}
// report an all-nullable or empty union as an implicit any in JS files
if symbol.ValueDeclaration != nil && ast.IsInJSFile(symbol.ValueDeclaration) &&
c.filterType(t, func(c *Type) bool { return c.Flags() & ^TypeFlagsNullable != 0 }) == c.neverType {
c.reportImplicitAny(symbol.ValueDeclaration, c.anyType, WideningKindNormal)
return c.anyType
}
return t
}

// A property is considered a constructor declared property when all declaration sites are this.xxx assignments,
// when no declaration sites have JSDoc type annotations, and when at least one declaration site is in the body of
// a class constructor.
func (c *Checker) isConstructorDeclaredThisProperty(symbol *ast.Symbol) (thisAssignmentDeclarationKind, *ast.Node) {
if symbol.ValueDeclaration == nil || !ast.IsBinaryExpression(symbol.ValueDeclaration) {
return thisAssignmentDeclarationNone, nil
}
if kind, ok := c.thisExpandoKinds[symbol]; ok {
location, ok2 := c.thisExpandoLocations[symbol]
if !ok2 {
panic("ctor should be cached whenever this expando location is cached")
}
return kind, location
}
allThis := true
var typeAnnotation *ast.Node
for _, declaration := range symbol.Declarations {
if ast.IsBinaryExpression(declaration) {
types = core.AppendIfUnique(types, c.checkExpressionForMutableLocation(declaration.AsBinaryExpression().Right, CheckModeNormal))
if !ast.IsBinaryExpression(declaration) {
allThis = false
break
}
bin := declaration.AsBinaryExpression()
if ast.GetAssignmentDeclarationKind(bin) == ast.JSDeclarationKindThisProperty &&
(bin.Left.Kind != ast.KindElementAccessExpression || ast.IsStringOrNumericLiteralLike(bin.Left.AsElementAccessExpression().ArgumentExpression)) {
// TODO: if bin.Type() != nil, use bin.Type()
if bin.Right.Kind == ast.KindTypeAssertionExpression {
typeAnnotation = bin.Right.AsTypeAssertion().Type
}
} else {
allThis = false
break
}
}
return c.getWidenedType(c.getUnionType(types))
var location *ast.Node
kind := thisAssignmentDeclarationNone
if allThis {
if typeAnnotation != nil {
location = typeAnnotation
kind = thisAssignmentDeclarationTyped
} else {
location = c.getDeclaringConstructor(symbol)
kind = core.IfElse(location == nil, thisAssignmentDeclarationMethod, thisAssignmentDeclarationConstructor)
}
}
c.thisExpandoKinds[symbol] = kind
c.thisExpandoLocations[symbol] = location
return kind, location
}

func (c *Checker) widenTypeForVariableLikeDeclaration(t *Type, declaration *ast.Node, reportErrors bool) *Type {
Expand Down Expand Up @@ -27595,8 +27686,8 @@ func (c *Checker) getContextualTypeForBinaryOperand(node *ast.Node, contextFlags
case ast.KindEqualsToken, ast.KindAmpersandAmpersandEqualsToken, ast.KindBarBarEqualsToken, ast.KindQuestionQuestionEqualsToken:
// In an assignment expression, the right operand is contextually typed by the type of the left operand
// unless it's an assignment declaration.
if node == binary.Right && !c.isReferenceToModuleExports(binary.Left) && (binary.Symbol == nil || c.canGetContextualTypeForAssignmentDeclaration(binary.Left)) {
return c.getContextualTypeFromAssignmentTarget(binary.Left)
if node == binary.Right && !c.isReferenceToModuleExports(binary.Left) && (binary.Symbol == nil || c.canGetContextualTypeForAssignmentDeclaration(node.Parent)) {
return c.getTypeOfExpression(binary.Left)
}
case ast.KindBarBarToken, ast.KindQuestionQuestionToken:
// When an || expression has a contextual type, the operands are contextually typed by that type, except
Expand All @@ -27622,47 +27713,60 @@ func (c *Checker) canGetContextualTypeForAssignmentDeclaration(node *ast.Node) b
// binder) of the form 'F.id = expr' or 'F[xxx] = expr'. If 'F' is declared as a variable with a type annotation,
// we can obtain a contextual type from the annotated type without triggering a circularity. Otherwise, the
// assignment declaration has no contextual type.
symbol := c.getExportSymbolOfValueSymbolIfExported(c.getResolvedSymbol(node.Expression()))
return symbol.ValueDeclaration != nil && ast.IsVariableDeclaration(symbol.ValueDeclaration) && symbol.ValueDeclaration.Type() != nil
}

func (c *Checker) isReferenceToModuleExports(node *ast.Node) bool {
if ast.IsAccessExpression(node) {
expr := node.Expression()
if ast.IsIdentifier(expr) {
// Node is the left operand of an assignment expression of the form 'module.exports = expr'.
symbol := c.getExportSymbolOfValueSymbolIfExported(c.getResolvedSymbol(expr))
return symbol.Flags&ast.SymbolFlagsModuleExports != 0
}
}
return false
}

func (c *Checker) getContextualTypeFromAssignmentTarget(node *ast.Node) *Type {
if ast.IsAccessExpression(node) && node.Expression().Kind == ast.KindThisKeyword {
left := node.AsBinaryExpression().Left
expr := left.Expression()
if ast.IsAccessExpression(left) && expr.Kind == ast.KindThisKeyword {
var symbol *ast.Symbol
if ast.IsPropertyAccessExpression(node) {
name := node.Name()
thisType := c.getTypeOfExpression(node.Expression())
if ast.IsPropertyAccessExpression(left) {
name := left.Name()
thisType := c.getTypeOfExpression(expr)
if ast.IsPrivateIdentifier(name) {
symbol = c.getPropertyOfType(thisType, binder.GetSymbolNameForPrivateIdentifier(thisType.symbol, name.Text()))
} else {
symbol = c.getPropertyOfType(thisType, name.Text())
}
} else {
propType := c.checkExpressionCached(node.AsElementAccessExpression().ArgumentExpression)
propType := c.checkExpressionCached(left.AsElementAccessExpression().ArgumentExpression)
if isTypeUsableAsPropertyName(propType) {
symbol = c.getPropertyOfType(c.getTypeOfExpression(node.Expression()), getPropertyNameFromType(propType))
symbol = c.getPropertyOfType(c.getTypeOfExpression(expr), getPropertyNameFromType(propType))
}
}
if symbol != nil {
d := symbol.ValueDeclaration
if d != nil && (ast.IsPropertyDeclaration(d) || ast.IsPropertySignatureDeclaration(d)) && d.Type() == nil && d.Initializer() == nil {
return nil
return false
}
}
symbol = node.Symbol()
if symbol != nil && symbol.ValueDeclaration != nil && symbol.ValueDeclaration.Type() == nil {
if !ast.IsObjectLiteralMethod(c.getThisContainer(expr, false, false)) {
return false
}
// and now for one single case of object literal methods
name := ast.GetElementOrPropertyAccessArgumentExpressionOrName(left)
if name == nil {
return false
} else {
// !!! contextual typing for `this` in object literals
return false
}
}
return true
}
return c.getTypeOfExpression(node)
symbol := c.getExportSymbolOfValueSymbolIfExported(c.getResolvedSymbol(expr))
return symbol.ValueDeclaration != nil && ast.IsVariableDeclaration(symbol.ValueDeclaration) && symbol.ValueDeclaration.Type() != nil
}

func (c *Checker) isReferenceToModuleExports(node *ast.Node) bool {
if ast.IsAccessExpression(node) {
expr := node.Expression()
if ast.IsIdentifier(expr) {
// Node is the left operand of an assignment expression of the form 'module.exports = expr'.
symbol := c.getExportSymbolOfValueSymbolIfExported(c.getResolvedSymbol(expr))
return symbol.Flags&ast.SymbolFlagsModuleExports != 0
}
}
return false
}

func (c *Checker) getContextualTypeForObjectLiteralElement(element *ast.Node, contextFlags ContextFlags) *Type {
Expand Down
7 changes: 4 additions & 3 deletions internal/checker/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,9 +152,10 @@ type ExportTypeLinks struct {
// Links for type aliases

type TypeAliasLinks struct {
declaredType *Type
typeParameters []*Type // Type parameters of type alias (undefined if non-generic)
instantiations map[string]*Type // Instantiations of generic type alias (undefined if non-generic)
declaredType *Type
typeParameters []*Type // Type parameters of type alias (undefined if non-generic)
instantiations map[string]*Type // Instantiations of generic type alias (undefined if non-generic)
isConstructorDeclaredProperty bool
}

// Links for declared types (type parameters, class types, interface types, enums)
Expand Down
Loading
Loading