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

feat: support class.hasInstance proposal (Stage 1) #46578

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 72 additions & 1 deletion src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32632,6 +32632,12 @@ namespace ts {
return checkImportMetaProperty(node);
}

if (node.keywordToken === SyntaxKind.ClassKeyword) {
const prop = getPropertyOfType(checkClassHasInstanceProperty(node), node.name.escapedText);
if (!prop) return errorType;
return getTypeOfSymbol(prop);
}

return Debug.assertNever(node.keywordToken);
}

Expand All @@ -32642,6 +32648,8 @@ namespace ts {
case SyntaxKind.NewKeyword:
const type = checkNewTargetMetaProperty(node);
return isErrorType(type) ? errorType : createNewTargetExpressionType(type);
case SyntaxKind.ClassKeyword:
return checkClassHasInstanceProperty(node);
default:
Debug.assertNever(node.keywordToken);
}
Expand Down Expand Up @@ -32677,6 +32685,19 @@ namespace ts {
return node.name.escapedText === "meta" ? getGlobalImportMetaType() : errorType;
}


function checkClassHasInstanceProperty(node: MetaProperty) {
const container = getContainingClass(node);
if (!container) {
error(node, Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_class, "class." + node.name.escapedText);
return errorType;
}
else {
const symbol = getSymbolOfNode(container)!;
return createClassMetaPropertyExpressionType(getTypeOfSymbol(symbol));
}
}

