Skip to content
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

ES private field check #44648

Merged
merged 45 commits into from
Sep 24, 2021
Merged
Show file tree
Hide file tree
Changes from 35 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
85 changes: 78 additions & 7 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 = getNodeLinks(privateId.parent).resolvedSymbol;
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 @@ -27715,6 +27737,27 @@ namespace ts {
}
}

function checkPrivateIdentifierExpression(privId: PrivateIdentifier): Type {
// The only valid position for a PrivateIdentifier to appear as an expression is on the left side of
// the `#field in expr` BinaryExpression
const isPrivateFieldInInExpression = isBinaryExpression(privId.parent)
&& privId.parent.left === privId
&& privId.parent.operatorToken.kind === SyntaxKind.InKeyword;
let symbolResolved = false;
if (isPrivateFieldInInExpression) {
const lexicallyScopedSymbol = lookupSymbolForPrivateIdentifierDeclaration(privId.escapedText, privId);
if (lexicallyScopedSymbol) {
symbolResolved = true;
markPropertyAsReferenced(lexicallyScopedSymbol, /* nodeForCheckWriteOnly: */ undefined, /* isThisAccess: */ false);
getNodeLinks(privId.parent).resolvedSymbol = lexicallyScopedSymbol;
}
}
if (!symbolResolved) {
error(privId, Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This error is not 100% correct. We could be inside a class body though this does match the existing errors when handling invalid privateIds.

class C {
    f() {
        return #hello; // Private identifiers are not allowed outside class bodies.
    }
}

https://www.typescriptlang.org/play?#code/MYGwhgzhAEDC0G8BQ1XQGYAoCUiVoICcBTAFwFdCA7aAYgAtiQQB7Abn1QF8keg

Copy link
Member

@rbuckton rbuckton Sep 22, 2021

Choose a reason for hiding this comment

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

This seems like something we should be reporting this as a grammar error. Something like:

Private identifiers are only allowed in class bodies and may only be used as part of a class member declaration, property access, or on the left-hand-side of an 'in' expression

@DanielRosenwasser any thoughts on wording?

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 that new error, and split the check into 3 levels.

  1. are we in a class, otherwise there is no valid way to have a private identifier
  2. is the privateIdentifier in a valid position
  3. does the privateIdentifier match a private member

}
return anyType;
sandersn marked this conversation as resolved.
Show resolved Hide resolved
}

function getPrivateIdentifierPropertyOfType(leftType: Type, lexicallyScopedIdentifier: Symbol): Symbol | undefined {
return getPropertyOfType(leftType, lexicallyScopedIdentifier.escapedName);
}
Expand Down Expand Up @@ -32023,14 +32066,34 @@ namespace ts {
}

function checkInExpression(left: Expression, right: Expression, leftType: Type, rightType: Type): Type {
const privIdOnLeft = isPrivateIdentifier(left);
if (privIdOnLeft) {
if (languageVersion < ScriptTarget.ESNext) {
checkExternalEmitHelpers(left, ExternalEmitHelpers.ClassPrivateFieldIn);
}
rbuckton marked this conversation as resolved.
Show resolved Hide resolved
// Unlike in 'checkPrivateIdentifierExpression' we now have access to the RHS type
// which provides us with the oppotunity to emit more detailed errors
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.

const symbol = getNodeLinks(left.parent).resolvedSymbol;
if (!symbol) {
const isUncheckedJS = isUncheckedJSSuggestion(left, rightType.symbol, /*excludeClasses*/ true);
reportNonexistentProperty(left, rightType, isUncheckedJS);
rbuckton marked this conversation as resolved.
Show resolved Hide resolved
}
rbuckton marked this conversation as resolved.
Show resolved Hide resolved
}
if (leftType === silentNeverType || rightType === silentNeverType) {
rbuckton marked this conversation as resolved.
Show resolved Hide resolved
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.

If we have a silentNeverType, we're generally in an inference path and bail out of checking. Instead of splitting up the function body around privIdOnLeft, should we just move this to the top of the function?

Copy link
Contributor Author

@acutmore acutmore Sep 22, 2021

Choose a reason for hiding this comment

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

I’ve been meaning to look into the difference between never and silentNever, thanks!

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 moved this to the top now. I hadn't done that because I thought we wouldn't get the checkExternalEmitHelpers error when the RHS was never but I checked and as you suggested - this is still OK as the silentNeverType has a different use case.

leftType = checkNonNullType(leftType, left);
if (!privIdOnLeft) {
leftType = checkNonNullType(leftType, left);
// TypeScript 1.0 spec (April 2014): 4.15.5
// Require the left operand to be of type Any, the String primitive type, or the Number 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);
}
}
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 +32111,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 @@ -33433,6 +33492,8 @@ namespace ts {
switch (kind) {
case SyntaxKind.Identifier:
return checkIdentifier(node as Identifier, checkMode);
case SyntaxKind.PrivateIdentifier:
return checkPrivateIdentifierExpression(node as PrivateIdentifier);
case SyntaxKind.ThisKeyword:
return checkThisExpression(node);
case SyntaxKind.SuperKeyword:
Expand Down Expand Up @@ -40219,6 +40280,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;
}
checkPrivateIdentifierExpression(name);
return links.resolvedSymbol;
}

return undefined;
}

Expand Down Expand Up @@ -41605,6 +41675,7 @@ namespace ts {
case ExternalEmitHelpers.MakeTemplateObject: return "__makeTemplateObject";
case ExternalEmitHelpers.ClassPrivateFieldGet: return "__classPrivateFieldGet";
case ExternalEmitHelpers.ClassPrivateFieldSet: return "__classPrivateFieldSet";
case ExternalEmitHelpers.ClassPrivateFieldIn: return "__classPrivateFieldIn";
case ExternalEmitHelpers.CreateBinding: return "__createBinding";
default: return Debug.fail("Unrecognized helper");
}
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(<weakMap/weakSet/constructor>, expression)`
*/
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);
sandersn marked this conversation as resolved.
Show resolved Hide resolved
};`
};

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),
};
}
}
8 changes: 8 additions & 0 deletions src/compiler/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4737,6 +4737,14 @@ namespace ts {
*
*/
function parseUnaryExpressionOrHigher(): UnaryExpression | BinaryExpression {
/**
* If we have a PrivateIdentifier, parse this unconditionally.
* A privateIdentifier is only valid on its own in the RelationalExpression: `#field in expr`.
* The checker will emit an error if this is not the case.
*/
if (token() === SyntaxKind.PrivateIdentifier) {
sandersn marked this conversation as resolved.
Show resolved Hide resolved
return parsePrivateIdentifier();
}
/**
* ES7 UpdateExpression:
* 1) LeftHandSideExpression[?Yield]
Expand Down
34 changes: 33 additions & 1 deletion src/compiler/transformers/classFields.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,15 +266,44 @@ namespace ts {

/**
* If we visit a private name, this means it is an undeclared private name.
* Replace it with an empty identifier to indicate a problem with the code.
* Replace it with an empty identifier to indicate a problem with the code,
* unless we are in a statement position - otherwise this will not trigger
* a SyntaxError.
*/
function visitPrivateIdentifier(node: PrivateIdentifier) {
if (!shouldTransformPrivateElementsOrClassStaticBlocks) {
return node;
}
if (isStatement(node.parent)) {
return node;
}
sandersn marked this conversation as resolved.
Show resolved Hide resolved
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);
Debug.assert(node.operatorToken.kind === SyntaxKind.InKeyword);
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 +856,9 @@ namespace ts {
}
}
}
if (node.operatorToken.kind === SyntaxKind.InKeyword && isPrivateIdentifier(node.left)) {
return visitPrivateIdentifierInInExpression(node);
}
return visitEachChild(node, visitor, context);
}

