@zackad/prettier-plugin-twig 0.16.3 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,12 +2,41 @@ import { doc } from "prettier";
2
2
  import {
3
3
  EXPRESSION_NEEDED,
4
4
  isWhitespaceNode,
5
+ hasLeadingComments,
5
6
  indentWithHardline
6
7
  } from "../util/index.js";
7
8
 
8
9
  const { group, indent, line, hardline } = doc.builders;
9
10
 
11
+ const printForWithTargetComments = (node, path, print) => {
12
+ const targets = [];
13
+ if (node.keyTarget) {
14
+ targets.push(path.call(print, "keyTarget"), ",", line);
15
+ }
16
+ targets.push(
17
+ path.call(print, "valueTarget"),
18
+ " in ",
19
+ path.call(print, "sequence")
20
+ );
21
+ if (node.condition) {
22
+ targets.push(line, "if ", path.call(print, "condition"));
23
+ }
24
+ return group([
25
+ node.trimLeft ? "{%-" : "{%",
26
+ " for",
27
+ indent([hardline, targets]),
28
+ hardline,
29
+ node.trimRightFor ? "-%}" : "%}"
30
+ ]);
31
+ };
32
+
10
33
  const printFor = (node, path, print) => {
34
+ if (
35
+ hasLeadingComments(node.keyTarget) ||
36
+ hasLeadingComments(node.valueTarget)
37
+ ) {
38
+ return printForWithTargetComments(node, path, print);
39
+ }
11
40
  const parts = [node.trimLeft ? "{%-" : "{%", " for "];
12
41
  if (node.keyTarget) {
13
42
  parts.push(path.call(print, "keyTarget"), ", ");
@@ -1,4 +1,5 @@
1
1
  import { doc } from "prettier";
2
+ import { hasTrailingComments } from "../util/index.js";
2
3
 
3
4
  const { group, join, line, softline, hardline, indent } = doc.builders;
4
5
 
@@ -12,6 +13,10 @@ const printOpener = (node, path, print) => {
12
13
  const mappedArguments = path.map(print, "arguments");
13
14
  const joinedArguments = join([",", line], mappedArguments);
14
15
  parts.push(indent([softline, joinedArguments]));
16
+ // The closing parenthesis must not end up in a trailing comment
17
+ if (hasTrailingComments(node.arguments[node.arguments.length - 1])) {
18
+ parts.push(softline);
19
+ }
15
20
  parts.push(")", line, node.trimRightMacro ? "-%}" : "%}");
16
21
  return group(parts);
17
22
  };
@@ -3,11 +3,13 @@ import { Node } from "../melody/melody-types/index.js";
3
3
  import {
4
4
  printChildBlock,
5
5
  isNotExpression,
6
+ hasLeadingComments,
7
+ printComments,
6
8
  STRING_NEEDS_QUOTES,
7
9
  GROUP_TOP_LEVEL_LOGICAL
8
10
  } from "../util/index.js";
9
11
 
10
- const { group, line, hardline } = doc.builders;
12
+ const { group, indent, line, hardline } = doc.builders;
11
13
 
12
14
  const shouldAvoidBreakBeforeClosing = valueNode =>
13
15
  Node.isObjectExpression(valueNode) ||
@@ -21,6 +23,19 @@ const buildSetStatement = (node, path, print, assignmentIndex) => {
21
23
  varDeclaration.value
22
24
  );
23
25
 
26
+ if (hasLeadingComments(varDeclaration)) {
27
+ return [
28
+ node.trimLeft ? "{%-" : "{%",
29
+ " set",
30
+ indent([
31
+ hardline,
32
+ path.call(print, "assignments", assignmentIndex)
33
+ ]),
34
+ hardline,
35
+ node.trimRight ? "-%}" : "%}"
36
+ ];
37
+ }
38
+
24
39
  return group([
25
40
  node.trimLeft ? "{%-" : "{%",
26
41
  " set ",
@@ -54,12 +69,22 @@ const printRegularSet = (node, path, print) => {
54
69
  };
55
70
 
56
71
  const printEmbracingSet = (node, path, print) => {
57
- const parts = [
58
- node.trimLeft ? "{%-" : "{%",
59
- " set ",
60
- path.call(print, "assignments", "0", "name"),
61
- node.trimRightSet ? " -%}" : " %}"
62
- ];
72
+ const assignment = node.assignments[0];
73
+ const printedName = path.call(print, "assignments", "0", "name");
74
+ const parts = hasLeadingComments(assignment)
75
+ ? [
76
+ node.trimLeft ? "{%-" : "{%",
77
+ " set",
78
+ indent([hardline, printComments(assignment, printedName)]),
79
+ hardline,
80
+ node.trimRightSet ? "-%}" : "%}"
81
+ ]
82
+ : [
83
+ node.trimLeft ? "{%-" : "{%",
84
+ " set ",
85
+ printedName,
86
+ node.trimRightSet ? " -%}" : " %}"
87
+ ];
63
88
  node[STRING_NEEDS_QUOTES] = false;
64
89
  const printedContents = printChildBlock(
65
90
  node,
@@ -1,23 +1,19 @@
1
1
  import {
2
- createTextGroups,
3
- stripTwigCommentChars,
4
- normalizeTwigComment,
2
+ parseTwigComment,
3
+ unifyWhitespace,
5
4
  countNewlines
6
5
  } from "../util/index.js";
7
6
 
8
7
  const printTwigComment = node => {
9
8
  const originalText = node.value.value || "";
10
- const commentText = stripTwigCommentChars(originalText);
11
- const trimLeft = originalText.length >= 3 ? originalText[2] === "-" : false;
12
- const trimRight =
13
- originalText.length >= 3 ? originalText.slice(-3, -2) === "-" : false;
9
+ const { text, open, close } = parseTwigComment(originalText);
14
10
 
15
- const numNewlines = countNewlines(commentText);
11
+ const numNewlines = countNewlines(text);
16
12
  if (numNewlines === 0) {
17
- return normalizeTwigComment(commentText, trimLeft, trimRight);
13
+ return [open, " ", unifyWhitespace(text), " ", close];
18
14
  }
19
15
 
20
- return [trimLeft ? "{#-" : "{#", commentText, trimRight ? "-#}" : "#}"];
16
+ return [open, text, close];
21
17
  };
22
18
 
23
19
  export { printTwigComment };
@@ -0,0 +1,43 @@
1
+ import { doc } from "prettier";
2
+
3
+ const { group, join, line, indentIfBreak, hardline, softline } = doc.builders;
4
+
5
+ /**
6
+ * @typedef {import('../melody/melody-extension-core/types.js').TypesDeclarationStatement} TypesDeclarationStatement
7
+ */
8
+
9
+ /**
10
+ * The `{% types %}` tag node printer.
11
+ *
12
+ * Introduced in Twig version 3.13.
13
+ *
14
+ * @param {TypesDeclarationStatement} node
15
+ */
16
+ const printTypesDeclarationStatement = (node, path, print) => {
17
+ const typesGroupId = Symbol("types-declarations");
18
+
19
+ const mappedTypes = path.map(print, "declarations");
20
+ const joinedTypes = join([",", line], mappedTypes);
21
+ const hasManyTypes = node.declarations.length > 1 ? hardline : softline;
22
+
23
+ const parts = [node.trimLeft ? "{%-" : "{%", " types "];
24
+
25
+ if (node.enclosed) {
26
+ parts.push("{");
27
+ }
28
+
29
+ parts.push(
30
+ indentIfBreak([hasManyTypes, joinedTypes], { groupId: typesGroupId }),
31
+ line
32
+ );
33
+
34
+ if (node.enclosed) {
35
+ parts.push("}", " ");
36
+ }
37
+
38
+ parts.push(node.trimRight ? "-%}" : "%}");
39
+
40
+ return group(parts, { id: typesGroupId });
41
+ };
42
+
43
+ export { printTypesDeclarationStatement };
@@ -0,0 +1,27 @@
1
+ import { doc } from "prettier";
2
+ import { STRING_NEEDS_QUOTES } from "../util/index.js";
3
+
4
+ const { group } = doc.builders;
5
+
6
+ /**
7
+ * @typedef {import('../melody/melody-extension-core/types.js').TypesVariableDeclaration} TypesVariableDeclaration
8
+ */
9
+
10
+ /**
11
+ * The `{% types foo?: 'string' %}` variable type node printer.
12
+ *
13
+ * Introduced in Twig version 3.13.
14
+ *
15
+ * @param {TypesVariableDeclaration} node
16
+ */
17
+ const printTypesVariableDeclaration = (node, path, print) => {
18
+ const printedName = path.call(print, "name");
19
+ const printedAssignment = node.optional ? "?: " : ": ";
20
+
21
+ node[STRING_NEEDS_QUOTES] = true;
22
+ const printedValue = path.call(print, "value");
23
+
24
+ return group([printedName, [printedAssignment, printedValue]]);
25
+ };
26
+
27
+ export { printTypesVariableDeclaration };
package/src/printer.js CHANGED
@@ -5,6 +5,7 @@ import { printElement } from "./print/Element.js";
5
5
  import { printAttribute } from "./print/Attribute.js";
6
6
  import { printIdentifier } from "./print/Identifier.js";
7
7
  import { printExpressionStatement } from "./print/ExpressionStatement.js";
8
+ import { printErroredStatement } from "./print/ErroredStatement.js";
8
9
  import { printMemberExpression } from "./print/MemberExpression.js";
9
10
  import { printFilterExpression } from "./print/FilterExpression.js";
10
11
  import { printArrowFunction } from "./print/ArrowFunction.js";
@@ -46,12 +47,17 @@ import { printFilterBlockStatement } from "./print/FilterBlockStatement.js";
46
47
  import { printVariableDeclarationStatement } from "./print/VariableDeclarationStatement.js";
47
48
  import { printNamedArgumentExpression } from "./print/NamedArgumentExpression.js";
48
49
  import { printSwitchTag } from "./print/SwitchTag.js";
50
+ import { printTypesDeclarationStatement } from "./print/TypesDeclarationStatement.js";
51
+ import { printTypesVariableDeclaration } from "./print/TypesVariableDeclaration.js";
49
52
  import {
53
+ printComments,
50
54
  isWhitespaceNode,
51
55
  isHtmlCommentEqualTo,
52
56
  isTwigCommentEqualTo
53
57
  } from "./util/index.js";
58
+ import { PRETTIER_IGNORED_CODE } from "./util/publicSymbols.js";
54
59
  import { ORIGINAL_SOURCE } from "./parser.js";
60
+ import { INLINE_COMMENT_ERROR } from "./melody/melody-parser/index.js";
55
61
 
56
62
  const printFunctions = {};
57
63
 
@@ -100,15 +106,21 @@ const print = (path, options, print) => {
100
106
  }
101
107
 
102
108
  checkForIgnoreEnd(node);
103
- const useOriginalSource =
109
+ node[PRETTIER_IGNORED_CODE] =
104
110
  (shouldApplyIgnoreNext(node) && ignoreNext) || ignoreRegion;
105
111
  const hasPrintFunction = printFunctions[nodeType];
106
112
 
107
113
  // Happy path: We have a formatting function, and the user wants the
108
114
  // node formatted
109
- if (!useOriginalSource && hasPrintFunction) {
115
+ if (!node[PRETTIER_IGNORED_CODE] && hasPrintFunction) {
116
+ if (node[INLINE_COMMENT_ERROR]) {
117
+ throw node[INLINE_COMMENT_ERROR];
118
+ }
110
119
  checkForIgnoreStart(node);
111
- return printFunctions[nodeType](node, path, print, options);
120
+ return printComments(
121
+ node,
122
+ printFunctions[nodeType](node, path, print, options)
123
+ );
112
124
  } else if (!hasPrintFunction) {
113
125
  console.warn(`No print function available for node type "${nodeType}"`);
114
126
  }
@@ -191,6 +203,7 @@ printFunctions["Element"] = printElement;
191
203
  printFunctions["Attribute"] = printAttribute;
192
204
  printFunctions["PrintTextStatement"] = printTextStatement;
193
205
  printFunctions["PrintExpressionStatement"] = printExpressionStatement;
206
+ printFunctions["PrintErroredStatement"] = printErroredStatement;
194
207
  printFunctions["MemberExpression"] = printMemberExpression;
195
208
  printFunctions["FilterExpression"] = printFilterExpression;
196
209
  printFunctions["ArrowFunction"] = printArrowFunction;
@@ -223,6 +236,8 @@ printFunctions["MountStatement"] = printMountStatement;
223
236
  printFunctions["ForStatement"] = printForStatement;
224
237
  printFunctions["BinaryConcatExpression"] = printBinaryExpression;
225
238
  printFunctions["SetStatement"] = printSetStatement;
239
+ printFunctions["TypesDeclarationStatement"] = printTypesDeclarationStatement;
240
+ printFunctions["TypesVariableDeclaration"] = printTypesVariableDeclaration;
226
241
  printFunctions["PropsStatement"] = printPropsStatement;
227
242
  printFunctions["PropItem"] = printPropItem;
228
243
  printFunctions["VariableDeclarationStatement"] =
@@ -1,28 +1,54 @@
1
1
  import { doc } from "prettier";
2
2
  import { Node } from "../melody/melody-types/index.js";
3
3
 
4
- const { line, indent, group } = doc.builders;
4
+ const { line, indent, group, hardline, join, lineSuffix, breakParent } =
5
+ doc.builders;
5
6
 
6
7
  const noSpaceBeforeToken = {
7
8
  ",": true
8
9
  };
9
10
 
11
+ const noSpaceAfterToken = {};
12
+
10
13
  const printSingleTwigTag = (node, path, print) => {
11
14
  const opener = node.trimLeft ? "{%-" : "{%";
12
15
  const parts = [opener, " ", node.tagName];
13
16
  const printedParts = path.map(print, "parts");
14
- if (printedParts.length > 0) {
15
- parts.push(" ", printedParts[0]);
17
+
18
+ const groupedNodes = [];
19
+ const groupedDocs = [];
20
+ for (let i = 0; i < node.parts.length; i++) {
21
+ const equalsToken = node.parts[i + 1];
22
+ const isAssignment =
23
+ Node.isGenericToken(equalsToken) &&
24
+ equalsToken.tokenText === "=" &&
25
+ node.parts[i + 2] !== undefined;
26
+ if (isAssignment) {
27
+ groupedNodes.push(node.parts[i]);
28
+ groupedDocs.push([printedParts[i], " = ", printedParts[i + 2]]);
29
+ i += 2;
30
+ } else {
31
+ groupedNodes.push(node.parts[i]);
32
+ groupedDocs.push(printedParts[i]);
33
+ }
34
+ }
35
+
36
+ if (groupedDocs.length > 0) {
37
+ parts.push(" ", groupedDocs[0]);
16
38
  }
17
39
  const indentedParts = [];
18
- for (let i = 1; i < node.parts.length; i++) {
19
- const part = node.parts[i];
40
+ for (let i = 1; i < groupedDocs.length; i++) {
41
+ const part = groupedNodes[i];
42
+ const prevPart = groupedNodes[i - 1];
20
43
  const isToken = Node.isGenericToken(part);
21
- const separator =
22
- isToken && noSpaceBeforeToken[part.tokenText] ? "" : line;
23
- indentedParts.push(separator, printedParts[i]);
44
+ const isPrevToken = Node.isGenericToken(prevPart);
45
+ const noSpaceBefore = isToken && noSpaceBeforeToken[part.tokenText];
46
+ const noSpaceAfter =
47
+ isPrevToken && noSpaceAfterToken[prevPart.tokenText];
48
+ const separator = noSpaceBefore || noSpaceAfter ? "" : line;
49
+ indentedParts.push(separator, groupedDocs[i]);
24
50
  }
25
- if (node.parts.length > 1) {
51
+ if (groupedDocs.length > 1) {
26
52
  parts.push(indent(indentedParts));
27
53
  }
28
54
  const closing = node.trimRight ? "-%}" : "%}";
@@ -30,4 +56,42 @@ const printSingleTwigTag = (node, path, print) => {
30
56
  return group(parts);
31
57
  };
32
58
 
33
- export { printSingleTwigTag };
59
+ const hasLeadingComments = node =>
60
+ !!node &&
61
+ Array.isArray(node.leadingComments) &&
62
+ node.leadingComments.length > 0;
63
+
64
+ const hasTrailingComments = node =>
65
+ !!node &&
66
+ Array.isArray(node.trailingComments) &&
67
+ node.trailingComments.length > 0;
68
+
69
+ const hasComments = node =>
70
+ hasLeadingComments(node) || hasTrailingComments(node);
71
+
72
+ // Own group, so the line breaks forced by the comments do not break the node itself
73
+ const printComments = (node, printed) => {
74
+ if (!hasComments(node)) {
75
+ return printed;
76
+ }
77
+ const parts = [];
78
+ if (hasLeadingComments(node)) {
79
+ parts.push(join(hardline, node.leadingComments), hardline);
80
+ }
81
+ parts.push(group(printed));
82
+ if (hasTrailingComments(node)) {
83
+ parts.push(
84
+ lineSuffix([" ", join(" ", node.trailingComments)]),
85
+ breakParent
86
+ );
87
+ }
88
+ return parts;
89
+ };
90
+
91
+ export {
92
+ printSingleTwigTag,
93
+ printComments,
94
+ hasLeadingComments,
95
+ hasTrailingComments,
96
+ hasComments
97
+ };
@@ -444,6 +444,42 @@ const stripTwigCommentChars = s => {
444
444
  return result;
445
445
  };
446
446
 
447
+ /**
448
+ * Splits a Twig comment into its text and the delimiters around it.
449
+ * Documentation comments (Twig 3.29) open with "{##" and may close
450
+ * symmetrically with "##}".
451
+ *
452
+ * @param {string} s
453
+ */
454
+ const parseTwigComment = s => {
455
+ let text = s.startsWith("{#") ? s.slice(2) : s;
456
+ // "{##}" is an empty regular comment, not a documentation comment
457
+ const isDocumentation = text.startsWith("#") && text !== "#}";
458
+ if (isDocumentation) {
459
+ text = text.slice(1);
460
+ }
461
+ const trimLeft = text.startsWith("-");
462
+ if (trimLeft) {
463
+ text = text.slice(1);
464
+ }
465
+ if (text.endsWith("#}")) {
466
+ text = text.slice(0, -2);
467
+ }
468
+ const hasSymmetricClose = isDocumentation && text.endsWith("#");
469
+ if (hasSymmetricClose) {
470
+ text = text.slice(0, -1);
471
+ }
472
+ const trimRight = text.endsWith("-");
473
+ if (trimRight) {
474
+ text = text.slice(0, -1);
475
+ }
476
+ return {
477
+ text,
478
+ open: (isDocumentation ? "{##" : "{#") + (trimLeft ? "-" : ""),
479
+ close: (trimRight ? "-" : "") + (hasSymmetricClose ? "##}" : "#}")
480
+ };
481
+ };
482
+
447
483
  const normalizeHtmlComment = s => {
448
484
  const commentText = stripHtmlCommentChars(s);
449
485
  return "<!-- " + unifyWhitespace(commentText) + " -->";
@@ -599,6 +635,8 @@ export {
599
635
  hasAtLeastTwoNewlines,
600
636
  stripHtmlCommentChars,
601
637
  stripTwigCommentChars,
638
+ parseTwigComment,
639
+ unifyWhitespace,
602
640
  normalizeHtmlComment,
603
641
  normalizeTwigComment,
604
642
  isHtmlCommentEqualTo,
@@ -55,6 +55,12 @@ const PRESERVE_LEADING_WHITESPACE = Symbol("PRESERVE_LEADING_WHITESPACE");
55
55
  */
56
56
  const PRESERVE_TRAILING_WHITESPACE = Symbol("PRESERVE_TRAILING_WHITESPACE");
57
57
 
58
+ /**
59
+ * Signals to statements that they should be ignored
60
+ * and printed as is.
61
+ */
62
+ const PRETTIER_IGNORED_CODE = Symbol("PRETTIER_IGNORED_CODE");
63
+
58
64
  /**
59
65
  * Signals to text statements that only newlines should be
60
66
  * preserved when hitting a whitespace-only node
@@ -77,6 +83,7 @@ const IS_ROOT_LOGICAL_EXPRESSION = Symbol("IS_ROOT_LOGICAL_EXPRESSION");
77
83
  export {
78
84
  STRING_NEEDS_QUOTES,
79
85
  OVERRIDE_QUOTE_CHAR,
86
+ PRETTIER_IGNORED_CODE,
80
87
  INSIDE_OF_STRING,
81
88
  EXPRESSION_NEEDED,
82
89
  FILTER_BLOCK,