function getTypeOfParameter(symbol: Symbol) {
const type = getTypeOfSymbol(symbol);
if (strictNullChecks) {
Expand Down Expand Up @@ -33051,6 +33072,40 @@ namespace ts {
return createAnonymousType(symbol, members, emptyArray, emptyArray, emptyArray);
}

// cache this type on the class symbol?
function createClassMetaPropertyExpressionType(targetClass: Type): Type {
// Create a synthetic type `ClassMetaProperty { hasInstance(value: unknown): value is TargetClass }`
const symbol = createSymbol(SymbolFlags.None, "ClassMetaProperty" as __String);

// class.hasInstance
const hasInstanceSymbol = createSymbol(SymbolFlags.Property, "hasInstance" as __String, CheckFlags.Readonly);
{
hasInstanceSymbol.parent = symbol;

const arg0 = createSymbol(SymbolFlags.None, "value" as __String);
arg0.type = unknownType;
// TODO: is it possible that cannot get construct signature from a class?
const classConstructor = getErasedSignature(getSingleSignature(targetClass, SignatureKind.Construct, /** allow members */ true)!);
const classInstance = classConstructor ? getReturnTypeOfSignature(classConstructor) : errorType;
const hasInstanceReturnType = createTypePredicate(TypePredicateKind.Identifier, "value", 0, classInstance);
const signature = createSignature(
/** declaration */ undefined,
/** generics */ undefined,
/** this */ undefined,
[arg0],
booleanType,
hasInstanceReturnType,
/** minArgCount */ 1,
SignatureFlags.None,
);
hasInstanceSymbol.type = createAnonymousType(/** symbol */ undefined, emptySymbols, [signature], emptyArray, emptyArray);
}

const members = createSymbolTable([hasInstanceSymbol]);
symbol.members = members;
return createAnonymousType(symbol, members, emptyArray, emptyArray, emptyArray);
}

function getReturnTypeFromBody(func: FunctionLikeDeclaration, checkMode?: CheckMode): Type {
if (!func.body) {
return errorType;
Expand Down Expand Up @@ -42927,6 +42982,11 @@ namespace ts {
if (parent.keywordToken === SyntaxKind.ImportKeyword && idText(node as Identifier) === "meta") {
return getGlobalImportMetaExpressionType().members!.get("meta" as __String);
}
if (parent.keywordToken === SyntaxKind.ClassKeyword && idText(node as Identifier) === "hasInstance") {
const meta = checkClassHasInstanceProperty(parent).symbol;
const prop = meta.members?.get(parent.name.escapedText);
return prop;
}
// no other meta properties are valid syntax, thus no others should have symbols
return undefined;
}
Expand Down Expand Up @@ -42999,8 +43059,9 @@ namespace ts {
case SyntaxKind.DefaultKeyword:
case SyntaxKind.FunctionKeyword:
case SyntaxKind.EqualsGreaterThanToken:
case SyntaxKind.ClassKeyword:
return getSymbolOfNode(node.parent);
case SyntaxKind.ClassKeyword:
return isMetaProperty(node.parent) ? checkMetaPropertyKeyword(node.parent).symbol : getSymbolOfNode(node.parent);
case SyntaxKind.ImportType:
return isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal, ignoreErrors) : undefined;

Expand Down Expand Up @@ -45665,6 +45726,16 @@ namespace ts {
return grammarErrorOnNode(node.name, Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, tokenToString(node.keywordToken), "meta");
}
break;
case SyntaxKind.ClassKeyword:
if (escapedText !== "hasInstance") {
return grammarErrorOnNode(node.name, Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, tokenToString(node.keywordToken), "hasInstance");
}
else {
if (node.parent.kind !== SyntaxKind.CallExpression) {
return grammarErrorOnNode(node, Diagnostics._0_expected, "class.hasInstance()");
}
}
break;
}
}

Expand Down
4 changes: 4 additions & 0 deletions src/compiler/diagnosticMessages.json
Original file line number Diff line number Diff line change
Expand Up @@ -6473,6 +6473,10 @@
"category": "Error",
"code": 17018
},
"Meta-property '{0}' is only allowed in the body of a class.": {
"category": "Error",
"code": 17019
},
"Circularity detected while resolving configuration: {0}": {
"category": "Error",
"code": 18000
Expand Down
1 change: 1 addition & 0 deletions src/compiler/factory/nodeFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3239,6 +3239,7 @@ namespace ts {
node.transformFlags |= TransformFlags.ContainsES2015;
break;
case SyntaxKind.ImportKeyword:
case SyntaxKind.ClassKeyword:
node.transformFlags |= TransformFlags.ContainsESNext;
break;
default:
Expand Down
19 changes: 16 additions & 3 deletions src/compiler/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4508,10 +4508,9 @@ namespace ts {
}

function isStartOfExpressionStatement(): boolean {
// As per the grammar, none of '{' or 'function' or 'class' can start an expression statement.
// As per the grammar, none of '{' or 'function' can start an expression statement.
return token() !== SyntaxKind.OpenBraceToken &&
token() !== SyntaxKind.FunctionKeyword &&
token() !== SyntaxKind.ClassKeyword &&
token() !== SyntaxKind.AtToken &&
isStartOfExpression();
}
Expand Down Expand Up @@ -6053,6 +6052,9 @@ namespace ts {

return parseFunctionExpression();
case SyntaxKind.ClassKeyword:
if (lookAhead(nextTokenIsDot)) {
return parseClassMetaProperty();
}
return parseClassExpression();
case SyntaxKind.FunctionKeyword:
return parseFunctionExpression();
Expand Down Expand Up @@ -6583,9 +6585,10 @@ namespace ts {
case SyntaxKind.LetKeyword:
case SyntaxKind.ConstKeyword:
case SyntaxKind.FunctionKeyword:
case SyntaxKind.ClassKeyword:
case SyntaxKind.EnumKeyword:
return true;
case SyntaxKind.ClassKeyword:
return !lookAhead(nextTokenIsDot);

// 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers;
// however, an identifier cannot be followed by another identifier on the same line. This is what we
Expand Down Expand Up @@ -6750,6 +6753,9 @@ namespace ts {
case SyntaxKind.FunctionKeyword:
return parseFunctionDeclaration(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined);
case SyntaxKind.ClassKeyword:
if (lookAhead(nextTokenIsDot)) {
return parseExpressionOrLabeledStatement();
}
return parseClassDeclaration(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined);
case SyntaxKind.IfKeyword:
return parseIfStatement();
Expand Down Expand Up @@ -7437,6 +7443,13 @@ namespace ts {
return Debug.fail("Should not have attempted to parse class member declaration.");
}

function parseClassMetaProperty(): MetaProperty {
const pos = getNodePos();
nextToken(); // advance past the 'class'
nextToken(); // advance past the dot
return finishNode(factory.createMetaProperty(SyntaxKind.ClassKeyword, parseIdentifierName()), pos);
}

function parseClassExpression(): ClassExpression {
return parseClassDeclarationOrExpression(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined, SyntaxKind.ClassExpression) as ClassExpression;
}
Expand Down
Loading