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 8 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
2 changes: 2 additions & 0 deletions src/compiler/binder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -881,6 +881,8 @@ namespace ts {
return (expr as PrefixUnaryExpression).operator === SyntaxKind.ExclamationToken && isNarrowingExpression((expr as PrefixUnaryExpression).operand);
case SyntaxKind.TypeOfExpression:
return isNarrowingExpression((expr as TypeOfExpression).expression);
case SyntaxKind.PrivateIdentifierInInExpression:
return isNarrowingExpression((expr as PrivateIdentifierInInExpression).expression);
}
return false;
}
Expand Down
103 changes: 97 additions & 6 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23653,6 +23653,26 @@ namespace ts {
return type;
}

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

const privateId = expr.name;
const symbol = lookupSymbolForPrivateIdentifierDeclaration(privateId.escapedText, privateId);
if (symbol === undefined) {
return type;
}
const classSymbol = symbol.parent!;
const classDecl = symbol.valueDeclaration;
Debug.assert(classDecl, "should always have a declaration");
const targetType = hasStaticModifier(classDecl)
acutmore marked this conversation as resolved.
Show resolved Hide resolved
? 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 @@ -24101,6 +24121,8 @@ namespace ts {
return narrowType(type, (expr as ParenthesizedExpression | NonNullExpression).expression, assumeTrue);
case SyntaxKind.BinaryExpression:
return narrowTypeByBinaryExpression(type, expr as BinaryExpression, assumeTrue);
case SyntaxKind.PrivateIdentifierInInExpression:
return narrowTypeByPrivateIdentifierInInExpression(type, expr as PrivateIdentifierInInExpression, assumeTrue);
case SyntaxKind.PrefixUnaryExpression:
if ((expr as PrefixUnaryExpression).operator === SyntaxKind.ExclamationToken) {
return narrowType(type, (expr as PrefixUnaryExpression).operand, !assumeTrue);
Expand Down Expand Up @@ -27860,16 +27882,36 @@ namespace ts {
return getSpellingSuggestionForName(name, arrayFrom(getMembersOfSymbol(baseType.symbol).values()), SymbolFlags.ClassMember);
}

function getSuggestedSymbolForNonexistentProperty(name: Identifier | PrivateIdentifier | string, containingType: Type): Symbol | undefined {
function getSuggestedSymbolForNonexistentProperty(propertyName: Identifier | PrivateIdentifier | string, containingType: Type): Symbol | undefined {
let props = getPropertiesOfType(containingType);
if (typeof name !== "string") {
const parent = name.parent;
let name: string;
if (typeof propertyName === "string") {
name = propertyName;
}
else {
name = idText(propertyName);
acutmore marked this conversation as resolved.
Show resolved Hide resolved
const parent = propertyName.parent;
if (isPropertyAccessExpression(parent)) {
props = filter(props, prop => isValidPropertyAccessForCompletions(parent, containingType, prop));
}
name = idText(name);
}
return getSpellingSuggestionForName(name, props, SymbolFlags.Value);
const suggestion = getSpellingSuggestionForName(name, props, SymbolFlags.Value);
if (suggestion) {
return suggestion;
}

if (typeof propertyName !== "string" && isPrivateIdentifier(propertyName)) {
const privateIdentifiers: Symbol[] = [];
forEachEnclosingClass(propertyName, (klass: ClassLikeDeclaration) => {
forEach(klass.members, member => {
acutmore marked this conversation as resolved.
Show resolved Hide resolved
if (isPrivateIdentifierClassElementDeclaration(member)) {
privateIdentifiers.push(member.symbol);
}
});
});
return getSpellingSuggestionForName(name, privateIdentifiers, SymbolFlags.Value);
}
return undefined;
}

function getSuggestedSymbolForNonexistentJSXAttribute(name: Identifier | PrivateIdentifier | string, containingType: Type): Symbol | undefined {
Expand Down Expand Up @@ -31668,6 +31710,11 @@ namespace ts {
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);
}
checkInExpressionRHS(right, rightType);
return booleanType;
}

function checkInExpressionRHS(right: Expression, rightType: Type) {
const rightTypeConstraint = getConstraintOfType(rightType);
if (!allTypesAssignableToKind(rightType, TypeFlags.NonPrimitive | TypeFlags.InstantiableNonPrimitive) ||
rightTypeConstraint && (
Expand All @@ -31677,7 +31724,6 @@ namespace ts {
) {
error(right, Diagnostics.The_right_hand_side_of_an_in_expression_must_not_be_a_primitive);
}
return booleanType;
}

function checkObjectLiteralAssignment(node: ObjectLiteralExpression, sourceType: Type, rightIsThis?: boolean): Type {
Expand Down Expand Up @@ -31914,6 +31960,40 @@ namespace ts {
return (target.flags & TypeFlags.Nullable) !== 0 || isTypeComparableTo(source, target);
}

function checkPrivateIdentifierInInExpression(node: PrivateIdentifierInInExpression, checkMode?: CheckMode) {
const privateId = node.name;
const exp = node.expression;
let rightType = checkExpression(exp, checkMode);

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

markPropertyAsReferenced(lexicallyScopedSymbol, /* nodeForCheckWriteOnly: */ undefined, /* isThisAccess: */ false);
getNodeLinks(node).resolvedSymbol = lexicallyScopedSymbol;

if (rightType === silentNeverType) {
return silentNeverType;
}
rightType = checkNonNullType(rightType, exp);
checkInExpressionRHS(exp, rightType);
return booleanType;
}

function createCheckBinaryExpression() {
interface WorkArea {
readonly checkMode: CheckMode | undefined;
Expand Down Expand Up @@ -33104,6 +33184,8 @@ namespace ts {
return checkPostfixUnaryExpression(node as PostfixUnaryExpression);
case SyntaxKind.BinaryExpression:
return checkBinaryExpression(node as BinaryExpression, checkMode);
case SyntaxKind.PrivateIdentifierInInExpression:
return checkPrivateIdentifierInInExpression(node as PrivateIdentifierInInExpression, checkMode);
case SyntaxKind.ConditionalExpression:
return checkConditionalExpression(node as ConditionalExpression, checkMode);
case SyntaxKind.SpreadElement:
Expand Down Expand Up @@ -39603,6 +39685,15 @@ namespace ts {
return resolveEntityName(name as Identifier, /*meaning*/ SymbolFlags.FunctionScopedVariable);
}

if (isPrivateIdentifier(name) && isPrivateIdentifierInInExpression(name.parent)) {
const links = getNodeLinks(name.parent);
if (links.resolvedSymbol) {
return links.resolvedSymbol;
}
checkPrivateIdentifierInInExpression(name.parent);
return links.resolvedSymbol;
}

return undefined;
}

Expand Down
20 changes: 20 additions & 0 deletions src/compiler/emitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1718,6 +1718,8 @@ namespace ts {
return emitPostfixUnaryExpression(node as PostfixUnaryExpression);
case SyntaxKind.BinaryExpression:
return emitBinaryExpression(node as BinaryExpression);
case SyntaxKind.PrivateIdentifierInInExpression:
return emitPrivateIdentifierInInExpression(node as PrivateIdentifierInInExpression);
case SyntaxKind.ConditionalExpression:
return emitConditionalExpression(node as ConditionalExpression);
case SyntaxKind.TemplateExpression:
Expand Down Expand Up @@ -2719,6 +2721,24 @@ namespace ts {
}
}

function emitPrivateIdentifierInInExpression(node: PrivateIdentifierInInExpression) {
const linesBeforeIn = getLinesBetweenNodes(node, node.name, node.inToken);
const linesAfterIn = getLinesBetweenNodes(node, node.inToken, node.expression);

emitLeadingCommentsOfPosition(node.name.pos);
emitPrivateIdentifier(node.name);
emitTrailingCommentsOfPosition(node.name.end);

writeLinesAndIndent(linesBeforeIn, /*writeSpaceIfNotIndenting*/ true);
emitLeadingCommentsOfPosition(node.inToken.pos);
writeTokenNode(node.inToken, writeKeyword);
emitTrailingCommentsOfPosition(node.inToken.end, /*prefixSpace*/ true);
writeLinesAndIndent(linesAfterIn, /*writeSpaceIfNotIndenting*/ true);

emit(node.expression);
decreaseIndentIf(linesBeforeIn, linesAfterIn);
}

function emitConditionalExpression(node: ConditionalExpression) {
const linesBeforeQuestion = getLinesBetweenNodes(node, node.condition, node.questionToken);
const linesAfterQuestion = getLinesBetweenNodes(node, node.questionToken, node.whenTrue);
Expand Down
18 changes: 18 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(receiver: Expression, state: Identifier): Expression;
rbuckton marked this conversation as resolved.
Show resolved Hide resolved
}

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(receiver: Expression, state: Identifier) {
rbuckton marked this conversation as resolved.
Show resolved Hide resolved
context.requestEmitHelper(classPrivateFieldInHelper);
return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldIn"), /* typeArguments*/ undefined, [receiver, state]);
}
}

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

export const classPrivateFieldInHelper: UnscopedEmitHelper = {
name: "typescript:classPrivateFieldIn",
importName: "__classPrivateFieldIn",
scoped: false,
text: `
var __classPrivateFieldIn = (this && this.__classPrivateFieldIn) || function(receiver, state) {
rbuckton marked this conversation as resolved.
Show resolved Hide resolved
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 +1003,7 @@ namespace ts {
exportStarHelper,
classPrivateFieldGetHelper,
classPrivateFieldSetHelper,
classPrivateFieldInHelper,
createBindingHelper,
setModuleDefaultHelper
], helper => helper.name));
Expand Down
30 changes: 30 additions & 0 deletions src/compiler/factory/nodeFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -445,6 +445,8 @@ namespace ts {
createMergeDeclarationMarker,
createSyntheticReferenceExpression,
updateSyntheticReferenceExpression,
createPrivateIdentifierInInExpression,
updatePrivateIdentifierInInExpression,
cloneNode,

// Lazily load factory methods for common operator factories and utilities
Expand Down Expand Up @@ -3123,6 +3125,34 @@ namespace ts {
: node;
}

// @api
function createPrivateIdentifierInInExpression(name: PrivateIdentifier, inToken: Token<SyntaxKind.InKeyword>, expression: Expression) {
const node = createBaseExpression<PrivateIdentifierInInExpression>(SyntaxKind.PrivateIdentifierInInExpression);
node.name = name;
node.inToken = inToken;
node.expression = expression;
node.transformFlags |=
propagateChildFlags(node.name) |
propagateChildFlags(node.inToken) |
propagateChildFlags(node.expression) |
TransformFlags.ContainsESNext;
return node;
}

// @api
function updatePrivateIdentifierInInExpression(
node: PrivateIdentifierInInExpression,
name: PrivateIdentifier,
inToken: Token<SyntaxKind.InKeyword>,
expression: Expression
): PrivateIdentifierInInExpression {
return node.name !== name
|| node.inToken !== inToken
|| node.expression !== expression
? update(createPrivateIdentifierInInExpression(name, inToken, expression), node)
: node;
}

//
// Misc
//
Expand Down
9 changes: 9 additions & 0 deletions src/compiler/factory/nodeTests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,11 @@ namespace ts {
return node.kind === SyntaxKind.EqualsGreaterThanToken;
}

/*@internal*/
export function isInKeyword(node: Node): node is InKeyword {
return node.kind === SyntaxKind.InKeyword;
}

// Identifiers

export function isIdentifier(node: Node): node is Identifier {
Expand Down Expand Up @@ -448,6 +453,10 @@ namespace ts {
return node.kind === SyntaxKind.CommaListExpression;
}

export function isPrivateIdentifierInInExpression(node: Node): node is PrivateIdentifierInInExpression {
return node.kind === SyntaxKind.PrivateIdentifierInInExpression;
}

// Misc

export function isTemplateSpan(node: Node): node is TemplateSpan {
Expand Down
34 changes: 33 additions & 1 deletion src/compiler/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,10 @@ namespace ts {
return visitNodes(cbNode, cbNodes, node.decorators);
case SyntaxKind.CommaListExpression:
return visitNodes(cbNode, cbNodes, (node as CommaListExpression).elements);
case SyntaxKind.PrivateIdentifierInInExpression:
return visitNode(cbNode, (node as PrivateIdentifierInInExpression).name) ||
visitNode(cbNode, (node as PrivateIdentifierInInExpression).inToken) ||
visitNode(cbNode, (node as PrivateIdentifierInInExpression).expression);

case SyntaxKind.JsxElement:
return visitNode(cbNode, (node as JsxElement).openingElement) ||
Expand Down Expand Up @@ -4455,9 +4459,32 @@ namespace ts {
);
}

function parsePrivateIdentifierInInExpression(pos: number): Expression {
// PrivateIdentifierInInExpression[in]:
// [+in] PrivateIdentifier in RelationalExpression[?in]

Debug.assert(token() === SyntaxKind.PrivateIdentifier, "parsePrivateIdentifierInInExpression should only have been called if we had a privateIdentifier");
Debug.assert(inDisallowInContext() === false, "parsePrivateIdentifierInInExpression should only have been called if 'in' is allowed");
const id = parsePrivateIdentifier();
if (token() !== SyntaxKind.InKeyword) {
return createMissingNode(SyntaxKind.InKeyword, /*reportAtCurrentPosition*/ true, Diagnostics._0_expected, tokenToString(SyntaxKind.InKeyword));
}

const inToken = parseTokenNode<Token<SyntaxKind.InKeyword>>();
const exp = parseBinaryExpressionOrHigher(OperatorPrecedence.Relational);
return finishNode(factory.createPrivateIdentifierInInExpression(id, inToken, exp), pos);
}

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

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

Expand Down Expand Up @@ -5981,6 +6008,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