Skip to content

do not add 'this' type for classes that considered safe (use 'this' only in property\element access expressions) #7474

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 2 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
35 changes: 27 additions & 8 deletions src/compiler/binder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ namespace ts {
let container: Node;
let blockScopeContainer: Node;
let lastContainer: Node;
let seenThisKeyword: boolean;
let usesThisTypeOrReference: boolean;

// state used by reachability checks
let hasExplicitReturn: boolean;
Expand Down Expand Up @@ -152,7 +152,7 @@ namespace ts {
container = undefined;
blockScopeContainer = undefined;
lastContainer = undefined;
seenThisKeyword = false;
usesThisTypeOrReference = false;
hasExplicitReturn = false;
labelStack = undefined;
labelIndexMap = undefined;
Expand Down Expand Up @@ -451,8 +451,17 @@ namespace ts {
// reset all emit helper flags on node (for incremental scenarios)
flags &= ~NodeFlags.EmitHelperFlags;

if (kind === SyntaxKind.InterfaceDeclaration) {
seenThisKeyword = false;
// for classes and interfaces we need to track the usages of 'this' inside the body of declaration
const trackThisOccurences = kind === SyntaxKind.InterfaceDeclaration || isClassLikeKind(kind);
// state of usesThisTypeOrReference should be saved and restored if either
// - trackThisOccurences is true
// - current node is function declaration / function expression - they don't capture lexical this
const needSaveThisState = trackThisOccurences || kind === SyntaxKind.FunctionDeclaration || kind === SyntaxKind.FunctionExpression;
let savedUsesThisTypeOrReference: boolean;

if (needSaveThisState) {
savedUsesThisTypeOrReference = usesThisTypeOrReference;
usesThisTypeOrReference = false;
}

const saveState = kind === SyntaxKind.SourceFile || kind === SyntaxKind.ModuleBlock || isFunctionLikeKind(kind);
Expand Down Expand Up @@ -481,8 +490,11 @@ namespace ts {
}
}

if (kind === SyntaxKind.InterfaceDeclaration) {
flags = seenThisKeyword ? flags | NodeFlags.ContainsThis : flags & ~NodeFlags.ContainsThis;
if (trackThisOccurences) {
flags = usesThisTypeOrReference ? flags | NodeFlags.UsesThisTypeOrReference : flags & ~NodeFlags.UsesThisTypeOrReference;
}
if (needSaveThisState) {
usesThisTypeOrReference = savedUsesThisTypeOrReference;
}

if (kind === SyntaxKind.SourceFile) {
Expand Down Expand Up @@ -1276,8 +1288,15 @@ namespace ts {
return checkStrictModePrefixUnaryExpression(<PrefixUnaryExpression>node);
case SyntaxKind.WithStatement:
return checkStrictModeWithStatement(<WithStatement>node);
case SyntaxKind.ThisKeyword:
if (node.parent.kind !== SyntaxKind.PropertyAccessExpression && node.parent.kind !== SyntaxKind.ElementAccessExpression) {
// property access\element access expressions are considered 'safe' usages of 'this' - 'this' cannot escape the class scope
// in all other cases pessimistically assume that 'this' can escape so class needs special treatment
usesThisTypeOrReference = true;
}
break;
case SyntaxKind.ThisType:
seenThisKeyword = true;
usesThisTypeOrReference = true;
return;
case SyntaxKind.TypePredicate:
return checkTypePredicate(node as TypePredicateNode);
Expand Down Expand Up @@ -1375,7 +1394,7 @@ namespace ts {
checkStrictModeIdentifier(parameterName as Identifier);
}
if (parameterName && parameterName.kind === SyntaxKind.ThisType) {
seenThisKeyword = true;
usesThisTypeOrReference = true;
}
bind(type);
}
Expand Down
110 changes: 82 additions & 28 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -825,7 +825,8 @@ namespace ts {
// No static member is present.
// Check if we're in an instance method and look for a relevant instance member.
if (location === container && !(location.flags & NodeFlags.Static)) {
const instanceType = (<InterfaceType>getDeclaredTypeOfSymbol(classSymbol)).thisType;
const declaredType = <InterfaceType>getDeclaredTypeOfSymbol(classSymbol);
const instanceType = declaredType.thisType || declaredType;
if (getPropertyOfType(instanceType, name)) {
error(errorLocation, Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, typeof nameArg === "string" ? nameArg : declarationNameToString(nameArg));
return true;
Expand Down Expand Up @@ -3328,25 +3329,62 @@ namespace ts {
}
}

// Returns true if the interface given by the symbol is free of "this" references. Specifically, the result is
// true if the interface itself contains no references to "this" in its body, if all base types are interfaces,
// and if none of the base interfaces have a "this" type.
function isIndependentInterface(symbol: Symbol): boolean {
function isIndependentBaseInterfaceList(nodes: NodeArray<ExpressionWithTypeArguments>): boolean {
if (!nodes) {
return true;
}
for (const node of nodes) {
if (!isIndependentHeritageClauseElement(node, /*classSymbol*/ undefined)) {
Copy link
Member

Choose a reason for hiding this comment

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

Might be worth merging in Ron's every from the transforms branch and making classSymbol optional so you can just say

return !nodes || !every(nodes, isIndependentHeritageClauseElement)

return false;
}
}
return true;
}

function isIndependentHeritageClauseElement(node: ExpressionWithTypeArguments, classSymbol: Symbol): boolean {
if (!node) {
return true;
}
if (isSupportedExpressionWithTypeArguments(node)) {
const baseSymbol = resolveEntityName(node.expression, SymbolFlags.Type, /*ignoreErrors*/ true);
if (!baseSymbol || baseSymbol === unknownSymbol) {
// pessimistically asssume that base type is not independent
return false;
}
const baseType = <InterfaceType>getDeclaredTypeOfSymbol(baseSymbol);
if (baseType.thisType) {
return false;
}
}
else if (classSymbol) {
Debug.assert((classSymbol.flags & SymbolFlags.Class) !== 0);
const baseTypes = getBaseTypes(<InterfaceType>getDeclaredTypeOfClassOrInterface(classSymbol));
if (baseTypes.length) {
return (<InterfaceType>baseTypes[0]).thisType === undefined;
}
}
return true;
}

// Returns true if the class\interface given by the symbol is free of "this" references. Specifically, the result is
// true if the class\interface itself contains no references to "this" in its body, if all base types are classes\interfaces,
// and if none of the base classes\interfaces have a "this" type.
Copy link
Member

Choose a reason for hiding this comment

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

For interfaces, what if the derived types (if any) have references to this? Wouldn't the base interface need a this type then?

function isIndependentClassOrInterface(symbol: Symbol): boolean {
for (const declaration of symbol.declarations) {
if (declaration.flags & NodeFlags.UsesThisTypeOrReference) {
return false;
}
if (declaration.kind === SyntaxKind.InterfaceDeclaration) {
if (declaration.flags & NodeFlags.ContainsThis) {
if (!isIndependentBaseInterfaceList(getInterfaceBaseTypeNodes(<InterfaceDeclaration>declaration))) {
return false;
}
const baseTypeNodes = getInterfaceBaseTypeNodes(<InterfaceDeclaration>declaration);
if (baseTypeNodes) {
for (const node of baseTypeNodes) {
if (isSupportedExpressionWithTypeArguments(node)) {
const baseSymbol = resolveEntityName(node.expression, SymbolFlags.Type, /*ignoreErrors*/ true);
if (!baseSymbol || !(baseSymbol.flags & SymbolFlags.Interface) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) {
return false;
}
}
}
}
else if (isClassLike(declaration)) {
const isIndependent = isIndependentHeritageClauseElement(getClassExtendsHeritageClauseElement(declaration), symbol) &&
isIndependentBaseInterfaceList(getClassImplementsHeritageClauseElements(declaration));

if (!isIndependent) {
return false;
Copy link
Member

Choose a reason for hiding this comment

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

I think it would be easier to read as

const isIndependentExtends = ...
const isIndependentImplements = ...
return isIndependentExtends && isIndependentImplements;

(The passthrough if (!isIndependent) return false; is a little suspicious because it doesn't do anything special.)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

current version won't check isIndependentImplements if isIndependentExtends parts returns false and suggested version will do both checks

Copy link
Member

Choose a reason for hiding this comment

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

good point. Maybe just get rid of the if and return directly then?

}
}
}
Expand All @@ -3365,7 +3403,9 @@ namespace ts {
// property types inferred from initializers and method return types inferred from return statements are very hard
// to exhaustively analyze). We give interfaces a "this" type if we can't definitely determine that they are free of
// "this" references.
if (outerTypeParameters || localTypeParameters || kind === TypeFlags.Class || !isIndependentInterface(symbol)) {
const isGeneric = outerTypeParameters || localTypeParameters;
const isIndependent = isIndependentClassOrInterface(symbol);
if (isGeneric || !isIndependent) {
type.flags |= TypeFlags.Reference;
type.typeParameters = concatenate(outerTypeParameters, localTypeParameters);
type.outerTypeParameters = outerTypeParameters;
Expand All @@ -3374,9 +3414,11 @@ namespace ts {
(<GenericType>type).instantiations[getTypeListId(type.typeParameters)] = <GenericType>type;
(<GenericType>type).target = <GenericType>type;
(<GenericType>type).typeArguments = type.typeParameters;
type.thisType = <TypeParameter>createType(TypeFlags.TypeParameter | TypeFlags.ThisType);
type.thisType.symbol = symbol;
type.thisType.constraint = type;
if (!isIndependent) {
type.thisType = <TypeParameter>createType(TypeFlags.TypeParameter | TypeFlags.ThisType);
type.thisType.symbol = symbol;
type.thisType.constraint = type;
}
}
}
return <InterfaceType>links.declaredType;
Expand Down Expand Up @@ -3576,13 +3618,18 @@ namespace ts {
}

function getTypeWithThisArgument(type: ObjectType, thisArgument?: Type) {
if (type.flags & TypeFlags.Reference) {
if (hasAssociatedThisType(type)) {
// instantiate type reference only if type uses thisType
return createTypeReference((<TypeReference>type).target,
concatenate((<TypeReference>type).typeArguments, [thisArgument || (<TypeReference>type).target.thisType]));
}
return type;
}

function hasAssociatedThisType(type: ObjectType): boolean {
return type.flags & TypeFlags.Reference && !!(<TypeReference>type).target.thisType;
}

function resolveObjectTypeMembers(type: ObjectType, source: InterfaceTypeWithDeclaredMembers, typeParameters: TypeParameter[], typeArguments: Type[]) {
let mapper = identityMapper;
let members = source.symbol.members;
Expand All @@ -3592,7 +3639,7 @@ namespace ts {
let numberIndexInfo = source.declaredNumberIndexInfo;
if (!rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) {
mapper = createTypeMapper(typeParameters, typeArguments);
members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1);
members = createInstantiatedSymbolTable(source.declaredProperties, mapper, hasAssociatedThisType(type) && typeParameters.length === 1);
callSignatures = instantiateList(source.declaredCallSignatures, mapper, instantiateSignature);
constructSignatures = instantiateList(source.declaredConstructSignatures, mapper, instantiateSignature);
stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper);
Expand All @@ -3603,9 +3650,11 @@ namespace ts {
if (members === source.symbol.members) {
members = createSymbolTable(source.declaredProperties);
}
const thisArgument = lastOrUndefined(typeArguments);
const thisArgument = hasAssociatedThisType(type) ? lastOrUndefined(typeArguments) : undefined;
for (const baseType of baseTypes) {
const instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType;
const instantiatedBaseType = thisArgument
? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument)
: instantiateType(baseType, mapper);
Copy link
Member

Choose a reason for hiding this comment

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

why do we now need to instantiate the baseType with no this argument?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

because baseType might be generic

addInheritedMembers(members, getPropertiesOfObjectType(instantiatedBaseType));
callSignatures = concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, SignatureKind.Call));
constructSignatures = concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, SignatureKind.Construct));
Expand All @@ -3622,7 +3671,7 @@ namespace ts {

function resolveTypeReferenceMembers(type: TypeReference): void {
const source = resolveDeclaredMembers(type.target);
const typeParameters = concatenate(source.typeParameters, [source.thisType]);
const typeParameters = source.thisType ? concatenate(source.typeParameters, [source.thisType]) : source.typeParameters;
const typeArguments = type.typeArguments && type.typeArguments.length === typeParameters.length ?
type.typeArguments : concatenate(type.typeArguments, [type]);
resolveObjectTypeMembers(type, source, typeParameters, typeArguments);
Expand Down Expand Up @@ -4961,7 +5010,8 @@ namespace ts {
if (parent && (isClassLike(parent) || parent.kind === SyntaxKind.InterfaceDeclaration)) {
if (!(container.flags & NodeFlags.Static) &&
(container.kind !== SyntaxKind.Constructor || isNodeDescendentOf(node, (<ConstructorDeclaration>container).body))) {
return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType;
const declaredType = getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent));
return declaredType.thisType || declaredType;
}
}
error(node, Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface);
Expand Down Expand Up @@ -5236,7 +5286,7 @@ namespace ts {
const declaration = <DeclarationWithTypeParameters>node;
if (declaration.typeParameters) {
for (const d of declaration.typeParameters) {
if (contains(mappedTypes, getDeclaredTypeOfTypeParameter(d.symbol))) {
if (contains(mappedTypes, getDeclaredTypeOfTypeParameter(getMergedSymbol(d.symbol)))) {
return true;
}
}
Expand Down Expand Up @@ -7637,7 +7687,11 @@ namespace ts {

if (isClassLike(container.parent)) {
const symbol = getSymbolOfNode(container.parent);
return container.flags & NodeFlags.Static ? getTypeOfSymbol(symbol) : (<InterfaceType>getDeclaredTypeOfSymbol(symbol)).thisType;
if (container.flags & NodeFlags.Static) {
return getTypeOfSymbol(symbol);
}
const declaredType = (<InterfaceType>getDeclaredTypeOfSymbol(symbol));
return declaredType.thisType || declaredType;
}

if (isInJavaScriptFile(node)) {
Expand Down
2 changes: 1 addition & 1 deletion src/compiler/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -387,7 +387,7 @@ namespace ts {
Const = 1 << 11, // Variable declaration
Namespace = 1 << 12, // Namespace declaration
ExportContext = 1 << 13, // Export context (initialized by binding)
ContainsThis = 1 << 14, // Interface contains references to "this"
UsesThisTypeOrReference = 1 << 14, // Class\interface contains references to "this"
HasImplicitReturn = 1 << 15, // If function implicitly returns on one of codepaths (initialized by binding)
HasExplicitReturn = 1 << 16, // If function has explicit reachable return on one of codepaths (initialized by binding)
GlobalAugmentation = 1 << 17, // Set if module declaration is an augmentation for the global scope
Expand Down
6 changes: 5 additions & 1 deletion src/compiler/utilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -676,7 +676,11 @@ namespace ts {
}

export function isClassLike(node: Node): node is ClassLikeDeclaration {
return node && (node.kind === SyntaxKind.ClassDeclaration || node.kind === SyntaxKind.ClassExpression);
return node && isClassLikeKind(node.kind);
}

export function isClassLikeKind(kind: SyntaxKind): boolean {
return kind === SyntaxKind.ClassDeclaration || kind === SyntaxKind.ClassExpression;
}

export function isFunctionLike(node: Node): node is FunctionLikeDeclaration {
Expand Down
2 changes: 1 addition & 1 deletion tests/baselines/reference/2dArrays.types
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class Board {
>this.ships.every(function (val) { return val.isSunk; }) : boolean
>this.ships.every : (callbackfn: (value: Ship, index: number, array: Ship[]) => boolean, thisArg?: any) => boolean
>this.ships : Ship[]
>this : this
>this : Board
>ships : Ship[]
>every : (callbackfn: (value: Ship, index: number, array: Ship[]) => boolean, thisArg?: any) => boolean
>function (val) { return val.isSunk; } : (val: Ship) => boolean
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@ class Point {
>"x=" + this.x : string
>"x=" : string
>this.x : number
>this : this
>this : Point
>x : number
>" y=" : string
>this.y : number
>this : this
>this : Point
>y : number
}
}
Expand Down Expand Up @@ -50,7 +50,7 @@ class ColoredPoint extends Point {
>toString : () => string
>" color=" : string
>this.color : string
>this : this
>this : ColoredPoint
>color : string
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ class C2 {

return this.x;
>this.x : IHasVisualizationModel
>this : this
>this : C2
>x : IHasVisualizationModel
}
set A(x) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class TestClass {
this.bar(x); // should not error
>this.bar(x) : void
>this.bar : { (x: string): void; (x: string[]): void; }
>this : this
>this : TestClass
>bar : { (x: string): void; (x: string[]): void; }
>x : any
}
Expand Down Expand Up @@ -71,7 +71,7 @@ class TestClass2 {
return this.bar(x); // should not error
>this.bar(x) : number
>this.bar : { (x: string): number; (x: string[]): number; }
>this : this
>this : TestClass2
>bar : { (x: string): number; (x: string[]): number; }
>x : any
}
Expand Down
2 changes: 1 addition & 1 deletion tests/baselines/reference/amdModuleName1.types
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ class Foo {
this.x = 5;
>this.x = 5 : number
>this.x : number
>this : this
>this : Foo
>x : number
>5 : number
}
Expand Down
Loading