Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Drop prettier/standalone from the expression formatter and load the printer on demand (#79639)

Romeo Van Snickaee69e552a10
diff --git a/frontend/src/metabase/querying/expressions/formatter/formatter.ts b/frontend/src/metabase/querying/expressions/formatter/formatter.ts
index 412cd4ed3af..c4d568eed17 100644
--- a/frontend/src/metabase/querying/expressions/formatter/formatter.ts
+++ b/frontend/src/metabase/querying/expressions/formatter/formatter.ts
@@ -1,428 +1,24 @@
-import type { AstPath, Doc, ParserOptions, Plugin } from "prettier";
-import { builders } from "prettier/doc";
-import { format as pformat } from "prettier/standalone";
-
-import { parseNumber } from "metabase/utils/number";
import * as Lib from "metabase-lib";
-import { isa } from "metabase-lib/v1/types/utils/isa";
-
-import { getClauseDefinition } from "../clause";
-import {
- formatDimensionName,
- formatIdentifier,
- formatMetricName,
- formatSegmentName,
-} from "../identifier";
-import { parsePunctuator } from "../punctuator";
-import { type StartDelimiter, formatStringLiteral } from "../string";
-
-import {
- pathMatchers as check,
- isDimensionOperator,
- isExpressionOperator,
- isValueOperator,
-} from "./utils";
-export type ExpressionNode = Lib.ExpressionParts | Lib.ExpressionArg | null;
-
-export type FormatClauseOptions = {
- query: Lib.Query;
- stageIndex: number;
-} & FormatOptions;
+import type { FormatClauseOptions, FormatOptions } from "./types";
export async function format(
expression: Lib.Expressionable,
options: FormatClauseOptions,
) {
- // prettier expects us to pass a string, but we have the AST already
- // so we pass a bogus string and ignore it. The actual ast is passed via
- // the root option.
const { query, stageIndex } = options;
const parts = Lib.expressionParts(query, stageIndex, expression);
return formatExpressionParts(parts, options);
}
-type FormatOptions = {
- query?: Lib.Query;
- stageIndex?: number;
- availableColumns?: Lib.ColumnMetadata[];
- printWidth?: number;
- stringDelimiter?: StartDelimiter;
-};
-
+/**
+ * The printer pulls in prettier's document layout engine, so it is loaded on
+ * demand to keep it out of the initial bundle.
+ */
export async function formatExpressionParts(
root: Lib.ExpressionParts | Lib.ExpressionArg,
options: FormatOptions = {},
) {
- // prettier expects us to pass a string, but we have the AST already
- // so we pass a bogus string and ignore it. The actual ast is passed via
- // the root option.
- return pformat("__not_used__", {
- parser: PRETTIER_PLUGIN_NAME,
- plugins: [plugin({ ...options, root })],
- printWidth: options.printWidth ?? 80,
- });
-}
-
-const PRETTIER_PLUGIN_NAME = "custom-expression";
-
-type InternalOptions = {
- root: ExpressionNode;
-};
-
-// Set up a prettier plugin that formats expressions
-function plugin(
- options: FormatOptions & InternalOptions,
-): Plugin<ExpressionNode> {
- return {
- languages: [
- {
- name: PRETTIER_PLUGIN_NAME,
- parsers: [PRETTIER_PLUGIN_NAME],
- },
- ],
- parsers: {
- [PRETTIER_PLUGIN_NAME]: {
- astFormat: PRETTIER_PLUGIN_NAME,
- parse() {
- return options.root;
- },
- locStart() {
- throw new Error("Not implemented");
- },
- locEnd() {
- throw new Error("Not implemented");
- },
- },
- },
- printers: {
- [PRETTIER_PLUGIN_NAME]: {
- preprocess(ast, opts) {
- opts.extra = options;
- return ast;
- },
- print,
- },
- },
- };
-}
-
-const {
- // prettier helpers
- join,
- indent,
- softline,
- line,
- group,
- ifBreak,
-} = builders;
-
-type Print = (path: AstPath<ExpressionNode>) => Doc;
-
-function print(
- path: AstPath<ExpressionNode>,
- options: ParserOptions<ExpressionNode> & { extra: FormatOptions },
- print: Print,
-): Doc {
- if (path.node === null) {
- return "";
- } else if (check.isNumberLiteral(path)) {
- return formatNumberLiteral(path.node);
- } else if (check.isBooleanLiteral(path)) {
- return formatBooleanLiteral(path.node);
- } else if (check.isStringLiteral(path)) {
- return formatStringLiteral(path.node, options.extra.stringDelimiter);
- } else if (check.isColumnMetadata(path)) {
- return formatColumn(path, options.extra);
- } else if (check.isMetricMetadata(path)) {
- return formatMetric(path, options.extra);
- } else if (check.isMeasureMetadata(path)) {
- return formatMeasure(path, options.extra);
- } else if (check.isSegmentMetadata(path)) {
- return formatSegment(path, options.extra);
- } else if (check.isExpressionOperator(path)) {
- return formatOperator(path, print);
- } else if (check.isDimensionOperator(path)) {
- return formatDimension(path);
- } else if (check.isValueOperator(path)) {
- return formatValueExpression(path, print);
- } else if (check.isExpressionParts(path)) {
- return formatFunctionCall(path, print);
- }
-
- throw new Error(`Unknown MBQL clause: ${JSON.stringify(path.node)}`);
-}
-
-// Helper to recurse into an AST node that is not easily expressed as a
-// property of the node currently in path.
-function recurse<T, R>(
- path: AstPath<T>,
- callback: (path: AstPath<T>) => R,
- value: T,
-): R {
- const { length } = path.stack;
- path.stack.push(value);
- try {
- return callback(path);
- } finally {
- path.stack.length = length;
- }
-}
-
-function formatNumberLiteral(node: number | bigint): Doc {
- return String(node);
-}
-
-function formatBooleanLiteral(node: boolean): Doc {
- return node ? "True" : "False";
-}
-
-function assert(condition: any, msg: string): asserts condition {
- if (!condition) {
- throw new Error(msg);
- }
-}
-
-function formatColumn(
- path: AstPath<Lib.ColumnMetadata>,
- options: FormatOptions,
-): Doc {
- const { query, stageIndex } = options;
- const column = path.node;
-
- assert(query !== undefined, "Expected query");
- assert(typeof stageIndex === "number", "Expected stageIndex");
- assert(Lib.isColumnMetadata(column), "Expected column");
-
- const info = Lib.displayInfo(query, stageIndex, column);
- return formatDimensionName(info.longDisplayName);
-}
-
-function formatMetric(
- path: AstPath<Lib.MetricMetadata>,
- options: FormatOptions,
-): Doc {
- const metric = path.node;
- const { query, stageIndex } = options;
-
- assert(query !== undefined, "Expected query");
- assert(typeof stageIndex === "number", "Expected stageIndex");
- assert(Lib.isMetricMetadata(metric), "Expected metric");
-
- const displayInfo = Lib.displayInfo(query, stageIndex, metric);
- return formatMetricName(displayInfo.displayName);
-}
-
-function formatMeasure(
- path: AstPath<Lib.MeasureMetadata>,
- options: FormatOptions,
-): Doc {
- const metric = path.node;
- const { query, stageIndex } = options;
-
- assert(query !== undefined, "Expected query");
- assert(typeof stageIndex === "number", "Expected stageIndex");
- assert(Lib.isMeasureMetadata(metric), "Expected measure");
-
- const displayInfo = Lib.displayInfo(query, stageIndex, metric);
- return formatMetricName(displayInfo.displayName);
-}
-
-function formatSegment(
- path: AstPath<Lib.SegmentMetadata>,
- options: FormatOptions,
-) {
- const segment = path.node;
- const { query, stageIndex } = options;
-
- assert(query !== undefined, "Expected query");
- assert(typeof stageIndex === "number", "Expected stageIndex");
- assert(Lib.isSegmentMetadata(segment), "Expected segment");
-
- const displayInfo = Lib.displayInfo(query, stageIndex, segment);
- return formatSegmentName(displayInfo.displayName);
-}
-
-function formatDimension(path: AstPath<Lib.ExpressionParts>): Doc {
- const { node } = path;
- assert(isDimensionOperator(node), "Expected dimension");
-
- const name = node.args[0];
- assert(typeof name === "string", "Expected expression name to be a string");
-
- return formatIdentifier(name);
-}
-
-function formatFunctionCall(
- path: AstPath<Lib.ExpressionParts>,
- print: Print,
-): Doc {
- const { node } = path;
-
- const args = node.args.map((arg: ExpressionNode) =>
- recurse(path, print, arg),
- );
-
- const options = formatExpressionOptions(node.options);
- if (options) {
- args.push(options);
- }
-
- // render a call expression as
- //
- // callee(arg1, arg2, ...)
- //
- // or, when not enough space
- //
- // callee(
- // arg1,
- // arg2,
- // ...
- // )
- return group([
- displayName(node.operator),
- "(",
- indent([
- // indent args
- softline,
- join([",", line], args),
- ]),
- softline,
- ")",
- ]);
-}
-
-function formatExpressionOptions(options: Lib.ExpressionOptions): Doc | null {
- if ("case-sensitive" in options && !options["case-sensitive"]) {
- return formatStringLiteral("case-insensitive");
- }
- if ("include-current" in options && options["include-current"]) {
- return formatStringLiteral("include-current");
- }
- if ("mode" in options && options.mode) {
- const camelCased = options.mode.replace(/-\w/g, (match) =>
- match.charAt(1).toUpperCase(),
- );
- return formatStringLiteral(camelCased);
- }
- return null;
-}
-
-function formatOperator(path: AstPath<Lib.ExpressionParts>, print: Print): Doc {
- const { node } = path;
-
- assert(
- isExpressionOperator(node),
- `Expected operator but got ${node.operator}`,
- );
-
- const operatorGoesOnNewline =
- node.operator === "and" || node.operator === "or";
-
- const args = node.args.map((arg, index) => {
- const ln = index === 0 || operatorGoesOnNewline ? "" : line;
-
- function ind(doc: Doc) {
- if (index === 0 || operatorGoesOnNewline) {
- return doc;
- }
- return indent(doc);
- }
-
- if (
- !Lib.isExpressionParts(arg) ||
- isValueOperator(arg) ||
- isDimensionOperator(arg)
- ) {
- // Not a call expression so not an operator
- return ind([ln, recurse(path, print, path.node.args[index])]);
- }
-
- const argOperator = arg.operator;
- const formattedArg = recurse(path, print, path.node.args[index]);
-
- const operatorPrecedence = precedence(node.operator);
- const argPrecedence = precedence(argOperator);
-
- const isLowerPrecedence = operatorPrecedence > argPrecedence;
- const isSamePrecedence = operatorPrecedence === argPrecedence;
-
- // "*","/" always have two arguments.
- // If the second argument of "/" is an expression, we have to calculate it first.
- // Hence, adding parenthesis.
- // "a / b * c" vs "a / (b * c)", "a / b / c" vs "a / (b / c)"
- // "a - b + c" vs "a - (b + c)", "a - b - c" vs "a - (b - c)"
- const isSamePrecedenceWithExecutionPriority = index > 0 && isSamePrecedence;
-
- const shouldUseParens =
- isLowerPrecedence || isSamePrecedenceWithExecutionPriority;
-
- if (shouldUseParens) {
- return ind(
- group([
- ln,
- "(",
- group(
- ifBreak(
- [indent([softline, group(formattedArg)]), softline],
- formattedArg,
- ),
- ),
- ")",
- ]),
- );
- } else {
- return ind([ln, formattedArg]);
- }
- });
-
- if (isUnaryOperator(node.operator)) {
- return [displayName(node.operator), " ", args[0]];
- }
-
- if (operatorGoesOnNewline) {
- return group(join([line, displayName(node.operator), " "], args));
- } else {
- return group(join([" ", displayName(node.operator)], args));
- }
-}
-
-function precedence(op: string): number {
- return parsePunctuator(op)?.precedence ?? Infinity;
-}
-
-function isUnaryOperator(op: Lib.ExpressionOperator) {
- return getClauseDefinition(op)?.args.length === 1;
-}
-
-function formatValueExpression(
- path: AstPath<Lib.ExpressionParts>,
- print: Print,
-): Doc {
- const { node } = path;
-
- assert(isValueOperator(node), "Expected value");
-
- const {
- args: [value],
- options,
- } = node;
-
- const baseType = options?.["base-type"];
- if (
- typeof value === "string" &&
- typeof baseType === "string" &&
- isa(baseType, "type/BigInteger")
- ) {
- const number = parseNumber(value);
- if (number != null) {
- return recurse(path, print, number);
- }
- }
- return recurse(path, print, node.args[0]);
-}
-
-function displayName(name: Lib.ExpressionOperator): string {
- assert(name !== "value", "Unexpected value clause");
- return getClauseDefinition(name)?.displayName ?? name;
+ const { printExpressionParts } = await import("./print");
+ return printExpressionParts(root, options);
}
diff --git a/frontend/src/metabase/querying/expressions/formatter/index.ts b/frontend/src/metabase/querying/expressions/formatter/index.ts
index 67c3953abdd..7442a1557ec 100644
--- a/frontend/src/metabase/querying/expressions/formatter/index.ts
+++ b/frontend/src/metabase/querying/expressions/formatter/index.ts
@@ -1 +1,2 @@
export * from "./formatter";
+export * from "./types";
diff --git a/frontend/src/metabase/querying/expressions/formatter/print.ts b/frontend/src/metabase/querying/expressions/formatter/print.ts
new file mode 100644
index 00000000000..19e783fe5d7
--- /dev/null
+++ b/frontend/src/metabase/querying/expressions/formatter/print.ts
@@ -0,0 +1,358 @@
+import { builders, printer } from "prettier/doc";
+
+import { parseNumber } from "metabase/utils/number";
+import * as Lib from "metabase-lib";
+import { isa } from "metabase-lib/v1/types/utils/isa";
+
+import { getClauseDefinition } from "../clause";
+import {
+ formatDimensionName,
+ formatIdentifier,
+ formatMetricName,
+ formatSegmentName,
+} from "../identifier";
+import { parsePunctuator } from "../punctuator";
+import { formatStringLiteral } from "../string";
+
+import type { ExpressionNode, FormatOptions } from "./types";
+import {
+ Path,
+ pathMatchers as check,
+ isDimensionOperator,
+ isExpressionOperator,
+ isValueOperator,
+} from "./utils";
+
+type Doc = builders.Doc;
+
+const {
+ // prettier helpers
+ join,
+ indent,
+ softline,
+ line,
+ group,
+ ifBreak,
+} = builders;
+
+const DEFAULT_PRINT_WIDTH = 80;
+const TAB_WIDTH = 2;
+
+export function printExpressionParts(
+ root: ExpressionNode,
+ options: FormatOptions,
+): string {
+ const doc = print(new Path(root), options);
+ const { formatted } = printer.printDocToString(doc, {
+ printWidth: options.printWidth ?? DEFAULT_PRINT_WIDTH,
+ tabWidth: TAB_WIDTH,
+ });
+ return formatted;
+}
+
+function print(path: Path<ExpressionNode>, options: FormatOptions): Doc {
+ if (path.node === null) {
+ return "";
+ } else if (check.isNumberLiteral(path)) {
+ return formatNumberLiteral(path.node);
+ } else if (check.isBooleanLiteral(path)) {
+ return formatBooleanLiteral(path.node);
+ } else if (check.isStringLiteral(path)) {
+ return formatStringLiteral(path.node, options.stringDelimiter);
+ } else if (check.isColumnMetadata(path)) {
+ return formatColumn(path, options);
+ } else if (check.isMetricMetadata(path)) {
+ return formatMetric(path, options);
+ } else if (check.isMeasureMetadata(path)) {
+ return formatMeasure(path, options);
+ } else if (check.isSegmentMetadata(path)) {
+ return formatSegment(path, options);
+ } else if (check.isExpressionOperator(path)) {
+ return formatOperator(path, options);
+ } else if (check.isDimensionOperator(path)) {
+ return formatDimension(path);
+ } else if (check.isValueOperator(path)) {
+ return formatValueExpression(path, options);
+ } else if (check.isExpressionParts(path)) {
+ return formatFunctionCall(path, options);
+ }
+
+ throw new Error(`Unknown MBQL clause: ${JSON.stringify(path.node)}`);
+}
+
+// Helper to recurse into an AST node that is not easily expressed as a
+// property of the node currently in path.
+function recurse(
+ path: Path<ExpressionNode>,
+ options: FormatOptions,
+ node: ExpressionNode,
+): Doc {
+ const { length } = path.stack;
+ path.stack.push(node);
+ try {
+ return print(path, options);
+ } finally {
+ path.stack.length = length;
+ }
+}
+
+function formatNumberLiteral(node: number | bigint): Doc {
+ return String(node);
+}
+
+function formatBooleanLiteral(node: boolean): Doc {
+ return node ? "True" : "False";
+}
+
+function assert(condition: any, msg: string): asserts condition {
+ if (!condition) {
+ throw new Error(msg);
+ }
+}
+
+function formatColumn(
+ path: Path<Lib.ColumnMetadata>,
+ options: FormatOptions,
+): Doc {
+ const { query, stageIndex } = options;
+ const column = path.node;
+
+ assert(query !== undefined, "Expected query");
+ assert(typeof stageIndex === "number", "Expected stageIndex");
+ assert(Lib.isColumnMetadata(column), "Expected column");
+
+ const info = Lib.displayInfo(query, stageIndex, column);
+ return formatDimensionName(info.longDisplayName);
+}
+
+function formatMetric(
+ path: Path<Lib.MetricMetadata>,
+ options: FormatOptions,
+): Doc {
+ const metric = path.node;
+ const { query, stageIndex } = options;
+
+ assert(query !== undefined, "Expected query");
+ assert(typeof stageIndex === "number", "Expected stageIndex");
+ assert(Lib.isMetricMetadata(metric), "Expected metric");
+
+ const displayInfo = Lib.displayInfo(query, stageIndex, metric);
+ return formatMetricName(displayInfo.displayName);
+}
+
+function formatMeasure(
+ path: Path<Lib.MeasureMetadata>,
+ options: FormatOptions,
+): Doc {
+ const metric = path.node;
+ const { query, stageIndex } = options;
+
+ assert(query !== undefined, "Expected query");
+ assert(typeof stageIndex === "number", "Expected stageIndex");
+ assert(Lib.isMeasureMetadata(metric), "Expected measure");
+
+ const displayInfo = Lib.displayInfo(query, stageIndex, metric);
+ return formatMetricName(displayInfo.displayName);
+}
+
+function formatSegment(
+ path: Path<Lib.SegmentMetadata>,
+ options: FormatOptions,
+) {
+ const segment = path.node;
+ const { query, stageIndex } = options;
+
+ assert(query !== undefined, "Expected query");
+ assert(typeof stageIndex === "number", "Expected stageIndex");
+ assert(Lib.isSegmentMetadata(segment), "Expected segment");
+
+ const displayInfo = Lib.displayInfo(query, stageIndex, segment);
+ return formatSegmentName(displayInfo.displayName);
+}
+
+function formatDimension(path: Path<Lib.ExpressionParts>): Doc {
+ const { node } = path;
+ assert(isDimensionOperator(node), "Expected dimension");
+
+ const name = node.args[0];
+ assert(typeof name === "string", "Expected expression name to be a string");
+
+ return formatIdentifier(name);
+}
+
+function formatFunctionCall(
+ path: Path<Lib.ExpressionParts>,
+ options: FormatOptions,
+): Doc {
+ const { node } = path;
+
+ const args = node.args.map((arg: ExpressionNode) =>
+ recurse(path, options, arg),
+ );
+
+ const expressionOptions = formatExpressionOptions(node.options);
+ if (expressionOptions) {
+ args.push(expressionOptions);
+ }
+
+ // render a call expression as
+ //
+ // callee(arg1, arg2, ...)
+ //
+ // or, when not enough space
+ //
+ // callee(
+ // arg1,
+ // arg2,
+ // ...
+ // )
+ return group([
+ displayName(node.operator),
+ "(",
+ indent([
+ // indent args
+ softline,
+ join([",", line], args),
+ ]),
+ softline,
+ ")",
+ ]);
+}
+
+function formatExpressionOptions(options: Lib.ExpressionOptions): Doc | null {
+ if ("case-sensitive" in options && !options["case-sensitive"]) {
+ return formatStringLiteral("case-insensitive");
+ }
+ if ("include-current" in options && options["include-current"]) {
+ return formatStringLiteral("include-current");
+ }
+ if ("mode" in options && options.mode) {
+ const camelCased = options.mode.replace(/-\w/g, (match) =>
+ match.charAt(1).toUpperCase(),
+ );
+ return formatStringLiteral(camelCased);
+ }
+ return null;
+}
+
+function formatOperator(
+ path: Path<Lib.ExpressionParts>,
+ options: FormatOptions,
+): Doc {
+ const { node } = path;
+
+ assert(
+ isExpressionOperator(node),
+ `Expected operator but got ${node.operator}`,
+ );
+
+ const operatorGoesOnNewline =
+ node.operator === "and" || node.operator === "or";
+
+ const args = node.args.map((arg, index) => {
+ const ln = index === 0 || operatorGoesOnNewline ? "" : line;
+
+ function ind(doc: Doc) {
+ if (index === 0 || operatorGoesOnNewline) {
+ return doc;
+ }
+ return indent(doc);
+ }
+
+ if (
+ !Lib.isExpressionParts(arg) ||
+ isValueOperator(arg) ||
+ isDimensionOperator(arg)
+ ) {
+ // Not a call expression so not an operator
+ return ind([ln, recurse(path, options, path.node.args[index])]);
+ }
+
+ const argOperator = arg.operator;
+ const formattedArg = recurse(path, options, path.node.args[index]);
+
+ const operatorPrecedence = precedence(node.operator);
+ const argPrecedence = precedence(argOperator);
+
+ const isLowerPrecedence = operatorPrecedence > argPrecedence;
+ const isSamePrecedence = operatorPrecedence === argPrecedence;
+
+ // "*","/" always have two arguments.
+ // If the second argument of "/" is an expression, we have to calculate it first.
+ // Hence, adding parenthesis.
+ // "a / b * c" vs "a / (b * c)", "a / b / c" vs "a / (b / c)"
+ // "a - b + c" vs "a - (b + c)", "a - b - c" vs "a - (b - c)"
+ const isSamePrecedenceWithExecutionPriority = index > 0 && isSamePrecedence;
+
+ const shouldUseParens =
+ isLowerPrecedence || isSamePrecedenceWithExecutionPriority;
+
+ if (shouldUseParens) {
+ return ind(
+ group([
+ ln,
+ "(",
+ group(
+ ifBreak(
+ [indent([softline, group(formattedArg)]), softline],
+ formattedArg,
+ ),
+ ),
+ ")",
+ ]),
+ );
+ } else {
+ return ind([ln, formattedArg]);
+ }
+ });
+
+ if (isUnaryOperator(node.operator)) {
+ return [displayName(node.operator), " ", args[0]];
+ }
+
+ if (operatorGoesOnNewline) {
+ return group(join([line, displayName(node.operator), " "], args));
+ } else {
+ return group(join([" ", displayName(node.operator)], args));
+ }
+}
+
+function precedence(op: string): number {
+ return parsePunctuator(op)?.precedence ?? Infinity;
+}
+
+function isUnaryOperator(op: Lib.ExpressionOperator) {
+ return getClauseDefinition(op)?.args.length === 1;
+}
+
+function formatValueExpression(
+ path: Path<Lib.ExpressionParts>,
+ options: FormatOptions,
+): Doc {
+ const { node } = path;
+
+ assert(isValueOperator(node), "Expected value");
+
+ const {
+ args: [value],
+ options: valueOptions,
+ } = node;
+
+ const baseType = valueOptions?.["base-type"];
+ if (
+ typeof value === "string" &&
+ typeof baseType === "string" &&
+ isa(baseType, "type/BigInteger")
+ ) {
+ const number = parseNumber(value);
+ if (number != null) {
+ return recurse(path, options, number);
+ }
+ }
+ return recurse(path, options, node.args[0]);
+}
+
+function displayName(name: Lib.ExpressionOperator): string {
+ assert(name !== "value", "Unexpected value clause");
+ return getClauseDefinition(name)?.displayName ?? name;
+}
diff --git a/frontend/src/metabase/querying/expressions/formatter/types.ts b/frontend/src/metabase/querying/expressions/formatter/types.ts
new file mode 100644
index 00000000000..b8621d7aa60
--- /dev/null
+++ b/frontend/src/metabase/querying/expressions/formatter/types.ts
@@ -0,0 +1,18 @@
+import type * as Lib from "metabase-lib";
+
+import type { StartDelimiter } from "../string";
+
+export type ExpressionNode = Lib.ExpressionParts | Lib.ExpressionArg | null;
+
+export type FormatOptions = {
+ query?: Lib.Query;
+ stageIndex?: number;
+ availableColumns?: Lib.ColumnMetadata[];
+ printWidth?: number;
+ stringDelimiter?: StartDelimiter;
+};
+
+export type FormatClauseOptions = {
+ query: Lib.Query;
+ stageIndex: number;
+} & FormatOptions;
diff --git a/frontend/src/metabase/querying/expressions/formatter/utils.ts b/frontend/src/metabase/querying/expressions/formatter/utils.ts
index 3f9d068dc7c..49cc9b419b2 100644
--- a/frontend/src/metabase/querying/expressions/formatter/utils.ts
+++ b/frontend/src/metabase/querying/expressions/formatter/utils.ts
@@ -1,17 +1,33 @@
-import type { AstPath } from "prettier";
-
import * as Lib from "metabase-lib";
import * as literal from "../literal";
+/**
+ * The stack of nodes from the root of the expression down to the node that is
+ * currently being printed. Only the top of the stack is typed, because the
+ * matchers below narrow it one node at a time.
+ */
+export class Path<T> {
+ readonly stack: unknown[];
+
+ constructor(root: T) {
+ this.stack = [root];
+ }
+
+ get node(): T {
+ // The type parameter tracks what the matchers have narrowed the top of the
+ // stack to, which the unknown[] element type cannot express.
+ return this.stack[this.stack.length - 1] as T;
+ }
+}
+
type Assertion<T> = T extends ((expr: any) => expr is infer U) ? U : never;
type Lifted<T> = {
- [K in keyof T]: (path: AstPath<unknown>) => path is AstPath<Assertion<T[K]>>;
+ [K in keyof T]: (path: Path<unknown>) => path is Path<Assertion<T[K]>>;
};
/**
- * Lift all matchers to work on Prettier's AstPath instead of on
- * single Expression nodes.
+ * Lift all matchers to work on a Path instead of on single Expression nodes.
*/
function lift<T>(matchers: T): Lifted<T> {
// @ts-expect-error: map is empty
@@ -26,21 +42,20 @@ function lift<T>(matchers: T): Lifted<T> {
}
/**
- * Lift a single matcher to work on Prettier's AstPath instead of on
- * a single Expression node.
+ * Lift a single matcher to work on a Path instead of on a single Expression
+ * node.
*/
function liftMatcher<T>(
matcher: (expr: unknown) => expr is T,
-): (path: AstPath<unknown>) => path is AstPath<T> {
- return (path: AstPath<unknown>): path is AstPath<T> => matcher(path.node);
+): (path: Path<unknown>) => path is Path<T> {
+ return (path: Path<unknown>): path is Path<T> => matcher(path.node);
}
/**
- * Lift all matchers to work on Prettier's AstPath instead of on
- * single Expression nodes.
+ * Lift all matchers to work on a Path instead of on single Expression nodes.
*
* For example, this will verify that path.node is a string literal and
- * asserts that path is AstPath<string>.
+ * asserts that path is Path<string>.
* @example
* pathMatchers.isStringLiteral(path)
*/