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

fix: Support auto accessors with TypeScript annotations #15209

Merged
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
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
1 change: 1 addition & 0 deletions packages/babel-parser/src/parse-error/standard-errors.ts
Expand Up @@ -35,6 +35,7 @@ export default {
AwaitNotInAsyncContext:
"'await' is only allowed within async functions and at the top levels of modules.",
AwaitNotInAsyncFunction: "'await' is only allowed within async functions.",
// TODO: Accesor -> Accessor
BadGetterArity: "A 'get' accesor must not have any formal parameters.",
BadSetterArity: "A 'set' accesor must have exactly one formal parameter.",
Copy link
Member Author

Choose a reason for hiding this comment

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

This is kind of annoying, delaying to babel8 means we have to copy and paste a lot of tests, and modify it immediately I'm not sure if it will affect compatibility.

Copy link
Contributor

Choose a reason for hiding this comment

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

We can do it in a separate PR.

We don't have to defer to Babel 8: The error message improvement can be shipped in patch releases, since it is not part of our API protocol. This approach is also similar to how Node.js treats its error message.

BadSetterRestParameter:
Expand Down
48 changes: 32 additions & 16 deletions packages/babel-parser/src/plugins/typescript/index.ts
Expand Up @@ -90,12 +90,14 @@ const TSErrors = ParseErrorEnum`typescript`({
propertyName: string;
}) =>
`Property '${propertyName}' cannot have an initializer because it is marked abstract.`,
AccesorCannotDeclareThisParameter:
AccessorCannotBeOptional:
Copy link
Member

Choose a reason for hiding this comment

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

We can (and should) fix the error messages now (i.e. BadSetterArity/BetGetterArity), but we should wait until Babel 8 to fix typos in error codes.

Copy link
Member Author

Choose a reason for hiding this comment

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

Do error codes refer to the property names? These seem to be only visible from the inside.

Copy link
Member

Choose a reason for hiding this comment

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

Yes they are the property names; and they are public. For example, prettier relies on them: https://github.com/prettier/prettier/blob/b50dfd1974d33abb980e9b4df949913932eeb478/src/language-js/parse/babel.js#L183

"An 'accessor' property cannot be declared optional.",
AccessorCannotDeclareThisParameter:
"'get' and 'set' accessors cannot declare 'this' parameters.",
AccesorCannotHaveTypeParameters: "An accessor cannot have type parameters.",
AccessorCannotHaveTypeParameters: "An accessor cannot have type parameters.",
ClassMethodHasDeclare: "Class methods cannot have the 'declare' modifier.",
ClassMethodHasReadonly: "Class methods cannot have the 'readonly' modifier.",
ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference:
ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference:
"A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference.",
ConstructorHasTypeParameters:
"Type parameters cannot appear on a constructor declaration.",
Expand Down Expand Up @@ -194,11 +196,11 @@ const TSErrors = ParseErrorEnum`typescript`({
"This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma, as in `<T,>() => ...`.",
ReservedTypeAssertion:
"This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead.",
SetAccesorCannotHaveOptionalParameter:
SetAccessorCannotHaveOptionalParameter:
"A 'set' accessor cannot have an optional parameter.",
SetAccesorCannotHaveRestParameter:
SetAccessorCannotHaveRestParameter:
"A 'set' accessor cannot have rest parameter.",
SetAccesorCannotHaveReturnType:
SetAccessorCannotHaveReturnType:
"A 'set' accessor cannot have a return type annotation.",
SingleTypeParameterWithoutTrailingComma: ({
typeParameterName,
Expand Down Expand Up @@ -835,7 +837,7 @@ export default (superClass: ClassWithMixin<typeof Parser, IJSXParserMixin>) =>
}
const method: N.TsMethodSignature = nodeAny;
if (method.kind && this.match(tt.lt)) {
this.raise(TSErrors.AccesorCannotHaveTypeParameters, {
this.raise(TSErrors.AccessorCannotHaveTypeParameters, {
at: this.state.curPosition(),
});
}
Expand All @@ -851,7 +853,7 @@ export default (superClass: ClassWithMixin<typeof Parser, IJSXParserMixin>) =>
if (method[paramsKey].length > 0) {
this.raise(Errors.BadGetterArity, { at: this.state.curPosition() });
if (this.isThisParam(method[paramsKey][0])) {
this.raise(TSErrors.AccesorCannotDeclareThisParameter, {
this.raise(TSErrors.AccessorCannotDeclareThisParameter, {
at: this.state.curPosition(),
});
}
Expand All @@ -862,26 +864,26 @@ export default (superClass: ClassWithMixin<typeof Parser, IJSXParserMixin>) =>
} else {
const firstParameter = method[paramsKey][0];
if (this.isThisParam(firstParameter)) {
this.raise(TSErrors.AccesorCannotDeclareThisParameter, {
this.raise(TSErrors.AccessorCannotDeclareThisParameter, {
at: this.state.curPosition(),
});
}
if (
firstParameter.type === "Identifier" &&
firstParameter.optional
) {
this.raise(TSErrors.SetAccesorCannotHaveOptionalParameter, {
this.raise(TSErrors.SetAccessorCannotHaveOptionalParameter, {
at: this.state.curPosition(),
});
}
if (firstParameter.type === "RestElement") {
this.raise(TSErrors.SetAccesorCannotHaveRestParameter, {
this.raise(TSErrors.SetAccessorCannotHaveRestParameter, {
at: this.state.curPosition(),
});
}
}
if (method[returnTypeKey]) {
this.raise(TSErrors.SetAccesorCannotHaveReturnType, {
this.raise(TSErrors.SetAccessorCannotHaveReturnType, {
at: method[returnTypeKey],
});
}
Expand Down Expand Up @@ -2794,7 +2796,7 @@ export default (superClass: ClassWithMixin<typeof Parser, IJSXParserMixin>) =>
!isPossiblyLiteralEnum(init)
) {
this.raise(
TSErrors.ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference,
TSErrors.ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference,
{ at: init },
);
}
Expand Down Expand Up @@ -3124,10 +3126,14 @@ export default (superClass: ClassWithMixin<typeof Parser, IJSXParserMixin>) =>
}

parseClassPropertyAnnotation(
node: N.ClassProperty | N.ClassPrivateProperty,
node: N.ClassProperty | N.ClassPrivateProperty | N.ClassAccessorProperty,
): void {
if (!node.optional && this.eat(tt.bang)) {
node.definite = true;
if (!node.optional) {
if (this.eat(tt.bang)) {
node.definite = true;
} else if (this.eat(tt.question)) {
node.optional = true;
}
}

const type = this.tsTryParseTypeAnnotation();
Expand Down Expand Up @@ -3181,6 +3187,16 @@ export default (superClass: ClassWithMixin<typeof Parser, IJSXParserMixin>) =>
return super.parseClassPrivateProperty(node);
}

parseClassAccessorProperty(
node: N.ClassAccessorProperty,
): N.ClassAccessorProperty {
this.parseClassPropertyAnnotation(node);
if (node.optional) {
this.raise(TSErrors.AccessorCannotBeOptional, { at: node });
}
return super.parseClassAccessorProperty(node);
}

pushClassMethod(
classBody: N.ClassBody,
method: N.ClassMethod,
Expand Down
@@ -0,0 +1,21 @@
abstract class Foo {
accessor prop: number = 1;
static accessor prop2: number = 1;
accessor #prop3: number = 1;
accessor [prop4]: number = 1;
private accessor prop5: number = 1;
abstract accessor prop6: number;
declare accessor prop7: number;
private accessor #p: any;

accessor a!;
abstract accessor #s;
accessor #d?;
Copy link
Contributor

Choose a reason for hiding this comment

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

This is not allowed in an abstract context. Can you update the test case?

Copy link
Member Author

Choose a reason for hiding this comment

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

Are you saying abstract accessor #s;?

Copy link
Contributor

@JLHwung JLHwung Nov 22, 2022

Choose a reason for hiding this comment

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

Oh actually accessor #d? is not allowed in both abstract class and non-abstract class. It seems to me the test case class/accessor covers only valid cases, can we make it a separate invalid test case?

abstract accessor f = 1;
readonly accessor g;
}

declare class C {
accessor x = 1;
#y = 1;
}
@@ -0,0 +1,6 @@
{
"plugins": [
"typescript",
"decoratorAutoAccessors"
]
}