Skip to content

ES private field check #44648

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 45 commits into from
Sep 24, 2021
Merged
Show file tree
Hide file tree
Changes from 26 commits
Commits
Show all changes
45 commits
Select commit Hold shift + click to select a range
f04f22c
es private fields in in (#52)
acutmore Jun 17, 2021
30dde52
[fixup] include inToken when walking forEachChild(node, cb)
acutmore Jun 18, 2021
31fa02b
Merge remote-tracking branch 'origin/main' into bb-private-field-in-in
acutmore Jun 18, 2021
307247c
Merge remote-tracking branch 'origin/main' into bb-private-field-in-in
acutmore Jun 30, 2021
61c677b
[squash] re-accept lib definition baseline changes
acutmore Jun 30, 2021
8292ee2
[squash] reduce if/else to ternary
acutmore Sep 15, 2021
4723380
[squash] drop 'originalName' and rename parameter instead
acutmore Sep 15, 2021
9f1c176
[squash] extend spelling suggestion to all privateIdentifiers
acutmore Sep 15, 2021
511ac22
[squash] revert the added lexical spelling suggestions logic
acutmore Sep 16, 2021
337f7e8
[squash] update baseline
acutmore Sep 16, 2021
d059c15
[squash] inline variable as per PR suggestion
acutmore Sep 16, 2021
79eeebe
[squash] test targets both esnext and es2020 as per PR comment
acutmore Sep 16, 2021
125df93
switch to using a binary expression
acutmore Sep 17, 2021
c6b2a21
Merge remote-tracking branch 'origin/main' into private-field-in-in
acutmore Sep 17, 2021
320bc00
[squash] PrivateIdentifier now extends PrimaryExpression
acutmore Sep 17, 2021
cc80c7d
[squash] accept public api baseline changes
acutmore Sep 17, 2021
ebbb063
[squash] classPrivateFieldInHelper now has documentation
acutmore Sep 17, 2021
ea4fd4b
[squash] type-check now follows existing in-expression path
acutmore Sep 20, 2021
8b78f01
[squash] parser now follows existing binaryExpression path
acutmore Sep 20, 2021
01c7042
[squash] correct typo in comment
acutmore Sep 21, 2021
fc2b262
[squash] no longer use esNext flag
acutmore Sep 21, 2021
c007a12
[squash] swap 'reciever, state' helper params
acutmore Sep 21, 2021
40bd336
[squash] remove change to parenthesizerRules
acutmore Sep 21, 2021
7982164
[squash] apply suggested changes to checker
acutmore Sep 21, 2021
1cd313f
[squash] remove need for assertion in fixSpelling
acutmore Sep 21, 2021
97f7d30
[squash] improve comment hint in test
acutmore Sep 21, 2021
e672957
[squash] fix comment typos
acutmore Sep 22, 2021
2b7425d
[squash] add flow-test for Foo | FooSub | Bar
acutmore Sep 22, 2021
52b9f2a
[squash] add checkExternalEmitHelpers call and new test case
acutmore Sep 22, 2021
476bf24
[squash] simplify and correct parser
acutmore Sep 22, 2021
be26d0a
[squash] move most of the added checker logic to expression level
acutmore Sep 22, 2021
f7ddce5
[squash] always error when privateId could not be resolved
acutmore Sep 22, 2021
01e0e60
[squash] reword comment
acutmore Sep 22, 2021
913d044
[squash] fix codeFixSpelling test
acutmore Sep 22, 2021
7c49552
[squash] do less work
acutmore Sep 22, 2021
c6b039f
store symbol by priateId not binaryExpression
acutmore Sep 23, 2021
6f56c6a
moved parsePrivateIdentifier into parsePrimaryExpression
acutmore Sep 23, 2021
c3b6c2a
[squash] checkInExpressionn bails out early on silentNeverType
acutmore Sep 23, 2021
5fbb2da
[squash] more detailed error messages
acutmore Sep 23, 2021
c924a51
[squash] resolves conflict in diagnosticMessages.json
acutmore Sep 23, 2021
27d494d
Merge remote-tracking branch 'origin/main' into private-field-in-in-b…
acutmore Sep 23, 2021
33c3b55
[squash] update baseline for importHelpersES6
acutmore Sep 23, 2021
e3c25c9
[squash] remove redundent if and comment from parser
acutmore Sep 23, 2021
74e56a6
[squash] split up grammar/check/symbolLookup
acutmore Sep 23, 2021
8447934
[squash] reword message for existing left side of in-expression error
acutmore Sep 23, 2021
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
77 changes: 68 additions & 9 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23846,6 +23846,9 @@ namespace ts {
case SyntaxKind.InstanceOfKeyword:
return narrowTypeByInstanceof(type, expr, assumeTrue);
case SyntaxKind.InKeyword:
if (isPrivateIdentifier(expr.left)) {
return narrowTypeByPrivateIdentifierInInExpression(type, expr, assumeTrue);
}
const target = getReferenceCandidate(expr.right);
const leftType = getTypeOfNode(expr.left);
if (leftType.flags & TypeFlags.StringLiteral) {
Expand Down Expand Up @@ -23876,6 +23879,25 @@ namespace ts {
return type;
}

function narrowTypeByPrivateIdentifierInInExpression(type: Type, expr: BinaryExpression, assumeTrue: boolean): Type {
const target = getReferenceCandidate(expr.right);
if (!isMatchingReference(reference, target)) {
return type;
}

const privateId = expr.left;
Debug.assertNode(privateId, isPrivateIdentifier);
const symbol = lookupSymbolForPrivateIdentifierDeclaration(privateId.escapedText, privateId);
Copy link
Member

Choose a reason for hiding this comment

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

Shouldn't this be cached on the private identifier? Is there a call that caches? lookupSymbolForPrivateIdentifierDeclaration doesn't, so I guess that there is a wrapper for it that does. This code should call that wrapper instead. (see comment about creating checkPrivateIdentifier -- that is probably the right place if it doesn't already exist.)

Copy link
Member

Choose a reason for hiding this comment

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

Thinking about this overnight, it's probably enough to create checkPrivateIdentifier in this PR, and fix caching later. The problem predates this PR, but it means that programs with lots of private identifers are likely to have performance problems.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

You were right, the symbol was cached. So not having to re-resolve the symbol when narrowing now.

Right now I am caching the symbol on the BinaryExpression parent. The only reason I am doing this is because otherwise 'findAllRefs' doesn't see the symbol. everything else seems to work if I store the symbol based on the PrivateIdentifier. I'd like to address this, I'm thinking there must be a 'set' that PrivateIds need to be added so they are valid places for 'findAllRefs' to search.

Copy link
Member

Choose a reason for hiding this comment

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

Should we be concerned that a code path could reach this line of code before the symbol is set?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I could put in a call to checkPrivateIdentifierExpression if the symbol comes back undefined to be safe.

Copy link
Member

Choose a reason for hiding this comment

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

For find-all-refs, you're possibly being tripped up by the fact PrivateIdentifier isn't handled by isExpressionNode:

export function isExpressionNode(node: Node): boolean {

called from here:

https://github.com/microsoft/TypeScript/blob/7c49552cd516da620b903edccc61af54d1872c3b/src/compiler/checker.ts#L40232

For an Identifier, we would perform a normal name resolution:

https://github.com/microsoft/TypeScript/blob/7c49552cd516da620b903edccc61af54d1872c3b/src/compiler/checker.ts#L40245

Instead, you're storing the symbol on the parent binary expression and then looking it up at https://github.com/microsoft/TypeScript/blob/7c49552cd516da620b903edccc61af54d1872c3b/src/compiler/checker.ts#L40284, which seems strange. We don't normally store the symbol on Identifier references, since they can have multiple meanings, so it seems a bit strange to cache it for PrivateIdentifier (despite @sandersn's comment). However, since a PrivateIdentifier can't have anything other than a value meaning currently, we could probably store it on the NodeLinks for the id itself, rather than its parent expression.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

thanks! Yes it was the isExpressionNode that was causing the find-all-refs issue. I had removed the old PrivateIdentifierInInExpression syntax kind from that predicate but not put PrivateIdentifiers in.

I rather than PrivateIdentifier always returning true for isExpressionNode, it only returns true if it's in a valid position to be an 'expression'. This means the checker can use isExpressionNode for the grammer checks.
I did think about utilities.ts exporting a new more explicit isPrivateIdentifierInValidExpressionPosition predicate for the checker to use instead but that didn't feel like it added much value.

I am now caching the resolved symbol on the privateId itself, not the parent. As private-identifiers can only reference one member of a syntactically outer class, and not come from a different script/module. This seems safe.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Should we be concerned that a code path could reach this line of code before the symbol is set?

While this wasn't happening in the tests. It did happen via the language server, and wasn't getting narrowed types on hover in vscode. I've added a call to checkPrivateIdentifierExpression when the symbol is undefined which fixes the issue.

Is there an alternative approach than checking for undefined, to see if the type-check has already happened? For the case when getting undefined is actually a cache-hit but because of a typo in the privateIdentifier it has no symbol to resolve to - yet checkPrivateIdentifierExpression would keep being called.

if (symbol === undefined) {
return type;
}
const classSymbol = symbol.parent!;
const targetType = hasStaticModifier(Debug.checkDefined(symbol.valueDeclaration, "should always have a declaration"))
? getTypeOfSymbol(classSymbol) as InterfaceType
: getDeclaredTypeOfSymbol(classSymbol);
return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom);
}

function narrowTypeByOptionalChainContainment(type: Type, operator: SyntaxKind, value: Expression, assumeTrue: boolean): Type {
// We are in a branch of obj?.foo === value (or any one of the other equality operators). We narrow obj as follows:
// When operator is === and type of value excludes undefined, null and undefined is removed from type of obj in true branch.
Expand Down Expand Up @@ -32023,14 +32045,46 @@ namespace ts {
}

function checkInExpression(left: Expression, right: Expression, leftType: Type, rightType: Type): Type {
if (leftType === silentNeverType || rightType === silentNeverType) {
return silentNeverType;
if (isPrivateIdentifier(left)) {
const lexicallyScopedSymbol = lookupSymbolForPrivateIdentifierDeclaration(left.escapedText, left);
Copy link
Member

Choose a reason for hiding this comment

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

You should add a call to checkExternalEmitHelpers , and need to add a ClassPrivateFieldIn flag to ExternalEmitHelpers in types.ts.

NOTE: in checkExternalEmitHelpers you don't need a branch like ExternalEmitHelpers.ClassPrivateFieldGet for ClassPrivateFieldIn. Those branches are checking for version-specific overloads from tslib which isn't needed in your case.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

done and added a test case for this.

if (lexicallyScopedSymbol === undefined) {
if (!getContainingClass(left)) {
error(left, Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
}
else {
const suggestion = getSuggestedSymbolForNonexistentProperty(left, rightType);
if (suggestion) {
const suggestedName = symbolName(suggestion);
error(left, Diagnostics.Cannot_find_name_0_Did_you_mean_1, diagnosticName(left), suggestedName);
}
else {
error(left, Diagnostics.Cannot_find_name_0, diagnosticName(left));
}
}
return anyType;
}

markPropertyAsReferenced(lexicallyScopedSymbol, /* nodeForCheckWriteOnly: */ undefined, /* isThisAccess: */ false);
Copy link
Member

Choose a reason for hiding this comment

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

most of this branch ought to be in a function called checkPrivateIdentifier that is shared between here and checkPropertyAccessExpressionOrQualifiedName/checkPrivateIdentifierPropertyAccess.

Specifically, it looks strange to markPropertyAsReferenced and set resolvedSymbol here -- checkExpression is normally what does that. If checkExpression can't directly call checkPrivateIdentifier, then the checkBinaryExpression trampoline should decide when to call checkPrivateIdentifier with whatever context is needed; then this function can stick to checking types.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I've added a checkPrivateIdentifierExpression, and added it to the checkExpression path. So the PrivateId is checked on it's own as usual for the LHS of a binary-expression, and also when we have parsed it in invalid situations. This function is what sets the resolvedSymbol, akin to a regular identifier.
I named it differently because it's not being used in checkPrivateIdentifierPropertyAccess - I wanted to make it clearer that it is only called when we are checking the PrivateId as an expression.
Though I was able to increase some of the shared code by switching to reportNonexistentProperty which is shared by checkPropertyAccessExpressionOrQualifiedName.

There is still some added logic to checkInExpression, as at this point we now have the RHS type too.

getNodeLinks(left.parent).resolvedSymbol = lexicallyScopedSymbol;
if (rightType === silentNeverType) {
return silentNeverType;
}
}
else {
if (leftType === silentNeverType || rightType === silentNeverType) {
return silentNeverType;
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
// which provides us with the oppotunity to emit more detailed errors
// which provides us with the opportunity to emit more detailed errors

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Regretting that when I disabled all of my extensions to free up some CPU I also disabled the code-spell-checker. I'll reenable, as mistakes like this shouldn't be getting through to the PR.

}
leftType = checkNonNullType(leftType, left);
// TypeScript 1.0 spec (April 2014): 4.15.5
// Require the left operand to be of type Any, the String primite type, or the Number primite type.
if (!(allTypesAssignableToKind(leftType, TypeFlags.StringLike | TypeFlags.NumberLike | TypeFlags.ESSymbolLike) ||
isTypeAssignableToKind(leftType, TypeFlags.Index | TypeFlags.TemplateLiteral | TypeFlags.StringMapping | TypeFlags.TypeParameter))) {
error(left, Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol);
}
}
leftType = checkNonNullType(leftType, left);
rightType = checkNonNullType(rightType, right);
// TypeScript 1.0 spec (April 2014): 4.15.5
// The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type,
// and the right operand to be
// The in operator requires the right operand to be
//
// 1. assignable to the non-primitive type,
// 2. an unconstrained type parameter,
Expand All @@ -32048,10 +32102,6 @@ namespace ts {
// unless *all* instantiations would result in an error.
//
// The result is always of the Boolean primitive type.
if (!(allTypesAssignableToKind(leftType, TypeFlags.StringLike | TypeFlags.NumberLike | TypeFlags.ESSymbolLike) ||
isTypeAssignableToKind(leftType, TypeFlags.Index | TypeFlags.TemplateLiteral | TypeFlags.StringMapping | TypeFlags.TypeParameter))) {
error(left, Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol);
}
const rightTypeConstraint = getConstraintOfType(rightType);
if (!allTypesAssignableToKind(rightType, TypeFlags.NonPrimitive | TypeFlags.InstantiableNonPrimitive) ||
rightTypeConstraint && (
Expand Down Expand Up @@ -40219,6 +40269,15 @@ namespace ts {
return resolveEntityName(name as Identifier, /*meaning*/ SymbolFlags.FunctionScopedVariable);
}

if (isPrivateIdentifier(name) && isBinaryExpression(name.parent)) {
const links = getNodeLinks(name.parent);
if (links.resolvedSymbol) {
return links.resolvedSymbol;
}
checkBinaryExpression(name.parent, CheckMode.Normal);
return links.resolvedSymbol;
}

return undefined;
}

Expand Down
2 changes: 2 additions & 0 deletions src/compiler/emitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1680,6 +1680,8 @@ namespace ts {
// Identifiers
case SyntaxKind.Identifier:
return emitIdentifier(node as Identifier);
case SyntaxKind.PrivateIdentifier:
return emitPrivateIdentifier(node as PrivateIdentifier);

// Expressions
case SyntaxKind.ArrayLiteralExpression:
Expand Down
30 changes: 30 additions & 0 deletions src/compiler/factory/emitHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ namespace ts {
// Class Fields Helpers
createClassPrivateFieldGetHelper(receiver: Expression, state: Identifier, kind: PrivateIdentifierKind, f: Identifier | undefined): Expression;
createClassPrivateFieldSetHelper(receiver: Expression, state: Identifier, value: Expression, kind: PrivateIdentifierKind, f: Identifier | undefined): Expression;
createClassPrivateFieldInHelper(state: Identifier, receiver: Expression): Expression;
}

export function createEmitHelperFactory(context: TransformationContext): EmitHelperFactory {
Expand Down Expand Up @@ -75,6 +76,7 @@ namespace ts {
// Class Fields Helpers
createClassPrivateFieldGetHelper,
createClassPrivateFieldSetHelper,
createClassPrivateFieldInHelper
};

/**
Expand Down Expand Up @@ -395,6 +397,10 @@ namespace ts {
return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldSet"), /*typeArguments*/ undefined, args);
}

function createClassPrivateFieldInHelper(state: Identifier, receiver: Expression) {
context.requestEmitHelper(classPrivateFieldInHelper);
return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldIn"), /* typeArguments*/ undefined, [state, receiver]);
}
}

/* @internal */
Expand Down Expand Up @@ -961,6 +967,29 @@ namespace ts {
};`
};

/**
* Parameters:
* @param state — One of the following:
* - A WeakMap when the member is a private instance field.
* - A WeakSet when the member is a private instance method or accessor.
* - A function value that should be the undecorated class constructor when the member is a private static field, method, or accessor.
* @param receiver — The object being checked if it has the private member.
*
* Usage:
* This helper is used to transform `#field in expression` to
* `__classPrivateFieldIn(expression, <weakMap/weakSet/constructor>)`
Copy link
Member

Choose a reason for hiding this comment

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

This comment needs to be updated.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

thanks!

*/
export const classPrivateFieldInHelper: UnscopedEmitHelper = {
name: "typescript:classPrivateFieldIn",
importName: "__classPrivateFieldIn",
scoped: false,
text: `
var __classPrivateFieldIn = (this && this.__classPrivateFieldIn) || function(state, receiver) {
if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object");
return typeof state === "function" ? receiver === state : state.has(receiver);
};`
};

let allUnscopedEmitHelpers: ReadonlyESMap<string, UnscopedEmitHelper> | undefined;

export function getAllUnscopedEmitHelpers() {
Expand All @@ -986,6 +1015,7 @@ namespace ts {
exportStarHelper,
classPrivateFieldGetHelper,
classPrivateFieldSetHelper,
classPrivateFieldInHelper,
createBindingHelper,
setModuleDefaultHelper
], helper => helper.name));
Expand Down
2 changes: 1 addition & 1 deletion src/compiler/factory/parenthesizerRules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -452,4 +452,4 @@ namespace ts {
parenthesizeConstituentTypesOfUnionOrIntersectionType: nodes => cast(nodes, isNodeArray),
parenthesizeTypeArguments: nodes => nodes && cast(nodes, isNodeArray),
};
}
}
22 changes: 18 additions & 4 deletions src/compiler/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4602,8 +4602,15 @@ namespace ts {
}

function parseBinaryExpressionOrHigher(precedence: OperatorPrecedence): Expression {
// parse a BinaryExpression the LHS is either:
// 1) a PrivateIdentifier when 'in' flag allowed and lookahead matches 'PrivateIdentifier in'
// 2) a UnaryExpression

const pos = getNodePos();
const leftOperand = parseUnaryExpressionOrHigher();
const lookaheadMatchesPrivateIdentifierIn = token() === SyntaxKind.PrivateIdentifier && !inDisallowInContext() && lookAhead(nextTokenIsInKeyword);
const leftOperand = lookaheadMatchesPrivateIdentifierIn
? parsePrivateIdentifier()
: parseUnaryExpressionOrHigher();
return parseBinaryExpressionRest(precedence, leftOperand, pos);
}

Expand Down Expand Up @@ -4640,9 +4647,11 @@ namespace ts {
// ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand
// a ** b - c
// ^token; leftOperand = b. Return b to the caller as a rightOperand
const consumeCurrentOperator = token() === SyntaxKind.AsteriskAsteriskToken ?
newPrecedence >= precedence :
newPrecedence > precedence;
const isPrivateIdentifierInInExpression = token() === SyntaxKind.InKeyword && isPrivateIdentifier(leftOperand);
const consumeCurrentOperator = isPrivateIdentifierInInExpression ||
Copy link
Member

@sandersn sandersn Sep 21, 2021

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 better to parse a private identifier unconditionally and add a grammar error in checkPrivateIdentifier if the identifier's parent is incorrect. Currently, it becomes a lot more complicated to convince myself that binary expression parsing is correct.
Edit: This way -> Currently

This also means that

  1. The change in parseBinaryExpressionOrHigher is not needed.
  2. checkExpression will need to call checkPrivateIdentifier to make sure that all incorrect uses of private identifiers get errors.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

You are 100% on the money with this. Turns out the parsing was incorrect, and so is the parsing in v8 (about to raise a ticket).

I'm changing things to the way you said and it works much better.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Parser logic updated now. At first I thought going with this approach had broken the tests but turned out the tests were wrong, and this new approach leads to the correct result.

When I wrote the tests for this back in Febuary there were not implementations to try, and babel did not get the parsing right (they have now addressed these issues). So I unfortunately developed the wrong intuition for how this syntax should parse when nested within other expressions.

Did spot an issue in V8 when trying to compare to what they do: https://bugs.chromium.org/p/v8/issues/detail?id=12259

(token() === SyntaxKind.AsteriskAsteriskToken ?
newPrecedence >= precedence :
newPrecedence > precedence);

if (!consumeCurrentOperator) {
break;
Expand Down Expand Up @@ -6131,6 +6140,11 @@ namespace ts {
return (tokenIsIdentifierOrKeyword(token()) || token() === SyntaxKind.NumericLiteral || token() === SyntaxKind.BigIntLiteral || token() === SyntaxKind.StringLiteral) && !scanner.hasPrecedingLineBreak();
}

function nextTokenIsInKeyword() {
nextToken();
return token() === SyntaxKind.InKeyword;
}

function isDeclaration(): boolean {
while (true) {
switch (token()) {
Expand Down
26 changes: 26 additions & 0 deletions src/compiler/transformers/classFields.ts
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,29 @@ namespace ts {
return setOriginalNode(factory.createIdentifier(""), node);
}

/**
* Visits `#id in expr`
*/
function visitPrivateIdentifierInInExpression(node: BinaryExpression) {
if (!shouldTransformPrivateElementsOrClassStaticBlocks) {
return node;
}
const privId = node.left;
Debug.assertNode(privId, isPrivateIdentifier);
const info = accessPrivateIdentifier(privId);
if (info) {
const receiver = visitNode(node.right, visitor, isExpression);

return setOriginalNode(
context.getEmitHelperFactory().createClassPrivateFieldInHelper(info.brandCheckIdentifier, receiver),
node
);
}

// Private name has not been declared. Subsequent transformers will handle this error
return visitEachChild(node, visitor, context);
}

/**
* Visits the members of a class that has fields.
*
Expand Down Expand Up @@ -827,6 +850,9 @@ namespace ts {
}
}
}
if (node.operatorToken.kind === SyntaxKind.InKeyword && isPrivateIdentifier(node.left)) {
return visitPrivateIdentifierInInExpression(node);
}
return visitEachChild(node, visitor, context);
}

Expand Down
3 changes: 2 additions & 1 deletion src/compiler/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1209,7 +1209,8 @@ namespace ts {
readonly expression: Expression;
}

export interface PrivateIdentifier extends Node {
// Typed as a PrimaryExpression due to its presence in BinaryExpressions (#field in expr)
export interface PrivateIdentifier extends PrimaryExpression {
readonly kind: SyntaxKind.PrivateIdentifier;
// escaping not strictly necessary
// avoids gotchas in transforms and utils
Expand Down
1 change: 1 addition & 0 deletions src/compiler/utilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3706,6 +3706,7 @@ namespace ts {
case SyntaxKind.ThisKeyword:
case SyntaxKind.SuperKeyword:
case SyntaxKind.Identifier:
case SyntaxKind.PrivateIdentifier:
case SyntaxKind.NullKeyword:
case SyntaxKind.TrueKeyword:
case SyntaxKind.FalseKeyword:
Expand Down
4 changes: 4 additions & 0 deletions src/services/codefixes/fixSpelling.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,10 @@ namespace ts.codefix {
}
suggestedSymbol = checker.getSuggestedSymbolForNonexistentProperty(node, containingType);
}
else if (isBinaryExpression(parent) && parent.operatorToken.kind === SyntaxKind.InKeyword && parent.left === node && isPrivateIdentifier(node)) {
const receiverType = checker.getTypeAtLocation(parent.right);
suggestedSymbol = checker.getSuggestedSymbolForNonexistentProperty(node, receiverType);
}
else if (isQualifiedName(parent) && parent.right === node) {
const symbol = checker.getSymbolAtLocation(parent.left);
if (symbol && symbol.flags & SymbolFlags.Module) {
Expand Down
6 changes: 6 additions & 0 deletions src/services/services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -401,6 +401,12 @@ namespace ts {
public kind!: SyntaxKind.PrivateIdentifier;
public escapedText!: __String;
public symbol!: Symbol;
_primaryExpressionBrand: any;
_memberExpressionBrand: any;
_leftHandSideExpressionBrand: any;
_updateExpressionBrand: any;
_unaryExpressionBrand: any;
_expressionBrand: any;
constructor(_kind: SyntaxKind.PrivateIdentifier, pos: number, end: number) {
super(pos, end);
}
Expand Down
2 changes: 1 addition & 1 deletion tests/baselines/reference/api/tsserverlibrary.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -666,7 +666,7 @@ declare namespace ts {
readonly parent: Declaration;
readonly expression: Expression;
}
export interface PrivateIdentifier extends Node {
export interface PrivateIdentifier extends PrimaryExpression {
readonly kind: SyntaxKind.PrivateIdentifier;
readonly escapedText: __String;
}
Expand Down
2 changes: 1 addition & 1 deletion tests/baselines/reference/api/typescript.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -666,7 +666,7 @@ declare namespace ts {
readonly parent: Declaration;
readonly expression: Expression;
}
export interface PrivateIdentifier extends Node {
export interface PrivateIdentifier extends PrimaryExpression {
readonly kind: SyntaxKind.PrivateIdentifier;
readonly escapedText: __String;
}
Expand Down
Loading