Files
test-repo/src/language-js/print/misc.js
T
fisker 0e0f879c1a Merge branch 'main' into next
# Conflicts:
#	docs/browser.md
#	package.json
#	scripts/release/yarn.lock
#	scripts/vendors/vendor-meta.json
#	scripts/vendors/vendors.mjs
#	src/cli/expand-patterns.js
#	src/cli/format.js
#	src/cli/utils.js
#	src/language-js/index.js
#	src/language-js/parse/postprocess/index.js
#	src/language-js/parse/postprocess/typescript.js
#	tests/format/misc/errors/invalid/jsfmt.spec.js
#	tests/integration/__tests__/__snapshots__/support-info.js.snap
#	website/playground/sidebar/SidebarOptions.js
#	yarn.lock
2022-06-19 11:12:22 +08:00

102 lines
2.4 KiB
JavaScript

import { isNonEmptyArray } from "../../common/util.js";
import { indent, join, line } from "../../document/builders.js";
import { isFlowAnnotationComment } from "../utils/index.js";
function printOptionalToken(path) {
const node = path.getValue();
if (
!node.optional ||
// It's an optional computed method parsed by typescript-estree.
// "?" is printed in `printMethod`.
(node.type === "Identifier" && node === path.getParentNode().key)
) {
return "";
}
if (
node.type === "OptionalCallExpression" ||
(node.type === "OptionalMemberExpression" && node.computed)
) {
return "?.";
}
return "?";
}
function printDefiniteToken(path) {
return path.getValue().definite ||
path.match(
undefined,
(node, name) =>
name === "id" && node.type === "VariableDeclarator" && node.definite
)
? "!"
: "";
}
function printFunctionTypeParameters(path, options, print) {
const fun = path.getValue();
if (fun.typeArguments) {
return print("typeArguments");
}
if (fun.typeParameters) {
return print("typeParameters");
}
return "";
}
function printTypeAnnotation(path, options, print) {
const node = path.getValue();
if (!node.typeAnnotation) {
return "";
}
const parentNode = path.getParentNode();
const isFunctionDeclarationIdentifier =
parentNode.type === "DeclareFunction" && parentNode.id === node;
if (isFlowAnnotationComment(options.originalText, node.typeAnnotation)) {
return [" /*: ", print("typeAnnotation"), " */"];
}
return [isFunctionDeclarationIdentifier ? "" : ": ", print("typeAnnotation")];
}
function printBindExpressionCallee(path, options, print) {
return ["::", print("callee")];
}
function printTypeScriptModifiers(path, options, print) {
const node = path.getValue();
if (!isNonEmptyArray(node.modifiers)) {
return "";
}
return [join(" ", path.map(print, "modifiers")), " "];
}
function adjustClause(node, clause, forceSpace) {
if (node.type === "EmptyStatement") {
return ";";
}
if (node.type === "BlockStatement" || forceSpace) {
return [" ", clause];
}
return indent([line, clause]);
}
function printRestSpread(path, options, print) {
return ["...", print("argument"), printTypeAnnotation(path, options, print)];
}
export {
printOptionalToken,
printDefiniteToken,
printFunctionTypeParameters,
printBindExpressionCallee,
printTypeScriptModifiers,
printTypeAnnotation,
printRestSpread,
adjustClause,
};