Revert "Switch print/embed to async (#13104)" (#13210)

This commit is contained in:
fisker Cheung authored and GitHub committed 2022-08-02 18:11:34 +08:00
1 parent b12396d69a
commit cdb1494170
70 files changed
+973 -1161

No files matched your search

-1
View File
@@ -2,7 +2,6 @@
- `prettier.format()` returns `Promise<string>`
- `prettier.formatWithCursor()` returns `Promise<{formatted: string, cursorOffset: number}>`
- `prettier.formatAST()` returns `Promise<string>`
- `prettier.check()` returns `Promise<boolean>`
- `prettier.getSupportInfo()` returns `Promise`
- `prettier.resolveConfig.sync` is removed
+3 -56
View File
@@ -1,60 +1,7 @@
#### [HIGHLIGHT] Support plugin with async parse function (#12748, #13104 by @fisker)
#### [HIGHLIGHT] Support plugin with async parse function (#12748 by @fisker)
[`parse` function](https://prettier.io/docs/en/plugins.html#parsers) in plugin can return a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) now.
In order to support async parser, we introduced several breaking changes to the plugin system:
<!-- TODO: Discuss this before v3 release -->
The third argument of the [`print`](https://prettier.io/docs/en/plugins.html#print) method of plugin printers (the `print` callback) returns `Promise<Doc>` now.
```diff
export const printers = {
"dance-ast": {
- print(path, options, print) {
- return [print("key"), ": ", print("value")];
+ async print(path, options, print) {
+ return [await print("key"), ": ", await print("value")];
},
},
}
```
The `print` and `textToDoc` arguments of the [`embed`](https://prettier.io/docs/en/plugins.html#optional-embed) method of plugin printers returns `Promise<Doc>` now.
```diff
export const printers = {
"dance-ast": {
- embed(path, print, textToDoc, options) {
+ async embed(path, print, textToDoc, options) {
const { text } = path.getValue();
- const doc = textToDoc(text, {...options, parser: "meriyah"});
+ const doc = await textToDoc(text, {...options, parser: "meriyah"});
return [doc, hardline];
},
},
}
```
`Promise`s returned in callback of `AstPath#{each,map}()`(aka `path`) are `await`ed.
```js
path.map((path, index) => Promise.resolve(index));
/* Prettier stable */
// -> [Promise<0>, Promise<1>]
/* Prettier main */
// -> Promise<[0, 1]>
```
Note: Due to limitation of `AstPath`, plugin should not try to call `print()` or `textToDoc()` in parallel, it may cause unexpected result.
```js
/* BAD */
const [key, value] = await Promise.all(
["key", "value"].map((property) => print(property))
);
return [key, ": ", value];
/* GOOD */
return [await print("key"), ": ", await print("key")];
```
Note: Since [`embed` functions in plugin](https://prettier.io/docs/en/plugins.html#optional-embed) are still sync, plugins with async parser can't be used to format embed code.
+13 -24
View File
@@ -197,10 +197,8 @@ function print(
path: AstPath,
options: object,
// Recursively print a child node
print: (
selector?: string | number | Array<string | number> | AstPath
) => Promise<Doc>
): Promise<Doc>;
print: (selector?: string | number | Array<string | number> | AstPath) => Doc
): Doc;
```
The `print` function is passed the following parameters:
@@ -212,18 +210,18 @@ The `print` function is passed the following parameters:
Here’s a simplified example to give an idea of what a typical implementation of `print` looks like:
```js
import { doc } from "prettier";
const {
builders: { group, indent, join, line, softline },
} = require("prettier").doc;
const { group, indent, join, line, softline } = doc.builders;
async function print(path, options, print) {
function print(path, options, print) {
const node = path.getValue();
switch (node.type) {
case "list":
return group([
"(",
indent([softline, join(line, await path.map(print, "elements"))]),
indent([softline, join(line, path.map(print, "elements"))]),
softline,
")",
]);
@@ -231,13 +229,7 @@ async function print(path, options, print) {
case "pair":
return group([
"(",
indent([
softline,
await print("left"),
line,
". ",
await print("right"),
]),
indent([softline, print("left"), line, ". ", print("right")]),
softline,
")",
]);
@@ -261,15 +253,13 @@ function embed(
// Path to the current AST node
path: AstPath,
// Print a node with the current printer
print: (
selector?: string | number | Array<string | number> | AstPath
) => Promise<Doc>,
print: (selector?: string | number | Array<string | number> | AstPath) => Doc,
// Parse and print some text using a different parser.
// You should set `options.parser` to specify which parser to use.
textToDoc: (text: string, options: object) => Promise<Doc>,
textToDoc: (text: string, options: object) => Doc,
// Current options
options: object
): Promise<Doc | null>;
): Doc | null;
```
The `embed` function acts like the `print` function, except that it is passed an additional `textToDoc` function, which can be used to render a doc using a different plugin. The `embed` function returns a Doc or a falsy value. If a falsy value is returned, the `print` function is called with the current `path`. If a Doc is returned, that Doc is used in printing and the `print` function is not called.
@@ -463,10 +453,9 @@ function isPreviousLineEmpty<N>(text: string, node: N, locStart: (node: N) => nu
Since plugins can be resolved using relative paths, when working on one you can do:
```js
import * as prettier from "prettier";
const prettier = require("prettier");
const code = "(add 1 2)";
await prettier.format(code, {
prettier.format(code, {
parser: "lisp",
plugins: ["."],
});
+22 -81
View File
@@ -15,24 +15,6 @@ function getNodeStackIndexHelper(stack, count) {
return -1;
}
const isThenable = (object) => typeof object?.then === "function";
const tryFinally = (fn, onSettled) => {
let result;
try {
result = fn();
} catch (error) {
onSettled();
throw error;
}
if (isThenable(result)) {
return result.finally(onSettled);
}
onSettled();
return result;
};
class AstPath {
constructor(value) {
this.stack = [value];
@@ -80,25 +62,17 @@ class AstPath {
value = value[name];
stack.push(name, value);
}
return tryFinally(
() => callback(this),
() => {
stack.length = length;
}
);
const result = callback(this);
stack.length = length;
return result;
}
callParent(callback, count = 0) {
const stackIndex = getNodeStackIndexHelper(this.stack, count + 1);
const parentValues = this.stack.splice(stackIndex + 1);
return tryFinally(
() => callback(this),
() => {
this.stack.push(...parentValues);
}
);
const result = callback(this);
this.stack.push(...parentValues);
return result;
}
// Similar to AstPath.prototype.call, except that the value obtained by
@@ -115,55 +89,24 @@ class AstPath {
stack.push(name, value);
}
const iteratee = (index) =>
tryFinally(
() => {
stack.push(index, value[index]);
return callback(this, index, value);
},
() => {
stack.length -= 2;
}
);
for (let i = 0; i < value.length; ++i) {
stack.push(i, value[i]);
callback(this, i, value);
stack.length -= 2;
}
return tryFinally(
() => {
let promise;
for (let index = 0; index < value.length; index++) {
if (promise) {
promise = promise.then(() => iteratee(index));
continue;
}
const result = iteratee(index);
if (isThenable(result)) {
promise = result;
}
}
return promise;
},
() => {
stack.length = length;
}
);
stack.length = length;
}
// Similar to AstPath.prototype.each, except that the results of the
// callback function invocations are stored in an array and returned at
// the end of the iteration.
map(callback, ...names) {
const results = [];
const maybePromise = this.each((path, index, value) => {
const result = callback(path, index, value);
results[index] = result;
return result;
const result = [];
this.each((path, index, value) => {
result[index] = callback(path, index, value);
}, ...names);
return isThenable(maybePromise)
? maybePromise.then(() => Promise.all(results))
: results;
return result;
}
/**
@@ -173,14 +116,12 @@ class AstPath {
try(callback) {
const { stack } = this;
const stackBackup = [...stack];
return tryFinally(
() => callback(),
() => {
stack.length = 0;
stack.push(...stackBackup);
}
);
try {
return callback();
} finally {
stack.length = 0;
stack.push(...stackBackup);
}
}
/**
+2 -2
View File
@@ -1,11 +1,11 @@
import { hardline } from "../document/builders.js";
import printFrontMatter from "../utils/front-matter/print.js";
async function embed(path, print, textToDoc /*, options */) {
function embed(path, print, textToDoc /*, options */) {
const node = path.getValue();
if (node.type === "front-matter") {
const doc = await printFrontMatter(node, textToDoc);
const doc = printFrontMatter(node, textToDoc);
return doc ? [doc, hardline] : "";
}
}
+36 -39
View File
@@ -78,7 +78,7 @@ function shouldPrintComma(options) {
return options.trailingComma === "es5" || options.trailingComma === "all";
}
async function genericPrint(path, options, print) {
function genericPrint(path, options, print) {
const node = path.getValue();
/* istanbul ignore if */
@@ -94,7 +94,7 @@ async function genericPrint(path, options, print) {
case "front-matter":
return [node.raw, hardline];
case "css-root": {
const nodes = await printNodeSequence(path, options, print);
const nodes = printNodeSequence(path, options, print);
const after = node.raws.after.trim();
return [
@@ -112,7 +112,7 @@ async function genericPrint(path, options, print) {
}
case "css-rule": {
return [
await print("selector"),
print("selector"),
node.important ? " !important" : "",
node.nodes
? [
@@ -125,10 +125,7 @@ async function genericPrint(path, options, print) {
: "",
"{",
node.nodes.length > 0
? indent([
hardline,
await printNodeSequence(path, options, print),
])
? indent([hardline, printNodeSequence(path, options, print)])
: "",
hardline,
"}",
@@ -147,8 +144,8 @@ async function genericPrint(path, options, print) {
typeof node.value === "string" && /^ *$/.test(node.value);
let value = hasComposesNode(node)
? removeLines(await print("value"))
: await print("value");
? removeLines(print("value"))
: print("value");
if (!isColon && lastLineHasInlineComment(trimmedBetween)) {
value = indent([hardline, dedent(value)]);
@@ -161,7 +158,7 @@ async function genericPrint(path, options, print) {
trimmedBetween,
node.extend || isValueAllSpace ? "" : " ",
options.parser === "less" && node.extend && node.selector
? ["extend(", await print("selector"), ")"]
? ["extend(", print("selector"), ")"]
: "",
value,
node.raws.important
@@ -182,7 +179,7 @@ async function genericPrint(path, options, print) {
node.nodes
? [
" {",
indent([softline, await printNodeSequence(path, options, print)]),
indent([softline, printNodeSequence(path, options, print)]),
softline,
"}",
]
@@ -205,7 +202,7 @@ async function genericPrint(path, options, print) {
if (options.parser === "less") {
if (node.mixin) {
return [
await print("selector"),
print("selector"),
node.important ? " !important" : "",
isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";",
];
@@ -214,7 +211,7 @@ async function genericPrint(path, options, print) {
if (node.function) {
return [
node.name,
await print("params"),
print("params"),
isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";",
];
}
@@ -224,14 +221,14 @@ async function genericPrint(path, options, print) {
"@",
node.name,
": ",
node.value ? await print("value") : "",
node.value ? print("value") : "",
node.raws.between.trim() ? node.raws.between.trim() + " " : "",
node.nodes
? [
"{",
indent([
node.nodes.length > 0 ? softline : "",
await printNodeSequence(path, options, print),
printNodeSequence(path, options, print),
]),
softline,
"}",
@@ -270,14 +267,14 @@ async function genericPrint(path, options, print) {
? hardline
: " "
: " ",
await print("params"),
print("params"),
]
: "",
node.selector ? indent([" ", await print("selector")]) : "",
node.selector ? indent([" ", print("selector")]) : "",
node.value
? group([
" ",
await print("value"),
print("value"),
isSCSSControlDirectiveNode(node, options)
? hasParensAroundNode(node)
? " "
@@ -303,7 +300,7 @@ async function genericPrint(path, options, print) {
"{",
indent([
node.nodes.length > 0 ? softline : "",
await printNodeSequence(path, options, print),
printNodeSequence(path, options, print),
]),
softline,
"}",
@@ -317,19 +314,19 @@ async function genericPrint(path, options, print) {
// postcss-media-query-parser
case "media-query-list": {
const parts = [];
await path.each(async (childPath) => {
path.each((childPath) => {
const node = childPath.getValue();
if (node.type === "media-query" && node.value === "") {
return;
}
parts.push(await print());
parts.push(print());
}, "nodes");
return group(indent(join(line, parts)));
}
case "media-query": {
return [
join(" ", await path.map(print, "nodes")),
join(" ", path.map(print, "nodes")),
isLastNode(path, node) ? "" : ",",
];
}
@@ -340,7 +337,7 @@ async function genericPrint(path, options, print) {
if (!node.nodes) {
return node.value;
}
return ["(", ...(await path.map(print, "nodes")), ")"];
return ["(", ...path.map(print, "nodes"), ")"];
}
case "media-feature": {
return maybeToLowerCase(
@@ -378,12 +375,12 @@ async function genericPrint(path, options, print) {
? line
: hardline,
],
await path.map(print, "nodes")
path.map(print, "nodes")
),
]);
}
case "selector-selector": {
return group(indent(await path.map(print, "nodes")));
return group(indent(path.map(print, "nodes")));
}
case "selector-comment": {
return node.value;
@@ -468,7 +465,7 @@ async function genericPrint(path, options, print) {
return [
maybeToLowerCase(node.value),
isNonEmptyArray(node.nodes)
? ["(", join(", ", await path.map(print, "nodes")), ")"]
? ["(", join(", ", path.map(print, "nodes")), ")"]
: "",
];
}
@@ -537,7 +534,7 @@ async function genericPrint(path, options, print) {
isInlineValueCommentNode(node)
);
const printed = await path.map(print, "groups");
const printed = path.map(print, "groups");
const parts = [];
const insideURLFunction = insideValueFunctionNode(path, "url");
@@ -873,14 +870,14 @@ async function genericPrint(path, options, print) {
node.groups[0].groups[0].value.startsWith("data:")))
) {
return [
node.open ? await print("open") : "",
join(",", await path.map(print, "groups")),
node.close ? await print("close") : "",
node.open ? print("open") : "",
join(",", path.map(print, "groups")),
node.close ? print("close") : "",
];
}
if (!node.open) {
const printed = await path.map(print, "groups");
const printed = path.map(print, "groups");
const res = [];
for (let i = 0; i < printed.length; i++) {
@@ -905,15 +902,15 @@ async function genericPrint(path, options, print) {
const printed = group(
[
node.open ? await print("open") : "",
node.open ? print("open") : "",
indent([
softline,
join(
[line],
await path.map(async (childPath, index) => {
path.map((childPath, index) => {
const child = childPath.getValue();
const isLast = index === node.groups.length - 1;
const printed = [await print(), isLast ? "" : ","];
const printed = [print(), isLast ? "" : ","];
// Key/Value pair in open paren already indented
if (
@@ -957,7 +954,7 @@ async function genericPrint(path, options, print) {
: ""
),
softline,
node.close ? await print("close") : "",
node.close ? print("close") : "",
],
{
shouldBreak,
@@ -972,7 +969,7 @@ async function genericPrint(path, options, print) {
insideAtRuleNode(path, "supports") && isMediaAndSupportsKeywords(node)
? " "
: "",
await print("group"),
print("group"),
];
}
case "value-paren": {
@@ -1033,9 +1030,9 @@ async function genericPrint(path, options, print) {
}
}
async function printNodeSequence(path, options, print) {
function printNodeSequence(path, options, print) {
const parts = [];
await path.each(async (pathChild, i, nodes) => {
path.each((pathChild, i, nodes) => {
const prevNode = nodes[i - 1];
if (
prevNode &&
@@ -1047,7 +1044,7 @@ async function printNodeSequence(path, options, print) {
options.originalText.slice(locStart(childNode), locEnd(childNode))
);
} else {
parts.push(await print());
parts.push(print());
}
if (i !== nodes.length - 1) {
+88 -107
View File
@@ -11,7 +11,7 @@ import { isNextLineEmpty, isNonEmptyArray } from "../common/util.js";
import { insertPragma } from "./pragma.js";
import { locStart, locEnd } from "./loc.js";
async function genericPrint(path, options, print) {
function genericPrint(path, options, print) {
const node = path.getValue();
if (!node) {
return "";
@@ -24,8 +24,8 @@ async function genericPrint(path, options, print) {
switch (node.kind) {
case "Document": {
const parts = [];
await path.each(async (pathChild, index, definitions) => {
parts.push(await print());
path.each((pathChild, index, definitions) => {
parts.push(print());
if (index !== definitions.length - 1) {
parts.push(hardline);
if (
@@ -42,7 +42,7 @@ async function genericPrint(path, options, print) {
const hasName = Boolean(node.name);
return [
hasOperation ? node.operation : "",
hasOperation && hasName ? [" ", await print("name")] : "",
hasOperation && hasName ? [" ", print("name")] : "",
hasOperation && !hasName && isNonEmptyArray(node.variableDefinitions)
? " "
: "",
@@ -53,22 +53,22 @@ async function genericPrint(path, options, print) {
softline,
join(
[ifBreak("", ", "), softline],
await path.map(print, "variableDefinitions")
path.map(print, "variableDefinitions")
),
]),
softline,
")",
])
: "",
await printDirectives(path, print, node),
printDirectives(path, print, node),
node.selectionSet ? (!hasOperation && !hasName ? "" : " ") : "",
await print("selectionSet"),
print("selectionSet"),
];
}
case "FragmentDefinition": {
return [
"fragment ",
await print("name"),
print("name"),
isNonEmptyArray(node.variableDefinitions)
? group([
"(",
@@ -76,7 +76,7 @@ async function genericPrint(path, options, print) {
softline,
join(
[ifBreak("", ", "), softline],
await path.map(print, "variableDefinitions")
path.map(print, "variableDefinitions")
),
]),
softline,
@@ -84,10 +84,10 @@ async function genericPrint(path, options, print) {
])
: "",
" on ",
await print("typeCondition"),
await printDirectives(path, print, node),
print("typeCondition"),
printDirectives(path, print, node),
" ",
await print("selectionSet"),
print("selectionSet"),
];
}
case "SelectionSet": {
@@ -95,10 +95,7 @@ async function genericPrint(path, options, print) {
"{",
indent([
hardline,
join(
hardline,
await printSequence(path, options, print, "selections")
),
join(hardline, printSequence(path, options, print, "selections")),
]),
hardline,
"}",
@@ -106,8 +103,8 @@ async function genericPrint(path, options, print) {
}
case "Field": {
return group([
node.alias ? [await print("alias"), ": "] : "",
await print("name"),
node.alias ? [print("alias"), ": "] : "",
print("name"),
node.arguments.length > 0
? group([
"(",
@@ -115,16 +112,16 @@ async function genericPrint(path, options, print) {
softline,
join(
[ifBreak("", ", "), softline],
await printSequence(path, options, print, "arguments")
printSequence(path, options, print, "arguments")
),
]),
softline,
")",
])
: "",
await printDirectives(path, print, node),
printDirectives(path, print, node),
node.selectionSet ? " " : "",
await print("selectionSet"),
print("selectionSet"),
]);
}
case "Name": {
@@ -161,14 +158,14 @@ async function genericPrint(path, options, print) {
return "null";
}
case "Variable": {
return ["$", await print("name")];
return ["$", print("name")];
}
case "ListValue": {
return group([
"[",
indent([
softline,
join([ifBreak("", ", "), softline], await path.map(print, "values")),
join([ifBreak("", ", "), softline], path.map(print, "values")),
]),
softline,
"]",
@@ -180,7 +177,7 @@ async function genericPrint(path, options, print) {
options.bracketSpacing && node.fields.length > 0 ? " " : "",
indent([
softline,
join([ifBreak("", ", "), softline], await path.map(print, "fields")),
join([ifBreak("", ", "), softline], path.map(print, "fields")),
]),
softline,
ifBreak(
@@ -192,13 +189,13 @@ async function genericPrint(path, options, print) {
}
case "ObjectField":
case "Argument": {
return [await print("name"), ": ", await print("value")];
return [print("name"), ": ", print("value")];
}
case "Directive": {
return [
"@",
await print("name"),
print("name"),
node.arguments.length > 0
? group([
"(",
@@ -206,7 +203,7 @@ async function genericPrint(path, options, print) {
softline,
join(
[ifBreak("", ", "), softline],
await printSequence(path, options, print, "arguments")
printSequence(path, options, print, "arguments")
),
]),
softline,
@@ -222,35 +219,32 @@ async function genericPrint(path, options, print) {
case "VariableDefinition": {
return [
await print("variable"),
print("variable"),
": ",
await print("type"),
node.defaultValue ? [" = ", await print("defaultValue")] : "",
await printDirectives(path, print, node),
print("type"),
node.defaultValue ? [" = ", print("defaultValue")] : "",
printDirectives(path, print, node),
];
}
case "ObjectTypeExtension":
case "ObjectTypeDefinition": {
return [
await print("description"),
print("description"),
node.description ? hardline : "",
node.kind === "ObjectTypeExtension" ? "extend " : "",
"type ",
await print("name"),
print("name"),
node.interfaces.length > 0
? [" implements ", ...(await printInterfaces(path, options, print))]
? [" implements ", ...printInterfaces(path, options, print)]
: "",
await printDirectives(path, print, node),
printDirectives(path, print, node),
node.fields.length > 0
? [
" {",
indent([
hardline,
join(
hardline,
await printSequence(path, options, print, "fields")
),
join(hardline, printSequence(path, options, print, "fields")),
]),
hardline,
"}",
@@ -261,9 +255,9 @@ async function genericPrint(path, options, print) {
case "FieldDefinition": {
return [
await print("description"),
print("description"),
node.description ? hardline : "",
await print("name"),
print("name"),
node.arguments.length > 0
? group([
"(",
@@ -271,7 +265,7 @@ async function genericPrint(path, options, print) {
softline,
join(
[ifBreak("", ", "), softline],
await printSequence(path, options, print, "arguments")
printSequence(path, options, print, "arguments")
),
]),
softline,
@@ -279,18 +273,18 @@ async function genericPrint(path, options, print) {
])
: "",
": ",
await print("type"),
await printDirectives(path, print, node),
print("type"),
printDirectives(path, print, node),
];
}
case "DirectiveDefinition": {
return [
await print("description"),
print("description"),
node.description ? hardline : "",
"directive ",
"@",
await print("name"),
print("name"),
node.arguments.length > 0
? group([
"(",
@@ -298,7 +292,7 @@ async function genericPrint(path, options, print) {
softline,
join(
[ifBreak("", ", "), softline],
await printSequence(path, options, print, "arguments")
printSequence(path, options, print, "arguments")
),
]),
softline,
@@ -307,29 +301,26 @@ async function genericPrint(path, options, print) {
: "",
node.repeatable ? " repeatable" : "",
" on ",
join(" | ", await path.map(print, "locations")),
join(" | ", path.map(print, "locations")),
];
}
case "EnumTypeExtension":
case "EnumTypeDefinition": {
return [
await print("description"),
print("description"),
node.description ? hardline : "",
node.kind === "EnumTypeExtension" ? "extend " : "",
"enum ",
await print("name"),
await printDirectives(path, print, node),
print("name"),
printDirectives(path, print, node),
node.values.length > 0
? [
" {",
indent([
hardline,
join(
hardline,
await printSequence(path, options, print, "values")
),
join(hardline, printSequence(path, options, print, "values")),
]),
hardline,
"}",
@@ -340,43 +331,40 @@ async function genericPrint(path, options, print) {
case "EnumValueDefinition": {
return [
await print("description"),
print("description"),
node.description ? hardline : "",
await print("name"),
await printDirectives(path, print, node),
print("name"),
printDirectives(path, print, node),
];
}
case "InputValueDefinition": {
return [
await print("description"),
print("description"),
node.description ? (node.description.block ? hardline : line) : "",
await print("name"),
print("name"),
": ",
await print("type"),
node.defaultValue ? [" = ", await print("defaultValue")] : "",
await printDirectives(path, print, node),
print("type"),
node.defaultValue ? [" = ", print("defaultValue")] : "",
printDirectives(path, print, node),
];
}
case "InputObjectTypeExtension":
case "InputObjectTypeDefinition": {
return [
await print("description"),
print("description"),
node.description ? hardline : "",
node.kind === "InputObjectTypeExtension" ? "extend " : "",
"input ",
await print("name"),
await printDirectives(path, print, node),
print("name"),
printDirectives(path, print, node),
node.fields.length > 0
? [
" {",
indent([
hardline,
join(
hardline,
await printSequence(path, options, print, "fields")
),
join(hardline, printSequence(path, options, print, "fields")),
]),
hardline,
"}",
@@ -388,7 +376,7 @@ async function genericPrint(path, options, print) {
case "SchemaExtension": {
return [
"extend schema",
await printDirectives(path, print, node),
printDirectives(path, print, node),
...(node.operationTypes.length > 0
? [
" {",
@@ -396,7 +384,7 @@ async function genericPrint(path, options, print) {
hardline,
join(
hardline,
await printSequence(path, options, print, "operationTypes")
printSequence(path, options, print, "operationTypes")
),
]),
hardline,
@@ -407,17 +395,17 @@ async function genericPrint(path, options, print) {
}
case "SchemaDefinition": {
return [
await print("description"),
print("description"),
node.description ? hardline : "",
"schema",
await printDirectives(path, print, node),
printDirectives(path, print, node),
" {",
node.operationTypes.length > 0
? indent([
hardline,
join(
hardline,
await printSequence(path, options, print, "operationTypes")
printSequence(path, options, print, "operationTypes")
),
])
: "",
@@ -427,30 +415,27 @@ async function genericPrint(path, options, print) {
}
case "OperationTypeDefinition": {
return [await print("operation"), ": ", await print("type")];
return [print("operation"), ": ", print("type")];
}
case "InterfaceTypeExtension":
case "InterfaceTypeDefinition": {
return [
await print("description"),
print("description"),
node.description ? hardline : "",
node.kind === "InterfaceTypeExtension" ? "extend " : "",
"interface ",
await print("name"),
print("name"),
node.interfaces.length > 0
? [" implements ", ...(await printInterfaces(path, options, print))]
? [" implements ", ...printInterfaces(path, options, print)]
: "",
await printDirectives(path, print, node),
printDirectives(path, print, node),
node.fields.length > 0
? [
" {",
indent([
hardline,
join(
hardline,
await printSequence(path, options, print, "fields")
),
join(hardline, printSequence(path, options, print, "fields")),
]),
hardline,
"}",
@@ -460,40 +445,36 @@ async function genericPrint(path, options, print) {
}
case "FragmentSpread": {
return [
"...",
await print("name"),
await printDirectives(path, print, node),
];
return ["...", print("name"), printDirectives(path, print, node)];
}
case "InlineFragment": {
return [
"...",
node.typeCondition ? [" on ", await print("typeCondition")] : "",
await printDirectives(path, print, node),
node.typeCondition ? [" on ", print("typeCondition")] : "",
printDirectives(path, print, node),
" ",
await print("selectionSet"),
print("selectionSet"),
];
}
case "UnionTypeExtension":
case "UnionTypeDefinition": {
return group([
await print("description"),
print("description"),
node.description ? hardline : "",
group([
node.kind === "UnionTypeExtension" ? "extend " : "",
"union ",
await print("name"),
await printDirectives(path, print, node),
print("name"),
printDirectives(path, print, node),
node.types.length > 0
? [
" =",
ifBreak("", " "),
indent([
ifBreak([line, " "]),
join([line, "| "], await path.map(print, "types")),
join([line, "| "], path.map(print, "types")),
]),
]
: "",
@@ -504,21 +485,21 @@ async function genericPrint(path, options, print) {
case "ScalarTypeExtension":
case "ScalarTypeDefinition": {
return [
await print("description"),
print("description"),
node.description ? hardline : "",
node.kind === "ScalarTypeExtension" ? "extend " : "",
"scalar ",
await print("name"),
await printDirectives(path, print, node),
print("name"),
printDirectives(path, print, node),
];
}
case "NonNullType": {
return [await print("type"), "!"];
return [print("type"), "!"];
}
case "ListType": {
return ["[", await print("type"), "]"];
return ["[", print("type"), "]"];
}
default:
@@ -527,12 +508,12 @@ async function genericPrint(path, options, print) {
}
}
async function printDirectives(path, print, node) {
function printDirectives(path, print, node) {
if (node.directives.length === 0) {
return "";
}
const printed = join(line, await path.map(print, "directives"));
const printed = join(line, path.map(print, "directives"));
if (
node.kind === "FragmentDefinition" ||
@@ -545,8 +526,8 @@ async function printDirectives(path, print, node) {
}
function printSequence(path, options, print, property) {
return path.map(async (path, index, sequence) => {
const printed = await print();
return path.map((path, index, sequence) => {
const printed = print();
if (
index < sequence.length - 1 &&
@@ -573,11 +554,11 @@ function printComment(commentPath) {
throw new Error("Not a comment: " + JSON.stringify(comment));
}
async function printInterfaces(path, options, print) {
function printInterfaces(path, options, print) {
const node = path.getNode();
const parts = [];
const { interfaces } = node;
const printed = await path.map((node) => print(node), "interfaces");
const printed = path.map((node) => print(node), "interfaces");
for (let index = 0; index < interfaces.length; index++) {
const interfaceNode = interfaces[index];
+44 -44
View File
@@ -31,7 +31,7 @@ const NEWLINES_TO_PRESERVE_MAX = 2;
// Formatter based on @glimmerjs/syntax's built-in test formatter:
// https://github.com/glimmerjs/glimmer-vm/blob/master/packages/%40glimmer/syntax/lib/generation/print.ts
async function print(path, options, print) {
function print(path, options, print) {
const node = path.getValue();
/* istanbul ignore if*/
@@ -49,11 +49,11 @@ async function print(path, options, print) {
case "Block":
case "Program":
case "Template": {
return group(await path.map(print, "body"));
return group(path.map(print, "body"));
}
case "ElementNode": {
const startingTag = group(await printStartingTag(path, print));
const startingTag = group(printStartingTag(path, print));
const escapeNextElementNode =
options.htmlWhitespaceSensitivity === "ignore" &&
@@ -74,7 +74,7 @@ async function print(path, options, print) {
if (options.htmlWhitespaceSensitivity === "ignore") {
return [
startingTag,
indent(await printChildren(path, options, print)),
indent(printChildren(path, options, print)),
hardline,
indent(endingTag),
escapeNextElementNode,
@@ -83,7 +83,7 @@ async function print(path, options, print) {
return [
startingTag,
indent(group(await printChildren(path, options, print))),
indent(group(printChildren(path, options, print))),
indent(endingTag),
escapeNextElementNode,
];
@@ -101,30 +101,30 @@ async function print(path, options, print) {
if (isElseIf) {
return [
await printElseIfBlock(path, print),
await printProgram(path, print, options),
await printInverse(path, print, options),
printElseIfBlock(path, print),
printProgram(path, print, options),
printInverse(path, print, options),
];
}
return [
await printOpenBlock(path, print),
printOpenBlock(path, print),
group([
await printProgram(path, print, options),
await printInverse(path, print, options),
await printCloseBlock(path, print, options),
printProgram(path, print, options),
printInverse(path, print, options),
printCloseBlock(path, print, options),
]),
];
}
case "ElementModifierStatement": {
return group(["{{", await printPathAndParams(path, print), "}}"]);
return group(["{{", printPathAndParams(path, print), "}}"]);
}
case "MustacheStatement": {
return group([
printOpeningMustache(node),
await printPathAndParams(path, print),
printPathAndParams(path, print),
printClosingMustache(node),
]);
}
@@ -132,7 +132,7 @@ async function print(path, options, print) {
case "SubExpression": {
return group([
"(",
await printSubExpressionPathAndParams(path, print),
printSubExpressionPathAndParams(path, print),
softline,
")",
]);
@@ -162,7 +162,7 @@ async function print(path, options, print) {
).quote
: "";
const valueDoc = await print("value");
const valueDoc = print("value");
return [
node.name,
@@ -178,10 +178,10 @@ async function print(path, options, print) {
}
case "Hash": {
return join(line, await path.map(print, "pairs"));
return join(line, path.map(print, "pairs"));
}
case "HashPair": {
return [node.key, "=", await print("value")];
return [node.key, "=", print("value")];
}
case "TextNode": {
/* if `{{my-component}}` (or any text containing "{{")
@@ -423,7 +423,7 @@ function sortByLoc(a, b) {
return locStart(a) - locStart(b);
}
async function printStartingTag(path, print) {
function printStartingTag(path, print) {
const node = path.getValue();
const types = ["attributes", "modifiers", "comments"].filter((property) =>
@@ -432,9 +432,9 @@ async function printStartingTag(path, print) {
const attributes = types.flatMap((type) => node[type]).sort(sortByLoc);
for (const attributeType of types) {
await path.each(async (attributePath) => {
path.each((attributePath) => {
const index = attributes.indexOf(attributePath.getValue());
attributes.splice(index, 1, [line, await print()]);
attributes.splice(index, 1, [line, print()]);
}, attributeType);
}
@@ -452,8 +452,8 @@ function printChildren(path, options, print) {
return "";
}
return path.map(async (childPath, childIndex) => {
const printedChild = await print();
return path.map((childPath, childIndex) => {
const printedChild = print();
if (childIndex === 0 && options.htmlWhitespaceSensitivity === "ignore") {
return [softline, printedChild];
@@ -523,15 +523,15 @@ function printInverseBlockClosingMustache(node) {
return [strip, closing];
}
async function printOpenBlock(path, print) {
function printOpenBlock(path, print) {
const node = path.getValue();
const openingMustache = printOpeningBlockOpeningMustache(node);
const closingMustache = printOpeningBlockClosingMustache(node);
const attributes = [await printPath(path, print)];
const attributes = [printPath(path, print)];
const params = await printParams(path, print);
const params = printParams(path, print);
if (params) {
attributes.push(line, params);
}
@@ -558,18 +558,18 @@ function printElseBlock(node, options) {
];
}
async function printElseIfBlock(path, print) {
function printElseIfBlock(path, print) {
const parentNode = path.getParentNode(1);
return [
printInverseBlockOpeningMustache(parentNode),
"else if ",
await printParams(path, print),
printParams(path, print),
printInverseBlockClosingMustache(parentNode),
];
}
async function printCloseBlock(path, print, options) {
function printCloseBlock(path, print, options) {
const node = path.getValue();
if (options.htmlWhitespaceSensitivity === "ignore") {
@@ -580,14 +580,14 @@ async function printCloseBlock(path, print, options) {
return [
escape,
printClosingBlockOpeningMustache(node),
await print("path"),
print("path"),
printClosingBlockClosingMustache(node),
];
}
return [
printClosingBlockOpeningMustache(node),
await print("path"),
print("path"),
printClosingBlockClosingMustache(node),
];
}
@@ -612,14 +612,14 @@ function blockStatementHasElse(node) {
return isNodeOfSomeType(node, ["BlockStatement"]) && node.inverse;
}
async function printProgram(path, print, options) {
function printProgram(path, print, options) {
const node = path.getValue();
if (blockStatementHasOnlyWhitespaceInProgram(node)) {
return "";
}
const program = await print("program");
const program = print("program");
if (options.htmlWhitespaceSensitivity === "ignore") {
return indent([hardline, program]);
@@ -628,10 +628,10 @@ async function printProgram(path, print, options) {
return indent(program);
}
async function printInverse(path, print, options) {
function printInverse(path, print, options) {
const node = path.getValue();
const inverse = await print("inverse");
const inverse = print("inverse");
const printed =
options.htmlWhitespaceSensitivity === "ignore"
? [hardline, inverse]
@@ -730,9 +730,9 @@ function needsOppositeQuote(path) {
/* SubExpression print helpers */
async function printSubExpressionPathAndParams(path, print) {
const printed = await printPath(path, print);
const params = await printParams(path, print);
function printSubExpressionPathAndParams(path, print) {
const printed = printPath(path, print);
const params = printParams(path, print);
if (!params) {
return printed;
@@ -743,9 +743,9 @@ async function printSubExpressionPathAndParams(path, print) {
/* misc. print helpers */
async function printPathAndParams(path, print) {
const p = await printPath(path, print);
const params = await printParams(path, print);
function printPathAndParams(path, print) {
const p = printPath(path, print);
const params = printParams(path, print);
if (!params) {
return p;
@@ -758,17 +758,17 @@ function printPath(path, print) {
return print("path");
}
async function printParams(path, print) {
function printParams(path, print) {
const node = path.getValue();
const parts = [];
if (node.params.length > 0) {
const params = await path.map(print, "params");
const params = path.map(print, "params");
parts.push(...params);
}
if (node.hash && node.hash.pairs.length > 0) {
const hash = await print("hash");
const hash = print("hash");
parts.push(hash);
}
+15 -19
View File
@@ -35,7 +35,7 @@ import {
} from "./utils/index.js";
import getNodeContent from "./get-node-content.js";
async function printEmbeddedAttributeValue(node, htmlTextToDoc, options) {
function printEmbeddedAttributeValue(node, htmlTextToDoc, options) {
const isKeyMatched = (patterns) =>
new RegExp(patterns.join("|")).test(node.fullName);
const getValue = () => unescapeQuoteEntities(node.value);
@@ -95,7 +95,7 @@ async function printEmbeddedAttributeValue(node, htmlTextToDoc, options) {
const value = getValue();
if (!value.includes("{{")) {
return printExpand(
await attributeTextToDoc(value, {
attributeTextToDoc(value, {
parser: "css",
__isHTMLStyleAttribute: true,
})
@@ -137,7 +137,7 @@ async function printEmbeddedAttributeValue(node, htmlTextToDoc, options) {
? "__vue_ts_event_binding"
: "__vue_event_binding";
return printMaybeHug(
await attributeTextToDoc(value, {
attributeTextToDoc(value, {
parser,
})
);
@@ -145,13 +145,13 @@ async function printEmbeddedAttributeValue(node, htmlTextToDoc, options) {
if (isKeyMatched(vueExpressionBindingPatterns)) {
return printMaybeHug(
await attributeTextToDoc(getValue(), { parser: "__vue_expression" })
attributeTextToDoc(getValue(), { parser: "__vue_expression" })
);
}
if (isKeyMatched(jsExpressionBindingPatterns)) {
return printMaybeHug(
await attributeTextToDoc(getValue(), { parser: "__js_expression" })
attributeTextToDoc(getValue(), { parser: "__js_expression" })
);
}
}
@@ -189,15 +189,11 @@ async function printEmbeddedAttributeValue(node, htmlTextToDoc, options) {
const ngI18nPatterns = ["^i18n(-.+)?$"];
if (isKeyMatched(ngStatementBindingPatterns)) {
return printMaybeHug(
await ngTextToDoc(getValue(), { parser: "__ng_action" })
);
return printMaybeHug(ngTextToDoc(getValue(), { parser: "__ng_action" }));
}
if (isKeyMatched(ngExpressionBindingPatterns)) {
return printMaybeHug(
await ngTextToDoc(getValue(), { parser: "__ng_binding" })
);
return printMaybeHug(ngTextToDoc(getValue(), { parser: "__ng_binding" }));
}
if (isKeyMatched(ngI18nPatterns)) {
@@ -210,7 +206,7 @@ async function printEmbeddedAttributeValue(node, htmlTextToDoc, options) {
if (isKeyMatched(ngDirectiveBindingPatterns)) {
return printMaybeHug(
await ngTextToDoc(getValue(), { parser: "__ng_directive" })
ngTextToDoc(getValue(), { parser: "__ng_directive" })
);
}
@@ -228,7 +224,7 @@ async function printEmbeddedAttributeValue(node, htmlTextToDoc, options) {
"{{",
indent([
line,
await ngTextToDoc(part, {
ngTextToDoc(part, {
parser: "__ng_interpolation",
__isInHtmlInterpolation: true, // to avoid unexpected `}}`
}),
@@ -249,7 +245,7 @@ async function printEmbeddedAttributeValue(node, htmlTextToDoc, options) {
return null;
}
async function embed(path, print, textToDoc, options) {
function embed(path, print, textToDoc, options) {
const node = path.getValue();
switch (node.type) {
@@ -269,7 +265,7 @@ async function embed(path, print, textToDoc, options) {
let isEmpty = /^\s*$/.test(content);
let doc = "";
if (!isEmpty) {
doc = await textToDoc(
doc = textToDoc(
htmlTrimPreserveIndentation(content),
{ parser, __embeddedInHtml: true },
{ stripTrailingHardline: true }
@@ -279,7 +275,7 @@ async function embed(path, print, textToDoc, options) {
return [
printOpeningTagPrefix(node, options),
group(await printOpeningTag(path, options, print)),
group(printOpeningTag(path, options, print)),
isEmpty ? "" : hardline,
doc,
isEmpty ? "" : hardline,
@@ -314,7 +310,7 @@ async function embed(path, print, textToDoc, options) {
return [
breakParent,
printOpeningTagPrefix(node, options),
await textToDoc(value, textToDocOptions, {
textToDoc(value, textToDocOptions, {
stripTrailingHardline: true,
}),
printClosingTagSuffix(node, options),
@@ -338,7 +334,7 @@ async function embed(path, print, textToDoc, options) {
return [
indent([
line,
await textToDoc(node.value, textToDocOptions, {
textToDoc(node.value, textToDocOptions, {
stripTrailingHardline: true,
}),
]),
@@ -382,7 +378,7 @@ async function embed(path, print, textToDoc, options) {
}
}
const embeddedAttributeValueDoc = await printEmbeddedAttributeValue(
const embeddedAttributeValueDoc = printEmbeddedAttributeValue(
node,
(code, opts) =>
// strictly prefer single quote to avoid unnecessary html entity escape
+8 -12
View File
@@ -110,14 +110,14 @@ function printBetweenLine(prevNode, nextNode) {
: softline;
}
async function printChildren(path, options, print) {
function printChildren(path, options, print) {
const node = path.getValue();
if (forceBreakChildren(node)) {
return [
breakParent,
...(await path.map(async (childPath) => {
...path.map((childPath) => {
const childNode = childPath.getValue();
const prevBetweenLine = !childNode.prev
? ""
@@ -129,14 +129,14 @@ async function printChildren(path, options, print) {
prevBetweenLine,
forceNextEmptyLine(childNode.prev) ? hardline : "",
],
await printChild(childPath, options, print),
printChild(childPath, options, print),
];
}, "children")),
}, "children"),
];
}
const groupIds = node.children.map(() => Symbol(""));
return path.map(async (childPath, childIndex) => {
return path.map((childPath, childIndex) => {
const childNode = childPath.getValue();
if (isTextLikeNode(childNode)) {
@@ -144,13 +144,9 @@ async function printChildren(path, options, print) {
const prevBetweenLine = printBetweenLine(childNode.prev, childNode);
if (prevBetweenLine) {
if (forceNextEmptyLine(childNode.prev)) {
return [
hardline,
hardline,
await printChild(childPath, options, print),
];
return [hardline, hardline, printChild(childPath, options, print)];
}
return [prevBetweenLine, await printChild(childPath, options, print)];
return [prevBetweenLine, printChild(childPath, options, print)];
}
}
return printChild(childPath, options, print);
@@ -205,7 +201,7 @@ async function printChildren(path, options, print) {
...prevParts,
group([
...leadingParts,
group([await printChild(childPath, options, print), ...trailingParts], {
group([printChild(childPath, options, print), ...trailingParts], {
id: groupIds[childIndex],
}),
]),
+6 -6
View File
@@ -27,15 +27,15 @@ import {
} from "./tag.js";
import { printChildren } from "./children.js";
async function printElement(path, options, print) {
function printElement(path, options, print) {
const node = path.getValue();
if (shouldPreserveContent(node, options)) {
return [
printOpeningTagPrefix(node, options),
group(await printOpeningTag(path, options, print)),
group(printOpeningTag(path, options, print)),
...replaceTextEndOfLine(getNodeContent(node, options)),
...(await printClosingTag(node, options)),
...printClosingTag(node, options),
printClosingTagSuffix(node, options),
];
}
@@ -69,9 +69,9 @@ async function printElement(path, options, print) {
const attrGroupId = Symbol("element-attr-group-id");
const printTag = async (doc) =>
const printTag = (doc) =>
group([
group(await printOpeningTag(path, options, print), { id: attrGroupId }),
group(printOpeningTag(path, options, print), { id: attrGroupId }),
doc,
printClosingTag(node, options),
]);
@@ -163,7 +163,7 @@ async function printElement(path, options, print) {
forceBreakContent(node) ? breakParent : "",
printChildrenDoc([
printLineBeforeChildren(),
await printChildren(path, options, print),
printChildren(path, options, print),
]),
printLineAfterChildren(),
]);
+4 -4
View File
@@ -213,7 +213,7 @@ function needsToBorrowParentOpeningTagEndMarker(node) {
return !node.prev && node.isLeadingSpaceSensitive && !node.hasLeadingSpaces;
}
async function printAttributes(path, options, print) {
function printAttributes(path, options, print) {
const node = path.getValue();
if (!isNonEmptyArray(node.attrs)) {
@@ -238,7 +238,7 @@ async function printAttributes(path, options, print) {
? (attribute) => ignoreAttributeData.includes(attribute.rawName)
: () => false;
const printedAttributes = await path.map((attributePath) => {
const printedAttributes = path.map((attributePath) => {
const attribute = attributePath.getValue();
return hasPrettierIgnoreAttribute(attribute)
? replaceTextEndOfLine(
@@ -310,12 +310,12 @@ function printOpeningTagEnd(node) {
: printOpeningTagEndMarker(node);
}
async function printOpeningTag(path, options, print) {
function printOpeningTag(path, options, print) {
const node = path.getValue();
return [
printOpeningTagStart(node, options),
await printAttributes(path, options, print),
printAttributes(path, options, print),
node.isSelfClosing ? "" : printOpeningTagEnd(node),
];
}
+3 -3
View File
@@ -29,7 +29,7 @@ import {
import { printElement } from "./print/element.js";
import { printChildren } from "./print/children.js";
async function genericPrint(path, options, print) {
function genericPrint(path, options, print) {
const node = path.getValue();
switch (node.type) {
@@ -40,7 +40,7 @@ async function genericPrint(path, options, print) {
options.__onHtmlRoot(node);
}
// use original concat to not break stripTrailingHardline
return [group(await printChildren(path, options, print)), hardline];
return [group(printChildren(path, options, print)), hardline];
case "element":
case "ieConditionalComment": {
return printElement(path, options, print);
@@ -51,7 +51,7 @@ async function genericPrint(path, options, print) {
case "interpolation":
return [
printOpeningTagStart(node, options),
...(await path.map(print, "children")),
...path.map(print, "children"),
printClosingTagEnd(node, options),
];
case "text": {
+5 -5
View File
@@ -6,11 +6,11 @@ import { group } from "../document/builders.js";
* v-for="(..., ...) in ..."
* v-for="(..., ...) of ..."
*/
async function printVueFor(value, attributeTextToDoc) {
function printVueFor(value, textToDoc) {
const { left, operator, right } = parseVueFor(value);
return [
group(
await attributeTextToDoc(`function _(${left}) {}`, {
textToDoc(`function _(${left}) {}`, {
parser: "babel",
__isVueForBindingLeft: true,
})
@@ -18,7 +18,7 @@ async function printVueFor(value, attributeTextToDoc) {
" ",
operator,
" ",
await attributeTextToDoc(
textToDoc(
right,
{ parser: "__js_expression" },
{ stripTrailingHardline: true }
@@ -72,8 +72,8 @@ function parseVueFor(value) {
};
}
function printVueBindings(value, attributeTextToDoc) {
return attributeTextToDoc(`function _(${value}) {}`, {
function printVueBindings(value, textToDoc) {
return textToDoc(`function _(${value}) {}`, {
parser: "babel",
__isVueBindings: true,
});
+3 -3
View File
@@ -3,7 +3,7 @@ import { indent, hardline, softline } from "../../document/builders.js";
import { mapDoc, replaceEndOfLine, cleanDoc } from "../../document/utils.js";
import { printTemplateExpressions } from "../print/template-literal.js";
async function format(path, print, textToDoc) {
function format(path, print, textToDoc) {
const node = path.getValue();
// Get full template literal with expressions replaced by placeholders
@@ -20,12 +20,12 @@ async function format(path, print, textToDoc) {
currVal,
""
);
const doc = await textToDoc(
const doc = textToDoc(
text,
{ parser: "scss" },
{ stripTrailingHardline: true }
);
const expressionDocs = await printTemplateExpressions(path, print);
const expressionDocs = printTemplateExpressions(path, print);
return transformCssDoc(doc, node, expressionDocs);
}
+3 -3
View File
@@ -4,7 +4,7 @@ import {
printTemplateExpressions,
} from "../print/template-literal.js";
async function format(path, print, textToDoc) {
function format(path, print, textToDoc) {
const node = path.getValue();
const numQuasis = node.quasis.length;
@@ -12,7 +12,7 @@ async function format(path, print, textToDoc) {
return "``";
}
const expressionDocs = await printTemplateExpressions(path, print);
const expressionDocs = printTemplateExpressions(path, print);
const parts = [];
for (let i = 0; i < numQuasis; i++) {
@@ -46,7 +46,7 @@ async function format(path, print, textToDoc) {
if (commentsAndWhitespaceOnly) {
doc = printGraphqlComments(lines);
} else {
doc = await textToDoc(
doc = textToDoc(
text,
{ parser: "graphql" },
{ stripTrailingHardline: true }
+3 -3
View File
@@ -7,7 +7,7 @@ import {
// The counter is needed to distinguish nested embeds.
let htmlTemplateLiteralCounter = 0;
async function format(path, print, textToDoc, options, { parser }) {
function format(path, print, textToDoc, options, { parser }) {
const node = path.getValue();
const counter = htmlTemplateLiteralCounter;
htmlTemplateLiteralCounter = (htmlTemplateLiteralCounter + 1) >>> 0;
@@ -23,14 +23,14 @@ async function format(path, print, textToDoc, options, { parser }) {
)
.join("");
const expressionDocs = await printTemplateExpressions(path, print);
const expressionDocs = printTemplateExpressions(path, print);
if (expressionDocs.length === 0 && text.trim().length === 0) {
return "``";
}
const placeholderRegex = new RegExp(composePlaceholder("(\\d+)"), "g");
let topLevelCount = 0;
const doc = await textToDoc(
const doc = textToDoc(
text,
{
parser,
+2 -2
View File
@@ -6,7 +6,7 @@ import {
} from "../../document/builders.js";
import { escapeTemplateCharacters } from "../print/template-literal.js";
async function format(path, print, textToDoc) {
function format(path, print, textToDoc) {
const node = path.getValue();
let text = node.quasis[0].value.raw.replace(
/((?:\\\\)*)\\`/g,
@@ -18,7 +18,7 @@ async function format(path, print, textToDoc) {
text = text.replace(new RegExp(`^${indentation}`, "gm"), "");
}
const doc = escapeTemplateCharacters(
await textToDoc(
textToDoc(
text,
{ parser: "markdown", __inJsTemplate: true },
{ stripTrailingHardline: true }
+14 -14
View File
@@ -4,7 +4,7 @@ import { printBinaryishExpression } from "./binaryish.js";
/** @typedef {import("../../common/ast-path.js").default} AstPath */
async function printAngular(path, options, print) {
function printAngular(path, options, print) {
const node = path.getValue();
// Angular nodes always starts with `NG`
@@ -15,7 +15,7 @@ async function printAngular(path, options, print) {
switch (node.type) {
case "NGRoot":
return [
await print("node"),
print("node"),
!hasComment(node.node)
? ""
: " //" + getComments(node.node)[0].value.trimEnd(),
@@ -26,9 +26,9 @@ async function printAngular(path, options, print) {
return group(
join(
[";", line],
await path.map(
async (childPath) =>
hasNgSideEffect(childPath) ? print() : ["(", await print(), ")"],
path.map(
(childPath) =>
hasNgSideEffect(childPath) ? print() : ["(", print(), ")"],
"expressions"
)
)
@@ -39,13 +39,13 @@ async function printAngular(path, options, print) {
return [node.prefix, ": ", node.value.trim()];
case "NGMicrosyntax":
return path.map(
async (childPath, index) => [
(childPath, index) => [
index === 0
? ""
: isNgForOf(childPath.getValue(), index, node)
? " "
: [";", line],
await print(),
print(),
],
"body"
);
@@ -55,8 +55,8 @@ async function printAngular(path, options, print) {
: JSON.stringify(node.name);
case "NGMicrosyntaxExpression":
return [
await print("expression"),
node.alias === null ? "" : [" as ", await print("alias")],
print("expression"),
node.alias === null ? "" : [" as ", print("alias")],
];
case "NGMicrosyntaxKeyedExpression": {
const index = path.getName();
@@ -72,19 +72,19 @@ async function printAngular(path, options, print) {
parentNode.body[index - 1].key.name === "then")) &&
parentNode.body[0].type === "NGMicrosyntaxExpression");
return [
await print("key"),
print("key"),
shouldNotPrintColon ? " " : ": ",
await print("expression"),
print("expression"),
];
}
case "NGMicrosyntaxLet":
return [
"let ",
await print("key"),
node.value === null ? "" : [" = ", await print("value")],
print("key"),
node.value === null ? "" : [" = ", print("value")],
];
case "NGMicrosyntaxAs":
return [await print("key"), " as ", await print("alias")];
return [print("key"), " as ", print("alias")];
default:
/* istanbul ignore next */
throw new Error(
+10 -15
View File
@@ -23,7 +23,7 @@ import { printOptionalToken, printTypeAnnotation } from "./misc.js";
/** @typedef {import("../../document/builders.js").Doc} Doc */
async function printArray(path, options, print) {
function printArray(path, options, print) {
const node = path.getValue();
/** @type{Doc[]} */
const parts = [];
@@ -103,14 +103,9 @@ async function printArray(path, options, print) {
indent([
softline,
shouldUseConciseFormatting
? await printArrayItemsConcisely(
path,
options,
print,
trailingComma
)
? printArrayItemsConcisely(path, options, print, trailingComma)
: [
await printArrayItems(path, options, "elements", print),
printArrayItems(path, options, "elements", print),
trailingComma,
],
printDanglingComments(path, options, /* sameIndent */ true),
@@ -125,7 +120,7 @@ async function printArray(path, options, print) {
parts.push(
printOptionalToken(path),
await printTypeAnnotation(path, options, print)
printTypeAnnotation(path, options, print)
);
return parts;
@@ -151,12 +146,12 @@ function isConciselyPrintedArray(node, options) {
);
}
async function printArrayItems(path, options, printPath, print) {
function printArrayItems(path, options, printPath, print) {
const printedElements = [];
let separatorParts = [];
await path.each(async (childPath) => {
printedElements.push(separatorParts, group(await print()));
path.each((childPath) => {
printedElements.push(separatorParts, group(print()));
separatorParts = [",", line];
if (
@@ -170,13 +165,13 @@ async function printArrayItems(path, options, printPath, print) {
return printedElements;
}
async function printArrayItemsConcisely(path, options, print, trailingComma) {
function printArrayItemsConcisely(path, options, print, trailingComma) {
const parts = [];
await path.each(async (childPath, i, elements) => {
path.each((childPath, i, elements) => {
const isLast = i === elements.length - 1;
parts.push([await print(), isLast ? trailingComma : ","]);
parts.push([print(), isLast ? trailingComma : ","]);
if (!isLast) {
parts.push(
+17 -23
View File
@@ -24,7 +24,7 @@ import {
import { shouldInlineLogicalExpression } from "./binaryish.js";
import { printCallExpression } from "./call-expression.js";
async function printAssignment(
function printAssignment(
path,
options,
print,
@@ -32,15 +32,9 @@ async function printAssignment(
operator,
rightPropertyName
) {
const layout = await chooseLayout(
path,
options,
print,
leftDoc,
rightPropertyName
);
const layout = chooseLayout(path, options, print, leftDoc, rightPropertyName);
const rightDoc = await print(rightPropertyName, { assignmentLayout: layout });
const rightDoc = print(rightPropertyName, { assignmentLayout: layout });
switch (layout) {
// First break after operator, then the sides are broken independently on their own lines
@@ -82,23 +76,23 @@ async function printAssignment(
}
}
async function printAssignmentExpression(path, options, print) {
function printAssignmentExpression(path, options, print) {
const node = path.getValue();
return printAssignment(
path,
options,
print,
await print("left"),
print("left"),
[" ", node.operator],
"right"
);
}
async function printVariableDeclarator(path, options, print) {
return printAssignment(path, options, print, await print("id"), " =", "init");
function printVariableDeclarator(path, options, print) {
return printAssignment(path, options, print, print("id"), " =", "init");
}
async function chooseLayout(path, options, print, leftDoc, rightPropertyName) {
function chooseLayout(path, options, print, leftDoc, rightPropertyName) {
const node = path.getValue();
const rightNode = node[rightPropertyName];
@@ -159,7 +153,7 @@ async function chooseLayout(path, options, print, leftDoc, rightPropertyName) {
const hasShortKey = isObjectPropertyWithShortKey(node, leftDoc, options);
if (
await path.call(
path.call(
() => shouldBreakAfterOperator(path, options, print, hasShortKey),
rightPropertyName
)
@@ -181,7 +175,7 @@ async function chooseLayout(path, options, print, leftDoc, rightPropertyName) {
return "fluid";
}
async function shouldBreakAfterOperator(path, options, print, hasShortKey) {
function shouldBreakAfterOperator(path, options, print, hasShortKey) {
const rightNode = path.getValue();
if (isBinaryish(rightNode) && !shouldInlineLogicalExpression(rightNode)) {
@@ -219,10 +213,10 @@ async function shouldBreakAfterOperator(path, options, print, hasShortKey) {
}
if (
isStringLiteral(node) ||
(await path.call(
path.call(
() => isPoorlyBreakableMemberOrCallChain(path, options, print),
...propertiesForPath
))
)
) {
return true;
}
@@ -334,7 +328,7 @@ function isTypeReference(node) {
* A chain with no calls at all or whose calls are all without arguments or with lone short arguments,
* excluding chains printed by `printMemberChain`
*/
async function isPoorlyBreakableMemberOrCallChain(
function isPoorlyBreakableMemberOrCallChain(
path,
options,
print,
@@ -350,7 +344,7 @@ async function isPoorlyBreakableMemberOrCallChain(
if (isCallExpression(node)) {
/** @type {any} TODO */
const doc = await printCallExpression(path, options, print);
const doc = printCallExpression(path, options, print);
if (doc.label === "member-chain") {
return false;
}
@@ -363,7 +357,7 @@ async function isPoorlyBreakableMemberOrCallChain(
return false;
}
if (await isCallExpressionWithComplexTypeArguments(node, print)) {
if (isCallExpressionWithComplexTypeArguments(node, print)) {
return false;
}
@@ -437,7 +431,7 @@ function isObjectPropertyWithShortKey(node, keyDoc, options) {
);
}
async function isCallExpressionWithComplexTypeArguments(node, print) {
function isCallExpressionWithComplexTypeArguments(node, print) {
const typeArgs = getTypeArgumentsFromCallExpression(node);
if (isNonEmptyArray(typeArgs)) {
if (typeArgs.length > 1) {
@@ -459,7 +453,7 @@ async function isCallExpressionWithComplexTypeArguments(node, print) {
const typeArgsKeyName = node.typeParameters
? "typeParameters"
: "typeArguments";
if (willBreak(await print(typeArgsKeyName))) {
if (willBreak(print(typeArgsKeyName))) {
return true;
}
}
+10 -12
View File
@@ -27,7 +27,7 @@ import {
/** @typedef {import("../../document/builders.js").Doc} Doc */
let uid = 0;
async function printBinaryishExpression(path, options, print) {
function printBinaryishExpression(path, options, print) {
const node = path.getValue();
const parent = path.getParentNode();
const parentParent = path.getParentNode(1);
@@ -40,7 +40,7 @@ async function printBinaryishExpression(path, options, print) {
const isHackPipeline =
isEnabledHackPipeline(options) && node.operator === "|>";
const parts = await printBinaryishExpressions(
const parts = printBinaryishExpressions(
path,
print,
options,
@@ -182,7 +182,7 @@ async function printBinaryishExpression(path, options, print) {
// precedence level and the AST is structured based on precedence
// level, things are naturally broken up correctly, i.e. `&&` is
// broken before `+`.
async function printBinaryishExpressions(
function printBinaryishExpressions(
path,
print,
options,
@@ -193,7 +193,7 @@ async function printBinaryishExpressions(
// Simply print the node normally.
if (!isBinaryish(node)) {
return [group(await print())];
return [group(print())];
}
/** @type{Doc[]} */
@@ -212,7 +212,7 @@ async function printBinaryishExpressions(
// which is unique in that it is right-associative.)
if (shouldFlatten(node.operator, node.left.operator)) {
// Flatten them out by recursively calling this function.
parts = await path.call(
parts = path.call(
(left) =>
printBinaryishExpressions(
left,
@@ -224,7 +224,7 @@ async function printBinaryishExpressions(
"left"
);
} else {
parts.push(group(await print("left")));
parts.push(group(print("left")));
}
const shouldInline = shouldInlineLogicalExpression(node);
@@ -243,9 +243,7 @@ async function printBinaryishExpressions(
": ",
join(
[line, ": "],
(await path.map(print, "arguments")).map((arg) =>
align(2, group(arg))
)
path.map(print, "arguments").map((arg) => align(2, group(arg)))
),
])
)
@@ -254,10 +252,10 @@ async function printBinaryishExpressions(
/** @type {Doc} */
let right;
if (shouldInline) {
right = [operator, " ", await print("right"), rightSuffix];
right = [operator, " ", print("right"), rightSuffix];
} else {
const isHackPipeline = isEnabledHackPipeline(options) && operator === "|>";
const rightContent = await (isHackPipeline
const rightContent = isHackPipeline
? path.call(
(left) =>
printBinaryishExpressions(
@@ -269,7 +267,7 @@ async function printBinaryishExpressions(
),
"right"
)
: print("right"));
: print("right");
right = [
lineBeforeOperator ? line : "",
operator,
+6 -6
View File
@@ -12,7 +12,7 @@ import { printBody } from "./statement.js";
/** @typedef {import("../../document/builders.js").Doc} Doc */
async function printBlock(path, options, print) {
function printBlock(path, options, print) {
const node = path.getValue();
const parts = [];
@@ -26,7 +26,7 @@ async function printBlock(path, options, print) {
}
parts.push("{");
const printed = await printBlockBody(path, options, print);
const printed = printBlockBody(path, options, print);
if (printed) {
parts.push(indent([hardline, printed]), hardline);
} else {
@@ -60,7 +60,7 @@ async function printBlock(path, options, print) {
return parts;
}
async function printBlockBody(path, options, print) {
function printBlockBody(path, options, print) {
const node = path.getValue();
const nodeHasDirectives = isNonEmptyArray(node.directives);
@@ -74,8 +74,8 @@ async function printBlockBody(path, options, print) {
const parts = [];
// Babel 6
if (nodeHasDirectives) {
await path.each(async (childPath, index, directives) => {
parts.push(await print());
path.each((childPath, index, directives) => {
parts.push(print());
if (index < directives.length - 1 || nodeHasBody || nodeHasComment) {
parts.push(hardline);
if (isNextLineEmpty(childPath.getValue(), options)) {
@@ -86,7 +86,7 @@ async function printBlockBody(path, options, print) {
}
if (nodeHasBody) {
parts.push(await printBody(path, options, print));
parts.push(printBody(path, options, print));
}
if (nodeHasComment) {
+8 -14
View File
@@ -31,7 +31,7 @@ import { willBreak } from "../../document/utils.js";
import { ArgExpansionBailout } from "../../common/errors.js";
import { isConciselyPrintedArray } from "./array.js";
async function printCallArguments(path, options, print) {
function printCallArguments(path, options, print) {
const node = path.getValue();
const isDynamicImport = node.type === "ImportExpression";
@@ -46,22 +46,16 @@ async function printCallArguments(path, options, print) {
// useEffect(() => { ... }, [foo, bar, baz])
if (isReactHookCallWithDepsArray(args)) {
return [
"(",
await print(["arguments", 0]),
", ",
await print(["arguments", 1]),
")",
];
return ["(", print(["arguments", 0]), ", ", print(["arguments", 1]), ")"];
}
let anyArgEmptyLine = false;
let hasEmptyLineFollowingFirstArg = false;
const lastArgIndex = args.length - 1;
const printedArguments = [];
await iterateCallArgumentsPath(path, async (argPath, index) => {
iterateCallArgumentsPath(path, (argPath, index) => {
const arg = argPath.getNode();
const parts = [await print()];
const parts = [print()];
if (index === lastArgIndex) {
// do nothing
@@ -116,12 +110,12 @@ async function printCallArguments(path, options, print) {
let printedExpanded = [];
try {
await path.try(async () => {
await iterateCallArgumentsPath(path, async (argPath, i) => {
path.try(() => {
iterateCallArgumentsPath(path, (argPath, i) => {
if (shouldGroupFirst && i === 0) {
printedExpanded = [
[
await print([], { expandFirstArg: true }),
print([], { expandFirstArg: true }),
printedArguments.length > 1 ? "," : "",
hasEmptyLineFollowingFirstArg ? hardline : line,
hasEmptyLineFollowingFirstArg ? hardline : "",
@@ -132,7 +126,7 @@ async function printCallArguments(path, options, print) {
if (shouldGroupLast && i === lastArgIndex) {
printedExpanded = [
...printedArguments.slice(0, -1),
await print([], { expandLastArg: true }),
print([], { expandLastArg: true }),
];
}
});
+8 -8
View File
@@ -14,7 +14,7 @@ import printMemberChain from "./member-chain.js";
import printCallArguments from "./call-arguments.js";
import { printOptionalToken, printFunctionTypeParameters } from "./misc.js";
async function printCallExpression(path, options, print) {
function printCallExpression(path, options, print) {
const node = path.getValue();
const parentNode = path.getParentNode();
const isNew = node.type === "NewExpression";
@@ -37,14 +37,14 @@ async function printCallExpression(path, options, print) {
(!isNew && isTestCall(node, parentNode)))
) {
const printed = [];
await iterateCallArgumentsPath(path, async () => {
printed.push(await print());
iterateCallArgumentsPath(path, () => {
printed.push(print());
});
return [
isNew ? "new " : "",
await print("callee"),
print("callee"),
optional,
await printFunctionTypeParameters(path, options, print),
printFunctionTypeParameters(path, options, print),
"(",
join(", ", printed),
")",
@@ -79,13 +79,13 @@ async function printCallExpression(path, options, print) {
const contents = [
isNew ? "new " : "",
isDynamicImport ? "import" : await print("callee"),
isDynamicImport ? "import" : print("callee"),
optional,
isIdentifierWithFlowAnnotation
? `/*:: ${node.callee.trailingComments[0].value.slice(2).trim()} */`
: "",
await printFunctionTypeParameters(path, options, print),
await printCallArguments(path, options, print),
printFunctionTypeParameters(path, options, print),
printCallArguments(path, options, print),
];
// We group here when the callee is itself a call expression.
+25 -28
View File
@@ -21,7 +21,7 @@ import { printPropertyKey } from "./property.js";
import { printAssignment } from "./assignment.js";
import { printClassMemberDecorators } from "./decorators.js";
async function printClass(path, options, print) {
function printClass(path, options, print) {
const node = path.getValue();
const parts = [];
@@ -50,17 +50,17 @@ async function printClass(path, options, print) {
const extendsParts = [];
if (node.id) {
partsGroup.push(" ", await print("id"));
partsGroup.push(" ", print("id"));
}
partsGroup.push(await print("typeParameters"));
partsGroup.push(print("typeParameters"));
if (node.superClass) {
const printed = [
await printSuperClass(path, options, print),
await print("superTypeParameters"),
printSuperClass(path, options, print),
print("superTypeParameters"),
];
const printedWithComments = await path.call(
const printedWithComments = path.call(
(superClass) => ["extends ", printComments(superClass, printed, options)],
"superClass"
);
@@ -70,12 +70,12 @@ async function printClass(path, options, print) {
extendsParts.push(" ", printedWithComments);
}
} else {
extendsParts.push(await printList(path, options, print, "extends"));
extendsParts.push(printList(path, options, print, "extends"));
}
extendsParts.push(
await printList(path, options, print, "mixins"),
await printList(path, options, print, "implements")
printList(path, options, print, "mixins"),
printList(path, options, print, "implements")
);
if (groupMode) {
@@ -90,7 +90,7 @@ async function printClass(path, options, print) {
parts.push(...partsGroup, ...extendsParts);
}
parts.push(" ", await print("body"));
parts.push(" ", print("body"));
return parts;
}
@@ -120,7 +120,7 @@ function shouldIndentOnlyHeritageClauses(node) {
);
}
async function printList(path, options, print, listName) {
function printList(path, options, print, listName) {
const node = path.getValue();
if (!isNonEmptyArray(node[listName])) {
return "";
@@ -141,12 +141,12 @@ async function printList(path, options, print, listName) {
printedLeadingComments,
printedLeadingComments && hardline,
listName,
group(indent([line, join([",", line], await path.map(print, listName))])),
group(indent([line, join([",", line], path.map(print, listName))])),
];
}
async function printSuperClass(path, options, print) {
const printed = await print("superClass");
function printSuperClass(path, options, print) {
const printed = print("superClass");
const parent = path.getParentNode();
if (parent.type === "AssignmentExpression") {
return group(
@@ -156,12 +156,12 @@ async function printSuperClass(path, options, print) {
return printed;
}
async function printClassMethod(path, options, print) {
function printClassMethod(path, options, print) {
const node = path.getValue();
const parts = [];
if (isNonEmptyArray(node.decorators)) {
parts.push(await printClassMemberDecorators(path, options, print));
parts.push(printClassMemberDecorators(path, options, print));
}
if (node.accessibility) {
parts.push(node.accessibility + " ");
@@ -185,18 +185,18 @@ async function printClassMethod(path, options, print) {
parts.push("override ");
}
parts.push(await printMethod(path, options, print));
parts.push(printMethod(path, options, print));
return parts;
}
async function printClassProperty(path, options, print) {
function printClassProperty(path, options, print) {
const node = path.getValue();
const parts = [];
const semi = options.semi ? ";" : "";
if (isNonEmptyArray(node.decorators)) {
parts.push(await printClassMemberDecorators(path, options, print));
parts.push(printClassMemberDecorators(path, options, print));
}
if (node.accessibility) {
parts.push(node.accessibility + " ");
@@ -217,22 +217,19 @@ async function printClassProperty(path, options, print) {
parts.push("readonly ");
}
if (node.variance) {
parts.push(await print("variance"));
parts.push(print("variance"));
}
if (node.type === "ClassAccessorProperty") {
parts.push("accessor ");
}
parts.push(
await printPropertyKey(path, options, print),
await printOptionalToken(path),
await printDefiniteToken(path),
await printTypeAnnotation(path, options, print)
printPropertyKey(path, options, print),
printOptionalToken(path),
printDefiniteToken(path),
printTypeAnnotation(path, options, print)
);
return [
await printAssignment(path, options, print, parts, " =", "value"),
semi,
];
return [printAssignment(path, options, print, parts, " =", "value"), semi];
}
export {
+6 -6
View File
@@ -9,24 +9,24 @@ import {
import { locStart, locEnd } from "../loc.js";
import { getParentExportDeclaration } from "../utils/index.js";
async function printClassMemberDecorators(path, options, print) {
function printClassMemberDecorators(path, options, print) {
const node = path.getValue();
return group([
join(line, await path.map(print, "decorators")),
join(line, path.map(print, "decorators")),
hasNewlineBetweenOrAfterDecorators(node, options) ? hardline : line,
]);
}
async function printDecoratorsBeforeExport(path, options, print) {
function printDecoratorsBeforeExport(path, options, print) {
// Export declarations are responsible for printing any decorators
// that logically apply to node.declaration.
return [
join(hardline, await path.map(print, "declaration", "decorators")),
join(hardline, path.map(print, "declaration", "decorators")),
hardline,
];
}
async function printDecorators(path, options, print) {
function printDecorators(path, options, print) {
const node = path.getValue();
const { decorators } = node;
@@ -51,7 +51,7 @@ async function printDecorators(path, options, print) {
: shouldBreak
? breakParent
: "",
join(line, await path.map(print, "decorators")),
join(line, path.map(print, "decorators")),
line,
];
}
+41 -50
View File
@@ -34,62 +34,53 @@ import {
printRestSpread,
} from "./misc.js";
async function printFlow(path, options, print) {
function printFlow(path, options, print) {
const node = path.getValue();
const semi = options.semi ? ";" : "";
/** @type{Doc[]} */
const parts = [];
switch (node.type) {
case "DeclareClass":
return printFlowDeclaration(path, await printClass(path, options, print));
return printFlowDeclaration(path, printClass(path, options, print));
case "DeclareFunction":
return printFlowDeclaration(path, [
"function ",
await print("id"),
print("id"),
node.predicate ? " " : "",
await print("predicate"),
print("predicate"),
semi,
]);
case "DeclareModule":
return printFlowDeclaration(path, [
"module ",
await print("id"),
print("id"),
" ",
await print("body"),
print("body"),
]);
case "DeclareModuleExports":
return printFlowDeclaration(path, [
"module.exports",
": ",
await print("typeAnnotation"),
print("typeAnnotation"),
semi,
]);
case "DeclareVariable":
return printFlowDeclaration(path, ["var ", await print("id"), semi]);
return printFlowDeclaration(path, ["var ", print("id"), semi]);
case "DeclareOpaqueType":
return printFlowDeclaration(
path,
await printOpaqueType(path, options, print)
);
return printFlowDeclaration(path, printOpaqueType(path, options, print));
case "DeclareInterface":
return printFlowDeclaration(
path,
await printInterface(path, options, print)
);
return printFlowDeclaration(path, printInterface(path, options, print));
case "DeclareTypeAlias":
return printFlowDeclaration(
path,
await printTypeAlias(path, options, print)
);
return printFlowDeclaration(path, printTypeAlias(path, options, print));
case "DeclareExportDeclaration":
return printFlowDeclaration(
path,
await printExportDeclaration(path, options, print)
printExportDeclaration(path, options, print)
);
case "DeclareExportAllDeclaration":
return printFlowDeclaration(
path,
await printExportAllDeclaration(path, options, print)
printExportAllDeclaration(path, options, print)
);
case "OpaqueType":
return printOpaqueType(path, options, print);
@@ -105,8 +96,8 @@ async function printFlow(path, options, print) {
return printTupleType(path, options, print);
case "GenericTypeAnnotation":
return [
await print("id"),
await printTypeParameters(path, options, print, "typeParameters"),
print("id"),
printTypeParameters(path, options, print, "typeParameters"),
];
case "IndexedAccessType":
case "OptionalIndexedAccessType":
@@ -118,7 +109,7 @@ async function printFlow(path, options, print) {
case "TypeParameter":
return printTypeParameter(path, options, print);
case "TypeofTypeAnnotation":
return ["typeof ", await print("argument")];
return ["typeof ", print("argument")];
case "ExistsTypeAnnotation":
return "*";
case "EmptyTypeAnnotation":
@@ -126,11 +117,11 @@ async function printFlow(path, options, print) {
case "MixedTypeAnnotation":
return "mixed";
case "ArrayTypeAnnotation":
return [await print("elementType"), "[]"];
return [print("elementType"), "[]"];
case "BooleanLiteralTypeAnnotation":
return String(node.value);
case "EnumDeclaration":
return ["enum ", await print("id"), " ", await print("body")];
return ["enum ", print("id"), " ", print("body")];
case "EnumBooleanBody":
case "EnumNumberBody":
case "EnumStringBody":
@@ -162,7 +153,7 @@ async function printFlow(path, options, print) {
node.members.length > 0
? [
hardline,
await printArrayItems(path, options, "members", print),
printArrayItems(path, options, "members", print),
node.hasUnknownMembers || shouldPrintComma(options) ? "," : "",
]
: [];
@@ -186,23 +177,23 @@ async function printFlow(path, options, print) {
case "EnumNumberMember":
case "EnumStringMember":
return [
await print("id"),
print("id"),
" = ",
typeof node.init === "object" ? await print("init") : String(node.init),
typeof node.init === "object" ? print("init") : String(node.init),
];
case "EnumDefaultedMember":
return print("id");
case "FunctionTypeParam": {
const name = node.name
? await print("name")
? print("name")
: path.getParentNode().this === node
? "this"
: "";
return [
name,
await printOptionalToken(path),
printOptionalToken(path),
name ? ": " : "",
await print("typeAnnotation"),
print("typeAnnotation"),
];
}
@@ -211,9 +202,9 @@ async function printFlow(path, options, print) {
return printInterface(path, options, print);
case "ClassImplements":
case "InterfaceExtends":
return [await print("id"), await print("typeParameters")];
return [print("id"), print("typeParameters")];
case "NullableTypeAnnotation":
return ["?", await print("typeAnnotation")];
return ["?", print("typeAnnotation")];
case "Variance": {
const { kind } = node;
assert.ok(kind === "plus" || kind === "minus");
@@ -224,19 +215,19 @@ async function printFlow(path, options, print) {
parts.push("static ");
}
parts.push(await print("value"));
parts.push(print("value"));
return parts;
case "ObjectTypeIndexer": {
return [
node.static ? "static " : "",
node.variance ? await print("variance") : "",
node.variance ? print("variance") : "",
"[",
await print("id"),
print("id"),
node.id ? ": " : "",
await print("key"),
print("key"),
"]: ",
await print("value"),
print("value"),
];
}
case "ObjectTypeProperty": {
@@ -251,11 +242,11 @@ async function printFlow(path, options, print) {
return [
modifier,
isGetterOrSetter(node) ? node.kind + " " : "",
node.variance ? await print("variance") : "",
await printPropertyKey(path, options, print),
node.variance ? print("variance") : "",
printPropertyKey(path, options, print),
printOptionalToken(path),
isFunctionNotation(node) ? "" : ": ",
await print("value"),
print("value"),
];
}
case "ObjectTypeAnnotation":
@@ -264,18 +255,18 @@ async function printFlow(path, options, print) {
return [
node.static ? "static " : "",
"[[",
await print("id"),
print("id"),
"]]",
printOptionalToken(path),
node.method ? "" : ": ",
await print("value"),
print("value"),
];
// Same as `RestElement`
case "ObjectTypeSpreadProperty":
return printRestSpread(path, options, print);
case "QualifiedTypeofIdentifier":
case "QualifiedTypeIdentifier":
return [await print("qualification"), ".", await print("id")];
return [print("qualification"), ".", print("id")];
case "StringLiteralTypeAnnotation":
return printString(rawText(node), options);
case "NumberLiteralTypeAnnotation":
@@ -289,15 +280,15 @@ async function printFlow(path, options, print) {
case "TypeCastExpression": {
return [
"(",
await print("expression"),
await printTypeAnnotation(path, options, print),
print("expression"),
printTypeAnnotation(path, options, print),
")",
];
}
case "TypeParameterDeclaration":
case "TypeParameterInstantiation": {
const printed = await printTypeParameters(path, options, print, "params");
const printed = printTypeParameters(path, options, print, "params");
if (options.parser === "flow") {
const start = locStart(node);
@@ -327,7 +318,7 @@ async function printFlow(path, options, print) {
// be either left alone or desugared into AST types that are fully
// supported by the pretty-printer.
case "DeclaredPredicate":
return ["%checks(", await print("value"), ")"];
return ["%checks(", print("value"), ")"];
case "AnyTypeAnnotation":
return "any";
case "BooleanTypeAnnotation":
+4 -4
View File
@@ -26,7 +26,7 @@ import { locEnd } from "../loc.js";
import { ArgExpansionBailout } from "../../common/errors.js";
import { printFunctionTypeParameters } from "./misc.js";
async function printFunctionParameters(
function printFunctionParameters(
path,
print,
options,
@@ -36,7 +36,7 @@ async function printFunctionParameters(
const functionNode = path.getValue();
const parameters = getFunctionParameters(functionNode);
const typeParams = printTypeParams
? await printFunctionTypeParameters(path, options, print)
? printFunctionTypeParameters(path, options, print)
: "";
if (parameters.length === 0) {
@@ -62,12 +62,12 @@ async function printFunctionParameters(
const isParametersInTestCall = isTestCall(parent);
const shouldHugParameters = shouldHugFunctionParameters(functionNode);
const printed = [];
await iterateFunctionParametersPath(path, async (parameterPath, index) => {
iterateFunctionParametersPath(path, (parameterPath, index) => {
const isLastParameter = index === parameters.length - 1;
if (isLastParameter && functionNode.rest) {
printed.push("...");
}
printed.push(await print());
printed.push(print());
if (isLastParameter) {
return;
}
+37 -45
View File
@@ -46,7 +46,7 @@ import {
import { printPropertyKey } from "./property.js";
import { printFunctionTypeParameters } from "./misc.js";
async function printFunction(path, print, options, args) {
function printFunction(path, print, options, args) {
const node = path.getValue();
let expandArg = false;
@@ -81,29 +81,29 @@ async function printFunction(path, print, options, args) {
}
if (node.id) {
parts.push(await print("id"));
parts.push(print("id"));
}
const parametersDoc = await printFunctionParameters(
const parametersDoc = printFunctionParameters(
path,
print,
options,
expandArg
);
const returnTypeDoc = await printReturnType(path, print, options);
const returnTypeDoc = printReturnType(path, print, options);
const shouldGroupParameters = shouldGroupFunctionParameters(
node,
returnTypeDoc
);
parts.push(
await printFunctionTypeParameters(path, options, print),
printFunctionTypeParameters(path, options, print),
group([
shouldGroupParameters ? group(parametersDoc) : parametersDoc,
returnTypeDoc,
]),
node.body ? " " : "",
await print("body")
print("body")
);
if (options.semi && (node.declare || !node.body)) {
@@ -113,7 +113,7 @@ async function printFunction(path, print, options, args) {
return parts;
}
async function printMethod(path, options, print) {
function printMethod(path, options, print) {
const node = path.getNode();
const { kind } = node;
const value = node.value || node;
@@ -135,36 +135,33 @@ async function printMethod(path, options, print) {
}
parts.push(
await printPropertyKey(path, options, print),
printPropertyKey(path, options, print),
node.optional || node.key.optional ? "?" : ""
);
if (node === value) {
parts.push(await printMethodInternal(path, options, print));
parts.push(printMethodInternal(path, options, print));
} else if (value.type === "FunctionExpression") {
parts.push(
await path.call(
(path) => printMethodInternal(path, options, print),
"value"
)
path.call((path) => printMethodInternal(path, options, print), "value")
);
} else {
parts.push(await print("value"));
parts.push(print("value"));
}
return parts;
}
async function printMethodInternal(path, options, print) {
function printMethodInternal(path, options, print) {
const node = path.getNode();
const parametersDoc = await printFunctionParameters(path, print, options);
const returnTypeDoc = await printReturnType(path, print, options);
const parametersDoc = printFunctionParameters(path, print, options);
const returnTypeDoc = printReturnType(path, print, options);
const shouldGroupParameters = shouldGroupFunctionParameters(
node,
returnTypeDoc
);
const parts = [
await printFunctionTypeParameters(path, options, print),
printFunctionTypeParameters(path, options, print),
group([
shouldGroupParameters ? group(parametersDoc) : parametersDoc,
returnTypeDoc,
@@ -172,7 +169,7 @@ async function printMethodInternal(path, options, print) {
];
if (node.body) {
parts.push(" ", await print("body"));
parts.push(" ", print("body"));
} else {
parts.push(options.semi ? ";" : "");
}
@@ -180,7 +177,7 @@ async function printMethodInternal(path, options, print) {
return parts;
}
async function printArrowFunctionSignature(path, options, print, args) {
function printArrowFunctionSignature(path, options, print, args) {
const node = path.getValue();
const parts = [];
@@ -189,10 +186,10 @@ async function printArrowFunctionSignature(path, options, print, args) {
}
if (shouldPrintParamsWithoutParens(path, options)) {
parts.push(await print(["params", 0]));
parts.push(print(["params", 0]));
} else {
const expandArg = args && (args.expandLastArg || args.expandFirstArg);
let returnTypeDoc = await printReturnType(path, print, options);
let returnTypeDoc = printReturnType(path, print, options);
if (expandArg) {
if (willBreak(returnTypeDoc)) {
throw new ArgExpansionBailout();
@@ -201,7 +198,7 @@ async function printArrowFunctionSignature(path, options, print, args) {
}
parts.push(
group([
await printFunctionParameters(
printFunctionParameters(
path,
print,
options,
@@ -280,15 +277,15 @@ function printArrowChain(
]);
}
async function printArrowFunction(path, options, print, args) {
function printArrowFunction(path, options, print, args) {
let node = path.getValue();
/** @type {Doc[]} */
const signatures = [];
const body = [];
let chainShouldBreak = false;
await (async function rec() {
const doc = await printArrowFunctionSignature(path, options, print, args);
(function rec() {
const doc = printArrowFunctionSignature(path, options, print, args);
if (signatures.length === 0) {
signatures.push(doc);
} else {
@@ -308,10 +305,10 @@ async function printArrowFunction(path, options, print, args) {
node.body.type !== "ArrowFunctionExpression" ||
(args && args.expandLastArg)
) {
body.unshift(await print("body", args));
body.unshift(print("body", args));
} else {
node = node.body;
await path.call(rec, "body");
path.call(rec, "body");
}
})();
@@ -418,10 +415,10 @@ function shouldPrintParamsWithoutParens(path, options) {
return false;
}
/** @returns {Promise<Doc>} */
async function printReturnType(path, print, options) {
/** @returns {Doc} */
function printReturnType(path, print, options) {
const node = path.getValue();
const returnType = await print("returnType");
const returnType = print("returnType");
if (
node.returnType &&
@@ -440,26 +437,21 @@ async function printReturnType(path, print, options) {
if (node.predicate) {
// The return type will already add the colon, but otherwise we
// need to do it ourselves
parts.push(node.returnType ? " " : ": ", await print("predicate"));
parts.push(node.returnType ? " " : ": ", print("predicate"));
}
return parts;
}
// `ReturnStatement` and `ThrowStatement`
async function printReturnOrThrowArgument(path, options, print) {
function printReturnOrThrowArgument(path, options, print) {
const node = path.getValue();
const semi = options.semi ? ";" : "";
const parts = [];
if (node.argument) {
if (returnArgumentHasLeadingComment(options, node.argument)) {
parts.push([
" (",
indent([hardline, await print("argument")]),
hardline,
")",
]);
parts.push([" (", indent([hardline, print("argument")]), hardline, ")"]);
} else if (
isBinaryish(node.argument) ||
node.argument.type === "SequenceExpression"
@@ -467,13 +459,13 @@ async function printReturnOrThrowArgument(path, options, print) {
parts.push(
group([
ifBreak(" (", " "),
indent([softline, await print("argument")]),
indent([softline, print("argument")]),
softline,
ifBreak(")"),
])
);
} else {
parts.push(" ", await print("argument"));
parts.push(" ", print("argument"));
}
}
@@ -499,12 +491,12 @@ async function printReturnOrThrowArgument(path, options, print) {
return parts;
}
async function printReturnStatement(path, options, print) {
return ["return", await printReturnOrThrowArgument(path, options, print)];
function printReturnStatement(path, options, print) {
return ["return", printReturnOrThrowArgument(path, options, print)];
}
async function printThrowStatement(path, options, print) {
return ["throw", await printReturnOrThrowArgument(path, options, print)];
function printThrowStatement(path, options, print) {
return ["throw", printReturnOrThrowArgument(path, options, print)];
}
// This recurses the return argument, looking for the first token
+4 -4
View File
@@ -19,10 +19,10 @@ function printHtmlBinding(path, options, print) {
if (options.__isVueForBindingLeft) {
return path.call(
async (functionDeclarationPath) => {
(functionDeclarationPath) => {
const printed = join(
[",", line],
await functionDeclarationPath.map(print, "params")
functionDeclarationPath.map(print, "params")
);
const { params } = functionDeclarationPath.getValue();
@@ -40,8 +40,8 @@ function printHtmlBinding(path, options, print) {
if (options.__isVueBindings) {
return path.call(
async (functionDeclarationPath) =>
join([",", line], await functionDeclarationPath.map(print, "params")),
(functionDeclarationPath) =>
join([",", line], functionDeclarationPath.map(print, "params")),
"program",
"body",
0
+5 -5
View File
@@ -4,7 +4,7 @@ import { hasComment, identity, CommentCheckFlags } from "../utils/index.js";
import { getTypeParametersGroupId } from "./type-parameters.js";
import { printTypeScriptModifiers } from "./misc.js";
async function printInterface(path, options, print) {
function printInterface(path, options, print) {
const node = path.getValue();
const parts = [];
if (node.declare) {
@@ -14,7 +14,7 @@ async function printInterface(path, options, print) {
if (node.type === "TSInterfaceDeclaration") {
parts.push(
node.abstract ? "abstract " : "",
await printTypeScriptModifiers(path, options, print)
printTypeScriptModifiers(path, options, print)
);
}
@@ -24,7 +24,7 @@ async function printInterface(path, options, print) {
const extendsParts = [];
if (node.type !== "InterfaceTypeAnnotation") {
partsGroup.push(" ", await print("id"), await print("typeParameters"));
partsGroup.push(" ", print("id"), print("typeParameters"));
}
const shouldIndentOnlyHeritageClauses =
@@ -43,7 +43,7 @@ async function printInterface(path, options, print) {
: line,
"extends ",
(node.extends.length === 1 ? identity : indent)(
join([",", line], await path.map(print, "extends"))
join([",", line], path.map(print, "extends"))
)
);
}
@@ -61,7 +61,7 @@ async function printInterface(path, options, print) {
parts.push(...partsGroup, ...extendsParts);
}
parts.push(" ", await print("body"));
parts.push(" ", print("body"));
return group(parts);
}
+37 -39
View File
@@ -52,21 +52,21 @@ const isEmptyStringOrAnyLine = (doc) =>
//
// To support that case properly, all leading and trailing spaces
// are stripped from the list of children, and replaced with a single hardline.
async function printJsxElementInternal(path, options, print) {
function printJsxElementInternal(path, options, print) {
const node = path.getValue();
if (node.type === "JSXElement" && isEmptyJsxElement(node)) {
return [await print("openingElement"), await print("closingElement")];
return [print("openingElement"), print("closingElement")];
}
const openingLines =
node.type === "JSXElement"
? await print("openingElement")
: await print("openingFragment");
? print("openingElement")
: print("openingFragment");
const closingLines =
node.type === "JSXElement"
? await print("closingElement")
: await print("closingFragment");
? print("closingElement")
: print("closingFragment");
if (
node.children.length === 1 &&
@@ -74,7 +74,7 @@ async function printJsxElementInternal(path, options, print) {
(node.children[0].expression.type === "TemplateLiteral" ||
node.children[0].expression.type === "TaggedTemplateExpression")
) {
return [openingLines, ...(await path.map(print, "children")), closingLines];
return [openingLines, ...path.map(print, "children"), closingLines];
}
// Convert `{" "}` to text nodes containing a space.
@@ -117,7 +117,7 @@ async function printJsxElementInternal(path, options, print) {
node.openingElement.name &&
node.openingElement.name.name === "fbt";
const children = await printJsxChildren(
const children = printJsxChildren(
path,
options,
print,
@@ -261,7 +261,7 @@ async function printJsxElementInternal(path, options, print) {
// This requires that we give it an array of alternating
// content and whitespace elements.
// To ensure this we add dummy `""` content elements as needed.
async function printJsxChildren(
function printJsxChildren(
path,
options,
print,
@@ -269,7 +269,7 @@ async function printJsxChildren(
isFacebookTranslationTag
) {
const parts = [];
await path.each(async (childPath, i, children) => {
path.each((childPath, i, children) => {
const child = childPath.getValue();
if (isLiteral(child)) {
const text = rawText(child);
@@ -353,7 +353,7 @@ async function printJsxChildren(
parts.push("", jsxWhitespace);
}
} else {
const printedChild = await print();
const printedChild = print();
parts.push(printedChild);
const next = children[i + 1];
@@ -463,10 +463,10 @@ function maybeWrapJsxElementInParens(path, elem, options) {
);
}
async function printJsxAttribute(path, options, print) {
function printJsxAttribute(path, options, print) {
const node = path.getValue();
const parts = [];
parts.push(await print("name"));
parts.push(print("name"));
if (node.value) {
let res;
@@ -485,7 +485,7 @@ async function printJsxAttribute(path, options, print) {
final = final.replace(regex, escaped);
res = [quote, final, quote];
} else {
res = await print("value");
res = print("value");
}
parts.push("=", res);
}
@@ -493,7 +493,7 @@ async function printJsxAttribute(path, options, print) {
return parts;
}
async function printJsxExpressionContainer(path, options, print) {
function printJsxExpressionContainer(path, options, print) {
const node = path.getValue();
const shouldInline = (node, parent) =>
@@ -514,19 +514,19 @@ async function printJsxExpressionContainer(path, options, print) {
(node.type === "ConditionalExpression" || isBinaryish(node)))));
if (shouldInline(node.expression, path.getParentNode(0))) {
return group(["{", await print("expression"), lineSuffixBoundary, "}"]);
return group(["{", print("expression"), lineSuffixBoundary, "}"]);
}
return group([
"{",
indent([softline, await print("expression")]),
indent([softline, print("expression")]),
softline,
lineSuffixBoundary,
"}",
]);
}
async function printJsxOpeningElement(path, options, print) {
function printJsxOpeningElement(path, options, print) {
const node = path.getValue();
const nameHasComments =
@@ -535,7 +535,7 @@ async function printJsxOpeningElement(path, options, print) {
// Don't break self-closing elements with no attributes and no comments
if (node.selfClosing && node.attributes.length === 0 && !nameHasComments) {
return ["<", await print("name"), await print("typeParameters"), " />"];
return ["<", print("name"), print("typeParameters"), " />"];
}
// don't break up opening elements with a single long text attribute
@@ -559,10 +559,10 @@ async function printJsxOpeningElement(path, options, print) {
) {
return group([
"<",
await print("name"),
await print("typeParameters"),
print("name"),
print("typeParameters"),
" ",
...(await path.map(print, "attributes")),
...path.map(print, "attributes"),
node.selfClosing ? " />" : ">",
]);
}
@@ -586,12 +586,10 @@ async function printJsxOpeningElement(path, options, print) {
return group(
[
"<",
await print("name"),
await print("typeParameters"),
indent(
await path.map(async () => [attributeLine, await print()], "attributes")
),
...(await printEndOfOpeningTag(node, options, nameHasComments)),
print("name"),
print("typeParameters"),
indent(path.map(() => [attributeLine, print()], "attributes")),
...printEndOfOpeningTag(node, options, nameHasComments),
],
{ shouldBreak }
);
@@ -635,13 +633,13 @@ function shouldPrintBracketSameLine(node, options, nameHasComments) {
);
}
async function printJsxClosingElement(path, options, print) {
function printJsxClosingElement(path, options, print) {
const node = path.getValue();
const parts = [];
parts.push("</");
const printed = await print("name");
const printed = print("name");
if (
hasComment(node.name, CommentCheckFlags.Leading | CommentCheckFlags.Line)
) {
@@ -679,10 +677,10 @@ function printJsxOpeningClosingFragment(path, options /*, print*/) {
];
}
async function printJsxElement(path, options, print) {
function printJsxElement(path, options, print) {
const elem = printComments(
path,
await printJsxElementInternal(path, options, print),
printJsxElementInternal(path, options, print),
options
);
return maybeWrapJsxElementInParens(path, elem, options);
@@ -699,13 +697,13 @@ function printJsxEmptyExpression(path, options /*, print*/) {
}
// `JSXSpreadAttribute` and `JSXSpreadChild`
async function printJsxSpreadAttribute(path, options, print) {
function printJsxSpreadAttribute(path, options, print) {
const node = path.getValue();
return [
"{",
await path.call(
async (p) => {
const printed = ["...", await print()];
path.call(
(p) => {
const printed = ["...", print()];
const node = p.getValue();
if (!hasComment(node) || !willPrintOwnComments(p)) {
return printed;
@@ -721,7 +719,7 @@ async function printJsxSpreadAttribute(path, options, print) {
];
}
async function printJsx(path, options, print) {
function printJsx(path, options, print) {
const node = path.getValue();
// JSX nodes always starts with `JSX`
@@ -735,9 +733,9 @@ async function printJsx(path, options, print) {
case "JSXIdentifier":
return String(node.name);
case "JSXNamespacedName":
return join(":", [await print("namespace"), await print("name")]);
return join(":", [print("namespace"), print("name")]);
case "JSXMemberExpression":
return join(".", [await print("object"), await print("property")]);
return join(".", [print("object"), print("property")]);
case "JSXSpreadAttribute":
return printJsxSpreadAttribute(path, options, print);
case "JSXSpreadChild": {
+15 -15
View File
@@ -48,7 +48,7 @@ import {
// The way it is structured in the AST is via a nested sequence of
// MemberExpression and CallExpression. We need to traverse the AST
// and make groups out of it to print it in the desired way.
async function printMemberChain(path, options, print) {
function printMemberChain(path, options, print) {
const parent = path.getParentNode();
const isExpressionStatement =
!parent || parent.type === "ExpressionStatement";
@@ -85,7 +85,7 @@ async function printMemberChain(path, options, print) {
return isNextLineEmpty(node, options);
}
async function rec(path) {
function rec(path) {
const node = path.getValue();
if (
isCallExpression(node) &&
@@ -97,16 +97,16 @@ async function printMemberChain(path, options, print) {
printComments(
path,
[
await printOptionalToken(path),
await printFunctionTypeParameters(path, options, print),
await printCallArguments(path, options, print),
printOptionalToken(path),
printFunctionTypeParameters(path, options, print),
printCallArguments(path, options, print),
],
options
),
shouldInsertEmptyLineAfter(node) ? hardline : "",
],
});
await path.call((callee) => rec(callee), "callee");
path.call((callee) => rec(callee), "callee");
} else if (isMemberish(node)) {
printedNodes.unshift({
node,
@@ -114,22 +114,22 @@ async function printMemberChain(path, options, print) {
printed: printComments(
path,
isMemberExpression(node)
? await printMemberLookup(path, options, print)
: await printBindExpressionCallee(path, options, print),
? printMemberLookup(path, options, print)
: printBindExpressionCallee(path, options, print),
options
),
});
await path.call((object) => rec(object), "object");
path.call((object) => rec(object), "object");
} else if (node.type === "TSNonNullExpression") {
printedNodes.unshift({
node,
printed: printComments(path, "!", options),
});
await path.call((expression) => rec(expression), "expression");
path.call((expression) => rec(expression), "expression");
} else {
printedNodes.unshift({
node,
printed: await print(),
printed: print(),
});
}
}
@@ -140,14 +140,14 @@ async function printMemberChain(path, options, print) {
printedNodes.unshift({
node,
printed: [
await printOptionalToken(path),
await printFunctionTypeParameters(path, options, print),
await printCallArguments(path, options, print),
printOptionalToken(path),
printFunctionTypeParameters(path, options, print),
printCallArguments(path, options, print),
],
});
if (node.callee) {
await path.call((callee) => rec(callee), "callee");
path.call((callee) => rec(callee), "callee");
}
// Once we have a linear list of printed nodes, we want to create groups out
+5 -5
View File
@@ -6,7 +6,7 @@ import {
} from "../utils/index.js";
import { printOptionalToken } from "./misc.js";
async function printMemberExpression(path, options, print) {
function printMemberExpression(path, options, print) {
const node = path.getValue();
const parent = path.getParentNode();
@@ -21,8 +21,8 @@ async function printMemberExpression(path, options, print) {
firstNonMemberParent.type === "TSNonNullExpression")
);
const objectDoc = await print("object");
const lookupDoc = await printMemberLookup(path, options, print);
const objectDoc = print("object");
const lookupDoc = printMemberLookup(path, options, print);
const shouldInline =
(firstNonMemberParent &&
@@ -48,8 +48,8 @@ async function printMemberExpression(path, options, print) {
]);
}
async function printMemberLookup(path, options, print) {
const property = await print("property");
function printMemberLookup(path, options, print) {
const property = print("property");
const node = path.getValue();
const optional = printOptionalToken(path);
+9 -16
View File
@@ -43,7 +43,7 @@ function printFunctionTypeParameters(path, options, print) {
return "";
}
async function printTypeAnnotation(path, options, print) {
function printTypeAnnotation(path, options, print) {
const node = path.getValue();
if (!node.typeAnnotation) {
return "";
@@ -55,25 +55,22 @@ async function printTypeAnnotation(path, options, print) {
parentNode.type === "DeclareFunction" && parentNode.id === node;
if (isFlowAnnotationComment(options.originalText, node.typeAnnotation)) {
return [" /*: ", await print("typeAnnotation"), " */"];
return [" /*: ", print("typeAnnotation"), " */"];
}
return [
isFunctionDeclarationIdentifier ? "" : ": ",
await print("typeAnnotation"),
];
return [isFunctionDeclarationIdentifier ? "" : ": ", print("typeAnnotation")];
}
async function printBindExpressionCallee(path, options, print) {
return ["::", await print("callee")];
function printBindExpressionCallee(path, options, print) {
return ["::", print("callee")];
}
async function printTypeScriptModifiers(path, options, print) {
function printTypeScriptModifiers(path, options, print) {
const node = path.getValue();
if (!isNonEmptyArray(node.modifiers)) {
return "";
}
return [join(" ", await path.map(print, "modifiers")), " "];
return [join(" ", path.map(print, "modifiers")), " "];
}
function adjustClause(node, clause, forceSpace) {
@@ -88,12 +85,8 @@ function adjustClause(node, clause, forceSpace) {
return indent([line, clause]);
}
async function printRestSpread(path, options, print) {
return [
"...",
await print("argument"),
await printTypeAnnotation(path, options, print),
];
function printRestSpread(path, options, print) {
return ["...", print("argument"), printTypeAnnotation(path, options, print)];
}
export {
+25 -25
View File
@@ -28,7 +28,7 @@ import {
* @typedef {import("../../document/builders.js").Doc} Doc
*/
async function printImportDeclaration(path, options, print) {
function printImportDeclaration(path, options, print) {
const node = path.getValue();
const semi = options.semi ? ";" : "";
/** @type{Doc[]} */
@@ -43,16 +43,16 @@ async function printImportDeclaration(path, options, print) {
}
parts.push(
await printModuleSpecifiers(path, options, print),
await printModuleSource(path, options, print),
await printImportAssertions(path, options, print),
printModuleSpecifiers(path, options, print),
printModuleSource(path, options, print),
printImportAssertions(path, options, print),
semi
);
return parts;
}
async function printExportDeclaration(path, options, print) {
function printExportDeclaration(path, options, print) {
const node = path.getValue();
/** @type{Doc[]} */
const parts = [];
@@ -60,7 +60,7 @@ async function printExportDeclaration(path, options, print) {
// Only print decorators here if they were written before the export,
// otherwise they are printed by the node.declaration
if (hasDecoratorsBeforeExport(node)) {
parts.push(await printDecoratorsBeforeExport(path, options, print));
parts.push(printDecoratorsBeforeExport(path, options, print));
}
const { type, exportKind, declaration } = node;
@@ -84,13 +84,13 @@ async function printExportDeclaration(path, options, print) {
}
if (declaration) {
parts.push(" ", await print("declaration"));
parts.push(" ", print("declaration"));
} else {
parts.push(
exportKind === "type" ? " type" : "",
await printModuleSpecifiers(path, options, print),
await printModuleSource(path, options, print),
await printImportAssertions(path, options, print)
printModuleSpecifiers(path, options, print),
printModuleSource(path, options, print),
printImportAssertions(path, options, print)
);
}
@@ -101,7 +101,7 @@ async function printExportDeclaration(path, options, print) {
return parts;
}
async function printExportAllDeclaration(path, options, print) {
function printExportAllDeclaration(path, options, print) {
const node = path.getValue();
const semi = options.semi ? ";" : "";
/** @type{Doc[]} */
@@ -118,12 +118,12 @@ async function printExportAllDeclaration(path, options, print) {
parts.push(" *");
if (exported) {
parts.push(" as ", await print("exported"));
parts.push(" as ", print("exported"));
}
parts.push(
await printModuleSource(path, options, print),
await printImportAssertions(path, options, print),
printModuleSource(path, options, print),
printImportAssertions(path, options, print),
semi
);
@@ -157,7 +157,7 @@ function shouldExportDeclarationPrintSemi(node, options) {
return false;
}
async function printModuleSource(path, options, print) {
function printModuleSource(path, options, print) {
const node = path.getValue();
if (!node.source) {
@@ -169,12 +169,12 @@ async function printModuleSource(path, options, print) {
if (!shouldNotPrintSpecifiers(node, options)) {
parts.push(" from");
}
parts.push(" ", await print("source"));
parts.push(" ", print("source"));
return parts;
}
async function printModuleSpecifiers(path, options, print) {
function printModuleSpecifiers(path, options, print) {
const node = path.getValue();
if (shouldNotPrintSpecifiers(node, options)) {
@@ -188,7 +188,7 @@ async function printModuleSpecifiers(path, options, print) {
const standaloneSpecifiers = [];
const groupedSpecifiers = [];
await path.each(async () => {
path.each(() => {
const specifierType = path.getValue().type;
if (
specifierType === "ExportNamespaceSpecifier" ||
@@ -196,12 +196,12 @@ async function printModuleSpecifiers(path, options, print) {
specifierType === "ImportNamespaceSpecifier" ||
specifierType === "ImportDefaultSpecifier"
) {
standaloneSpecifiers.push(await print());
standaloneSpecifiers.push(print());
} else if (
specifierType === "ExportSpecifier" ||
specifierType === "ImportSpecifier"
) {
groupedSpecifiers.push(await print());
groupedSpecifiers.push(print());
} else {
/* istanbul ignore next */
throw new Error(
@@ -268,13 +268,13 @@ function shouldNotPrintSpecifiers(node, options) {
);
}
async function printImportAssertions(path, options, print) {
function printImportAssertions(path, options, print) {
const node = path.getNode();
if (isNonEmptyArray(node.assertions)) {
return [
" assert {",
options.bracketSpacing ? " " : "",
join(", ", await path.map(print, "assertions")),
join(", ", path.map(print, "assertions")),
options.bracketSpacing ? " " : "",
"}",
];
@@ -282,7 +282,7 @@ async function printImportAssertions(path, options, print) {
return "";
}
async function printModuleSpecifier(path, options, print) {
function printModuleSpecifier(path, options, print) {
const node = path.getNode();
const { type } = node;
@@ -310,11 +310,11 @@ async function printModuleSpecifier(path, options, print) {
) {
left = "*";
} else if (leftSideNode) {
left = await print(leftSideProperty);
left = print(leftSideProperty);
}
if (rightSideNode && !isShorthandSpecifier(node)) {
right = await print(rightSideProperty);
right = print(rightSideProperty);
}
parts.push(left, left && right ? " as " : "", right);
+6 -10
View File
@@ -29,7 +29,7 @@ import { printHardlineAfterHeritage } from "./class.js";
/** @typedef {import("../../document/builders.js").Doc} Doc */
async function printObject(path, options, print) {
function printObject(path, options, print) {
const semi = options.semi ? ";" : "";
const node = path.getValue();
@@ -101,11 +101,11 @@ async function printObject(path, options, print) {
// printing them.
const propsAndLoc = [];
for (const field of fields) {
await path.each(async (childPath) => {
path.each((childPath) => {
const node = childPath.getValue();
propsAndLoc.push({
node,
printed: await print(),
printed: print(),
loc: locStart(node),
});
}, field);
@@ -173,11 +173,7 @@ async function printObject(path, options, print) {
let content;
if (props.length === 0) {
if (!hasComment(node, CommentCheckFlags.Dangling)) {
return [
leftBrace,
rightBrace,
await printTypeAnnotation(path, options, print),
];
return [leftBrace, rightBrace, printTypeAnnotation(path, options, print)];
}
content = group([
@@ -186,7 +182,7 @@ async function printObject(path, options, print) {
softline,
rightBrace,
printOptionalToken(path),
await printTypeAnnotation(path, options, print),
printTypeAnnotation(path, options, print),
]);
} else {
content = [
@@ -204,7 +200,7 @@ async function printObject(path, options, print) {
options.bracketSpacing ? line : softline,
rightBrace,
printOptionalToken(path),
await printTypeAnnotation(path, options, print),
printTypeAnnotation(path, options, print),
];
}
+5 -5
View File
@@ -11,11 +11,11 @@ import { printAssignment } from "./assignment.js";
const needsQuoteProps = new WeakMap();
async function printPropertyKey(path, options, print) {
function printPropertyKey(path, options, print) {
const node = path.getNode();
if (node.computed) {
return ["[", await print("key"), "]"];
return ["[", print("key"), "]"];
}
const parent = path.getParentNode();
@@ -23,7 +23,7 @@ async function printPropertyKey(path, options, print) {
// flow has `Identifier` key, other parsers use `PrivateIdentifier` (ESTree) or `PrivateName`
if (node.type === "ClassPrivateProperty" && key.type === "Identifier") {
return ["#", await print("key")];
return ["#", print("key")];
}
if (options.quoteProps === "consistent" && !needsQuoteProps.has(parent)) {
@@ -87,7 +87,7 @@ async function printPropertyKey(path, options, print) {
return print("key");
}
async function printProperty(path, options, print) {
function printProperty(path, options, print) {
const node = path.getValue();
if (node.shorthand) {
return print("value");
@@ -97,7 +97,7 @@ async function printProperty(path, options, print) {
path,
options,
print,
await printPropertyKey(path, options, print),
printPropertyKey(path, options, print),
":",
"value"
);
+4 -4
View File
@@ -16,13 +16,13 @@ import { shouldPrintParamsWithoutParens } from "./function.js";
* @typedef {import("../../common/ast-path.js")} AstPath
*/
async function printStatementSequence(path, options, print, property) {
function printStatementSequence(path, options, print, property) {
const node = path.getValue();
const parts = [];
const isClassBody = node.type === "ClassBody";
const lastStatement = getLastStatement(node[property]);
await path.each(async (path, index, statements) => {
path.each((path, index, statements) => {
const node = path.getValue();
// Skip printing EmptyStatement nodes to avoid leaving stray
@@ -31,7 +31,7 @@ async function printStatementSequence(path, options, print, property) {
return;
}
const printed = await print();
const printed = print();
// in no-semi mode, prepend statement with semicolon if it might break ASI
// don't prepend the only JSX element in a program with semicolon
@@ -42,7 +42,7 @@ async function printStatementSequence(path, options, print, property) {
statementNeedsASIProtection(path, options)
) {
if (hasComment(node, CommentCheckFlags.Leading)) {
parts.push(await print([], { needsSemi: true }));
parts.push(print([], { needsSemi: true }));
} else {
parts.push(";", printed);
}
+9 -9
View File
@@ -20,7 +20,7 @@ import {
isMemberExpression,
} from "../utils/index.js";
async function printTemplateLiteral(path, print, options) {
function printTemplateLiteral(path, print, options) {
const node = path.getValue();
const isTemplateLiteral = node.type === "TemplateLiteral";
@@ -28,7 +28,7 @@ async function printTemplateLiteral(path, print, options) {
isTemplateLiteral &&
isJestEachTemplateLiteral(node, path.getParentNode())
) {
const printed = await printJestEachTemplateLiteral(path, options, print);
const printed = printJestEachTemplateLiteral(path, options, print);
if (printed) {
return printed;
}
@@ -39,7 +39,7 @@ async function printTemplateLiteral(path, print, options) {
}
const parts = [];
let expressions = await path.map(print, expressionsKey);
let expressions = path.map(print, expressionsKey);
const isSimple = isSimpleTemplateLiteral(node);
if (isSimple) {
@@ -54,10 +54,10 @@ async function printTemplateLiteral(path, print, options) {
parts.push(lineSuffixBoundary, "`");
await path.each(async (childPath) => {
path.each((childPath) => {
const i = childPath.getName();
parts.push(await print());
parts.push(print());
if (i < expressions.length) {
// For a template literal of the following form:
@@ -107,7 +107,7 @@ async function printTemplateLiteral(path, print, options) {
return parts;
}
async function printJestEachTemplateLiteral(path, options, print) {
function printJestEachTemplateLiteral(path, options, print) {
/**
* a | b | expected
* ${1} | ${1} | ${2}
@@ -121,7 +121,7 @@ async function printJestEachTemplateLiteral(path, options, print) {
headerNames.some((headerName) => headerName.length > 0)
) {
options.__inJestEach = true;
const expressions = await path.map(print, "expressions");
const expressions = path.map(print, "expressions");
options.__inJestEach = false;
const parts = [];
const stringifiedExpressions = expressions.map(
@@ -196,9 +196,9 @@ async function printJestEachTemplateLiteral(path, options, print) {
}
}
async function printTemplateExpression(path, print) {
function printTemplateExpression(path, print) {
const node = path.getValue();
let printed = await print();
let printed = print();
if (hasComment(node)) {
printed = group([indent([softline, printed]), softline]);
}
+13 -19
View File
@@ -101,7 +101,7 @@ function conditionalExpressionChainContainsJsx(node) {
return false;
}
async function printTernaryTest(path, options, print) {
function printTernaryTest(path, options, print) {
const node = path.getValue();
const isConditionalExpression = node.type === "ConditionalExpression";
const alternateNodePropertyName = isConditionalExpression
@@ -111,14 +111,8 @@ async function printTernaryTest(path, options, print) {
const parent = path.getParentNode();
const printed = isConditionalExpression
? await print("test")
: [
await print("checkType"),
" ",
"extends",
" ",
await print("extendsType"),
];
? print("test")
: [print("checkType"), " ", "extends", " ", print("extendsType")];
/**
* a
* ? b
@@ -191,9 +185,9 @@ function shouldExtraIndentForConditionalExpression(path) {
* @param {AstPath} path - The path to the ConditionalExpression/TSConditionalType node.
* @param {Options} options - Prettier options
* @param {Function} print - Print function to call recursively
* @returns {Promise<Doc>}
* @returns {Doc}
*/
async function printTernary(path, options, print) {
function printTernary(path, options, print) {
const node = path.getValue();
const isConditionalExpression = node.type === "ConditionalExpression";
const consequentNodePropertyName = isConditionalExpression
@@ -270,12 +264,12 @@ async function printTernary(path, options, print) {
parts.push(
" ? ",
isNil(consequentNode)
? await print(consequentNodePropertyName)
: wrap(await print(consequentNodePropertyName)),
? print(consequentNodePropertyName)
: wrap(print(consequentNodePropertyName)),
" : ",
alternateNode.type === node.type || isNil(alternateNode)
? await print(alternateNodePropertyName)
: wrap(await print(alternateNodePropertyName))
? print(alternateNodePropertyName)
: wrap(print(alternateNodePropertyName))
);
} else {
// normal mode
@@ -283,13 +277,13 @@ async function printTernary(path, options, print) {
line,
"? ",
consequentNode.type === node.type ? ifBreak("", "(") : "",
align(2, await print(consequentNodePropertyName)),
align(2, print(consequentNodePropertyName)),
consequentNode.type === node.type ? ifBreak("", ")") : "",
line,
": ",
alternateNode.type === node.type
? await print(alternateNodePropertyName)
: align(2, await print(alternateNodePropertyName)),
? print(alternateNodePropertyName)
: align(2, print(alternateNodePropertyName)),
];
parts.push(
parent.type !== node.type ||
@@ -342,7 +336,7 @@ async function printTernary(path, options, print) {
const shouldExtraIndent = shouldExtraIndentForConditionalExpression(path);
const result = maybeGroup([
await printTernaryTest(path, options, print),
printTernaryTest(path, options, print),
forceNoIndent ? parts : indent(parts),
isConditionalExpression && breakClosingParen && !shouldExtraIndent
? softline
+23 -28
View File
@@ -56,18 +56,18 @@ function shouldHugType(node) {
return false;
}
async function printOpaqueType(path, options, print) {
function printOpaqueType(path, options, print) {
const semi = options.semi ? ";" : "";
const node = path.getValue();
const parts = [];
parts.push("opaque type ", await print("id"), await print("typeParameters"));
parts.push("opaque type ", print("id"), print("typeParameters"));
if (node.supertype) {
parts.push(": ", await print("supertype"));
parts.push(": ", print("supertype"));
}
if (node.impltype) {
parts.push(" = ", await print("impltype"));
parts.push(" = ", print("impltype"));
}
parts.push(semi);
@@ -75,26 +75,26 @@ async function printOpaqueType(path, options, print) {
return parts;
}
async function printTypeAlias(path, options, print) {
function printTypeAlias(path, options, print) {
const semi = options.semi ? ";" : "";
const node = path.getValue();
const parts = [];
if (node.declare) {
parts.push("declare ");
}
parts.push("type ", await print("id"), await print("typeParameters"));
parts.push("type ", print("id"), print("typeParameters"));
const rightPropertyName =
node.type === "TSTypeAliasDeclaration" ? "typeAnnotation" : "right";
return [
await printAssignment(path, options, print, parts, " =", rightPropertyName),
printAssignment(path, options, print, parts, " =", rightPropertyName),
semi,
];
}
// `TSIntersectionType` and `IntersectionTypeAnnotation`
async function printIntersectionType(path, options, print) {
function printIntersectionType(path, options, print) {
const node = path.getValue();
const types = await path.map(print, "types");
const types = path.map(print, "types");
const result = [];
let wasIndented = false;
for (let i = 0; i < types.length; ++i) {
@@ -121,7 +121,7 @@ async function printIntersectionType(path, options, print) {
}
// `TSUnionType` and `UnionTypeAnnotation`
async function printUnionType(path, options, print) {
function printUnionType(path, options, print) {
const node = path.getValue();
// single-line variation
// A | B | C
@@ -164,8 +164,8 @@ async function printUnionType(path, options, print) {
// | child1
// // comment
// | child2
const printed = await path.map(async (typePath) => {
let printedType = await print();
const printed = path.map((typePath) => {
let printedType = print();
if (!shouldHug) {
printedType = align(2, printedType);
}
@@ -203,7 +203,7 @@ async function printUnionType(path, options, print) {
}
// `TSFunctionType` and `FunctionTypeAnnotation`
async function printFunctionType(path, options, print) {
function printFunctionType(path, options, print) {
const node = path.getValue();
const parts = [];
// FunctionTypeAnnotation is ambiguous:
@@ -246,7 +246,7 @@ async function printFunctionType(path, options, print) {
parts.push("(");
}
const parametersDoc = await printFunctionParameters(
const parametersDoc = printFunctionParameters(
path,
print,
options,
@@ -260,9 +260,9 @@ async function printFunctionType(path, options, print) {
node.returnType || node.predicate || node.typeAnnotation
? [
isArrowFunctionTypeAnnotation ? " => " : ": ",
await print("returnType"),
await print("predicate"),
await print("typeAnnotation"),
print("returnType"),
print("predicate"),
print("typeAnnotation"),
]
: "";
@@ -285,7 +285,7 @@ async function printFunctionType(path, options, print) {
}
// `TSTupleType` and `TupleTypeAnnotation`
async function printTupleType(path, options, print) {
function printTupleType(path, options, print) {
const node = path.getValue();
const typesField = node.type === "TSTupleType" ? "elementTypes" : "types";
const types = node[typesField];
@@ -295,7 +295,7 @@ async function printTupleType(path, options, print) {
"[",
indent([
bracketsDelimiterLine,
await printArrayItems(path, options, typesField, print),
printArrayItems(path, options, typesField, print),
]),
ifBreak(isNonEmptyTuple && shouldPrintComma(options, "all") ? "," : ""),
printDanglingComments(path, options, /* sameIndent */ true),
@@ -305,24 +305,19 @@ async function printTupleType(path, options, print) {
}
// `TSIndexedAccessType`, `IndexedAccessType`, and `OptionalIndexedAccessType`
async function printIndexedAccessType(path, options, print) {
function printIndexedAccessType(path, options, print) {
const node = path.getValue();
const leftDelimiter =
node.type === "OptionalIndexedAccessType" && node.optional ? "?.[" : "[";
return [
await print("objectType"),
leftDelimiter,
await print("indexType"),
"]",
];
return [print("objectType"), leftDelimiter, print("indexType"), "]"];
}
// `TSJSDocNullableType`, `TSJSDocNonNullableType`
async function printJSDocType(path, print, token) {
function printJSDocType(path, print, token) {
const node = path.getValue();
return [
node.postfix ? "" : token,
await print("typeAnnotation"),
print("typeAnnotation"),
node.postfix ? token : "",
];
}
+15 -12
View File
@@ -23,7 +23,7 @@ import { isArrowFunctionVariableDeclarator } from "./assignment.js";
const getTypeParametersGroupId = createGroupIdMapper("typeParameters");
async function printTypeParameters(path, options, print, paramsKey) {
function printTypeParameters(path, options, print, paramsKey) {
const node = path.getValue();
if (!node[paramsKey]) {
@@ -58,7 +58,7 @@ async function printTypeParameters(path, options, print, paramsKey) {
if (shouldInline) {
return [
"<",
join(", ", await path.map(print, paramsKey)),
join(", ", path.map(print, paramsKey)),
printDanglingCommentsForInline(path, options),
">",
];
@@ -82,7 +82,7 @@ async function printTypeParameters(path, options, print, paramsKey) {
return group(
[
"<",
indent([softline, join([",", line], await path.map(print, paramsKey))]),
indent([softline, join([",", line], path.map(print, paramsKey))]),
trailingComma,
softline,
">",
@@ -108,24 +108,27 @@ function printDanglingCommentsForInline(path, options) {
return [printed, hardline];
}
async function printTypeParameter(path, options, print) {
function printTypeParameter(path, options, print) {
const node = path.getValue();
const parts = [];
const parent = path.getParentNode();
if (parent.type === "TSMappedType") {
parts.push("[", await print("name"));
parts.push("[", print("name"));
if (node.constraint) {
parts.push(" in ", await print("constraint"));
parts.push(" in ", print("constraint"));
}
if (parent.nameType) {
parts.push(" as ", await path.callParent(() => print("nameType")));
parts.push(
" as ",
path.callParent(() => print("nameType"))
);
}
parts.push("]");
return parts;
}
if (node.variance) {
parts.push(await print("variance"));
parts.push(print("variance"));
}
if (node.in) {
@@ -136,18 +139,18 @@ async function printTypeParameter(path, options, print) {
parts.push("out ");
}
parts.push(await print("name"));
parts.push(print("name"));
if (node.bound) {
parts.push(": ", await print("bound"));
parts.push(": ", print("bound"));
}
if (node.constraint) {
parts.push(" extends ", await print("constraint"));
parts.push(" extends ", print("constraint"));
}
if (node.default) {
parts.push(" = ", await print("default"));
parts.push(" = ", print("default"));
}
return parts;
+58 -68
View File
@@ -45,7 +45,7 @@ import {
printJSDocType,
} from "./type-annotation.js";
async function printTypescript(path, options, print) {
function printTypescript(path, options, print) {
const node = path.getValue();
// TypeScript nodes always starts with `TS`
@@ -71,31 +71,31 @@ async function printTypescript(path, options, print) {
const castGroup = group([
"<",
indent([softline, await print("typeAnnotation")]),
indent([softline, print("typeAnnotation")]),
softline,
">",
]);
const exprContents = [
ifBreak("("),
indent([softline, await print("expression")]),
indent([softline, print("expression")]),
softline,
ifBreak(")"),
];
if (shouldBreakAfterCast) {
return conditionalGroup([
[castGroup, await print("expression")],
[castGroup, print("expression")],
[castGroup, group(exprContents, { shouldBreak: true })],
[castGroup, await print("expression")],
[castGroup, print("expression")],
]);
}
return group([castGroup, await print("expression")]);
return group([castGroup, print("expression")]);
}
case "TSDeclareFunction":
return printFunction(path, print, options);
case "TSExportAssignment":
return ["export = ", await print("expression"), semi];
return ["export = ", print("expression"), semi];
case "TSModuleBlock":
return printBlock(path, options, print);
case "TSInterfaceBody":
@@ -104,7 +104,7 @@ async function printTypescript(path, options, print) {
case "TSTypeAliasDeclaration":
return printTypeAlias(path, options, print);
case "TSQualifiedName":
return join(".", [await print("left"), await print("right")]);
return join(".", [print("left"), print("right")]);
case "TSAbstractMethodDefinition":
case "TSDeclareMethod":
return printClassMethod(path, options, print);
@@ -112,10 +112,10 @@ async function printTypescript(path, options, print) {
return printClassProperty(path, options, print);
case "TSInterfaceHeritage":
case "TSExpressionWithTypeArguments": // Babel AST
parts.push(await print("expression"));
parts.push(print("expression"));
if (node.typeParameters) {
parts.push(await print("typeParameters"));
parts.push(print("typeParameters"));
}
return parts;
@@ -123,30 +123,26 @@ async function printTypescript(path, options, print) {
return printTemplateLiteral(path, print, options);
case "TSNamedTupleMember":
return [
await print("label"),
print("label"),
node.optional ? "?" : "",
": ",
await print("elementType"),
print("elementType"),
];
case "TSRestType":
return ["...", await print("typeAnnotation")];
return ["...", print("typeAnnotation")];
case "TSOptionalType":
return [await print("typeAnnotation"), "?"];
return [print("typeAnnotation"), "?"];
case "TSInterfaceDeclaration":
return printInterface(path, options, print);
case "TSClassImplements":
return [await print("expression"), await print("typeParameters")];
return [print("expression"), print("typeParameters")];
case "TSTypeParameterDeclaration":
case "TSTypeParameterInstantiation":
return printTypeParameters(path, options, print, "params");
case "TSTypeParameter":
return printTypeParameter(path, options, print);
case "TSAsExpression": {
parts.push(
await print("expression"),
" as ",
await print("typeAnnotation")
);
parts.push(print("expression"), " as ", print("typeAnnotation"));
const parent = path.getParentNode();
if (
(isCallExpression(parent) && parent.callee === node) ||
@@ -157,24 +153,24 @@ async function printTypescript(path, options, print) {
return parts;
}
case "TSArrayType":
return [await print("elementType"), "[]"];
return [print("elementType"), "[]"];
case "TSPropertySignature": {
if (node.readonly) {
parts.push("readonly ");
}
parts.push(
await printPropertyKey(path, options, print),
await printOptionalToken(path)
printPropertyKey(path, options, print),
printOptionalToken(path)
);
if (node.typeAnnotation) {
parts.push(": ", await print("typeAnnotation"));
parts.push(": ", print("typeAnnotation"));
}
// This isn't valid semantically, but it's in the AST so we can print it.
if (node.initializer) {
parts.push(" = ", await print("initializer"));
parts.push(" = ", print("initializer"));
}
return parts;
@@ -196,15 +192,11 @@ async function printTypescript(path, options, print) {
parts.push("readonly ");
}
parts.push(await print("parameter"));
parts.push(print("parameter"));
return parts;
case "TSTypeQuery":
return [
"typeof ",
await print("exprName"),
await print("typeParameters"),
];
return ["typeof ", print("exprName"), print("typeParameters")];
case "TSIndexSignature": {
const parent = path.getParentNode();
@@ -220,7 +212,7 @@ async function printTypescript(path, options, print) {
const parametersGroup = group([
indent([
softline,
join([", ", softline], await path.map(print, "parameters")),
join([", ", softline], path.map(print, "parameters")),
]),
trailingComma,
softline,
@@ -235,26 +227,26 @@ async function printTypescript(path, options, print) {
"[",
node.parameters ? parametersGroup : "",
node.typeAnnotation ? "]: " : "]",
node.typeAnnotation ? await print("typeAnnotation") : "",
node.typeAnnotation ? print("typeAnnotation") : "",
parent.type === "ClassBody" ? semi : "",
];
}
case "TSTypePredicate":
return [
node.asserts ? "asserts " : "",
await print("parameterName"),
node.typeAnnotation ? [" is ", await print("typeAnnotation")] : "",
print("parameterName"),
node.typeAnnotation ? [" is ", print("typeAnnotation")] : "",
];
case "TSNonNullExpression":
return [await print("expression"), "!"];
return [print("expression"), "!"];
case "TSImportType":
return [
!node.isTypeOf ? "" : "typeof ",
"import(",
await print(node.parameter ? "parameter" : "argument"),
print(node.parameter ? "parameter" : "argument"),
")",
!node.qualifier ? "" : [".", await print("qualifier")],
await printTypeParameters(path, options, print, "typeParameters"),
!node.qualifier ? "" : [".", print("qualifier")],
printTypeParameters(path, options, print, "typeParameters"),
];
case "TSLiteralType":
return print("literal");
@@ -272,7 +264,7 @@ async function printTypescript(path, options, print) {
parts.push(
group(
await printFunctionParameters(
printFunctionParameters(
path,
print,
options,
@@ -286,14 +278,14 @@ async function printTypescript(path, options, print) {
const isType = node.type === "TSConstructorType";
parts.push(
isType ? " => " : ": ",
await print("returnType"),
await print("typeAnnotation")
print("returnType"),
print("typeAnnotation")
);
}
return parts;
}
case "TSTypeOperator":
return [node.operator, " ", await print("typeAnnotation")];
return [node.operator, " ", print("typeAnnotation")];
case "TSMappedType": {
const shouldBreak = hasNewlineInRange(
options.originalText,
@@ -311,13 +303,13 @@ async function printTypescript(path, options, print) {
" ",
]
: "",
await printTypeScriptModifiers(path, options, print),
await print("typeParameter"),
printTypeScriptModifiers(path, options, print),
print("typeParameter"),
node.optional
? getTypeScriptMappedTypeModifier(node.optional, "?")
: "",
node.typeAnnotation ? ": " : "",
await print("typeAnnotation"),
print("typeAnnotation"),
ifBreak(semi),
]),
printDanglingComments(path, options, /* sameIndent */ true),
@@ -340,12 +332,12 @@ async function printTypescript(path, options, print) {
node.abstract ? "abstract " : "",
node.declare ? "declare " : "",
node.computed ? "[" : "",
await print("key"),
print("key"),
node.computed ? "]" : "",
printOptionalToken(path)
);
const parametersDoc = await printFunctionParameters(
const parametersDoc = printFunctionParameters(
path,
print,
options,
@@ -357,9 +349,7 @@ async function printTypescript(path, options, print) {
? "returnType"
: "typeAnnotation";
const returnTypeNode = node[returnTypePropertyName];
const returnTypeDoc = returnTypeNode
? await print(returnTypePropertyName)
: "";
const returnTypeDoc = returnTypeNode ? print(returnTypePropertyName) : "";
const shouldGroupParameters = shouldGroupFunctionParameters(
node,
returnTypeDoc
@@ -374,7 +364,7 @@ async function printTypescript(path, options, print) {
return group(parts);
}
case "TSNamespaceExportDeclaration":
parts.push("export as namespace ", await print("id"));
parts.push("export as namespace ", print("id"));
if (options.semi) {
parts.push(";");
@@ -387,13 +377,13 @@ async function printTypescript(path, options, print) {
}
if (node.modifiers) {
parts.push(await printTypeScriptModifiers(path, options, print));
parts.push(printTypeScriptModifiers(path, options, print));
}
if (node.const) {
parts.push("const ");
}
parts.push("enum ", await print("id"), " ");
parts.push("enum ", print("id"), " ");
if (node.members.length === 0) {
parts.push(
@@ -405,7 +395,7 @@ async function printTypescript(path, options, print) {
"{",
indent([
hardline,
await printArrayItems(path, options, "members", print),
printArrayItems(path, options, "members", print),
shouldPrintComma(options, "es5") ? "," : "",
]),
printDanglingComments(path, options, /* sameIndent */ true),
@@ -418,13 +408,13 @@ async function printTypescript(path, options, print) {
return parts;
case "TSEnumMember":
if (node.computed) {
parts.push("[", await print("id"), "]");
parts.push("[", print("id"), "]");
} else {
parts.push(await print("id"));
parts.push(print("id"));
}
if (node.initializer) {
parts.push(" = ", await print("initializer"));
parts.push(" = ", print("initializer"));
}
return parts;
case "TSImportEqualsDeclaration":
@@ -438,7 +428,7 @@ async function printTypescript(path, options, print) {
parts.push(node.importKind, " ");
}
parts.push(await print("id"), " = ", await print("moduleReference"));
parts.push(print("id"), " = ", print("moduleReference"));
if (options.semi) {
parts.push(";");
@@ -446,7 +436,7 @@ async function printTypescript(path, options, print) {
return group(parts);
case "TSExternalModuleReference":
return ["require(", await print("expression"), ")"];
return ["require(", print("expression"), ")"];
case "TSModuleDeclaration": {
const parent = path.getParentNode();
const isExternalModule = isLiteral(node.id);
@@ -460,7 +450,7 @@ async function printTypescript(path, options, print) {
if (node.declare) {
parts.push("declare ");
}
parts.push(await printTypeScriptModifiers(path, options, print));
parts.push(printTypeScriptModifiers(path, options, print));
const textBetweenNodeAndItsId = options.originalText.slice(
locStart(node),
@@ -484,12 +474,12 @@ async function printTypescript(path, options, print) {
}
}
parts.push(await print("id"));
parts.push(print("id"));
if (bodyIsDeclaration) {
parts.push(await print("body"));
parts.push(print("body"));
} else if (node.body) {
parts.push(" ", group(await print("body")));
parts.push(" ", group(print("body")));
} else {
parts.push(semi);
}
@@ -501,7 +491,7 @@ async function printTypescript(path, options, print) {
return printTernary(path, options, print);
case "TSInferType":
return ["infer", " ", await print("typeParameter")];
return ["infer", " ", print("typeParameter")];
case "TSIntersectionType":
return printIntersectionType(path, options, print);
case "TSUnionType":
@@ -512,8 +502,8 @@ async function printTypescript(path, options, print) {
return printTupleType(path, options, print);
case "TSTypeReference":
return [
await print("typeName"),
await printTypeParameters(path, options, print, "typeParameters"),
print("typeName"),
printTypeParameters(path, options, print, "typeParameters"),
];
case "TSTypeAnnotation":
return print("typeAnnotation");
@@ -530,7 +520,7 @@ async function printTypescript(path, options, print) {
case "TSJSDocNonNullableType":
return printJSDocType(path, print, /* token */ "!");
case "TSInstantiationExpression":
return [await print("expression"), await print("typeParameters")];
return [print("expression"), print("typeParameters")];
default:
/* istanbul ignore next */
throw new Error(
+6 -10
View File
@@ -1,18 +1,17 @@
import { hardline, indent, join } from "../document/builders.js";
import preprocess from "./print-preprocess.js";
async function genericPrint(path, options, print) {
function genericPrint(path, options, print) {
const node = path.getValue();
switch (node.type) {
case "JsonRoot":
return [await print("node"), hardline];
return [print("node"), hardline];
case "ArrayExpression": {
if (node.elements.length === 0) {
return "[]";
}
const printed = await path.map(
const printed = path.map(
() => (path.getValue() === null ? "null" : print()),
"elements"
);
@@ -31,18 +30,15 @@ async function genericPrint(path, options, print) {
"{",
indent([
hardline,
join([",", hardline], await path.map(print, "properties")),
join([",", hardline], path.map(print, "properties")),
]),
hardline,
"}",
];
case "ObjectProperty":
return [await print("key"), ": ", await print("value")];
return [print("key"), ": ", print("value")];
case "UnaryExpression":
return [
node.operator === "+" ? "" : node.operator,
await print("argument"),
];
return [node.operator === "+" ? "" : node.operator, print("argument")];
case "NullLiteral":
return "null";
case "BooleanLiteral":
+72 -84
View File
@@ -87,8 +87,8 @@ import { printComment } from "./print/comment.js";
import { printLiteral } from "./print/literal.js";
import { printDecorators } from "./print/decorators.js";
async function genericPrint(path, options, print, args) {
const printed = await printPathNoParens(path, options, print, args);
function genericPrint(path, options, print, args) {
const printed = printPathNoParens(path, options, print, args);
if (!printed) {
return "";
}
@@ -113,7 +113,7 @@ async function genericPrint(path, options, print, args) {
let parts = [printed];
const printedDecorators = await printDecorators(path, options, print);
const printedDecorators = printDecorators(path, options, print);
const isClassExpressionWithDecorators =
node.type === "ClassExpression" && printedDecorators;
// Nodes (except `ClassExpression`) with decorators can't have parentheses and don't need leading semicolons
@@ -165,7 +165,7 @@ async function genericPrint(path, options, print, args) {
return parts;
}
async function printPathNoParens(path, options, print, args) {
function printPathNoParens(path, options, print, args) {
const node = path.getValue();
const semi = options.semi ? ";" : "";
@@ -185,7 +185,7 @@ async function printPathNoParens(path, options, print, args) {
printFlow,
printTypescript,
]) {
const printed = await printer(path, options, print);
const printed = printer(path, options, print);
if (typeof printed !== "undefined") {
return printed;
}
@@ -198,15 +198,15 @@ async function printPathNoParens(path, options, print, args) {
case "JsExpressionRoot":
return print("node");
case "JsonRoot":
return [await print("node"), hardline];
return [print("node"), hardline];
case "File":
// Print @babel/parser's InterpreterDirective here so that
// leading comments on the `Program` node get printed after the hashbang.
if (node.program && node.program.interpreter) {
parts.push(await print(["program", "interpreter"]));
parts.push(print(["program", "interpreter"]));
}
parts.push(await print("program"));
parts.push(print("program"));
return parts;
@@ -218,7 +218,7 @@ async function printPathNoParens(path, options, print, args) {
case "ExpressionStatement": {
// Detect Flow and TypeScript directives
if (node.directive) {
return [await printDirective(node.expression, options), semi];
return [printDirective(node.expression, options), semi];
}
if (
@@ -232,7 +232,7 @@ async function printPathNoParens(path, options, print, args) {
parent.body[0] === node
) {
return [
await print("expression"),
print("expression"),
isVueEventBindingExpression(node.expression) ? ";" : "",
];
}
@@ -247,7 +247,7 @@ async function printPathNoParens(path, options, print, args) {
// Do not append semicolon after the only JSX element in a program
return [
await print("expression"),
print("expression"),
isTheOnlyJsxElementInMarkdown(options, path) ? "" : semi,
danglingComment ? [" ", danglingComment] : "",
];
@@ -259,11 +259,11 @@ async function printPathNoParens(path, options, print, args) {
(node.expression.type === "ObjectExpression" ||
node.expression.type === "ArrayExpression");
if (shouldHug) {
return ["(", await print("expression"), ")"];
return ["(", print("expression"), ")"];
}
return group([
"(",
indent([softline, await print("expression")]),
indent([softline, print("expression")]),
softline,
")",
]);
@@ -276,24 +276,21 @@ async function printPathNoParens(path, options, print, args) {
case "LogicalExpression":
return printBinaryishExpression(path, options, print);
case "AssignmentPattern":
return [await print("left"), " = ", await print("right")];
return [print("left"), " = ", print("right")];
case "OptionalMemberExpression":
case "MemberExpression": {
return printMemberExpression(path, options, print);
}
case "MetaProperty":
return [await print("meta"), ".", await print("property")];
return [print("meta"), ".", print("property")];
case "BindExpression":
if (node.object) {
parts.push(await print("object"));
parts.push(print("object"));
}
parts.push(
group(
indent([
softline,
await printBindExpressionCallee(path, options, print),
])
indent([softline, printBindExpressionCallee(path, options, print)])
)
);
@@ -301,9 +298,9 @@ async function printPathNoParens(path, options, print, args) {
case "Identifier": {
return [
node.name,
await printOptionalToken(path),
await printDefiniteToken(path),
await printTypeAnnotation(path, options, print),
printOptionalToken(path),
printDefiniteToken(path),
printTypeAnnotation(path, options, print),
];
}
case "V8IntrinsicIdentifier":
@@ -326,14 +323,14 @@ async function printPathNoParens(path, options, print, args) {
parts.push("*");
}
if (node.argument) {
parts.push(" ", await print("argument"));
parts.push(" ", print("argument"));
}
return parts;
case "AwaitExpression": {
parts.push("await");
if (node.argument) {
parts.push(" ", await print("argument"));
parts.push(" ", print("argument"));
const parent = path.getParentNode();
if (
(isCallExpression(parent) && parent.callee === node) ||
@@ -369,7 +366,7 @@ async function printPathNoParens(path, options, print, args) {
case "ExportDefaultSpecifier":
return printModuleSpecifier(path, options, print);
case "ImportAttribute":
return [await print("key"), ": ", await print("value")];
return [print("key"), ": ", print("value")];
case "Import":
return "import";
case "BlockStatement":
@@ -400,7 +397,7 @@ async function printPathNoParens(path, options, print, args) {
case "ObjectMethod":
return printMethod(path, options, print);
case "Decorator":
return ["@", await print("expression")];
return ["@", print("expression")];
case "ArrayExpression":
case "ArrayPattern":
case "TupleExpression":
@@ -415,23 +412,23 @@ async function printPathNoParens(path, options, print, args) {
// the few places a SequenceExpression appears unparenthesized, we want
// to indent expressions after the first.
const parts = [];
await path.each(async (expressionPath, index) => {
path.each((expressionPath, index) => {
if (index === 0) {
parts.push(await print());
parts.push(print());
} else {
parts.push(",", indent([line, await print()]));
parts.push(",", indent([line, print()]));
}
}, "expressions");
return group(parts);
}
return group(join([",", line], await path.map(print, "expressions")));
return group(join([",", line], path.map(print, "expressions")));
}
case "ThisExpression":
return "this";
case "Super":
return "super";
case "Directive":
return [await print("value"), semi]; // Babel 6
return [print("value"), semi]; // Babel 6
case "DirectiveLiteral":
return printDirective(node, options);
case "UnaryExpression":
@@ -443,20 +440,15 @@ async function printPathNoParens(path, options, print, args) {
if (hasComment(node.argument)) {
parts.push(
group([
"(",
indent([softline, await print("argument")]),
softline,
")",
])
group(["(", indent([softline, print("argument")]), softline, ")"])
);
} else {
parts.push(await print("argument"));
parts.push(print("argument"));
}
return parts;
case "UpdateExpression":
parts.push(await print("argument"), node.operator);
parts.push(print("argument"), node.operator);
if (node.prefix) {
parts.reverse();
@@ -466,7 +458,7 @@ async function printPathNoParens(path, options, print, args) {
case "ConditionalExpression":
return printTernary(path, options, print);
case "VariableDeclaration": {
const printed = await path.map(print, "declarations");
const printed = path.map(print, "declarations");
// We generally want to terminate all variable declarations with a
// semicolon, except when they in the () part of for loops.
@@ -511,15 +503,15 @@ async function printPathNoParens(path, options, print, args) {
case "WithStatement":
return group([
"with (",
await print("object"),
print("object"),
")",
adjustClause(node.body, await print("body")),
adjustClause(node.body, print("body")),
]);
case "IfStatement": {
const con = adjustClause(node.consequent, await print("consequent"));
const con = adjustClause(node.consequent, print("consequent"));
const opening = group([
"if (",
group([indent([softline, await print("test")]), softline]),
group([indent([softline, print("test")]), softline]),
")",
con,
]);
@@ -548,7 +540,7 @@ async function printPathNoParens(path, options, print, args) {
group(
adjustClause(
node.alternate,
await print("alternate"),
print("alternate"),
node.alternate.type === "IfStatement"
)
)
@@ -558,7 +550,7 @@ async function printPathNoParens(path, options, print, args) {
return parts;
}
case "ForStatement": {
const body = adjustClause(node.body, await print("body"));
const body = adjustClause(node.body, print("body"));
// We want to keep dangling comments above the loop to stay consistent.
// Any comment positioned between the for statement and the parentheses
@@ -581,13 +573,13 @@ async function printPathNoParens(path, options, print, args) {
group([
indent([
softline,
await print("init"),
print("init"),
";",
line,
await print("test"),
print("test"),
";",
line,
await print("update"),
print("update"),
]),
softline,
]),
@@ -599,18 +591,18 @@ async function printPathNoParens(path, options, print, args) {
case "WhileStatement":
return group([
"while (",
group([indent([softline, await print("test")]), softline]),
group([indent([softline, print("test")]), softline]),
")",
adjustClause(node.body, await print("body")),
adjustClause(node.body, print("body")),
]);
case "ForInStatement":
return group([
"for (",
await print("left"),
print("left"),
" in ",
await print("right"),
print("right"),
")",
adjustClause(node.body, await print("body")),
adjustClause(node.body, print("body")),
]);
case "ForOfStatement":
@@ -618,15 +610,15 @@ async function printPathNoParens(path, options, print, args) {
"for",
node.await ? " await" : "",
" (",
await print("left"),
print("left"),
" of ",
await print("right"),
print("right"),
")",
adjustClause(node.body, await print("body")),
adjustClause(node.body, print("body")),
]);
case "DoWhileStatement": {
const clause = adjustClause(node.body, await print("body"));
const clause = adjustClause(node.body, print("body"));
const doBody = group(["do", clause]);
parts = [doBody];
@@ -637,7 +629,7 @@ async function printPathNoParens(path, options, print, args) {
}
parts.push(
"while (",
group([indent([softline, await print("test")]), softline]),
group([indent([softline, print("test")]), softline]),
")",
semi
);
@@ -645,12 +637,12 @@ async function printPathNoParens(path, options, print, args) {
return parts;
}
case "DoExpression":
return [node.async ? "async " : "", "do ", await print("body")];
return [node.async ? "async " : "", "do ", print("body")];
case "BreakStatement":
parts.push("break");
if (node.label) {
parts.push(" ", await print("label"));
parts.push(" ", print("label"));
}
parts.push(semi);
@@ -660,7 +652,7 @@ async function printPathNoParens(path, options, print, args) {
parts.push("continue");
if (node.label) {
parts.push(" ", await print("label"));
parts.push(" ", print("label"));
}
parts.push(semi);
@@ -668,16 +660,16 @@ async function printPathNoParens(path, options, print, args) {
return parts;
case "LabeledStatement":
if (node.body.type === "EmptyStatement") {
return [await print("label"), ":;"];
return [print("label"), ":;"];
}
return [await print("label"), ": ", await print("body")];
return [print("label"), ": ", print("body")];
case "TryStatement":
return [
"try ",
await print("block"),
node.handler ? [" ", await print("handler")] : "",
node.finalizer ? [" finally ", await print("finalizer")] : "",
print("block"),
node.handler ? [" ", print("handler")] : "",
node.finalizer ? [" finally ", print("finalizer")] : "",
];
case "CatchClause":
if (node.param) {
@@ -692,24 +684,24 @@ async function printPathNoParens(path, options, print, args) {
backwards: true,
}))
);
const param = await print("param");
const param = print("param");
return [
"catch ",
parameterHasComments
? ["(", indent([softline, param]), softline, ") "]
: ["(", param, ") "],
await print("body"),
print("body"),
];
}
return ["catch ", await print("body")];
return ["catch ", print("body")];
// Note: ignoring n.lexical because it has no printing consequences.
case "SwitchStatement":
return [
group([
"switch (",
indent([softline, await print("discriminant")]),
indent([softline, print("discriminant")]),
softline,
")",
]),
@@ -719,10 +711,10 @@ async function printPathNoParens(path, options, print, args) {
hardline,
join(
hardline,
await path.map(async (casePath, index, cases) => {
path.map((casePath, index, cases) => {
const caseNode = casePath.getValue();
return [
await print(),
print(),
index !== cases.length - 1 &&
isNextLineEmpty(caseNode, options)
? hardline
@@ -737,7 +729,7 @@ async function printPathNoParens(path, options, print, args) {
];
case "SwitchCase": {
if (node.test) {
parts.push("case ", await print("test"), ":");
parts.push("case ", print("test"), ":");
} else {
parts.push("default:");
}
@@ -751,7 +743,7 @@ async function printPathNoParens(path, options, print, args) {
);
if (consequent.length > 0) {
const cons = await printSwitchCaseConsequent(path, options, print);
const cons = printSwitchCaseConsequent(path, options, print);
parts.push(
consequent.length === 1 && consequent[0].type === "BlockStatement"
@@ -783,15 +775,11 @@ async function printPathNoParens(path, options, print, args) {
case "TemplateLiteral":
return printTemplateLiteral(path, print, options);
case "TaggedTemplateExpression":
return [
await print("tag"),
await print("typeParameters"),
await print("quasi"),
];
return [print("tag"), print("typeParameters"), print("quasi")];
case "PrivateIdentifier":
return ["#", await print("name")];
return ["#", print("name")];
case "PrivateName":
return ["#", await print("id")];
return ["#", print("id")];
case "InterpreterDirective":
parts.push("#!", node.value, hardline);
@@ -811,7 +799,7 @@ async function printPathNoParens(path, options, print, args) {
case "ModuleExpression": {
parts.push("module {");
const printed = await print("body");
const printed = print("body");
if (printed) {
parts.push(indent([hardline, printed]), hardline);
}
+9 -9
View File
@@ -1120,20 +1120,20 @@ function getFunctionParameters(node) {
return parameters;
}
async function iterateFunctionParametersPath(path, iteratee) {
function iterateFunctionParametersPath(path, iteratee) {
const node = path.getValue();
let index = 0;
const callback = (childPath) => iteratee(childPath, index++);
if (node.this) {
await path.call(callback, "this");
path.call(callback, "this");
}
if (Array.isArray(node.parameters)) {
await path.each(callback, "parameters");
path.each(callback, "parameters");
} else if (Array.isArray(node.params)) {
await path.each(callback, "params");
path.each(callback, "params");
}
if (node.rest) {
await path.call(callback, "rest");
path.call(callback, "rest");
}
}
@@ -1156,16 +1156,16 @@ function getCallArguments(node) {
return args;
}
async function iterateCallArgumentsPath(path, iteratee) {
function iterateCallArgumentsPath(path, iteratee) {
const node = path.getValue();
if (node.type === "ImportExpression") {
await path.call((sourcePath) => iteratee(sourcePath, 0), "source");
path.call((sourcePath) => iteratee(sourcePath, 0), "source");
if (node.attributes) {
await path.call((sourcePath) => iteratee(sourcePath, 1), "attributes");
path.call((sourcePath) => iteratee(sourcePath, 1), "attributes");
}
} else {
await path.each(iteratee, "arguments");
path.each(iteratee, "arguments");
}
}
+3 -3
View File
@@ -7,7 +7,7 @@ import { replaceEndOfLine } from "../document/utils.js";
import printFrontMatter from "../utils/front-matter/print.js";
import { getFencedCodeBlockValue } from "./utils.js";
async function embed(path, print, textToDoc, options) {
function embed(path, print, textToDoc, options) {
const node = path.getValue();
if (node.type === "code" && node.lang !== null) {
@@ -21,7 +21,7 @@ async function embed(path, print, textToDoc, options) {
if (node.lang === "tsx") {
newOptions.filepath = "dummy.tsx";
}
const doc = await textToDoc(
const doc = textToDoc(
getFencedCodeBlockValue(node, options.originalText),
newOptions,
{ stripTrailingHardline: true }
@@ -45,7 +45,7 @@ async function embed(path, print, textToDoc, options) {
// MDX
case "importExport":
return [
await textToDoc(
textToDoc(
node.value,
{ parser: "babel" },
{ stripTrailingHardline: true }
+1 -1
View File
@@ -40,7 +40,7 @@ function createParse({ isMDX }) {
.use(isMDX ? htmlToJsx : identity)
.use(wikiLink)
.use(looseItems);
return processor.run(processor.parse(text));
return processor.runSync(processor.parse(text));
};
}
+29 -32
View File
@@ -49,7 +49,7 @@ const SIBLING_NODE_TYPES = new Set([
"footnoteDefinition",
]);
async function genericPrint(path, options, print) {
function genericPrint(path, options, print) {
const node = path.getValue();
if (shouldRemainTheSameContent(path)) {
@@ -79,7 +79,7 @@ async function genericPrint(path, options, print) {
return "";
}
return [
normalizeDoc(await printRoot(path, options, print)),
normalizeDoc(printRoot(path, options, print)),
!TRAILING_HARDLINE_NODES.has(getLastDescendantNode(node).type)
? hardline
: "",
@@ -167,12 +167,12 @@ async function genericPrint(path, options, print) {
style =
hasPrevOrNextWord || getAncestorNode(path, "emphasis") ? "*" : "_";
}
return [style, await printChildren(path, options, print), style];
return [style, printChildren(path, options, print), style];
}
case "strong":
return ["**", await printChildren(path, options, print), "**"];
return ["**", printChildren(path, options, print), "**"];
case "delete":
return ["~~", await printChildren(path, options, print), "~~"];
return ["~~", printChildren(path, options, print), "~~"];
case "inlineCode": {
const backtickCount = getMinNotPresentContinuousCount(node.value, "`");
const style = "`".repeat(backtickCount || 1);
@@ -207,7 +207,7 @@ async function genericPrint(path, options, print) {
case "[":
return [
"[",
await printChildren(path, options, print),
printChildren(path, options, print),
"](",
printUrl(node.url, ")"),
printTitle(node.title, options),
@@ -229,11 +229,11 @@ async function genericPrint(path, options, print) {
")",
];
case "blockquote":
return ["> ", align("> ", await printChildren(path, options, print))];
return ["> ", align("> ", printChildren(path, options, print))];
case "heading":
return [
"#".repeat(node.depth) + " ",
await printChildren(path, options, print),
printChildren(path, options, print),
];
case "code": {
if (node.isIndented) {
@@ -290,7 +290,7 @@ async function genericPrint(path, options, print) {
);
return printChildren(path, options, print, {
processor: async (childPath, index) => {
processor: (childPath, index) => {
const prefix = getPrefix();
const childNode = childPath.getValue();
@@ -300,17 +300,14 @@ async function genericPrint(path, options, print) {
childNode.children[0].position.start.column !==
childNode.children[1].position.start.column
) {
return [
prefix,
await printListItem(childPath, options, print, prefix),
];
return [prefix, printListItem(childPath, options, print, prefix)];
}
return [
prefix,
align(
" ".repeat(prefix.length),
await printListItem(childPath, options, print, prefix)
printListItem(childPath, options, print, prefix)
),
];
@@ -348,7 +345,7 @@ async function genericPrint(path, options, print) {
case "linkReference":
return [
"[",
await printChildren(path, options, print),
printChildren(path, options, print),
"]",
node.referenceType === "full"
? ["[", node.identifier, "]"]
@@ -387,7 +384,7 @@ async function genericPrint(path, options, print) {
// https://github.com/remarkjs/remark-footnotes#optionsinlinenotes
/* istanbul ignore next */
case "footnote":
return ["[^", await printChildren(path, options, print), "]"];
return ["[^", printChildren(path, options, print), "]"];
case "footnoteReference":
return ["[^", node.identifier, "]"];
case "footnoteDefinition": {
@@ -404,13 +401,13 @@ async function genericPrint(path, options, print) {
node.identifier,
"]: ",
shouldInlineFootnote
? await printChildren(path, options, print)
? printChildren(path, options, print)
: group([
align(
" ".repeat(4),
await printChildren(path, options, print, {
processor: async (childPath, index) =>
index === 0 ? group([softline, await print()]) : print(),
printChildren(path, options, print, {
processor: (childPath, index) =>
index === 0 ? group([softline, print()]) : print(),
})
),
nextNode && nextNode.type === "footnoteDefinition"
@@ -461,21 +458,21 @@ async function genericPrint(path, options, print) {
}
}
async function printListItem(path, options, print, listPrefix) {
function printListItem(path, options, print, listPrefix) {
const node = path.getValue();
const prefix = node.checked === null ? "" : node.checked ? "[x] " : "[ ] ";
return [
prefix,
await printChildren(path, options, print, {
processor: async (childPath, index) => {
printChildren(path, options, print, {
processor: (childPath, index) => {
if (index === 0 && childPath.getValue().type !== "list") {
return align(" ".repeat(prefix.length), await print());
return align(" ".repeat(prefix.length), print());
}
const alignment = " ".repeat(
clamp(options.tabWidth - listPrefix.length, 0, 3) // 4+ will cause indented code block
);
return [alignment, align(alignment, await print())];
return [alignment, align(alignment, print())];
},
}),
];
@@ -557,15 +554,15 @@ function printLine(path, value, options) {
: "";
}
async function printTable(path, options, print) {
function printTable(path, options, print) {
const node = path.getValue();
const columnMaxWidths = [];
// { [rowIndex: number]: { [columnIndex: number]: {text: string, width: number} } }
const contents = await path.map(
const contents = path.map(
(rowPath) =>
rowPath.map(async (cellPath, columnIndex) => {
const text = printDocToString(await print(), options).formatted;
rowPath.map((cellPath, columnIndex) => {
const text = printDocToString(print(), options).formatted;
const width = getStringWidth(text);
columnMaxWidths[columnIndex] = Math.max(
columnMaxWidths[columnIndex] || 3, // minimum width = 3 (---, :--, :-:, --:)
@@ -696,7 +693,7 @@ function printRoot(path, options, print) {
});
}
async function printChildren(path, options, print, events = {}) {
function printChildren(path, options, print, events = {}) {
const { postprocessor } = events;
const processor = events.processor || (() => print());
@@ -705,10 +702,10 @@ async function printChildren(path, options, print, events = {}) {
let lastChildNode;
await path.each(async (childPath, index) => {
path.each((childPath, index) => {
const childNode = childPath.getValue();
const result = await processor(childPath, index);
const result = processor(childPath, index);
if (result !== false) {
const data = {
parts,
+2 -2
View File
@@ -20,7 +20,7 @@ import {
} from "../utils.js";
import { alignWithSpaces } from "./misc.js";
async function printBlock(path, print, options) {
function printBlock(path, print, options) {
const node = path.getValue();
const parentIndent = getAncestorCount(path, (ancestorNode) =>
isNode(ancestorNode, ["sequence", "mapping"])
@@ -37,7 +37,7 @@ async function printBlock(path, print, options) {
}
if (hasIndicatorComment(node)) {
parts.push(" ", await print("indicatorComment"));
parts.push(" ", print("indicatorComment"));
}
const lineContents = getBlockValueLineContents(node, {
@@ -8,7 +8,7 @@ import {
import { isEmptyNode, getLast, hasEndComments } from "../utils.js";
import { printNextEmptyLine, alignWithSpaces } from "./misc.js";
async function printFlowMapping(path, print, options) {
function printFlowMapping(path, print, options) {
const node = path.getValue();
const isMapping = node.type === "flowMapping";
const openMarker = isMapping ? "{" : "[";
@@ -30,10 +30,10 @@ async function printFlowMapping(path, print, options) {
openMarker,
alignWithSpaces(options.tabWidth, [
bracketSpacing,
await printChildren(path, print, options),
printChildren(path, print, options),
options.trailingComma === "none" ? "" : ifBreak(","),
hasEndComments(node)
? [hardline, join(hardline, await path.map(print, "endComments"))]
? [hardline, join(hardline, path.map(print, "endComments"))]
: "",
]),
isLastItemEmptyMappingItem ? "" : bracketSpacing,
@@ -41,11 +41,11 @@ async function printFlowMapping(path, print, options) {
];
}
async function printChildren(path, print, options) {
function printChildren(path, print, options) {
const node = path.getValue();
const parts = await path.map(
async (childPath, index) => [
await print(),
const parts = path.map(
(childPath, index) => [
print(),
index === node.children.length - 1
? ""
: [
+6 -7
View File
@@ -19,7 +19,7 @@ import {
} from "../utils.js";
import { alignWithSpaces } from "./misc.js";
async function printMappingItem(node, parentNode, path, print, options) {
function printMappingItem(node, parentNode, path, print, options) {
const { key, value } = node;
const isEmptyMappingKey = isEmptyNode(key);
@@ -29,7 +29,7 @@ async function printMappingItem(node, parentNode, path, print, options) {
return ": ";
}
const printedKey = await print("key");
const printedKey = print("key");
const spaceBeforeColon = needsSpaceInFrontOfMappingValue(node) ? " " : "";
if (isEmptyMappingValue) {
@@ -49,7 +49,7 @@ async function printMappingItem(node, parentNode, path, print, options) {
return ["? ", alignWithSpaces(2, printedKey)];
}
const printedValue = await print("value");
const printedValue = print("value");
if (isEmptyMappingKey) {
return [": ", alignWithSpaces(2, printedValue)];
}
@@ -62,10 +62,9 @@ async function printMappingItem(node, parentNode, path, print, options) {
hardline,
join(
"",
(await path.map(print, "value", "leadingComments")).map((comment) => [
comment,
hardline,
])
path
.map(print, "value", "leadingComments")
.map((comment) => [comment, hardline])
),
": ",
alignWithSpaces(2, printedValue),
+27 -37
View File
@@ -40,27 +40,24 @@ import {
import printMappingItem from "./print/mapping-item.js";
import printBlock from "./print/block.js";
async function genericPrint(path, options, print) {
function genericPrint(path, options, print) {
const node = path.getValue();
/** @type {Doc[]} */
const parts = [];
if (node.type !== "mappingValue" && hasLeadingComments(node)) {
parts.push([
join(hardline, await path.map(print, "leadingComments")),
hardline,
]);
parts.push([join(hardline, path.map(print, "leadingComments")), hardline]);
}
const { tag, anchor } = node;
if (tag) {
parts.push(await print("tag"));
parts.push(print("tag"));
}
if (tag && anchor) {
parts.push(" ");
}
if (anchor) {
parts.push(await print("anchor"));
parts.push(print("anchor"));
}
/** @type {Doc} */
@@ -91,7 +88,7 @@ async function genericPrint(path, options, print) {
if (hasMiddleComments(node)) {
parts.push([
node.middleComments.length === 1 ? "" : hardline,
join(hardline, await path.map(print, "middleComments")),
join(hardline, path.map(print, "middleComments")),
hardline,
]);
}
@@ -107,7 +104,7 @@ async function genericPrint(path, options, print) {
)
);
} else {
parts.push(group(await printNode(node, parentNode, path, options, print)));
parts.push(group(printNode(node, parentNode, path, options, print)));
}
if (hasTrailingComment(node) && !isNode(node, ["document", "documentHead"])) {
@@ -119,7 +116,7 @@ async function genericPrint(path, options, print) {
isInlineNode(node)
? ""
: breakParent,
await print("trailingComment"),
print("trailingComment"),
])
);
}
@@ -130,8 +127,8 @@ async function genericPrint(path, options, print) {
hardline,
join(
hardline,
await path.map(
async (path) => [
path.map(
(path) => [
isPreviousLineEmpty(
options.originalText,
path.getValue(),
@@ -139,7 +136,7 @@ async function genericPrint(path, options, print) {
)
? hardline
: "",
await print(),
print(),
],
"endComments"
)
@@ -151,22 +148,22 @@ async function genericPrint(path, options, print) {
return parts;
}
async function printNode(node, parentNode, path, options, print) {
function printNode(node, parentNode, path, options, print) {
switch (node.type) {
case "root": {
const { children } = node;
const parts = [];
await path.each(async (childPath, index) => {
path.each((childPath, index) => {
const document = children[index];
const nextDocument = children[index + 1];
if (index !== 0) {
parts.push(hardline);
}
parts.push(await print());
parts.push(print());
if (shouldPrintDocumentEndMarker(document, nextDocument)) {
parts.push(hardline, "...");
if (hasTrailingComment(document)) {
parts.push(" ", await print("trailingComment"));
parts.push(" ", print("trailingComment"));
}
} else if (nextDocument && !hasTrailingComment(nextDocument.head)) {
parts.push(hardline, "---");
@@ -194,26 +191,26 @@ async function printNode(node, parentNode, path, options, print) {
) === "head"
) {
if (node.head.children.length > 0 || node.head.endComments.length > 0) {
parts.push(await print("head"));
parts.push(print("head"));
}
if (hasTrailingComment(node.head)) {
parts.push(["---", " ", await print(["head", "trailingComment"])]);
parts.push(["---", " ", print(["head", "trailingComment"])]);
} else {
parts.push("---");
}
}
if (shouldPrintDocumentBody(node)) {
parts.push(await print("body"));
parts.push(print("body"));
}
return join(hardline, parts);
}
case "documentHead":
return join(hardline, [
...(await path.map(print, "children")),
...(await path.map(print, "endComments")),
...path.map(print, "children"),
...path.map(print, "endComments"),
]);
case "documentBody": {
const { children, endComments } = node;
@@ -233,9 +230,9 @@ async function printNode(node, parentNode, path, options, print) {
}
return [
join(hardline, await path.map(print, "children")),
join(hardline, path.map(print, "children")),
separator,
join(hardline, await path.map(print, "endComments")),
join(hardline, path.map(print, "endComments")),
];
}
case "directive":
@@ -280,7 +277,7 @@ async function printNode(node, parentNode, path, options, print) {
node.type === "quoteDouble" ? doubleQuote : singleQuote;
return [
originalQuote,
await printFlowScalarContent(node.type, raw, options),
printFlowScalarContent(node.type, raw, options),
originalQuote,
];
}
@@ -288,7 +285,7 @@ async function printNode(node, parentNode, path, options, print) {
if (raw.includes(doubleQuote)) {
return [
singleQuote,
await printFlowScalarContent(
printFlowScalarContent(
node.type,
node.type === "quoteDouble"
? raw
@@ -305,7 +302,7 @@ async function printNode(node, parentNode, path, options, print) {
if (raw.includes(singleQuote)) {
return [
doubleQuote,
await printFlowScalarContent(
printFlowScalarContent(
node.type,
node.type === "quoteSingle"
? // single quote needs to be escaped by 2 single quotes in quoteSingle
@@ -318,11 +315,7 @@ async function printNode(node, parentNode, path, options, print) {
}
const quote = options.singleQuote ? singleQuote : doubleQuote;
return [
quote,
await printFlowScalarContent(node.type, raw, options),
quote,
];
return [quote, printFlowScalarContent(node.type, raw, options), quote];
}
case "blockFolded":
case "blockLiteral": {
@@ -330,12 +323,9 @@ async function printNode(node, parentNode, path, options, print) {
}
case "mapping":
case "sequence":
return join(hardline, await path.map(print, "children"));
return join(hardline, path.map(print, "children"));
case "sequenceItem":
return [
"- ",
alignWithSpaces(2, node.content ? await print("content") : ""),
];
return ["- ", alignWithSpaces(2, node.content ? print("content") : "")];
case "mappingKey":
case "mappingValue":
return !node.content ? "" : print("content");
+9 -8
View File
@@ -25,7 +25,7 @@ import { printSubtree } from "./multiparser.js";
* state of the recursion. It is called "path", because it represents
* the path to the current node through the Abstract Syntax Tree.
*/
async function printAstToDoc(ast, options, alignmentSize = 0) {
function printAstToDoc(ast, options, alignmentSize = 0) {
const { printer } = options;
if (printer.preprocess) {
@@ -35,7 +35,7 @@ async function printAstToDoc(ast, options, alignmentSize = 0) {
const cache = new Map();
const path = new AstPath(ast);
let doc = await mainPrint();
let doc = mainPrint();
if (alignmentSize > 0) {
// Add a hardline to make the indents take effect
@@ -69,13 +69,13 @@ async function printAstToDoc(ast, options, alignmentSize = 0) {
return cache.get(value);
}
const promise = callPluginPrintFunction(path, options, mainPrint, args);
const doc = callPluginPrintFunction(path, options, mainPrint, args);
if (shouldCache) {
cache.set(value, promise);
cache.set(value, doc);
}
return promise;
return doc;
}
}
@@ -101,12 +101,13 @@ function printPrettierIgnoredNode(node, options) {
return { doc: originalText.slice(start, end), printedComments };
}
async function callPluginPrintFunction(path, options, printPath, args) {
function callPluginPrintFunction(path, options, printPath, args) {
const node = path.getValue();
const { printer } = options;
let doc;
let printedComments;
// Escape hatch
if (printer.hasPrettierIgnore && printer.hasPrettierIgnore(path)) {
({ doc, printedComments } = printPrettierIgnoredNode(node, options));
@@ -114,7 +115,7 @@ async function callPluginPrintFunction(path, options, printPath, args) {
if (node) {
try {
// Potentially switch to a different parser
doc = await printSubtree(path, printPath, options, printAstToDoc);
doc = printSubtree(path, printPath, options, printAstToDoc);
} catch (error) {
/* istanbul ignore if */
if (process.env.PRETTIER_DEBUG) {
@@ -125,7 +126,7 @@ async function callPluginPrintFunction(path, options, printPath, args) {
}
if (!doc) {
doc = await printer.print(path, options, printPath, args);
doc = printer.print(path, options, printPath, args);
}
}
+3 -3
View File
@@ -47,7 +47,7 @@ async function coreFormat(originalText, opts, addAlignmentSize = 0) {
}
const astComments = attachComments(text, ast, opts);
const doc = await printAstToDoc(ast, opts, addAlignmentSize);
const doc = printAstToDoc(ast, opts, addAlignmentSize);
const result = printDocToString(doc, opts);
@@ -334,9 +334,9 @@ const prettier = {
return parsed;
},
async formatAST(ast, options) {
formatAST(ast, options) {
options = normalizeOptions(options);
const doc = await printAstToDoc(ast, options);
const doc = printAstToDoc(ast, options);
return printDocToString(doc, options);
},
+8 -4
View File
@@ -1,7 +1,7 @@
import { stripTrailingHardline } from "../document/utils.js";
import { normalize } from "./options.js";
import { ensureAllCommentsPrinted, attach } from "./comments.js";
import { parse } from "./parser.js";
import { parseSync } from "./parser.js";
function printSubtree(path, print, options, printAstToDoc) {
if (options.printer.embed && options.embeddedLanguageFormatting === "auto") {
@@ -21,7 +21,7 @@ function printSubtree(path, print, options, printAstToDoc) {
}
}
async function textToDoc(
function textToDoc(
text,
partialNextOptions,
parentOptions,
@@ -39,9 +39,13 @@ async function textToDoc(
{ passThrough: true }
);
const result = await parse(text, nextOptions);
const result = parseSync(text, nextOptions);
const { ast } = result;
if (typeof ast?.then === "function") {
throw new TypeError("async parse is not supported in embed");
}
text = result.text;
const astComments = ast.comments;
@@ -52,7 +56,7 @@ async function textToDoc(
// @ts-expect-error -- Casting to `unique symbol` isn't allowed in JSDoc comment
nextOptions[Symbol.for("tokens")] = ast.tokens || [];
const doc = await printAstToDoc(ast, nextOptions);
const doc = printAstToDoc(ast, nextOptions);
ensureAllCommentsPrinted(astComments);
if (shouldStripTrailingHardline) {
+37 -1
View File
@@ -102,4 +102,40 @@ function handleParseError(error, text) {
throw error;
}
export { parse, resolveParser };
// TODO: Remove this when we allow async parser in embed
function parseSync(originalText, opts) {
const parsers = getParsers(opts);
// Create a new object {parserName: parseFn}. Uses defineProperty() to only call
// the parsers getters when actually calling the parser `parse` function.
const parsersForCustomParserApi = Object.defineProperties(
{},
Object.fromEntries(
Object.keys(parsers).map((parserName) => [
parserName,
{
enumerable: true,
get() {
return parsers[parserName].parse;
},
},
])
)
);
const parser = resolveParser(opts, parsers);
const text = parser.preprocess
? parser.preprocess(originalText, opts)
: originalText;
let ast;
try {
ast = parser.parse(text, parsersForCustomParserApi, opts);
} catch (error) {
handleParseError(error, originalText);
}
return { text, ast };
}
export { parse, parseSync, resolveParser };
+2 -6
View File
@@ -1,14 +1,10 @@
import { hardline, markAsRoot } from "../../document/builders.js";
async function print(node, textToDoc) {
function print(node, textToDoc) {
if (node.lang === "yaml") {
const value = node.value.trim();
const doc = value
? await textToDoc(
value,
{ parser: "yaml" },
{ stripTrailingHardline: true }
)
? textToDoc(value, { parser: "yaml" }, { stripTrailingHardline: true })
: "";
return markAsRoot([
node.startDelimiter,
@@ -0,0 +1,40 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`async-parser.txt format 1`] = `
====================================options=====================================
parsers: ["async-parser"]
printWidth: 80
| printWidth
=====================================input======================================
A text will format as "Formatted by async-parser plugin".
=====================================output=====================================
Formatted by async-parser plugin
================================================================================
`;
exports[`with-aync-parser-code-block.md format 1`] = `
====================================options=====================================
parsers: ["markdown"]
printWidth: 80
| printWidth
=====================================input======================================
\`\`\`async-parser
Since we don't allow async parser in embed format, so this will not be changed.
\`\`\`
\`\`\`uppercase-rocks
This text should be uppercased.
\`\`\`
=====================================output=====================================
\`\`\`async-parser
Since we don't allow async parser in embed format, so this will not be changed.
\`\`\`
\`\`\`uppercase-rocks
THIS TEXT SHOULD BE UPPERCASED.
\`\`\`
================================================================================
`;
@@ -0,0 +1,10 @@
import createEsmUtils from "esm-utils";
const { require } = createEsmUtils(import.meta);
const plugins = [
require("../../../../config/prettier-plugins/prettier-plugin-async-parser/index.cjs"),
require("../../../../config/prettier-plugins/prettier-plugin-uppercase-rocks/index.cjs"),
];
run_spec(import.meta, ["markdown"], { plugins });
@@ -0,0 +1,7 @@
```async-parser
Since we don't allow async parser in embed format, so this will not be changed.
```
```uppercase-rocks
This text should be uppercased.
```
@@ -16,12 +16,8 @@ module.exports = {
},
printers: {
foo: {
async print(path) {
const { default: prettier } = await import(
"../../../../../../config/prettier-entry.js"
);
const { concat } = prettier.doc.builders;
return concat(["foo+", path.getValue().text]);
print(path) {
return ["foo+", path.getValue().text];
},
},
},
@@ -16,12 +16,8 @@ module.exports = {
},
printers: {
foobar: {
async print(path) {
const { default: prettier } = await import(
"../../../../../../config/prettier-entry.js"
);
const { concat } = prettier.doc.builders;
return concat(["foobar+", path.getValue().text]);
print(path) {
return ["foobar+", path.getValue().text];
},
},
},
@@ -15,12 +15,8 @@ module.exports = {
},
printers: {
bar: {
async print(path) {
const { default: prettier } = await import(
"../../../../../config/prettier-entry.js"
);
const { concat } = prettier.doc.builders;
return concat(["content from `prettier-plugin-bar` package + ", path.getValue().text]);
print(path) {
return ["content from `prettier-plugin-bar` package + ", path.getValue().text];
},
},
},
@@ -15,16 +15,11 @@ module.exports = {
},
printers: {
bar: {
async print(path) {
const { default: prettier } = await import(
"../../../config/prettier-entry.js"
);
const { concat } = prettier.doc.builders;
return concat([
print(path) {
return [
"content from `prettier-plugin-bar.js` file + ",
path.getValue().text,
]);
];
},
},
},
@@ -15,12 +15,8 @@ module.exports = {
},
printers: {
bespoke: {
async print(path) {
const { default: prettier } = await import(
"../../../../../../config/prettier-entry.js"
);
const { concat } = prettier.doc.builders;
return concat(["bespoke+", path.getValue().text]);
print(path) {
return ["bespoke+", path.getValue().text];
},
},
},
@@ -16,12 +16,8 @@ module.exports = {
},
printers: {
"foo-ast": {
async print(path) {
const { default: prettier } = await import(
"../../../config/prettier-entry.js"
);
const { concat } = prettier.doc.builders;
return concat(["!", path.getValue().text]);
print(path) {
return ["!", path.getValue().text];
},
},
},
@@ -16,12 +16,9 @@ module.exports = {
},
printers: {
"foo-ast": {
async print(path) {
const { default: prettier } = await import(
"../../../config/prettier-entry.js"
);
const { lineSuffix } = prettier.doc.builders;
return lineSuffix(path.getValue().text.trim());
print(path) {
// TODO[@fisker]: Use `lineSuffix` after we support ESM plugin
return { type: "line-suffix", contents: path.getValue().text.trim() };
},
},
},