diff --git a/commands.md b/commands.md index f42ab0831..8cbfd1c7c 100644 --- a/commands.md +++ b/commands.md @@ -1,4 +1,4 @@ -The core of the algorithm is implemented in `src/document/{printer,builders,utils}.js`. The printer uses the basic formatting abstractions provided to construct a format when printing a node. +The core of the algorithm is implemented in `src/document/{printer,builders,utilities}/`. The printer uses the basic formatting abstractions provided to construct a format when printing a node. ## Prettier's intermediate representation: `Doc` diff --git a/eslint.config.js b/eslint.config.js index 4cadfb36e..b32e79a90 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -435,7 +435,7 @@ const configs = [ "prettier-internal-rules/no-node-comments": [ "error", { - file: "src/language-js/utils/index.js", + file: "src/language-js/utilities/index.js", functions: ["hasComment", "getComments"], }, "src/language-js/pragma.js", @@ -445,7 +445,7 @@ const configs = [ "src/language-js/parse/json.js", "src/language-js/parse/acorn.js", "src/language-js/parse/oxc.js", - "src/language-js/parse/utils/wrap-babel-expression.js", + "src/language-js/parse/utilities/wrap-babel-expression.js", ], "prettier-internal-rules/prefer-create-type-check-function": [ "error", diff --git a/jest.config.js b/jest.config.js index 439d658a1..b0b1c5b23 100644 --- a/jest.config.js +++ b/jest.config.js @@ -51,7 +51,7 @@ if (nodejsMajorVersion <= 14) { testPathIgnorePatterns.push( "/tests/integration/__tests__/plugin-parsers.js", "/tests/integration/__tests__/normalize-doc.js", - "/tests/integration/__tests__/doc-utils-clean-doc.js", + "/tests/integration/__tests__/doc-utilities-clean-doc.js", "/tests/integration/__tests__/config-invalid.js", // `@prettier/cli` uses `node:stream/consumers`, not available on Node.js v14 "/tests/integration/__tests__/experimental-cli.js", diff --git a/package.json b/package.json index 8264380a3..871b30c10 100644 --- a/package.json +++ b/package.json @@ -229,7 +229,7 @@ "src/index.cjs", "src/document/debug.js", "src/universal/*.browser.js", - "src/utils/unexpected-node-error.js", + "src/utilities/unexpected-node-error.js", "src/language-js/types/estree.d.ts", "src/**/**/*.d.ts" ] diff --git a/scripts/benchmark/bench.js b/scripts/benchmark/bench.js index 59bc10cbe..d6869417e 100644 --- a/scripts/benchmark/bench.js +++ b/scripts/benchmark/bench.js @@ -7,7 +7,8 @@ const groupSize = Number(groupSizeString); const { format } = await import(`./${version}/dist/index.mjs`); const sourceText = readFileSync( - process.env.PRETTIER_PERF_FILENAME || "../../src/language-js/utils/index.js", + process.env.PRETTIER_PERF_FILENAME || + "../../src/language-js/utilities/index.js", "utf8", ); diff --git a/scripts/build-website.js b/scripts/build-website.js index 7f3a90b67..226f6b55a 100644 --- a/scripts/build-website.js +++ b/scripts/build-website.js @@ -14,7 +14,7 @@ import { WEBSITE_DIR, writeFile, writeJson, -} from "./utils/index.js"; +} from "./utilities/index.js"; const runYarn = (command, args, options) => spawn("yarn", [command, ...args], { stdio: "inherit", ...options }); diff --git a/scripts/build/build-dependencies-license.js b/scripts/build/build-dependencies-license.js index d75d8e589..c9d1b4b80 100644 --- a/scripts/build/build-dependencies-license.js +++ b/scripts/build/build-dependencies-license.js @@ -2,7 +2,7 @@ import fs from "node:fs/promises"; import path from "node:path"; import { outdent } from "outdent"; import rollupPluginLicense from "rollup-plugin-license"; -import { PROJECT_ROOT } from "../utils/index.js"; +import { PROJECT_ROOT } from "../utilities/index.js"; const separator = `\n${"-".repeat(40)}\n\n`; diff --git a/scripts/build/build-javascript-module.js b/scripts/build/build-javascript-module.js index fe78ab6a7..f259cdbc9 100644 --- a/scripts/build/build-javascript-module.js +++ b/scripts/build/build-javascript-module.js @@ -6,7 +6,7 @@ import createEsmUtils from "esm-utils"; import { PRODUCTION_MINIMAL_NODE_JS_VERSION, PROJECT_ROOT, -} from "../utils/index.js"; +} from "../utilities/index.js"; import esbuildPluginAddDefaultExport from "./esbuild-plugins/add-default-export.js"; import esbuildPluginEvaluate from "./esbuild-plugins/evaluate.js"; import esbuildPluginPrimitiveDefine from "./esbuild-plugins/primitive-define.js"; @@ -17,7 +17,7 @@ import esbuildPluginThrowWarnings from "./esbuild-plugins/throw-warnings.js"; import esbuildPluginUmd from "./esbuild-plugins/umd.js"; import esbuildPluginVisualizer from "./esbuild-plugins/visualizer.js"; import transform from "./transform/index.js"; -import { getPackageFile } from "./utils.js"; +import { getPackageFile } from "./utilities.js"; const { readJsonSync, diff --git a/scripts/build/build-package-json.js b/scripts/build/build-package-json.js index e9f7f7fe6..3283b2580 100644 --- a/scripts/build/build-package-json.js +++ b/scripts/build/build-package-json.js @@ -4,7 +4,7 @@ import { PROJECT_ROOT, readJson, writeJson, -} from "../utils/index.js"; +} from "../utilities/index.js"; const keysToKeep = [ "name", diff --git a/scripts/build/build-types.js b/scripts/build/build-types.js index 358b25469..86f1c9ef0 100644 --- a/scripts/build/build-types.js +++ b/scripts/build/build-types.js @@ -3,7 +3,7 @@ import path from "node:path"; import url from "node:url"; import { isValidIdentifier } from "@babel/types"; import { outdent } from "outdent"; -import { PROJECT_ROOT, writeFile } from "../utils/index.js"; +import { PROJECT_ROOT, writeFile } from "../utilities/index.js"; async function typesFileBuilder({ packageConfig, file }) { /** diff --git a/scripts/build/build.js b/scripts/build/build.js index bbf30a308..584f9623e 100644 --- a/scripts/build/build.js +++ b/scripts/build/build.js @@ -7,7 +7,7 @@ import createEsmUtils from "esm-utils"; import styleText from "node-style-text"; import prettyBytes from "pretty-bytes"; import prettyMilliseconds from "pretty-ms"; -import { DIST_DIR } from "../utils/index.js"; +import { DIST_DIR } from "../utilities/index.js"; import packageConfigs from "./config.js"; import parseArguments from "./parse-arguments.js"; diff --git a/scripts/build/config.js b/scripts/build/config.js index 79b88b961..28aa80abf 100644 --- a/scripts/build/config.js +++ b/scripts/build/config.js @@ -3,7 +3,7 @@ import path from "node:path"; import url from "node:url"; import createEsmUtils from "esm-utils"; import { outdent } from "outdent"; -import { copyFile, DIST_DIR, PROJECT_ROOT } from "../utils/index.js"; +import { copyFile, DIST_DIR, PROJECT_ROOT } from "../utilities/index.js"; import buildDependenciesLicense from "./build-dependencies-license.js"; import buildJavascriptModule from "./build-javascript-module.js"; import buildOxcWasmParser from "./build-oxc-wasm-parser.js"; @@ -15,7 +15,7 @@ import { import buildTypes from "./build-types.js"; import esmifyTypescriptEslint from "./esmify-typescript-eslint.js"; import modifyTypescriptModule from "./modify-typescript-module.js"; -import { getPackageFile } from "./utils.js"; +import { getPackageFile } from "./utilities.js"; const { require, diff --git a/scripts/build/esmify-typescript-eslint.js b/scripts/build/esmify-typescript-eslint.js index 694b4e862..f2e5ff92d 100644 --- a/scripts/build/esmify-typescript-eslint.js +++ b/scripts/build/esmify-typescript-eslint.js @@ -2,7 +2,7 @@ import * as path from "node:path"; import { outdent } from "outdent"; -import { PROJECT_ROOT, writeFile } from "../utils/index.js"; +import { PROJECT_ROOT, writeFile } from "../utilities/index.js"; function esmifyTypescriptEslint(text) { /* diff --git a/scripts/build/modify-typescript-module.js b/scripts/build/modify-typescript-module.js index 7a93bd891..1aa8d77df 100644 --- a/scripts/build/modify-typescript-module.js +++ b/scripts/build/modify-typescript-module.js @@ -2,7 +2,7 @@ import path from "node:path"; import escapeStringRegexp from "escape-string-regexp"; import MagicString from "magic-string"; import { outdent } from "outdent"; -import { PROJECT_ROOT, writeFile } from "../utils/index.js"; +import { PROJECT_ROOT, writeFile } from "../utilities/index.js"; import UNUSED_SPECIFIERS from "./typescript-unused-specifiers.js"; function* getModules(text) { diff --git a/scripts/build/parse-arguments.js b/scripts/build/parse-arguments.js index 25c0743c7..fb0b6a99d 100644 --- a/scripts/build/parse-arguments.js +++ b/scripts/build/parse-arguments.js @@ -1,6 +1,6 @@ import path from "node:path"; import { parseArgs } from "node:util"; -import { DIST_DIR } from "../utils/index.js"; +import { DIST_DIR } from "../utilities/index.js"; const isUnique = (array) => new Set(array).size === array.length; diff --git a/scripts/build/transform/index.js b/scripts/build/transform/index.js index 07e82694c..84a38c86d 100644 --- a/scripts/build/transform/index.js +++ b/scripts/build/transform/index.js @@ -3,7 +3,7 @@ import generate from "@babel/generator"; import { parse } from "@babel/parser"; import { traverseFast as traverse } from "@babel/types"; import { outdent } from "outdent"; -import { PROJECT_ROOT, SOURCE_DIR } from "../../utils/index.js"; +import { PROJECT_ROOT, SOURCE_DIR } from "../../utilities/index.js"; import * as transforms from "./transforms/index.js"; const packageTransforms = new Map([ diff --git a/scripts/build/transform/transforms/get-public-doc-functionality.js b/scripts/build/transform/transforms/get-public-doc-functionality.js index 796416156..9f69faf84 100644 --- a/scripts/build/transform/transforms/get-public-doc-functionality.js +++ b/scripts/build/transform/transforms/get-public-doc-functionality.js @@ -1,7 +1,7 @@ import path from "node:path"; import { pathToFileURL } from "node:url"; import makeSynchronized from "make-synchronized"; -import { SOURCE_DIR } from "../../../utils/index.js"; +import { SOURCE_DIR } from "../../../utilities/index.js"; const PUBLIC_MODULE_URL = pathToFileURL( path.join(SOURCE_DIR, "document/public.js"), diff --git a/scripts/build/transform/transforms/transform-doc-module-imports.js b/scripts/build/transform/transforms/transform-doc-module-imports.js index ebf0ee34a..6d635637a 100644 --- a/scripts/build/transform/transforms/transform-doc-module-imports.js +++ b/scripts/build/transform/transforms/transform-doc-module-imports.js @@ -1,5 +1,5 @@ import path from "node:path"; -import { SOURCE_DIR } from "../../../utils/index.js"; +import { SOURCE_DIR } from "../../../utilities/index.js"; import getPublicDocFunctionality from "./get-public-doc-functionality.js"; import { createIdentifier, diff --git a/scripts/build/utils.js b/scripts/build/utilities.js similarity index 96% rename from scripts/build/utils.js rename to scripts/build/utilities.js index a766f7193..71c1d0d5c 100644 --- a/scripts/build/utils.js +++ b/scripts/build/utilities.js @@ -3,7 +3,7 @@ import path from "node:path"; import url from "node:url"; import { resolve } from "import-meta-resolve"; import { isUrl, toUrl } from "url-or-path"; -import { PROJECT_ROOT } from "../utils/index.js"; +import { PROJECT_ROOT } from "../utilities/index.js"; const NODE_MODULES_PATH = path.join(PROJECT_ROOT, "node_modules"); diff --git a/scripts/bundle-eslint-config.js b/scripts/bundle-eslint-config.js index 1a056c243..972005bb6 100644 --- a/scripts/bundle-eslint-config.js +++ b/scripts/bundle-eslint-config.js @@ -3,7 +3,7 @@ import fs from "node:fs/promises"; import path from "node:path"; import eslintPluginCompat from "eslint-plugin-compat"; import buildConfig from "./build/config.js"; -import { DIST_DIR } from "./utils/index.js"; +import { DIST_DIR } from "./utilities/index.js"; const { browserslist: targets } = JSON.parse( await fs.readFile(new URL("../package.json", import.meta.url)), diff --git a/scripts/changelog-for-patch.js b/scripts/changelog-for-patch.js index bccd25666..764a40e70 100644 --- a/scripts/changelog-for-patch.js +++ b/scripts/changelog-for-patch.js @@ -10,7 +10,7 @@ import { getEntries, printEntries, replaceVersions, -} from "./utils/changelog.js"; +} from "./utilities/changelog.js"; const { previousVersion, newVersion } = parseArguments(); diff --git a/scripts/draft-blog-post.js b/scripts/draft-blog-post.js index e20cc778e..305924c3e 100644 --- a/scripts/draft-blog-post.js +++ b/scripts/draft-blog-post.js @@ -12,7 +12,7 @@ import { getEntries, printEntries, replaceVersions, -} from "./utils/changelog.js"; +} from "./utilities/changelog.js"; const { __dirname, require } = createEsmUtils(import.meta); const blogDir = path.join(__dirname, "../website/blog"); diff --git a/scripts/format-test-lint.js b/scripts/format-test-lint.js index aed9b1831..9cf5f7e0e 100644 --- a/scripts/format-test-lint.js +++ b/scripts/format-test-lint.js @@ -4,7 +4,7 @@ import fs from "node:fs/promises"; import path from "node:path"; -import { PROJECT_ROOT } from "./utils/index.js"; +import { PROJECT_ROOT } from "./utilities/index.js"; const FORMAT_TEST_DIRECTORY = path.join(PROJECT_ROOT, "tests/format/"); const TEST_SCRIPT_FILE_NAME = "format.test.js"; diff --git a/scripts/generate-changelog.js b/scripts/generate-changelog.js index 32d9b472d..92c776919 100755 --- a/scripts/generate-changelog.js +++ b/scripts/generate-changelog.js @@ -12,7 +12,7 @@ import fs from "node:fs/promises"; import enquirer from "enquirer"; import openEditor from "open-editor"; -import { CHANGELOG_CATEGORIES } from "./utils/changelog-categories.js"; +import { CHANGELOG_CATEGORIES } from "./utilities/changelog-categories.js"; const prNumberPrompt = new enquirer.NumberPrompt({ message: "Input your Pull Request number:", diff --git a/scripts/generate-schema.js b/scripts/generate-schema.js index fac2f42b7..389554dba 100644 --- a/scripts/generate-schema.js +++ b/scripts/generate-schema.js @@ -1,5 +1,5 @@ #!/usr/bin/env node -import { generateSchema } from "./utils/generate-schema.js"; +import { generateSchema } from "./utilities/generate-schema.js"; console.log(await generateSchema()); diff --git a/scripts/lint-changelog.js b/scripts/lint-changelog.js index ea751a6e0..26ceec1c6 100644 --- a/scripts/lint-changelog.js +++ b/scripts/lint-changelog.js @@ -6,7 +6,7 @@ import indexToPosition from "index-to-position"; import { outdent } from "outdent"; import remarkParse from "remark-parse"; import unified from "unified"; -import { CHANGELOG_CATEGORIES } from "./utils/changelog-categories.js"; +import { CHANGELOG_CATEGORIES } from "./utilities/changelog-categories.js"; const CHANGELOG_DIR = "changelog_unreleased"; const TEMPLATE_FILE = "TEMPLATE.md"; diff --git a/scripts/release/get-formatted-date.js b/scripts/release/get-formatted-date.js index 0d7c40c8a..e4b71ef4d 100644 --- a/scripts/release/get-formatted-date.js +++ b/scripts/release/get-formatted-date.js @@ -1,4 +1,4 @@ -// TODO: Implement this in `utils.js` when jest.importActual is landed. +// TODO: Implement this in `utilities.js` when jest.importActual is landed. export default function getFormattedDate() { const date = new Date(); const isoStr = date.toISOString(); diff --git a/scripts/release/run.js b/scripts/release/run.js index 97bba9c51..29fb43156 100644 --- a/scripts/release/run.js +++ b/scripts/release/run.js @@ -1,7 +1,7 @@ import semver from "semver"; import parseArguments from "./parse-arguments.js"; import * as steps from "./steps/index.js"; -import { logPromise, readJson } from "./utils.js"; +import { logPromise, readJson } from "./utilities.js"; const params = parseArguments(); const { diff --git a/scripts/release/steps/bump-prettier.js b/scripts/release/steps/bump-prettier.js index c77c89082..f21592c5f 100644 --- a/scripts/release/steps/bump-prettier.js +++ b/scripts/release/steps/bump-prettier.js @@ -1,6 +1,12 @@ import fs from "node:fs"; import semver from "semver"; -import { logPromise, readJson, runGit, runYarn, writeJson } from "../utils.js"; +import { + logPromise, + readJson, + runGit, + runYarn, + writeJson, +} from "../utilities.js"; async function format() { await runYarn(["fix:prettier"]); diff --git a/scripts/release/steps/check-git-status.js b/scripts/release/steps/check-git-status.js index f30abd8c3..835dcc1d0 100644 --- a/scripts/release/steps/check-git-status.js +++ b/scripts/release/steps/check-git-status.js @@ -1,4 +1,4 @@ -import { runGit } from "../utils.js"; +import { runGit } from "../utilities.js"; export default async function checkGitStatus({ next }) { const { stdout: status } = await runGit(["status", "--porcelain"]); diff --git a/scripts/release/steps/clean-changelog.js b/scripts/release/steps/clean-changelog.js index 24482ace1..48f8b4cad 100644 --- a/scripts/release/steps/clean-changelog.js +++ b/scripts/release/steps/clean-changelog.js @@ -1,7 +1,7 @@ import fs from "node:fs/promises"; import { fileURLToPath } from "node:url"; import fastGlob from "fast-glob"; -import { runGit } from "../utils.js"; +import { runGit } from "../utilities.js"; export default async function cleanChangelog({ repo }) { const changelogUnreleasedDir = fileURLToPath( diff --git a/scripts/release/steps/generate-bundles.js b/scripts/release/steps/generate-bundles.js index 5a536be3e..7f61b1bd7 100644 --- a/scripts/release/steps/generate-bundles.js +++ b/scripts/release/steps/generate-bundles.js @@ -1,5 +1,5 @@ import styleText from "node-style-text"; -import { logPromise, readJson, runYarn } from "../utils.js"; +import { logPromise, readJson, runYarn } from "../utilities.js"; export default async function generateBundles({ dry, version, manual }) { if (!manual) { diff --git a/scripts/release/steps/install-dependencies.js b/scripts/release/steps/install-dependencies.js index 3e108d82a..67a5a62d9 100644 --- a/scripts/release/steps/install-dependencies.js +++ b/scripts/release/steps/install-dependencies.js @@ -1,5 +1,5 @@ import fs from "node:fs/promises"; -import { runGit, runYarn } from "../utils.js"; +import { runGit, runYarn } from "../utilities.js"; const PROJECT_ROOT = new URL("../../../", import.meta.url); diff --git a/scripts/release/steps/lint-files.js b/scripts/release/steps/lint-files.js index 8442d66f2..011649829 100644 --- a/scripts/release/steps/lint-files.js +++ b/scripts/release/steps/lint-files.js @@ -1,4 +1,4 @@ -import { runYarn } from "../utils.js"; +import { runYarn } from "../utilities.js"; const lintFiles = () => runYarn("lint"); diff --git a/scripts/release/steps/merge-blog-post.js b/scripts/release/steps/merge-blog-post.js index 0b3546d41..e1cfa7e99 100644 --- a/scripts/release/steps/merge-blog-post.js +++ b/scripts/release/steps/merge-blog-post.js @@ -1,6 +1,6 @@ import styleText from "node-style-text"; import semver from "semver"; -import { runGit, waitForEnter } from "../utils.js"; +import { runGit, waitForEnter } from "../utilities.js"; export default async function mergeBlogPost({ dry, diff --git a/scripts/release/steps/post-publish-steps.js b/scripts/release/steps/post-publish-steps.js index dfba9401d..8e07f39ff 100644 --- a/scripts/release/steps/post-publish-steps.js +++ b/scripts/release/steps/post-publish-steps.js @@ -1,6 +1,6 @@ import styleText from "node-style-text"; import outdent from "outdent"; -import { fetchText, logPromise, writeFile } from "../utils.js"; +import { fetchText, logPromise, writeFile } from "../utilities.js"; const SCHEMA_REPO = "SchemaStore/schemastore"; const SCHEMA_PATH = "src/schemas/json/prettierrc.json"; @@ -10,7 +10,7 @@ const EDIT_URL = `https://github.com/${SCHEMA_REPO}/edit/master/${SCHEMA_PATH}`; // Any optional or manual step can be warned in this script. async function checkSchema() { - const { generateSchema } = await import("../../utils/generate-schema.js"); + const { generateSchema } = await import("../../utilities/generate-schema.js"); const schema = await generateSchema(); const remoteSchema = await logPromise( "Checking current schema in SchemaStore", diff --git a/scripts/release/steps/publish-to-npm.js b/scripts/release/steps/publish-to-npm.js index ec6c4ca23..7f79956ad 100644 --- a/scripts/release/steps/publish-to-npm.js +++ b/scripts/release/steps/publish-to-npm.js @@ -1,6 +1,6 @@ import enquirer from "enquirer"; import spawn from "nano-spawn"; -import { waitForEnter } from "../utils.js"; +import { waitForEnter } from "../utilities.js"; export default async function publishToNpm({ dry }) { console.log(`Ready to publish to NPM${dry ? "(--dry-run)" : ""}`); diff --git a/scripts/release/steps/push-to-git.js b/scripts/release/steps/push-to-git.js index 7304c56ac..381dc21a0 100644 --- a/scripts/release/steps/push-to-git.js +++ b/scripts/release/steps/push-to-git.js @@ -1,4 +1,4 @@ -import { runGit } from "../utils.js"; +import { runGit } from "../utilities.js"; export default async function pushToGit({ version, repo }) { await runGit(["commit", "-am", `Release ${version}`]); diff --git a/scripts/release/steps/show-instructions-after-npm-publish.js b/scripts/release/steps/show-instructions-after-npm-publish.js index ba23e6440..d5663095f 100644 --- a/scripts/release/steps/show-instructions-after-npm-publish.js +++ b/scripts/release/steps/show-instructions-after-npm-publish.js @@ -5,7 +5,7 @@ import { getBlogPostInfo, getChangelogContent, waitForEnter, -} from "../utils.js"; +} from "../utilities.js"; const RELEASE_URL_BASE = "https://github.com/prettier/prettier/releases/new?"; export function getReleaseUrl(version, previousVersion) { diff --git a/scripts/release/steps/update-changelog.js b/scripts/release/steps/update-changelog.js index 2c391755d..cbcf9407c 100644 --- a/scripts/release/steps/update-changelog.js +++ b/scripts/release/steps/update-changelog.js @@ -8,7 +8,7 @@ import { logPromise, runYarn, waitForEnter, -} from "../utils.js"; +} from "../utilities.js"; function writeChangelog(params) { const changelog = fs.readFileSync("CHANGELOG.md", "utf8"); diff --git a/scripts/release/steps/update-dependents-count.js b/scripts/release/steps/update-dependents-count.js index d2b054fe9..07dcd083f 100644 --- a/scripts/release/steps/update-dependents-count.js +++ b/scripts/release/steps/update-dependents-count.js @@ -1,5 +1,5 @@ import styleText from "node-style-text"; -import { fetchText, logPromise, processFile, runGit } from "../utils.js"; +import { fetchText, logPromise, processFile, runGit } from "../utilities.js"; async function getNpmDependentsCount() { const npmPage = await logPromise( diff --git a/scripts/release/steps/update-version.js b/scripts/release/steps/update-version.js index 210631e11..28c69a739 100644 --- a/scripts/release/steps/update-version.js +++ b/scripts/release/steps/update-version.js @@ -1,4 +1,4 @@ -import { processFile, readJson, runYarn, writeJson } from "../utils.js"; +import { processFile, readJson, runYarn, writeJson } from "../utilities.js"; export default async function updateVersion({ version, next }) { const pkg = await readJson("package.json"); diff --git a/scripts/release/steps/wait-for-bot-release.js b/scripts/release/steps/wait-for-bot-release.js index fc3390ccf..8919e8cfe 100644 --- a/scripts/release/steps/wait-for-bot-release.js +++ b/scripts/release/steps/wait-for-bot-release.js @@ -1,6 +1,6 @@ import styleText from "node-style-text"; import outdent from "outdent"; -import { logPromise, waitForEnter } from "../utils.js"; +import { logPromise, waitForEnter } from "../utilities.js"; export async function isVersionReleased(version) { const response = await fetch("https://registry.npmjs.org/prettier/"); diff --git a/scripts/release/utils.js b/scripts/release/utilities.js similarity index 100% rename from scripts/release/utils.js rename to scripts/release/utilities.js diff --git a/scripts/utils/changelog-categories.js b/scripts/utilities/changelog-categories.js similarity index 100% rename from scripts/utils/changelog-categories.js rename to scripts/utilities/changelog-categories.js diff --git a/scripts/utils/changelog.js b/scripts/utilities/changelog.js similarity index 100% rename from scripts/utils/changelog.js rename to scripts/utilities/changelog.js diff --git a/scripts/utils/generate-schema.js b/scripts/utilities/generate-schema.js similarity index 100% rename from scripts/utils/generate-schema.js rename to scripts/utilities/generate-schema.js diff --git a/scripts/utils/index.js b/scripts/utilities/index.js similarity index 100% rename from scripts/utils/index.js rename to scripts/utilities/index.js diff --git a/src/cli/expand-patterns.js b/src/cli/expand-patterns.js index 6e75e585e..761633e43 100644 --- a/src/cli/expand-patterns.js +++ b/src/cli/expand-patterns.js @@ -4,7 +4,7 @@ import { directoryIgnorerWithoutNodeModules, } from "./directory-ignorer.js"; import { fastGlob } from "./prettier-internal.js"; -import { lstatSafe, normalizeToPosix } from "./utils.js"; +import { lstatSafe, normalizeToPosix } from "./utilities.js"; /** @import {Context} from './context.js' */ diff --git a/src/cli/file-info.js b/src/cli/file-info.js index 1b21bdfbc..ead85ffe5 100644 --- a/src/cli/file-info.js +++ b/src/cli/file-info.js @@ -1,7 +1,7 @@ import path from "node:path"; import stringify from "fast-json-stable-stringify"; import { format, getFileInfo } from "../index.js"; -import { printToScreen } from "./utils.js"; +import { printToScreen } from "./utilities.js"; // Note: This does not work with `--config-precedence` async function logFileInfoOrDie(context) { diff --git a/src/cli/find-cache-file.js b/src/cli/find-cache-file.js index 7de9eee46..8d94ed78a 100644 --- a/src/cli/find-cache-file.js +++ b/src/cli/find-cache-file.js @@ -2,7 +2,7 @@ import fs from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import findCacheDirectory from "find-cache-directory"; -import { isJson, statSafe } from "./utils.js"; +import { isJson, statSafe } from "./utilities.js"; /** * Find default cache file (`./node_modules/.cache/prettier/.prettier-cache`) using https://github.com/sindresorhus/find-cache-directory diff --git a/src/cli/find-config-path.js b/src/cli/find-config-path.js index bc752efbb..2337eae96 100644 --- a/src/cli/find-config-path.js +++ b/src/cli/find-config-path.js @@ -1,6 +1,6 @@ import path from "node:path"; import { resolveConfigFile } from "../index.js"; -import { normalizeToPosix, printToScreen } from "./utils.js"; +import { normalizeToPosix, printToScreen } from "./utilities.js"; async function logResolvedConfigPathOrDie(context) { const file = context.argv.findConfigPath; diff --git a/src/cli/format-results-cache.js b/src/cli/format-results-cache.js index 6fddcb20a..1dec77ce0 100644 --- a/src/cli/format-results-cache.js +++ b/src/cli/format-results-cache.js @@ -5,7 +5,7 @@ import fs from "node:fs"; import stringify from "fast-json-stable-stringify"; import fileEntryCache from "file-entry-cache"; import { version as prettierVersion } from "../index.js"; -import { createHash } from "./utils.js"; +import { createHash } from "./utilities.js"; const optionsHashCache = new WeakMap(); const nodeVersion = process.version; diff --git a/src/cli/format.js b/src/cli/format.js index c0a50e3fb..0c41e1aea 100644 --- a/src/cli/format.js +++ b/src/cli/format.js @@ -13,7 +13,7 @@ import { errors, picocolors, } from "./prettier-internal.js"; -import { normalizeToPosix, statSafe } from "./utils.js"; +import { normalizeToPosix, statSafe } from "./utilities.js"; function diff(a, b) { return createTwoFilesPatch("", "", a, b, "", "", { context: 2 }); diff --git a/src/cli/index.js b/src/cli/index.js index 0b97d62ca..7d9959e70 100644 --- a/src/cli/index.js +++ b/src/cli/index.js @@ -8,7 +8,7 @@ import mockable from "./mockable.js"; import { parseArgvWithoutPlugins } from "./options/parse-cli-arguments.js"; import printSupportInfo from "./print-support-info.js"; import { createDetailedUsage, createUsage } from "./usage.js"; -import { printToScreen } from "./utils.js"; +import { printToScreen } from "./utilities.js"; async function run(rawArguments = process.argv.slice(2)) { // Create a default level logger, so we can log errors during `logLevel` parsing diff --git a/src/cli/mockable.js b/src/cli/mockable.js index 804da58fd..f807ad18b 100644 --- a/src/cli/mockable.js +++ b/src/cli/mockable.js @@ -5,7 +5,7 @@ import { isCI } from "ci-info"; import { __internal as sharedWithCli } from "../index.js"; import clearStreamText from "./utilities/clear-stream-text.js"; -const mockable = sharedWithCli.utils.createMockable({ +const mockable = sharedWithCli.utilities.createMockable({ clearStreamText, getTimestamp: performance.now.bind(performance), isCI: () => isCI, diff --git a/src/cli/options/parse-cli-arguments.js b/src/cli/options/parse-cli-arguments.js index ba6b69eff..7681e9249 100644 --- a/src/cli/options/parse-cli-arguments.js +++ b/src/cli/options/parse-cli-arguments.js @@ -1,5 +1,5 @@ import camelCase from "camelcase"; -import { pick } from "../utils.js"; +import { pick } from "../utilities.js"; import createMinimistOptions from "./create-minimist-options.js"; import { getContextOptionsWithoutPlugins } from "./get-context-options.js"; import minimist from "./minimist.js"; diff --git a/src/cli/print-support-info.js b/src/cli/print-support-info.js index 5dc91d766..fc46bae0b 100644 --- a/src/cli/print-support-info.js +++ b/src/cli/print-support-info.js @@ -1,6 +1,6 @@ import stringify from "fast-json-stable-stringify"; import { format, getSupportInfo } from "../index.js"; -import { omit, printToScreen } from "./utils.js"; +import { omit, printToScreen } from "./utilities.js"; const sortByName = (array) => array.sort((a, b) => a.name.localeCompare(b.name)); diff --git a/src/cli/usage.js b/src/cli/usage.js index f40337c87..3a6c8e15c 100644 --- a/src/cli/usage.js +++ b/src/cli/usage.js @@ -1,7 +1,7 @@ import camelCase from "camelcase"; import { categoryOrder, usageSummary } from "./constants.evaluate.js"; import { formatOptionsHiddenDefaults } from "./prettier-internal.js"; -import { groupBy } from "./utils.js"; +import { groupBy } from "./utilities.js"; const OPTION_USAGE_THRESHOLD = 25; const CHOICE_USAGE_MARGIN = 3; diff --git a/src/cli/utils.js b/src/cli/utilities.js similarity index 97% rename from src/cli/utils.js rename to src/cli/utilities.js index 01de5ed48..16a0d6f52 100644 --- a/src/cli/utils.js +++ b/src/cli/utilities.js @@ -106,7 +106,7 @@ const normalizeToPosix = ? (filepath) => filepath.replaceAll("\\", "/") : (filepath) => filepath; -export const { omit } = sharedWithCli.utils; +export const { omit } = sharedWithCli.utilities; export { createHash, groupBy, diff --git a/src/common/get-file-info.js b/src/common/get-file-info.js index d74228c55..656910f21 100644 --- a/src/common/get-file-info.js +++ b/src/common/get-file-info.js @@ -1,7 +1,7 @@ import { resolveConfig } from "../config/resolve-config.js"; import { loadBuiltinPlugins, loadPlugins } from "../main/plugins/index.js"; -import { isIgnored } from "../utils/ignore.js"; -import inferParser from "../utils/infer-parser.js"; +import { isIgnored } from "../utilities/ignore.js"; +import inferParser from "../utilities/infer-parser.js"; /** * @typedef {{ ignorePath?: string | URL | (string | URL)[], withNodeModules?: boolean, plugins: object, resolveConfig?: boolean }} FileInfoOptions diff --git a/src/common/mockable.js b/src/common/mockable.js index cbf68566c..786c2221b 100644 --- a/src/common/mockable.js +++ b/src/common/mockable.js @@ -1,4 +1,4 @@ -import createMockable from "../utils/create-mockable.js"; +import createMockable from "../utilities/create-mockable.js"; const mockable = createMockable({ getPrettierConfigSearchStopDirectory: () => undefined, diff --git a/src/config/prettier-config/load-external-config.js b/src/config/prettier-config/load-external-config.js index 0f69763b5..fa9a31eba 100644 --- a/src/config/prettier-config/load-external-config.js +++ b/src/config/prettier-config/load-external-config.js @@ -1,5 +1,5 @@ -import importFromFile from "../../utils/import-from-file.js"; -import requireFromFile from "../../utils/require-from-file.js"; +import importFromFile from "../../utilities/import-from-file.js"; +import requireFromFile from "../../utilities/require-from-file.js"; const requireErrorCodesShouldBeIgnored = new Set([ "MODULE_NOT_FOUND", diff --git a/src/config/prettier-config/loaders.js b/src/config/prettier-config/loaders.js index de8482998..5d2862e75 100644 --- a/src/config/prettier-config/loaders.js +++ b/src/config/prettier-config/loaders.js @@ -2,7 +2,7 @@ import { pathToFileURL } from "node:url"; import json5 from "json5"; import parseJson from "parse-json"; import { parse as parseToml } from "smol-toml"; -import readFile from "../../utils/read-file.js"; +import readFile from "../../utilities/read-file.js"; async function readJson(file) { const content = await readFile(file); diff --git a/src/config/resolve-config.js b/src/config/resolve-config.js index 44fb6017c..14e19901f 100644 --- a/src/config/resolve-config.js +++ b/src/config/resolve-config.js @@ -1,7 +1,7 @@ import path from "node:path"; import micromatch from "micromatch"; import { toPath } from "url-or-path"; -import partition from "../utils/partition.js"; +import partition from "../utilities/partition.js"; import { clearEditorconfigCache, loadEditorconfig as loadEditorconfigForFile, diff --git a/src/document/printer/printer.js b/src/document/printer/printer.js index 70fcb9e03..da70b467c 100644 --- a/src/document/printer/printer.js +++ b/src/document/printer/printer.js @@ -1,5 +1,5 @@ import { convertEndOfLineToChars } from "../../common/end-of-line.js"; -import getStringWidth from "../../utils/get-string-width.js"; +import getStringWidth from "../../utilities/get-string-width.js"; import { DOC_TYPE_ALIGN, DOC_TYPE_ARRAY, diff --git a/src/document/utilities/assert-doc.js b/src/document/utilities/assert-doc.js index 743bc3916..2c4f5e9e5 100644 --- a/src/document/utilities/assert-doc.js +++ b/src/document/utilities/assert-doc.js @@ -1,4 +1,4 @@ -import noop from "../../utils/noop.js"; +import noop from "../../utilities/noop.js"; import { DOC_TYPE_IF_BREAK, DOC_TYPE_LINE, diff --git a/src/index.cjs b/src/index.cjs index b8e3befb0..e526bbc90 100644 --- a/src/index.cjs +++ b/src/index.cjs @@ -39,7 +39,7 @@ for (const name of debugApiFunctionNames) { prettier.__debug = debugApis; if (process.env.NODE_ENV === "production") { - prettier.util = require("./utils/public.js"); + prettier.util = require("./utilities/public.js"); prettier.doc = require("./document/public.js"); prettier.version = require("./main/version.evaluate.js").default; } else { @@ -47,7 +47,7 @@ if (process.env.NODE_ENV === "production") { util: { get() { try { - return require("./utils/public.js"); + return require("./utilities/public.js"); } catch { // No op } diff --git a/src/index.d.ts b/src/index.d.ts index a1b53ab58..de4bdc9c6 100644 --- a/src/index.d.ts +++ b/src/index.d.ts @@ -844,7 +844,7 @@ export function getSupportInfo( */ export const version: string; -// https://github.com/prettier/prettier/blob/next/src/utils/public.js +// https://github.com/prettier/prettier/blob/main/src/utilities/public.js export namespace util { interface SkipOptions { backwards?: boolean | undefined; diff --git a/src/index.js b/src/index.js index 8a8a7050b..3dd68e019 100644 --- a/src/index.js +++ b/src/index.js @@ -30,10 +30,10 @@ import { getSupportInfo as getSupportInfoWithoutPlugins, normalizeOptionSettings, } from "./main/support.js"; -import createMockable from "./utils/create-mockable.js"; -import { createIsIgnoredFunction } from "./utils/ignore.js"; -import inferParserWithoutPlugins from "./utils/infer-parser.js"; -import omit from "./utils/object-omit.js"; +import createMockable from "./utilities/create-mockable.js"; +import { createIsIgnoredFunction } from "./utilities/ignore.js"; +import inferParserWithoutPlugins from "./utilities/infer-parser.js"; +import omit from "./utilities/object-omit.js"; /** * @param {*} fn @@ -109,7 +109,7 @@ const sharedWithCli = { createTwoFilesPatch, picocolors, closetLevenshteinMatch, - utils: { + utilities: { omit, createMockable, }, @@ -139,4 +139,4 @@ export { export { default as getFileInfo } from "./common/get-file-info.js"; export * as doc from "./document/public.js"; export { default as version } from "./main/version.evaluate.js"; -export * as util from "./utils/public.js"; +export * as util from "./utilities/public.js"; diff --git a/src/language-css/get-visitor-keys.js b/src/language-css/get-visitor-keys.js index d58d77cf3..558c57e6b 100644 --- a/src/language-css/get-visitor-keys.js +++ b/src/language-css/get-visitor-keys.js @@ -1,4 +1,4 @@ -import createGetVisitorKeys from "../utils/create-get-visitor-keys.js"; +import createGetVisitorKeys from "../utilities/create-get-visitor-keys.js"; import visitorKeys from "./visitor-keys.js"; const getVisitorKeys = createGetVisitorKeys(visitorKeys); diff --git a/src/language-css/languages.evaluate.js b/src/language-css/languages.evaluate.js index 240414dcb..26878ea91 100644 --- a/src/language-css/languages.evaluate.js +++ b/src/language-css/languages.evaluate.js @@ -1,5 +1,5 @@ import * as linguistLanguages from "linguist-languages"; -import createLanguage from "../utils/create-language.js"; +import createLanguage from "../utilities/create-language.js"; const languages = [ createLanguage(linguistLanguages.CSS, (data) => ({ diff --git a/src/language-css/loc.js b/src/language-css/loc.js index 2832f1e39..c781b8caa 100644 --- a/src/language-css/loc.js +++ b/src/language-css/loc.js @@ -1,6 +1,6 @@ -import isNonEmptyArray from "../utils/is-non-empty-array.js"; -import lineColumnToIndex from "../utils/line-column-to-index.js"; -import { skipEverythingButNewLine } from "../utils/skip.js"; +import isNonEmptyArray from "../utilities/is-non-empty-array.js"; +import lineColumnToIndex from "../utilities/line-column-to-index.js"; +import { skipEverythingButNewLine } from "../utilities/skip.js"; function fixValueWordLoc(node, originalIndex) { const { value } = node; diff --git a/src/language-css/parse/parse-media-query.js b/src/language-css/parse/parse-media-query.js index 39fed66a0..ad6c96cc2 100644 --- a/src/language-css/parse/parse-media-query.js +++ b/src/language-css/parse/parse-media-query.js @@ -1,5 +1,5 @@ import postcssMediaQueryParser from "postcss-media-query-parser"; -import { addMissingType, addTypePrefix } from "./utils.js"; +import { addMissingType, addTypePrefix } from "./utilities.js"; const parse = postcssMediaQueryParser.default; diff --git a/src/language-css/parse/parse-selector.js b/src/language-css/parse/parse-selector.js index 241631db4..9816d7447 100644 --- a/src/language-css/parse/parse-selector.js +++ b/src/language-css/parse/parse-selector.js @@ -1,5 +1,5 @@ import PostcssSelectorParser from "postcss-selector-parser/dist/processor.js"; -import { addTypePrefix } from "./utils.js"; +import { addTypePrefix } from "./utilities.js"; function parseSelector(selector) { // If there's a comment inside of a selector, the parser tries to parse diff --git a/src/language-css/parse/parse-value.js b/src/language-css/parse/parse-value.js index ea628fe53..dd859dee7 100644 --- a/src/language-css/parse/parse-value.js +++ b/src/language-css/parse/parse-value.js @@ -1,11 +1,11 @@ import PostcssValuesParser from "postcss-values-parser/lib/parser.js"; -import getFunctionArgumentsText from "../utils/get-function-arguments-text.js"; -import getValueRoot from "../utils/get-value-root.js"; -import hasSCSSInterpolation from "../utils/has-scss-interpolation.js"; -import hasStringOrFunction from "../utils/has-string-or-function.js"; -import isSCSSVariable from "../utils/is-scss-variable.js"; +import getFunctionArgumentsText from "../utilities/get-function-arguments-text.js"; +import getValueRoot from "../utilities/get-value-root.js"; +import hasSCSSInterpolation from "../utilities/has-scss-interpolation.js"; +import hasStringOrFunction from "../utilities/has-string-or-function.js"; +import isSCSSVariable from "../utilities/is-scss-variable.js"; import parseSelector from "./parse-selector.js"; -import { addTypePrefix } from "./utils.js"; +import { addTypePrefix } from "./utilities.js"; const isClosingParenthesis = (node) => node.type === "paren" && node.value === ")"; diff --git a/src/language-css/parse/utils.js b/src/language-css/parse/utilities.js similarity index 100% rename from src/language-css/parse/utils.js rename to src/language-css/parse/utilities.js diff --git a/src/language-css/parser-postcss.js b/src/language-css/parser-postcss.js index 605de5111..dab842b36 100644 --- a/src/language-css/parser-postcss.js +++ b/src/language-css/parser-postcss.js @@ -12,10 +12,10 @@ import { import parseMediaQuery from "./parse/parse-media-query.js"; import parseSelector from "./parse/parse-selector.js"; import parseValue from "./parse/parse-value.js"; -import { addTypePrefix } from "./parse/utils.js"; +import { addTypePrefix } from "./parse/utilities.js"; import { hasIgnorePragma, hasPragma } from "./pragma.js"; -import isModuleRuleName from "./utils/is-module-rule-name.js"; -import isSCSSNestedPropertyNode from "./utils/is-scss-nested-property-node.js"; +import isModuleRuleName from "./utilities/is-module-rule-name.js"; +import isSCSSNestedPropertyNode from "./utilities/is-scss-nested-property-node.js"; const DEFAULT_SCSS_DIRECTIVE = /(\s*)(!default).*$/u; const GLOBAL_SCSS_DIRECTIVE = /(\s*)(!global).*$/u; diff --git a/src/language-css/print/comma-separated-value-group.js b/src/language-css/print/comma-separated-value-group.js index f1cdeeb27..0077005b6 100644 --- a/src/language-css/print/comma-separated-value-group.js +++ b/src/language-css/print/comma-separated-value-group.js @@ -37,7 +37,7 @@ import { isSCSSControlDirectiveNode, isSubtractionNode, isWordNode, -} from "../utils/index.js"; +} from "../utilities/index.js"; /** * @import AstPath from "../../common/ast-path.js" diff --git a/src/language-css/print/misc.js b/src/language-css/print/misc.js index e6ddc1a1d..5b90035f9 100644 --- a/src/language-css/print/misc.js +++ b/src/language-css/print/misc.js @@ -1,5 +1,5 @@ -import printNumber from "../../utils/print-number.js"; -import printString from "../../utils/print-string.js"; +import printNumber from "../../utilities/print-number.js"; +import printString from "../../utilities/print-string.js"; import CSS_UNITS from "./css-units.evaluate.js"; function printUnit(unit) { diff --git a/src/language-css/print/parenthesized-value-group.js b/src/language-css/print/parenthesized-value-group.js index a520c21d8..9cf4710ef 100644 --- a/src/language-css/print/parenthesized-value-group.js +++ b/src/language-css/print/parenthesized-value-group.js @@ -14,8 +14,8 @@ import { line, softline, } from "../../document/index.js"; -import isNextLineEmpty from "../../utils/is-next-line-empty.js"; -import isNonEmptyArray from "../../utils/is-non-empty-array.js"; +import isNextLineEmpty from "../../utilities/is-next-line-empty.js"; +import isNonEmptyArray from "../../utilities/is-non-empty-array.js"; import { locEnd, locStart } from "../loc.js"; import { isConfigurationNode, @@ -24,7 +24,7 @@ import { isSCSSMapItemNode, isURLFunctionNode, isVarFunctionNode, -} from "../utils/index.js"; +} from "../utilities/index.js"; import { shouldPrintTrailingComma } from "./misc.js"; function hasComma({ node, parent }, options) { diff --git a/src/language-css/print/sequence.js b/src/language-css/print/sequence.js index b004a3b2e..97051c7e6 100644 --- a/src/language-css/print/sequence.js +++ b/src/language-css/print/sequence.js @@ -1,7 +1,7 @@ import { hardline, line } from "../../document/index.js"; import { isFrontMatter } from "../../main/front-matter/index.js"; -import hasNewline from "../../utils/has-newline.js"; -import isNextLineEmpty from "../../utils/is-next-line-empty.js"; +import hasNewline from "../../utilities/has-newline.js"; +import isNextLineEmpty from "../../utilities/is-next-line-empty.js"; import { locEnd, locStart } from "../loc.js"; function printSequence(path, options, print) { diff --git a/src/language-css/printer-postcss.js b/src/language-css/printer-postcss.js index 0c14c8439..4ee70ae7f 100644 --- a/src/language-css/printer-postcss.js +++ b/src/language-css/printer-postcss.js @@ -10,9 +10,9 @@ import { removeLines, softline, } from "../document/index.js"; -import isNonEmptyArray from "../utils/is-non-empty-array.js"; -import printString from "../utils/print-string.js"; -import UnexpectedNodeError from "../utils/unexpected-node-error.js"; +import isNonEmptyArray from "../utilities/is-non-empty-array.js"; +import printString from "../utilities/print-string.js"; +import UnexpectedNodeError from "../utilities/unexpected-node-error.js"; import clean from "./clean.js"; import embed from "./embed.js"; import getVisitorKeys from "./get-visitor-keys.js"; @@ -47,7 +47,7 @@ import { isWideKeywords, lastLineHasInlineComment, maybeToLowerCase, -} from "./utils/index.js"; +} from "./utilities/index.js"; function genericPrint(path, options, print) { const { node } = path; diff --git a/src/language-css/utils/get-function-arguments-text.js b/src/language-css/utilities/get-function-arguments-text.js similarity index 100% rename from src/language-css/utils/get-function-arguments-text.js rename to src/language-css/utilities/get-function-arguments-text.js diff --git a/src/language-css/utils/get-value-root.js b/src/language-css/utilities/get-value-root.js similarity index 100% rename from src/language-css/utils/get-value-root.js rename to src/language-css/utilities/get-value-root.js diff --git a/src/language-css/utils/has-scss-interpolation.js b/src/language-css/utilities/has-scss-interpolation.js similarity index 86% rename from src/language-css/utils/has-scss-interpolation.js rename to src/language-css/utilities/has-scss-interpolation.js index a2e455959..9c4417ae4 100644 --- a/src/language-css/utils/has-scss-interpolation.js +++ b/src/language-css/utilities/has-scss-interpolation.js @@ -1,4 +1,4 @@ -import isNonEmptyArray from "../../utils/is-non-empty-array.js"; +import isNonEmptyArray from "../../utilities/is-non-empty-array.js"; function hasSCSSInterpolation(groupList) { if (isNonEmptyArray(groupList)) { diff --git a/src/language-css/utils/has-string-or-function.js b/src/language-css/utilities/has-string-or-function.js similarity index 100% rename from src/language-css/utils/has-string-or-function.js rename to src/language-css/utilities/has-string-or-function.js diff --git a/src/language-css/utils/index.js b/src/language-css/utilities/index.js similarity index 100% rename from src/language-css/utils/index.js rename to src/language-css/utilities/index.js diff --git a/src/language-css/utils/is-module-rule-name.js b/src/language-css/utilities/is-module-rule-name.js similarity index 100% rename from src/language-css/utils/is-module-rule-name.js rename to src/language-css/utilities/is-module-rule-name.js diff --git a/src/language-css/utils/is-scss-nested-property-node.js b/src/language-css/utilities/is-scss-nested-property-node.js similarity index 100% rename from src/language-css/utils/is-scss-nested-property-node.js rename to src/language-css/utilities/is-scss-nested-property-node.js diff --git a/src/language-css/utils/is-scss-variable.js b/src/language-css/utilities/is-scss-variable.js similarity index 100% rename from src/language-css/utils/is-scss-variable.js rename to src/language-css/utilities/is-scss-variable.js diff --git a/src/language-graphql/get-visitor-keys.js b/src/language-graphql/get-visitor-keys.js index 0739142eb..01f48a9d7 100644 --- a/src/language-graphql/get-visitor-keys.js +++ b/src/language-graphql/get-visitor-keys.js @@ -1,4 +1,4 @@ -import createGetVisitorKeys from "../utils/create-get-visitor-keys.js"; +import createGetVisitorKeys from "../utilities/create-get-visitor-keys.js"; import visitorKeys from "./visitor-keys.js"; const getVisitorKeys = createGetVisitorKeys(visitorKeys, "kind"); diff --git a/src/language-graphql/languages.evaluate.js b/src/language-graphql/languages.evaluate.js index 6f02a96dd..7be21e627 100644 --- a/src/language-graphql/languages.evaluate.js +++ b/src/language-graphql/languages.evaluate.js @@ -1,5 +1,5 @@ import * as linguistLanguages from "linguist-languages"; -import createLanguage from "../utils/create-language.js"; +import createLanguage from "../utilities/create-language.js"; const languages = [ createLanguage(linguistLanguages.GraphQL, () => ({ diff --git a/src/language-graphql/pragma.js b/src/language-graphql/pragma.js index 96e324d3d..28dcd39da 100644 --- a/src/language-graphql/pragma.js +++ b/src/language-graphql/pragma.js @@ -2,7 +2,7 @@ import { FORMAT_PRAGMA_TO_INSERT, GRAPHQL_HAS_IGNORE_PRAGMA_REGEXP, GRAPHQL_HAS_PRAGMA_REGEXP, -} from "../utils/pragma/pragma.evaluate.js"; +} from "../utilities/pragma/pragma.evaluate.js"; const hasPragma = (text) => GRAPHQL_HAS_PRAGMA_REGEXP.test(text); const hasIgnorePragma = (text) => GRAPHQL_HAS_IGNORE_PRAGMA_REGEXP.test(text); diff --git a/src/language-graphql/printer-graphql.js b/src/language-graphql/printer-graphql.js index 00f6913c3..f87a794f1 100644 --- a/src/language-graphql/printer-graphql.js +++ b/src/language-graphql/printer-graphql.js @@ -7,9 +7,9 @@ import { line, softline, } from "../document/index.js"; -import isNextLineEmpty from "../utils/is-next-line-empty.js"; -import isNonEmptyArray from "../utils/is-non-empty-array.js"; -import UnexpectedNodeError from "../utils/unexpected-node-error.js"; +import isNextLineEmpty from "../utilities/is-next-line-empty.js"; +import isNonEmptyArray from "../utilities/is-non-empty-array.js"; +import UnexpectedNodeError from "../utilities/unexpected-node-error.js"; import getVisitorKeys from "./get-visitor-keys.js"; import { locEnd, locStart } from "./loc.js"; import { insertPragma } from "./pragma.js"; diff --git a/src/language-handlebars/clean.js b/src/language-handlebars/clean.js index 10300d0a4..a6b229145 100644 --- a/src/language-handlebars/clean.js +++ b/src/language-handlebars/clean.js @@ -1,4 +1,4 @@ -import htmlWhitespaceUtils from "../utils/html-whitespace-utils.js"; +import htmlWhitespace from "../utilities/html-whitespace.js"; function clean(original, cloned, parent) { // (Glimmer/HTML) ignore TextNode @@ -16,7 +16,7 @@ function clean(original, cloned, parent) { ) { cloned.chars = ""; } else { - cloned.chars = htmlWhitespaceUtils.split(trimmed).join(" "); + cloned.chars = htmlWhitespace.split(trimmed).join(" "); } } diff --git a/src/language-handlebars/get-visitor-keys.js b/src/language-handlebars/get-visitor-keys.js index 50df7ba20..f4d75eb17 100644 --- a/src/language-handlebars/get-visitor-keys.js +++ b/src/language-handlebars/get-visitor-keys.js @@ -1,4 +1,4 @@ -import createGetVisitorKeys from "../utils/create-get-visitor-keys.js"; +import createGetVisitorKeys from "../utilities/create-get-visitor-keys.js"; import visitorKeys from "./visitor-keys.evaluate.js"; const getVisitorKeys = createGetVisitorKeys(visitorKeys); diff --git a/src/language-handlebars/languages.evaluate.js b/src/language-handlebars/languages.evaluate.js index d2183ee80..0bfac9ccd 100644 --- a/src/language-handlebars/languages.evaluate.js +++ b/src/language-handlebars/languages.evaluate.js @@ -1,5 +1,5 @@ import * as linguistLanguages from "linguist-languages"; -import createLanguage from "../utils/create-language.js"; +import createLanguage from "../utilities/create-language.js"; const languages = [ createLanguage(linguistLanguages.Handlebars, () => ({ diff --git a/src/language-handlebars/printer-glimmer.js b/src/language-handlebars/printer-glimmer.js index d673414b6..5c2767aa6 100644 --- a/src/language-handlebars/printer-glimmer.js +++ b/src/language-handlebars/printer-glimmer.js @@ -10,15 +10,19 @@ import { replaceEndOfLine, softline, } from "../document/index.js"; -import getPreferredQuote from "../utils/get-preferred-quote.js"; -import htmlWhitespaceUtils from "../utils/html-whitespace-utils.js"; -import isNonEmptyArray from "../utils/is-non-empty-array.js"; -import UnexpectedNodeError from "../utils/unexpected-node-error.js"; +import getPreferredQuote from "../utilities/get-preferred-quote.js"; +import htmlWhitespace from "../utilities/html-whitespace.js"; +import isNonEmptyArray from "../utilities/is-non-empty-array.js"; +import UnexpectedNodeError from "../utilities/unexpected-node-error.js"; import clean from "./clean.js"; import embed from "./embed.js"; import getVisitorKeys from "./get-visitor-keys.js"; import { locEnd, locStart } from "./loc.js"; -import { hasPrettierIgnore, isVoidElement, isWhitespaceNode } from "./utils.js"; +import { + hasPrettierIgnore, + isVoidElement, + isWhitespaceNode, +} from "./utilities.js"; /** @import {Doc} from "../document/index.js" @@ -170,8 +174,8 @@ function print(path, options, print) { if (parent.tag === "style") { text = text.replaceAll(/^\n+/gu, ""); - text = htmlWhitespaceUtils.trimEnd(text); - text = htmlWhitespaceUtils.dedentString(text); + text = htmlWhitespace.trimEnd(text); + text = htmlWhitespace.dedentString(text); return replaceEndOfLine(text, hardline); } @@ -218,7 +222,7 @@ function print(path, options, print) { return replaceEndOfLine(text); } - const isWhitespaceOnly = htmlWhitespaceUtils.isWhitespaceOnly(text); + const isWhitespaceOnly = htmlWhitespace.isWhitespaceOnly(text); const { isFirst, isLast } = path; if (options.htmlWhitespaceSensitivity !== "ignore") { @@ -249,8 +253,7 @@ function print(path, options, print) { return breaks; } - const leadingWhitespace = - htmlWhitespaceUtils.getLeadingWhitespace(text); + const leadingWhitespace = htmlWhitespace.getLeadingWhitespace(text); let leadBreaks = []; if (leadingWhitespace) { @@ -264,8 +267,7 @@ function print(path, options, print) { text = text.slice(leadingWhitespace.length); } - const tailingWhitespace = - htmlWhitespaceUtils.getTrailingWhitespace(text); + const tailingWhitespace = htmlWhitespace.getTrailingWhitespace(text); let trailBreaks = []; if (tailingWhitespace) { if (!shouldTrimTrailingNewlines) { @@ -351,12 +353,12 @@ function print(path, options, print) { trailingSpace = ""; } - if (htmlWhitespaceUtils.hasLeadingWhitespace(text)) { - text = leadingSpace + htmlWhitespaceUtils.trimStart(text); + if (htmlWhitespace.hasLeadingWhitespace(text)) { + text = leadingSpace + htmlWhitespace.trimStart(text); } - if (htmlWhitespaceUtils.hasTrailingWhitespace(text)) { - text = htmlWhitespaceUtils.trimEnd(text) + trailingSpace; + if (htmlWhitespace.hasTrailingWhitespace(text)) { + text = htmlWhitespace.trimEnd(text) + trailingSpace; } return [ @@ -672,7 +674,7 @@ function printInverse(path, options, print) { /* TextNode print helpers */ function getTextValueParts(value) { - return join(line, htmlWhitespaceUtils.split(value)); + return join(line, htmlWhitespace.split(value)); } function getCurrentAttributeName(path) { @@ -712,7 +714,7 @@ function generateHardlines(number = 0) { /* StringLiteral print helpers */ -/** @import {Quote} from "../utils/get-preferred-quote.js" */ +/** @import {Quote} from "../utilities/get-preferred-quote.js" */ /** * Prints a string literal with the correct surrounding quotes based on diff --git a/src/language-handlebars/utils.js b/src/language-handlebars/utilities.js similarity index 100% rename from src/language-handlebars/utils.js rename to src/language-handlebars/utilities.js diff --git a/src/language-html/embed.js b/src/language-html/embed.js index 5c9bbb557..2a13c90fc 100644 --- a/src/language-html/embed.js +++ b/src/language-html/embed.js @@ -5,10 +5,10 @@ import { indent, line, } from "../document/index.js"; -import htmlWhitespaceUtils from "../utils/html-whitespace-utils.js"; +import htmlWhitespace from "../utilities/html-whitespace.js"; import printAngularControlFlowBlockParameters from "./embed/angular-control-flow-block-parameters.js"; import printAttribute from "./embed/attribute.js"; -import { formatAttributeValue } from "./embed/utils.js"; +import { formatAttributeValue } from "./embed/utilities.js"; import getNodeContent from "./get-node-content.js"; import { needsToBorrowPrevClosingTagEndMarker, @@ -22,8 +22,8 @@ import { inferElementParser, isScriptLikeTag, isVueNonHtmlBlock, -} from "./utils/index.js"; -import isVueSfcWithTypescriptScript from "./utils/is-vue-sfc-with-typescript-script.js"; +} from "./utilities/index.js"; +import isVueSfcWithTypescriptScript from "./utilities/is-vue-sfc-with-typescript-script.js"; const embeddedAngularControlFlowBlocks = new Set([ "if", @@ -81,7 +81,7 @@ function embed(path, options) { return async (textToDoc) => { const value = parser === "markdown" - ? htmlWhitespaceUtils.dedentString( + ? htmlWhitespace.dedentString( node.value.replace(/^[^\S\n]*\n/u, ""), ) : node.value; diff --git a/src/language-html/embed/angular-attributes.js b/src/language-html/embed/angular-attributes.js index 602f6a29e..7d91f3b7c 100644 --- a/src/language-html/embed/angular-attributes.js +++ b/src/language-html/embed/angular-attributes.js @@ -2,7 +2,7 @@ import { fill } from "../../document/index.js"; import { getTextValueParts, getUnescapedAttributeValue, -} from "../utils/index.js"; +} from "../utilities/index.js"; import { isAngularInterpolation, printAngularInterpolation, @@ -11,7 +11,7 @@ import { formatAttributeValue, printExpand, shouldHugJsExpression, -} from "./utils.js"; +} from "./utilities.js"; /** @import {AttributeValuePrinter} from "./attribute.js" diff --git a/src/language-html/embed/angular-control-flow-block-parameters.js b/src/language-html/embed/angular-control-flow-block-parameters.js index bbdab27ba..cee397078 100644 --- a/src/language-html/embed/angular-control-flow-block-parameters.js +++ b/src/language-html/embed/angular-control-flow-block-parameters.js @@ -1,4 +1,4 @@ -import { formatAttributeValue, shouldHugJsExpression } from "./utils.js"; +import { formatAttributeValue, shouldHugJsExpression } from "./utilities.js"; function printAngularControlFlowBlockParameters( textToDoc, diff --git a/src/language-html/embed/angular-interpolation.js b/src/language-html/embed/angular-interpolation.js index 08f9ea4c3..188721f7f 100644 --- a/src/language-html/embed/angular-interpolation.js +++ b/src/language-html/embed/angular-interpolation.js @@ -1,6 +1,6 @@ import { group, indent, line, replaceEndOfLine } from "../../document/index.js"; -import { getUnescapedAttributeValue } from "../utils/index.js"; -import { formatAttributeValue } from "./utils.js"; +import { getUnescapedAttributeValue } from "../utilities/index.js"; +import { formatAttributeValue } from "./utilities.js"; const interpolationRegex = /\{\{(.+?)\}\}/su; diff --git a/src/language-html/embed/class-names.js b/src/language-html/embed/class-names.js index 0050af13b..8cacf92fe 100644 --- a/src/language-html/embed/class-names.js +++ b/src/language-html/embed/class-names.js @@ -1,4 +1,4 @@ -import { getUnescapedAttributeValue } from "../utils/index.js"; +import { getUnescapedAttributeValue } from "../utilities/index.js"; /** @import {AttributeValuePredicate, AttributeValuePrint} from "./attribute.js" diff --git a/src/language-html/embed/event-handler.js b/src/language-html/embed/event-handler.js index 27635ae75..48a74293b 100644 --- a/src/language-html/embed/event-handler.js +++ b/src/language-html/embed/event-handler.js @@ -1,6 +1,6 @@ import htmlEventAttributesArray from "@prettier/html-event-attributes"; -import { getUnescapedAttributeValue } from "../utils/index.js"; -import { formatAttributeValue } from "./utils.js"; +import { getUnescapedAttributeValue } from "../utilities/index.js"; +import { formatAttributeValue } from "./utilities.js"; /** @import {AttributeValuePredicate, AttributeValuePrint} from "./attribute.js" diff --git a/src/language-html/embed/parse-permissions-policy.js b/src/language-html/embed/parse-permissions-policy.js index 9e38a9573..a4695fa73 100644 --- a/src/language-html/embed/parse-permissions-policy.js +++ b/src/language-html/embed/parse-permissions-policy.js @@ -5,7 +5,7 @@ Based on https://github.com/helmetjs/content-security-policy-parser/blob/main/mo 1. Skip ASCII check, so we won't remove invalid directives. 1. Skip directive name normalization, so the printer can know what's the original name. */ -import htmlWhitespaceUtils from "../../utils/html-whitespace-utils.js"; +import htmlWhitespace from "../../utilities/html-whitespace.js"; /** @typedef {{ @@ -28,7 +28,7 @@ function parsePermissionsPolicy(policy) { // U+003B SEMICOLON character (;):" for (let token of policy.split(";")) { // "1. Strip leading and trailing ASCII whitespace from token." - token = htmlWhitespaceUtils.trim(token); + token = htmlWhitespace.trim(token); // "2. If token is an empty string, or if token is not an ASCII string, // continue." @@ -42,7 +42,7 @@ function parsePermissionsPolicy(policy) { // code points from token which are not ASCII whitespace." // "6. Let directive value be the result of splitting token on // ASCII whitespace." - const [name, ...value] = htmlWhitespaceUtils.split(token); + const [name, ...value] = htmlWhitespace.split(token); // "4. Set directive name to be the result of running ASCII lowercase on // directive name." diff --git a/src/language-html/embed/permissions-policy.js b/src/language-html/embed/permissions-policy.js index 561577272..a02a1c623 100644 --- a/src/language-html/embed/permissions-policy.js +++ b/src/language-html/embed/permissions-policy.js @@ -1,7 +1,7 @@ import { ifBreak, line } from "../../document/index.js"; -import { getUnescapedAttributeValue } from "../utils/index.js"; +import { getUnescapedAttributeValue } from "../utilities/index.js"; import parsePermissionsPolicy from "./parse-permissions-policy.js"; -import { printExpand } from "./utils.js"; +import { printExpand } from "./utilities.js"; /** @import {AttributeValuePredicate, AttributeValuePrint} from "./attribute.js" diff --git a/src/language-html/embed/print-vue-script-generic-attribute-value.js b/src/language-html/embed/print-vue-script-generic-attribute-value.js index 986a5b0b9..4c65349f9 100644 --- a/src/language-html/embed/print-vue-script-generic-attribute-value.js +++ b/src/language-html/embed/print-vue-script-generic-attribute-value.js @@ -1,5 +1,5 @@ -import { getUnescapedAttributeValue } from "../utils/index.js"; -import { formatAttributeValue, shouldHugJsExpression } from "./utils.js"; +import { getUnescapedAttributeValue } from "../utilities/index.js"; +import { formatAttributeValue, shouldHugJsExpression } from "./utilities.js"; /** * @import {Doc} from "../../document/index.js" diff --git a/src/language-html/embed/srcset.js b/src/language-html/embed/srcset.js index b627e6649..0050bc516 100644 --- a/src/language-html/embed/srcset.js +++ b/src/language-html/embed/srcset.js @@ -1,7 +1,7 @@ import parseSrcset from "@prettier/parse-srcset"; import { ifBreak, join, line } from "../../document/index.js"; -import { getUnescapedAttributeValue } from "../utils/index.js"; -import { printExpand } from "./utils.js"; +import { getUnescapedAttributeValue } from "../utilities/index.js"; +import { printExpand } from "./utilities.js"; /** @import {Doc} from "../../document/index.js" diff --git a/src/language-html/embed/style.js b/src/language-html/embed/style.js index d933c5afb..65547f174 100644 --- a/src/language-html/embed/style.js +++ b/src/language-html/embed/style.js @@ -1,5 +1,5 @@ -import { getUnescapedAttributeValue } from "../utils/index.js"; -import { printExpand } from "./utils.js"; +import { getUnescapedAttributeValue } from "../utilities/index.js"; +import { printExpand } from "./utilities.js"; /** @import {AttributeValuePredicate, AttributeValuePrint} from "./attribute.js" diff --git a/src/language-html/embed/utils.js b/src/language-html/embed/utilities.js similarity index 100% rename from src/language-html/embed/utils.js rename to src/language-html/embed/utilities.js diff --git a/src/language-html/embed/vue-attributes.js b/src/language-html/embed/vue-attributes.js index 3ea8db1b3..c6841c976 100644 --- a/src/language-html/embed/vue-attributes.js +++ b/src/language-html/embed/vue-attributes.js @@ -3,10 +3,10 @@ import { isVueScriptTag, isVueSfcBindingsAttribute, isVueSlotAttribute, -} from "../utils/index.js"; -import isVueSfcWithTypescriptScript from "../utils/is-vue-sfc-with-typescript-script.js"; +} from "../utilities/index.js"; +import isVueSfcWithTypescriptScript from "../utilities/is-vue-sfc-with-typescript-script.js"; import { printVueScriptGenericAttributeValue } from "./print-vue-script-generic-attribute-value.js"; -import { formatAttributeValue, shouldHugJsExpression } from "./utils.js"; +import { formatAttributeValue, shouldHugJsExpression } from "./utilities.js"; import { printVueBindings } from "./vue-bindings.js"; import { printVueVForDirective } from "./vue-v-for-directive.js"; diff --git a/src/language-html/embed/vue-bindings.js b/src/language-html/embed/vue-bindings.js index a6ba48d8f..6f5ae4016 100644 --- a/src/language-html/embed/vue-bindings.js +++ b/src/language-html/embed/vue-bindings.js @@ -1,6 +1,6 @@ -import { getUnescapedAttributeValue } from "../utils/index.js"; -import isVueSfcWithTypescriptScript from "../utils/is-vue-sfc-with-typescript-script.js"; -import { formatAttributeValue } from "./utils.js"; +import { getUnescapedAttributeValue } from "../utilities/index.js"; +import isVueSfcWithTypescriptScript from "../utilities/is-vue-sfc-with-typescript-script.js"; +import { formatAttributeValue } from "./utilities.js"; /** * @import {Doc} from "../../document/index.js" diff --git a/src/language-html/embed/vue-v-for-directive.js b/src/language-html/embed/vue-v-for-directive.js index ce908a17e..929a912e5 100644 --- a/src/language-html/embed/vue-v-for-directive.js +++ b/src/language-html/embed/vue-v-for-directive.js @@ -1,7 +1,7 @@ import { group } from "../../document/index.js"; -import { getUnescapedAttributeValue } from "../utils/index.js"; -import isVueSfcWithTypescriptScript from "../utils/is-vue-sfc-with-typescript-script.js"; -import { formatAttributeValue } from "./utils.js"; +import { getUnescapedAttributeValue } from "../utilities/index.js"; +import isVueSfcWithTypescriptScript from "../utilities/is-vue-sfc-with-typescript-script.js"; +import { formatAttributeValue } from "./utilities.js"; /** * @import {Doc} from "../../document/index.js" diff --git a/src/language-html/get-visitor-keys.js b/src/language-html/get-visitor-keys.js index 0739142eb..01f48a9d7 100644 --- a/src/language-html/get-visitor-keys.js +++ b/src/language-html/get-visitor-keys.js @@ -1,4 +1,4 @@ -import createGetVisitorKeys from "../utils/create-get-visitor-keys.js"; +import createGetVisitorKeys from "../utilities/create-get-visitor-keys.js"; import visitorKeys from "./visitor-keys.js"; const getVisitorKeys = createGetVisitorKeys(visitorKeys, "kind"); diff --git a/src/language-html/languages.evaluate.js b/src/language-html/languages.evaluate.js index 0f4ef2822..800abe822 100644 --- a/src/language-html/languages.evaluate.js +++ b/src/language-html/languages.evaluate.js @@ -1,5 +1,5 @@ import * as linguistLanguages from "linguist-languages"; -import createLanguage from "../utils/create-language.js"; +import createLanguage from "../utilities/create-language.js"; const languages = [ createLanguage(linguistLanguages.HTML, () => ({ diff --git a/src/language-html/parse/postprocess.js b/src/language-html/parse/postprocess.js index eae990e2a..2837f0651 100644 --- a/src/language-html/parse/postprocess.js +++ b/src/language-html/parse/postprocess.js @@ -4,10 +4,10 @@ import { RecursiveVisitor, visitAll, } from "angular-html-parser"; -import isNonEmptyArray from "../../utils/is-non-empty-array.js"; -import HTML_ELEMENT_ATTRIBUTES from "../utils/html-elements-attributes.evaluate.js"; -import HTML_TAGS from "../utils/html-tags.evaluate.js"; -import isUnknownNamespace from "../utils/is-unknown-namespace.js"; +import isNonEmptyArray from "../../utilities/is-non-empty-array.js"; +import HTML_ELEMENT_ATTRIBUTES from "../utilities/html-elements-attributes.evaluate.js"; +import HTML_TAGS from "../utilities/html-tags.evaluate.js"; +import isUnknownNamespace from "../utilities/is-unknown-namespace.js"; import { Node } from "./ast.js"; import { parseIeConditionalComment } from "./conditional-comment.js"; diff --git a/src/language-html/pragma.js b/src/language-html/pragma.js index 4868bd9dd..92ae86529 100644 --- a/src/language-html/pragma.js +++ b/src/language-html/pragma.js @@ -2,7 +2,7 @@ import { FORMAT_PRAGMA_TO_INSERT, HTML_HAS_IGNORE_PRAGMA_REGEXP, HTML_HAS_PRAGMA_REGEXP, -} from "../utils/pragma/pragma.evaluate.js"; +} from "../utilities/pragma/pragma.evaluate.js"; const hasPragma = (text) => HTML_HAS_PRAGMA_REGEXP.test(text); const hasIgnorePragma = (text) => HTML_HAS_IGNORE_PRAGMA_REGEXP.test(text); diff --git a/src/language-html/print-preprocess.js b/src/language-html/print-preprocess.js index bddde3ec5..ec7d5b330 100644 --- a/src/language-html/print-preprocess.js +++ b/src/language-html/print-preprocess.js @@ -1,5 +1,5 @@ import { ParseSourceSpan } from "angular-html-parser"; -import htmlWhitespaceUtils from "../utils/html-whitespace-utils.js"; +import htmlWhitespace from "../utilities/html-whitespace.js"; import { canHaveInterpolation, getLeadingAndTrailingHtmlWhitespace, @@ -9,7 +9,7 @@ import { isLeadingSpaceSensitiveNode, isTrailingSpaceSensitiveNode, isWhitespaceSensitiveNode, -} from "./utils/index.js"; +} from "./utilities/index.js"; const PREPROCESS_PIPELINE = [ removeIgnorableFirstLf, @@ -143,7 +143,7 @@ function mergeSimpleElementIntoText(ast /* , options */) { node.attrs.length === 0 && node.children.length === 1 && node.firstChild.kind === "text" && - !htmlWhitespaceUtils.hasWhitespaceCharacter(node.children[0].value) && + !htmlWhitespace.hasWhitespaceCharacter(node.children[0].value) && !node.firstChild.hasLeadingSpaces && !node.firstChild.hasTrailingSpaces && node.isLeadingSpaceSensitive && @@ -264,7 +264,7 @@ function extractWhitespaces(ast, options) { children.length === 0 || (children.length === 1 && children[0].kind === "text" && - htmlWhitespaceUtils.trim(children[0].value).length === 0) + htmlWhitespace.trim(children[0].value).length === 0) ) { node.hasDanglingSpaces = children.length > 0; node.$children = []; diff --git a/src/language-html/print/angular-control-flow-block.js b/src/language-html/print/angular-control-flow-block.js index 82253bd50..e1d0919e0 100644 --- a/src/language-html/print/angular-control-flow-block.js +++ b/src/language-html/print/angular-control-flow-block.js @@ -6,7 +6,7 @@ import { line, softline, } from "../../document/index.js"; -import { hasPrettierIgnore } from "../utils/index.js"; +import { hasPrettierIgnore } from "../utilities/index.js"; import ANGULAR_CONTROL_FLOW_BLOCK_SETTINGS from "./angular-control-flow-block-settings.evaluate.js"; import { printChildren } from "./children.js"; diff --git a/src/language-html/print/children.js b/src/language-html/print/children.js index bc22a8cbd..2a98c5521 100644 --- a/src/language-html/print/children.js +++ b/src/language-html/print/children.js @@ -7,8 +7,8 @@ import { replaceEndOfLine, softline, } from "../../document/index.js"; -import htmlWhitespaceUtils from "../../utils/html-whitespace-utils.js"; -import isNonEmptyArray from "../../utils/is-non-empty-array.js"; +import htmlWhitespace from "../../utilities/html-whitespace.js"; +import isNonEmptyArray from "../../utilities/is-non-empty-array.js"; import { locEnd, locStart } from "../loc.js"; import { forceBreakChildren, @@ -16,7 +16,7 @@ import { hasPrettierIgnore, isTextLikeNode, preferHardlineAsLeadingSpaces, -} from "../utils/index.js"; +} from "../utilities/index.js"; import { needsToBorrowNextOpeningTagStartMarker, needsToBorrowParentClosingTagStartMarker, @@ -51,7 +51,7 @@ function printChild(path, options, print) { return [ printOpeningTagPrefix(child, options), replaceEndOfLine( - htmlWhitespaceUtils.trimEnd( + htmlWhitespace.trimEnd( options.originalText.slice( locStart(child) + (child.prev && needsToBorrowNextOpeningTagStartMarker(child.prev) diff --git a/src/language-html/print/element.js b/src/language-html/print/element.js index dce0d4fdb..3ae5ab6e0 100644 --- a/src/language-html/print/element.js +++ b/src/language-html/print/element.js @@ -15,7 +15,7 @@ import { isScriptLikeTag, isVueCustomBlock, shouldPreserveContent, -} from "../utils/index.js"; +} from "../utilities/index.js"; import { printChildren } from "./children.js"; import { needsToBorrowLastChildClosingTagEndMarker, diff --git a/src/language-html/print/tag.js b/src/language-html/print/tag.js index 6e8ebd86c..429f1d9e5 100644 --- a/src/language-html/print/tag.js +++ b/src/language-html/print/tag.js @@ -11,7 +11,7 @@ import { replaceEndOfLine, softline, } from "../../document/index.js"; -import isNonEmptyArray from "../../utils/is-non-empty-array.js"; +import isNonEmptyArray from "../../utilities/is-non-empty-array.js"; import { locEnd, locStart } from "../loc.js"; import { getLastDescendant, @@ -20,7 +20,7 @@ import { isTextLikeNode, isVueSfcBlock, shouldPreserveContent, -} from "../utils/index.js"; +} from "../utilities/index.js"; function printClosingTag(node, options) { return [ diff --git a/src/language-html/printer-html.js b/src/language-html/printer-html.js index 6d51941db..289634f1e 100644 --- a/src/language-html/printer-html.js +++ b/src/language-html/printer-html.js @@ -10,9 +10,9 @@ import { line, replaceEndOfLine, } from "../document/index.js"; -import getPreferredQuote from "../utils/get-preferred-quote.js"; -import htmlWhitespaceUtils from "../utils/html-whitespace-utils.js"; -import UnexpectedNodeError from "../utils/unexpected-node-error.js"; +import getPreferredQuote from "../utilities/get-preferred-quote.js"; +import htmlWhitespace from "../utilities/html-whitespace.js"; +import UnexpectedNodeError from "../utilities/unexpected-node-error.js"; import clean from "./clean.js"; import embed from "./embed.js"; import getVisitorKeys from "./get-visitor-keys.js"; @@ -35,7 +35,7 @@ import { printOpeningTagStart, } from "./print/tag.js"; import preprocess from "./print-preprocess.js"; -import { getTextValueParts, unescapeQuoteEntities } from "./utils/index.js"; +import { getTextValueParts, unescapeQuoteEntities } from "./utilities/index.js"; function genericPrint(path, options, print) { const { node } = path; @@ -55,7 +55,7 @@ function genericPrint(path, options, print) { case "angularControlFlowBlockParameters": return printAngularControlFlowBlockParameters(path, options, print); case "angularControlFlowBlockParameter": - return htmlWhitespaceUtils.trim(node.expression); + return htmlWhitespace.trim(node.expression); case "angularLetDeclaration": // print like "break-after-operator" layout assignment in estree printer diff --git a/src/language-html/utils/html-elements-attributes.evaluate.js b/src/language-html/utilities/html-elements-attributes.evaluate.js similarity index 100% rename from src/language-html/utils/html-elements-attributes.evaluate.js rename to src/language-html/utilities/html-elements-attributes.evaluate.js diff --git a/src/language-html/utils/html-tags.evaluate.js b/src/language-html/utilities/html-tags.evaluate.js similarity index 100% rename from src/language-html/utils/html-tags.evaluate.js rename to src/language-html/utilities/html-tags.evaluate.js diff --git a/src/language-html/utils/index.js b/src/language-html/utilities/index.js similarity index 96% rename from src/language-html/utils/index.js rename to src/language-html/utilities/index.js index f8fc3d15f..ec00e6262 100644 --- a/src/language-html/utils/index.js +++ b/src/language-html/utilities/index.js @@ -9,8 +9,8 @@ import { replaceEndOfLine, } from "../../document/index.js"; import { isFrontMatter } from "../../main/front-matter/index.js"; -import htmlWhitespaceUtils from "../../utils/html-whitespace-utils.js"; -import inferParser from "../../utils/infer-parser.js"; +import htmlWhitespace from "../../utilities/html-whitespace.js"; +import inferParser from "../../utilities/infer-parser.js"; import { CSS_DISPLAY_DEFAULT, CSS_DISPLAY_TAGS, @@ -22,14 +22,14 @@ import isUnknownNamespace from "./is-unknown-namespace.js"; const htmlTrimLeadingBlankLines = (string) => string.replaceAll(/^[\t\f\r ]*\n/gu, ""); const htmlTrimPreserveIndentation = (string) => - htmlTrimLeadingBlankLines(htmlWhitespaceUtils.trimEnd(string)); + htmlTrimLeadingBlankLines(htmlWhitespace.trimEnd(string)); const getLeadingAndTrailingHtmlWhitespace = (string) => { let text = string; - const leadingWhitespace = htmlWhitespaceUtils.getLeadingWhitespace(text); + const leadingWhitespace = htmlWhitespace.getLeadingWhitespace(text); if (leadingWhitespace) { text = text.slice(leadingWhitespace.length); } - const trailingWhitespace = htmlWhitespaceUtils.getTrailingWhitespace(text); + const trailingWhitespace = htmlWhitespace.getTrailingWhitespace(text); if (trailingWhitespace) { text = text.slice(0, -trailingWhitespace.length); } @@ -590,10 +590,10 @@ function getTextValueParts(node, value = node.value) { ? node.parent.isIndentationSensitive ? replaceEndOfLine(value) : replaceEndOfLine( - htmlWhitespaceUtils.dedentString(htmlTrimPreserveIndentation(value)), + htmlWhitespace.dedentString(htmlTrimPreserveIndentation(value)), hardline, ) - : join(line, htmlWhitespaceUtils.split(value)); + : join(line, htmlWhitespace.split(value)); } function isVueScriptTag(node, options) { diff --git a/src/language-html/utils/is-unknown-namespace.js b/src/language-html/utilities/is-unknown-namespace.js similarity index 100% rename from src/language-html/utils/is-unknown-namespace.js rename to src/language-html/utilities/is-unknown-namespace.js diff --git a/src/language-html/utils/is-vue-sfc-with-typescript-script.js b/src/language-html/utilities/is-vue-sfc-with-typescript-script.js similarity index 100% rename from src/language-html/utils/is-vue-sfc-with-typescript-script.js rename to src/language-html/utilities/is-vue-sfc-with-typescript-script.js diff --git a/src/language-js/clean.js b/src/language-js/clean.js index d49d36539..986bcbe47 100644 --- a/src/language-js/clean.js +++ b/src/language-js/clean.js @@ -3,7 +3,7 @@ import { isMeaningfulEmptyStatement, isNumericLiteral, isStringLiteral, -} from "./utils/index.js"; +} from "./utilities/index.js"; const ignoredProperties = new Set([ "range", diff --git a/src/language-js/comments/printer-methods.js b/src/language-js/comments/can-attach-comment.js similarity index 66% rename from src/language-js/comments/printer-methods.js rename to src/language-js/comments/can-attach-comment.js index 952e39cc5..ef7bfe821 100644 --- a/src/language-js/comments/printer-methods.js +++ b/src/language-js/comments/can-attach-comment.js @@ -1,14 +1,11 @@ -import isNonEmptyArray from "../../utils/is-non-empty-array.js"; +import isNonEmptyArray from "../../utilities/is-non-empty-array.js"; import { createTypeCheckFunction, getFunctionParameters, - hasNodeIgnoreComment, - isJsxElement, isMeaningfulEmptyStatement, isMethod, isTsAsConstExpression, - isUnionType, -} from "../utils/index.js"; +} from "../utilities/index.js"; /** * @import {Node} from "../types/estree.js" @@ -148,56 +145,4 @@ function canAttachComment(node, ancestors) { return true; } -const isClassOrInterface = createTypeCheckFunction([ - "ClassDeclaration", - "ClassExpression", - "DeclareClass", - "DeclareInterface", - "InterfaceDeclaration", - "TSInterfaceDeclaration", - // Can't have `id` or `typeParameters` - // "InterfaceTypeAnnotation", -]); - -/** - * @param {AstPath} path - * @returns {boolean} - */ -function willPrintOwnComments(path) { - const { key, parent } = path; - if ( - (key === "types" && isUnionType(parent)) || - (key === "argument" && parent.type === "JSXSpreadAttribute") || - (key === "expression" && parent.type === "JSXSpreadChild") || - (key === "superClass" && - (parent.type === "ClassDeclaration" || - parent.type === "ClassExpression")) || - ((key === "id" || key === "typeParameters") && - isClassOrInterface(parent)) || - // Not tested, don't know how to - (key === "patterns" && parent.type === "MatchOrPattern") - ) { - return true; - } - - const { node } = path; - if (hasNodeIgnoreComment(node)) { - return false; - } - - return isJsxElement(node) || isUnionType(node); -} - -function isGap(text, { parser }) { - if (parser === "flow" || parser === "hermes" || parser === "babel-flow") { - // Example: (a /* b */ /* : c */) - // gap ^^^^ - text = text.replaceAll(/[\s(]/gu, ""); - return text === "" || text === "/*" || text === "/*::"; - } -} - -export { printComment } from "../print/comment.js"; -export { default as isBlockComment } from "../utils/is-block-comment.js"; -export { default as handleComments } from "./handle-comments.js"; -export { canAttachComment, isGap, willPrintOwnComments }; +export default canAttachComment; diff --git a/src/language-js/comments/handle-comments.js b/src/language-js/comments/handle-comments.js index e03ec7ef1..ee62a416f 100644 --- a/src/language-js/comments/handle-comments.js +++ b/src/language-js/comments/handle-comments.js @@ -2,12 +2,12 @@ import { addDanglingComment, addLeadingComment, addTrailingComment, -} from "../../main/comments/utils.js"; -import getNextNonSpaceNonCommentCharacter from "../../utils/get-next-non-space-non-comment-character.js"; -import getNextNonSpaceNonCommentCharacterIndex from "../../utils/get-next-non-space-non-comment-character-index.js"; -import hasNewline from "../../utils/has-newline.js"; -import hasNewlineInRange from "../../utils/has-newline-in-range.js"; -import isNonEmptyArray from "../../utils/is-non-empty-array.js"; +} from "../../main/comments/utilities.js"; +import getNextNonSpaceNonCommentCharacter from "../../utilities/get-next-non-space-non-comment-character.js"; +import getNextNonSpaceNonCommentCharacterIndex from "../../utilities/get-next-non-space-non-comment-character-index.js"; +import hasNewline from "../../utilities/has-newline.js"; +import hasNewlineInRange from "../../utilities/has-newline-in-range.js"; +import isNonEmptyArray from "../../utilities/is-non-empty-array.js"; import { locEnd, locStart } from "../loc.js"; import { createTypeCheckFunction, @@ -22,10 +22,10 @@ import { isObjectProperty, isPrettierIgnoreComment, isUnionType, -} from "../utils/index.js"; -import isBlockComment from "../utils/is-block-comment.js"; -import isLineComment from "../utils/is-line-comment.js"; -import isTypeCastComment from "../utils/is-type-cast-comment.js"; +} from "../utilities/index.js"; +import isBlockComment from "../utilities/is-block-comment.js"; +import isLineComment from "../utilities/is-line-comment.js"; +import isTypeCastComment from "../utilities/is-type-cast-comment.js"; /** @import * as Estree from "../types/estree.js" */ diff --git a/src/language-js/comments/is-gap.js b/src/language-js/comments/is-gap.js new file mode 100644 index 000000000..d49562176 --- /dev/null +++ b/src/language-js/comments/is-gap.js @@ -0,0 +1,10 @@ +function isGap(text, { parser }) { + if (parser === "flow" || parser === "hermes" || parser === "babel-flow") { + // Example: (a /* b */ /* : c */) + // gap ^^^^ + text = text.replaceAll(/[\s(]/gu, ""); + return text === "" || text === "/*" || text === "/*::"; + } +} + +export default isGap; diff --git a/src/language-js/comments/will-print-own-comments.js b/src/language-js/comments/will-print-own-comments.js new file mode 100644 index 000000000..04c176d92 --- /dev/null +++ b/src/language-js/comments/will-print-own-comments.js @@ -0,0 +1,53 @@ +import { + createTypeCheckFunction, + hasNodeIgnoreComment, + isJsxElement, + isUnionType, +} from "../utilities/index.js"; + +/** + * @import {Node} from "../types/estree.js" + * @import AstPath from "../../common/ast-path.js" + */ + +const isClassOrInterface = createTypeCheckFunction([ + "ClassDeclaration", + "ClassExpression", + "DeclareClass", + "DeclareInterface", + "InterfaceDeclaration", + "TSInterfaceDeclaration", + // Can't have `id` or `typeParameters` + // "InterfaceTypeAnnotation", +]); + +/** + * @param {AstPath} path + * @returns {boolean} + */ +function willPrintOwnComments(path) { + const { key, parent } = path; + if ( + (key === "types" && isUnionType(parent)) || + (key === "argument" && parent.type === "JSXSpreadAttribute") || + (key === "expression" && parent.type === "JSXSpreadChild") || + (key === "superClass" && + (parent.type === "ClassDeclaration" || + parent.type === "ClassExpression")) || + ((key === "id" || key === "typeParameters") && + isClassOrInterface(parent)) || + // Not tested, don't know how to + (key === "patterns" && parent.type === "MatchOrPattern") + ) { + return true; + } + + const { node } = path; + if (hasNodeIgnoreComment(node)) { + return false; + } + + return isJsxElement(node) || isUnionType(node); +} + +export default willPrintOwnComments; diff --git a/src/language-js/embed/css.js b/src/language-js/embed/css.js index 393862ed8..f7a76de3d 100644 --- a/src/language-js/embed/css.js +++ b/src/language-js/embed/css.js @@ -6,10 +6,10 @@ import { replaceEndOfLine, softline, } from "../../document/index.js"; -import isNonEmptyArray from "../../utils/is-non-empty-array.js"; +import isNonEmptyArray from "../../utilities/is-non-empty-array.js"; import { printTemplateExpressions } from "../print/template-literal.js"; -import isNodeMatches from "../utils/is-node-matches.js"; -import { isAngularComponentStyles } from "./utils.js"; +import isNodeMatches from "../utilities/is-node-matches.js"; +import { isAngularComponentStyles } from "./utilities.js"; async function printEmbedCss(textToDoc, print, path /* , options*/) { const { node } = path; diff --git a/src/language-js/embed/graphql.js b/src/language-js/embed/graphql.js index 97b35102f..74fe61013 100644 --- a/src/language-js/embed/graphql.js +++ b/src/language-js/embed/graphql.js @@ -3,7 +3,7 @@ import { escapeTemplateCharacters, printTemplateExpressions, } from "../print/template-literal.js"; -import { hasLanguageComment } from "./utils.js"; +import { hasLanguageComment } from "./utilities.js"; async function printEmbedGraphQL(textToDoc, print, path /* , options*/) { const { node } = path; diff --git a/src/language-js/embed/html.js b/src/language-js/embed/html.js index 68476d354..8d04d30f9 100644 --- a/src/language-js/embed/html.js +++ b/src/language-js/embed/html.js @@ -10,7 +10,7 @@ import { printTemplateExpressions, uncookTemplateElementValue, } from "../print/template-literal.js"; -import { hasLanguageComment, isAngularComponentTemplate } from "./utils.js"; +import { hasLanguageComment, isAngularComponentTemplate } from "./utilities.js"; // The counter is needed to distinguish nested embeds. let htmlTemplateLiteralCounter = 0; diff --git a/src/language-js/embed/utils.js b/src/language-js/embed/utilities.js similarity index 98% rename from src/language-js/embed/utils.js rename to src/language-js/embed/utilities.js index 9737a34c7..86ff723ac 100644 --- a/src/language-js/embed/utils.js +++ b/src/language-js/embed/utilities.js @@ -3,7 +3,7 @@ import { hasComment, isArrayExpression, isObjectProperty, -} from "../utils/index.js"; +} from "../utilities/index.js"; const angularComponentObjectExpressionPredicates = [ (node, name) => node.type === "ObjectExpression" && name === "properties", diff --git a/src/language-js/languages.evaluate.js b/src/language-js/languages.evaluate.js index 9e6b43d1e..d618250e7 100644 --- a/src/language-js/languages.evaluate.js +++ b/src/language-js/languages.evaluate.js @@ -1,5 +1,5 @@ import * as linguistLanguages from "linguist-languages"; -import createLanguage from "../utils/create-language.js"; +import createLanguage from "../utilities/create-language.js"; const languages = [ createLanguage(linguistLanguages.JavaScript, (data) => ({ diff --git a/src/language-js/needs-parens.js b/src/language-js/parentheses/needs-parentheses.js similarity index 99% rename from src/language-js/needs-parens.js rename to src/language-js/parentheses/needs-parentheses.js index 200fd28f3..f6e4b6303 100644 --- a/src/language-js/needs-parens.js +++ b/src/language-js/parentheses/needs-parentheses.js @@ -1,4 +1,4 @@ -import isNonEmptyArray from "../utils/is-non-empty-array.js"; +import isNonEmptyArray from "../../utilities/is-non-empty-array.js"; import { createTypeCheckFunction, getFunctionParameters, @@ -20,17 +20,17 @@ import { isUnionType, shouldFlatten, startsWithNoLookaheadToken, -} from "./utils/index.js"; +} from "../utilities/index.js"; /** - * @import AstPath from "../common/ast-path.js" + * @import AstPath from "../../common/ast-path.js" */ /** * @param {AstPath} path * @returns {boolean} */ -function needsParens(path, options) { +function needsParentheses(path, options) { if (path.isRoot) { return false; } @@ -1145,13 +1145,14 @@ function shouldWrapFunctionForExportDefault(path, options) { // in some cases the function is already wrapped // (e.g. `export default (function() {})();`) // in this case we don't need to add extra parens - !needsParens(path, options) + !needsParentheses(path, options) ); } if ( !hasNakedLeftSide(node) || - (parent.type !== "ExportDefaultDeclaration" && needsParens(path, options)) + (parent.type !== "ExportDefaultDeclaration" && + needsParentheses(path, options)) ) { return false; } @@ -1346,4 +1347,4 @@ function canDecoratorExpressionUnparenthesized(node) { ); } -export default needsParens; +export default needsParentheses; diff --git a/src/language-js/parse/acorn.js b/src/language-js/parse/acorn.js index 98cb314e5..539b90233 100644 --- a/src/language-js/parse/acorn.js +++ b/src/language-js/parse/acorn.js @@ -1,16 +1,16 @@ import { Parser as AcornParser } from "acorn"; import acornJsx from "acorn-jsx"; import createError from "../../common/parser-create-error.js"; -import { tryCombinationsSync } from "../../utils/try-combinations.js"; +import { tryCombinationsSync } from "../../utilities/try-combinations.js"; import postprocess from "./postprocess/index.js"; -import createParser from "./utils/create-parser.js"; +import createParser from "./utilities/create-parser.js"; import { getSourceType, SOURCE_TYPE_COMBINATIONS, SOURCE_TYPE_COMMONJS, SOURCE_TYPE_MODULE, SOURCE_TYPE_SCRIPT, -} from "./utils/source-types.js"; +} from "./utilities/source-types.js"; /** @import {Options} from "acorn"; diff --git a/src/language-js/parse/babel.js b/src/language-js/parse/babel.js index f8957df1d..ab19cb6a2 100644 --- a/src/language-js/parse/babel.js +++ b/src/language-js/parse/babel.js @@ -1,16 +1,16 @@ import { parse as babelParse, parseExpression } from "@babel/parser"; -import getNextNonSpaceNonCommentCharacterIndex from "../../utils/get-next-non-space-non-comment-character-index.js"; -import { tryCombinationsSync } from "../../utils/try-combinations.js"; -import getShebang from "../utils/get-shebang.js"; +import getNextNonSpaceNonCommentCharacterIndex from "../../utilities/get-next-non-space-non-comment-character-index.js"; +import { tryCombinationsSync } from "../../utilities/try-combinations.js"; +import getShebang from "../utilities/get-shebang.js"; import postprocess from "./postprocess/index.js"; -import createBabelParseError from "./utils/create-babel-parse-error.js"; -import createParser from "./utils/create-parser.js"; +import createBabelParseError from "./utilities/create-babel-parse-error.js"; +import createParser from "./utilities/create-parser.js"; import { getSourceType, SOURCE_TYPE_COMMONJS, SOURCE_TYPE_MODULE, -} from "./utils/source-types.js"; -import wrapBabelExpression from "./utils/wrap-babel-expression.js"; +} from "./utilities/source-types.js"; +import wrapBabelExpression from "./utilities/wrap-babel-expression.js"; const createBabelParser = (options) => createParser(createParse(options)); diff --git a/src/language-js/parse/espree.js b/src/language-js/parse/espree.js index 5369d111e..79d04f028 100644 --- a/src/language-js/parse/espree.js +++ b/src/language-js/parse/espree.js @@ -1,12 +1,12 @@ import { parse as espreeParse } from "espree"; import createError from "../../common/parser-create-error.js"; -import { tryCombinationsSync } from "../../utils/try-combinations.js"; +import { tryCombinationsSync } from "../../utilities/try-combinations.js"; import postprocess from "./postprocess/index.js"; -import createParser from "./utils/create-parser.js"; +import createParser from "./utilities/create-parser.js"; import { getSourceType, SOURCE_TYPE_COMBINATIONS, -} from "./utils/source-types.js"; +} from "./utilities/source-types.js"; /** @import {Options} from "espree" */ diff --git a/src/language-js/parse/flow.js b/src/language-js/parse/flow.js index 578e4402f..c6d0f97b9 100644 --- a/src/language-js/parse/flow.js +++ b/src/language-js/parse/flow.js @@ -1,7 +1,7 @@ import flowParser from "flow-parser"; import createError from "../../common/parser-create-error.js"; import postprocess from "./postprocess/index.js"; -import createParser from "./utils/create-parser.js"; +import createParser from "./utilities/create-parser.js"; // https://github.com/facebook/flow/tree/main/packages/flow-parser#options // Keep this sync with `/scripts/sync-flow-test.js` diff --git a/src/language-js/parse/hermes.js b/src/language-js/parse/hermes.js index 0dd3d34a7..cc81c9047 100644 --- a/src/language-js/parse/hermes.js +++ b/src/language-js/parse/hermes.js @@ -1,7 +1,7 @@ import { parse as hermesParse } from "hermes-parser"; import createError from "../../common/parser-create-error.js"; import postprocess from "./postprocess/index.js"; -import createParser from "./utils/create-parser.js"; +import createParser from "./utilities/create-parser.js"; function createParseError(error) { let { message, loc } = error; diff --git a/src/language-js/parse/meriyah.js b/src/language-js/parse/meriyah.js index d4c51853b..75f6455a2 100644 --- a/src/language-js/parse/meriyah.js +++ b/src/language-js/parse/meriyah.js @@ -1,16 +1,16 @@ import { parse as meriyahParse } from "meriyah"; import createError from "../../common/parser-create-error.js"; -import { tryCombinationsSync } from "../../utils/try-combinations.js"; +import { tryCombinationsSync } from "../../utilities/try-combinations.js"; import postprocess from "./postprocess/index.js"; -import createParser from "./utils/create-parser.js"; +import createParser from "./utilities/create-parser.js"; import { getSourceType, SOURCE_TYPE_COMBINATIONS, -} from "./utils/source-types.js"; +} from "./utilities/source-types.js"; /** @import {ESTree as MeriyahESTree} from "meriyah"; -@import {SOURCE_TYPE_MODULE, SOURCE_TYPE_COMMONJS} from "./utils/source-types.js"; +@import {SOURCE_TYPE_MODULE, SOURCE_TYPE_COMMONJS} from "./utilities/source-types.js"; */ // https://github.com/meriyah/meriyah/blob/4676f60b6c149d7082bde2c9147f9ae2359c8075/src/parser.ts#L185 diff --git a/src/language-js/parse/oxc.js b/src/language-js/parse/oxc.js index 1e7e5d735..b6093d505 100644 --- a/src/language-js/parse/oxc.js +++ b/src/language-js/parse/oxc.js @@ -1,15 +1,15 @@ import indexToPosition from "index-to-position"; import { parse as oxcParse } from "oxc-parser"; import createError from "../../common/parser-create-error.js"; -import { tryCombinations } from "../../utils/try-combinations.js"; +import { tryCombinations } from "../../utilities/try-combinations.js"; import postprocess from "./postprocess/index.js"; -import createParser from "./utils/create-parser.js"; -import jsxRegexp from "./utils/jsx-regexp.evaluate.js"; +import createParser from "./utilities/create-parser.js"; +import jsxRegexp from "./utilities/jsx-regexp.evaluate.js"; import { getSourceType, SOURCE_TYPE_COMMONJS, SOURCE_TYPE_SCRIPT, -} from "./utils/source-types.js"; +} from "./utilities/source-types.js"; /** @import {ParseResult, ParserOptions as ParserOptionsWithoutExperimentalRawTransfer} from "oxc-parser" */ /** @typedef {Omit & { diff --git a/src/language-js/parse/postprocess/index.js b/src/language-js/parse/postprocess/index.js index f4c2a6fbe..5a4e1cc5f 100644 --- a/src/language-js/parse/postprocess/index.js +++ b/src/language-js/parse/postprocess/index.js @@ -1,10 +1,10 @@ import * as assert from "#universal/assert"; import { locEnd, locStart } from "../../loc.js"; -import createTypeCheckFunction from "../../utils/create-type-check-function.js"; -import getRaw from "../../utils/get-raw.js"; -import isBlockComment from "../../utils/is-block-comment.js"; -import isLineComment from "../../utils/is-line-comment.js"; -import isTypeCastComment from "../../utils/is-type-cast-comment.js"; +import createTypeCheckFunction from "../../utilities/create-type-check-function.js"; +import getRaw from "../../utilities/get-raw.js"; +import isBlockComment from "../../utilities/is-block-comment.js"; +import isLineComment from "../../utilities/is-line-comment.js"; +import isTypeCastComment from "../../utilities/is-type-cast-comment.js"; import mergeNestledJsdocComments from "./merge-nestled-jsdoc-comments.js"; import visitNode from "./visit-node.js"; diff --git a/src/language-js/parse/postprocess/merge-nestled-jsdoc-comments.js b/src/language-js/parse/postprocess/merge-nestled-jsdoc-comments.js index 549e7513c..53cf3108f 100644 --- a/src/language-js/parse/postprocess/merge-nestled-jsdoc-comments.js +++ b/src/language-js/parse/postprocess/merge-nestled-jsdoc-comments.js @@ -1,7 +1,7 @@ import { locEnd, locStart } from "../../loc.js"; -import isBlockComment from "../../utils/is-block-comment.js"; -import isIndentableBlockComment from "../../utils/is-indentable-block-comment.js"; -import isLineComment from "../../utils/is-line-comment.js"; +import isBlockComment from "../../utilities/is-block-comment.js"; +import isIndentableBlockComment from "../../utilities/is-indentable-block-comment.js"; +import isLineComment from "../../utilities/is-line-comment.js"; function mergeNestledJsdocComments(comments) { if (comments.length < 2) { diff --git a/src/language-js/parse/typescript.js b/src/language-js/parse/typescript.js index a2c6cbab7..87c1567b5 100644 --- a/src/language-js/parse/typescript.js +++ b/src/language-js/parse/typescript.js @@ -1,14 +1,14 @@ import { parse as parseTypeScript } from "@typescript-eslint/typescript-estree"; import createError from "../../common/parser-create-error.js"; -import { tryCombinationsSync } from "../../utils/try-combinations.js"; +import { tryCombinationsSync } from "../../utilities/try-combinations.js"; import postprocess from "./postprocess/index.js"; -import createParser from "./utils/create-parser.js"; -import jsxRegexp from "./utils/jsx-regexp.evaluate.js"; -import replaceHashbang from "./utils/replace-hashbang.js"; +import createParser from "./utilities/create-parser.js"; +import jsxRegexp from "./utilities/jsx-regexp.evaluate.js"; +import replaceHashbang from "./utilities/replace-hashbang.js"; import { getSourceType, SOURCE_TYPE_COMBINATIONS, -} from "./utils/source-types.js"; +} from "./utilities/source-types.js"; /** @import {TSESTreeOptions} from "@typescript-eslint/typescript-estree" */ diff --git a/src/language-js/parse/utils/create-babel-parse-error.js b/src/language-js/parse/utilities/create-babel-parse-error.js similarity index 100% rename from src/language-js/parse/utils/create-babel-parse-error.js rename to src/language-js/parse/utilities/create-babel-parse-error.js diff --git a/src/language-js/parse/utils/create-parser.js b/src/language-js/parse/utilities/create-parser.js similarity index 100% rename from src/language-js/parse/utils/create-parser.js rename to src/language-js/parse/utilities/create-parser.js diff --git a/src/language-js/parse/utils/jsx-regexp.evaluate.js b/src/language-js/parse/utilities/jsx-regexp.evaluate.js similarity index 100% rename from src/language-js/parse/utils/jsx-regexp.evaluate.js rename to src/language-js/parse/utilities/jsx-regexp.evaluate.js diff --git a/src/language-js/parse/utils/replace-hashbang.js b/src/language-js/parse/utilities/replace-hashbang.js similarity index 100% rename from src/language-js/parse/utils/replace-hashbang.js rename to src/language-js/parse/utilities/replace-hashbang.js diff --git a/src/language-js/parse/utils/source-types.js b/src/language-js/parse/utilities/source-types.js similarity index 100% rename from src/language-js/parse/utils/source-types.js rename to src/language-js/parse/utilities/source-types.js diff --git a/src/language-js/parse/utils/wrap-babel-expression.js b/src/language-js/parse/utilities/wrap-babel-expression.js similarity index 100% rename from src/language-js/parse/utils/wrap-babel-expression.js rename to src/language-js/parse/utilities/wrap-babel-expression.js diff --git a/src/language-js/pragma.js b/src/language-js/pragma.js index 3f7ad568d..1bef7e050 100644 --- a/src/language-js/pragma.js +++ b/src/language-js/pragma.js @@ -4,8 +4,8 @@ import { FORMAT_IGNORE_PRAGMAS, FORMAT_PRAGMA_TO_INSERT, FORMAT_PRAGMAS, -} from "../utils/pragma/pragma.evaluate.js"; -import getShebang from "./utils/get-shebang.js"; +} from "../utilities/pragma/pragma.evaluate.js"; +import getShebang from "./utilities/get-shebang.js"; function parseDocBlock(text) { const shebang = getShebang(text); diff --git a/src/language-js/print/angular.js b/src/language-js/print/angular.js index f208d0593..30285d466 100644 --- a/src/language-js/print/angular.js +++ b/src/language-js/print/angular.js @@ -1,6 +1,6 @@ import { group, join, line } from "../../document/index.js"; -import UnexpectedNodeError from "../../utils/unexpected-node-error.js"; -import { createTypeCheckFunction, hasNode } from "../utils/index.js"; +import UnexpectedNodeError from "../../utilities/unexpected-node-error.js"; +import { createTypeCheckFunction, hasNode } from "../utilities/index.js"; import { printBinaryishExpression } from "./binaryish.js"; /** @import AstPath from "../../common/ast-path.js" */ diff --git a/src/language-js/print/array-type.js b/src/language-js/print/array-type.js new file mode 100644 index 000000000..7f07f4b2f --- /dev/null +++ b/src/language-js/print/array-type.js @@ -0,0 +1,9 @@ +/* +- `TSArrayType` +- `ArrayTypeAnnotation` +*/ +function printArrayType(print) { + return [print("elementType"), "[]"]; +} + +export { printArrayType }; diff --git a/src/language-js/print/array.js b/src/language-js/print/array.js index 130782c52..9da195471 100644 --- a/src/language-js/print/array.js +++ b/src/language-js/print/array.js @@ -8,10 +8,10 @@ import { softline, } from "../../document/index.js"; import { printDanglingComments } from "../../main/comments/print.js"; -import hasNewline from "../../utils/has-newline.js"; -import isNextLineEmptyAfterIndex from "../../utils/is-next-line-empty.js"; -import skipInlineComment from "../../utils/skip-inline-comment.js"; -import skipTrailingComment from "../../utils/skip-trailing-comment.js"; +import hasNewline from "../../utilities/has-newline.js"; +import isNextLineEmptyAfterIndex from "../../utilities/is-next-line-empty.js"; +import skipInlineComment from "../../utilities/skip-inline-comment.js"; +import skipTrailingComment from "../../utilities/skip-trailing-comment.js"; import { locEnd, locStart } from "../loc.js"; import { CommentCheckFlags, @@ -21,7 +21,7 @@ import { isObjectExpression, isSignedNumericLiteral, shouldPrintComma, -} from "../utils/index.js"; +} from "../utilities/index.js"; import { printOptionalToken } from "./misc.js"; import { printTypeAnnotationProperty } from "./type-annotation.js"; diff --git a/src/language-js/print/arrow-function.js b/src/language-js/print/arrow-function.js index 89ad77fab..6eeccfb01 100644 --- a/src/language-js/print/arrow-function.js +++ b/src/language-js/print/arrow-function.js @@ -14,7 +14,7 @@ import { printCommentsSeparately, printDanglingComments, } from "../../main/comments/print.js"; -import getNextNonSpaceNonCommentCharacterIndex from "../../utils/get-next-non-space-non-comment-character-index.js"; +import getNextNonSpaceNonCommentCharacterIndex from "../../utilities/get-next-non-space-non-comment-character-index.js"; import { locEnd } from "../loc.js"; import { CommentCheckFlags, @@ -29,7 +29,7 @@ import { isTemplateOnItsOwnLine, shouldPrintComma, startsWithNoLookaheadToken, -} from "../utils/index.js"; +} from "../utilities/index.js"; import { printReturnType, shouldPrintParamsWithoutParens } from "./function.js"; import { printFunctionParameters } from "./function-parameters.js"; diff --git a/src/language-js/print/assignment.js b/src/language-js/print/assignment.js index 67159c106..938397233 100644 --- a/src/language-js/print/assignment.js +++ b/src/language-js/print/assignment.js @@ -8,8 +8,8 @@ import { lineSuffixBoundary, willBreak, } from "../../document/index.js"; -import getStringWidth from "../../utils/get-string-width.js"; -import isNonEmptyArray from "../../utils/is-non-empty-array.js"; +import getStringWidth from "../../utilities/get-string-width.js"; +import isNonEmptyArray from "../../utilities/is-non-empty-array.js"; import { getCallArguments, hasLeadingOwnLineComment, @@ -24,7 +24,7 @@ import { isStringLiteral, isTypeAlias, isUnionType, -} from "../utils/index.js"; +} from "../utilities/index.js"; import { shouldInlineLogicalExpression } from "./binaryish.js"; import { printCallExpression } from "./call-expression.js"; diff --git a/src/language-js/print/binaryish.js b/src/language-js/print/binaryish.js index 0c0310947..33d6022bf 100644 --- a/src/language-js/print/binaryish.js +++ b/src/language-js/print/binaryish.js @@ -26,8 +26,8 @@ import { isObjectExpression, isObjectProperty, shouldFlatten, -} from "../utils/index.js"; -import isTypeCastComment from "../utils/is-type-cast-comment.js"; +} from "../utilities/index.js"; +import isTypeCastComment from "../utilities/is-type-cast-comment.js"; /** @import {Doc} from "../../document/index.js" */ diff --git a/src/language-js/print/bind-expression.js b/src/language-js/print/bind-expression.js new file mode 100644 index 000000000..8f8bf5383 --- /dev/null +++ b/src/language-js/print/bind-expression.js @@ -0,0 +1,14 @@ +import { group, indent, softline } from "../../document/index.js"; + +function printBindExpression(path, options, print) { + return [ + print("object"), + group(indent([softline, printBindExpressionCallee(path, options, print)])), + ]; +} + +function printBindExpressionCallee(path, options, print) { + return ["::", print("callee")]; +} + +export { printBindExpression, printBindExpressionCallee }; diff --git a/src/language-js/print/block.js b/src/language-js/print/block.js index 5094c3b3c..d5b83521d 100644 --- a/src/language-js/print/block.js +++ b/src/language-js/print/block.js @@ -1,11 +1,11 @@ import { hardline, indent } from "../../document/index.js"; import { printDanglingComments } from "../../main/comments/print.js"; -import isNonEmptyArray from "../../utils/is-non-empty-array.js"; +import isNonEmptyArray from "../../utilities/is-non-empty-array.js"; import { CommentCheckFlags, hasComment, isNextLineEmpty, -} from "../utils/index.js"; +} from "../utilities/index.js"; import { printStatementSequence } from "./statement.js"; /** @import {Doc} from "../../document/index.js" */ diff --git a/src/language-js/print/call-arguments.js b/src/language-js/print/call-arguments.js index ae7e10d03..c076fc87c 100644 --- a/src/language-js/print/call-arguments.js +++ b/src/language-js/print/call-arguments.js @@ -34,7 +34,7 @@ import { isStringLiteral, iterateCallArgumentsPath, shouldPrintComma, -} from "../utils/index.js"; +} from "../utilities/index.js"; import { isConciselyPrintedArray } from "./array.js"; /* diff --git a/src/language-js/print/call-expression.js b/src/language-js/print/call-expression.js index a27a53567..7e3034d67 100644 --- a/src/language-js/print/call-expression.js +++ b/src/language-js/print/call-expression.js @@ -1,5 +1,5 @@ import { group, join } from "../../document/index.js"; -import pathNeedsParens from "../needs-parens.js"; +import needsParentheses from "../parentheses/needs-parentheses.js"; import { getCallArguments, hasComment, @@ -10,7 +10,7 @@ import { isTemplateOnItsOwnLine, isTestCall, iterateCallArgumentsPath, -} from "../utils/index.js"; +} from "../utilities/index.js"; import printCallArguments from "./call-arguments.js"; import printMemberChain from "./member-chain.js"; import { printOptionalToken } from "./misc.js"; @@ -80,7 +80,7 @@ function printCallExpression(path, options, print) { !isNewExpression && isMemberish(node.callee) && !path.call( - () => pathNeedsParens(path, options), + () => needsParentheses(path, options), "callee", ...(node.callee.type === "ChainExpression" ? ["expression"] : []), ) diff --git a/src/language-js/print/cast-expression.js b/src/language-js/print/cast-expression.js index fe9aca478..a411c9dc7 100644 --- a/src/language-js/print/cast-expression.js +++ b/src/language-js/print/cast-expression.js @@ -3,7 +3,7 @@ import { createTypeCheckFunction, isCallExpression, isMemberExpression, -} from "../utils/index.js"; +} from "../utilities/index.js"; const isSatisfiesExpression = createTypeCheckFunction([ "SatisfiesExpression", diff --git a/src/language-js/print/class-body.js b/src/language-js/print/class-body.js index 34d5dd4c6..3c292110d 100644 --- a/src/language-js/print/class-body.js +++ b/src/language-js/print/class-body.js @@ -7,8 +7,8 @@ import { softline, } from "../../document/index.js"; import { printDanglingComments } from "../../main/comments/print.js"; -import hasNewline from "../../utils/has-newline.js"; -import hasNewlineInRange from "../../utils/has-newline-in-range.js"; +import hasNewline from "../../utilities/has-newline.js"; +import hasNewlineInRange from "../../utilities/has-newline-in-range.js"; import { locEnd, locStart } from "../loc.js"; import { CommentCheckFlags, @@ -17,7 +17,7 @@ import { hasComment, isNextLineEmpty, shouldPrintComma, -} from "../utils/index.js"; +} from "../utilities/index.js"; import { shouldHugTheOnlyParameter } from "./function-parameters.js"; /* diff --git a/src/language-js/print/class.js b/src/language-js/print/class.js index 876b033b6..db49d5650 100644 --- a/src/language-js/print/class.js +++ b/src/language-js/print/class.js @@ -12,14 +12,14 @@ import { printCommentsSeparately, printDanglingComments, } from "../../main/comments/print.js"; -import createGroupIdMapper from "../../utils/create-group-id-mapper.js"; -import isNonEmptyArray from "../../utils/is-non-empty-array.js"; +import createGroupIdMapper from "../../utilities/create-group-id-mapper.js"; +import isNonEmptyArray from "../../utilities/is-non-empty-array.js"; import { CommentCheckFlags, createTypeCheckFunction, hasComment, isMemberExpression, -} from "../utils/index.js"; +} from "../utilities/index.js"; import { printAssignment } from "./assignment.js"; import { printClassMemberDecorators } from "./decorators.js"; import { printMethod } from "./function.js"; diff --git a/src/language-js/print/comment.js b/src/language-js/print/comment.js index 6121d3144..f2e50f35e 100644 --- a/src/language-js/print/comment.js +++ b/src/language-js/print/comment.js @@ -1,8 +1,8 @@ import { hardline, join, replaceEndOfLine } from "../../document/index.js"; import { locEnd, locStart } from "../loc.js"; -import isBlockComment from "../utils/is-block-comment.js"; -import isIndentableBlockComment from "../utils/is-indentable-block-comment.js"; -import isLineComment from "../utils/is-line-comment.js"; +import isBlockComment from "../utilities/is-block-comment.js"; +import isIndentableBlockComment from "../utilities/is-indentable-block-comment.js"; +import isLineComment from "../utilities/is-line-comment.js"; function printComment(path, options) { const comment = path.node; diff --git a/src/language-js/print/component.js b/src/language-js/print/component.js index e325837ec..e5f2040c3 100644 --- a/src/language-js/print/component.js +++ b/src/language-js/print/component.js @@ -7,9 +7,9 @@ import { softline, } from "../../document/index.js"; import { printDanglingComments } from "../../main/comments/print.js"; -import getNextNonSpaceNonCommentCharacter from "../../utils/get-next-non-space-non-comment-character.js"; +import getNextNonSpaceNonCommentCharacter from "../../utilities/get-next-non-space-non-comment-character.js"; import { locEnd } from "../loc.js"; -import { isNextLineEmpty, shouldPrintComma } from "../utils/index.js"; +import { isNextLineEmpty, shouldPrintComma } from "../utilities/index.js"; import { printDeclareToken } from "./misc.js"; /** diff --git a/src/language-js/print/decorators.js b/src/language-js/print/decorators.js index 7c6d893e9..ac0487211 100644 --- a/src/language-js/print/decorators.js +++ b/src/language-js/print/decorators.js @@ -5,11 +5,11 @@ import { join, line, } from "../../document/index.js"; -import hasNewline from "../../utils/has-newline.js"; -import isNonEmptyArray from "../../utils/is-non-empty-array.js"; +import hasNewline from "../../utilities/has-newline.js"; +import isNonEmptyArray from "../../utilities/is-non-empty-array.js"; import { hasSameLocStart, locEnd } from "../loc.js"; -import { isExportDeclaration } from "../utils/index.js"; -import isIgnored from "../utils/is-ignored.js"; +import { isExportDeclaration } from "../utilities/index.js"; +import isIgnored from "../utilities/is-ignored.js"; function printClassMemberDecorators(path, options, print) { const { node } = path; diff --git a/src/language-js/print/enum.js b/src/language-js/print/enum.js index 3ec414541..0df9fbbe7 100644 --- a/src/language-js/print/enum.js +++ b/src/language-js/print/enum.js @@ -13,6 +13,23 @@ function printEnumBody(path, options, print) { return printEnumMembers(path, options, print); } +function printFlowEnumBody(path, options, print) { + const { node } = path; + return [ + node.type === "EnumSymbolBody" || node.explicitType + ? `of ${node.type + .slice( + // `Enum` + 4, + // `Body` + -4, + ) + .toLowerCase()} ` + : "", + printEnumBody(path, options, print), + ]; +} + /* - `EnumBooleanMember`(flow) - `EnumNumberMember`(flow) @@ -66,4 +83,9 @@ function printEnumDeclaration(path, print) { ]; } -export { printEnumBody, printEnumDeclaration, printEnumMember }; +export { + printEnumBody, + printEnumDeclaration, + printEnumMember, + printFlowEnumBody, +}; diff --git a/src/language-js/print/estree.js b/src/language-js/print/estree.js index 616a01ae5..fbf9a1ef0 100644 --- a/src/language-js/print/estree.js +++ b/src/language-js/print/estree.js @@ -9,8 +9,8 @@ import { softline, } from "../../document/index.js"; import { printDanglingComments } from "../../main/comments/print.js"; -import hasNewline from "../../utils/has-newline.js"; -import UnexpectedNodeError from "../../utils/unexpected-node-error.js"; +import hasNewline from "../../utilities/has-newline.js"; +import UnexpectedNodeError from "../../utilities/unexpected-node-error.js"; import { locEnd, locStart } from "../loc.js"; import { CommentCheckFlags, @@ -25,8 +25,8 @@ import { isObjectExpression, needsHardlineAfterDanglingComment, startsWithNoLookaheadToken, -} from "../utils/index.js"; -import isBlockComment from "../utils/is-block-comment.js"; +} from "../utilities/index.js"; +import isBlockComment from "../utilities/is-block-comment.js"; import { printArray } from "./array.js"; import { printArrowFunction } from "./arrow-function.js"; import { @@ -34,6 +34,7 @@ import { printVariableDeclarator, } from "./assignment.js"; import { printBinaryishExpression } from "./binaryish.js"; +import { printBindExpression } from "./bind-expression.js"; import { printBlock } from "./block.js"; import { printCallExpression } from "./call-expression.js"; import { @@ -54,11 +55,9 @@ import { printLiteral } from "./literal.js"; import { printMemberExpression } from "./member.js"; import { adjustClause, - printBindExpressionCallee, printDeclareToken, printDefiniteToken, printOptionalToken, - printRestSpread, } from "./misc.js"; import { printExportDeclaration, @@ -67,6 +66,7 @@ import { } from "./module.js"; import { printObject } from "./object.js"; import { printProperty } from "./property.js"; +import { printRestElement, printSpreadElement } from "./rest-element.js"; import { printStatementSequence } from "./statement.js"; import { printTaggedTemplateExpression, @@ -140,12 +140,7 @@ function printEstree(path, options, print, args) { case "MetaProperty": return [print("meta"), ".", print("property")]; case "BindExpression": - return [ - print("object"), - group( - indent([softline, printBindExpressionCallee(path, options, print)]), - ), - ]; + return printBindExpression(path, options, print); case "Identifier": return [ node.name, @@ -157,10 +152,9 @@ function printEstree(path, options, print, args) { case "V8IntrinsicIdentifier": return ["%", node.name]; case "SpreadElement": - case "SpreadElementPattern": - case "SpreadPropertyPattern": + return printSpreadElement(path, print); case "RestElement": - return printRestSpread(path, print); + return printRestElement(path, print); case "FunctionDeclaration": case "FunctionExpression": return printFunction(path, options, print, args); diff --git a/src/language-js/print/expression-statement.js b/src/language-js/print/expression-statement.js index aa0f9cad1..835f3e78b 100644 --- a/src/language-js/print/expression-statement.js +++ b/src/language-js/print/expression-statement.js @@ -1,13 +1,13 @@ -import { - isVueEventBindingFunctionExpression, - isVueEventBindingMemberExpression, - unwrapVueEventBindingTsNode, -} from "../utils/vue-event-binding.js"; import { isSingleHtmlEventHandlerExpressionStatement, isSingleJsxExpressionStatementInMarkdown, isSingleVueEventBindingExpressionStatement, -} from "./semicolon.js"; +} from "../semicolon/semicolon.js"; +import { + isVueEventBindingFunctionExpression, + isVueEventBindingMemberExpression, + unwrapVueEventBindingTsNode, +} from "../utilities/vue-event-binding.js"; function shouldPrintSemicolon(path, options) { if (isSingleVueEventBindingExpressionStatement(path, options)) { diff --git a/src/language-js/print/flow.js b/src/language-js/print/flow.js index 4bc58347e..24230abfb 100644 --- a/src/language-js/print/flow.js +++ b/src/language-js/print/flow.js @@ -2,12 +2,13 @@ import * as assert from "#universal/assert"; import { replaceEndOfLine } from "../../document/index.js"; -import printNumber from "../../utils/print-number.js"; -import printString from "../../utils/print-string.js"; -import getRaw from "../utils/get-raw.js"; -import { isMethod } from "../utils/index.js"; -import isFlowKeywordType from "../utils/is-flow-keyword-type.js"; +import printNumber from "../../utilities/print-number.js"; +import printString from "../../utilities/print-string.js"; +import getRaw from "../utilities/get-raw.js"; +import { isMethod } from "../utilities/index.js"; +import isFlowKeywordType from "../utilities/is-flow-keyword-type.js"; import { printArray } from "./array.js"; +import { printArrayType } from "./array-type.js"; import { printBinaryCastExpression } from "./cast-expression.js"; import { printClass, @@ -20,43 +21,39 @@ import { printComponentTypeParameter, } from "./component.js"; import { - printEnumBody, printEnumDeclaration, printEnumMember, + printFlowEnumBody, } from "./enum.js"; +import { printFunctionType } from "./function-type.js"; import { printDeclareHook, printHook, printHookTypeAnnotation, } from "./hook.js"; +import { printIndexedAccessType } from "./indexed-access-type.js"; +import { printInferType } from "./infer-type.js"; +import { printIntersectionType } from "./intersection-type.js"; import { printBigInt } from "./literal.js"; import { printFlowMappedTypeProperty } from "./mapped-type.js"; import { printMatch, printMatchCase, printMatchPattern } from "./match.js"; -import { - printDeclareToken, - printOptionalToken, - printRestSpread, -} from "./misc.js"; +import { printDeclareToken, printOptionalToken } from "./misc.js"; import { printExportDeclaration } from "./module.js"; +import { printOpaqueType } from "./opaque-type.js"; import { printPropertyKey } from "./property.js"; +import { printSpreadElement } from "./rest-element.js"; +import { printRestType } from "./rest-type.js"; import { printTernary } from "./ternary.js"; +import { printNamedTupleMember } from "./tuple.js"; +import { printTypeAlias } from "./type-alias.js"; import { - printArrayType, - printFunctionType, - printIndexedAccessType, - printInferType, - printIntersectionType, - printNamedTupleMember, - printOpaqueType, - printRestType, - printTypeAlias, printTypeAnnotation, printTypeAnnotationProperty, - printTypePredicate, - printTypeQuery, - printUnionType, } from "./type-annotation.js"; import { printTypeParameter, printTypeParameters } from "./type-parameters.js"; +import { printTypePredicate } from "./type-predicate.js"; +import { printTypeQuery } from "./type-query.js"; +import { printUnionType } from "./union-type.js"; function printFlow(path, options, print) { const { node } = path; @@ -165,19 +162,7 @@ function printFlow(path, options, print) { case "EnumBigIntBody": case "EnumStringBody": case "EnumSymbolBody": - return [ - node.type === "EnumSymbolBody" || node.explicitType - ? `of ${node.type - .slice( - // `Enum` - 4, - // `Body` - -4, - ) - .toLowerCase()} ` - : "", - printEnumBody(path, options, print), - ]; + return printFlowEnumBody(path, options, print); case "EnumBooleanMember": case "EnumNumberMember": @@ -275,7 +260,7 @@ function printFlow(path, options, print) { ]; // Same as `RestElement` case "ObjectTypeSpreadProperty": - return printRestSpread(path, print); + return printSpreadElement(path, print); case "QualifiedTypeofIdentifier": case "QualifiedTypeIdentifier": return [print("qualification"), ".", print("id")]; diff --git a/src/language-js/print/function-parameters.js b/src/language-js/print/function-parameters.js index 928368565..2cfb316a8 100644 --- a/src/language-js/print/function-parameters.js +++ b/src/language-js/print/function-parameters.js @@ -10,8 +10,8 @@ import { willBreak, } from "../../document/index.js"; import { printDanglingComments } from "../../main/comments/print.js"; -import getNextNonSpaceNonCommentCharacter from "../../utils/get-next-non-space-non-comment-character.js"; -import isNonEmptyArray from "../../utils/is-non-empty-array.js"; +import getNextNonSpaceNonCommentCharacter from "../../utilities/get-next-non-space-non-comment-character.js"; +import isNonEmptyArray from "../../utilities/is-non-empty-array.js"; import { locEnd } from "../loc.js"; import { getFunctionParameters, @@ -27,7 +27,7 @@ import { isTypeAnnotationAFunction, iterateFunctionParametersPath, shouldPrintComma, -} from "../utils/index.js"; +} from "../utilities/index.js"; /** @import AstPath from "../../common/ast-path.js" */ diff --git a/src/language-js/print/function-type.js b/src/language-js/print/function-type.js new file mode 100644 index 000000000..5f1e094c8 --- /dev/null +++ b/src/language-js/print/function-type.js @@ -0,0 +1,95 @@ +import { group } from "../../document/index.js"; +import { hasSameLocStart } from "../loc.js"; +import { isFlowObjectTypePropertyAFunction } from "../utilities/index.js"; +import { printClassMemberSemicolon } from "./class.js"; +import { + printFunctionParameters, + shouldGroupFunctionParameters, +} from "./function-parameters.js"; +import { printAbstractToken } from "./misc.js"; +import { printTypeAnnotationProperty } from "./type-annotation.js"; + +/** + * @import {Doc} from "../../document/index.js" + */ + +/* +- `TSFunctionType` (TypeScript) +- `TSCallSignatureDeclaration` (TypeScript) +- `TSConstructorType` (TypeScript) +- `TSConstructSignatureDeclaration` (TypeScript) +- `FunctionTypeAnnotation` (Flow) +*/ +function printFunctionType(path, options, print) { + const { node } = path; + /** @type {Doc[]} */ + const parts = [ + // `TSConstructorType` only + printAbstractToken(path), + ]; + + if ( + node.type === "TSConstructorType" || + node.type === "TSConstructSignatureDeclaration" + ) { + parts.push("new "); + } + + let parametersDoc = printFunctionParameters( + path, + options, + print, + /* shouldExpandArgument */ false, + /* shouldPrintTypeParameters */ true, + ); + + const returnTypeDoc = []; + // `flow` doesn't wrap the `returnType` with `TypeAnnotation`, so the colon + // needs to be added separately. + if (node.type === "FunctionTypeAnnotation") { + returnTypeDoc.push( + isFlowArrowFunctionTypeAnnotation(path) ? " => " : ": ", + print("returnType"), + ); + } else { + returnTypeDoc.push(printTypeAnnotationProperty(path, print, "returnType")); + } + + if (shouldGroupFunctionParameters(node, returnTypeDoc)) { + parametersDoc = group(parametersDoc); + } + + parts.push(parametersDoc, returnTypeDoc); + + return [ + group(parts), + node.type === "TSConstructSignatureDeclaration" || + node.type === "TSCallSignatureDeclaration" + ? printClassMemberSemicolon(path, options) + : "", + ]; +} + +/* +`FunctionTypeAnnotation` is ambiguous: +- `declare function foo(a: B): void;` +- `var A: (a: B) => void;` +*/ +function isFlowArrowFunctionTypeAnnotation(path) { + const { node, parent } = path; + return ( + node.type === "FunctionTypeAnnotation" && + (isFlowObjectTypePropertyAFunction(parent) || + !( + ((parent.type === "ObjectTypeProperty" || + parent.type === "ObjectTypeInternalSlot") && + !parent.variance && + !parent.optional && + hasSameLocStart(parent, node)) || + parent.type === "ObjectTypeCallProperty" || + path.getParentNode(2)?.type === "DeclareFunction" + )) + ); +} + +export { printFunctionType }; diff --git a/src/language-js/print/function.js b/src/language-js/print/function.js index c2c9d2f11..c0cc75b37 100644 --- a/src/language-js/print/function.js +++ b/src/language-js/print/function.js @@ -7,7 +7,7 @@ import { softline, } from "../../document/index.js"; import { printDanglingComments } from "../../main/comments/print.js"; -import hasNewlineInRange from "../../utils/has-newline-in-range.js"; +import hasNewlineInRange from "../../utilities/has-newline-in-range.js"; import { locEnd, locStart } from "../loc.js"; import { CommentCheckFlags, @@ -21,7 +21,7 @@ import { isCallExpression, isJsxElement, isMethod, -} from "../utils/index.js"; +} from "../utilities/index.js"; import { printFunctionParameters, shouldBreakFunctionParameters, diff --git a/src/language-js/print/index-signature.js b/src/language-js/print/index-signature.js new file mode 100644 index 000000000..4c5dd374b --- /dev/null +++ b/src/language-js/print/index-signature.js @@ -0,0 +1,43 @@ +import { + group, + ifBreak, + indent, + join, + softline, +} from "../../document/index.js"; +import { shouldPrintComma } from "../utilities/index.js"; +import { printClassMemberSemicolon } from "./class.js"; +import { printTypeAnnotationProperty } from "./type-annotation.js"; + +function printIndexSignature(path, options, print) { + const { node } = path; + // The typescript parser accepts multiple parameters here. If you're + // using them, it makes sense to have a trailing comma. But if you + // aren't, this is more like a computed property name than an array. + // So we leave off the trailing comma when there's just one parameter. + const trailingComma = + node.parameters.length > 1 + ? ifBreak(shouldPrintComma(options) ? "," : "") + : ""; + + const parametersGroup = group([ + indent([softline, join([", ", softline], path.map(print, "parameters"))]), + trailingComma, + softline, + ]); + + const isClassMember = path.key === "body" && path.parent.type === "ClassBody"; + + return [ + // `static` only allowed in class member + isClassMember && node.static ? "static " : "", + node.readonly ? "readonly " : "", + "[", + node.parameters ? parametersGroup : "", + "]", + printTypeAnnotationProperty(path, print), + printClassMemberSemicolon(path, options), + ]; +} + +export { printIndexSignature }; diff --git a/src/language-js/print/index.js b/src/language-js/print/index.js index 9532c9338..f2d53b9d8 100644 --- a/src/language-js/print/index.js +++ b/src/language-js/print/index.js @@ -1,15 +1,15 @@ import { group, indent, inheritLabel, line } from "../../document/index.js"; -import isNonEmptyArray from "../../utils/is-non-empty-array.js"; +import isNonEmptyArray from "../../utilities/is-non-empty-array.js"; import { locEnd, locStart } from "../loc.js"; -import pathNeedsParens from "../needs-parens.js"; -import { createTypeCheckFunction } from "../utils/index.js"; -import isIgnored from "../utils/is-ignored.js"; +import needsParentheses from "../parentheses/needs-parentheses.js"; +import { shouldPrintLeadingSemicolon } from "../semicolon/semicolon.js"; +import { createTypeCheckFunction } from "../utilities/index.js"; +import isIgnored from "../utilities/is-ignored.js"; import { printAngular } from "./angular.js"; import { printDecorators } from "./decorators.js"; import { printEstree } from "./estree.js"; import { printFlow } from "./flow.js"; import { printJsx } from "./jsx.js"; -import { shouldPrintLeadingSemicolon } from "./semicolon.js"; import { printTypescript } from "./typescript.js"; /** @@ -81,7 +81,7 @@ function print(path, options, print, args) { return inheritLabel(doc, (doc) => group([decoratorsDoc, doc])); } - const needsParens = pathNeedsParens(path, options); + const needsParens = needsParentheses(path, options); const needsSemi = shouldPrintLeadingSemicolon(path, options); if (!decoratorsDoc && !needsParens && !needsSemi) { diff --git a/src/language-js/print/indexed-access-type.js b/src/language-js/print/indexed-access-type.js new file mode 100644 index 000000000..f5037daea --- /dev/null +++ b/src/language-js/print/indexed-access-type.js @@ -0,0 +1,18 @@ +import { printOptionalToken } from "./misc.js"; + +/* +- `TSIndexedAccessType`(TypeScript) +- `IndexedAccessType`(flow) +- `OptionalIndexedAccessType`(flow) +*/ +function printIndexedAccessType(path, options, print) { + return [ + print("objectType"), + printOptionalToken(path), + "[", + print("indexType"), + "]", + ]; +} + +export { printIndexedAccessType }; diff --git a/src/language-js/print/infer-type.js b/src/language-js/print/infer-type.js new file mode 100644 index 000000000..efd00fd57 --- /dev/null +++ b/src/language-js/print/infer-type.js @@ -0,0 +1,9 @@ +/* +- `TSInferType`(TypeScript) +- `InferTypeAnnotation`(flow) +*/ +function printInferType(path, options, print) { + return ["infer ", print("typeParameter")]; +} + +export { printInferType }; diff --git a/src/language-js/print/intersection-type.js b/src/language-js/print/intersection-type.js new file mode 100644 index 000000000..92626d989 --- /dev/null +++ b/src/language-js/print/intersection-type.js @@ -0,0 +1,43 @@ +import { group, indent, line } from "../../document/index.js"; +import { hasLeadingOwnLineComment, isObjectType } from "../utilities/index.js"; + +// `TSIntersectionType` and `IntersectionTypeAnnotation` +function printIntersectionType(path, options, print) { + let wasIndented = false; + return group( + path.map(({ isFirst, previous, node, index }) => { + const doc = print(); + if (isFirst) { + return doc; + } + + const currentIsObjectType = isObjectType(node); + const previousIsObjectType = isObjectType(previous); + + // If both are objects, don't indent + if (previousIsObjectType && currentIsObjectType) { + return [" & ", wasIndented ? indent(doc) : doc]; + } + + if ( + // If no object is involved, go to the next line if it breaks + (!previousIsObjectType && !currentIsObjectType) || + hasLeadingOwnLineComment(options.originalText, node) + ) { + if (options.experimentalOperatorPosition === "start") { + return indent([line, "& ", doc]); + } + return indent([" &", line, doc]); + } + + // If you go from object to non-object or vis-versa, then inline it + if (index > 1) { + wasIndented = true; + } + + return [" & ", index > 1 ? indent(doc) : doc]; + }, "types"), + ); +} + +export { printIntersectionType }; diff --git a/src/language-js/print/js-doc-type.js b/src/language-js/print/js-doc-type.js new file mode 100644 index 000000000..8e21c30e5 --- /dev/null +++ b/src/language-js/print/js-doc-type.js @@ -0,0 +1,13 @@ +import { printTypeAnnotationProperty } from "./type-annotation.js"; + +// `TSJSDocNullableType`, `TSJSDocNonNullableType` +function printJSDocType(path, print, token) { + const { node } = path; + return [ + node.postfix ? "" : token, + printTypeAnnotationProperty(path, print), + node.postfix ? token : "", + ]; +} + +export { printJSDocType }; diff --git a/src/language-js/print/jsx.js b/src/language-js/print/jsx.js index 41d2065ed..b60e84ff8 100644 --- a/src/language-js/print/jsx.js +++ b/src/language-js/print/jsx.js @@ -18,11 +18,11 @@ import { printComments, printDanglingComments, } from "../../main/comments/print.js"; -import getPreferredQuote from "../../utils/get-preferred-quote.js"; -import UnexpectedNodeError from "../../utils/unexpected-node-error.js"; -import WhitespaceUtils from "../../utils/whitespace-utils.js"; -import pathNeedsParens from "../needs-parens.js"; -import getRaw from "../utils/get-raw.js"; +import getPreferredQuote from "../../utilities/get-preferred-quote.js"; +import UnexpectedNodeError from "../../utilities/unexpected-node-error.js"; +import WhitespaceUtilities from "../../utilities/whitespace-utilities.js"; +import needsParentheses from "../parentheses/needs-parentheses.js"; +import getRaw from "../utilities/get-raw.js"; import { CommentCheckFlags, createTypeCheckFunction, @@ -34,7 +34,7 @@ import { isJsxElement, isObjectExpression, isStringLiteral, -} from "../utils/index.js"; +} from "../utilities/index.js"; /* Only the following are treated as whitespace inside JSX. @@ -44,7 +44,7 @@ Only the following are treated as whitespace inside JSX. - U+000D CR - U+0009 TAB */ -const jsxWhitespaceUtils = new WhitespaceUtils(" \n\r\t"); +const jsxWhitespace = new WhitespaceUtilities(" \n\r\t"); const isEmptyStringOrAnyLine = (doc) => doc === "" || doc === line || doc === hardline || doc === softline; @@ -126,7 +126,7 @@ function printJsxElementInternal(path, options, print) { const isMdxBlock = path.parent.rootMarker === "mdx"; const rawJsxWhitespace = options.singleQuote ? "{' '}" : '{" "}'; - const jsxWhitespace = isMdxBlock + const whitespace = isMdxBlock ? line : ifBreak([rawJsxWhitespace, softline], " "); @@ -136,7 +136,7 @@ function printJsxElementInternal(path, options, print) { path, options, print, - jsxWhitespace, + whitespace, isFacebookTranslationTag, ); @@ -157,15 +157,15 @@ function printJsxElementInternal(path, options, print) { const isLineFollowedByJsxWhitespace = (children[i] === softline || children[i] === hardline) && children[i + 1] === "" && - children[i + 2] === jsxWhitespace; + children[i + 2] === whitespace; const isJsxWhitespaceFollowedByLine = - children[i] === jsxWhitespace && + children[i] === whitespace && children[i + 1] === "" && (children[i + 2] === softline || children[i + 2] === hardline); const isDoubleJsxWhitespace = - children[i] === jsxWhitespace && + children[i] === whitespace && children[i + 1] === "" && - children[i + 2] === jsxWhitespace; + children[i + 2] === whitespace; const isPairOfHardOrSoftLines = (children[i] === softline && children[i + 1] === "" && @@ -216,7 +216,7 @@ function printJsxElementInternal(path, options, print) { for (const [i, child] of children.entries()) { // There are a number of situations where we need to ensure we display // whitespace as `{" "}` when outputting this element over multiple lines. - if (child === jsxWhitespace) { + if (child === whitespace) { if (i === 1 && isEmptyDoc(children[i - 1])) { if (children.length === 2) { // Solitary whitespace @@ -317,7 +317,7 @@ function printJsxChildren( path, options, print, - jsxWhitespace, + whitespace, isFacebookTranslationTag, ) { /** @type {Doc} */ @@ -342,10 +342,7 @@ function printJsxChildren( // Contains a non-whitespace character if (isMeaningfulJsxText(node)) { - const words = jsxWhitespaceUtils.split( - text, - /* captureWhitespace */ true, - ); + const words = jsxWhitespace.split(text, /* captureWhitespace */ true); // Starts with whitespace if (words[0] === "") { @@ -360,7 +357,7 @@ function printJsxChildren( ), ); } else { - pushLine(jsxWhitespace); + pushLine(whitespace); } words.shift(); } @@ -396,7 +393,7 @@ function printJsxChildren( ), ); } else { - pushLine(jsxWhitespace); + pushLine(whitespace); } } else { pushLine( @@ -415,7 +412,7 @@ function printJsxChildren( pushLine(hardline); } } else { - pushLine(jsxWhitespace); + pushLine(whitespace); } } else { const printedChild = print(); @@ -424,8 +421,8 @@ function printJsxChildren( const directlyFollowedByMeaningfulText = next && isMeaningfulJsxText(next); if (directlyFollowedByMeaningfulText) { - const trimmed = jsxWhitespaceUtils.trim(getRaw(next)); - const [firstWord] = jsxWhitespaceUtils.split(trimmed); + const trimmed = jsxWhitespace.trim(getRaw(next)); + const [firstWord] = jsxWhitespace.split(trimmed); pushLine( separatorNoWhitespace( isFacebookTranslationTag, @@ -505,7 +502,7 @@ function maybeWrapJsxElementInParens(path, elem, options) { } const shouldBreak = shouldBreakJsxElement(path); - const needsParens = pathNeedsParens(path, options); + const needsParens = needsParentheses(path, options); return group( [ @@ -866,7 +863,7 @@ function isEmptyJsxElement(node) { function isMeaningfulJsxText(node) { return ( node.type === "JSXText" && - (jsxWhitespaceUtils.hasNonWhitespaceCharacter(getRaw(node)) || + (jsxWhitespace.hasNonWhitespaceCharacter(getRaw(node)) || !/\n/u.test(getRaw(node))) ); } diff --git a/src/language-js/print/literal.js b/src/language-js/print/literal.js index da06fa30a..aa1549118 100644 --- a/src/language-js/print/literal.js +++ b/src/language-js/print/literal.js @@ -1,6 +1,6 @@ import { replaceEndOfLine } from "../../document/index.js"; -import printNumber from "../../utils/print-number.js"; -import printString from "../../utils/print-string.js"; +import printNumber from "../../utilities/print-number.js"; +import printString from "../../utilities/print-string.js"; /** * @import {Node} from "../types/estree.js" diff --git a/src/language-js/print/mapped-type.js b/src/language-js/print/mapped-type.js index 2f3102ed1..5784272f4 100644 --- a/src/language-js/print/mapped-type.js +++ b/src/language-js/print/mapped-type.js @@ -7,10 +7,10 @@ import { softline, } from "../../document/index.js"; import { printDanglingComments } from "../../main/comments/print.js"; -import hasNewlineInRange from "../../utils/has-newline-in-range.js"; +import hasNewlineInRange from "../../utilities/has-newline-in-range.js"; import { locStart } from "../loc.js"; -import getTextWithoutComments from "../utils/get-text-without-comments.js"; -import { CommentCheckFlags, hasComment } from "../utils/index.js"; +import getTextWithoutComments from "../utilities/get-text-without-comments.js"; +import { CommentCheckFlags, hasComment } from "../utilities/index.js"; import { printClassMemberSemicolon } from "./class.js"; /** diff --git a/src/language-js/print/match.js b/src/language-js/print/match.js index 12b42e91a..b97bbf443 100644 --- a/src/language-js/print/match.js +++ b/src/language-js/print/match.js @@ -12,14 +12,14 @@ import { printComments, printDanglingComments, } from "../../main/comments/print.js"; -import pathNeedsParens from "../needs-parens.js"; +import needsParentheses from "../parentheses/needs-parentheses.js"; import { CommentCheckFlags, createTypeCheckFunction, hasComment, hasLeadingOwnLineComment, isNextLineEmpty, -} from "../utils/index.js"; +} from "../utilities/index.js"; /* - `MatchExpression` (Flow) @@ -233,7 +233,7 @@ function printMatchOrPattern(path, options, print) { const code = [ifBreak(["| "]), join([line, "| "], printed)]; - if (pathNeedsParens(path, options)) { + if (needsParentheses(path, options)) { return group([indent([ifBreak([softline]), code]), softline]); } diff --git a/src/language-js/print/member-chain.js b/src/language-js/print/member-chain.js index 8cf14979f..46dbc3fd4 100644 --- a/src/language-js/print/member-chain.js +++ b/src/language-js/print/member-chain.js @@ -9,10 +9,10 @@ import { willBreak, } from "../../document/index.js"; import { printComments } from "../../main/comments/print.js"; -import getNextNonSpaceNonCommentCharacterIndex from "../../utils/get-next-non-space-non-comment-character-index.js"; -import isNextLineEmptyAfterIndex from "../../utils/is-next-line-empty.js"; +import getNextNonSpaceNonCommentCharacterIndex from "../../utilities/get-next-non-space-non-comment-character-index.js"; +import isNextLineEmptyAfterIndex from "../../utilities/is-next-line-empty.js"; import { locEnd } from "../loc.js"; -import pathNeedsParens from "../needs-parens.js"; +import needsParentheses from "../parentheses/needs-parentheses.js"; import { CommentCheckFlags, hasComment, @@ -24,10 +24,11 @@ import { isNextLineEmpty, isNumericLiteral, isSimpleCallArgument, -} from "../utils/index.js"; +} from "../utilities/index.js"; +import { printBindExpressionCallee } from "./bind-expression.js"; import printCallArguments from "./call-arguments.js"; import { printMemberLookup } from "./member.js"; -import { printBindExpressionCallee, printOptionalToken } from "./misc.js"; +import { printOptionalToken } from "./misc.js"; /** * @import {Doc} from "../../document/index.js" @@ -122,7 +123,7 @@ function printMemberChain(path, options, print) { } else if (isMemberish(node)) { printedNodes.unshift({ node, - needsParens: pathNeedsParens(path, options), + needsParens: needsParentheses(path, options), printed: printComments( path, isMemberExpression(node) diff --git a/src/language-js/print/member.js b/src/language-js/print/member.js index 52456d7bd..3fbcfa3c0 100644 --- a/src/language-js/print/member.js +++ b/src/language-js/print/member.js @@ -4,7 +4,7 @@ import { isCallExpression, isMemberExpression, isNumericLiteral, -} from "../utils/index.js"; +} from "../utilities/index.js"; import { printOptionalToken } from "./misc.js"; const isCallExpressionWithArguments = (node) => { diff --git a/src/language-js/print/method-signature.js b/src/language-js/print/method-signature.js new file mode 100644 index 000000000..3db90cb70 --- /dev/null +++ b/src/language-js/print/method-signature.js @@ -0,0 +1,49 @@ +import { group } from "../../document/index.js"; +import { printClassMemberSemicolon } from "./class.js"; +import { + printFunctionParameters, + shouldGroupFunctionParameters, +} from "./function-parameters.js"; +import { + printOptionalToken, + printTypeScriptAccessibilityToken, +} from "./misc.js"; +import { printTypeAnnotationProperty } from "./type-annotation.js"; + +function printMethodSignature(path, options, print) { + const { node } = path; + const parts = []; + const kind = node.kind && node.kind !== "method" ? `${node.kind} ` : ""; + parts.push( + printTypeScriptAccessibilityToken(node), + kind, + node.computed ? "[" : "", + print("key"), + node.computed ? "]" : "", + printOptionalToken(path), + ); + + const parametersDoc = printFunctionParameters( + path, + options, + print, + /* shouldExpandArgument */ false, + /* shouldPrintTypeParameters */ true, + ); + + const returnTypeDoc = printTypeAnnotationProperty(path, print, "returnType"); + const shouldGroupParameters = shouldGroupFunctionParameters( + node, + returnTypeDoc, + ); + + parts.push(shouldGroupParameters ? group(parametersDoc) : parametersDoc); + + if (node.returnType) { + parts.push(group(returnTypeDoc)); + } + + return [group(parts), printClassMemberSemicolon(path, options)]; +} + +export { printMethodSignature }; diff --git a/src/language-js/print/misc.js b/src/language-js/print/misc.js index bad1485a1..d3635dbc4 100644 --- a/src/language-js/print/misc.js +++ b/src/language-js/print/misc.js @@ -5,8 +5,7 @@ import { hasComment, isCallExpression, isMemberExpression, -} from "../utils/index.js"; -import { printTypeAnnotationProperty } from "./type-annotation.js"; +} from "../utilities/index.js"; /** * @import AstPath from "../../common/ast-path.js" @@ -98,10 +97,6 @@ function printAbstractToken({ node }) { return node.abstract || isTsAbstractNode(node) ? "abstract " : ""; } -function printBindExpressionCallee(path, options, print) { - return ["::", print("callee")]; -} - function adjustClause(node, clause, forceSpace) { if (node.type === "EmptyStatement") { return hasComment(node, CommentCheckFlags.Leading) ? [" ", clause] : clause; @@ -114,10 +109,6 @@ function adjustClause(node, clause, forceSpace) { return indent([line, clause]); } -function printRestSpread(path, print) { - return ["...", print("argument"), printTypeAnnotationProperty(path, print)]; -} - function printTypeScriptAccessibilityToken(node) { return node.accessibility ? node.accessibility + " " : ""; } @@ -125,10 +116,8 @@ function printTypeScriptAccessibilityToken(node) { export { adjustClause, printAbstractToken, - printBindExpressionCallee, printDeclareToken, printDefiniteToken, printOptionalToken, - printRestSpread, printTypeScriptAccessibilityToken, }; diff --git a/src/language-js/print/module-declaration.js b/src/language-js/print/module-declaration.js new file mode 100644 index 000000000..3ad87fc27 --- /dev/null +++ b/src/language-js/print/module-declaration.js @@ -0,0 +1,15 @@ +import { group } from "../../document/index.js"; +import { printDeclareToken } from "./misc.js"; + +function printModuleDeclaration(path, options, print) { + const { node } = path; + + return [ + printDeclareToken(path), + node.kind === "global" ? "" : `${node.kind} `, + print("id"), + node.body ? [" ", group(print("body"))] : options.semi ? ";" : "", + ]; +} + +export { printModuleDeclaration }; diff --git a/src/language-js/print/module.js b/src/language-js/print/module.js index e1bcf1386..ee4dbc6e7 100644 --- a/src/language-js/print/module.js +++ b/src/language-js/print/module.js @@ -9,11 +9,11 @@ import { softline, } from "../../document/index.js"; import { printDanglingComments } from "../../main/comments/print.js"; -import isNonEmptyArray from "../../utils/is-non-empty-array.js"; -import UnexpectedNodeError from "../../utils/unexpected-node-error.js"; +import isNonEmptyArray from "../../utilities/is-non-empty-array.js"; +import UnexpectedNodeError from "../../utilities/unexpected-node-error.js"; import { hasSameLoc, locEnd, locStart } from "../loc.js"; -import getRaw from "../utils/get-raw.js"; -import getTextWithoutComments from "../utils/get-text-without-comments.js"; +import getRaw from "../utilities/get-raw.js"; +import getTextWithoutComments from "../utilities/get-text-without-comments.js"; import { CommentCheckFlags, createTypeCheckFunction, @@ -21,7 +21,7 @@ import { isStringLiteral, needsHardlineAfterDanglingComment, shouldPrintComma, -} from "../utils/index.js"; +} from "../utilities/index.js"; import { printDecoratorsBeforeExport } from "./decorators.js"; import { printDeclareToken } from "./misc.js"; import { printObject } from "./object.js"; diff --git a/src/language-js/print/object.js b/src/language-js/print/object.js index c859dfb20..38ca29de2 100644 --- a/src/language-js/print/object.js +++ b/src/language-js/print/object.js @@ -8,11 +8,11 @@ import { softline, } from "../../document/index.js"; import { printDanglingComments } from "../../main/comments/print.js"; -import hasNewline from "../../utils/has-newline.js"; -import hasNewlineInRange from "../../utils/has-newline-in-range.js"; -import isNonEmptyArray from "../../utils/is-non-empty-array.js"; +import hasNewline from "../../utilities/has-newline.js"; +import hasNewlineInRange from "../../utilities/has-newline-in-range.js"; +import isNonEmptyArray from "../../utilities/is-non-empty-array.js"; import { locEnd, locStart } from "../loc.js"; -import getTextWithoutComments from "../utils/get-text-without-comments.js"; +import getTextWithoutComments from "../utilities/get-text-without-comments.js"; import { CommentCheckFlags, createTypeCheckFunction, @@ -21,7 +21,7 @@ import { isNextLineEmpty, isObjectType, shouldPrintComma, -} from "../utils/index.js"; +} from "../utilities/index.js"; import { shouldHugTheOnlyParameter } from "./function-parameters.js"; import { printOptionalToken } from "./misc.js"; import { printTypeAnnotationProperty } from "./type-annotation.js"; diff --git a/src/language-js/print/opaque-type.js b/src/language-js/print/opaque-type.js new file mode 100644 index 000000000..1a756447a --- /dev/null +++ b/src/language-js/print/opaque-type.js @@ -0,0 +1,45 @@ +import { group, indent, line } from "../../document/index.js"; +import { printDeclareToken } from "./misc.js"; + +/* +- `DeclareOpaqueType`(flow) +- `OpaqueType`(flow) +*/ +function printOpaqueType(path, options, print) { + const { node } = path; + const parts = [ + printDeclareToken(path), + "opaque type ", + print("id"), + print("typeParameters"), + ]; + + if (node.supertype) { + parts.push(": ", print("supertype")); + } + + if (node.lowerBound || node.upperBound) { + const lowerAndUpperBoundParts = []; + if (node.lowerBound) { + lowerAndUpperBoundParts.push( + indent([line, "super ", print("lowerBound")]), + ); + } + if (node.upperBound) { + lowerAndUpperBoundParts.push( + indent([line, "extends ", print("upperBound")]), + ); + } + parts.push(group(lowerAndUpperBoundParts)); + } + + if (node.impltype) { + parts.push(" = ", print("impltype")); + } + + parts.push(options.semi ? ";" : ""); + + return parts; +} + +export { printOpaqueType }; diff --git a/src/language-js/print/property.js b/src/language-js/print/property.js index 1d1898330..a1a68ac42 100644 --- a/src/language-js/print/property.js +++ b/src/language-js/print/property.js @@ -1,9 +1,9 @@ import isEs5IdentifierName from "is-es5-identifier-name"; import { printComments } from "../../main/comments/print.js"; -import printNumber from "../../utils/print-number.js"; -import printString from "../../utils/print-string.js"; -import getRaw from "../utils/get-raw.js"; -import { isNumericLiteral, isStringLiteral } from "../utils/index.js"; +import printNumber from "../../utilities/print-number.js"; +import printString from "../../utilities/print-string.js"; +import getRaw from "../utilities/get-raw.js"; +import { isNumericLiteral, isStringLiteral } from "../utilities/index.js"; import { printAssignment } from "./assignment.js"; const needsQuoteProps = new WeakMap(); diff --git a/src/language-js/print/rest-element.js b/src/language-js/print/rest-element.js new file mode 100644 index 000000000..84899f932 --- /dev/null +++ b/src/language-js/print/rest-element.js @@ -0,0 +1,10 @@ +import { printTypeAnnotationProperty } from "./type-annotation.js"; + +function printRestOrSpreadElement(path, print) { + return ["...", print("argument"), printTypeAnnotationProperty(path, print)]; +} + +export { + printRestOrSpreadElement as printRestElement, + printRestOrSpreadElement as printSpreadElement, +}; diff --git a/src/language-js/print/rest-type.js b/src/language-js/print/rest-type.js new file mode 100644 index 000000000..e0cc1b48a --- /dev/null +++ b/src/language-js/print/rest-type.js @@ -0,0 +1,17 @@ +/* +- `TSRestType`(TypeScript) +- `TupleTypeSpreadElement`(flow) +*/ +function printRestType(path, options, print) { + const { node } = path; + + return [ + "...", + ...(node.type === "TupleTypeSpreadElement" && node.label + ? [print("label"), ": "] + : []), + print("typeAnnotation"), + ]; +} + +export { printRestType }; diff --git a/src/language-js/print/statement.js b/src/language-js/print/statement.js index 2107fce90..80331cf35 100644 --- a/src/language-js/print/statement.js +++ b/src/language-js/print/statement.js @@ -1,5 +1,5 @@ import { hardline } from "../../document/index.js"; -import { isNextLineEmpty } from "../utils/index.js"; +import { isNextLineEmpty } from "../utilities/index.js"; /** * @import {Doc} from "../../document/index.js" diff --git a/src/language-js/print/template-literal.js b/src/language-js/print/template-literal.js index 05566ef3b..d6e483dba 100644 --- a/src/language-js/print/template-literal.js +++ b/src/language-js/print/template-literal.js @@ -11,9 +11,9 @@ import { printDocToString, softline, } from "../../document/index.js"; -import getIndentSize from "../../utils/get-indent-size.js"; -import getStringWidth from "../../utils/get-string-width.js"; -import hasNewlineInRange from "../../utils/has-newline-in-range.js"; +import getIndentSize from "../../utilities/get-indent-size.js"; +import getStringWidth from "../../utilities/get-string-width.js"; +import hasNewlineInRange from "../../utilities/has-newline-in-range.js"; import { locEnd, locStart } from "../loc.js"; import { CommentCheckFlags, @@ -22,7 +22,7 @@ import { isBinaryCastExpression, isBinaryish, isMemberExpression, -} from "../utils/index.js"; +} from "../utilities/index.js"; /** * @import {Doc} from "../../document/index.js" diff --git a/src/language-js/print/ternary-old.js b/src/language-js/print/ternary-old.js index 2d9202dc2..e5bb4464d 100644 --- a/src/language-js/print/ternary-old.js +++ b/src/language-js/print/ternary-old.js @@ -12,7 +12,7 @@ import { isCallExpression, isJsxElement, isMemberExpression, -} from "../utils/index.js"; +} from "../utilities/index.js"; /** * @import {Doc} from "../../document/index.js" diff --git a/src/language-js/print/ternary.js b/src/language-js/print/ternary.js index 941aa494c..b6ee65f51 100644 --- a/src/language-js/print/ternary.js +++ b/src/language-js/print/ternary.js @@ -9,9 +9,9 @@ import { softline, } from "../../document/index.js"; import { printDanglingComments } from "../../main/comments/print.js"; -import hasNewlineInRange from "../../utils/has-newline-in-range.js"; +import hasNewlineInRange from "../../utilities/has-newline-in-range.js"; import { locEnd, locStart } from "../loc.js"; -import pathNeedsParens from "../needs-parens.js"; +import needsParentheses from "../parentheses/needs-parentheses.js"; import { CommentCheckFlags, getComments, @@ -23,8 +23,8 @@ import { isLoneShortArgument, isMemberExpression, isSimpleExpressionByNodeCount, -} from "../utils/index.js"; -import isBlockComment from "../utils/is-block-comment.js"; +} from "../utilities/index.js"; +import isBlockComment from "../utilities/is-block-comment.js"; import { printTernaryOld } from "./ternary-old.js"; /** @@ -221,7 +221,8 @@ function printTernary(path, options, print, args) { const shouldExtraIndent = shouldExtraIndentForConditionalExpression(path); const breakClosingParen = shouldBreakClosingParen(node, parent); - const breakTSClosingParen = isTSConditional && pathNeedsParens(path, options); + const breakTSClosingParen = + isTSConditional && needsParentheses(path, options); const fillTab = !isBigTabs ? "" diff --git a/src/language-js/print/tuple.js b/src/language-js/print/tuple.js new file mode 100644 index 000000000..db94a7dd8 --- /dev/null +++ b/src/language-js/print/tuple.js @@ -0,0 +1,18 @@ +/* +- `TSNamedTupleMember`(TypeScript) +- `TupleTypeLabeledElement`(flow) +*/ +function printNamedTupleMember(path, options, print) { + const { node } = path; + + return [ + // `TupleTypeLabeledElement` only + node.variance ? print("variance") : "", + print("label"), + node.optional ? "?" : "", + ": ", + print("elementType"), + ]; +} + +export { printNamedTupleMember }; diff --git a/src/language-js/print/type-alias.js b/src/language-js/print/type-alias.js new file mode 100644 index 000000000..0ecdfbd36 --- /dev/null +++ b/src/language-js/print/type-alias.js @@ -0,0 +1,26 @@ +import { printAssignment } from "./assignment.js"; +import { printDeclareToken } from "./misc.js"; + +/* +- `DeclareTypeAlias`(flow) +- `TypeAlias`(flow) +- `TSTypeAliasDeclaration`(TypeScript) +*/ +function printTypeAlias(path, options, print) { + const { node } = path; + const parts = [ + printDeclareToken(path), + "type ", + print("id"), + print("typeParameters"), + ]; + + const rightPropertyName = + node.type === "TSTypeAliasDeclaration" ? "typeAnnotation" : "right"; + return [ + printAssignment(path, options, print, parts, " =", rightPropertyName), + options.semi ? ";" : "", + ]; +} + +export { printTypeAlias }; diff --git a/src/language-js/print/type-annotation.js b/src/language-js/print/type-annotation.js index 1f9eed093..d56a4e7f2 100644 --- a/src/language-js/print/type-annotation.js +++ b/src/language-js/print/type-annotation.js @@ -1,75 +1,16 @@ -import { - align, - group, - ifBreak, - indent, - join, - line, - softline, -} from "../../document/index.js"; -import { - printComments, - printCommentsSeparately, -} from "../../main/comments/print.js"; -import { hasSameLocStart } from "../loc.js"; -import pathNeedsParens from "../needs-parens.js"; import { CommentCheckFlags, - createTypeCheckFunction, hasComment, - hasLeadingOwnLineComment, - isConditionalType, - isFlowObjectTypePropertyAFunction, isObjectType, isSimpleType, - isTypeAlias, isUnionType, -} from "../utils/index.js"; -import { printAssignment } from "./assignment.js"; -import { printClassMemberSemicolon } from "./class.js"; -import { - printFunctionParameters, - shouldGroupFunctionParameters, -} from "./function-parameters.js"; -import { - printAbstractToken, - printDeclareToken, - printOptionalToken, -} from "./misc.js"; +} from "../utilities/index.js"; +import { shouldHugUnionType } from "./union-type.js"; /** * @import {Doc} from "../../document/index.js" */ -const isVoidType = createTypeCheckFunction([ - "VoidTypeAnnotation", - "TSVoidKeyword", - "NullLiteralTypeAnnotation", - "TSNullKeyword", -]); - -const isObjectLikeType = createTypeCheckFunction([ - "ObjectTypeAnnotation", - "TSTypeLiteral", - // This is a bit aggressive but captures Array<{x}> - "GenericTypeAnnotation", - "TSTypeReference", -]); - -function shouldHugUnionType(node) { - const { types } = node; - if (types.some((node) => hasComment(node))) { - return false; - } - - const objectType = types.find((node) => isObjectLikeType(node)); - if (!objectType) { - return false; - } - - return types.every((node) => node === objectType || isVoidType(node)); -} - function shouldHugType(node) { if (isSimpleType(node) || isObjectType(node)) { return true; @@ -82,353 +23,6 @@ function shouldHugType(node) { return false; } -/* -- `DeclareOpaqueType`(flow) -- `OpaqueType`(flow) -*/ -function printOpaqueType(path, options, print) { - const { node } = path; - const parts = [ - printDeclareToken(path), - "opaque type ", - print("id"), - print("typeParameters"), - ]; - - if (node.supertype) { - parts.push(": ", print("supertype")); - } - - if (node.lowerBound || node.upperBound) { - const lowerAndUpperBoundParts = []; - if (node.lowerBound) { - lowerAndUpperBoundParts.push( - indent([line, "super ", print("lowerBound")]), - ); - } - if (node.upperBound) { - lowerAndUpperBoundParts.push( - indent([line, "extends ", print("upperBound")]), - ); - } - parts.push(group(lowerAndUpperBoundParts)); - } - - if (node.impltype) { - parts.push(" = ", print("impltype")); - } - - parts.push(options.semi ? ";" : ""); - - return parts; -} - -/* -- `DeclareTypeAlias`(flow) -- `TypeAlias`(flow) -- `TSTypeAliasDeclaration`(TypeScript) -*/ -function printTypeAlias(path, options, print) { - const { node } = path; - const parts = [ - printDeclareToken(path), - "type ", - print("id"), - print("typeParameters"), - ]; - - const rightPropertyName = - node.type === "TSTypeAliasDeclaration" ? "typeAnnotation" : "right"; - return [ - printAssignment(path, options, print, parts, " =", rightPropertyName), - options.semi ? ";" : "", - ]; -} - -// `TSIntersectionType` and `IntersectionTypeAnnotation` -function printIntersectionType(path, options, print) { - let wasIndented = false; - return group( - path.map(({ isFirst, previous, node, index }) => { - const doc = print(); - if (isFirst) { - return doc; - } - - const currentIsObjectType = isObjectType(node); - const previousIsObjectType = isObjectType(previous); - - // If both are objects, don't indent - if (previousIsObjectType && currentIsObjectType) { - return [" & ", wasIndented ? indent(doc) : doc]; - } - - if ( - // If no object is involved, go to the next line if it breaks - (!previousIsObjectType && !currentIsObjectType) || - hasLeadingOwnLineComment(options.originalText, node) - ) { - if (options.experimentalOperatorPosition === "start") { - return indent([line, "& ", doc]); - } - return indent([" &", line, doc]); - } - - // If you go from object to non-object or vis-versa, then inline it - if (index > 1) { - wasIndented = true; - } - - return [" & ", index > 1 ? indent(doc) : doc]; - }, "types"), - ); -} - -// `TSUnionType` and `UnionTypeAnnotation` -function printUnionType(path, options, print) { - const { node } = path; - // single-line variation - // A | B | C - - // multi-line variation - // | A - // | B - // | C - - const { parent } = path; - - // If there's a leading comment, the parent is doing the indentation - const shouldIndent = - parent.type !== "TypeParameterInstantiation" && - (!isConditionalType(parent) || !options.experimentalTernaries) && - parent.type !== "TSTypeParameterInstantiation" && - parent.type !== "GenericTypeAnnotation" && - parent.type !== "TSTypeReference" && - parent.type !== "TSTypeAssertion" && - parent.type !== "TupleTypeAnnotation" && - parent.type !== "TSTupleType" && - !( - parent.type === "FunctionTypeParam" && - !parent.name && - path.grandparent.this !== parent - ) && - !( - (isTypeAlias(parent) || parent.type === "VariableDeclarator") && - hasLeadingOwnLineComment(options.originalText, node) - ) && - !( - isTypeAlias(parent) && - hasComment(parent.id, CommentCheckFlags.Trailing | CommentCheckFlags.Line) - ); - - // { - // a: string - // } | null | void - // should be inlined and not be printed in the multi-line variant - const shouldHug = shouldHugType(node); - - // We want to align the children but without its comment, so it looks like - // | child1 - // // comment - // | child2 - const printed = path.map(() => { - let printedType = print(); - if (!shouldHug) { - printedType = align(2, printedType); - } - - return printComments(path, printedType, options); - }, "types"); - - const { leading, trailing } = printCommentsSeparately(path, options); - - if (shouldHug) { - return [leading, join(" | ", printed), trailing]; - } - - const shouldAddStartLine = - shouldIndent && !hasLeadingOwnLineComment(options.originalText, node); - - const mainParts = [ - ifBreak([shouldAddStartLine ? line : "", "| "]), - join([line, "| "], printed), - ]; - - if (pathNeedsParens(path, options)) { - return [leading, group([indent(mainParts), softline]), trailing]; - } - - const parts = [leading, group(mainParts)]; - - if (parent.type === "TupleTypeAnnotation" || parent.type === "TSTupleType") { - const elementTypes = - parent[ - // TODO: Remove `types` when babel changes AST of `TupleTypeAnnotation` - parent.type === "TupleTypeAnnotation" && parent.types - ? "types" - : "elementTypes" - ]; - - if (elementTypes.length > 1) { - return [ - group([ - indent([ifBreak(["(", softline]), parts]), - softline, - ifBreak(")"), - ]), - trailing, - ]; - } - } - - return [group(shouldIndent ? indent(parts) : parts), trailing]; -} - -/* -`FunctionTypeAnnotation` is ambiguous: -- `declare function foo(a: B): void;` -- `var A: (a: B) => void;` -*/ -function isFlowArrowFunctionTypeAnnotation(path) { - const { node, parent } = path; - return ( - node.type === "FunctionTypeAnnotation" && - (isFlowObjectTypePropertyAFunction(parent) || - !( - ((parent.type === "ObjectTypeProperty" || - parent.type === "ObjectTypeInternalSlot") && - !parent.variance && - !parent.optional && - hasSameLocStart(parent, node)) || - parent.type === "ObjectTypeCallProperty" || - path.getParentNode(2)?.type === "DeclareFunction" - )) - ); -} - -/* -- `TSFunctionType` (TypeScript) -- `TSCallSignatureDeclaration` (TypeScript) -- `TSConstructorType` (TypeScript) -- `TSConstructSignatureDeclaration` (TypeScript) -- `FunctionTypeAnnotation` (Flow) -*/ -function printFunctionType(path, options, print) { - const { node } = path; - /** @type {Doc[]} */ - const parts = [ - // `TSConstructorType` only - printAbstractToken(path), - ]; - - if ( - node.type === "TSConstructorType" || - node.type === "TSConstructSignatureDeclaration" - ) { - parts.push("new "); - } - - let parametersDoc = printFunctionParameters( - path, - options, - print, - /* shouldExpandArgument */ false, - /* shouldPrintTypeParameters */ true, - ); - - const returnTypeDoc = []; - // `flow` doesn't wrap the `returnType` with `TypeAnnotation`, so the colon - // needs to be added separately. - if (node.type === "FunctionTypeAnnotation") { - returnTypeDoc.push( - isFlowArrowFunctionTypeAnnotation(path) ? " => " : ": ", - print("returnType"), - ); - } else { - returnTypeDoc.push(printTypeAnnotationProperty(path, print, "returnType")); - } - - if (shouldGroupFunctionParameters(node, returnTypeDoc)) { - parametersDoc = group(parametersDoc); - } - - parts.push(parametersDoc, returnTypeDoc); - - return [ - group(parts), - node.type === "TSConstructSignatureDeclaration" || - node.type === "TSCallSignatureDeclaration" - ? printClassMemberSemicolon(path, options) - : "", - ]; -} - -/* -- `TSIndexedAccessType`(TypeScript) -- `IndexedAccessType`(flow) -- `OptionalIndexedAccessType`(flow) -*/ -function printIndexedAccessType(path, options, print) { - return [ - print("objectType"), - printOptionalToken(path), - "[", - print("indexType"), - "]", - ]; -} - -/* -- `TSInferType`(TypeScript) -- `InferTypeAnnotation`(flow) -*/ -function printInferType(path, options, print) { - return ["infer ", print("typeParameter")]; -} - -// `TSJSDocNullableType`, `TSJSDocNonNullableType` -function printJSDocType(path, print, token) { - const { node } = path; - return [ - node.postfix ? "" : token, - printTypeAnnotationProperty(path, print), - node.postfix ? token : "", - ]; -} - -/* -- `TSRestType`(TypeScript) -- `TupleTypeSpreadElement`(flow) -*/ -function printRestType(path, options, print) { - const { node } = path; - - return [ - "...", - ...(node.type === "TupleTypeSpreadElement" && node.label - ? [print("label"), ": "] - : []), - print("typeAnnotation"), - ]; -} - -/* -- `TSNamedTupleMember`(TypeScript) -- `TupleTypeLabeledElement`(flow) -*/ -function printNamedTupleMember(path, options, print) { - const { node } = path; - - return [ - // `TupleTypeLabeledElement` only - node.variance ? print("variance") : "", - print("label"), - node.optional ? "?" : "", - ": ", - print("elementType"), - ]; -} - /* Normally the `(TS)TypeAnnotation` node starts with `:` token. If we print `:` in parent node, `cursorNodeDiff` in `/src/main/core.js` will consider `:` is removed, cause cursor moves, see #12491. @@ -570,60 +164,4 @@ function printTypeAnnotation(path, options, print) { : print("typeAnnotation"); } -/* -- `TSArrayType` -- `ArrayTypeAnnotation` -*/ -function printArrayType(print) { - return [print("elementType"), "[]"]; -} - -/* -- `TSTypeQuery` (TypeScript) -- `TypeofTypeAnnotation` (flow) -*/ -function printTypeQuery({ node }, print) { - const argumentPropertyName = - node.type === "TSTypeQuery" ? "exprName" : "argument"; - return ["typeof ", print(argumentPropertyName), print("typeArguments")]; -} - -/* -- `TSTypePredicate` (TypeScript) -- `TypePredicate` (flow) -*/ -function printTypePredicate(path, print) { - const { node } = path; - const prefix = - node.type === "TSTypePredicate" && node.asserts - ? "asserts " - : node.type === "TypePredicate" && node.kind - ? `${node.kind} ` - : ""; - return [ - prefix, - print("parameterName"), - node.typeAnnotation - ? [" is ", printTypeAnnotationProperty(path, print)] - : "", - ]; -} - -export { - printArrayType, - printFunctionType, - printIndexedAccessType, - printInferType, - printIntersectionType, - printJSDocType, - printNamedTupleMember, - printOpaqueType, - printRestType, - printTypeAlias, - printTypeAnnotation, - printTypeAnnotationProperty, - printTypePredicate, - printTypeQuery, - printUnionType, - shouldHugType, -}; +export { printTypeAnnotation, printTypeAnnotationProperty, shouldHugType }; diff --git a/src/language-js/print/type-assertion.js b/src/language-js/print/type-assertion.js new file mode 100644 index 000000000..d7c09b87a --- /dev/null +++ b/src/language-js/print/type-assertion.js @@ -0,0 +1,40 @@ +import { + conditionalGroup, + group, + ifBreak, + indent, + softline, +} from "../../document/index.js"; +import { isArrayExpression, isObjectExpression } from "../utilities/index.js"; + +function printTypeAssertion(path, options, print) { + const { node } = path; + const shouldBreakAfterCast = !( + isArrayExpression(node.expression) || isObjectExpression(node.expression) + ); + + const castGroup = group([ + "<", + indent([softline, print("typeAnnotation")]), + softline, + ">", + ]); + + const exprContents = [ + ifBreak("("), + indent([softline, print("expression")]), + softline, + ifBreak(")"), + ]; + + if (shouldBreakAfterCast) { + return conditionalGroup([ + [castGroup, print("expression")], + [castGroup, group(exprContents, { shouldBreak: true })], + [castGroup, print("expression")], + ]); + } + return group([castGroup, print("expression")]); +} + +export { printTypeAssertion }; diff --git a/src/language-js/print/type-parameters.js b/src/language-js/print/type-parameters.js index cf55297be..19a8aa0fd 100644 --- a/src/language-js/print/type-parameters.js +++ b/src/language-js/print/type-parameters.js @@ -17,7 +17,7 @@ import { isObjectType, isTestCall, shouldPrintComma, -} from "../utils/index.js"; +} from "../utilities/index.js"; import { isArrowFunctionVariableDeclarator } from "./assignment.js"; import { printTypeAnnotationProperty, diff --git a/src/language-js/print/type-predicate.js b/src/language-js/print/type-predicate.js new file mode 100644 index 000000000..d58cbf506 --- /dev/null +++ b/src/language-js/print/type-predicate.js @@ -0,0 +1,24 @@ +import { printTypeAnnotationProperty } from "./type-annotation.js"; + +/* +- `TSTypePredicate` (TypeScript) +- `TypePredicate` (flow) +*/ +function printTypePredicate(path, print) { + const { node } = path; + const prefix = + node.type === "TSTypePredicate" && node.asserts + ? "asserts " + : node.type === "TypePredicate" && node.kind + ? `${node.kind} ` + : ""; + return [ + prefix, + print("parameterName"), + node.typeAnnotation + ? [" is ", printTypeAnnotationProperty(path, print)] + : "", + ]; +} + +export { printTypePredicate }; diff --git a/src/language-js/print/type-query.js b/src/language-js/print/type-query.js new file mode 100644 index 000000000..95b9e80b9 --- /dev/null +++ b/src/language-js/print/type-query.js @@ -0,0 +1,11 @@ +/* +- `TSTypeQuery` (TypeScript) +- `TypeofTypeAnnotation` (flow) +*/ +function printTypeQuery({ node }, print) { + const argumentPropertyName = + node.type === "TSTypeQuery" ? "exprName" : "argument"; + return ["typeof ", print(argumentPropertyName), print("typeArguments")]; +} + +export { printTypeQuery }; diff --git a/src/language-js/print/typescript.js b/src/language-js/print/typescript.js index 34ac271cd..b1135d2f8 100644 --- a/src/language-js/print/typescript.js +++ b/src/language-js/print/typescript.js @@ -1,19 +1,7 @@ -import { - conditionalGroup, - group, - ifBreak, - indent, - join, - softline, -} from "../../document/index.js"; -import UnexpectedNodeError from "../../utils/unexpected-node-error.js"; -import { - isArrayExpression, - isObjectExpression, - shouldPrintComma, -} from "../utils/index.js"; -import isTsKeywordType from "../utils/is-ts-keyword-type.js"; +import UnexpectedNodeError from "../../utilities/unexpected-node-error.js"; +import isTsKeywordType from "../utilities/is-ts-keyword-type.js"; import { printArray } from "./array.js"; +import { printArrayType } from "./array-type.js"; import { printBlock } from "./block.js"; import { printCallExpression } from "./call-expression.js"; import { printBinaryCastExpression } from "./cast-expression.js"; @@ -30,37 +18,35 @@ import { printEnumMember, } from "./enum.js"; import { printFunction, printMethodValue } from "./function.js"; -import { - printFunctionParameters, - shouldGroupFunctionParameters, -} from "./function-parameters.js"; +import { printFunctionType } from "./function-type.js"; +import { printIndexSignature } from "./index-signature.js"; +import { printIndexedAccessType } from "./indexed-access-type.js"; +import { printInferType } from "./infer-type.js"; +import { printIntersectionType } from "./intersection-type.js"; +import { printJSDocType } from "./js-doc-type.js"; import { printTypeScriptMappedType } from "./mapped-type.js"; +import { printMethodSignature } from "./method-signature.js"; import { - printDeclareToken, printOptionalToken, printTypeScriptAccessibilityToken, } from "./misc.js"; import { printImportKind } from "./module.js"; +import { printModuleDeclaration } from "./module-declaration.js"; import { printPropertyKey } from "./property.js"; +import { printRestType } from "./rest-type.js"; import { printTemplateLiteral } from "./template-literal.js"; import { printTernary } from "./ternary.js"; +import { printNamedTupleMember } from "./tuple.js"; +import { printTypeAlias } from "./type-alias.js"; import { - printArrayType, - printFunctionType, - printIndexedAccessType, - printInferType, - printIntersectionType, - printJSDocType, - printNamedTupleMember, - printRestType, - printTypeAlias, printTypeAnnotation, printTypeAnnotationProperty, - printTypePredicate, - printTypeQuery, - printUnionType, } from "./type-annotation.js"; +import { printTypeAssertion } from "./type-assertion.js"; import { printTypeParameter, printTypeParameters } from "./type-parameters.js"; +import { printTypePredicate } from "./type-predicate.js"; +import { printTypeQuery } from "./type-query.js"; +import { printUnionType } from "./union-type.js"; function printTypescript(path, options, print) { const { node } = path; @@ -78,35 +64,9 @@ function printTypescript(path, options, print) { switch (node.type) { case "TSThisType": return "this"; - case "TSTypeAssertion": { - const shouldBreakAfterCast = !( - isArrayExpression(node.expression) || - isObjectExpression(node.expression) - ); + case "TSTypeAssertion": + return printTypeAssertion(path, options, print); - const castGroup = group([ - "<", - indent([softline, print("typeAnnotation")]), - softline, - ">", - ]); - - const exprContents = [ - ifBreak("("), - indent([softline, print("expression")]), - softline, - ifBreak(")"), - ]; - - if (shouldBreakAfterCast) { - return conditionalGroup([ - [castGroup, print("expression")], - [castGroup, group(exprContents, { shouldBreak: true })], - [castGroup, print("expression")], - ]); - } - return group([castGroup, print("expression")]); - } case "TSDeclareFunction": return printFunction(path, options, print); case "TSExportAssignment": @@ -171,39 +131,9 @@ function printTypescript(path, options, print) { case "TSTypeQuery": return printTypeQuery(path, print); - case "TSIndexSignature": { - // The typescript parser accepts multiple parameters here. If you're - // using them, it makes sense to have a trailing comma. But if you - // aren't, this is more like a computed property name than an array. - // So we leave off the trailing comma when there's just one parameter. - const trailingComma = - node.parameters.length > 1 - ? ifBreak(shouldPrintComma(options) ? "," : "") - : ""; + case "TSIndexSignature": + return printIndexSignature(path, options, print); - const parametersGroup = group([ - indent([ - softline, - join([", ", softline], path.map(print, "parameters")), - ]), - trailingComma, - softline, - ]); - - const isClassMember = - path.key === "body" && path.parent.type === "ClassBody"; - - return [ - // `static` only allowed in class member - isClassMember && node.static ? "static " : "", - node.readonly ? "readonly " : "", - "[", - node.parameters ? parametersGroup : "", - "]", - printTypeAnnotationProperty(path, print), - printClassMemberSemicolon(path, options), - ]; - } case "TSTypePredicate": return printTypePredicate(path, print); case "TSNonNullExpression": @@ -225,44 +155,9 @@ function printTypescript(path, options, print) { case "TSMappedType": return printTypeScriptMappedType(path, options, print); - case "TSMethodSignature": { - const parts = []; - const kind = node.kind && node.kind !== "method" ? `${node.kind} ` : ""; - parts.push( - printTypeScriptAccessibilityToken(node), - kind, - node.computed ? "[" : "", - print("key"), - node.computed ? "]" : "", - printOptionalToken(path), - ); + case "TSMethodSignature": + return printMethodSignature(path, options, print); - const parametersDoc = printFunctionParameters( - path, - options, - print, - /* shouldExpandArgument */ false, - /* shouldPrintTypeParameters */ true, - ); - - const returnTypeDoc = printTypeAnnotationProperty( - path, - print, - "returnType", - ); - const shouldGroupParameters = shouldGroupFunctionParameters( - node, - returnTypeDoc, - ); - - parts.push(shouldGroupParameters ? group(parametersDoc) : parametersDoc); - - if (node.returnType) { - parts.push(group(returnTypeDoc)); - } - - return [group(parts), printClassMemberSemicolon(path, options)]; - } case "TSNamespaceExportDeclaration": return ["export as namespace ", print("id"), options.semi ? ";" : ""]; case "TSEnumDeclaration": @@ -284,12 +179,7 @@ function printTypescript(path, options, print) { case "TSExternalModuleReference": return printCallExpression(path, options, print); case "TSModuleDeclaration": - return [ - printDeclareToken(path), - node.kind === "global" ? "" : `${node.kind} `, - print("id"), - node.body ? [" ", group(print("body"))] : options.semi ? ";" : "", - ]; + return printModuleDeclaration(path, options, print); case "TSConditionalType": return printTernary(path, options, print); diff --git a/src/language-js/print/union-type.js b/src/language-js/print/union-type.js new file mode 100644 index 000000000..ea9499809 --- /dev/null +++ b/src/language-js/print/union-type.js @@ -0,0 +1,153 @@ +import { + align, + group, + ifBreak, + indent, + join, + line, + softline, +} from "../../document/index.js"; +import { + printComments, + printCommentsSeparately, +} from "../../main/comments/print.js"; +import needsParentheses from "../parentheses/needs-parentheses.js"; +import { + CommentCheckFlags, + createTypeCheckFunction, + hasComment, + hasLeadingOwnLineComment, + isConditionalType, + isTypeAlias, +} from "../utilities/index.js"; + +// `TSUnionType` and `UnionTypeAnnotation` +function printUnionType(path, options, print) { + const { node } = path; + // single-line variation + // A | B | C + + // multi-line variation + // | A + // | B + // | C + + const { parent } = path; + + // If there's a leading comment, the parent is doing the indentation + const shouldIndent = + parent.type !== "TypeParameterInstantiation" && + (!isConditionalType(parent) || !options.experimentalTernaries) && + parent.type !== "TSTypeParameterInstantiation" && + parent.type !== "GenericTypeAnnotation" && + parent.type !== "TSTypeReference" && + parent.type !== "TSTypeAssertion" && + parent.type !== "TupleTypeAnnotation" && + parent.type !== "TSTupleType" && + !( + parent.type === "FunctionTypeParam" && + !parent.name && + path.grandparent.this !== parent + ) && + !( + (isTypeAlias(parent) || parent.type === "VariableDeclarator") && + hasLeadingOwnLineComment(options.originalText, node) + ) && + !( + isTypeAlias(parent) && + hasComment(parent.id, CommentCheckFlags.Trailing | CommentCheckFlags.Line) + ); + + // { + // a: string + // } | null | void + // should be inlined and not be printed in the multi-line variant + const shouldHug = shouldHugUnionType(node); + + // We want to align the children but without its comment, so it looks like + // | child1 + // // comment + // | child2 + const printed = path.map(() => { + let printedType = print(); + if (!shouldHug) { + printedType = align(2, printedType); + } + + return printComments(path, printedType, options); + }, "types"); + + const { leading, trailing } = printCommentsSeparately(path, options); + + if (shouldHug) { + return [leading, join(" | ", printed), trailing]; + } + + const shouldAddStartLine = + shouldIndent && !hasLeadingOwnLineComment(options.originalText, node); + + const mainParts = [ + ifBreak([shouldAddStartLine ? line : "", "| "]), + join([line, "| "], printed), + ]; + + if (needsParentheses(path, options)) { + return [leading, group([indent(mainParts), softline]), trailing]; + } + + const parts = [leading, group(mainParts)]; + + if (parent.type === "TupleTypeAnnotation" || parent.type === "TSTupleType") { + const elementTypes = + parent[ + // TODO: Remove `types` when babel changes AST of `TupleTypeAnnotation` + parent.type === "TupleTypeAnnotation" && parent.types + ? "types" + : "elementTypes" + ]; + + if (elementTypes.length > 1) { + return [ + group([ + indent([ifBreak(["(", softline]), parts]), + softline, + ifBreak(")"), + ]), + trailing, + ]; + } + } + + return [group(shouldIndent ? indent(parts) : parts), trailing]; +} + +const isVoidType = createTypeCheckFunction([ + "VoidTypeAnnotation", + "TSVoidKeyword", + "NullLiteralTypeAnnotation", + "TSNullKeyword", +]); + +const isObjectLikeType = createTypeCheckFunction([ + "ObjectTypeAnnotation", + "TSTypeLiteral", + // This is a bit aggressive but captures Array<{x}> + "GenericTypeAnnotation", + "TSTypeReference", +]); + +function shouldHugUnionType(node) { + const { types } = node; + if (types.some((node) => hasComment(node))) { + return false; + } + + const objectType = types.find((node) => isObjectLikeType(node)); + if (!objectType) { + return false; + } + + return types.every((node) => node === objectType || isVoidType(node)); +} + +export { printUnionType, shouldHugUnionType }; diff --git a/src/language-js/printer.js b/src/language-js/printer.js index c7839136f..27cd50d80 100644 --- a/src/language-js/printer.js +++ b/src/language-js/printer.js @@ -3,19 +3,17 @@ export const features = { experimental_avoidAstMutation: true, }; export { default as massageAstNode } from "./clean.js"; -export { - canAttachComment, - handleComments, - isBlockComment, - isGap, - printComment, - willPrintOwnComments, -} from "./comments/printer-methods.js"; +export { default as canAttachComment } from "./comments/can-attach-comment.js"; +export { default as handleComments } from "./comments/handle-comments.js"; +export { default as isGap } from "./comments/is-gap.js"; +export { default as willPrintOwnComments } from "./comments/will-print-own-comments.js"; export { default as embed } from "./embed/index.js"; export { insertPragma } from "./pragma.js"; +export { printComment } from "./print/comment.js"; export { default as print, default as printPrettierIgnored, } from "./print/index.js"; export { default as getVisitorKeys } from "./traverse/get-visitor-keys.js"; -export { default as hasPrettierIgnore } from "./utils/is-ignored.js"; +export { default as isBlockComment } from "./utilities/is-block-comment.js"; +export { default as hasPrettierIgnore } from "./utilities/is-ignored.js"; diff --git a/src/language-js/print/semicolon.js b/src/language-js/semicolon/semicolon.js similarity index 93% rename from src/language-js/print/semicolon.js rename to src/language-js/semicolon/semicolon.js index c7a932696..b6c488035 100644 --- a/src/language-js/print/semicolon.js +++ b/src/language-js/semicolon/semicolon.js @@ -1,10 +1,10 @@ -import pathNeedsParens from "../needs-parens.js"; +import needsParentheses from "../parentheses/needs-parentheses.js"; +import { shouldPrintParamsWithoutParens } from "../print/function.js"; import { getLeftSidePathName, hasNakedLeftSide, isJsxElement, -} from "../utils/index.js"; -import { shouldPrintParamsWithoutParens } from "./function.js"; +} from "../utilities/index.js"; function shouldPrintLeadingSemicolon(path, options) { if ( @@ -76,7 +76,7 @@ function expressionNeedsASIProtection(path, options) { } } - if (pathNeedsParens(path, options)) { + if (needsParentheses(path, options)) { return true; } diff --git a/src/language-js/traverse/get-visitor-keys.js b/src/language-js/traverse/get-visitor-keys.js index 96b5dbfd0..b9bdd2fc4 100644 --- a/src/language-js/traverse/get-visitor-keys.js +++ b/src/language-js/traverse/get-visitor-keys.js @@ -1,4 +1,4 @@ -import createGetVisitorKeys from "../../utils/create-get-visitor-keys.js"; +import createGetVisitorKeys from "../../utilities/create-get-visitor-keys.js"; import visitorKeys from "./visitor-keys.evaluate.js"; const getVisitorKeys = createGetVisitorKeys(visitorKeys); diff --git a/src/language-js/utils/create-type-check-function.js b/src/language-js/utilities/create-type-check-function.js similarity index 100% rename from src/language-js/utils/create-type-check-function.js rename to src/language-js/utilities/create-type-check-function.js diff --git a/src/language-js/utils/get-raw.js b/src/language-js/utilities/get-raw.js similarity index 100% rename from src/language-js/utils/get-raw.js rename to src/language-js/utilities/get-raw.js diff --git a/src/language-js/utils/get-shebang.js b/src/language-js/utilities/get-shebang.js similarity index 100% rename from src/language-js/utils/get-shebang.js rename to src/language-js/utilities/get-shebang.js diff --git a/src/language-js/utils/get-text-without-comments.js b/src/language-js/utilities/get-text-without-comments.js similarity index 100% rename from src/language-js/utils/get-text-without-comments.js rename to src/language-js/utilities/get-text-without-comments.js diff --git a/src/language-js/utils/index.js b/src/language-js/utilities/index.js similarity index 98% rename from src/language-js/utils/index.js rename to src/language-js/utilities/index.js index a57eada69..6d6add2f6 100644 --- a/src/language-js/utils/index.js +++ b/src/language-js/utilities/index.js @@ -1,9 +1,9 @@ -import { hasDescendant } from "../../utils/ast-utils.js"; -import getStringWidth from "../../utils/get-string-width.js"; -import hasNewline from "../../utils/has-newline.js"; -import isNextLineEmptyAfterIndex from "../../utils/is-next-line-empty.js"; -import isNonEmptyArray from "../../utils/is-non-empty-array.js"; -import printString from "../../utils/print-string.js"; +import { hasDescendant } from "../../utilities/ast.js"; +import getStringWidth from "../../utilities/get-string-width.js"; +import hasNewline from "../../utilities/has-newline.js"; +import isNextLineEmptyAfterIndex from "../../utilities/is-next-line-empty.js"; +import isNonEmptyArray from "../../utilities/is-non-empty-array.js"; +import printString from "../../utilities/print-string.js"; import { hasSameLocStart, locEnd, locStart } from "../loc.js"; import getVisitorKeys from "../traverse/get-visitor-keys.js"; import createTypeCheckFunction from "./create-type-check-function.js"; diff --git a/src/language-js/utils/is-block-comment.js b/src/language-js/utilities/is-block-comment.js similarity index 100% rename from src/language-js/utils/is-block-comment.js rename to src/language-js/utilities/is-block-comment.js diff --git a/src/language-js/utils/is-flow-keyword-type.js b/src/language-js/utilities/is-flow-keyword-type.js similarity index 100% rename from src/language-js/utils/is-flow-keyword-type.js rename to src/language-js/utilities/is-flow-keyword-type.js diff --git a/src/language-js/utils/is-ignored.js b/src/language-js/utilities/is-ignored.js similarity index 75% rename from src/language-js/utils/is-ignored.js rename to src/language-js/utilities/is-ignored.js index 13cdbe11f..a2ec0857e 100644 --- a/src/language-js/utils/is-ignored.js +++ b/src/language-js/utilities/is-ignored.js @@ -1,5 +1,5 @@ import { hasJsxIgnoreComment } from "../print/jsx.js"; -import { hasNodeIgnoreComment } from "../utils/index.js"; +import { hasNodeIgnoreComment } from "./index.js"; function isIgnored(path) { return hasNodeIgnoreComment(path.node) || hasJsxIgnoreComment(path); diff --git a/src/language-js/utils/is-indentable-block-comment.js b/src/language-js/utilities/is-indentable-block-comment.js similarity index 100% rename from src/language-js/utils/is-indentable-block-comment.js rename to src/language-js/utilities/is-indentable-block-comment.js diff --git a/src/language-js/utils/is-line-comment.js b/src/language-js/utilities/is-line-comment.js similarity index 100% rename from src/language-js/utils/is-line-comment.js rename to src/language-js/utilities/is-line-comment.js diff --git a/src/language-js/utils/is-meaningful-empty-statement.js b/src/language-js/utilities/is-meaningful-empty-statement.js similarity index 100% rename from src/language-js/utils/is-meaningful-empty-statement.js rename to src/language-js/utilities/is-meaningful-empty-statement.js diff --git a/src/language-js/utils/is-node-matches.js b/src/language-js/utilities/is-node-matches.js similarity index 94% rename from src/language-js/utils/is-node-matches.js rename to src/language-js/utilities/is-node-matches.js index 91ca793a2..79d62f361 100644 --- a/src/language-js/utils/is-node-matches.js +++ b/src/language-js/utilities/is-node-matches.js @@ -1,4 +1,4 @@ -// Copied from https://github.com/sindresorhus/eslint-plugin-unicorn/blob/d53d935951aa815c763fc9441aa452c763294715/rules/utils/is-node-matches.js +// Copied from https://github.com/sindresorhus/eslint-plugin-unicorn/blob/d53d935951aa815c763fc9441aa452c763294715/rules/utilities/is-node-matches.js /** * @import {Node} from "../types/estree.js" diff --git a/src/language-js/utils/is-ts-keyword-type.js b/src/language-js/utilities/is-ts-keyword-type.js similarity index 100% rename from src/language-js/utils/is-ts-keyword-type.js rename to src/language-js/utilities/is-ts-keyword-type.js diff --git a/src/language-js/utils/is-type-cast-comment.js b/src/language-js/utilities/is-type-cast-comment.js similarity index 100% rename from src/language-js/utils/is-type-cast-comment.js rename to src/language-js/utilities/is-type-cast-comment.js diff --git a/src/language-js/utils/vue-event-binding.js b/src/language-js/utilities/vue-event-binding.js similarity index 100% rename from src/language-js/utils/vue-event-binding.js rename to src/language-js/utilities/vue-event-binding.js diff --git a/src/language-json/get-visitor-keys.js b/src/language-json/get-visitor-keys.js index d58d77cf3..558c57e6b 100644 --- a/src/language-json/get-visitor-keys.js +++ b/src/language-json/get-visitor-keys.js @@ -1,4 +1,4 @@ -import createGetVisitorKeys from "../utils/create-get-visitor-keys.js"; +import createGetVisitorKeys from "../utilities/create-get-visitor-keys.js"; import visitorKeys from "./visitor-keys.js"; const getVisitorKeys = createGetVisitorKeys(visitorKeys); diff --git a/src/language-json/languages.evaluate.js b/src/language-json/languages.evaluate.js index 949b686a3..d2cc41275 100644 --- a/src/language-json/languages.evaluate.js +++ b/src/language-json/languages.evaluate.js @@ -1,5 +1,5 @@ import * as linguistLanguages from "linguist-languages"; -import createLanguage from "../utils/create-language.js"; +import createLanguage from "../utilities/create-language.js"; // A list of files that are commonly generated by tools and should not be // formatted by the default JSON parser to avoid unwanted diffs. diff --git a/src/language-json/parser-json.js b/src/language-json/parser-json.js index 2746b5f7e..9f3247b14 100644 --- a/src/language-json/parser-json.js +++ b/src/language-json/parser-json.js @@ -1,9 +1,9 @@ import { parse, parseExpression } from "@babel/parser"; import createError from "../common/parser-create-error.js"; -import createBabelParseError from "../language-js/parse/utils/create-babel-parse-error.js"; -import createParser from "../language-js/parse/utils/create-parser.js"; -import wrapBabelExpression from "../language-js/parse/utils/wrap-babel-expression.js"; -import isNonEmptyArray from "../utils/is-non-empty-array.js"; +import createBabelParseError from "../language-js/parse/utilities/create-babel-parse-error.js"; +import createParser from "../language-js/parse/utilities/create-parser.js"; +import wrapBabelExpression from "../language-js/parse/utilities/wrap-babel-expression.js"; +import isNonEmptyArray from "../utilities/is-non-empty-array.js"; const babelParseOptions = { tokens: false, diff --git a/src/language-json/printer-estree-json.js b/src/language-json/printer-estree-json.js index 42a40c524..dd132aa43 100644 --- a/src/language-json/printer-estree-json.js +++ b/src/language-json/printer-estree-json.js @@ -1,5 +1,5 @@ import { hardline, indent, join } from "../document/index.js"; -import UnexpectedNodeError from "../utils/unexpected-node-error.js"; +import UnexpectedNodeError from "../utilities/unexpected-node-error.js"; function genericPrint(path, options, print) { const { node } = path; diff --git a/src/language-markdown/embed.js b/src/language-markdown/embed.js index 0ff92ed74..b00b7903b 100644 --- a/src/language-markdown/embed.js +++ b/src/language-markdown/embed.js @@ -1,7 +1,7 @@ import { hardline, markAsRoot, replaceEndOfLine } from "../document/index.js"; -import getMaxContinuousCount from "../utils/get-max-continuous-count.js"; -import inferParser from "../utils/infer-parser.js"; -import { getFencedCodeBlockValue } from "./utils.js"; +import getMaxContinuousCount from "../utilities/get-max-continuous-count.js"; +import inferParser from "../utilities/infer-parser.js"; +import { getFencedCodeBlockValue } from "./utilities.js"; function embed(path, options) { const { node } = path; diff --git a/src/language-markdown/get-visitor-keys.js b/src/language-markdown/get-visitor-keys.js index d58d77cf3..558c57e6b 100644 --- a/src/language-markdown/get-visitor-keys.js +++ b/src/language-markdown/get-visitor-keys.js @@ -1,4 +1,4 @@ -import createGetVisitorKeys from "../utils/create-get-visitor-keys.js"; +import createGetVisitorKeys from "../utilities/create-get-visitor-keys.js"; import visitorKeys from "./visitor-keys.js"; const getVisitorKeys = createGetVisitorKeys(visitorKeys); diff --git a/src/language-markdown/languages.evaluate.js b/src/language-markdown/languages.evaluate.js index 15fddbcea..e37bd3be2 100644 --- a/src/language-markdown/languages.evaluate.js +++ b/src/language-markdown/languages.evaluate.js @@ -1,5 +1,5 @@ import * as linguistLanguages from "linguist-languages"; -import createLanguage from "../utils/create-language.js"; +import createLanguage from "../utilities/create-language.js"; const languages = [ createLanguage(linguistLanguages.Markdown, (data) => ({ diff --git a/src/language-markdown/pragma.js b/src/language-markdown/pragma.js index 10785416d..c9509494c 100644 --- a/src/language-markdown/pragma.js +++ b/src/language-markdown/pragma.js @@ -3,7 +3,7 @@ import { FORMAT_PRAGMA_TO_INSERT, MARKDOWN_HAS_IGNORE_PRAGMA_REGEXP, MARKDOWN_HAS_PRAGMA_REGEXP, -} from "../utils/pragma/pragma.evaluate.js"; +} from "../utilities/pragma/pragma.evaluate.js"; const hasPragma = (text) => parseFrontMatter(text).content.trimStart().match(MARKDOWN_HAS_PRAGMA_REGEXP) diff --git a/src/language-markdown/print-preprocess.js b/src/language-markdown/print-preprocess.js index 521a91dec..4bfa85d0d 100644 --- a/src/language-markdown/print-preprocess.js +++ b/src/language-markdown/print-preprocess.js @@ -1,5 +1,5 @@ -import htmlWhitespaceUtils from "../utils/html-whitespace-utils.js"; -import { getOrderedListItemInfo, mapAst, splitText } from "./utils.js"; +import htmlWhitespace from "../utilities/html-whitespace.js"; +import { getOrderedListItemInfo, mapAst, splitText } from "./utilities.js"; // 0x0 ~ 0x10ffff const isSingleCharRegex = /^\\?.$/su; @@ -97,10 +97,10 @@ function splitTextIntoSentences(ast) { // CommonMark doesn't remove trailing/leading \f, but it should be // removed in the HTML rendering process if (index === 0) { - value = htmlWhitespaceUtils.trimStart(value); + value = htmlWhitespace.trimStart(value); } if (index === parentNode.children.length - 1) { - value = htmlWhitespaceUtils.trimEnd(value); + value = htmlWhitespace.trimEnd(value); } } diff --git a/src/language-markdown/print-whitespace.js b/src/language-markdown/print-whitespace.js index 3713b67f4..1f01f46e6 100644 --- a/src/language-markdown/print-whitespace.js +++ b/src/language-markdown/print-whitespace.js @@ -4,10 +4,10 @@ import { KIND_CJK_PUNCTUATION, KIND_K_LETTER, KIND_NON_CJK, -} from "./utils.js"; +} from "./utilities.js"; /** - * @import {WordNode, WhitespaceValue, WordKind} from "./utils.js" + * @import {WordNode, WhitespaceValue, WordKind} from "./utilities.js" * @import AstPath from "../common/ast-path.js" * @typedef {"always" | "never" | "preserve"} ProseWrap * @typedef {{ next?: WordNode | null, previous?: WordNode | null }} diff --git a/src/language-markdown/print/children.js b/src/language-markdown/print/children.js index 8980a9c1a..daaa5e0a3 100644 --- a/src/language-markdown/print/children.js +++ b/src/language-markdown/print/children.js @@ -3,7 +3,7 @@ import { INLINE_NODE_TYPES, INLINE_NODE_WRAPPER_TYPES, isPrettierIgnore, -} from "../utils.js"; +} from "../utilities.js"; /** * @import AstPath from "../../common/ast-path.js" diff --git a/src/language-markdown/print/list.js b/src/language-markdown/print/list.js index 5f9ee860a..86ae1e663 100644 --- a/src/language-markdown/print/list.js +++ b/src/language-markdown/print/list.js @@ -2,7 +2,7 @@ import { align } from "../../document/index.js"; import { getNthListSiblingIndex, hasGitDiffFriendlyOrderedList, -} from "../utils.js"; +} from "../utilities.js"; import { printChildren } from "./children.js"; /** diff --git a/src/language-markdown/print/table.js b/src/language-markdown/print/table.js index c69218f7f..9f1165199 100644 --- a/src/language-markdown/print/table.js +++ b/src/language-markdown/print/table.js @@ -6,7 +6,7 @@ import { join, } from "../../document/index.js"; import { printDocToString } from "../../document/printer/printer.js"; -import getStringWidth from "../../utils/get-string-width.js"; +import getStringWidth from "../../utilities/get-string-width.js"; function printTable(path, options, print) { const { node } = path; diff --git a/src/language-markdown/print/word.js b/src/language-markdown/print/word.js index 66f4d1c8f..35feed9e4 100644 --- a/src/language-markdown/print/word.js +++ b/src/language-markdown/print/word.js @@ -1,5 +1,5 @@ import { PUNCTUATION_REGEXP } from "../constants.evaluate.js"; -import { isAutolink } from "../utils.js"; +import { isAutolink } from "../utilities.js"; /** * @import AstPath from "../../common/ast-path.js" diff --git a/src/language-markdown/printer-markdown.js b/src/language-markdown/printer-markdown.js index 22a2a063e..60b572c65 100644 --- a/src/language-markdown/printer-markdown.js +++ b/src/language-markdown/printer-markdown.js @@ -14,10 +14,10 @@ import { replaceEndOfLine, softline, } from "../document/index.js"; -import getMaxContinuousCount from "../utils/get-max-continuous-count.js"; -import getMinNotPresentContinuousCount from "../utils/get-min-not-present-continuous-count.js"; -import getPreferredQuote from "../utils/get-preferred-quote.js"; -import UnexpectedNodeError from "../utils/unexpected-node-error.js"; +import getMaxContinuousCount from "../utilities/get-max-continuous-count.js"; +import getMinNotPresentContinuousCount from "../utilities/get-min-not-present-continuous-count.js"; +import getPreferredQuote from "../utilities/get-preferred-quote.js"; +import UnexpectedNodeError from "../utilities/unexpected-node-error.js"; import clean from "./clean.js"; import embed from "./embed.js"; import getVisitorKeys from "./get-visitor-keys.js"; @@ -37,7 +37,7 @@ import { isAutolink, isPrettierIgnore, splitText, -} from "./utils.js"; +} from "./utilities.js"; /** * @import {Doc} from "../document/index.js" diff --git a/src/language-markdown/unified-plugins/html-to-jsx.js b/src/language-markdown/unified-plugins/html-to-jsx.js index c8d866632..cf0c4a609 100644 --- a/src/language-markdown/unified-plugins/html-to-jsx.js +++ b/src/language-markdown/unified-plugins/html-to-jsx.js @@ -1,5 +1,5 @@ import { COMMENT_REGEX } from "../mdx.js"; -import { INLINE_NODE_WRAPPER_TYPES, mapAst } from "../utils.js"; +import { INLINE_NODE_WRAPPER_TYPES, mapAst } from "../utilities.js"; function htmlToJsx() { return (ast) => diff --git a/src/language-markdown/utils.js b/src/language-markdown/utilities.js similarity index 100% rename from src/language-markdown/utils.js rename to src/language-markdown/utilities.js diff --git a/src/language-yaml/get-visitor-keys.js b/src/language-yaml/get-visitor-keys.js index d58d77cf3..558c57e6b 100644 --- a/src/language-yaml/get-visitor-keys.js +++ b/src/language-yaml/get-visitor-keys.js @@ -1,4 +1,4 @@ -import createGetVisitorKeys from "../utils/create-get-visitor-keys.js"; +import createGetVisitorKeys from "../utilities/create-get-visitor-keys.js"; import visitorKeys from "./visitor-keys.js"; const getVisitorKeys = createGetVisitorKeys(visitorKeys); diff --git a/src/language-yaml/languages.evaluate.js b/src/language-yaml/languages.evaluate.js index a0ded8978..5a709b1ff 100644 --- a/src/language-yaml/languages.evaluate.js +++ b/src/language-yaml/languages.evaluate.js @@ -1,5 +1,5 @@ import * as linguistLanguages from "linguist-languages"; -import createLanguage from "../utils/create-language.js"; +import createLanguage from "../utilities/create-language.js"; const ignoredFilenames = new Set([ // `yarn.lock` is not YAML in Yarn v1: https://github.com/yarnpkg/yarn/issues/5629 diff --git a/src/language-yaml/pragma.js b/src/language-yaml/pragma.js index 822bbc897..2c0878bd3 100644 --- a/src/language-yaml/pragma.js +++ b/src/language-yaml/pragma.js @@ -3,7 +3,7 @@ import { YAML_HAS_IGNORE_PRAGMA_REGEXP, YAML_HAS_PRAGMA_REGEXP, YAML_IS_PRAGMA_REGEXP, -} from "../utils/pragma/pragma.evaluate.js"; +} from "../utilities/pragma/pragma.evaluate.js"; const isPragma = (text) => YAML_IS_PRAGMA_REGEXP.test(text); const hasPragma = (text) => YAML_HAS_PRAGMA_REGEXP.test(text); diff --git a/src/language-yaml/print-preprocess.js b/src/language-yaml/print-preprocess.js index 2857036d7..f3ddf8aae 100644 --- a/src/language-yaml/print-preprocess.js +++ b/src/language-yaml/print-preprocess.js @@ -1,4 +1,4 @@ -import { defineShortcut, mapNode } from "./utils.js"; +import { defineShortcut, mapNode } from "./utilities.js"; function preprocess(ast) { return mapNode(ast, defineShortcuts); diff --git a/src/language-yaml/print/block.js b/src/language-yaml/print/block.js index f756ef61b..cddba7d33 100644 --- a/src/language-yaml/print/block.js +++ b/src/language-yaml/print/block.js @@ -14,7 +14,7 @@ import { getBlockValueLineContents, hasIndicatorComment, isLastDescendantNode, -} from "../utils.js"; +} from "../utilities.js"; import { alignWithSpaces } from "./misc.js"; function printBlock(path, options, print) { diff --git a/src/language-yaml/print/flow-mapping-sequence.js b/src/language-yaml/print/flow-mapping-sequence.js index 634319f24..56e82cb3b 100644 --- a/src/language-yaml/print/flow-mapping-sequence.js +++ b/src/language-yaml/print/flow-mapping-sequence.js @@ -5,7 +5,7 @@ import { line, softline, } from "../../document/index.js"; -import { hasEndComments, isEmptyNode } from "../utils.js"; +import { hasEndComments, isEmptyNode } from "../utilities.js"; import { alignWithSpaces, printNextEmptyLine } from "./misc.js"; function printFlowMapping(path, options, print) { diff --git a/src/language-yaml/print/mapping-item.js b/src/language-yaml/print/mapping-item.js index 3eb1645c2..e0781eeca 100644 --- a/src/language-yaml/print/mapping-item.js +++ b/src/language-yaml/print/mapping-item.js @@ -15,7 +15,7 @@ import { isEmptyNode, isInlineNode, isNode, -} from "../utils.js"; +} from "../utilities.js"; import { alignWithSpaces } from "./misc.js"; function printMappingItem(path, options, print) { diff --git a/src/language-yaml/print/misc.js b/src/language-yaml/print/misc.js index c8ce4c5ae..96154f344 100644 --- a/src/language-yaml/print/misc.js +++ b/src/language-yaml/print/misc.js @@ -1,5 +1,5 @@ import { align, softline } from "../../document/index.js"; -import { hasEndComments, isNextLineEmpty, isNode } from "../utils.js"; +import { hasEndComments, isNextLineEmpty, isNode } from "../utilities.js"; const printedEmptyLineCache = new WeakMap(); function printNextEmptyLine(path, originalText) { diff --git a/src/language-yaml/printer-yaml.js b/src/language-yaml/printer-yaml.js index 5253eb554..834fad171 100644 --- a/src/language-yaml/printer-yaml.js +++ b/src/language-yaml/printer-yaml.js @@ -10,8 +10,8 @@ import { lineSuffix, replaceEndOfLine, } from "../document/index.js"; -import isPreviousLineEmpty from "../utils/is-previous-line-empty.js"; -import UnexpectedNodeError from "../utils/unexpected-node-error.js"; +import isPreviousLineEmpty from "../utilities/is-previous-line-empty.js"; +import UnexpectedNodeError from "../utilities/unexpected-node-error.js"; import clean from "./clean.js"; import embed from "./embed.js"; import getVisitorKeys from "./get-visitor-keys.js"; @@ -40,7 +40,7 @@ import { isInlineNode, isLastDescendantNode, isNode, -} from "./utils.js"; +} from "./utilities.js"; function genericPrint(path, options, print) { const { node } = path; diff --git a/src/language-yaml/utils.js b/src/language-yaml/utilities.js similarity index 99% rename from src/language-yaml/utils.js rename to src/language-yaml/utilities.js index 9632ff9ea..90e5183ee 100644 --- a/src/language-yaml/utils.js +++ b/src/language-yaml/utilities.js @@ -1,4 +1,4 @@ -import isNonEmptyArray from "../utils/is-non-empty-array.js"; +import isNonEmptyArray from "../utilities/is-non-empty-array.js"; /** * @param {any} value diff --git a/src/main/comments/attach.js b/src/main/comments/attach.js index 2a18ba4cb..ae8ed3b9c 100644 --- a/src/main/comments/attach.js +++ b/src/main/comments/attach.js @@ -1,12 +1,12 @@ import * as assert from "#universal/assert"; -import hasNewline from "../../utils/has-newline.js"; -import isNonEmptyArray from "../../utils/is-non-empty-array.js"; +import hasNewline from "../../utilities/has-newline.js"; +import isNonEmptyArray from "../../utilities/is-non-empty-array.js"; import getSortedChildNodes from "../utilities/get-sorted-child-nodes.js"; import { addDanglingComment, addLeadingComment, addTrailingComment, -} from "./utils.js"; +} from "./utilities.js"; /** * @import AstPath from "../../common/ast-path.js" diff --git a/src/main/comments/print.js b/src/main/comments/print.js index d9f84db6c..31a6ee6ee 100644 --- a/src/main/comments/print.js +++ b/src/main/comments/print.js @@ -7,11 +7,11 @@ import { line, lineSuffix, } from "../../document/index.js"; -import hasNewline from "../../utils/has-newline.js"; -import isNonEmptyArray from "../../utils/is-non-empty-array.js"; -import isPreviousLineEmpty from "../../utils/is-previous-line-empty.js"; -import { skipSpaces } from "../../utils/skip.js"; -import skipNewline from "../../utils/skip-newline.js"; +import hasNewline from "../../utilities/has-newline.js"; +import isNonEmptyArray from "../../utilities/is-non-empty-array.js"; +import isPreviousLineEmpty from "../../utilities/is-previous-line-empty.js"; +import { skipSpaces } from "../../utilities/skip.js"; +import skipNewline from "../../utilities/skip-newline.js"; /** * @import AstPath from "../../common/ast-path.js" diff --git a/src/main/comments/utils.js b/src/main/comments/utilities.js similarity index 100% rename from src/main/comments/utils.js rename to src/main/comments/utilities.js diff --git a/src/main/core.js b/src/main/core.js index 9a1ee5aa3..811733f1d 100644 --- a/src/main/core.js +++ b/src/main/core.js @@ -11,7 +11,7 @@ import { printDocToDebug, printDocToString as printDocToStringWithoutNormalizeOptions, } from "../document/index.js"; -import getAlignmentSize from "../utils/get-alignment-size.js"; +import getAlignmentSize from "../utilities/get-alignment-size.js"; import { prepareToPrint, printAstToDoc } from "./ast-to-doc.js"; import getCursorLocation from "./get-cursor-node.js"; import massageAst from "./massage-ast.js"; diff --git a/src/main/create-print-pre-check-function.js b/src/main/create-print-pre-check-function.js index 352cd603b..191a74df0 100644 --- a/src/main/create-print-pre-check-function.js +++ b/src/main/create-print-pre-check-function.js @@ -1,4 +1,4 @@ -import noop from "../utils/noop.js"; +import noop from "../utilities/noop.js"; function createPrintPreCheckFunction(options) { // All core plugins have full list of keys for possible child nodes diff --git a/src/main/front-matter/embed.js b/src/main/front-matter/embed.js index cc7544a0f..6b09022b5 100644 --- a/src/main/front-matter/embed.js +++ b/src/main/front-matter/embed.js @@ -1,5 +1,5 @@ import { hardline, markAsRoot } from "../../document/index.js"; -import inferParser from "../../utils/infer-parser.js"; +import inferParser from "../../utilities/infer-parser.js"; import isFrontMatter from "./is-front-matter.js"; const SUPPORTED_EMBED_LANGUAGES = new Set(["yaml", "toml"]); diff --git a/src/main/get-cursor-node.js b/src/main/get-cursor-node.js index 487b295e6..4d0585c23 100644 --- a/src/main/get-cursor-node.js +++ b/src/main/get-cursor-node.js @@ -1,4 +1,4 @@ -import { getChildren, getDescendants, isLeaf } from "../utils/ast-utils.js"; +import { getChildren, getDescendants, isLeaf } from "../utilities/ast.js"; /** * Find the location of the cursor in the AST, represented in one of the diff --git a/src/main/massage-ast.js b/src/main/massage-ast.js index 6d356c43d..49449ddb2 100644 --- a/src/main/massage-ast.js +++ b/src/main/massage-ast.js @@ -1,4 +1,4 @@ -import isObject from "../utils/is-object.js"; +import isObject from "../utilities/is-object.js"; function massageAst(ast, options) { const { printer } = options; diff --git a/src/main/normalize-format-options.js b/src/main/normalize-format-options.js index e44ac92bc..08a1c2503 100644 --- a/src/main/normalize-format-options.js +++ b/src/main/normalize-format-options.js @@ -1,6 +1,6 @@ import { UndefinedParserError } from "../common/errors.js"; import { getSupportInfo } from "../main/support.js"; -import inferParser from "../utils/infer-parser.js"; +import inferParser from "../utilities/infer-parser.js"; import normalizeOptions from "./normalize-options.js"; import { getParserPluginByParserName, diff --git a/src/main/plugins/load-plugin.js b/src/main/plugins/load-plugin.js index dd805ff9c..37f7c3bd7 100644 --- a/src/main/plugins/load-plugin.js +++ b/src/main/plugins/load-plugin.js @@ -1,7 +1,7 @@ import path from "node:path"; import { pathToFileURL } from "node:url"; import { isUrl, toPath } from "url-or-path"; -import importFromDirectory from "../../utils/import-from-directory.js"; +import importFromDirectory from "../../utilities/import-from-directory.js"; /** @param {string | URL} name diff --git a/src/main/utilities/get-sorted-child-nodes.js b/src/main/utilities/get-sorted-child-nodes.js index c0a3d33d4..b36f81710 100644 --- a/src/main/utilities/get-sorted-child-nodes.js +++ b/src/main/utilities/get-sorted-child-nodes.js @@ -1,4 +1,4 @@ -import { getChildren } from "../../utils/ast-utils.js"; +import { getChildren } from "../../utilities/ast.js"; function getSortedChildNodes(node, ancestors, options) { const { cache: childNodesCache } = options; diff --git a/src/standalone.js b/src/standalone.js index 8277956ee..e5ed71f06 100644 --- a/src/standalone.js +++ b/src/standalone.js @@ -53,4 +53,4 @@ export { }; export * as doc from "./document/public.js"; export { default as version } from "./main/version.evaluate.js"; -export * as util from "./utils/public.js"; +export * as util from "./utilities/public.js"; diff --git a/src/universal/assert.browser.js b/src/universal/assert.browser.js index 06ff36e4c..b214413af 100644 --- a/src/universal/assert.browser.js +++ b/src/universal/assert.browser.js @@ -2,4 +2,4 @@ export { default as equal, default as ok, default as strictEqual, -} from "../utils/noop.js"; +} from "../utilities/noop.js"; diff --git a/src/universal/index.js b/src/universal/index.js index 91d2eaf1a..f56419142 100644 --- a/src/universal/index.js +++ b/src/universal/index.js @@ -14,6 +14,6 @@ const getFileBasename = (file) => { }; export { getFileBasename }; -export { default as getInterpreter } from "../utils/get-interpreter.js"; +export { default as getInterpreter } from "../utilities/get-interpreter.js"; export { fileURLToPath } from "node:url"; export { isUrl } from "url-or-path"; diff --git a/src/utils/ast-utils.js b/src/utilities/ast.js similarity index 95% rename from src/utils/ast-utils.js rename to src/utilities/ast.js index 7d73e9dfe..b3437e5d1 100644 --- a/src/utils/ast-utils.js +++ b/src/utilities/ast.js @@ -1,7 +1,7 @@ import isObject from "./is-object.js"; /** -@import {GetVisitorKeys, Node} from "../utils/create-get-visitor-keys.js" +@import {GetVisitorKeys, Node} from "./create-get-visitor-keys.js" @typedef {(node: Node) => boolean} Predicate */ diff --git a/src/utils/create-get-visitor-keys.js b/src/utilities/create-get-visitor-keys.js similarity index 100% rename from src/utils/create-get-visitor-keys.js rename to src/utilities/create-get-visitor-keys.js diff --git a/src/utils/create-group-id-mapper.js b/src/utilities/create-group-id-mapper.js similarity index 100% rename from src/utils/create-group-id-mapper.js rename to src/utilities/create-group-id-mapper.js diff --git a/src/utils/create-language.js b/src/utilities/create-language.js similarity index 100% rename from src/utils/create-language.js rename to src/utilities/create-language.js diff --git a/src/utils/create-mockable.js b/src/utilities/create-mockable.js similarity index 100% rename from src/utils/create-mockable.js rename to src/utilities/create-mockable.js diff --git a/src/utils/get-alignment-size.js b/src/utilities/get-alignment-size.js similarity index 100% rename from src/utils/get-alignment-size.js rename to src/utilities/get-alignment-size.js diff --git a/src/utils/get-indent-size.js b/src/utilities/get-indent-size.js similarity index 100% rename from src/utils/get-indent-size.js rename to src/utilities/get-indent-size.js diff --git a/src/utils/get-interpreter.js b/src/utilities/get-interpreter.js similarity index 100% rename from src/utils/get-interpreter.js rename to src/utilities/get-interpreter.js diff --git a/src/utils/get-max-continuous-count.js b/src/utilities/get-max-continuous-count.js similarity index 100% rename from src/utils/get-max-continuous-count.js rename to src/utilities/get-max-continuous-count.js diff --git a/src/utils/get-min-not-present-continuous-count.js b/src/utilities/get-min-not-present-continuous-count.js similarity index 100% rename from src/utils/get-min-not-present-continuous-count.js rename to src/utilities/get-min-not-present-continuous-count.js diff --git a/src/utils/get-next-non-space-non-comment-character-index.js b/src/utilities/get-next-non-space-non-comment-character-index.js similarity index 100% rename from src/utils/get-next-non-space-non-comment-character-index.js rename to src/utilities/get-next-non-space-non-comment-character-index.js diff --git a/src/utils/get-next-non-space-non-comment-character.js b/src/utilities/get-next-non-space-non-comment-character.js similarity index 100% rename from src/utils/get-next-non-space-non-comment-character.js rename to src/utilities/get-next-non-space-non-comment-character.js diff --git a/src/utils/get-preferred-quote.js b/src/utilities/get-preferred-quote.js similarity index 100% rename from src/utils/get-preferred-quote.js rename to src/utilities/get-preferred-quote.js diff --git a/src/utils/get-string-width.js b/src/utilities/get-string-width.js similarity index 100% rename from src/utils/get-string-width.js rename to src/utilities/get-string-width.js diff --git a/src/utils/has-newline-in-range.js b/src/utilities/has-newline-in-range.js similarity index 100% rename from src/utils/has-newline-in-range.js rename to src/utilities/has-newline-in-range.js diff --git a/src/utils/has-newline.js b/src/utilities/has-newline.js similarity index 100% rename from src/utils/has-newline.js rename to src/utilities/has-newline.js diff --git a/src/utils/has-spaces.js b/src/utilities/has-spaces.js similarity index 100% rename from src/utils/has-spaces.js rename to src/utilities/has-spaces.js diff --git a/src/utilities/html-whitespace.js b/src/utilities/html-whitespace.js new file mode 100644 index 000000000..8923bd188 --- /dev/null +++ b/src/utilities/html-whitespace.js @@ -0,0 +1,7 @@ +import WhitespaceUtilities from "./whitespace-utilities.js"; + +// https://infra.spec.whatwg.org/#ascii-whitespace +const HTML_WHITESPACE_CHARACTERS = ["\t", "\n", "\f", "\r", " "]; +const htmlWhitespace = new WhitespaceUtilities(HTML_WHITESPACE_CHARACTERS); + +export default htmlWhitespace; diff --git a/src/utils/ignore.js b/src/utilities/ignore.js similarity index 98% rename from src/utils/ignore.js rename to src/utilities/ignore.js index d86dffcb1..552498682 100644 --- a/src/utils/ignore.js +++ b/src/utilities/ignore.js @@ -2,7 +2,7 @@ import path from "node:path"; import url from "node:url"; import createIgnore from "ignore"; import { isUrl, toPath } from "url-or-path"; -import readFile from "../utils/read-file.js"; +import readFile from "./read-file.js"; /** @type {(filePath: string) => string} */ const slash = diff --git a/src/utils/import-from-directory.js b/src/utilities/import-from-directory.js similarity index 100% rename from src/utils/import-from-directory.js rename to src/utilities/import-from-directory.js diff --git a/src/utils/import-from-file.js b/src/utilities/import-from-file.js similarity index 100% rename from src/utils/import-from-file.js rename to src/utilities/import-from-file.js diff --git a/src/utils/infer-parser.js b/src/utilities/infer-parser.js similarity index 100% rename from src/utils/infer-parser.js rename to src/utilities/infer-parser.js diff --git a/src/utils/is-next-line-empty.js b/src/utilities/is-next-line-empty.js similarity index 100% rename from src/utils/is-next-line-empty.js rename to src/utilities/is-next-line-empty.js diff --git a/src/utils/is-non-empty-array.js b/src/utilities/is-non-empty-array.js similarity index 100% rename from src/utils/is-non-empty-array.js rename to src/utilities/is-non-empty-array.js diff --git a/src/utils/is-object.js b/src/utilities/is-object.js similarity index 100% rename from src/utils/is-object.js rename to src/utilities/is-object.js diff --git a/src/utils/is-previous-line-empty.js b/src/utilities/is-previous-line-empty.js similarity index 100% rename from src/utils/is-previous-line-empty.js rename to src/utilities/is-previous-line-empty.js diff --git a/src/utils/line-column-to-index.js b/src/utilities/line-column-to-index.js similarity index 100% rename from src/utils/line-column-to-index.js rename to src/utilities/line-column-to-index.js diff --git a/src/utils/make-string.js b/src/utilities/make-string.js similarity index 100% rename from src/utils/make-string.js rename to src/utilities/make-string.js diff --git a/src/utils/narrow-emojis.evaluate.js b/src/utilities/narrow-emojis.evaluate.js similarity index 100% rename from src/utils/narrow-emojis.evaluate.js rename to src/utilities/narrow-emojis.evaluate.js diff --git a/src/utils/noop.js b/src/utilities/noop.js similarity index 100% rename from src/utils/noop.js rename to src/utilities/noop.js diff --git a/src/utils/object-omit.js b/src/utilities/object-omit.js similarity index 100% rename from src/utils/object-omit.js rename to src/utilities/object-omit.js diff --git a/src/utils/partition.js b/src/utilities/partition.js similarity index 100% rename from src/utils/partition.js rename to src/utilities/partition.js diff --git a/src/utils/pragma/pragma.evaluate.js b/src/utilities/pragma/pragma.evaluate.js similarity index 100% rename from src/utils/pragma/pragma.evaluate.js rename to src/utilities/pragma/pragma.evaluate.js diff --git a/src/utils/print-number.js b/src/utilities/print-number.js similarity index 100% rename from src/utils/print-number.js rename to src/utilities/print-number.js diff --git a/src/utils/print-string.js b/src/utilities/print-string.js similarity index 100% rename from src/utils/print-string.js rename to src/utilities/print-string.js diff --git a/src/utils/public.js b/src/utilities/public.js similarity index 99% rename from src/utils/public.js rename to src/utilities/public.js index e967c5927..444db8690 100644 --- a/src/utils/public.js +++ b/src/utilities/public.js @@ -137,7 +137,7 @@ export { addDanglingComment, addLeadingComment, addTrailingComment, -} from "../main/comments/utils.js"; +} from "../main/comments/utilities.js"; export { default as getAlignmentSize } from "./get-alignment-size.js"; export { default as getIndentSize } from "./get-indent-size.js"; export { default as getMaxContinuousCount } from "./get-max-continuous-count.js"; diff --git a/src/utils/read-file.js b/src/utilities/read-file.js similarity index 100% rename from src/utils/read-file.js rename to src/utilities/read-file.js diff --git a/src/utils/require-from-file.js b/src/utilities/require-from-file.js similarity index 100% rename from src/utils/require-from-file.js rename to src/utilities/require-from-file.js diff --git a/src/utils/skip-inline-comment.js b/src/utilities/skip-inline-comment.js similarity index 100% rename from src/utils/skip-inline-comment.js rename to src/utilities/skip-inline-comment.js diff --git a/src/utils/skip-newline.js b/src/utilities/skip-newline.js similarity index 100% rename from src/utils/skip-newline.js rename to src/utilities/skip-newline.js diff --git a/src/utils/skip-trailing-comment.js b/src/utilities/skip-trailing-comment.js similarity index 100% rename from src/utils/skip-trailing-comment.js rename to src/utilities/skip-trailing-comment.js diff --git a/src/utils/skip.js b/src/utilities/skip.js similarity index 100% rename from src/utils/skip.js rename to src/utilities/skip.js diff --git a/src/utils/try-combinations.js b/src/utilities/try-combinations.js similarity index 100% rename from src/utils/try-combinations.js rename to src/utilities/try-combinations.js diff --git a/src/utils/unexpected-node-error.js b/src/utilities/unexpected-node-error.js similarity index 100% rename from src/utils/unexpected-node-error.js rename to src/utilities/unexpected-node-error.js diff --git a/src/utils/whitespace-utils.js b/src/utilities/whitespace-utilities.js similarity index 98% rename from src/utils/whitespace-utils.js rename to src/utilities/whitespace-utilities.js index 9e9ee9c9b..7d451467a 100644 --- a/src/utils/whitespace-utils.js +++ b/src/utilities/whitespace-utilities.js @@ -1,6 +1,6 @@ import escapeStringRegexp from "escape-string-regexp"; -class WhitespaceUtils { +class WhitespaceUtilities { #whitespaceCharacters; constructor(whitespaceCharacters) { @@ -151,4 +151,4 @@ class WhitespaceUtils { } } -export default WhitespaceUtils; +export default WhitespaceUtilities; diff --git a/src/utils/html-whitespace-utils.js b/src/utils/html-whitespace-utils.js deleted file mode 100644 index d87e832fb..000000000 --- a/src/utils/html-whitespace-utils.js +++ /dev/null @@ -1,7 +0,0 @@ -import WhitespaceUtils from "./whitespace-utils.js"; - -// https://infra.spec.whatwg.org/#ascii-whitespace -const HTML_WHITESPACE_CHARACTERS = ["\t", "\n", "\f", "\r", " "]; -const htmlWhitespaceUtils = new WhitespaceUtils(HTML_WHITESPACE_CHARACTERS); - -export default htmlWhitespaceUtils; diff --git a/tests/config/prettier-plugins/prettier-plugin-dummy-toml/index.js b/tests/config/prettier-plugins/prettier-plugin-dummy-toml/index.js index 8523216a4..217d66ec1 100644 --- a/tests/config/prettier-plugins/prettier-plugin-dummy-toml/index.js +++ b/tests/config/prettier-plugins/prettier-plugin-dummy-toml/index.js @@ -1,5 +1,5 @@ import { outdent } from "outdent"; -import createPlugin from "../../utils/create-plugin.cjs"; +import createPlugin from "../../utilities/create-plugin.cjs"; const plugin = createPlugin({ name: "toml", diff --git a/tests/config/prettier-plugins/prettier-plugin-uppercase-rocks/index.js b/tests/config/prettier-plugins/prettier-plugin-uppercase-rocks/index.js index e3d8ea8a3..c2fca396b 100644 --- a/tests/config/prettier-plugins/prettier-plugin-uppercase-rocks/index.js +++ b/tests/config/prettier-plugins/prettier-plugin-uppercase-rocks/index.js @@ -1,4 +1,4 @@ -import createPlugin from "../../utils/create-plugin.cjs"; +import createPlugin from "../../utilities/create-plugin.cjs"; const plugin = createPlugin({ name: "uppercase-rocks", diff --git a/tests/config/require-standalone.cjs b/tests/config/require-standalone.cjs index c02c30979..5a0ac7777 100644 --- a/tests/config/require-standalone.cjs +++ b/tests/config/require-standalone.cjs @@ -1,7 +1,7 @@ "use strict"; const vm = require("vm"); const fastGlob = require("fast-glob"); -const createSandBox = require("./utils/create-sandbox.cjs"); +const createSandBox = require("./utilities/create-sandbox.cjs"); const sandbox = createSandBox({ files: fastGlob.sync(["standalone.js", "plugins/*.js"], { diff --git a/tests/config/run-format-test.js b/tests/config/run-format-test.js index 64bf003bf..c7fab1beb 100644 --- a/tests/config/run-format-test.js +++ b/tests/config/run-format-test.js @@ -3,11 +3,11 @@ import path from "node:path"; import url from "node:url"; import createEsmUtils from "esm-utils"; import getPrettier from "./get-prettier.js"; -import checkParsers from "./utils/check-parsers.js"; -import consistentEndOfLine from "./utils/consistent-end-of-line.js"; -import createSnapshot from "./utils/create-snapshot.js"; -import stringifyOptionsForTitle from "./utils/stringify-options-for-title.js"; -import visualizeEndOfLine from "./utils/visualize-end-of-line.js"; +import checkParsers from "./utilities/check-parsers.js"; +import consistentEndOfLine from "./utilities/consistent-end-of-line.js"; +import createSnapshot from "./utilities/create-snapshot.js"; +import stringifyOptionsForTitle from "./utilities/stringify-options-for-title.js"; +import visualizeEndOfLine from "./utilities/visualize-end-of-line.js"; const { __dirname } = createEsmUtils(import.meta); diff --git a/tests/config/utils/check-parsers.js b/tests/config/utilities/check-parsers.js similarity index 100% rename from tests/config/utils/check-parsers.js rename to tests/config/utilities/check-parsers.js diff --git a/tests/config/utils/consistent-end-of-line.js b/tests/config/utilities/consistent-end-of-line.js similarity index 100% rename from tests/config/utils/consistent-end-of-line.js rename to tests/config/utilities/consistent-end-of-line.js diff --git a/tests/config/utils/create-plugin.cjs b/tests/config/utilities/create-plugin.cjs similarity index 100% rename from tests/config/utils/create-plugin.cjs rename to tests/config/utilities/create-plugin.cjs diff --git a/tests/config/utils/create-sandbox.cjs b/tests/config/utilities/create-sandbox.cjs similarity index 100% rename from tests/config/utils/create-sandbox.cjs rename to tests/config/utilities/create-sandbox.cjs diff --git a/tests/config/utils/create-snapshot.js b/tests/config/utilities/create-snapshot.js similarity index 100% rename from tests/config/utils/create-snapshot.js rename to tests/config/utilities/create-snapshot.js diff --git a/tests/config/utils/stringify-options-for-title.js b/tests/config/utilities/stringify-options-for-title.js similarity index 100% rename from tests/config/utils/stringify-options-for-title.js rename to tests/config/utilities/stringify-options-for-title.js diff --git a/tests/config/utils/visualize-end-of-line.js b/tests/config/utilities/visualize-end-of-line.js similarity index 100% rename from tests/config/utils/visualize-end-of-line.js rename to tests/config/utilities/visualize-end-of-line.js diff --git a/tests/config/utils/visualize-range.js b/tests/config/utilities/visualize-range.js similarity index 100% rename from tests/config/utils/visualize-range.js rename to tests/config/utilities/visualize-range.js diff --git a/tests/integration/__tests__/bundle.js b/tests/integration/__tests__/bundle.js index 9e60e8708..2c05526ea 100644 --- a/tests/integration/__tests__/bundle.js +++ b/tests/integration/__tests__/bundle.js @@ -5,7 +5,7 @@ import fastGlob from "fast-glob"; import coreOptions from "../../../src/main/core-options.evaluate.js"; import codeSamples from "../../../website/playground/codeSamples.mjs"; import prettier from "../../config/prettier-entry.js"; -import createSandBox from "../../config/utils/create-sandbox.cjs"; +import createSandBox from "../../config/utilities/create-sandbox.cjs"; import { projectRoot } from "../env.js"; const { require, importModule } = createEsmUtils(import.meta); diff --git a/tests/integration/__tests__/doc-utils-clean-doc.js b/tests/integration/__tests__/doc-utilities-clean-doc.js similarity index 100% rename from tests/integration/__tests__/doc-utils-clean-doc.js rename to tests/integration/__tests__/doc-utilities-clean-doc.js diff --git a/tests/integration/__tests__/plugin-override-buitin-plugins.js b/tests/integration/__tests__/plugin-override-buitin-plugins.js index 9bc08ff03..50d408fba 100644 --- a/tests/integration/__tests__/plugin-override-buitin-plugins.js +++ b/tests/integration/__tests__/plugin-override-buitin-plugins.js @@ -1,5 +1,5 @@ import prettier from "../../config/prettier-entry.js"; -import createPlugin from "../../config/utils/create-plugin.cjs"; +import createPlugin from "../../config/utilities/create-plugin.cjs"; test("plugins can override builtin plugins", async () => { const outputWithoutPlugin = await prettier.format("foo()", { diff --git a/tests/integration/__tests__/util-shared.js b/tests/integration/__tests__/public-utilities.js similarity index 85% rename from tests/integration/__tests__/util-shared.js rename to tests/integration/__tests__/public-utilities.js index 3cb6eaf08..62095c11d 100644 --- a/tests/integration/__tests__/util-shared.js +++ b/tests/integration/__tests__/public-utilities.js @@ -1,36 +1,36 @@ import prettier from "../../config/prettier-entry.js"; -const sharedUtil = prettier.util; +const utilities = prettier.util; test("shared util has correct structure", () => { - expect(typeof sharedUtil.getMaxContinuousCount).toBe("function"); - expect(typeof sharedUtil.getStringWidth).toBe("function"); - expect(typeof sharedUtil.getAlignmentSize).toBe("function"); - expect(typeof sharedUtil.getIndentSize).toBe("function"); - expect(typeof sharedUtil.skip).toBe("function"); - expect(typeof sharedUtil.skipWhitespace).toBe("function"); - expect(typeof sharedUtil.skipSpaces).toBe("function"); - expect(typeof sharedUtil.skipToLineEnd).toBe("function"); - expect(typeof sharedUtil.skipEverythingButNewLine).toBe("function"); - expect(typeof sharedUtil.skipInlineComment).toBe("function"); - expect(typeof sharedUtil.skipTrailingComment).toBe("function"); - expect(typeof sharedUtil.skipNewline).toBe("function"); - expect(typeof sharedUtil.hasNewline).toBe("function"); - expect(typeof sharedUtil.hasNewlineInRange).toBe("function"); - expect(typeof sharedUtil.hasSpaces).toBe("function"); - expect(typeof sharedUtil.isNextLineEmpty).toBe("function"); - expect(typeof sharedUtil.isNextLineEmptyAfterIndex).toBe("function"); - expect(typeof sharedUtil.isPreviousLineEmpty).toBe("function"); - expect(typeof sharedUtil.getNextNonSpaceNonCommentCharacter).toBe("function"); - expect(typeof sharedUtil.getNextNonSpaceNonCommentCharacterIndex).toBe( + expect(typeof utilities.getMaxContinuousCount).toBe("function"); + expect(typeof utilities.getStringWidth).toBe("function"); + expect(typeof utilities.getAlignmentSize).toBe("function"); + expect(typeof utilities.getIndentSize).toBe("function"); + expect(typeof utilities.skip).toBe("function"); + expect(typeof utilities.skipWhitespace).toBe("function"); + expect(typeof utilities.skipSpaces).toBe("function"); + expect(typeof utilities.skipToLineEnd).toBe("function"); + expect(typeof utilities.skipEverythingButNewLine).toBe("function"); + expect(typeof utilities.skipInlineComment).toBe("function"); + expect(typeof utilities.skipTrailingComment).toBe("function"); + expect(typeof utilities.skipNewline).toBe("function"); + expect(typeof utilities.hasNewline).toBe("function"); + expect(typeof utilities.hasNewlineInRange).toBe("function"); + expect(typeof utilities.hasSpaces).toBe("function"); + expect(typeof utilities.isNextLineEmpty).toBe("function"); + expect(typeof utilities.isNextLineEmptyAfterIndex).toBe("function"); + expect(typeof utilities.isPreviousLineEmpty).toBe("function"); + expect(typeof utilities.getNextNonSpaceNonCommentCharacter).toBe("function"); + expect(typeof utilities.getNextNonSpaceNonCommentCharacterIndex).toBe( "function", ); - expect(typeof sharedUtil.makeString).toBe("function"); - expect(typeof sharedUtil.getPreferredQuote).toBe("function"); + expect(typeof utilities.makeString).toBe("function"); + expect(typeof utilities.getPreferredQuote).toBe("function"); }); test("sharedUtil.getMaxContinuousCount", () => { - const { getMaxContinuousCount } = sharedUtil; + const { getMaxContinuousCount } = utilities; expect(getMaxContinuousCount("|---|--|-|--|---|", "-")).toBe(3); expect(getMaxContinuousCount("|...|", ".")).toBe(3); @@ -50,7 +50,7 @@ test("sharedUtil.getMaxContinuousCount", () => { }); test("sharedUtil.getStringWidth", () => { - const { getStringWidth } = sharedUtil; + const { getStringWidth } = utilities; // From https://github.com/sindresorhus/string-width/blob/main/test.js expect(getStringWidth("abcde")).toBe(5); @@ -93,7 +93,7 @@ test("sharedUtil.getStringWidth", () => { }); test("sharedUtil.getAlignmentSize", () => { - const { getAlignmentSize } = sharedUtil; + const { getAlignmentSize } = utilities; expect(getAlignmentSize(" ")).toBe(3); expect(getAlignmentSize(" ", /* tabWidth */ 2, /* startIndex */ 2)).toBe(1); expect(getAlignmentSize("\t\t", /* tabWidth */ 2)).toBe(4); @@ -104,7 +104,7 @@ test("sharedUtil.getAlignmentSize", () => { }); test("sharedUtil.getIndentSize", () => { - const { getIndentSize } = sharedUtil; + const { getIndentSize } = utilities; expect(getIndentSize("\n a")).toBe(3); expect(getIndentSize("\n a", /* tabWidth */ 2)).toBe(3); expect(getIndentSize("\n\t\ta", /* tabWidth */ 2)).toBe(4); @@ -118,7 +118,7 @@ test("sharedUtil.getNextNonSpaceNonCommentCharacter and sharedUtil.getNextNonSpa const { getNextNonSpaceNonCommentCharacter, getNextNonSpaceNonCommentCharacterIndex, - } = sharedUtil; + } = utilities; const FAKE_NODE = { type: "Identifier", name: "a" }; { @@ -169,7 +169,7 @@ test("sharedUtil.getNextNonSpaceNonCommentCharacter and sharedUtil.getNextNonSpa test("sharedUtil.isPreviousLineEmpty, sharedUtil.isNextLineEmpty and sharedUtil.isNextLineEmptyAfterIndex", () => { const { isPreviousLineEmpty, isNextLineEmpty, isNextLineEmptyAfterIndex } = - sharedUtil; + utilities; const FAKE_NODE_A = { type: "Identifier", name: "a" }; const FAKE_NODE_B = { type: "Identifier", name: "b" }; @@ -213,7 +213,7 @@ test("sharedUtil.isPreviousLineEmpty, sharedUtil.isNextLineEmpty and sharedUtil. }); test("sharedUtil.makeString", () => { - const { makeString } = sharedUtil; + const { makeString } = utilities; const DOUBLE_QUOTE = '"'; const SINGLE_QUOTE = "'"; @@ -268,7 +268,7 @@ test("sharedUtil.makeString", () => { }); test("sharedUtil.getPreferredQuote", () => { - const { getPreferredQuote } = sharedUtil; + const { getPreferredQuote } = utilities; const DOUBLE_QUOTE = '"'; const SINGLE_QUOTE = "'"; diff --git a/tests/integration/__tests__/schema.js b/tests/integration/__tests__/schema.js index 31f8b51db..218b9178f 100644 --- a/tests/integration/__tests__/schema.js +++ b/tests/integration/__tests__/schema.js @@ -1,4 +1,4 @@ -import { generateSchemaData } from "../../../scripts/utils/generate-schema.js"; +import { generateSchemaData } from "../../../scripts/utilities/generate-schema.js"; import prettier from "../../config/prettier-entry.js"; test("schema", async () => { diff --git a/tests/integration/cli/infer-parser/override-builtin-plugin-languages/dummy-js-plugin.js b/tests/integration/cli/infer-parser/override-builtin-plugin-languages/dummy-js-plugin.js index ed9c1f03c..e73ff6e8d 100644 --- a/tests/integration/cli/infer-parser/override-builtin-plugin-languages/dummy-js-plugin.js +++ b/tests/integration/cli/infer-parser/override-builtin-plugin-languages/dummy-js-plugin.js @@ -1,5 +1,5 @@ -import createPlugin from "../../../../config/utils/create-plugin.cjs"; +import createPlugin from "../../../../config/utilities/create-plugin.cjs"; const PARSER_NAME = 'dummy-js-parser' const PRINT_MARK = `formatted by '${PARSER_NAME}' parser` diff --git a/tests/integration/plugins/automatic/prettier-plugin-baz.js b/tests/integration/plugins/automatic/prettier-plugin-baz.js index 61fa15fb7..a4dd32b3d 100644 --- a/tests/integration/plugins/automatic/prettier-plugin-baz.js +++ b/tests/integration/plugins/automatic/prettier-plugin-baz.js @@ -1,4 +1,4 @@ -import createPlugin from "../../../config/utils/create-plugin.cjs"; +import createPlugin from "../../../config/utilities/create-plugin.cjs"; const plugin = createPlugin({ name: "baz", diff --git a/tests/integration/plugins/languages/is-supported.js b/tests/integration/plugins/languages/is-supported.js index 5db7588f8..6bea97665 100644 --- a/tests/integration/plugins/languages/is-supported.js +++ b/tests/integration/plugins/languages/is-supported.js @@ -1,5 +1,5 @@ import path from "node:path"; -import createPlugin from "../../../config/utils/create-plugin.cjs"; +import createPlugin from "../../../config/utilities/create-plugin.cjs"; const PARSER_NAME = "parser-name-inferred-from-language-is-supported"; const PRINT_MARK = `formatted by '${PARSER_NAME}' parser`; diff --git a/tests/unit/get-descendants.js b/tests/unit/get-descendants.js index 521d5999c..037b15d1b 100644 --- a/tests/unit/get-descendants.js +++ b/tests/unit/get-descendants.js @@ -1,4 +1,4 @@ -import { getDescendants } from "../../src/utils/ast-utils.js"; +import { getDescendants } from "../../src/utilities/ast.js"; const tree = { id: "tree", diff --git a/tests/unit/get-parser-plugin-by-parser-name.js b/tests/unit/get-parser-plugin-by-parser-name.js index cf3fdd2a4..5abf26404 100644 --- a/tests/unit/get-parser-plugin-by-parser-name.js +++ b/tests/unit/get-parser-plugin-by-parser-name.js @@ -1,6 +1,6 @@ import { ConfigError } from "../../src/common/errors.js"; import { getParserPluginByParserName } from "../../src/main/parser-and-printer.js"; -import createPlugin from "../config/utils/create-plugin.cjs"; +import createPlugin from "../config/utilities/create-plugin.cjs"; describe("unit tests for getParserPluginByParserName", () => { const getMockPlugins = (name) => [ diff --git a/tests/unit/get-printer-plugin-by-ast-format.js b/tests/unit/get-printer-plugin-by-ast-format.js index 61f75e735..d257293c3 100644 --- a/tests/unit/get-printer-plugin-by-ast-format.js +++ b/tests/unit/get-printer-plugin-by-ast-format.js @@ -1,6 +1,6 @@ import { ConfigError } from "../../src/common/errors.js"; import { getPrinterPluginByAstFormat } from "../../src/main/parser-and-printer.js"; -import createPlugin from "../config/utils/create-plugin.cjs"; +import createPlugin from "../config/utilities/create-plugin.cjs"; describe("unit tests for getPrinterPluginByAstFormat", () => { const getMockPlugins = (name) => [ diff --git a/tests/unit/make-string.js b/tests/unit/make-string.js index b8f04bf66..206a1efae 100644 --- a/tests/unit/make-string.js +++ b/tests/unit/make-string.js @@ -1,4 +1,4 @@ -import makeString from "../../src/utils/make-string.js"; +import makeString from "../../src/utilities/make-string.js"; const DOUBLE_QUOTE = '"'; const SINGLE_QUOTE = "'"; diff --git a/tests/unit/whitespace-utils.js b/tests/unit/whitespace-utilities.js similarity index 73% rename from tests/unit/whitespace-utils.js rename to tests/unit/whitespace-utilities.js index 47193ce46..b2d22cd37 100644 --- a/tests/unit/whitespace-utils.js +++ b/tests/unit/whitespace-utilities.js @@ -1,20 +1,22 @@ -import WhitespaceUtils from "../../src/utils/whitespace-utils.js"; +import WhitespaceUtilities from "../../src/utilities/whitespace-utilities.js"; it("constructor", () => { - expect(() => new WhitespaceUtils()).toThrow(TypeError); - expect(() => new WhitespaceUtils(1)).toThrow(TypeError); - expect(() => new WhitespaceUtils("")).toThrow(TypeError); - expect(() => new WhitespaceUtils([])).toThrow(TypeError); - expect(() => new WhitespaceUtils([""])).toThrow(TypeError); - expect(() => new WhitespaceUtils(["a"])).toThrow(TypeError); - expect(() => new WhitespaceUtils("a")).toThrow(TypeError); - expect(() => new WhitespaceUtils(["\r\n"])).toThrow(TypeError); + expect(() => new WhitespaceUtilities()).toThrow(TypeError); + expect(() => new WhitespaceUtilities(1)).toThrow(TypeError); + expect(() => new WhitespaceUtilities("")).toThrow(TypeError); + expect(() => new WhitespaceUtilities([])).toThrow(TypeError); + expect(() => new WhitespaceUtilities([""])).toThrow(TypeError); + expect(() => new WhitespaceUtilities(["a"])).toThrow(TypeError); + expect(() => new WhitespaceUtilities("a")).toThrow(TypeError); + expect(() => new WhitespaceUtilities(["\r\n"])).toThrow(TypeError); - expect(new WhitespaceUtils("\r\n")).toBeInstanceOf(WhitespaceUtils); - expect(new WhitespaceUtils(["\r", "\n"])).toBeInstanceOf(WhitespaceUtils); + expect(new WhitespaceUtilities("\r\n")).toBeInstanceOf(WhitespaceUtilities); + expect(new WhitespaceUtilities(["\r", "\n"])).toBeInstanceOf( + WhitespaceUtilities, + ); }); -const utils = new WhitespaceUtils(" "); +const utils = new WhitespaceUtilities(" "); describe("trimStart", () => { for (const [string, expected] of [ ["", ""], diff --git a/website/blog/2023-07-05-3.0.0.md b/website/blog/2023-07-05-3.0.0.md index fdf99b40e..104a4639f 100644 --- a/website/blog/2023-07-05-3.0.0.md +++ b/website/blog/2023-07-05-3.0.0.md @@ -2092,14 +2092,14 @@ Align with other tools like ESLint and Stylelint. ```jsx // Prettier 2.8 Checking formatting... -[warn] src\utils\create-get-visitor-keys.js -[warn] src\utils\unexpected-node-error.js +[warn] src\utilities\create-get-visitor-keys.js +[warn] src\utilities\unexpected-node-error.js [warn] Code style issues found in 2 files. Forgot to run Prettier? // Prettier 3.0 Checking formatting... -[warn] src/utils/create-get-visitor-keys.js -[warn] src/utils/unexpected-node-error.js +[warn] src/utilities/create-get-visitor-keys.js +[warn] src/utilities/unexpected-node-error.js [warn] Code style issues found in 2 files. Forgot to run Prettier? ``` diff --git a/website/playground/Playground.jsx b/website/playground/Playground.jsx index 5edd3b201..5e3f0bb9f 100644 --- a/website/playground/Playground.jsx +++ b/website/playground/Playground.jsx @@ -11,7 +11,14 @@ import { Checkbox } from "./sidebar/inputs.jsx"; import Option from "./sidebar/options.jsx"; import SidebarOptions from "./sidebar/SidebarOptions.jsx"; import * as urlHash from "./urlHash.js"; -import * as util from "./util.js"; +import { + buildCliArgs, + convertOffsetToSelection, + convertSelectionToRange, + getAstAutoFold, + getCodemirrorMode, + getDefaults, +} from "./utilities.js"; const { React } = window; @@ -61,10 +68,7 @@ class Playground extends React.Component { const original = urlHash.read(); - const defaultOptions = util.getDefaults( - props.availableOptions, - ENABLED_OPTIONS, - ); + const defaultOptions = getDefaults(props.availableOptions, ENABLED_OPTIONS); const options = Object.assign(defaultOptions, original.options); @@ -110,13 +114,13 @@ class Playground extends React.Component { if (this.state.trackCursorOffset) { this.handleOptionValueChange( this.cursorOffsetOption, - util.convertSelectionToRange(selection, this.state.content)[0], + convertSelectionToRange(selection, this.state.content)[0], ); } }; this.setSelectionAsRange = () => { const { selection, content, options } = this.state; - const [rangeStart, rangeEnd] = util.convertSelectionToRange( + const [rangeStart, rangeEnd] = convertSelectionToRange( selection, content, ); @@ -182,7 +186,7 @@ class Playground extends React.Component { "rangeEnd", "cursorOffset", ]); - const cliOptions = util.buildCliArgs(orderedOptions, options); + const cliOptions = buildCliArgs(orderedOptions, options); return formatMarkdown({ input: content, @@ -207,7 +211,7 @@ class Playground extends React.Component { return this.props.worker .format(content, { parser: "__js_expression", - cursorOffset: util.convertSelectionToRange(selection, content)[0], + cursorOffset: convertSelectionToRange(selection, content)[0], }) .then(({ error, formatted, cursorOffset }) => { if (error) { @@ -216,7 +220,7 @@ class Playground extends React.Component { this.setState({ content: formatted, - selection: util.convertOffsetToSelection(cursorOffset, formatted), + selection: convertOffsetToSelection(cursorOffset, formatted), }); }); } @@ -224,13 +228,13 @@ class Playground extends React.Component { insertDummyId() { const { content, selection } = this.state; const dummyId = generateDummyId(); - const range = util.convertSelectionToRange(selection, content); + const range = convertSelectionToRange(selection, content); const modifiedContent = content.slice(0, range[0]) + dummyId + content.slice(range[1]); this.setState({ content: modifiedContent, - selection: util.convertOffsetToSelection( + selection: convertOffsetToSelection( range[0] + dummyId.length, modifiedContent, ), @@ -420,7 +424,7 @@ class Playground extends React.Component {
{editorState.showInput ? ( ) : null} {editorState.showPreprocessedAst && !isDocExplorer ? ( ) : null} {editorState.showDoc && !isDocExplorer ? ( @@ -454,12 +458,12 @@ class Playground extends React.Component { {editorState.showComments && !isDocExplorer ? ( ) : null} {editorState.showOutput ? ( diff --git a/website/playground/index.jsx b/website/playground/index.jsx index ef86d50d9..f26d4b325 100644 --- a/website/playground/index.jsx +++ b/website/playground/index.jsx @@ -2,7 +2,7 @@ import "codemirror-graphql/cm6-legacy/mode.esm.js"; import "./install-service-worker.js"; import Playground from "./Playground.jsx"; -import { fixPrettierVersion } from "./util.js"; +import { fixPrettierVersion } from "./utilities.js"; import VersionLink from "./VersionLink.jsx"; import WorkerApi from "./WorkerApi.js"; diff --git a/website/playground/sidebar/SidebarOptions.jsx b/website/playground/sidebar/SidebarOptions.jsx index f3f8bdbc7..f3b01d440 100644 --- a/website/playground/sidebar/SidebarOptions.jsx +++ b/website/playground/sidebar/SidebarOptions.jsx @@ -1,7 +1,7 @@ import { SidebarCategory } from "./components.jsx"; import Option from "./options.jsx"; -// Copied from `/src/cli/utils.js` +// Copied from `/src/cli/utilities.js` function groupBy(array, iteratee) { const result = Object.create(null); diff --git a/website/playground/util.js b/website/playground/utilities.js similarity index 100% rename from website/playground/util.js rename to website/playground/utilities.js