-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
multiparser.js
340 lines (306 loc) · 9.31 KB
/
multiparser.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
"use strict";
const util = require("./util");
const docUtils = require("./doc-utils");
const docBuilders = require("./doc-builders");
const comments = require("./comments");
const indent = docBuilders.indent;
const hardline = docBuilders.hardline;
const softline = docBuilders.softline;
const concat = docBuilders.concat;
function printSubtree(subtreeParser, path, print, options) {
const next = Object.assign({}, { transformDoc: doc => doc }, subtreeParser);
next.options = Object.assign({}, options, next.options, {
originalText: next.text
});
const ast = require("./parser").parse(next.text, next.options);
const astComments = ast.comments;
delete ast.comments;
comments.attach(astComments, ast, next.text, next.options);
const nextDoc = require("./printer").printAstToDoc(ast, next.options);
return next.transformDoc(nextDoc, { path, print });
}
/**
* @returns {{ text, options?, transformDoc? } | void}
*/
function getSubtreeParser(path, options) {
switch (options.parser) {
case "parse5":
return fromHtmlParser2(path, options);
case "babylon":
case "flow":
case "typescript":
return fromBabylonFlowOrTypeScript(path, options);
}
}
function fromBabylonFlowOrTypeScript(path) {
const node = path.getValue();
switch (node.type) {
case "TemplateLiteral": {
const isCss = [isStyledJsx, isStyledComponents].some(isIt => isIt(path));
if (isCss) {
// Get full template literal with expressions replaced by placeholders
const rawQuasis = node.quasis.map(q => q.value.raw);
const text = rawQuasis.join("@prettier-placeholder");
return {
options: { parser: "postcss" },
transformDoc: transformCssDoc,
text: text
};
}
break;
}
case "TemplateElement": {
const parent = path.getParentNode();
const parentParent = path.getParentNode(1);
/*
* react-relay and graphql-tag
* graphql`...`
* graphql.experimental`...`
* gql`...`
*/
if (
parentParent &&
parentParent.type === "TaggedTemplateExpression" &&
parent.quasis.length === 1 &&
((parentParent.tag.type === "MemberExpression" &&
parentParent.tag.object.name === "graphql" &&
parentParent.tag.property.name === "experimental") ||
(parentParent.tag.type === "Identifier" &&
(parentParent.tag.name === "gql" ||
parentParent.tag.name === "graphql")))
) {
return {
options: { parser: "graphql" },
transformDoc: doc =>
concat([
indent(concat([softline, stripTrailingHardline(doc)])),
softline
]),
text: parent.quasis[0].value.raw
};
}
break;
}
}
}
function fromHtmlParser2(path, options) {
const node = path.getValue();
switch (node.type) {
case "text": {
const parent = path.getParentNode();
// Inline JavaScript
if (
parent.type === "script" &&
((!parent.attribs.lang && !parent.attribs.lang) ||
parent.attribs.type === "text/javascript" ||
parent.attribs.type === "application/javascript")
) {
const parser = options.parser === "flow" ? "flow" : "babylon";
return {
options: { parser },
transformDoc: doc => concat([hardline, doc]),
text: getText(options, node)
};
}
// Inline TypeScript
if (
parent.type === "script" &&
(parent.attribs.type === "application/x-typescript" ||
parent.attribs.lang === "ts")
) {
return {
options: { parser: "typescript" },
transformDoc: doc => concat([hardline, doc]),
text: getText(options, node)
};
}
// Inline Styles
if (parent.type === "style") {
return {
options: { parser: "postcss" },
transformDoc: doc => concat([hardline, stripTrailingHardline(doc)]),
text: getText(options, node)
};
}
break;
}
case "attribute": {
/*
* Vue binding sytax: JS expressions
* :class="{ 'some-key': value }"
* v-bind:id="'list-' + id"
* v-if="foo && !bar"
* @click="someFunction()"
*/
if (/(^@)|(^v-)|:/.test(node.key) && !/^\w+$/.test(node.value)) {
return {
text: node.value,
options: {
parser: parseJavaScriptExpression,
// Use singleQuote since HTML attributes use double-quotes.
// TODO(azz): We still need to do an entity escape on the attribute.
singleQuote: true
},
transformDoc: doc => {
return concat([
node.key,
'="',
util.hasNewlineInRange(node.value, 0, node.value.length)
? doc
: docUtils.removeLines(doc),
'"'
]);
}
};
}
}
}
}
function transformCssDoc(quasisDoc, parent) {
const parentNode = parent.path.getValue();
const expressionDocs = parentNode.expressions
? parent.path.map(parent.print, "expressions")
: [];
const newDoc = replacePlaceholders(quasisDoc, expressionDocs);
/* istanbul ignore if */
if (!newDoc) {
throw new Error("Couldn't insert all the expressions");
}
return concat([
"`",
indent(concat([softline, stripTrailingHardline(newDoc)])),
softline,
"`"
]);
}
// Search all the placeholders in the quasisDoc tree
// and replace them with the expression docs one by one
// returns a new doc with all the placeholders replaced,
// or null if it couldn't replace any expression
function replacePlaceholders(quasisDoc, expressionDocs) {
if (!expressionDocs || !expressionDocs.length) {
return quasisDoc;
}
const expressions = expressionDocs.slice();
const newDoc = docUtils.mapDoc(quasisDoc, doc => {
if (!doc || !doc.parts || !doc.parts.length) {
return doc;
}
let parts = doc.parts;
if (
parts.length > 1 &&
parts[0] === "@" &&
typeof parts[1] === "string" &&
parts[1].startsWith("prettier-placeholder")
) {
// If placeholder is split, join it
const at = parts[0];
const placeholder = parts[1];
const rest = parts.slice(2);
parts = [at + placeholder].concat(rest);
}
if (
typeof parts[0] === "string" &&
parts[0].startsWith("@prettier-placeholder")
) {
const placeholder = parts[0];
const rest = parts.slice(1);
// When the expression has a suffix appended, like:
// animation: linear ${time}s ease-out;
const suffix = placeholder.slice("@prettier-placeholder".length);
const expression = expressions.shift();
parts = ["${", expression, "}" + suffix].concat(rest);
}
return Object.assign({}, doc, {
parts: parts
});
});
return expressions.length === 0 ? newDoc : null;
}
function parseJavaScriptExpression(text, parsers) {
// Force parsing as an expression
const ast = parsers.babylon(`(${text})`);
// Extract expression from the declaration
return {
type: "File",
program: ast.program.body[0].expression
};
}
function getText(options, node) {
return options.originalText.slice(util.locStart(node), util.locEnd(node));
}
function stripTrailingHardline(doc) {
// HACK remove ending hardline, original PR: #1984
if (
doc.type === "concat" &&
doc.parts[0].type === "concat" &&
doc.parts[0].parts.length === 2 &&
// doc.parts[0].parts[1] === hardline :
doc.parts[0].parts[1].type === "concat" &&
doc.parts[0].parts[1].parts.length === 2 &&
doc.parts[0].parts[1].parts[0].hard &&
doc.parts[0].parts[1].parts[1].type === "break-parent"
) {
return doc.parts[0].parts[0];
}
return doc;
}
/**
* Template literal in this context:
* <style jsx>{`div{color:red}`}</style>
*/
function isStyledJsx(path) {
const node = path.getValue();
const parent = path.getParentNode();
const parentParent = path.getParentNode(1);
return (
parentParent &&
node.quasis &&
parent.type === "JSXExpressionContainer" &&
parentParent.type === "JSXElement" &&
parentParent.openingElement.name.name === "style" &&
parentParent.openingElement.attributes.some(
attribute => attribute.name.name === "jsx"
)
);
}
/**
* styled-components template literals
*/
function isStyledComponents(path) {
const parent = path.getParentNode();
if (!parent || parent.type !== "TaggedTemplateExpression") {
return false;
}
const tag = parent.tag;
switch (tag.type) {
case "MemberExpression":
return (
// styled.foo``
isStyledIdentifier(tag.object) ||
// Component.extend``
(/^[A-Z]/.test(tag.object.name) && tag.property.name === "extend")
);
case "CallExpression":
return (
// styled(Component)``
isStyledIdentifier(tag.callee) ||
// styled.foo.attr({})``
(tag.callee.type === "MemberExpression" &&
tag.callee.object.type === "MemberExpression" &&
isStyledIdentifier(tag.callee.object.object))
);
case "Identifier":
// css``
return tag.name === "css";
default:
return false;
}
}
function isStyledIdentifier(node) {
return node.type === "Identifier" && node.name === "styled";
}
module.exports = {
getSubtreeParser,
printSubtree
};