Skip to content

Commit

Permalink
Fix generating invalid syntax for transform on RHS of binary expressi…
Browse files Browse the repository at this point in the history
…o in ternary condition

Note that `a < (b | c) ? true : false` compiles but `a < b | c ? true : false` does not compile
  • Loading branch information
chetbox committed Aug 12, 2023
1 parent 6a9e61b commit 9c5819f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
3 changes: 3 additions & 0 deletions src/__test__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ describe("jexlExpressionStringFromAst", () => {
'z + 0 + " A " + (a + 1) + " B " + (b + 2) + " C " + (c == 0 ? "c1" : "c2")',
],
["a ? b1 ? b2 : b3 : c1 ? c2 : c3", null],
["a < b | c", null],
["a < (b | c) ? true : false", null], // Jexl can't parse this if the brackets are removed
["a | b < c ? true : false", null],
];

test.each(expressions)("`%s`", (input, expected) => {
Expand Down
25 changes: 19 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,15 @@ export function escapeKeyOfExpressionIdentifier(

export function jexlExpressionStringFromAst(
grammar: JexlGrammar,
ast: JexlAst | null
ast: JexlAst | null,
ancestors: JexlAst[] = []
): string {
if (!ast) {
return "";
}

const recur = (ast: JexlAst) => jexlExpressionStringFromAst(grammar, ast);
const recur = (childAst: JexlAst) =>
jexlExpressionStringFromAst(grammar, childAst, [...ancestors, ast]);

const recurWithBracketsIfRequired = (
parentElement: JexlElement | null,
Expand All @@ -46,10 +48,18 @@ export function jexlExpressionStringFromAst(
? childBinaryExpressionElement.precedence
: Infinity;

const rhsOfBinaryOpInTernaryConditionWorkaround =
isRightHandSide &&
childAst.type === "FunctionCall" &&
childAst.pool === "transforms" &&
parentElement?.type === "binaryOp" &&
ancestors[ancestors.length - 1]?.type === "ConditionalExpression";

const childExpressionString = recur(childAst);
if (
isRightHandSide
? parentPrecedence >= childPrecedence
? parentPrecedence >= childPrecedence ||
rhsOfBinaryOpInTernaryConditionWorkaround
: parentPrecedence > childPrecedence
) {
return `(${childExpressionString})`;
Expand All @@ -59,9 +69,12 @@ export function jexlExpressionStringFromAst(

switch (ast.type) {
case "Literal":
if (typeof ast.value === 'number' && ast.value.toString().includes("e")) {
const prefix = ast.value < 0 ? "-" : ""
return prefix + Math.abs(ast.value).toLocaleString("en-US", { useGrouping: false })
if (typeof ast.value === "number" && ast.value.toString().includes("e")) {
const prefix = ast.value < 0 ? "-" : "";
return (
prefix +
Math.abs(ast.value).toLocaleString("en-US", { useGrouping: false })
);
}
return JSON.stringify(ast.value);
case "Identifier":
Expand Down

0 comments on commit 9c5819f

Please sign in to comment.