Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: Add support for spread operator #54

Merged
merged 1 commit into from
Nov 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,18 @@ __Example__
+ printWidth: 120
```

### Features
- Add support for spread operator

__Example__
```twig
<twig:Component {{ ...vars }} />

{% set numbers = [1, 2, ...moreNumbers] %}
{% set ratings = {'q1': 10, 'q2': 5, ...moreRatings} %}

{{ 'Hello %s %s!'|format(...['Fabien', 'Potencier']) }}
```
---
## 0.11.1 (2024-11-13)

Expand Down
7 changes: 7 additions & 0 deletions src/melody/melody-extension-core/operators.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,13 @@ export const binaryOperators = [];
export const tests = [];

//region Unary Expressions
export const SpreadExpression = createUnaryOperator(
"...",
"SpreadExpression",
// I can't find precedence reference for spread operator
// Ref: https://twig.symfony.com/doc/3.x/templates.html#operators
20
);
export const UnaryNotExpression = createUnaryOperator(
"not",
"UnaryNotExpression",
Expand Down
19 changes: 12 additions & 7 deletions src/melody/melody-parser/Parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -764,6 +764,8 @@ export default class Parser {
while (!tokens.test(Types.RBRACKET) && !tokens.test(Types.EOF)) {
let computed = false;
let key;

// find the key part of object property
if (tokens.test(Types.STRING_START)) {
key = this.matchStringExpression();
if (!n.is(key, "StringLiteral")) {
Expand All @@ -780,14 +782,11 @@ export default class Parser {
key = this.matchExpression();
computed = true;
} else {
this.error({
title: "Invalid map key",
pos: tokens.la(0).pos,
advice:
"Key must be a string, symbol or a number but was " +
tokens.next()
});
// if none above check is matches, we can assume that key part is being omitted
// noop
}

// find the value part of object property
if (tokens.test(Types.COLON)) {
tokens.expect(Types.COLON);
const value = this.matchExpression();
Expand All @@ -796,12 +795,18 @@ export default class Parser {
copyEnd(prop, value);
obj.properties.push(prop);
} else {
// when the part is missing, we can assume that it is being omitted
if (key === undefined) {
computed = true;
key = this.matchExpression();
}
const value = key;
const prop = new n.ObjectProperty(value, computed);
copyStart(prop, key);
copyEnd(prop, value);
obj.properties.push(prop);
}

if (!tokens.test(Types.RBRACKET)) {
tokens.expect(Types.COMMA);
// support trailing comma
Expand Down
20 changes: 18 additions & 2 deletions src/print/UnarySubclass.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import {
findParentNode,
isMultipartExpression,
IS_ROOT_LOGICAL_EXPRESSION,
GROUP_TOP_LEVEL_LOGICAL
GROUP_TOP_LEVEL_LOGICAL,
wrapExpressionIfNeeded,
EXPRESSION_NEEDED
} from "../util/index.js";

const { softline, indent, group } = doc.builders;
Expand Down Expand Up @@ -41,17 +43,31 @@ const printLogicalExpression = (node, path, print) => {
};

const p = (node, path, print) => {
// We need this part to prevent argument being wrapped into expression separated from operator
// Example:
// with node[EXPRESSION_NEEDED] = true; // default value
// input: {{ ...vars }}
// output: ...{{ vars }}
// with node[EXPRESSION_NEEDED] = false;
// input: {{ ...vars }}
// output: {{ ...vars }}
node[EXPRESSION_NEEDED] = false;
zackad marked this conversation as resolved.
Show resolved Hide resolved

const parts = [];
// Example: a is not same as ... => Here, the "not" is printed "inline"
// Therefore, we do not output it here
const hasTestExpressionArgument = Node.isTestExpression(node.argument);
if (isLogicalOperator(node.operator) && !hasTestExpressionArgument) {
return printLogicalExpression(node, path, print);
}
if (!hasTestExpressionArgument) {
if (node.operator === "...") {
parts.push(node.operator);
} else if (!hasTestExpressionArgument) {
parts.push(node.operator, " ");
}
parts.push(path.call(print, "argument"));
wrapExpressionIfNeeded(path, parts, node);

return parts;
};

Expand Down
17 changes: 17 additions & 0 deletions tests/Expressions/__snapshots__/spread_operator.snap.twig
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
Some variation of spread operator

{{ ...some_var }}
<twig:Component {{ ...vars }} />

{% set numbers = [1, 2, ...moreNumbers] %}
{% set ratings = {
q1: 10,
...options,
q2: 5,
...moreRatings,
q3,
option: '',
'other-option'
} %}

{{ 'Hello %s %s!'|format(...['Fabien', 'Potencier']) }}
11 changes: 11 additions & 0 deletions tests/Expressions/jsfmt.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,17 @@ describe("Expressions", () => {
});
await expect(actual).toMatchFileSnapshot(snapshotFile);
});

it("should handle spread operators", async () => {
const { actual, snapshotFile } = await run_spec(import.meta.url, {
source: "spread_operator.twig",
formatOptions: {
twigAlwaysBreakObjects: false
}
});
await expect(actual).toMatchFileSnapshot(snapshotFile);
});

it("should handle string concatenation", async () => {
const { actual, snapshotFile } = await run_spec(import.meta.url, {
source: "stringConcat.twig"
Expand Down
9 changes: 9 additions & 0 deletions tests/Expressions/spread_operator.twig
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
Some variation of spread operator

{{ ...some_var }}
<twig:Component {{ ...vars }} />

{% set numbers = [1, 2, ...moreNumbers] %}
{% set ratings = {'q1': 10, ...options, 'q2': 5, ...moreRatings, q3, 'option':'','other-option'} %}

{{ 'Hello %s %s!'|format(...['Fabien', 'Potencier']) }}