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 all 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
89 changes: 82 additions & 7 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23856,6 +23856,9 @@ namespace ts {
case SyntaxKind.InstanceOfKeyword:
return narrowTypeByInstanceof(type, expr, assumeTrue);
case SyntaxKind.InKeyword:
if (isPrivateIdentifier(expr.left)) {
return narrowTypeByPrivateIdentifierInInExpression(type, expr, assumeTrue);
}
rbuckton marked this conversation as resolved.
Show resolved Hide resolved
const target = getReferenceCandidate(expr.right);
const leftType = getTypeOfNode(expr.left);
if (leftType.flags & TypeFlags.StringLiteral) {
Expand Down Expand Up @@ -23886,6 +23889,24 @@ namespace ts {
return type;
}
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.


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

Debug.assertNode(expr.left, isPrivateIdentifier);
const symbol = getSymbolForPrivateIdentifierExpression(expr.left);
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 @@ -27730,6 +27751,40 @@ namespace ts {
}
}

function checkGrammarPrivateIdentifierExpression(privId: PrivateIdentifier): boolean {
if (!getContainingClass(privId)) {
return grammarErrorOnNode(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

}
if (!isExpressionNode(privId)) {
sandersn marked this conversation as resolved.
Show resolved Hide resolved
return grammarErrorOnNode(privId, Diagnostics.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);
}
if (!getSymbolForPrivateIdentifierExpression(privId)) {
return grammarErrorOnNode(privId, Diagnostics.Cannot_find_name_0, idText(privId));
}
return false;
}

function checkPrivateIdentifierExpression(privId: PrivateIdentifier): Type {
checkGrammarPrivateIdentifierExpression(privId);
const symbol = getSymbolForPrivateIdentifierExpression(privId);
if (symbol) {
markPropertyAsReferenced(symbol, /* nodeForCheckWriteOnly: */ undefined, /* isThisAccess: */ false);
}
return anyType;
}

function getSymbolForPrivateIdentifierExpression(privId: PrivateIdentifier): Symbol | undefined {
if (!isExpressionNode(privId)) {
return undefined;
}

const links = getNodeLinks(privId);
if (links.resolvedSymbol === undefined) {
links.resolvedSymbol = lookupSymbolForPrivateIdentifierDeclaration(privId.escapedText, privId);
}
return links.resolvedSymbol;
}

function getPrivateIdentifierPropertyOfType(leftType: Type, lexicallyScopedIdentifier: Symbol): Symbol | undefined {
return getPropertyOfType(leftType, lexicallyScopedIdentifier.escapedName);
}
Expand Down Expand Up @@ -32050,11 +32105,29 @@ namespace ts {
if (leftType === silentNeverType || rightType === silentNeverType) {
return silentNeverType;
sandersn marked this conversation as resolved.
Show resolved Hide resolved
}
leftType = checkNonNullType(leftType, left);
if (isPrivateIdentifier(left)) {
if (languageVersion < ScriptTarget.ESNext) {
checkExternalEmitHelpers(left, ExternalEmitHelpers.ClassPrivateFieldIn);
}
// Unlike in 'checkPrivateIdentifierExpression' we now have access to the RHS type
// which provides us with the opportunity to emit more detailed errors
if (!getNodeLinks(left).resolvedSymbol && getContainingClass(left)) {
const isUncheckedJS = isUncheckedJSSuggestion(left, rightType.symbol, /*excludeClasses*/ true);
reportNonexistentProperty(left, rightType, isUncheckedJS);
}
sandersn marked this conversation as resolved.
Show resolved Hide resolved
}
else {
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_a_private_identifier_or_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 @@ -32072,10 +32145,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 @@ -33457,6 +33526,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 @@ -40236,6 +40307,9 @@ namespace ts {
}
return result;
}
else if (isPrivateIdentifier(name)) {
return getSymbolForPrivateIdentifierExpression(name);
}
else if (name.kind === SyntaxKind.PropertyAccessExpression || name.kind === SyntaxKind.QualifiedName) {
const links = getNodeLinks(name);
if (links.resolvedSymbol) {
Expand Down Expand Up @@ -41651,6 +41725,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
6 changes: 5 additions & 1 deletion src/compiler/diagnosticMessages.json
Original file line number Diff line number Diff line change
Expand Up @@ -1392,6 +1392,10 @@
"category": "Message",
"code": 1450
},
"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": {
"category": "Error",
"code": 1451
},

"The types of '{0}' are incompatible between these types.": {
"category": "Error",
Expand Down Expand Up @@ -1654,7 +1658,7 @@
"category": "Error",
"code": 2359
},
"The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'.": {
"The left-hand side of an 'in' expression must be a private identifier or of type 'any', 'string', 'number', or 'symbol'.": {
"category": "Error",
"code": 2360
},
Expand Down
2 changes: 2 additions & 0 deletions src/compiler/emitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1684,6 +1684,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),
};
}
}
2 changes: 2 additions & 0 deletions src/compiler/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5617,6 +5617,8 @@ namespace ts {
break;
case SyntaxKind.TemplateHead:
return parseTemplateExpression(/* isTaggedTemplate */ false);
case SyntaxKind.PrivateIdentifier:
return parsePrivateIdentifier();
}

return parseIdentifier(Diagnostics.Expression_expected);
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 @@ -1214,7 +1214,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 @@ -6853,7 +6854,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
3 changes: 3 additions & 0 deletions src/compiler/utilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1949,6 +1949,8 @@ namespace ts {
node = node.parent;
}
return node.parent.kind === SyntaxKind.TypeQuery || isJSDocLinkLike(node.parent) || isJSDocNameReference(node.parent) || isJSDocMemberName(node.parent) || isJSXTagName(node);
case SyntaxKind.PrivateIdentifier:
return isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === SyntaxKind.InKeyword;
case SyntaxKind.Identifier:
if (node.parent.kind === SyntaxKind.TypeQuery || isJSDocLinkLike(node.parent) || isJSDocNameReference(node.parent) || isJSDocMemberName(node.parent) || isJSXTagName(node)) {
return true;
Expand Down Expand Up @@ -3706,6 +3708,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
1 change: 1 addition & 0 deletions src/compiler/utilitiesPublic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1516,6 +1516,7 @@ namespace ts {
case SyntaxKind.ClassExpression:
case SyntaxKind.FunctionExpression:
case SyntaxKind.Identifier:
case SyntaxKind.PrivateIdentifier: // technically this is only an Expression if it's in a `#field in expr` BinaryExpression
case SyntaxKind.RegularExpressionLiteral:
case SyntaxKind.NumericLiteral:
case SyntaxKind.BigIntLiteral:
Expand Down
4 changes: 2 additions & 2 deletions src/services/codefixes/fixForgottenThisPropertyAccess.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ namespace ts.codefix {
const didYouMeanStaticMemberCode = Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code;
const errorCodes = [
Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code,
Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies.code,
Diagnostics.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.code,
didYouMeanStaticMemberCode,
];
registerCodeFix({
Expand Down 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