Skip to content

Commit

Permalink
Improve @babel/generator typings (#14644)
Browse files Browse the repository at this point in the history
* generator

* refactor: merge {start,end}Terminatorless to printTerminatorless

* inline buildYieldAwait

* inline ExportDeclaration

* also export Pos

* let getPossibleRaw return string | void

* Apply suggestions from code review

Co-authored-by: Nicol貌 Ribaudo <nicolo.ribaudo@gmail.com>
Co-authored-by: liuxingbaoyu <30521560+liuxingbaoyu@users.noreply.github.com>

* address review comments

* do not export internal printer method

* simplify needsWhitespace

Co-authored-by: Nicol貌 Ribaudo <nicolo.ribaudo@gmail.com>
Co-authored-by: liuxingbaoyu <30521560+liuxingbaoyu@users.noreply.github.com>
  • Loading branch information
3 people committed Jun 20, 2022
1 parent 0343255 commit 320fe88
Show file tree
Hide file tree
Showing 17 changed files with 556 additions and 308 deletions.
23 changes: 13 additions & 10 deletions packages/babel-generator/src/buffer.ts
@@ -1,12 +1,11 @@
import type SourceMap from "./source-map";
import type * as t from "@babel/types";
import * as charcodes from "charcodes";

type Pos = {
export type Pos = {
line: number;
column: number;
};
type Loc = {
export type Loc = {
start?: Pos;
end?: Pos;
identifierName?: string;
Expand Down Expand Up @@ -63,14 +62,18 @@ export default class Buffer {

// Encoding the sourcemap is moderately CPU expensive.
get map() {
return (result.map = map ? map.get() : null);
const resultMap = map ? map.get() : null;
result.map = resultMap;
return resultMap;
},
set map(value) {
Object.defineProperty(result, "map", { value, writable: true });
},
// Retrieving the raw mappings is very memory intensive.
get rawMappings() {
return (result.rawMappings = map?.getRawMappings());
const mappings = map?.getRawMappings();
result.rawMappings = mappings;
return mappings;
},
set rawMappings(value) {
Object.defineProperty(result, "rawMappings", { value, writable: true });
Expand Down Expand Up @@ -241,7 +244,7 @@ export default class Buffer {
* With this line, there will be one mapping range over "mod" and another
* over "();", where previously it would have been a single mapping.
*/
exactSource(loc: any, cb: () => void) {
exactSource(loc: Loc | undefined, cb: () => void) {
this.source("start", loc);

cb();
Expand All @@ -262,7 +265,7 @@ export default class Buffer {
* will be given this position in the sourcemap.
*/

source(prop: string, loc: t.SourceLocation): void {
source(prop: "start" | "end", loc: Loc | undefined): void {
if (prop && !loc) return;

// Since this is called extremely often, we re-use the same _sourcePosition
Expand All @@ -274,7 +277,7 @@ export default class Buffer {
* Call a callback with a specific source location and restore on completion.
*/

withSource(prop: string, loc: t.SourceLocation, cb: () => void): void {
withSource(prop: "start" | "end", loc: Loc, cb: () => void): void {
if (!this._map) return cb();

// Use the call stack to manage a stack of "source location" data because
Expand Down Expand Up @@ -309,14 +312,14 @@ export default class Buffer {
* sourcemap output, so that certain printers can be sure that the
* "end" location that they set is actually treated as the end position.
*/
_disallowPop(prop: string, loc: t.SourceLocation) {
_disallowPop(prop: "start" | "end", loc: Loc) {
if (prop && !loc) return;

this._disallowedPop = this._normalizePosition(prop, loc, SourcePos());
}

_normalizePosition(
prop: string,
prop: "start" | "end",
loc: Loc | undefined | null,
targetObj: SourcePos,
) {
Expand Down
2 changes: 1 addition & 1 deletion packages/babel-generator/src/generators/base.ts
Expand Up @@ -58,7 +58,7 @@ const unescapedDoubleQuoteRE = /(?:^|[^\\])(?:\\\\)*"/;

export function DirectiveLiteral(this: Printer, node: t.DirectiveLiteral) {
const raw = this.getPossibleRaw(node);
if (!this.format.minified && raw != null) {
if (!this.format.minified && raw !== undefined) {
this.token(raw);
return;
}
Expand Down
15 changes: 10 additions & 5 deletions packages/babel-generator/src/generators/classes.ts
Expand Up @@ -9,7 +9,7 @@ import * as charCodes from "charcodes";
export function ClassDeclaration(
this: Printer,
node: t.ClassDeclaration,
parent: any,
parent: t.Node,
) {
if (
!this.format.decoratorsBeforeExport ||
Expand Down Expand Up @@ -86,7 +86,7 @@ export function ClassProperty(this: Printer, node: t.ClassProperty) {
// between member modifiers and the property key.
this.source("end", node.key.loc);

this.tsPrintClassMemberModifiers(node, /* isField */ true);
this.tsPrintClassMemberModifiers(node);

if (node.computed) {
this.token("[");
Expand Down Expand Up @@ -125,7 +125,8 @@ export function ClassAccessorProperty(
// between member modifiers and the property key.
this.source("end", node.key.loc);

this.tsPrintClassMemberModifiers(node, /* isField */ true);
// TS does not support class accessor property yet
this.tsPrintClassMemberModifiers(node);

this.word("accessor");
this.printInnerComments(node);
Expand All @@ -136,6 +137,7 @@ export function ClassAccessorProperty(
this.print(node.key, node);
this.token("]");
} else {
// Todo: Flow does not support class accessor property yet.
this._variance(node);
this.print(node.key, node);
}
Expand Down Expand Up @@ -190,12 +192,15 @@ export function ClassPrivateMethod(this: Printer, node: t.ClassPrivateMethod) {
this.print(node.body, node);
}

export function _classMethodHead(this: Printer, node) {
export function _classMethodHead(
this: Printer,
node: t.ClassMethod | t.ClassPrivateMethod | t.TSDeclareMethod,
) {
this.printJoin(node.decorators, node);
// catch up to method key, avoid line break
// between member modifiers/method heads and the method key.
this.source("end", node.key.loc);
this.tsPrintClassMemberModifiers(node, /* isField */ false);
this.tsPrintClassMemberModifiers(node);
this._methodHead(node);
}

Expand Down
44 changes: 22 additions & 22 deletions packages/babel-generator/src/generators/expressions.ts
Expand Up @@ -49,9 +49,7 @@ export function UpdateExpression(this: Printer, node: t.UpdateExpression) {
this.token(node.operator);
this.print(node.argument, node);
} else {
this.startTerminatorless(true);
this.print(node.argument, node);
this.endTerminatorless();
this.printTerminatorless(node.argument, node, true);
this.token(node.operator);
}
}
Expand All @@ -74,7 +72,7 @@ export function ConditionalExpression(
export function NewExpression(
this: Printer,
node: t.NewExpression,
parent: any,
parent: t.Node,
) {
this.word("new");
this.space();
Expand Down Expand Up @@ -116,7 +114,7 @@ export function Super(this: Printer) {

function isDecoratorMemberExpression(
node: t.Expression | t.V8IntrinsicIdentifier,
) {
): boolean {
switch (node.type) {
case "Identifier":
return true;
Expand Down Expand Up @@ -218,25 +216,27 @@ export function Import(this: Printer) {
this.word("import");
}

function buildYieldAwait(keyword: string) {
return function (this: Printer, node: any) {
this.word(keyword);

if (node.delegate) {
this.token("*");
}
export function AwaitExpression(this: Printer, node: t.AwaitExpression) {
this.word("await");

if (node.argument) {
this.space();
const terminatorState = this.startTerminatorless();
this.print(node.argument, node);
this.endTerminatorless(terminatorState);
}
};
if (node.argument) {
this.space();
this.printTerminatorless(node.argument, node, false);
}
}

export const YieldExpression = buildYieldAwait("yield");
export const AwaitExpression = buildYieldAwait("await");
export function YieldExpression(this: Printer, node: t.YieldExpression) {
this.word("yield");

if (node.delegate) {
this.token("*");
}

if (node.argument) {
this.space();
this.printTerminatorless(node.argument, node, false);
}
}

export function EmptyStatement(this: Printer) {
this.semicolon(true /* force */);
Expand Down Expand Up @@ -265,7 +265,7 @@ export function AssignmentPattern(this: Printer, node: t.AssignmentPattern) {
export function AssignmentExpression(
this: Printer,
node: t.AssignmentExpression,
parent: any,
parent: t.Node,
) {
// Somewhere inside a for statement `init` node but doesn't usually
// needs a paren except for `in` expressions: `for (a in b ? a : b;;)`
Expand Down
31 changes: 23 additions & 8 deletions packages/babel-generator/src/generators/flow.ts
Expand Up @@ -48,7 +48,7 @@ export function DeclareClass(
export function DeclareFunction(
this: Printer,
node: t.DeclareFunction,
parent: any,
parent: t.Node,
) {
if (!isDeclareExportDeclaration(parent)) {
this.word("declare");
Expand Down Expand Up @@ -118,7 +118,7 @@ export function DeclareTypeAlias(this: Printer, node: t.DeclareTypeAlias) {
export function DeclareOpaqueType(
this: Printer,
node: t.DeclareOpaqueType,
parent: any,
parent: t.Node,
) {
if (!isDeclareExportDeclaration(parent)) {
this.word("declare");
Expand All @@ -130,7 +130,7 @@ export function DeclareOpaqueType(
export function DeclareVariable(
this: Printer,
node: t.DeclareVariable,
parent: any,
parent: t.Node,
) {
if (!isDeclareExportDeclaration(parent)) {
this.word("declare");
Expand Down Expand Up @@ -174,7 +174,7 @@ export function EnumDeclaration(this: Printer, node: t.EnumDeclaration) {
}

function enumExplicitType(
context: any,
context: Printer,
name: string,
hasExplicitType: boolean,
) {
Expand All @@ -187,7 +187,7 @@ function enumExplicitType(
context.space();
}

function enumBody(context: any, node: any) {
function enumBody(context: Printer, node: t.EnumBody) {
const { members } = node;
context.token("{");
context.indent();
Expand Down Expand Up @@ -236,7 +236,10 @@ export function EnumDefaultedMember(
this.token(",");
}

function enumInitializedMember(context: any, node: any) {
function enumInitializedMember(
context: Printer,
node: t.EnumBooleanMember | t.EnumNumberMember | t.EnumStringMember,
) {
const { id, init } = node;
context.print(id, node);
context.space();
Expand All @@ -258,7 +261,10 @@ export function EnumStringMember(this: Printer, node: t.EnumStringMember) {
enumInitializedMember(this, node);
}

function FlowExportDeclaration(this: Printer, node: any) {
function FlowExportDeclaration(
this: Printer,
node: t.DeclareExportDeclaration,
) {
if (node.declaration) {
const declar = node.declaration;
this.print(declar, node);
Expand Down Expand Up @@ -384,7 +390,16 @@ export function _interfaceish(
this.print(node.body, node);
}

export function _variance(this: Printer, node) {
export function _variance(
this: Printer,
node:
| t.TypeParameter
| t.ObjectTypeIndexer
| t.ObjectTypeProperty
| t.ClassProperty
| t.ClassPrivateProperty
| t.ClassAccessorProperty,
) {
if (node.variance) {
if (node.variance.kind === "plus") {
this.token("+");
Expand Down
2 changes: 1 addition & 1 deletion packages/babel-generator/src/generators/jsx.ts
Expand Up @@ -54,7 +54,7 @@ export function JSXSpreadChild(this: Printer, node: t.JSXSpreadChild) {
export function JSXText(this: Printer, node: t.JSXText) {
const raw = this.getPossibleRaw(node);

if (raw != null) {
if (raw !== undefined) {
this.token(raw);
} else {
this.token(node.value);
Expand Down

0 comments on commit 320fe88

Please sign in to comment.