Expand Down
6 changes: 4 additions & 2 deletions 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 Expand Up @@ -6830,7 +6831,8 @@ namespace ts {
MakeTemplateObject = 1 << 18, // __makeTemplateObject (used for constructing template string array objects)
ClassPrivateFieldGet = 1 << 19, // __classPrivateFieldGet (used by the class private field transformation)
ClassPrivateFieldSet = 1 << 20, // __classPrivateFieldSet (used by the class private field transformation)
CreateBinding = 1 << 21, // __createBinding (use by the module transform for (re)exports and namespace imports)
ClassPrivateFieldIn = 1 << 21, // __classPrivateFieldIn (used by the class private field transformation)
CreateBinding = 1 << 22, // __createBinding (use by the module transform for (re)exports and namespace imports)
FirstEmitHelper = Extends,
LastEmitHelper = CreateBinding,

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
2 changes: 1 addition & 1 deletion src/services/codefixes/fixForgottenThisPropertyAccess.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ namespace ts.codefix {

function getInfo(sourceFile: SourceFile, pos: number, diagCode: number): Info | undefined {
const node = getTokenAtPosition(sourceFile, pos);
if (isIdentifier(node)) {
if (isIdentifier(node) || isPrivateIdentifier(node)) {
return { node, className: diagCode === didYouMeanStaticMemberCode ? getContainingClass(node)!.name!.text : undefined };
}
}
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