@zackad/prettier-plugin-twig 0.7.0-alpha.1

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.
Files changed (55) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +141 -0
  3. package/package.json +39 -0
  4. package/src/index.js +130 -0
  5. package/src/parser.js +82 -0
  6. package/src/print/AliasExpression.js +5 -0
  7. package/src/print/ArrayExpression.js +14 -0
  8. package/src/print/Attribute.js +50 -0
  9. package/src/print/AutoescapeBlock.js +31 -0
  10. package/src/print/BinaryExpression.js +155 -0
  11. package/src/print/BlockStatement.js +48 -0
  12. package/src/print/CallExpression.js +38 -0
  13. package/src/print/ConditionalExpression.js +27 -0
  14. package/src/print/Declaration.js +15 -0
  15. package/src/print/DoStatement.js +10 -0
  16. package/src/print/Element.js +63 -0
  17. package/src/print/EmbedStatement.js +38 -0
  18. package/src/print/ExpressionStatement.js +25 -0
  19. package/src/print/ExtendsStatement.js +13 -0
  20. package/src/print/FilterBlockStatement.js +27 -0
  21. package/src/print/FilterExpression.js +131 -0
  22. package/src/print/FlushStatement.js +7 -0
  23. package/src/print/ForStatement.js +58 -0
  24. package/src/print/FromStatement.js +32 -0
  25. package/src/print/GenericToken.js +5 -0
  26. package/src/print/GenericTwigTag.js +30 -0
  27. package/src/print/HtmlComment.js +22 -0
  28. package/src/print/Identifier.js +15 -0
  29. package/src/print/IfStatement.js +81 -0
  30. package/src/print/ImportDeclaration.js +18 -0
  31. package/src/print/IncludeStatement.js +26 -0
  32. package/src/print/MacroDeclarationStatement.js +31 -0
  33. package/src/print/MemberExpression.js +23 -0
  34. package/src/print/MountStatement.js +84 -0
  35. package/src/print/NamedArgumentExpression.js +10 -0
  36. package/src/print/ObjectExpression.js +21 -0
  37. package/src/print/ObjectProperty.js +25 -0
  38. package/src/print/SequenceExpression.js +21 -0
  39. package/src/print/SetStatement.js +91 -0
  40. package/src/print/SliceExpression.js +8 -0
  41. package/src/print/SpacelessBlock.js +23 -0
  42. package/src/print/StringLiteral.js +63 -0
  43. package/src/print/SwitchTag.js +35 -0
  44. package/src/print/TestExpression.js +47 -0
  45. package/src/print/TextStatement.js +45 -0
  46. package/src/print/TwigComment.js +23 -0
  47. package/src/print/UnaryExpression.js +18 -0
  48. package/src/print/UnarySubclass.js +58 -0
  49. package/src/print/UseStatement.js +25 -0
  50. package/src/print/VariableDeclarationStatement.js +21 -0
  51. package/src/printer.js +252 -0
  52. package/src/util/index.js +3 -0
  53. package/src/util/printFunctions.js +33 -0
  54. package/src/util/publicFunctions.js +593 -0
  55. package/src/util/publicSymbols.js +88 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,141 @@
