Skip to content

Commit

Permalink
Fix parsing of methods and fields named "declare" (#575)
Browse files Browse the repository at this point in the history
Fixes #545

When originally porting babel/babel#11146, there was a
mistake where we were using `eatContextual` when actually it was important to
use `tsParseModifier`, since `tsParseModifier` won't eat a name token if the
following token indicates that it must be the name of a method or field. This PR
fixes that by switching to `tsParseModifier` as Babel does.

It might be good to later refactor/simplify `tsParseModifier` if the keyword
specificity is just for error handling (and to maybe avoid the
snapshot/restore), but that can be a follow-up.
  • Loading branch information
alangpierce authored Dec 30, 2020
1 parent 18709a7 commit b3190e2
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 8 deletions.
5 changes: 3 additions & 2 deletions src/parser/traverser/statement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
tsParseIdentifierStatement,
tsParseImportEqualsDeclaration,
tsParseMaybeDecoratorArguments,
tsParseModifier,
tsStartParseFunctionParams,
tsTryParseClassMemberWithIsStatic,
tsTryParseExport,
Expand Down Expand Up @@ -692,9 +693,9 @@ function parseClassBody(classContextId: number): void {

function parseClassMember(memberStart: number, classContextId: number): void {
if (isTypeScriptEnabled) {
eatContextual(ContextualKeyword._declare);
tsParseModifier([ContextualKeyword._declare]);
tsParseAccessModifier();
eatContextual(ContextualKeyword._declare);
tsParseModifier([ContextualKeyword._declare]);
}
let isStatic = false;
if (match(tt.name) && state.contextualKeyword === ContextualKeyword._static) {
Expand Down
43 changes: 37 additions & 6 deletions test/typescript-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2233,13 +2233,13 @@ describe("typescript transform", () => {
`,
`"use strict";
class Foo {
constructor() {
Expand Down Expand Up @@ -2372,6 +2372,37 @@ describe("typescript transform", () => {
`,
);
});

it("correctly handles methods and fields named declare", () => {
assertTypeScriptResult(
`
class A {
declare() {
}
}
class B {
static declare() {
}
}
class C {
declare = 2;
}
`,
`"use strict";
class A {
declare() {
}
}
class B {
static declare() {
}
}
class C {constructor() { C.prototype.__init.call(this); }
__init() {this.declare = 2}
}
`,
);
});
Expand Down

0 comments on commit b3190e2

Please sign in to comment.