1
+ # Prettier Plugin for Twig
2
+
3
+ > [!WARNING]
4
+ > Not ready. DON'T USE!
5
+
6
+ Forked from [trivago/prettier-plugin-twig-melody](https://github.com/trivago/prettier-plugin-twig-melody) with focus on twig template only.
7
+
8
+ ![Prettier Banner](https://raw.githubusercontent.com/prettier/prettier-logo/master/images/prettier-banner-light.png)
9
+
10
+ ![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/zackad/prettier-plugin-twig-melody/ci.yaml?branch=master&style=for-the-badge&logo=github)
11
+ ![GitHub License](https://img.shields.io/github/license/zackad/prettier-plugin-twig-melody?style=for-the-badge)
12
+ ![GitHub Release](https://img.shields.io/github/v/release/zackad/prettier-plugin-twig-melody?display_name=release&style=for-the-badge&logo=github)
13
+ ![GitHub Tag](https://img.shields.io/github/v/tag/zackad/prettier-plugin-twig-melody?style=for-the-badge)
14
+
15
+ ---
16
+
17
+ This Plugin enables Prettier to format `.twig` files, as well as `.html.twig`.
18
+
19
+ ## Install
20
+
21
+ ```bash
22
+ yarn add --dev @zackad/prettier-plugin-twig
23
+ ```
24
+
25
+ ## Use
26
+
27
+ ```bash
28
+ prettier --write "**/*.twig"
29
+ ```
30
+
31
+ In your editor, if the plugin is not automatically picked up and invoked (e.g., if you are using format on save, but no formatting is happening when you save), try adding the plugin explicitly in your Prettier configuration (e.g., `.prettierrc.json`) using the `plugins` key:
32
+
33
+ ```json
34
+ {
35
+ "printWidth": 80,
36
+ "tabWidth": 4,
37
+ "plugins": ["@zackad/prettier-plugin-twig"]
38
+ }
39
+ ```
40
+
41
+ ## Options
42
+
43
+ This Prettier plugin comes with some options that you can add to your Prettier configuration (e.g., `prettierrc.json`).
44
+
45
+ ### twigSingleQuote (default: `true`)
46
+
47
+ Values can be `true` or `false`. If `true`, single quotes will be used for string literals in Twig files.
48
+
49
+ ### twigPrintWidth (default: `80`)
50
+
51
+ Because Twig files might have a lot of nesting, it can be useful to define a separate print width for Twig files. This can be done with this option. If it is not set, the standard `printWidth` option is used.
52
+
53
+ ### twigAlwaysBreakObjects (default: `false`)
54
+
55
+ If set to `true`, objects will always be wrapped/broken, even if they would fit on one line:
56
+
57
+ ```html
58
+ <section
59
+ class="{{ {
60
+ base: css.prices
61
+ } | classes }}"
62
+ ></section>
63
+ ```
64
+
65
+ If set to `false` (default value), this would be printed as:
66
+
67
+ ```html
68
+ <section class="{{ { base: css.prices } | classes }}"></section>
69
+ ```
70
+
71
+ ### twigFollowOfficialCodingStandards (default: `true`)
72
+
73
+ Follow the standards described in [https://twig.symfony.com/doc/2.x/coding_standards.html](https://twig.symfony.com/doc/2.x/coding_standards.html) exactly. If set to `false`, some slight deviations might occur, such as spaces around the filter `|` operator (`s | upper` instead of `s|upper`).
74
+
75
+ ### twigOutputEndblockName (default: `false`)
76
+
77
+ Choose whether to output the block name in `{% endblock %}` tags (e.g., `{% endblock content %}`) or not. The default is not to output it.
78
+
79
+ ### twigMultiTags (default: `[]`)
80
+
81
+ An array of coherent sequences of non-standard Twig tags that should be treated as belonging together. Example (inspired by [Craft CMS](https://docs.craftcms.com/v2/templating/nav.html)):
82
+
83
+ ```json
84
+ twigMultiTags: [
85
+ "nav,endnav",
86
+ "switch,case,default,endswitch",
87
+ "ifchildren,endifchildren",
88
+ "cache,endcache"
89
+ ]
90
+ ```
91
+
92
+ Looking at the case of `nav,endnav`, this means that the Twig tags `{% nav %}` and `{% endnav %}` will be treated as a pair, and everything in between will be indented:
93
+
94
+ ```twig
95
+ {% nav entry in entries %}
96
+ <li>
97
+ <a href="{{ entry.url }}">{{ entry.title }}</a>
98
+ </li>
99
+ {% endnav %}
100
+ ```
101
+
102
+ If we did not list the `"nav,endnav"` entry in `twigMultiTags`, this code example would be printed without indentation, because `{% nav %}` and `{% endnav %}` would be treated as unrelated, individual Twig tags:
103
+
104
+ ```twig
105
+ {% nav entry in entries %}
106
+ <li>
107
+ <a href="{{ entry.url }}">{{ entry.title }}</a>
108
+ </li>
109
+ {% endnav %}
110
+ ```
111
+
112
+ Note that the order matters: It has to be `"nav,endnav"`, and it must not be `"endnav,nav"`. In general, the first and the last tag name matter. In the case of `"switch,case,default,endswitch"`, the order of `case` and `default` does not matter. However, `switch` has to come first, and `endswitch` has to come last.
113
+
114
+ ## Features
115
+
116
+ ### `prettier-ignore` and `prettier-ignore-start`
117
+
118
+ When you are not happy with how Prettier formats a certain element or section in the code, you can tell it to leave it in peace:
119
+
120
+ ```
121
+ {# prettier-ignore #}
122
+ <div class="weird-formatting" >This will not be re-formatted</div>
123
+
124
+ <div class="weird-formatting" >But this will be</div>
125
+ ```
126
+
127
+ You can also tell Prettier to leave entire regions as they are:
128
+
129
+ ```
130
+ {# prettier-ignore-start #}
131
+ ...
132
+ {# prettier-ignore-end #}
133
+ ```
134
+
135
+ ## Testing
136
+
137
+ - You can call `yarn test`to test against all regular tests
138
+
139
+ ## Credit
140
+
141
+ - Author: Tom Bartel <thomas.bartel@trivago.com>
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@zackad/prettier-plugin-twig",
3
+ "version": "0.7.0-alpha.1",
4
+ "description": "Prettier Plugin for Twig",
5
+ "repository": "https://github.com/zackad/prettier-plugin-twig",
6
+ "license": "Apache-2.0",
7
+ "author": "Tom Bartel <thomas.bartel@trivago.com>",
8
+ "type": "module",
9
+ "exports": "./src/index.js",
10
+ "files": [
11
+ "src"
12
+ ],
13
+ "scripts": {
14
+ "lint": "DEBUG=eslint:cli-engine eslint .",
15
+ "prettier": "prettier --plugin=./src/index.js --parser=melody",
16
+ "test": "vitest --run"
17
+ },
18
+ "dependencies": {
19
+ "babel-types": "^6.26.0",
20
+ "melody-extension-core": "^1.7.5",
21
+ "melody-parser": "^1.7.5",
22
+ "melody-traverse": "^1.7.5",
23
+ "melody-types": "^1.7.5",
24
+ "prettier": "^3.0.0",
25
+ "resolve": "^1.12.0"
26
+ },
27
+ "devDependencies": {
28
+ "eslint": "^8.56.0",
29
+ "eslint-config-prettier": "^9.1.0",
30
+ "eslint-plugin-import": "^2.29.1",
31
+ "eslint-plugin-jest": "^27.9.0",
32
+ "eslint-plugin-prettier": "^5.0.0",
33
+ "eslint-plugin-prettier-doc": "^1.1.0",
34
+ "vitest": "^1.5.0"
35
+ },
36
+ "engines": {
37
+ "node": ">=18"
38
+ }
39
+ }
package/src/index.js ADDED
@@ -0,0 +1,130 @@
1
+ import { print } from "./printer.js";
2
+ import { parse } from "./parser.js";
3
+ import * as symbols from "./util/publicSymbols.js";
4
+ import * as publicFunctions from "./util/publicFunctions.js";
5
+
6
+ const languages = [
7
+ {
8
+ name: "melody",
9
+ parsers: ["melody"],
10
+ group: "Melody",
11
+ tmScope: "melody.twig",
12
+ aceMode: "html",
13
+ codemirrorMode: "clike",
14
+ codemirrorMimeType: "text/melody-twig",
15
+ extensions: [".melody.twig", ".html.twig", ".twig"],
16
+ linguistLanguageId: 0,
17
+ vscodeLanguageIds: ["twig"]
18
+ }
19
+ ];
20
+
21
+ function hasPragma(/* text */) {
22
+ return false;
23
+ }
24
+
25
+ function locStart(/* node */) {
26
+ return -1;
27
+ }
28
+
29
+ function locEnd(/* node */) {
30
+ return -1;
31
+ }
32
+
33
+ const parsers = {
34
+ melody: {
35
+ parse,
36
+ astFormat: "melody",
37
+ hasPragma,
38
+ locStart,
39
+ locEnd
40
+ }
41
+ };
42
+
43
+ function canAttachComment(node) {
44
+ return node.ast_type && node.ast_type !== "comment";
45
+ }
46
+
47
+ function printComment(commentPath) {
48
+ const comment = commentPath.getValue();
49
+
50
+ switch (comment.ast_type) {
51
+ case "comment":
52
+ return comment.value;
53
+ default:
54
+ throw new Error("Not a comment: " + JSON.stringify(comment));
55
+ }
56
+ }
57
+
58
+ function clean(ast, newObj) {
59
+ delete newObj.lineno;
60
+ delete newObj.col_offset;
61
+ }
62
+
63
+ const printers = {
64
+ melody: {
65
+ print,
66
+ // hasPrettierIgnore,
67
+ printComment,
68
+ canAttachComment,
69
+ massageAstNode: clean,
70
+ willPrintOwnComments: () => true
71
+ }
72
+ };
73
+
74
+ const options = {
75
+ twigMultiTags: {
76
+ type: "path",
77
+ category: "Global",
78
+ array: true,
79
+ default: [{ value: [] }],
80
+ description: "Make custom Twig tags known to the parser."
81
+ },
82
+ twigSingleQuote: {
83
+ type: "boolean",
84
+ category: "Global",
85
+ default: true,
86
+ description: "Use single quotes in Twig files?"
87
+ },
88
+ twigAlwaysBreakObjects: {
89
+ type: "boolean",
90
+ category: "Global",
91
+ default: true,
92
+ description: "Should objects always break in Twig files?"
93
+ },
94
+ twigPrintWidth: {
95
+ type: "int",
96
+ category: "Global",
97
+ default: 80,
98
+ description: "Print width for Twig files"
99
+ },
100
+ twigFollowOfficialCodingStandards: {
101
+ type: "boolean",
102
+ category: "Global",
103
+ default: true,
104
+ description:
105
+ "See https://twig.symfony.com/doc/2.x/coding_standards.html"
106
+ },
107
+ twigOutputEndblockName: {
108
+ type: "boolean",
109
+ category: "Global",
110
+ default: false,
111
+ description: "Output the Twig block name in the 'endblock' tag"
112
+ }
113
+ };
114
+
115
+ const pluginExports = {
116
+ languages,
117
+ printers,
118
+ parsers,
119
+ options
120
+ };
121
+ const combinedExports = Object.assign(
122
+ {},
123
+ pluginExports,
124
+ symbols,
125
+ publicFunctions
126
+ );
127
+
128
+ // This exports defines the Prettier plugin
129
+ // See https://github.com/prettier/prettier/blob/master/docs/plugins.md
130
+ export default combinedExports;
package/src/parser.js ADDED
@@ -0,0 +1,82 @@
1
+ import { CharStream, Lexer, TokenStream, Parser } from "melody-parser";
2
+ import { extension as coreExtension } from "melody-extension-core";
3
+
4
+ const ORIGINAL_SOURCE = Symbol("ORIGINAL_SOURCE");
5
+
6
+ const createConfiguredLexer = (code, ...extensions) => {
7
+ const lexer = new Lexer(new CharStream(code));
8
+ for (const extension of extensions) {
9
+ if (extension.unaryOperators) {
10
+ lexer.addOperators(...extension.unaryOperators.map(op => op.text));
11
+ }
12
+ if (extension.binaryOperators) {
13
+ lexer.addOperators(...extension.binaryOperators.map(op => op.text));
14
+ }
15
+ }
16
+ return lexer;
17
+ };
18
+
19
+ const applyParserExtensions = (parser, ...extensions) => {
20
+ for (const extension of extensions) {
21
+ if (extension.tags) {
22
+ for (const tag of extension.tags) {
23
+ parser.addTag(tag);
24
+ }
25
+ }
26
+ if (extension.unaryOperators) {
27
+ for (const op of extension.unaryOperators) {
28
+ parser.addUnaryOperator(op);
29
+ }
30
+ }
31
+ if (extension.binaryOperators) {
32
+ for (const op of extension.binaryOperators) {
33
+ parser.addBinaryOperator(op);
34
+ }
35
+ }
36
+ if (extension.tests) {
37
+ for (const test of extension.tests) {
38
+ parser.addTest(test);
39
+ }
40
+ }
41
+ }
42
+ };
43
+
44
+ const createConfiguredParser = (code, multiTagConfig, ...extensions) => {
45
+ const parser = new Parser(
46
+ new TokenStream(createConfiguredLexer(code, ...extensions), {
47
+ ignoreWhitespace: true,
48
+ ignoreComments: false,
49
+ ignoreHtmlComments: false,
50
+ applyWhitespaceTrimming: false
51
+ }),
52
+ {
53
+ ignoreComments: false,
54
+ ignoreHtmlComments: false,
55
+ ignoreDeclarations: false,
56
+ decodeEntities: false,
57
+ multiTags: multiTagConfig,
58
+ allowUnknownTags: true
59
+ }
60
+ );
61
+ applyParserExtensions(parser, ...extensions);
62
+ return parser;
63
+ };
64
+
65
+ const getMultiTagConfig = (tagsCsvs = []) =>
66
+ tagsCsvs.reduce((acc, curr) => {
67
+ const tagNames = curr.split(",");
68
+ acc[tagNames[0].trim()] = tagNames.slice(1).map(s => s.trim());
69
+ return acc;
70
+ }, {});
71
+
72
+ const parse = (text, parsers, options) => {
73
+ const multiTagConfig = getMultiTagConfig(options.twigMultiTags || []);
74
+
75
+ const extensions = [coreExtension];
76
+ const parser = createConfiguredParser(text, multiTagConfig, ...extensions);
77
+ const ast = parser.parse();
78
+ ast[ORIGINAL_SOURCE] = text;
79
+ return ast;
80
+ };
81
+
82
+ export { parse, ORIGINAL_SOURCE };
@@ -0,0 +1,5 @@
1
+ const p = (node, path, print) => {
2
+ return [path.call(print, "name"), " as ", path.call(print, "alias")];
3
+ };
4
+
5
+ export { p as printAliasExpression };
@@ -0,0 +1,14 @@
1
+ import { doc } from "prettier";
2
+ import { STRING_NEEDS_QUOTES } from "../util/index.js";
3
+
4
+ const { group, softline, line, indent, join } = doc.builders;
5
+
6
+ const p = (node, path, print) => {
7
+ node[STRING_NEEDS_QUOTES] = true;
8
+ const mappedElements = path.map(print, "elements");
9
+ const indentedContent = [softline, join([",", line], mappedElements)];
10
+
11
+ return group(["[", indent(indentedContent), softline, "]"]);
12
+ };
13
+
14
+ export { p as printArrayExpression };
@@ -0,0 +1,50 @@
1
+ import { Node } from "melody-types";
2
+ import { EXPRESSION_NEEDED, STRING_NEEDS_QUOTES } from "../util/index.js";
3
+
4
+ const mayCorrectWhitespace = attrName =>
5
+ ["id", "class", "type"].indexOf(attrName) > -1;
6
+
7
+ const sanitizeWhitespace = s => s.replace(/\s+/g, " ").trim();
8
+
9
+ const printConcatenatedString = (valueNode, path, print, ...initialPath) => {
10
+ const printedFragments = [];
11
+ let currentNode = valueNode;
12
+ const currentPath = initialPath;
13
+ while (Node.isBinaryConcatExpression(currentNode)) {
14
+ printedFragments.unshift(path.call(print, ...currentPath, "right"));
15
+ currentPath.push("left");
16
+ currentNode = currentNode.left;
17
+ }
18
+ printedFragments.unshift(path.call(print, ...currentPath));
19
+ return printedFragments;
20
+ };
21
+
22
+ const p = (node, path, print = print) => {
23
+ node[EXPRESSION_NEEDED] = false;
24
+ const docs = [path.call(print, "name")];
25
+ node[EXPRESSION_NEEDED] = true;
26
+ node[STRING_NEEDS_QUOTES] = false;
27
+ if (node.value) {
28
+ docs.push('="');
29
+ if (
30
+ Node.isBinaryConcatExpression(node.value) &&
31
+ node.value.wasImplicitConcatenation
32
+ ) {
33
+ // Special handling for concatenated string values
34
+ docs.push(
35
+ printConcatenatedString(node.value, path, print, "value")
36
+ );
37
+ } else {
38
+ const isStringValue = Node.isStringLiteral(node.value);
39
+ if (mayCorrectWhitespace(node.name.name) && isStringValue) {
40
+ node.value.value = sanitizeWhitespace(node.value.value);
41
+ }
42
+ docs.push(path.call(print, "value"));
43
+ }
44
+ docs.push('"');
45
+ }
46
+
47
+ return docs;
48
+ };
49
+
50
+ export { p as printAttribute };